diff --git a/DEPS b/DEPS index 26db66d..dbd6eabd 100644 --- a/DEPS +++ b/DEPS
@@ -126,11 +126,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': '3abdd7a90e453ba7a9e2cad76e3526195ece14a6', + 'skia_revision': '98385ba6c5c691c092372b9010f8375c005e0448', # 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': '95b3a9a61e175269f5c3a90c54d1df6407ccdc7d', + 'v8_revision': '003f99ea6ea916e527e8eacd733cdd5c919e6ae5', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -138,7 +138,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': 'bf5dbd8d67feb3e1eaa939ac24839fbc414cc611', + 'angle_revision': '740db7fd279529530019546457f048f06f4fbc8e', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -154,7 +154,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling BoringSSL # and whatever else without interference from each other. - 'boringssl_revision': '1a51a5b4a6bdf7ee11b443f21f08dc2ba2de9815', + 'boringssl_revision': '70fe6105565e71e44e0a2a4ee617a26fd8fdcd96', # 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. @@ -174,7 +174,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling freetype # and whatever else without interference from each other. - 'freetype_revision': '1e7a8f30c231bace001c617099e78f78743dd3b4', + 'freetype_revision': 'a6feefdfefd6eb8e62728f40638241bb1d8c993e', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling HarfBuzz # and whatever else without interference from each other. @@ -186,7 +186,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': '78b1c61fff2b004763c374db5039840dc74238b0', + 'catapult_revision': '11e283fea2536277797e09893a547cbd094e4426', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -234,7 +234,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'spv_tools_revision': '0f4bf0720a9cd49d7375ae1296c874133df5ea34', + 'spv_tools_revision': '9b6ba4d1c57e7dac46406ef96c726348cdea49b9', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -250,7 +250,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'dawn_revision': '978fa65a2cc5e73f70b4d5c4021e49654b7c61b1', + 'dawn_revision': '7771f58c7f2429b9f1c532f1f3196423e5b9fb80', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -729,7 +729,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'b0d7bc961a5a5114e61d412a8c506e387445a0ba', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '971e4cb2b43d928c59a3e0e58d30dec03e8f2a9e', 'condition': 'checkout_linux', }, @@ -754,7 +754,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '484d74fa21a52aeee2665671d970b999291d5900', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '61d0c292535e8e6c1102f198ec1ef47f50075ceb', 'src/third_party/devtools-node-modules': Var('chromium_git') + '/external/github.com/ChromeDevTools/devtools-node-modules' + '@' + Var('devtools_node_modules_revision'), @@ -1089,7 +1089,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '71b40a07a007a995bee17af078c3543f447b41f0', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '10ef8b33f128b6def49291c2c0de2e0e2eb84437', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + 'ac0d98b5cee6c024b0cffeb4f8f45b6fc5ccdb78', @@ -1252,7 +1252,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'db52df17f0d012983dc281e4864c71485a86bd0e', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '3f408d006a607b6306f08e4639b23f036a74238c', + Var('webrtc_git') + '/src.git' + '@' + 'e98954c35e97dfe4d50fe6bd75587b14ffb6568e', 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -1293,7 +1293,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@5ae20aeb484437c65f85657d17e5e171189b8622', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@96982ab4da6c91f6c47c129af5b91d76977c03c3', 'condition': 'checkout_src_internal', },
diff --git a/PRESUBMIT.py b/PRESUBMIT.py index 7f2ec1b2..ee980b0 100644 --- a/PRESUBMIT.py +++ b/PRESUBMIT.py
@@ -655,6 +655,7 @@ 'build/android/gyp/aar.pydeps', 'build/android/gyp/aidl.pydeps', 'build/android/gyp/apkbuilder.pydeps', + 'build/android/gyp/assert_static_initializers.pydeps', 'build/android/gyp/bytecode_processor.pydeps', 'build/android/gyp/compile_resources.pydeps', 'build/android/gyp/create_bundle_wrapper_script.pydeps',
diff --git a/android_webview/BUILD.gn b/android_webview/BUILD.gn index 77f57f1..a3a2ad1 100644 --- a/android_webview/BUILD.gn +++ b/android_webview/BUILD.gn
@@ -107,6 +107,12 @@ ] } +java_cpp_enum("aw_settings_force_dark_mode") { + sources = [ + "browser/aw_settings.h", + ] +} + jinja_template("system_webview_manifest") { input = "apk/java/AndroidManifest.xml" output = system_webview_android_manifest @@ -343,17 +349,20 @@ "java/res/values-am/components_strings.xml", "java/res/values-ar/components_strings.xml", "java/res/values-bg/components_strings.xml", + "java/res/values-bn/components_strings.xml", "java/res/values-ca/components_strings.xml", "java/res/values-cs/components_strings.xml", "java/res/values-da/components_strings.xml", "java/res/values-de/components_strings.xml", "java/res/values-el/components_strings.xml", "java/res/values-en-rGB/components_strings.xml", - "java/res/values-es-rUS/components_strings.xml", "java/res/values-es/components_strings.xml", + "java/res/values-es-rUS/components_strings.xml", + "java/res/values-et/components_strings.xml", "java/res/values-fa/components_strings.xml", "java/res/values-fi/components_strings.xml", "java/res/values-fr/components_strings.xml", + "java/res/values-gu/components_strings.xml", "java/res/values-hi/components_strings.xml", "java/res/values-hr/components_strings.xml", "java/res/values-hu/components_strings.xml", @@ -361,9 +370,13 @@ "java/res/values-it/components_strings.xml", "java/res/values-iw/components_strings.xml", "java/res/values-ja/components_strings.xml", + "java/res/values-kn/components_strings.xml", "java/res/values-ko/components_strings.xml", "java/res/values-lt/components_strings.xml", "java/res/values-lv/components_strings.xml", + "java/res/values-ml/components_strings.xml", + "java/res/values-mr/components_strings.xml", + "java/res/values-ms/components_strings.xml", "java/res/values-nb/components_strings.xml", "java/res/values-nl/components_strings.xml", "java/res/values-pl/components_strings.xml", @@ -376,6 +389,8 @@ "java/res/values-sr/components_strings.xml", "java/res/values-sv/components_strings.xml", "java/res/values-sw/components_strings.xml", + "java/res/values-ta/components_strings.xml", + "java/res/values-te/components_strings.xml", "java/res/values-th/components_strings.xml", "java/res/values-tl/components_strings.xml", "java/res/values-tr/components_strings.xml", @@ -988,6 +1003,7 @@ ":android_webview_java_enums_srcjar", ":aw_error_ui", ":aw_safe_browsing_action", + ":aw_settings_force_dark_mode", "//components/safe_browsing/db:sb_threat_values", ] @@ -1010,17 +1026,20 @@ "values-am/android_webview_strings.xml", "values-ar/android_webview_strings.xml", "values-bg/android_webview_strings.xml", + "values-bn/android_webview_strings.xml", "values-ca/android_webview_strings.xml", "values-cs/android_webview_strings.xml", "values-da/android_webview_strings.xml", "values-de/android_webview_strings.xml", "values-el/android_webview_strings.xml", "values-en-rGB/android_webview_strings.xml", - "values-es-rUS/android_webview_strings.xml", "values-es/android_webview_strings.xml", + "values-es-rUS/android_webview_strings.xml", + "values-et/android_webview_strings.xml", "values-fa/android_webview_strings.xml", "values-fi/android_webview_strings.xml", "values-fr/android_webview_strings.xml", + "values-gu/android_webview_strings.xml", "values-hi/android_webview_strings.xml", "values-hr/android_webview_strings.xml", "values-hu/android_webview_strings.xml", @@ -1028,9 +1047,13 @@ "values-it/android_webview_strings.xml", "values-iw/android_webview_strings.xml", "values-ja/android_webview_strings.xml", + "values-kn/android_webview_strings.xml", "values-ko/android_webview_strings.xml", "values-lt/android_webview_strings.xml", "values-lv/android_webview_strings.xml", + "values-ml/android_webview_strings.xml", + "values-mr/android_webview_strings.xml", + "values-ms/android_webview_strings.xml", "values-nb/android_webview_strings.xml", "values-nl/android_webview_strings.xml", "values-pl/android_webview_strings.xml", @@ -1043,6 +1066,8 @@ "values-sr/android_webview_strings.xml", "values-sv/android_webview_strings.xml", "values-sw/android_webview_strings.xml", + "values-ta/android_webview_strings.xml", + "values-te/android_webview_strings.xml", "values-th/android_webview_strings.xml", "values-tl/android_webview_strings.xml", "values-tr/android_webview_strings.xml",
diff --git a/android_webview/browser/aw_contents.cc b/android_webview/browser/aw_contents.cc index 47c09aef..c585f63 100644 --- a/android_webview/browser/aw_contents.cc +++ b/android_webview/browser/aw_contents.cc
@@ -20,6 +20,7 @@ #include "android_webview/browser/aw_render_process.h" #include "android_webview/browser/aw_renderer_priority.h" #include "android_webview/browser/aw_resource_context.h" +#include "android_webview/browser/aw_settings.h" #include "android_webview/browser/aw_web_contents_delegate.h" #include "android_webview/browser/browser_view_renderer.h" #include "android_webview/browser/child_frame.h" @@ -854,6 +855,12 @@ } } +void AwContents::OnViewTreeForceDarkStateChanged( + bool view_tree_force_dark_state) { + view_tree_force_dark_state_ = view_tree_force_dark_state; + web_contents_->NotifyPreferencesChanged(); +} + base::android::ScopedJavaLocalRef<jbyteArray> AwContents::GetCertificate( JNIEnv* env, const JavaParamRef<jobject>& obj) {
diff --git a/android_webview/browser/aw_contents.h b/android_webview/browser/aw_contents.h index e3ba863..ddb1da7 100644 --- a/android_webview/browser/aw_contents.h +++ b/android_webview/browser/aw_contents.h
@@ -217,6 +217,8 @@ jint GetEffectivePriority(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); + bool GetViewTreeForceDarkState() { return view_tree_force_dark_state_; } + // PermissionRequestHandlerClient implementation. void OnPermissionRequest(base::android::ScopedJavaLocalRef<jobject> j_request, AwPermissionRequest* request) override; @@ -279,6 +281,8 @@ void PostInvalidate() override; void OnNewPicture() override; gfx::Point GetLocationOnScreen() override; + void OnViewTreeForceDarkStateChanged( + bool view_tree_force_dark_state) override; // |new_value| is in physical pixel scale. void ScrollContainerViewTo(const gfx::Vector2d& new_value) override; @@ -391,6 +395,8 @@ std::unique_ptr<PermissionRequestHandler> permission_request_handler_; std::unique_ptr<autofill::AutofillProvider> autofill_provider_; + bool view_tree_force_dark_state_ = false; + // GURL is supplied by the content layer as requesting frame. // Callback is supplied by the content layer, and is invoked with the result // from the permission prompt.
diff --git a/android_webview/browser/aw_draw_fn_impl.cc b/android_webview/browser/aw_draw_fn_impl.cc index ecd181a3..f5345be 100644 --- a/android_webview/browser/aw_draw_fn_impl.cc +++ b/android_webview/browser/aw_draw_fn_impl.cc
@@ -321,6 +321,8 @@ } void AwDrawFnImpl::OnSync(AwDrawFn_OnSyncParams* params) { + render_thread_manager_.UpdateViewTreeForceDarkStateOnRT( + params->apply_force_dark); render_thread_manager_.CommitFrameOnRT(); }
diff --git a/android_webview/browser/aw_settings.cc b/android_webview/browser/aw_settings.cc index a19b3a08..7d17d42 100644 --- a/android_webview/browser/aw_settings.cc +++ b/android_webview/browser/aw_settings.cc
@@ -489,6 +489,21 @@ web_prefs->scroll_top_left_interop_enabled = Java_AwSettings_getScrollTopLeftInteropEnabledLocked(env, obj); + + switch (Java_AwSettings_getForceDarkModeLocked(env, obj)) { + case ForceDarkMode::FORCE_DARK_OFF: + web_prefs->force_dark_mode_enabled = false; + break; + case ForceDarkMode::FORCE_DARK_ON: + web_prefs->force_dark_mode_enabled = true; + break; + case ForceDarkMode::FORCE_DARK_AUTO: { + AwContents* contents = AwContents::FromWebContents(web_contents()); + web_prefs->force_dark_mode_enabled = + contents && contents->GetViewTreeForceDarkState(); + break; + } + } } static jlong JNI_AwSettings_Init(JNIEnv* env,
diff --git a/android_webview/browser/aw_settings.h b/android_webview/browser/aw_settings.h index 3f3eec88..59b39a3 100644 --- a/android_webview/browser/aw_settings.h +++ b/android_webview/browser/aw_settings.h
@@ -21,6 +21,13 @@ class AwSettings : public content::WebContentsObserver { public: + // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.android_webview.settings + enum ForceDarkMode { + FORCE_DARK_OFF = 0, + FORCE_DARK_AUTO = 1, + FORCE_DARK_ON = 2, + }; + static AwSettings* FromWebContents(content::WebContents* web_contents); static bool GetAllowSniffingFileUrls();
diff --git a/android_webview/browser/browser_view_renderer.cc b/android_webview/browser/browser_view_renderer.cc index a3dd7acd..bcacb607 100644 --- a/android_webview/browser/browser_view_renderer.cc +++ b/android_webview/browser/browser_view_renderer.cc
@@ -269,6 +269,11 @@ UpdateMemoryPolicy(); } +void BrowserViewRenderer::OnViewTreeForceDarkStateChanged( + bool view_tree_force_dark_state) { + client_->OnViewTreeForceDarkStateChanged(view_tree_force_dark_state); +} + void BrowserViewRenderer::RemoveCompositorFrameConsumer( CompositorFrameConsumer* consumer) { ReturnUncommittedFrames(consumer->PassUncommittedFrameOnUI());
diff --git a/android_webview/browser/browser_view_renderer.h b/android_webview/browser/browser_view_renderer.h index f703e3d..177c1c9e 100644 --- a/android_webview/browser/browser_view_renderer.h +++ b/android_webview/browser/browser_view_renderer.h
@@ -153,6 +153,8 @@ uint32_t layer_tree_frame_sink_id) override; void OnParentDrawConstraintsUpdated( CompositorFrameConsumer* compositor_frame_consumer) override; + void OnViewTreeForceDarkStateChanged( + bool view_tree_force_dark_state) override; void SetActiveCompositorID(const CompositorID& compositor_id);
diff --git a/android_webview/browser/browser_view_renderer_client.h b/android_webview/browser/browser_view_renderer_client.h index c13656b..d717bfc 100644 --- a/android_webview/browser/browser_view_renderer_client.h +++ b/android_webview/browser/browser_view_renderer_client.h
@@ -52,6 +52,10 @@ // Create a text selection handle on demand. virtual ui::TouchHandleDrawable* CreateDrawable() = 0; + // Called when the view tree force dark state changes + virtual void OnViewTreeForceDarkStateChanged( + bool view_tree_force_dark_state) = 0; + protected: virtual ~BrowserViewRendererClient() {} };
diff --git a/android_webview/browser/compositor_frame_producer.h b/android_webview/browser/compositor_frame_producer.h index a207c4d..65260fc 100644 --- a/android_webview/browser/compositor_frame_producer.h +++ b/android_webview/browser/compositor_frame_producer.h
@@ -24,6 +24,8 @@ uint32_t layer_tree_frame_sink_id) = 0; virtual void OnParentDrawConstraintsUpdated( CompositorFrameConsumer* compositor_frame_consumer) = 0; + virtual void OnViewTreeForceDarkStateChanged( + bool view_tree_force_dark_state) = 0; virtual void RemoveCompositorFrameConsumer( CompositorFrameConsumer* consumer) = 0;
diff --git a/android_webview/browser/permission/aw_permission_request.h b/android_webview/browser/permission/aw_permission_request.h index 3072e3c..b205adb 100644 --- a/android_webview/browser/permission/aw_permission_request.h +++ b/android_webview/browser/permission/aw_permission_request.h
@@ -18,7 +18,7 @@ class AwPermissionRequestDelegate; // This class wraps a permission request, it works with PermissionRequestHandler -// and its' Java peer to represent the request to AwContentsClient. +// and its Java peer to represent the request to AwContentsClient. // The specific permission request should implement the // AwPermissionRequestDelegate interface, See MediaPermissionRequest. // This object is owned by the java peer.
diff --git a/android_webview/browser/render_thread_manager.cc b/android_webview/browser/render_thread_manager.cc index 386e6ca..f679567 100644 --- a/android_webview/browser/render_thread_manager.cc +++ b/android_webview/browser/render_thread_manager.cc
@@ -44,6 +44,16 @@ } } +void RenderThreadManager::ViewTreeForceDarkStateChangedOnUI( + bool view_tree_force_dark_state) { + DCHECK(ui_loop_->BelongsToCurrentThread()); + CheckUiCallsAllowed(); + if (producer_weak_ptr_) { + producer_weak_ptr_->OnViewTreeForceDarkStateChanged( + view_tree_force_dark_state); + } +} + void RenderThreadManager::SetScrollOffsetOnUI(gfx::Vector2d scroll_offset) { DCHECK(ui_loop_->BelongsToCurrentThread()); CheckUiCallsAllowed(); @@ -145,6 +155,17 @@ hardware_renderer_->CommitFrame(); } +void RenderThreadManager::UpdateViewTreeForceDarkStateOnRT( + bool view_tree_force_dark_state) { + if (view_tree_force_dark_state_ == view_tree_force_dark_state) + return; + view_tree_force_dark_state_ = view_tree_force_dark_state; + ui_loop_->PostTask( + FROM_HERE, + base::BindOnce(&RenderThreadManager::ViewTreeForceDarkStateChangedOnUI, + ui_thread_weak_ptr_, view_tree_force_dark_state_)); +} + void RenderThreadManager::DrawOnRT(bool save_restore, HardwareRendererDrawParams* params) { // Force GL binding init if it's not yet initialized.
diff --git a/android_webview/browser/render_thread_manager.h b/android_webview/browser/render_thread_manager.h index 7ae7aab..7aaa544 100644 --- a/android_webview/browser/render_thread_manager.h +++ b/android_webview/browser/render_thread_manager.h
@@ -53,6 +53,7 @@ uint32_t layer_tree_frame_sink_id); void CommitFrameOnRT(); + void UpdateViewTreeForceDarkStateOnRT(bool view_tree_force_dark_state); void DrawOnRT(bool save_restore, HardwareRendererDrawParams* params); void DestroyHardwareRendererOnRT(bool save_restore); @@ -79,6 +80,7 @@ // UI thread methods. void UpdateParentDrawConstraintsOnUI(); + void ViewTreeForceDarkStateChangedOnUI(bool view_tree_force_dark_state); void CheckUiCallsAllowed() const { #if DCHECK_IS_ON() DCHECK(ui_calls_allowed_); @@ -98,6 +100,7 @@ // Accessed by RT thread. std::unique_ptr<HardwareRenderer> hardware_renderer_; + bool view_tree_force_dark_state_ = false; // Accessed by both UI and RT thread. mutable base::Lock lock_;
diff --git a/android_webview/browser/surfaces_instance.cc b/android_webview/browser/surfaces_instance.cc index 569c2f5..5b3a948a 100644 --- a/android_webview/browser/surfaces_instance.cc +++ b/android_webview/browser/surfaces_instance.cc
@@ -22,6 +22,7 @@ #include "components/viz/service/display/display.h" #include "components/viz/service/display/display_scheduler.h" #include "components/viz/service/display_embedder/skia_output_surface_impl.h" +#include "components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.h" #include "components/viz/service/frame_sinks/compositor_frame_sink_support.h" #include "components/viz/service/frame_sinks/frame_sink_manager_impl.h" #include "gpu/command_buffer/service/shared_context_state.h" @@ -65,7 +66,8 @@ // Webview does not own the surface so should not clear it. settings.should_clear_root_render_pass = false; - settings.use_skia_renderer = features::IsUsingSkiaRenderer(); + settings.use_skia_renderer = + features::IsUsingSkiaRenderer() || features::IsUsingSkiaRendererNonDDL(); // The SharedBitmapManager is null as we do not support or use software // compositing on Android. @@ -100,9 +102,16 @@ .enabled_gpu_driver_bug_workarounds), nullptr /* gr_shader_cache */); } - output_surface = std::make_unique<viz::SkiaOutputSurfaceImpl>( - task_executor, base::MakeRefCounted<AwGLSurface>(), - shared_context_state_); + if (features::IsUsingSkiaRendererNonDDL()) { + output_surface = std::make_unique<viz::SkiaOutputSurfaceImplNonDDL>( + base::MakeRefCounted<AwGLSurface>(), shared_context_state_, + task_executor->mailbox_manager(), + task_executor->sync_point_manager()); + } else { + output_surface = std::make_unique<viz::SkiaOutputSurfaceImpl>( + task_executor, base::MakeRefCounted<AwGLSurface>(), + shared_context_state_); + } skia_output_surface = static_cast<viz::SkiaOutputSurface*>(output_surface.get()); } else {
diff --git a/android_webview/browser/test/rendering_test.h b/android_webview/browser/test/rendering_test.h index 5d9f728b..31fab662 100644 --- a/android_webview/browser/test/rendering_test.h +++ b/android_webview/browser/test/rendering_test.h
@@ -69,6 +69,8 @@ void DidDrawOnRT() override {} virtual void OnParentDrawConstraintsUpdated() {} + void OnViewTreeForceDarkStateChanged( + bool view_tree_force_dark_state) override {} protected:
diff --git a/android_webview/glue/java/src/com/android/webview/chromium/WebViewContentsClientAdapter.java b/android_webview/glue/java/src/com/android/webview/chromium/WebViewContentsClientAdapter.java index ffa63d1..c1ba2d99d 100644 --- a/android_webview/glue/java/src/com/android/webview/chromium/WebViewContentsClientAdapter.java +++ b/android_webview/glue/java/src/com/android/webview/chromium/WebViewContentsClientAdapter.java
@@ -119,7 +119,7 @@ WebView newWebView = t.getWebView(); if (newWebView == mWebView) { throw new IllegalArgumentException( - "Parent WebView cannot host it's own popup window. Please " + "Parent WebView cannot host its own popup window. Please " + "use WebSettings.setSupportMultipleWindows(false)"); }
diff --git a/android_webview/java/src/org/chromium/android_webview/AwContents.java b/android_webview/java/src/org/chromium/android_webview/AwContents.java index f8df2c5..2fa6c2c 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwContents.java +++ b/android_webview/java/src/org/chromium/android_webview/AwContents.java
@@ -868,7 +868,7 @@ mBrowserContext = browserContext; - // setWillNotDraw(false) is required since WebView draws it's own contents using it's + // setWillNotDraw(false) is required since WebView draws its own contents using its // container view. If this is ever not the case we should remove this, as it removes // Android's gatherTransparentRegion optimization for the view. mContainerView = containerView; @@ -1057,7 +1057,7 @@ } private void setContainerView(ViewGroup newContainerView) { - // setWillNotDraw(false) is required since WebView draws it's own contents using it's + // setWillNotDraw(false) is required since WebView draws its own contents using its // container view. If this is ever not the case we should remove this, as it removes // Android's gatherTransparentRegion optimization for the view. mContainerView = newContainerView;
diff --git a/android_webview/java/src/org/chromium/android_webview/AwSettings.java b/android_webview/java/src/org/chromium/android_webview/AwSettings.java index 8bd35fb..b887a98 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwSettings.java +++ b/android_webview/java/src/org/chromium/android_webview/AwSettings.java
@@ -16,6 +16,7 @@ import android.util.Log; import android.webkit.WebSettings; +import org.chromium.android_webview.settings.ForceDarkMode; import org.chromium.base.ContextUtils; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; @@ -54,13 +55,12 @@ public static final int LAYOUT_ALGORITHM_NARROW_COLUMNS = 2; public static final int LAYOUT_ALGORITHM_TEXT_AUTOSIZING = 3; - @Retention(RetentionPolicy.SOURCE) - @IntDef({FORCE_DARK_OFF, FORCE_DARK_AUTO, FORCE_DARK_ON}) - public @interface ForceDarkMode {} + public static final int FORCE_DARK_OFF = ForceDarkMode.FORCE_DARK_OFF; + public static final int FORCE_DARK_AUTO = ForceDarkMode.FORCE_DARK_AUTO; + public static final int FORCE_DARK_ON = ForceDarkMode.FORCE_DARK_ON; - public static final int FORCE_DARK_OFF = -1; - public static final int FORCE_DARK_AUTO = 0; - public static final int FORCE_DARK_ON = +1; + @ForceDarkMode + private int mForceDarkMode = ForceDarkMode.FORCE_DARK_AUTO; // This class must be created on the UI thread. Afterwards, it can be // used from any thread. Internally, the class uses a message queue @@ -110,8 +110,6 @@ private boolean mSpatialNavigationEnabled; // Default depends on device features. private boolean mEnableSupportedHardwareAcceleratedFeatures; private int mMixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW; - @ForceDarkMode - private int mForceDarkMode = FORCE_DARK_AUTO; private boolean mCSSHexAlphaColorEnabled; private boolean mScrollTopLeftInteropEnabled; private boolean mShouldSuppressErrorPage; @@ -1677,14 +1675,22 @@ @ForceDarkMode public int getForceDarkMode() { synchronized (mAwSettingsLock) { - return mForceDarkMode; + return getForceDarkModeLocked(); } } + @CalledByNative + @ForceDarkMode + public int getForceDarkModeLocked() { + assert Thread.holdsLock(mAwSettingsLock); + return mForceDarkMode; + } + public void setForceDarkMode(@ForceDarkMode int forceDarkMode) { synchronized (mAwSettingsLock) { if (mForceDarkMode != forceDarkMode) { mForceDarkMode = forceDarkMode; + mEventHandler.updateWebkitPreferencesLocked(); } } }
diff --git a/android_webview/java/strings/android_webview_strings.grd b/android_webview/java/strings/android_webview_strings.grd index 3dd5770..b957723 100644 --- a/android_webview/java/strings/android_webview_strings.grd +++ b/android_webview/java/strings/android_webview_strings.grd
@@ -4,6 +4,7 @@ <output filename="values-am/android_webview_strings.xml" lang="am" type="android" /> <output filename="values-ar/android_webview_strings.xml" lang="ar" type="android" /> <output filename="values-bg/android_webview_strings.xml" lang="bg" type="android" /> + <output filename="values-bn/android_webview_strings.xml" lang="bn" type="android" /> <output filename="values-ca/android_webview_strings.xml" lang="ca" type="android" /> <output filename="values-cs/android_webview_strings.xml" lang="cs" type="android" /> <output filename="values-da/android_webview_strings.xml" lang="da" type="android" /> @@ -13,10 +14,12 @@ <output filename="values-en-rGB/android_webview_strings.xml" lang="en-GB" type="android" /> <output filename="values-es/android_webview_strings.xml" lang="es" type="android" /> <output filename="values-es-rUS/android_webview_strings.xml" lang="es-419" type="android" /> + <output filename="values-et/android_webview_strings.xml" lang="et" type="android" /> <output filename="values-fa/android_webview_strings.xml" lang="fa" type="android" /> <output filename="values-fi/android_webview_strings.xml" lang="fi" type="android" /> <output filename="values-tl/android_webview_strings.xml" lang="fil" type="android" /> <output filename="values-fr/android_webview_strings.xml" lang="fr" type="android" /> + <output filename="values-gu/android_webview_strings.xml" lang="gu" type="android" /> <output filename="values-hi/android_webview_strings.xml" lang="hi" type="android" /> <output filename="values-hr/android_webview_strings.xml" lang="hr" type="android" /> <output filename="values-hu/android_webview_strings.xml" lang="hu" type="android" /> @@ -24,9 +27,13 @@ <output filename="values-it/android_webview_strings.xml" lang="it" type="android" /> <output filename="values-iw/android_webview_strings.xml" lang="iw" type="android" /> <output filename="values-ja/android_webview_strings.xml" lang="ja" type="android" /> + <output filename="values-kn/android_webview_strings.xml" lang="kn" type="android" /> <output filename="values-ko/android_webview_strings.xml" lang="ko" type="android" /> <output filename="values-lt/android_webview_strings.xml" lang="lt" type="android" /> <output filename="values-lv/android_webview_strings.xml" lang="lv" type="android" /> + <output filename="values-ml/android_webview_strings.xml" lang="ml" type="android" /> + <output filename="values-mr/android_webview_strings.xml" lang="mr" type="android" /> + <output filename="values-ms/android_webview_strings.xml" lang="ms" type="android" /> <output filename="values-nl/android_webview_strings.xml" lang="nl" type="android" /> <output filename="values-nb/android_webview_strings.xml" lang="no" type="android" /> <output filename="values-pl/android_webview_strings.xml" lang="pl" type="android" /> @@ -39,6 +46,8 @@ <output filename="values-sr/android_webview_strings.xml" lang="sr" type="android" /> <output filename="values-sv/android_webview_strings.xml" lang="sv" type="android" /> <output filename="values-sw/android_webview_strings.xml" lang="sw" type="android" /> + <output filename="values-ta/android_webview_strings.xml" lang="ta" type="android" /> + <output filename="values-te/android_webview_strings.xml" lang="te" type="android" /> <output filename="values-th/android_webview_strings.xml" lang="th" type="android" /> <output filename="values-tr/android_webview_strings.xml" lang="tr" type="android" /> <output filename="values-uk/android_webview_strings.xml" lang="uk" type="android" />
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/AwVariationsSeedFetcherTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/AwVariationsSeedFetcherTest.java index 295b1cc..1b5ce4a 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/AwVariationsSeedFetcherTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/AwVariationsSeedFetcherTest.java
@@ -109,7 +109,7 @@ public CallbackHelper helper = new CallbackHelper(); @Override - public SeedInfo downloadContent(VariationsSeedFetcher.VariationsPlatform platform, + public SeedInfo downloadContent(@VariationsSeedFetcher.VariationsPlatform int platform, String restrictMode, String milestone, String channel) throws SocketTimeoutException, UnknownHostException, IOException { Assert.assertEquals(VariationsSeedFetcher.VariationsPlatform.ANDROID_WEBVIEW, platform);
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/AwZoomTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/AwZoomTest.java index 0314abdc..a67a937 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/AwZoomTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/AwZoomTest.java
@@ -263,7 +263,7 @@ // Now force an orientation change, and try to display the zoom picker // again. Make sure that we don't crash when the ZoomPicker registers - // it's receiver. + // its receiver. Activity activity = mActivityTestRule.getActivity(); int orientation = activity.getRequestedOrientation(); @@ -273,7 +273,7 @@ invokeZoomPickerOnUiThread(); // We may crash shortly (as the zoom picker has a short delay in it before - // it tries to register it's BroadcastReceiver), so sleep to verify we don't. + // it tries to register its BroadcastReceiver), so sleep to verify we don't. // The delay is encoded in ZoomButtonsController#ZOOM_CONTROLS_TIMEOUT, // if that changes we may need to update this test. Thread.sleep(ViewConfiguration.getZoomControlsTimeout());
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/GetTitleTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/GetTitleTest.java index 612cdab5..7ccc4b8a 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/GetTitleTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/GetTitleTest.java
@@ -136,7 +136,7 @@ /** * When the loaded file has empty title, the page title is set to the url it loads from. - * It also contains: hostName, portNumber information if its part of the loaded URL. + * It also contains: hostName, portNumber information if it's part of the loaded URL. * @throws Throwable */ @Test @@ -149,7 +149,7 @@ /** * When the loaded file has no title, the page title is set to the urk it loads from. - * It also contains: hostName, portNumber information if its part of the loaded URL. + * It also contains: hostName, portNumber information if it's part of the loaded URL. * @throws Throwable */ @Test
diff --git a/android_webview/tools/system_webview_shell/layout_tests/src/org/chromium/webview_shell/test/WebViewLayoutTest.java b/android_webview/tools/system_webview_shell/layout_tests/src/org/chromium/webview_shell/test/WebViewLayoutTest.java index 2f7b7b3..0aeb11d 100644 --- a/android_webview/tools/system_webview_shell/layout_tests/src/org/chromium/webview_shell/test/WebViewLayoutTest.java +++ b/android_webview/tools/system_webview_shell/layout_tests/src/org/chromium/webview_shell/test/WebViewLayoutTest.java
@@ -243,6 +243,7 @@ } } + @DisabledTest(message = "crbug.com/929129") @Test @MediumTest public void testRequestMIDIAccess() throws Exception {
diff --git a/android_webview/tools/system_webview_shell/test/data/run_tests_rebaseline.sh b/android_webview/tools/system_webview_shell/test/data/run_tests_rebaseline.sh index 5563630..5f4dd1f 100755 --- a/android_webview/tools/system_webview_shell/test/data/run_tests_rebaseline.sh +++ b/android_webview/tools/system_webview_shell/test/data/run_tests_rebaseline.sh
@@ -15,7 +15,7 @@ # which is also the default if no directory is provided). # This script will produce a shadow test_rebaseline/ directory # with the new rebased expectation files. -# It is recommended to run this script from it's local +# It is recommended to run this script from its local # directory in order to have the rebaseline files placed # at the same level as the original test files. #
diff --git a/ash/app_list/views/search_box_view.cc b/ash/app_list/views/search_box_view.cc index 74a3fa3f..c614108 100644 --- a/ash/app_list/views/search_box_view.cc +++ b/ash/app_list/views/search_box_view.cc
@@ -384,12 +384,10 @@ // Current non-autocompleted text. const base::string16& user_typed_text = search_box()->text().substr(0, highlight_range_.start()); - if (last_key_pressed_ == ui::VKEY_BACK || last_key_pressed_ == ui::VKEY_UP || - last_key_pressed_ == ui::VKEY_DOWN || - last_key_pressed_ == ui::VKEY_LEFT || - last_key_pressed_ == ui::VKEY_RIGHT || !first_visible_result || + if (last_key_pressed_ == ui::VKEY_BACK || + last_key_pressed_ == ui::VKEY_DELETE || !first_visible_result || user_typed_text.length() < kMinimumLengthToAutocomplete) { - // Backspace or arrow keys were pressed, no results exist, or current text + // If the suggestion was rejected, no results exist, or current text // is too short for a confident autocomplete suggestion. return; } @@ -512,6 +510,11 @@ search_box()->SetCompositionText(composition_text); search_box()->set_controller(this); + // The controller was null briefly, so it was unaware of a highlight change. + // As a result, we need to manually declare the range to allow for proper + // selection behavior. + search_box()->SelectRange(highlight_range_); + // Send an event to alert ChromeVox that an autocomplete has occurred. // The |kValueChanged| type lets ChromeVox know that it should scan // |node_data| for "Value". @@ -548,28 +551,9 @@ if (!is_search_box_active()) return false; - // Handles autocomplete text confirmation/deletion - // TODO(ginko) fix logic for arrow keys in autocomplete - if (search_box()->HasFocus() && !search_box()->text().empty() && - ShouldProcessAutocomplete()) { - // If the search box has no text in it currently, autocomplete should not - // work. + // Record the |last_key_pressed_| for autocomplete. + if (!search_box()->text().empty() && ShouldProcessAutocomplete()) last_key_pressed_ = key_event.key_code(); - if (key_event.type() == ui::ET_KEY_PRESSED && - key_event.key_code() != ui::VKEY_BACK) { - if (key_event.key_code() == ui::VKEY_TAB && HasAutocompleteText()) { - AcceptAutocompleteText(); - return true; - } else if ((key_event.key_code() == ui::VKEY_UP || - key_event.key_code() == ui::VKEY_DOWN || - key_event.key_code() == ui::VKEY_LEFT || - key_event.key_code() == ui::VKEY_RIGHT) && - HasAutocompleteText()) { - ClearAutocompleteText(); - return true; - } - } - } // Only arrow key events intended for traversal within search results should // be handled from here.
diff --git a/ash/app_list/views/search_box_view_unittest.cc b/ash/app_list/views/search_box_view_unittest.cc index 84c4377d..052d5a3 100644 --- a/ash/app_list/views/search_box_view_unittest.cc +++ b/ash/app_list/views/search_box_view_unittest.cc
@@ -614,14 +614,6 @@ true); } -// Tests that only the autocomplete suggestion text is deleted after pressing -// up, down, left, right, or backspace. -TEST_P(SearchBoxViewAutocompleteTest, - SearchBoxDeletesAutocompleteTextOnlyAfterUpDownLeftRightBackspace) { - TestKeyEvent(ui::KeyEvent(ui::ET_KEY_PRESSED, key_code(), ui::EF_NONE), - false); -} - // Tests that autocomplete is not handled if IME is using composition text. TEST_F(SearchBoxViewAutocompleteTest, SearchBoxAutocompletesNotHandledForIME) { // Add a search result with a non-empty title field.
diff --git a/ash/system/network/network_icon.cc b/ash/system/network/network_icon.cc index 8596c680..7880b50 100644 --- a/ash/system/network/network_icon.cc +++ b/ash/system/network/network_icon.cc
@@ -16,7 +16,6 @@ #include "base/strings/utf_string_conversions.h" #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" -#include "chromeos/network/portal_detector/network_portal_detector.h" #include "chromeos/network/tether_constants.h" #include "components/vector_icons/vector_icons.h" #include "third_party/cros_system_api/dbus/service_constants.h" @@ -29,7 +28,6 @@ using chromeos::NetworkConnectionHandler; using chromeos::NetworkHandler; -using chromeos::NetworkPortalDetector; using chromeos::NetworkState; using chromeos::NetworkStateHandler; using chromeos::NetworkTypePattern; @@ -59,9 +57,6 @@ // Updates the local state for cellular networks. Returns true if changed. bool UpdateCellularState(const chromeos::NetworkState* network); - // Updates the portal state for wireless networks. Returns true if changed. - bool UpdatePortalState(const chromeos::NetworkState* network); - // Gets |badges| based on |network| and the current state. void GetBadges(const NetworkState* network, Badges* badges); @@ -357,18 +352,21 @@ // Determine whether or not we need to update the icon. bool dirty = image_.isNull(); - // If the network state has changed, the icon needs updating. - if (connection_state_ != network->connection_state()) { - connection_state_ = network->connection_state(); + std::string connection_state = network->connection_state(); + if (connection_state != connection_state_) { + connection_state_ = connection_state; dirty = true; } - dirty |= UpdatePortalState(network); - - if (network->Matches(NetworkTypePattern::Wireless())) { - dirty |= UpdateWirelessStrengthIndex(network); + bool behind_captive_portal = network->IsCaptivePortal(); + if (behind_captive_portal != behind_captive_portal_) { + behind_captive_portal_ = behind_captive_portal; + dirty = true; } + if (network->Matches(NetworkTypePattern::Wireless())) + dirty |= UpdateWirelessStrengthIndex(network); + if (network->Matches(NetworkTypePattern::Cellular())) dirty |= UpdateCellularState(network); @@ -408,22 +406,6 @@ return dirty; } -bool NetworkIconImpl::UpdatePortalState(const NetworkState* network) { - bool behind_captive_portal = false; - if (network && chromeos::network_portal_detector::IsInitialized()) { - NetworkPortalDetector::CaptivePortalState state = - chromeos::network_portal_detector::GetInstance()->GetCaptivePortalState( - network->guid()); - behind_captive_portal = - state.status == NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_PORTAL; - } - - if (behind_captive_portal == behind_captive_portal_) - return false; - behind_captive_portal_ = behind_captive_portal; - return true; -} - void NetworkIconImpl::GetBadges(const NetworkState* network, Badges* badges) { DCHECK(network);
diff --git a/ash/system/network/tray_network_state_observer.cc b/ash/system/network/tray_network_state_observer.cc index 602433a..688ae59 100644 --- a/ash/system/network/tray_network_state_observer.cc +++ b/ash/system/network/tray_network_state_observer.cc
@@ -35,20 +35,15 @@ ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION) { update_frequency_ = 0; // Send updates immediately for tests. } - // TODO(mash): Figure out what to do about NetworkHandler and - // NetworkPortalDetector. + // TODO(mash): Figure out what to do about NetworkHandler. if (NetworkHandler::IsInitialized()) { NetworkHandler::Get()->network_state_handler()->AddObserver(this, FROM_HERE); wifi_enabled_ = IsWifiEnabled(); } - if (chromeos::network_portal_detector::IsInitialized()) - chromeos::network_portal_detector::GetInstance()->AddObserver(this); } TrayNetworkStateObserver::~TrayNetworkStateObserver() { - if (chromeos::network_portal_detector::IsInitialized()) - chromeos::network_portal_detector::GetInstance()->RemoveObserver(this); if (NetworkHandler::IsInitialized()) { NetworkHandler::Get()->network_state_handler()->RemoveObserver(this, FROM_HERE); @@ -76,12 +71,6 @@ SignalUpdate(false /* notify_a11y */); } -void TrayNetworkStateObserver::OnPortalDetectionCompleted( - const chromeos::NetworkState* network, - const chromeos::NetworkPortalDetector::CaptivePortalState& state) { - SignalUpdate(true /* notify_a11y */); -} - void TrayNetworkStateObserver::SignalUpdate(bool notify_a11y) { bool old_state = wifi_enabled_; wifi_enabled_ = IsWifiEnabled();
diff --git a/ash/system/network/tray_network_state_observer.h b/ash/system/network/tray_network_state_observer.h index 1f2d611..d926312 100644 --- a/ash/system/network/tray_network_state_observer.h +++ b/ash/system/network/tray_network_state_observer.h
@@ -10,13 +10,10 @@ #include "base/macros.h" #include "base/timer/timer.h" #include "chromeos/network/network_state_handler_observer.h" -#include "chromeos/network/portal_detector/network_portal_detector.h" namespace ash { -class TrayNetworkStateObserver - : public chromeos::NetworkStateHandlerObserver, - public chromeos::NetworkPortalDetector::Observer { +class TrayNetworkStateObserver : public chromeos::NetworkStateHandlerObserver { public: class Delegate { public: @@ -39,12 +36,6 @@ active_networks) override; void NetworkPropertiesUpdated(const chromeos::NetworkState* network) override; - // NetworkPortalDetector::Observer - void OnPortalDetectionCompleted( - const chromeos::NetworkState* network, - const chromeos::NetworkPortalDetector::CaptivePortalState& state) - override; - private: void SignalUpdate(bool notify_a11y); void SendNetworkStateChanged(bool notify_a11y);
diff --git a/ash/wm/default_state.cc b/ash/wm/default_state.cc index cda9814..d4c012dd 100644 --- a/ash/wm/default_state.cc +++ b/ash/wm/default_state.cc
@@ -378,7 +378,7 @@ screen_util::GetMaximizedWindowBoundsInParent(window_state->window())); return true; } - if (window_state->IsFullscreen()) { + if (window_state->IsFullscreen() || window_state->IsPinned()) { window_state->SetBoundsDirect( screen_util::GetDisplayBoundsInParent(window_state->window())); return true;
diff --git a/base/BUILD.gn b/base/BUILD.gn index d84c3353..39ca8f18 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -953,8 +953,6 @@ "trace_event/trace_event_impl.h", "trace_event/trace_event_memory_overhead.cc", "trace_event/trace_event_memory_overhead.h", - "trace_event/trace_event_system_stats_monitor.cc", - "trace_event/trace_event_system_stats_monitor.h", "trace_event/trace_log.cc", "trace_event/trace_log.h", "trace_event/trace_log_constants.cc", @@ -1543,7 +1541,6 @@ "system/sys_info_posix.cc", "task/task_scheduler/initialization_util.cc", "task/task_scheduler/initialization_util.h", - "trace_event/trace_event_system_stats_monitor.cc", ] if (is_nacl_nonsfi) { @@ -2500,6 +2497,7 @@ "task/sequence_manager/lazily_deallocated_deque_unittest.cc", "task/sequence_manager/sequence_manager_impl_unittest.cc", "task/sequence_manager/task_queue_selector_unittest.cc", + "task/sequence_manager/test/mock_time_message_pump_unittest.cc", "task/sequence_manager/thread_controller_with_message_pump_impl_unittest.cc", "task/sequence_manager/time_domain_unittest.cc", "task/sequence_manager/work_queue_sets_unittest.cc", @@ -2581,7 +2579,6 @@ "trace_event/trace_config_unittest.cc", "trace_event/trace_event_filter_test_utils.cc", "trace_event/trace_event_filter_test_utils.h", - "trace_event/trace_event_system_stats_monitor_unittest.cc", "trace_event/trace_event_unittest.cc", "trace_event/traced_value_unittest.cc", "traits_bag_unittest.cc",
diff --git a/base/android/java/src/org/chromium/base/task/AsyncTask.java b/base/android/java/src/org/chromium/base/task/AsyncTask.java index 41747e7..c02b1ae8f 100644 --- a/base/android/java/src/org/chromium/base/task/AsyncTask.java +++ b/base/android/java/src/org/chromium/base/task/AsyncTask.java
@@ -5,7 +5,6 @@ package org.chromium.base.task; import android.os.Binder; -import android.os.Process; import android.support.annotation.IntDef; import android.support.annotation.MainThread; import android.support.annotation.WorkerThread; @@ -34,10 +33,14 @@ public abstract class AsyncTask<Result> { private static final String TAG = "AsyncTask"; + private static TaskTraits sLowPriorityTraits = + new TaskTraits().taskPriority(TaskPriority.LOWEST).mayBlock(true); /** * An {@link Executor} that can be used to execute tasks in parallel. + * We use the lowest task priority, and mayBlock = true since any user of this could block. */ - public static final Executor THREAD_POOL_EXECUTOR = new ChromeThreadPoolExecutor(); + public static final Executor THREAD_POOL_EXECUTOR = + (Runnable r) -> PostTask.postTask(sLowPriorityTraits, r); /** * An {@link Executor} that executes tasks one at a time in serial @@ -100,7 +103,6 @@ mTaskInvoked.set(true); Result result = null; try { - Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); result = doInBackground(); Binder.flushPendingCommands(); } catch (Throwable tr) { @@ -353,6 +355,20 @@ return this; } + /** + * Executes an AsyncTask with the given task traits. Provides no guarantees about sequencing or + * which thread it runs on. + * + * @param taskTraits traits which describe this AsyncTask. + * @return This instance of AsyncTask. + */ + @MainThread + public final AsyncTask<Result> executeWithTaskTraits(TaskTraits taskTraits) { + executionPreamble(); + PostTask.postTask(taskTraits, mFuture); + return this; + } + private void finish(Result result) { if (isCancelled()) { onCancelled(result);
diff --git a/base/android/java/src/org/chromium/base/task/ChromeThreadPoolExecutor.java b/base/android/java/src/org/chromium/base/task/ChromeThreadPoolExecutor.java index 7538843..fdab8f9 100644 --- a/base/android/java/src/org/chromium/base/task/ChromeThreadPoolExecutor.java +++ b/base/android/java/src/org/chromium/base/task/ChromeThreadPoolExecutor.java
@@ -6,6 +6,8 @@ import static java.util.concurrent.TimeUnit.SECONDS; +import android.os.Process; + import org.chromium.base.BuildConfig; import org.chromium.base.VisibleForTesting; @@ -34,7 +36,11 @@ private final AtomicInteger mCount = new AtomicInteger(1); @Override public Thread newThread(Runnable r) { - return new Thread(r, "CrAsyncTask #" + mCount.getAndIncrement()); + Thread t = new Thread(() -> { + Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); + r.run(); + }, "CrAsyncTask #" + mCount.getAndIncrement()); + return t; } }; @@ -109,9 +115,9 @@ } @Override - public void execute(Runnable command) { + public void execute(Runnable r) { try { - super.execute(command); + super.execute(r); } catch (RejectedExecutionException e) { Map<String, Integer> counts = getNumberOfClassNameOccurrencesInQueue();
diff --git a/base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java b/base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java index f351f68..dad7384 100644 --- a/base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java +++ b/base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java
@@ -4,6 +4,7 @@ package org.chromium.base.task; +import android.os.Process; import android.support.annotation.Nullable; import android.util.Pair; @@ -21,7 +22,6 @@ */ @JNINamespace("base") public class TaskRunnerImpl implements TaskRunner { - @Nullable private final TaskTraits mTaskTraits; private final String mTraceEvent; private final @TaskRunnerType int mTaskRunnerType; @@ -30,6 +30,9 @@ protected final Runnable mRunPreNativeTaskClosure = this::runPreNativeTask; private boolean mIsDestroying; private final LifetimeAssert mLifetimeAssert = LifetimeAssert.create(this); + private static final ChromeThreadPoolExecutor THREAD_POOL_EXECUTOR = + new ChromeThreadPoolExecutor(); + @Nullable protected LinkedList<Runnable> mPreNativeTasks = new LinkedList<>(); @Nullable @@ -103,7 +106,7 @@ * time. */ protected void schedulePreNativeTask() { - AsyncTask.THREAD_POOL_EXECUTOR.execute(mRunPreNativeTaskClosure); + THREAD_POOL_EXECUTOR.execute(mRunPreNativeTaskClosure); } /** @@ -116,6 +119,17 @@ if (mPreNativeTasks == null) return; task = mPreNativeTasks.poll(); } + switch (mTaskTraits.mPriority) { + case TaskPriority.USER_VISIBLE: + Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); + break; + case TaskPriority.HIGHEST: + Process.setThreadPriority(Process.THREAD_PRIORITY_MORE_FAVORABLE); + break; + default: + Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); + break; + } task.run(); } }
diff --git a/base/android/jni_generator/jni_generator.py b/base/android/jni_generator/jni_generator.py index d9c0254..75ec34f5 100755 --- a/base/android/jni_generator/jni_generator.py +++ b/base/android/jni_generator/jni_generator.py
@@ -643,8 +643,10 @@ return mangled_name -def MangleCalledByNatives(jni_params, called_by_natives): - """Mangles all the overloads from the call_by_natives list.""" +def MangleCalledByNatives(jni_params, called_by_natives, always_mangle): + """Mangles all the overloads from the call_by_natives list or + mangle all methods if always_mangle is true. + """ method_counts = collections.defaultdict( lambda: collections.defaultdict(lambda: 0)) for called_by_native in called_by_natives: @@ -655,7 +657,7 @@ java_class_name = called_by_native.java_class_name method_name = called_by_native.name method_id_var_name = method_name - if method_counts[java_class_name][method_name] > 1: + if always_mangle or method_counts[java_class_name][method_name] > 1: method_id_var_name = GetMangledMethodName(jni_params, method_name, called_by_native.params, called_by_native.return_type) @@ -684,12 +686,13 @@ return re.sub('^(?: {2})+$\n', '', string, flags=re.MULTILINE) -def ExtractCalledByNatives(jni_params, contents): +def ExtractCalledByNatives(jni_params, contents, always_mangle): """Parses all methods annotated with @CalledByNative. Args: jni_params: JniParams object. contents: the contents of the java file. + always_mangle: See MangleCalledByNatives. Returns: A list of dict with information about the annotated methods. @@ -724,7 +727,7 @@ if '@CalledByNative' in line1: raise ParseError('could not parse @CalledByNative method signature', line1, line2) - return MangleCalledByNatives(jni_params, called_by_natives) + return MangleCalledByNatives(jni_params, called_by_natives, always_mangle) def RemoveComments(contents): @@ -800,7 +803,8 @@ signature=JniParams.ParseJavaPSignature(contents[lineno + 1]), is_constructor=True)] self.called_by_natives = MangleCalledByNatives(self.jni_params, - self.called_by_natives) + self.called_by_natives, + options.always_mangle) self.constant_fields = [] re_constant_field = re.compile('.*?public static final int (?P<name>.*?);') re_constant_field_value = re.compile( @@ -931,7 +935,9 @@ self.jni_params.ExtractImportsAndInnerClasses(contents) jni_namespace = ExtractJNINamespace(contents) or options.namespace natives = ExtractNatives(contents, options.ptr_type) - called_by_natives = ExtractCalledByNatives(self.jni_params, contents) + called_by_natives = ExtractCalledByNatives(self.jni_params, + contents, + options.always_mangle) natives += ProxyHelpers.ExtractStaticProxyNatives( fully_qualified_class, contents, options.ptr_type, @@ -1591,6 +1597,8 @@ help='Add additional profiling instrumentation.') option_parser.add_option('--enable_tracing', action='store_true', help='Add TRACE_EVENTs to generated functions.') + option_parser.add_option('--always_mangle', action='store_true', + help='Mangle all function names') option_parser.add_option( '--use_proxy_hash', action='store_true',
diff --git a/base/android/jni_generator/jni_generator_tests.py b/base/android/jni_generator/jni_generator_tests.py index bc99a7a..4b927dc 100755 --- a/base/android/jni_generator/jni_generator_tests.py +++ b/base/android/jni_generator/jni_generator_tests.py
@@ -48,6 +48,7 @@ self.enable_profiling = False self.enable_tracing = False self.use_proxy_hash = False + self.always_mangle = False class BaseTest(unittest.TestCase): @@ -543,8 +544,8 @@ """ jni_params = jni_generator.JniParams('org/chromium/Foo') jni_params.ExtractImportsAndInnerClasses(test_data) - called_by_natives = jni_generator.ExtractCalledByNatives(jni_params, - test_data) + called_by_natives = jni_generator.ExtractCalledByNatives( + jni_params, test_data, always_mangle=False) golden_called_by_natives = [ CalledByNative( return_type='InnerClass', @@ -787,7 +788,7 @@ @CalledByNative scooby doo -""") +""", always_mangle=False) self.fail('Expected a ParseError') except jni_generator.ParseError, e: self.assertEquals(('@CalledByNative', 'scooby doo'), e.context_lines) @@ -831,6 +832,27 @@ datatype='java/lang/String'),], 'java/io/InputStream')) + def testMethodNameAlwaysMangle(self): + test_data = """ + import f.o.o.Bar; + import f.o.o.Baz; + + class Clazz { + @CalledByNative + public Baz methodz(Bar bar) { + return null; + } + } + """ + jni_params = jni_generator.JniParams('org/chromium/Foo') + jni_params.ExtractImportsAndInnerClasses(test_data) + called_by_natives = jni_generator.ExtractCalledByNatives(jni_params, + test_data, + always_mangle=True) + self.assertEquals(1, len(called_by_natives)) + method = called_by_natives[0] + self.assertEquals('methodzFOOB_FOOB', method.method_id_var_name) + def testFromJavaPGenerics(self): contents = """ public abstract class java.util.HashSet<T> extends java.util.AbstractSet<E>
diff --git a/base/fuchsia/scoped_service_binding.h b/base/fuchsia/scoped_service_binding.h index 3acabde7..302af71 100644 --- a/base/fuchsia/scoped_service_binding.h +++ b/base/fuchsia/scoped_service_binding.h
@@ -20,7 +20,6 @@ ScopedServiceBinding(ServiceDirectory* service_directory, Interface* impl) : directory_(service_directory), impl_(impl) { directory_->AddService( - Interface::Name_, BindRepeating(&ScopedServiceBinding::BindClient, Unretained(this))); } @@ -33,9 +32,8 @@ } private: - void BindClient(zx::channel channel) { - bindings_.AddBinding(impl_, - fidl::InterfaceRequest<Interface>(std::move(channel))); + void BindClient(fidl::InterfaceRequest<Interface> request) { + bindings_.AddBinding(impl_, std::move(request)); } void OnBindingSetEmpty() {
diff --git a/base/fuchsia/service_directory.cc b/base/fuchsia/service_directory.cc index 211a1b0..93c416f6 100644 --- a/base/fuchsia/service_directory.cc +++ b/base/fuchsia/service_directory.cc
@@ -47,7 +47,7 @@ void ServiceDirectory::AddServiceUnsafe( StringPiece name, - ConnectServiceCallback connect_callback) { + RepeatingCallback<void(zx::channel)> connect_callback) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(services_.find(name) == services_.end());
diff --git a/base/fuchsia/service_directory.h b/base/fuchsia/service_directory.h index db6fe4a2..9813b58 100644 --- a/base/fuchsia/service_directory.h +++ b/base/fuchsia/service_directory.h
@@ -36,9 +36,6 @@ // object. class BASE_EXPORT ServiceDirectory { public: - // Callback called to connect incoming requests. - using ConnectServiceCallback = RepeatingCallback<void(zx::channel channel)>; - // Responds to service requests over the supplied |request| channel. explicit ServiceDirectory( fidl::InterfaceRequest<::fuchsia::io::Directory> request); @@ -53,13 +50,16 @@ static ServiceDirectory* GetDefault(); template <typename Interface> - void AddService( - RepeatingCallback<fidl::InterfaceRequest<Interface>> connect_callback) { - AddService(Interface::Name_, - BindRepeating([connect_callback](zx::channel request) { - connect_callback.Run( - fidl::InterfaceRequest<Interface>(std::move(request))); - })); + void AddService(RepeatingCallback<void(fidl::InterfaceRequest<Interface>)> + connect_callback) { + AddServiceUnsafe( + Interface::Name_, + BindRepeating( + [](decltype(connect_callback) callback, zx::channel request) { + callback.Run( + fidl::InterfaceRequest<Interface>(std::move(request))); + }, + connect_callback)); } void RemoveService(StringPiece name); void RemoveAllServices(); @@ -68,10 +68,11 @@ // This is used only when proxying requests for interfaces not known at // compile-time. Use the type-safe APIs above whenever possible. void AddServiceUnsafe(StringPiece name, - ConnectServiceCallback connect_callback); + RepeatingCallback<void(zx::channel)> connect_callback); // TODO(https://crbug.com/920920): Clean up callers and remove this synonym. - void AddService(StringPiece name, ConnectServiceCallback connect_callback) { + void AddService(StringPiece name, + RepeatingCallback<void(zx::channel)> connect_callback) { AddServiceUnsafe(name, std::move(connect_callback)); } @@ -84,7 +85,7 @@ THREAD_CHECKER(thread_checker_); svc_dir_t* svc_dir_ = nullptr; - flat_map<std::string, ConnectServiceCallback> services_; + flat_map<std::string, RepeatingCallback<void(zx::channel)>> services_; DISALLOW_COPY_AND_ASSIGN(ServiceDirectory); };
diff --git a/base/memory/discardable_shared_memory.cc b/base/memory/discardable_shared_memory.cc index 5ad48a97..57494b5 100644 --- a/base/memory/discardable_shared_memory.cc +++ b/base/memory/discardable_shared_memory.cc
@@ -487,12 +487,14 @@ size_t length) { #if defined(OS_ANDROID) if (region.IsValid()) { - int pin_result = - ashmem_pin_region(region.GetPlatformHandle(), offset, length); - if (pin_result == ASHMEM_WAS_PURGED) - return PURGED; - if (pin_result < 0) - return FAILED; + if (ashmem_device_is_supported()) { + int pin_result = + ashmem_pin_region(region.GetPlatformHandle(), offset, length); + if (pin_result == ASHMEM_WAS_PURGED) + return PURGED; + if (pin_result < 0) + return FAILED; + } } #endif return SUCCESS; @@ -505,9 +507,11 @@ size_t length) { #if defined(OS_ANDROID) if (region.IsValid()) { - int unpin_result = - ashmem_unpin_region(region.GetPlatformHandle(), offset, length); - DCHECK_EQ(0, unpin_result); + if (ashmem_device_is_supported()) { + int unpin_result = + ashmem_unpin_region(region.GetPlatformHandle(), offset, length); + DCHECK_EQ(0, unpin_result); + } } #endif } @@ -516,4 +520,11 @@ return Time::Now(); } +#if defined(OS_ANDROID) +// static +bool DiscardableSharedMemory::IsAshmemDeviceSupportedForTesting() { + return ashmem_device_is_supported(); +} +#endif + } // namespace base
diff --git a/base/memory/discardable_shared_memory.h b/base/memory/discardable_shared_memory.h index 52a78b1..44d4cab 100644 --- a/base/memory/discardable_shared_memory.h +++ b/base/memory/discardable_shared_memory.h
@@ -150,6 +150,12 @@ trace_event::ProcessMemoryDump* pmd, bool is_owned) const; +#if defined(OS_ANDROID) + // Returns true if the Ashmem device is supported on this system. + // Only use this for unit-testing. + static bool IsAshmemDeviceSupportedForTesting(); +#endif + private: // LockPages/UnlockPages are platform-native discardable page management // helper functions. Both expect |offset| to be specified relative to the
diff --git a/base/memory/discardable_shared_memory_unittest.cc b/base/memory/discardable_shared_memory_unittest.cc index 78712d8..538f5c69 100644 --- a/base/memory/discardable_shared_memory_unittest.cc +++ b/base/memory/discardable_shared_memory_unittest.cc
@@ -245,6 +245,11 @@ TEST(DiscardableSharedMemoryTest, LockShouldFailIfPlatformLockPagesFails) { const uint32_t kDataSize = 1024; + // This test cannot succeed on devices without a proper ashmem device + // because Lock() will always succeed. + if (!DiscardableSharedMemory::IsAshmemDeviceSupportedForTesting()) + return; + DiscardableSharedMemory memory1; bool rv1 = memory1.CreateAndMap(kDataSize); ASSERT_TRUE(rv1);
diff --git a/base/message_loop/message_pump.cc b/base/message_loop/message_pump.cc index 23a0f94..9076176 100644 --- a/base/message_loop/message_pump.cc +++ b/base/message_loop/message_pump.cc
@@ -6,8 +6,6 @@ namespace base { -void MessagePump::Delegate::BeforeDoInternalWork() {} - MessagePump::MessagePump() = default; MessagePump::~MessagePump() = default;
diff --git a/base/message_loop/message_pump.h b/base/message_loop/message_pump.h index 012bafa..ebbc4e5 100644 --- a/base/message_loop/message_pump.h +++ b/base/message_loop/message_pump.h
@@ -23,8 +23,10 @@ public: virtual ~Delegate() = default; - // Called before work performed internal to the message pump is executed. - virtual void BeforeDoInternalWork(); + // Called before work performed internal to the message pump is executed, + // including waiting for a wake up. Currently only called on Windows. + // TODO(wittman): Implement for other platforms. + virtual void BeforeDoInternalWork() = 0; struct NextWorkInfo { // Helper to extract a TimeDelta for pumps that need a
diff --git a/base/message_loop/message_pump_unittest.cc b/base/message_loop/message_pump_unittest.cc index d5f4e43a..4c9d0320 100644 --- a/base/message_loop/message_pump_unittest.cc +++ b/base/message_loop/message_pump_unittest.cc
@@ -62,6 +62,7 @@ MockMessagePumpDelegate() = default; // MessagePump::Delegate: + void BeforeDoInternalWork() {} MOCK_METHOD0(DoSomeWork, MessagePump::Delegate::NextWorkInfo()); MOCK_METHOD0(DoWork, bool()); MOCK_METHOD1(DoDelayedWork, bool(TimeTicks*)); @@ -177,6 +178,8 @@ action_.store(NONE); } + void BeforeDoInternalWork() override {} + MessagePump::Delegate::NextWorkInfo DoSomeWork() override { switch (action_.load()) { case NONE:
diff --git a/base/message_loop/message_pump_win.cc b/base/message_loop/message_pump_win.cc index 607ed31..97f45e7 100644 --- a/base/message_loop/message_pump_win.cc +++ b/base/message_loop/message_pump_win.cc
@@ -203,6 +203,8 @@ if (more_work_is_plausible) continue; + // WaitForWork() does some work itself, so notify the delegate of it. + state_->delegate->BeforeDoInternalWork(); WaitForWork(); // Wait (sleep) until we have work to do again. } }
diff --git a/base/message_loop/work_id_provider.h b/base/message_loop/work_id_provider.h index 8f08f2d..2d833bc 100644 --- a/base/message_loop/work_id_provider.h +++ b/base/message_loop/work_id_provider.h
@@ -11,10 +11,9 @@ #include "base/threading/thread_checker.h" namespace base { -class MessageLoopImpl; namespace sequence_manager { namespace internal { -class SequenceManagerImpl; +class ThreadControllerWithMessagePumpImpl; } } // namespace sequence_manager @@ -54,8 +53,7 @@ private: // Friended to allow use of IncrementWorkId(). - friend class MessageLoopImpl; - friend class sequence_manager::internal::SequenceManagerImpl; + friend class sequence_manager::internal::ThreadControllerWithMessagePumpImpl; WorkIdProvider();
diff --git a/base/process/process_metrics.h b/base/process/process_metrics.h index 3bba9aa..16e9785 100644 --- a/base/process/process_metrics.h +++ b/base/process/process_metrics.h
@@ -534,7 +534,7 @@ // Collects and holds performance metrics for system memory and disk. // Provides functionality to retrieve the data on various platforms and // to serialize the stored data. -class SystemMetrics { +class BASE_EXPORT SystemMetrics { public: SystemMetrics();
diff --git a/base/sampling_heap_profiler/poisson_allocation_sampler.cc b/base/sampling_heap_profiler/poisson_allocation_sampler.cc index 20b1d82a..1f393456 100644 --- a/base/sampling_heap_profiler/poisson_allocation_sampler.cc +++ b/base/sampling_heap_profiler/poisson_allocation_sampler.cc
@@ -131,7 +131,7 @@ bool g_deterministic; // A positive value if profiling is running, otherwise it's zero. -std::atomic_int g_running; +std::atomic_bool g_running; // Pointer to the current |LockFreeAddressHashSet|. std::atomic<LockFreeAddressHashSet*> g_sampled_addresses_set; @@ -390,16 +390,6 @@ g_hooks_install_callback(); } -void PoissonAllocationSampler::Start() { - InstallAllocatorHooksOnce(); - ++g_running; -} - -void PoissonAllocationSampler::Stop() { - int count = --g_running; - CHECK_GE(count, 0); -} - void PoissonAllocationSampler::SetSamplingInterval(size_t sampling_interval) { // TODO(alph): Reset the sample being collected if running. g_sampling_interval = sampling_interval; @@ -552,6 +542,8 @@ ScopedMuteThreadSamples no_reentrancy_scope; AutoLock lock(mutex_); observers_.push_back(observer); + InstallAllocatorHooksOnce(); + g_running = !observers_.empty(); } void PoissonAllocationSampler::RemoveSamplesObserver( @@ -561,6 +553,7 @@ auto it = std::find(observers_.begin(), observers_.end(), observer); CHECK(it != observers_.end()); observers_.erase(it); + g_running = !observers_.empty(); } } // namespace base
diff --git a/base/sampling_heap_profiler/poisson_allocation_sampler.h b/base/sampling_heap_profiler/poisson_allocation_sampler.h index 0dfb8b2a8..ecd09bd 100644 --- a/base/sampling_heap_profiler/poisson_allocation_sampler.h +++ b/base/sampling_heap_profiler/poisson_allocation_sampler.h
@@ -75,8 +75,6 @@ void AddSamplesObserver(SamplesObserver*); void RemoveSamplesObserver(SamplesObserver*); - void Start(); - void Stop(); void SetSamplingInterval(size_t sampling_interval); void SuppressRandomnessForTest(bool suppress);
diff --git a/base/sampling_heap_profiler/sampling_heap_profiler.cc b/base/sampling_heap_profiler/sampling_heap_profiler.cc index 87caa3b..d12de8a7 100644 --- a/base/sampling_heap_profiler/sampling_heap_profiler.cc +++ b/base/sampling_heap_profiler/sampling_heap_profiler.cc
@@ -46,16 +46,12 @@ return 0; } #endif - auto* sampler = PoissonAllocationSampler::Get(); - sampler->AddSamplesObserver(this); - sampler->Start(); + PoissonAllocationSampler::Get()->AddSamplesObserver(this); return last_sample_ordinal_; } void SamplingHeapProfiler::Stop() { - auto* sampler = PoissonAllocationSampler::Get(); - sampler->Stop(); - sampler->RemoveSamplesObserver(this); + PoissonAllocationSampler::Get()->RemoveSamplesObserver(this); } void SamplingHeapProfiler::SetSamplingInterval(size_t sampling_interval) {
diff --git a/base/sampling_heap_profiler/sampling_heap_profiler_unittest.cc b/base/sampling_heap_profiler/sampling_heap_profiler_unittest.cc index 44707d1..110d8256 100644 --- a/base/sampling_heap_profiler/sampling_heap_profiler_unittest.cc +++ b/base/sampling_heap_profiler/sampling_heap_profiler_unittest.cc
@@ -62,11 +62,9 @@ auto* sampler = PoissonAllocationSampler::Get(); sampler->SuppressRandomnessForTest(true); sampler->SetSamplingInterval(1024); - sampler->Start(); sampler->AddSamplesObserver(&collector); void* volatile p = malloc(10000); free(p); - sampler->Stop(); sampler->RemoveSamplesObserver(&collector); EXPECT_TRUE(collector.sample_added); EXPECT_TRUE(collector.sample_removed); @@ -77,14 +75,12 @@ auto* sampler = PoissonAllocationSampler::Get(); sampler->SuppressRandomnessForTest(true); sampler->SetSamplingInterval(1024); - sampler->Start(); sampler->AddSamplesObserver(&collector); { PoissonAllocationSampler::ScopedMuteThreadSamples muted_scope; void* volatile p = malloc(10000); free(p); } - sampler->Stop(); sampler->RemoveSamplesObserver(&collector); EXPECT_FALSE(collector.sample_added); EXPECT_FALSE(collector.sample_removed);
diff --git a/base/task/sequence_manager/sequence_manager_impl.cc b/base/task/sequence_manager/sequence_manager_impl.cc index 0c5cda2..5832dc9 100644 --- a/base/task/sequence_manager/sequence_manager_impl.cc +++ b/base/task/sequence_manager/sequence_manager_impl.cc
@@ -123,6 +123,14 @@ TRACE_EVENT_OBJECT_DELETED_WITH_ID( TRACE_DISABLED_BY_DEFAULT("sequence_manager"), "SequenceManager", this); + // Make sure no Task is running as given that RunLoop does not support the + // Delegate being destroyed from a Task and + // ThreadControllerWithMessagePumpImpl does not support being destroyed from a + // Task. If we are using a ThreadControllerImpl (i.e. no pump) destruction is + // fine + DCHECK(!controller_->GetBoundMessagePump() || + main_thread_only().task_execution_stack.empty()); + // TODO(altimin): restore default task runner automatically when // ThreadController is destroyed. controller_->RestoreDefaultTaskRunner(); @@ -218,7 +226,6 @@ void SequenceManagerImpl::CompleteInitializationOnBoundThread() { controller_->AddNestingObserver(this); - work_id_provider_ = WorkIdProvider::GetForCurrentThread(); main_thread_only().nesting_observer_registered_ = true; if (GetMessagePump()) MessageLoopCurrent::BindToCurrentThreadInternal(this); @@ -414,8 +421,7 @@ controller_->ScheduleWork(); } -void SequenceManagerImpl::MaybeScheduleImmediateWork( - const Location& from_here) { +void SequenceManagerImpl::ScheduleWork() { controller_->ScheduleWork(); } @@ -439,8 +445,6 @@ executing_task.task_queue->GetName(), "task_type", executing_task.task_type); - work_id_provider_->IncrementWorkId(); - return task; } @@ -789,7 +793,7 @@ DCHECK(queue->IsQueueEnabled()); // Only schedule DoWork if there's something to do. if (queue->HasTaskToRunImmediately() && !queue->BlockedByFence()) - MaybeScheduleImmediateWork(FROM_HERE); + ScheduleWork(); } void SequenceManagerImpl::ReclaimMemory() {
diff --git a/base/task/sequence_manager/sequence_manager_impl.h b/base/task/sequence_manager/sequence_manager_impl.h index e3838c1b..aafea911 100644 --- a/base/task/sequence_manager/sequence_manager_impl.h +++ b/base/task/sequence_manager/sequence_manager_impl.h
@@ -22,7 +22,6 @@ #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/message_loop/message_loop.h" -#include "base/message_loop/work_id_provider.h" #include "base/pending_task.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" @@ -166,11 +165,8 @@ void DeletePendingTasks() override; bool HasTasks() override; - // Requests that a task to process work is posted on the main task runner. - // These tasks are de-duplicated in two buckets: main-thread and all other - // threads. This distinction is done to reduce the overhead from locks, we - // assume the main-thread path will be hot. - void MaybeScheduleImmediateWork(const Location& from_here); + // Requests that a task to process work is scheduled. + void ScheduleWork(); // Requests that a delayed task to process work is posted on the main task // runner. These delayed tasks are de-duplicated. Must be called on the thread @@ -393,11 +389,6 @@ // Whether to add the queue time to tasks. base::subtle::Atomic32 add_queue_time_to_tasks_ = 0; - // Non-null provider of id state for identifying distinct work items executed - // by the message loop (task, event, etc.). Cached on the class to avoid TLS - // lookups on task execution. - WorkIdProvider* work_id_provider_ = nullptr; - // A check to bail out early during memory corruption. // https://crbug.com/757940 bool Validate();
diff --git a/base/task/sequence_manager/sequence_manager_impl_unittest.cc b/base/task/sequence_manager/sequence_manager_impl_unittest.cc index dafe6de..b64e40c 100644 --- a/base/task/sequence_manager/sequence_manager_impl_unittest.cc +++ b/base/task/sequence_manager/sequence_manager_impl_unittest.cc
@@ -9,6 +9,7 @@ #include <utility> #include "base/bind.h" +#include "base/callback.h" #include "base/location.h" #include "base/memory/ref_counted_memory.h" #include "base/message_loop/message_loop.h" @@ -23,6 +24,7 @@ #include "base/task/sequence_manager/task_queue_impl.h" #include "base/task/sequence_manager/task_queue_selector.h" #include "base/task/sequence_manager/test/mock_time_domain.h" +#include "base/task/sequence_manager/test/mock_time_message_pump.h" #include "base/task/sequence_manager/test/sequence_manager_for_test.h" #include "base/task/sequence_manager/test/test_task_queue.h" #include "base/task/sequence_manager/test/test_task_time_observer.h" @@ -31,6 +33,7 @@ #include "base/task/sequence_manager/work_queue_sets.h" #include "base/test/bind_test_util.h" #include "base/test/mock_callback.h" +#include "base/test/null_task_runner.h" #include "base/test/simple_test_tick_clock.h" #include "base/test/test_mock_time_task_runner.h" #include "base/test/test_simple_task_runner.h" @@ -147,6 +150,67 @@ std::unique_ptr<SequenceManagerForTest> sequence_manager_; }; +class FixtureWithWithMockMessagePump : public Fixture { + public: + FixtureWithWithMockMessagePump() { + // A null clock triggers some assertions. + mock_clock_.Advance(TimeDelta::FromMilliseconds(1)); + + auto pump = std::make_unique<MockTimeMessagePump>(&mock_clock_); + pump_ = pump.get(); + sequence_manager_ = SequenceManagerForTest::Create( + std::make_unique<ThreadControllerWithMessagePumpImpl>(std::move(pump), + &mock_clock_), + SequenceManager::Settings{.randomised_sampling_enabled = false}); + sequence_manager_->SetDefaultTaskRunner(MakeRefCounted<NullTaskRunner>()); + } + + void AdvanceMockTickClock(TimeDelta delta) override { + mock_clock_.Advance(delta); + } + + const TickClock* mock_tick_clock() const override { return &mock_clock_; } + + TimeDelta NextPendingTaskDelay() const override { + return pump_->next_wake_up_time() - mock_clock_.NowTicks(); + } + + void FastForwardBy(TimeDelta delta) override { + pump_->SetAllowTimeToAutoAdvanceUntil(mock_clock_.NowTicks() + delta); + pump_->SetStopWhenMessagePumpIsIdle(true); + RunLoop().Run(); + pump_->SetStopWhenMessagePumpIsIdle(false); + } + + void FastForwardUntilNoTasksRemain() override { + pump_->SetAllowTimeToAutoAdvanceUntil(TimeTicks::Max()); + pump_->SetStopWhenMessagePumpIsIdle(true); + RunLoop().Run(); + pump_->SetStopWhenMessagePumpIsIdle(false); + pump_->SetAllowTimeToAutoAdvanceUntil(mock_clock_.NowTicks()); + } + + void RunDoWorkOnce() override { + pump_->SetQuitAfterDoSomeWork(true); + RunLoop().Run(); + pump_->SetQuitAfterDoSomeWork(false); + } + + SequenceManagerForTest* sequence_manager() const override { + return sequence_manager_.get(); + } + + void DestroySequenceManager() override { + pump_ = nullptr; + sequence_manager_.reset(); + }; + + private: + MockTimeMessagePump* pump_ = nullptr; + SimpleTestTickClock mock_clock_; + std::unique_ptr<SequenceManagerForTest> sequence_manager_; +}; + // SequenceManagerImpl uses TestMockTimeTaskRunner which controls // both task execution and mock clock. // TODO(kraynov): Make this class to support all TestTypes. @@ -160,6 +224,9 @@ case TestType::kUseMockTaskRunner: fixture_ = std::make_unique<FixtureWithMockTaskRunner>(); break; + case TestType::kUseMessagePump: + fixture_ = std::make_unique<FixtureWithWithMockMessagePump>(); + break; default: DCHECK(false); } @@ -229,6 +296,19 @@ std::unique_ptr<Fixture> fixture_; }; +std::string GetTestNameSuffix(const testing::TestParamInfo<TestType>& info) { + switch (info.param) { + case TestType::kUseMockTaskRunner: + return "MockTaskRunner"; + case TestType::kUseMessagePump: + return "MessagePump"; + case TestType::kUseMessageLoop: + return "MessageLoop"; + case TestType::kCustom: + return "Custom"; + } +} + // TODO(carlscab): Remove once the classes below have been migrated to // SequenceManagerTest class SequenceManagerTestBase : public testing::TestWithParam<TestType> { @@ -312,44 +392,6 @@ }; // TODO(carlscab): Migrate to SequenceManagerTest and remove -class SequenceManagerTestWithMessagePump : public SequenceManagerTestBase { - protected: - void SetUp() override { SetUpWithMessagePump(); } - - void SetUpWithMessageLoop() { - message_loop_.reset(new MessageLoop()); - // A null clock triggers some assertions. - mock_clock_.Advance(TimeDelta::FromMilliseconds(1)); - start_time_ = mock_clock_.NowTicks(); - - manager_ = SequenceManagerForTest::Create( - message_loop_->GetMessageLoopBase(), ThreadTaskRunnerHandle::Get(), - &mock_clock_, - SequenceManager::Settings{.randomised_sampling_enabled = false}); - } - - void SetUpWithMessagePump() { - mock_clock_.Advance(TimeDelta::FromMilliseconds(1)); - start_time_ = mock_clock_.NowTicks(); - manager_ = SequenceManagerForTest::Create( - std::make_unique<ThreadControllerWithMessagePumpImpl>( - std::make_unique<MessagePumpDefault>(), &mock_clock_), - SequenceManager::Settings{.randomised_sampling_enabled = false}); - // ThreadControllerWithMessagePumpImpl doesn't provide - // a default task runner. - default_task_queue_ = manager_->CreateTaskQueueWithType<TestTaskQueue>( - TaskQueue::Spec("default")); - manager_->SetDefaultTaskRunner(default_task_queue_->task_runner()); - } - - const TickClock* GetTickClock() { return &mock_clock_; } - - scoped_refptr<TestTaskQueue> default_task_queue_; - std::unique_ptr<MessageLoop> message_loop_; - SimpleTestTickClock mock_clock_; -}; - -// TODO(carlscab): Migrate to SequenceManagerTest and remove class SequenceManagerTestWithCustomInitialization : public SequenceManagerTestWithMessageLoop { protected: @@ -357,19 +399,11 @@ }; INSTANTIATE_TEST_CASE_P(, - SequenceManagerTest, - testing::Values(TestType::kUseMockTaskRunner)); - -INSTANTIATE_TEST_CASE_P(, SequenceManagerTestWithMessageLoop, testing::Values(TestType::kUseMessageLoop, TestType::kUseMessagePump)); INSTANTIATE_TEST_CASE_P(, - SequenceManagerTestWithMessagePump, - testing::Values(TestType::kUseMessagePump)); - -INSTANTIATE_TEST_CASE_P(, SequenceManagerTestWithCustomInitialization, testing::Values(TestType::kCustom)); @@ -1262,16 +1296,38 @@ EXPECT_THAT(run_order, ElementsAre(3u, 2u, 1u)); } +namespace { +class RefCountedCallbackFactory { + public: + OnceCallback<void()> WrapCallback(OnceCallback<void()> cb) { + return BindOnce( + [](OnceCallback<void()> cb, WeakPtr<bool>) { std::move(cb).Run(); }, + std::move(cb), task_references_.GetWeakPtr()); + } + + bool HasReferences() const { return task_references_.HasWeakPtrs(); } + + private: + bool dummy_; + WeakPtrFactory<bool> task_references_{&dummy_}; +}; +} // namespace + TEST_P(SequenceManagerTest, NoTasksAfterShutdown) { auto queue = CreateTaskQueue(); + StrictMock<MockTask> task; + RefCountedCallbackFactory counter; - std::vector<EnqueueOrder> run_order; - queue->task_runner()->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order)); + EXPECT_CALL(task, Run).Times(0); + queue->task_runner()->PostTask(FROM_HERE, counter.WrapCallback(task.Get())); DestroySequenceManager(); - queue->task_runner()->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order)); + queue->task_runner()->PostTask(FROM_HERE, counter.WrapCallback(task.Get())); - RunLoop().RunUntilIdle(); - EXPECT_TRUE(run_order.empty()); + if (GetParam() != TestType::kUseMessagePump) { + RunLoop().RunUntilIdle(); + } + + EXPECT_FALSE(counter.HasReferences()); } void PostTaskToRunner(scoped_refptr<TestTaskQueue> runner, @@ -1539,12 +1595,14 @@ &lazy_now)); } -TEST_P(SequenceManagerTest, DeleteSequenceManagerInsideATask) { - auto queue = CreateTaskQueue(); +TEST(SequenceManagerWithTaskRunnerTest, DeleteSequenceManagerInsideATask) { + FixtureWithMockTaskRunner fixture; + auto queue = + fixture.sequence_manager()->CreateTaskQueue(TaskQueue::Spec("test")); - queue->task_runner()->PostTask( - FROM_HERE, - BindOnce(&SequenceManagerTest::DestroySequenceManager, Unretained(this))); + queue->task_runner()->PostTask(FROM_HERE, BindLambdaForTesting([&]() { + fixture.DestroySequenceManager(); + })); // This should not crash, assuming DoWork detects the SequenceManager has // been deleted. @@ -1964,13 +2022,13 @@ TimeDelta::FromMilliseconds(30)); domain_b->SetNowTicks(start_time_ticks + TimeDelta::FromMilliseconds(50)); - sequence_manager()->MaybeScheduleImmediateWork(FROM_HERE); + sequence_manager()->ScheduleWork(); RunLoop().RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(4u, 5u, 6u)); domain_a->SetNowTicks(start_time_ticks + TimeDelta::FromMilliseconds(50)); - sequence_manager()->MaybeScheduleImmediateWork(FROM_HERE); + sequence_manager()->ScheduleWork(); RunLoop().RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(4u, 5u, 6u, 1u, 2u, 3u)); @@ -2006,7 +2064,7 @@ TimeDelta::FromMilliseconds(40)); domain_a->SetNowTicks(start_time_ticks + TimeDelta::FromMilliseconds(20)); - sequence_manager()->MaybeScheduleImmediateWork(FROM_HERE); + sequence_manager()->ScheduleWork(); RunLoop().RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1u, 2u)); @@ -2016,7 +2074,7 @@ queue->SetTimeDomain(domain_b.get()); domain_b->SetNowTicks(start_time_ticks + TimeDelta::FromMilliseconds(50)); - sequence_manager()->MaybeScheduleImmediateWork(FROM_HERE); + sequence_manager()->ScheduleWork(); RunLoop().RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1u, 2u, 3u, 4u)); @@ -2125,7 +2183,9 @@ // Unless the immediate work queue is emptied. sequence_manager()->TakeTask(); + sequence_manager()->DidRunTask(); sequence_manager()->TakeTask(); + sequence_manager()->DidRunTask(); EXPECT_CALL(observer, OnQueueNextWakeUpChanged(queue.get(), _)); queue->task_runner()->PostTask(FROM_HERE, BindOnce(&NopTask)); sequence_manager()->ReloadEmptyWorkQueues(); @@ -2375,7 +2435,7 @@ FROM_HERE, BindOnce(&QuadraticTask::Run, Unretained(this)), delay_); task_runner_->PostDelayedTask( FROM_HERE, BindOnce(&QuadraticTask::Run, Unretained(this)), delay_); - fixture_->FastForwardBy(TimeDelta::FromMilliseconds(5)); + fixture_->AdvanceMockTickClock(TimeDelta::FromMilliseconds(5)); } int Count() const { return count_; } @@ -2408,7 +2468,7 @@ count_++; task_runner_->PostDelayedTask( FROM_HERE, BindOnce(&LinearTask::Run, Unretained(this)), delay_); - fixture_->FastForwardBy(TimeDelta::FromMilliseconds(5)); + fixture_->AdvanceMockTickClock(TimeDelta::FromMilliseconds(5)); } int Count() const { return count_; } @@ -3130,7 +3190,9 @@ std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = queue->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); - EXPECT_EQ(TimeDelta::Max(), NextPendingTaskDelay()); + EXPECT_EQ(GetParam() == TestType::kUseMessagePump ? TimeDelta::FromDays(1) + : TimeDelta::Max(), + NextPendingTaskDelay()); voter->SetQueueEnabled(true); EXPECT_EQ(TimeDelta::FromMilliseconds(1), NextPendingTaskDelay()); @@ -3161,7 +3223,9 @@ EXPECT_EQ(TimeDelta::FromMilliseconds(100), NextPendingTaskDelay()); voter2->SetQueueEnabled(false); - EXPECT_EQ(TimeDelta::Max(), NextPendingTaskDelay()); + EXPECT_EQ(GetParam() == TestType::kUseMessagePump ? TimeDelta::FromDays(1) + : TimeDelta::Max(), + NextPendingTaskDelay()); } TEST_P(SequenceManagerTest, GetNextScheduledWakeUp) { @@ -3417,7 +3481,9 @@ // thread. DestroySequenceManager(); - FastForwardUntilNoTasksRemain(); + if (GetParam() != TestType::kUseMessagePump) { + FastForwardUntilNoTasksRemain(); + } EXPECT_THAT(run_times, ElementsAre(kStartTime + TimeDelta::FromMilliseconds(100), @@ -3430,6 +3496,7 @@ std::vector<TimeTicks> run_times; scoped_refptr<TestTaskQueue> main_tq = CreateTaskQueue(); WeakPtr<TestTaskQueue> main_tq_weak_ptr = main_tq->GetWeakPtr(); + RefCountedCallbackFactory counter; EXPECT_EQ(1u, sequence_manager()->ActiveQueuesCount()); EXPECT_EQ(0u, sequence_manager()->QueuesToShutdownCount()); @@ -3437,7 +3504,9 @@ for (int i = 1; i <= 5; ++i) { main_tq->task_runner()->PostDelayedTask( - FROM_HERE, BindOnce(&RecordTimeTask, &run_times, mock_tick_clock()), + FROM_HERE, + counter.WrapCallback( + BindOnce(&RecordTimeTask, &run_times, mock_tick_clock())), TimeDelta::FromMilliseconds(i * 100)); } FastForwardBy(TimeDelta::FromMilliseconds(250)); @@ -3455,11 +3524,14 @@ // Ensure that all queues-to-gracefully-shutdown are properly unregistered. DestroySequenceManager(); - FastForwardUntilNoTasksRemain(); + if (GetParam() != TestType::kUseMessagePump) { + FastForwardUntilNoTasksRemain(); + } EXPECT_THAT(run_times, ElementsAre(kStartTime + TimeDelta::FromMilliseconds(100), kStartTime + TimeDelta::FromMilliseconds(200))); + EXPECT_FALSE(counter.HasReferences()); } TEST_P(SequenceManagerTestWithCustomInitialization, DefaultTaskRunnerSupport) { @@ -3990,7 +4062,7 @@ } // namespace -TEST_P(SequenceManagerTestWithMessagePump, DestructionObserverTest) { +TEST_P(SequenceManagerTest, DestructionObserverTest) { auto queue = CreateTaskQueue(); // Verify that the destruction observer gets called at the very end (after @@ -4001,7 +4073,7 @@ bool destruction_observer_called = false; SMDestructionObserver observer(&task_destroyed, &destruction_observer_called); - manager_->AddDestructionObserver(&observer); + sequence_manager()->AddDestructionObserver(&observer); queue->task_runner()->PostDelayedTask( FROM_HERE, BindOnce(&DestructionObserverProbe::Run, @@ -4009,7 +4081,7 @@ &task_destroyed, &destruction_observer_called)), kDelay); - manager_.reset(); + DestroySequenceManager(); EXPECT_TRUE(observer.task_destroyed_before_message_loop()); // The task should have been destroyed when we deleted the loop.
diff --git a/base/task/sequence_manager/task_queue.cc b/base/task/sequence_manager/task_queue.cc index ce72109..3886937 100644 --- a/base/task/sequence_manager/task_queue.cc +++ b/base/task/sequence_manager/task_queue.cc
@@ -7,6 +7,7 @@ #include <utility> #include "base/bind.h" +#include "base/memory/ptr_util.h" #include "base/task/sequence_manager/associated_thread_id.h" #include "base/task/sequence_manager/sequence_manager_impl.h" #include "base/task/sequence_manager/task_queue_impl.h" @@ -48,6 +49,69 @@ } // namespace +TaskQueue::QueueEnabledVoter::QueueEnabledVoter( + scoped_refptr<TaskQueue> task_queue) + : task_queue_(std::move(task_queue)), enabled_(true) { + task_queue_->AddQueueEnabledVoter(enabled_); +} + +TaskQueue::QueueEnabledVoter::~QueueEnabledVoter() { + task_queue_->RemoveQueueEnabledVoter(enabled_); +} + +void TaskQueue::QueueEnabledVoter::SetQueueEnabled(bool enabled) { + if (enabled == enabled_) + return; + enabled_ = enabled; + task_queue_->OnQueueEnabledVoteChanged(enabled_); +} + +void TaskQueue::AddQueueEnabledVoter(bool voter_is_enabled) { + DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker); + ++voter_count_; + if (voter_is_enabled) + ++enabled_voter_count_; +} + +void TaskQueue::RemoveQueueEnabledVoter(bool voter_is_enabled) { + DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker); + if (!impl_) + return; + + bool was_enabled = AreAllQueueEnabledVotersEnabled(); + if (voter_is_enabled) { + --enabled_voter_count_; + DCHECK_GE(enabled_voter_count_, 0); + } + + --voter_count_; + DCHECK_GE(voter_count_, 0); + + bool is_enabled = AreAllQueueEnabledVotersEnabled(); + if (was_enabled != is_enabled) + impl_->SetQueueEnabled(is_enabled); +} + +bool TaskQueue::AreAllQueueEnabledVotersEnabled() const { + return enabled_voter_count_ == voter_count_; +} + +void TaskQueue::OnQueueEnabledVoteChanged(bool enabled) { + DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker); + bool was_enabled = AreAllQueueEnabledVotersEnabled(); + if (enabled) { + ++enabled_voter_count_; + DCHECK_LE(enabled_voter_count_, voter_count_); + } else { + --enabled_voter_count_; + DCHECK_GE(enabled_voter_count_, 0); + } + + bool is_enabled = AreAllQueueEnabledVotersEnabled(); + if (was_enabled != is_enabled) + impl_->SetQueueEnabled(is_enabled); +} + TaskQueue::TaskQueue(std::unique_ptr<internal::TaskQueueImpl> impl, const TaskQueue::Spec& spec) : impl_(std::move(impl)), @@ -118,7 +182,7 @@ DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker); if (!impl_) return nullptr; - return impl_->CreateQueueEnabledVoter(this); + return WrapUnique(new QueueEnabledVoter(this)); } bool TaskQueue::IsQueueEnabled() const {
diff --git a/base/task/sequence_manager/task_queue.h b/base/task/sequence_manager/task_queue.h index 1b661c12..f046f4d 100644 --- a/base/task/sequence_manager/task_queue.h +++ b/base/task/sequence_manager/task_queue.h
@@ -192,20 +192,26 @@ // An interface that lets the owner vote on whether or not the associated // TaskQueue should be enabled. - class QueueEnabledVoter { + class BASE_EXPORT QueueEnabledVoter { public: - QueueEnabledVoter() = default; - virtual ~QueueEnabledVoter() = default; + ~QueueEnabledVoter(); + + QueueEnabledVoter(const QueueEnabledVoter&) = delete; + const QueueEnabledVoter& operator=(const QueueEnabledVoter&) = delete; // Votes to enable or disable the associated TaskQueue. The TaskQueue will // only be enabled if all the voters agree it should be enabled, or if there // are no voters. // NOTE this must be called on the thread the associated TaskQueue was // created on. - virtual void SetQueueEnabled(bool enabled) = 0; + void SetQueueEnabled(bool enabled); private: - DISALLOW_COPY_AND_ASSIGN(QueueEnabledVoter); + friend class TaskQueue; + explicit QueueEnabledVoter(scoped_refptr<TaskQueue> task_queue); + + scoped_refptr<TaskQueue> const task_queue_; + bool enabled_; }; // Returns an interface that allows the caller to vote on whether or not this @@ -326,6 +332,11 @@ friend class internal::SequenceManagerImpl; friend class internal::TaskQueueImpl; + void AddQueueEnabledVoter(bool voter_is_enabled); + void RemoveQueueEnabledVoter(bool voter_is_enabled); + bool AreAllQueueEnabledVotersEnabled() const; + void OnQueueEnabledVoteChanged(bool enabled); + bool IsOnMainThread() const; Optional<MoveableAutoLock> AcquireImplReadLockIfNeeded() const; @@ -349,6 +360,9 @@ scoped_refptr<internal::AssociatedThreadId> associated_thread_; scoped_refptr<SingleThreadTaskRunner> default_task_runner_; + int enabled_voter_count_ = 0; + int voter_count_ = 0; + DISALLOW_COPY_AND_ASSIGN(TaskQueue); };
diff --git a/base/task/sequence_manager/task_queue_impl.cc b/base/task/sequence_manager/task_queue_impl.cc index c33e1e8..d8ada23 100644 --- a/base/task/sequence_manager/task_queue_impl.cc +++ b/base/task/sequence_manager/task_queue_impl.cc
@@ -131,8 +131,7 @@ immediate_work_queue(new WorkQueue(task_queue, "immediate", WorkQueue::QueueType::kImmediate)), - is_enabled_refcount(0), - voter_refcount(0), + is_enabled(true), blame_context(nullptr), is_enabled_for_test(true) {} @@ -491,9 +490,8 @@ // can be called elsewhere (e.g. tests and fast-path for posting // delayed tasks). Ensure that there is a DoWork posting. No-op inside // existing DoWork due to DoWork deduplication. - if (IsQueueEnabled() || !main_thread_only().current_fence) { - sequence_manager_->MaybeScheduleImmediateWork(FROM_HERE); - } + if (IsQueueEnabled() || !main_thread_only().current_fence) + sequence_manager_->ScheduleWork(); } UpdateDelayedWakeUp(lazy_now); @@ -697,7 +695,7 @@ } if (IsQueueEnabled() && task_unblocked) - sequence_manager_->MaybeScheduleImmediateWork(FROM_HERE); + sequence_manager_->ScheduleWork(); } void TaskQueueImpl::InsertFenceAt(TimeTicks time) { @@ -727,7 +725,7 @@ } if (IsQueueEnabled() && task_unblocked) - sequence_manager_->MaybeScheduleImmediateWork(FROM_HERE); + sequence_manager_->ScheduleWork(); } bool TaskQueueImpl::BlockedByFence() const { @@ -794,64 +792,15 @@ state->EndDictionary(); } -TaskQueueImpl::QueueEnabledVoterImpl::QueueEnabledVoterImpl( - scoped_refptr<TaskQueue> task_queue) - : task_queue_(task_queue), enabled_(true) {} - -TaskQueueImpl::QueueEnabledVoterImpl::~QueueEnabledVoterImpl() { - if (task_queue_->GetTaskQueueImpl()) - task_queue_->GetTaskQueueImpl()->RemoveQueueEnabledVoter(this); -} - -void TaskQueueImpl::QueueEnabledVoterImpl::SetQueueEnabled(bool enabled) { - if (enabled_ == enabled) - return; - - task_queue_->GetTaskQueueImpl()->OnQueueEnabledVoteChanged(enabled); - enabled_ = enabled; -} - -void TaskQueueImpl::RemoveQueueEnabledVoter( - const QueueEnabledVoterImpl* voter) { - // Bail out if we're being called from TaskQueueImpl::UnregisterTaskQueue. - if (!main_thread_only().time_domain) - return; - - bool was_enabled = IsQueueEnabled(); - if (voter->enabled_) { - main_thread_only().is_enabled_refcount--; - DCHECK_GE(main_thread_only().is_enabled_refcount, 0); - } - - main_thread_only().voter_refcount--; - DCHECK_GE(main_thread_only().voter_refcount, 0); - - bool is_enabled = IsQueueEnabled(); - if (was_enabled != is_enabled) - EnableOrDisableWithSelector(is_enabled); -} - bool TaskQueueImpl::IsQueueEnabled() const { - // By default is_enabled_refcount and voter_refcount both equal zero. - return (main_thread_only().is_enabled_refcount == - main_thread_only().voter_refcount) && - main_thread_only().is_enabled_for_test; + return main_thread_only().is_enabled; } -void TaskQueueImpl::OnQueueEnabledVoteChanged(bool enabled) { - bool was_enabled = IsQueueEnabled(); - if (enabled) { - main_thread_only().is_enabled_refcount++; - DCHECK_LE(main_thread_only().is_enabled_refcount, - main_thread_only().voter_refcount); - } else { - main_thread_only().is_enabled_refcount--; - DCHECK_GE(main_thread_only().is_enabled_refcount, 0); +void TaskQueueImpl::SetQueueEnabled(bool enabled) { + if (main_thread_only().is_enabled != enabled) { + main_thread_only().is_enabled = enabled; + EnableOrDisableWithSelector(enabled); } - - bool is_enabled = IsQueueEnabled(); - if (was_enabled != is_enabled) - EnableOrDisableWithSelector(is_enabled); } void TaskQueueImpl::EnableOrDisableWithSelector(bool enable) { @@ -877,14 +826,6 @@ } } -std::unique_ptr<TaskQueue::QueueEnabledVoter> -TaskQueueImpl::CreateQueueEnabledVoter(scoped_refptr<TaskQueue> task_queue) { - DCHECK_EQ(task_queue->GetTaskQueueImpl(), this); - main_thread_only().voter_refcount++; - main_thread_only().is_enabled_refcount++; - return std::make_unique<QueueEnabledVoterImpl>(task_queue); -} - void TaskQueueImpl::ReclaimMemory(TimeTicks now) { if (main_thread_only().delayed_incoming_queue.empty()) return; @@ -1015,11 +956,6 @@ return sequence_manager_->GetWeakPtr(); } -void TaskQueueImpl::SetQueueEnabledForTest(bool enabled) { - main_thread_only().is_enabled_for_test = enabled; - EnableOrDisableWithSelector(IsQueueEnabled()); -} - void TaskQueueImpl::ActivateDelayedFenceIfNeeded(TimeTicks now) { if (!main_thread_only().delayed_fence) return;
diff --git a/base/task/sequence_manager/task_queue_impl.h b/base/task/sequence_manager/task_queue_impl.h index fa16a45b..20c0fb54 100644 --- a/base/task/sequence_manager/task_queue_impl.h +++ b/base/task/sequence_manager/task_queue_impl.h
@@ -104,9 +104,8 @@ // TaskQueue implementation. const char* GetName() const; - std::unique_ptr<TaskQueue::QueueEnabledVoter> CreateQueueEnabledVoter( - scoped_refptr<TaskQueue> owning_task_queue); bool IsQueueEnabled() const; + void SetQueueEnabled(bool enabled); bool IsEmpty() const; size_t GetNumberOfPendingTasks() const; bool HasTaskToRunImmediately() const; @@ -198,25 +197,6 @@ void PushImmediateIncomingTaskForTest(Task&& task); - class QueueEnabledVoterImpl : public TaskQueue::QueueEnabledVoter { - public: - explicit QueueEnabledVoterImpl(scoped_refptr<TaskQueue> task_queue); - ~QueueEnabledVoterImpl() override; - - // QueueEnabledVoter implementation. - void SetQueueEnabled(bool enabled) override; - - TaskQueueImpl* GetTaskQueueForTest() const { - return task_queue_->GetTaskQueueImpl(); - } - - private: - friend class TaskQueueImpl; - - scoped_refptr<TaskQueue> task_queue_; - bool enabled_; - }; - // Iterates over |delayed_incoming_queue| removing canceled tasks. In // addition MaybeShrinkQueue is called on all internal queues. void ReclaimMemory(TimeTicks now); @@ -246,10 +226,6 @@ // affect this. bool HasTasks() const; - // Disables queue for testing purposes, when a QueueEnabledVoter can't be - // constructed due to not having TaskQueue. - void SetQueueEnabledForTest(bool enabled); - protected: void SetDelayedWakeUpForTesting(Optional<DelayedWakeUp> wake_up); @@ -378,8 +354,7 @@ DelayedIncomingQueue delayed_incoming_queue; ObserverList<MessageLoop::TaskObserver>::Unchecked task_observers; base::internal::HeapHandle heap_handle; - int is_enabled_refcount; - int voter_refcount; + bool is_enabled; trace_event::BlameContext* blame_context; // Not owned. EnqueueOrder current_fence; Optional<TimeTicks> delayed_fence; @@ -432,8 +407,6 @@ TimeTicks now, trace_event::TracedValue* state); - void RemoveQueueEnabledVoter(const QueueEnabledVoterImpl* voter); - void OnQueueEnabledVoteChanged(bool enabled); void EnableOrDisableWithSelector(bool enable); // Schedules delayed work on time domain and calls the observer.
diff --git a/base/task/sequence_manager/task_queue_selector_unittest.cc b/base/task/sequence_manager/task_queue_selector_unittest.cc index 46da3a9..0cd86e3 100644 --- a/base/task/sequence_manager/task_queue_selector_unittest.cc +++ b/base/task/sequence_manager/task_queue_selector_unittest.cc
@@ -204,12 +204,12 @@ } TEST_F(TaskQueueSelectorTest, TestObserverWithEnabledQueue) { - task_queues_[1]->SetQueueEnabledForTest(false); + task_queues_[1]->SetQueueEnabled(false); selector_.DisableQueue(task_queues_[1].get()); MockObserver mock_observer; selector_.SetTaskQueueSelectorObserver(&mock_observer); EXPECT_CALL(mock_observer, OnTaskQueueEnabled(_)).Times(1); - task_queues_[1]->SetQueueEnabledForTest(true); + task_queues_[1]->SetQueueEnabled(true); selector_.EnableQueue(task_queues_[1].get()); } @@ -229,9 +229,9 @@ size_t queue_order[] = {0, 1, 2, 3, 4}; PushTasks(queue_order, 5); - task_queues_[2]->SetQueueEnabledForTest(false); + task_queues_[2]->SetQueueEnabled(false); selector_.DisableQueue(task_queues_[2].get()); - task_queues_[4]->SetQueueEnabledForTest(false); + task_queues_[4]->SetQueueEnabled(false); selector_.DisableQueue(task_queues_[4].get()); // Disabling a queue should not affect its priority. EXPECT_EQ(TaskQueue::kNormalPriority, task_queues_[2]->GetQueuePriority()); @@ -239,12 +239,12 @@ EXPECT_THAT(PopTasksAndReturnQueueIndices(), ElementsAre(0, 1, 3)); EXPECT_CALL(mock_observer, OnTaskQueueEnabled(_)).Times(2); - task_queues_[2]->SetQueueEnabledForTest(true); + task_queues_[2]->SetQueueEnabled(true); selector_.EnableQueue(task_queues_[2].get()); selector_.SetQueuePriority(task_queues_[2].get(), TaskQueue::kBestEffortPriority); EXPECT_THAT(PopTasksAndReturnQueueIndices(), ElementsAre(2)); - task_queues_[4]->SetQueueEnabledForTest(true); + task_queues_[4]->SetQueueEnabled(true); selector_.EnableQueue(task_queues_[4].get()); EXPECT_THAT(PopTasksAndReturnQueueIndices(), ElementsAre(4)); } @@ -253,7 +253,7 @@ EXPECT_TRUE(task_queues_[2]->delayed_work_queue()->Empty()); EXPECT_TRUE(task_queues_[2]->immediate_work_queue()->Empty()); - task_queues_[2]->SetQueueEnabledForTest(false); + task_queues_[2]->SetQueueEnabled(false); selector_.SetQueuePriority(task_queues_[2].get(), TaskQueue::kHighestPriority); @@ -262,7 +262,7 @@ EXPECT_TRUE(task_queues_[2]->delayed_work_queue()->Empty()); EXPECT_FALSE(task_queues_[2]->immediate_work_queue()->Empty()); - task_queues_[2]->SetQueueEnabledForTest(true); + task_queues_[2]->SetQueueEnabled(true); EXPECT_EQ(TaskQueue::kHighestPriority, task_queues_[2]->GetQueuePriority()); EXPECT_THAT(PopTasksAndReturnQueueIndices(), ElementsAre(2, 0, 1, 3, 4)); @@ -274,14 +274,14 @@ // Test only disabled queues. size_t queue_order[] = {0}; PushTasks(queue_order, 1); - task_queues_[0]->SetQueueEnabledForTest(false); + task_queues_[0]->SetQueueEnabled(false); selector_.DisableQueue(task_queues_[0].get()); EXPECT_EQ(nullptr, selector_.SelectWorkQueueToService()); // These tests are unusual since there's no TQM. To avoid a later DCHECK when // deleting the task queue, we re-enable the queue here so the selector // doesn't get out of sync. - task_queues_[0]->SetQueueEnabledForTest(true); + task_queues_[0]->SetQueueEnabled(true); selector_.EnableQueue(task_queues_[0].get()); } @@ -686,7 +686,7 @@ std::unique_ptr<TaskQueueImpl> task_queue(NewTaskQueueWithBlockReporting()); selector.AddQueue(task_queue.get()); - task_queue->SetQueueEnabledForTest(false); + task_queue->SetQueueEnabled(false); selector.DisableQueue(task_queue.get()); Task task(PostedTask(test_closure_, FROM_HERE), TimeTicks(), EnqueueOrder(), @@ -695,7 +695,7 @@ EXPECT_EQ(nullptr, selector.SelectWorkQueueToService()); - task_queue->SetQueueEnabledForTest(true); + task_queue->SetQueueEnabled(true); selector.EnableQueue(task_queue.get()); selector.RemoveQueue(task_queue.get()); task_queue->UnregisterTaskQueue(); @@ -711,8 +711,8 @@ selector.AddQueue(task_queue.get()); selector.AddQueue(task_queue2.get()); - task_queue->SetQueueEnabledForTest(false); - task_queue2->SetQueueEnabledForTest(false); + task_queue->SetQueueEnabled(false); + task_queue2->SetQueueEnabled(false); selector.DisableQueue(task_queue.get()); selector.DisableQueue(task_queue2.get()); @@ -731,14 +731,14 @@ EXPECT_CALL(mock_observer, OnTaskQueueEnabled(_)).Times(2); - task_queue->SetQueueEnabledForTest(true); + task_queue->SetQueueEnabled(true); selector.EnableQueue(task_queue.get()); selector.RemoveQueue(task_queue.get()); task_queue->UnregisterTaskQueue(); EXPECT_EQ(nullptr, selector.SelectWorkQueueToService()); - task_queue2->SetQueueEnabledForTest(true); + task_queue2->SetQueueEnabled(true); selector.EnableQueue(task_queue2.get()); selector.RemoveQueue(task_queue2.get()); task_queue2->UnregisterTaskQueue();
diff --git a/base/task/sequence_manager/test/mock_time_message_pump.cc b/base/task/sequence_manager/test/mock_time_message_pump.cc new file mode 100644 index 0000000..66b6f2cb --- /dev/null +++ b/base/task/sequence_manager/test/mock_time_message_pump.cc
@@ -0,0 +1,88 @@ +// 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. + +#include "base/task/sequence_manager/test/mock_time_message_pump.h" + +#include <algorithm> + +#include "base/auto_reset.h" +#include "base/test/simple_test_tick_clock.h" + +namespace base { +namespace sequence_manager { + +MockTimeMessagePump::MockTimeMessagePump(SimpleTestTickClock* clock) + : clock_(clock) {} + +MockTimeMessagePump::~MockTimeMessagePump() {} + +bool MockTimeMessagePump::MaybeAdvanceTime(TimeTicks target_time) { + auto now = clock_->NowTicks(); + + if (target_time <= now) + return true; + + TimeTicks next_now; + + if (!target_time.is_max()) { + next_now = std::min(allow_advance_until_, target_time); + } else if (allow_advance_until_ == TimeTicks::Max()) { + next_now = now; + } else { + next_now = allow_advance_until_; + } + + if (now < next_now) { + clock_->SetNowTicks(next_now); + return true; + } + return false; +} + +void MockTimeMessagePump::Run(Delegate* delegate) { + AutoReset<bool> auto_reset_keep_running(&keep_running_, true); + + for (;;) { + Delegate::NextWorkInfo info = delegate->DoSomeWork(); + + if (!keep_running_ || quit_after_do_some_work_) + break; + + if (info.is_immediate()) + continue; + + bool have_immediate_work = delegate->DoIdleWork(); + + if (!keep_running_) + break; + + if (have_immediate_work) + continue; + + if (MaybeAdvanceTime(info.delayed_run_time)) + continue; + + next_wake_up_time_ = info.delayed_run_time; + + if (stop_when_message_pump_is_idle_) + return; + + NOTREACHED() << "Pump would go to sleep. Probably not what you wanted, " + "consider rewriting your test."; + } +} + +void MockTimeMessagePump::Quit() { + keep_running_ = false; +} + +void MockTimeMessagePump::ScheduleWork() {} + +void MockTimeMessagePump::ScheduleDelayedWork( + const TimeTicks& delayed_work_time) { + next_wake_up_time_ = delayed_work_time; +} + +} // namespace sequence_manager +} // namespace base
diff --git a/base/task/sequence_manager/test/mock_time_message_pump.h b/base/task/sequence_manager/test/mock_time_message_pump.h new file mode 100644 index 0000000..223dfa5 --- /dev/null +++ b/base/task/sequence_manager/test/mock_time_message_pump.h
@@ -0,0 +1,86 @@ +// 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. + +#ifndef BASE_TASK_SEQUENCE_MANAGER_TEST_MOCK_TIME_MESSAGE_PUMP_H_ +#define BASE_TASK_SEQUENCE_MANAGER_TEST_MOCK_TIME_MESSAGE_PUMP_H_ + +#include "base/callback.h" +#include "base/message_loop/message_pump.h" +#include "base/optional.h" +#include "base/synchronization/waitable_event.h" +#include "base/time/time.h" + +namespace base { + +class SimpleTestTickClock; + +namespace sequence_manager { + +// MessagePump implementation that uses a SimpleTestTickClock to keep track of +// time and will advance it as needed to keep running tasks. +// +// This pump will actually check fail if it ever has to go to sleep as this +// would indicate that the unit test might block indefinitely. +// TODO(carlscab): In the future we could consider sleeping if there is no +// outstanding |delayed_work_time_|, because we could be woken up by concurrent +// ScheduleWork() calls. +class MockTimeMessagePump : public MessagePump { + public: + explicit MockTimeMessagePump(SimpleTestTickClock* clock); + ~MockTimeMessagePump() override; + + // MessagePump implementation + void Run(Delegate* delegate) override; + void Quit() override; + void ScheduleWork() override; + void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override; + + // Returns the time at which the pump would have to wake up to be perform + // work. + TimeTicks next_wake_up_time() const { return next_wake_up_time_; } + + // Quits after the first call to Delegate::DoSomeWork(). Useful + // for tests that want to make sure certain things happen during a DoSomeWork + // call. + void SetQuitAfterDoSomeWork(bool quit_after_do_some_work) { + quit_after_do_some_work_ = quit_after_do_some_work; + } + + // Allows this instance to advance the SimpleTestTickClock up to but not over + // |advance_until| when idle (i.e. when a regular pump would go to sleep). + // The clock will allways be advanced to |advance_until|, even if there are no + // tasks requiring it (i.e. delayed tasks to be run after + // |advance_until|) except for a value of TimeTicks::Max() which will advance + // the clock as long as there is pending delayed work. + void SetAllowTimeToAutoAdvanceUntil(TimeTicks advance_until) { + allow_advance_until_ = advance_until; + } + + // Quit when this pump's Delegate is out of work (i.e. when a regular pump + // would go to sleep) and we are not allowed to advance the clock anymore. + void SetStopWhenMessagePumpIsIdle(bool stop_when_message_pump_is_idle) { + stop_when_message_pump_is_idle_ = stop_when_message_pump_is_idle; + } + + private: + // Returns true if the clock was indeed advanced and thus we should attempt + // another iteration of the DoSomeWork-DoIdleWork-loop. + bool MaybeAdvanceTime(TimeTicks target_time); + + SimpleTestTickClock* const clock_; + // This flag is set to false when Run should return. + bool keep_running_ = true; + + bool stop_when_message_pump_is_idle_ = false; + bool quit_after_do_some_work_ = false; + + TimeTicks next_wake_up_time_{TimeTicks::Max()}; + + TimeTicks allow_advance_until_ = TimeTicks::Min(); +}; + +} // namespace sequence_manager +} // namespace base + +#endif // BASE_TASK_SEQUENCE_MANAGER_TEST_MOCK_TIME_MESSAGE_PUMP_H_
diff --git a/base/task/sequence_manager/test/mock_time_message_pump_unittest.cc b/base/task/sequence_manager/test/mock_time_message_pump_unittest.cc new file mode 100644 index 0000000..dfa6e408 --- /dev/null +++ b/base/task/sequence_manager/test/mock_time_message_pump_unittest.cc
@@ -0,0 +1,185 @@ +// 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. + +#include "base/task/sequence_manager/test/mock_time_message_pump.h" + +#include "base/message_loop/message_pump.h" +#include "base/test/simple_test_tick_clock.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace base { +namespace sequence_manager { +namespace { + +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Invoke; +using ::testing::Return; +using ::testing::SetArgPointee; +using ::testing::StrictMock; + +class MockMessagePumpDelegate : public MessagePump::Delegate { + public: + MOCK_METHOD0(BeforeDoInternalWork, void()); + MOCK_METHOD0(DoWork, bool()); + MOCK_METHOD1(DoDelayedWork, bool(TimeTicks*)); + MOCK_METHOD0(DoSomeWork, NextWorkInfo()); + MOCK_METHOD0(DoIdleWork, bool()); +}; + +MessagePump::Delegate::NextWorkInfo NextWorkInfo(TimeTicks delayed_run_time) { + MessagePump::Delegate::NextWorkInfo info; + info.delayed_run_time = delayed_run_time; + return info; +} + +TEST(MockMessagePumpTest, KeepsRunningIfNotAllowedToAdvanceTime) { + SimpleTestTickClock mock_clock; + mock_clock.Advance(TimeDelta::FromHours(42)); + StrictMock<MockMessagePumpDelegate> delegate; + MockTimeMessagePump pump(&mock_clock); + const auto kStartTime = mock_clock.NowTicks(); + const auto kFutureTime = kStartTime + TimeDelta::FromSeconds(42); + + EXPECT_CALL(delegate, DoSomeWork) + .WillOnce(Return(NextWorkInfo(TimeTicks()))) + .WillOnce(Return(NextWorkInfo(TimeTicks()))) + .WillOnce(Return(NextWorkInfo(kFutureTime))); + EXPECT_CALL(delegate, DoIdleWork).WillOnce(Invoke([&] { + pump.Quit(); + return false; + })); + + pump.Run(&delegate); + + EXPECT_THAT(mock_clock.NowTicks(), Eq(kStartTime)); +} + +TEST(MockMessagePumpTest, AdvancesTimeAsAllowed) { + SimpleTestTickClock mock_clock; + mock_clock.Advance(TimeDelta::FromHours(42)); + StrictMock<MockMessagePumpDelegate> delegate; + MockTimeMessagePump pump(&mock_clock); + const auto kStartTime = mock_clock.NowTicks(); + const auto kEndTime = kStartTime + TimeDelta::FromSeconds(2); + + pump.SetAllowTimeToAutoAdvanceUntil(kEndTime); + pump.SetStopWhenMessagePumpIsIdle(true); + EXPECT_CALL(delegate, DoSomeWork).Times(3).WillRepeatedly(Invoke([&]() { + return NextWorkInfo(mock_clock.NowTicks() + TimeDelta::FromSeconds(1)); + })); + EXPECT_CALL(delegate, DoIdleWork).Times(3).WillRepeatedly(Return(false)); + + pump.Run(&delegate); + + EXPECT_THAT(mock_clock.NowTicks(), Eq(kEndTime)); +} + +TEST(MockMessagePumpTest, CanQuitAfterMaybeDoWork) { + SimpleTestTickClock mock_clock; + mock_clock.Advance(TimeDelta::FromHours(42)); + StrictMock<MockMessagePumpDelegate> delegate; + MockTimeMessagePump pump(&mock_clock); + + pump.SetQuitAfterDoSomeWork(true); + EXPECT_CALL(delegate, DoSomeWork).WillOnce(Return(NextWorkInfo(TimeTicks()))); + + pump.Run(&delegate); +} + +TEST(MockMessagePumpTest, AdvancesUntilAllowedTime) { + SimpleTestTickClock mock_clock; + mock_clock.Advance(TimeDelta::FromHours(42)); + StrictMock<MockMessagePumpDelegate> delegate; + MockTimeMessagePump pump(&mock_clock); + const auto kStartTime = mock_clock.NowTicks(); + const auto kEndTime = kStartTime + TimeDelta::FromSeconds(2); + const auto kNextDelayedWorkTime = kEndTime + TimeDelta::FromSeconds(2); + + pump.SetAllowTimeToAutoAdvanceUntil(kEndTime); + pump.SetStopWhenMessagePumpIsIdle(true); + EXPECT_CALL(delegate, DoSomeWork) + .Times(2) + .WillRepeatedly(Return(NextWorkInfo(kNextDelayedWorkTime))); + EXPECT_CALL(delegate, DoIdleWork).Times(2).WillRepeatedly(Return(false)); + + pump.Run(&delegate); + + EXPECT_THAT(mock_clock.NowTicks(), Eq(kEndTime)); +} + +TEST(MockMessagePumpTest, StoresNextWakeUpTime) { + SimpleTestTickClock mock_clock; + StrictMock<MockMessagePumpDelegate> delegate; + MockTimeMessagePump pump(&mock_clock); + const auto kStartTime = mock_clock.NowTicks(); + const auto kEndTime = kStartTime; + const auto kNextDelayedWorkTime = kEndTime + TimeDelta::FromSeconds(2); + + pump.SetAllowTimeToAutoAdvanceUntil(kEndTime); + pump.SetStopWhenMessagePumpIsIdle(true); + EXPECT_CALL(delegate, DoSomeWork) + .WillOnce(Return(NextWorkInfo(kNextDelayedWorkTime))); + EXPECT_CALL(delegate, DoIdleWork).WillOnce(Return(false)); + + pump.Run(&delegate); + + EXPECT_THAT(pump.next_wake_up_time(), Eq(kNextDelayedWorkTime)); +} + +TEST(MockMessagePumpTest, StoresNextWakeUpTimeInScheduleDelayedWork) { + SimpleTestTickClock mock_clock; + StrictMock<MockMessagePumpDelegate> delegate; + MockTimeMessagePump pump(&mock_clock); + const auto kNextDelayedWorkTime = + mock_clock.NowTicks() + TimeDelta::FromSeconds(2); + + pump.ScheduleDelayedWork(kNextDelayedWorkTime); + + EXPECT_THAT(pump.next_wake_up_time(), Eq(kNextDelayedWorkTime)); +} + +TEST(MockMessagePumpTest, NextDelayedWorkTimeInThePastKeepsRunning) { + SimpleTestTickClock mock_clock; + mock_clock.Advance(TimeDelta::FromHours(42)); + StrictMock<MockMessagePumpDelegate> delegate; + MockTimeMessagePump pump(&mock_clock); + const auto kNextDelayedWorkTime = mock_clock.NowTicks(); + mock_clock.Advance(TimeDelta::FromHours(2)); + + pump.SetStopWhenMessagePumpIsIdle(true); + + EXPECT_CALL(delegate, DoSomeWork) + .WillOnce(Return(NextWorkInfo(kNextDelayedWorkTime))) + .WillOnce(Return(NextWorkInfo(kNextDelayedWorkTime))) + .WillOnce(Return(NextWorkInfo(TimeTicks::Max()))); + EXPECT_CALL(delegate, DoIdleWork).WillRepeatedly(Return(false)); + + pump.Run(&delegate); +} + +TEST(MockMessagePumpTest, + AdvancesUntilAllowedTimeWhenNextDelayedWorkTimeIsMax) { + SimpleTestTickClock mock_clock; + mock_clock.Advance(TimeDelta::FromHours(42)); + StrictMock<MockMessagePumpDelegate> delegate; + MockTimeMessagePump pump(&mock_clock); + const auto kAdvanceUntil = + mock_clock.NowTicks() + TimeDelta::FromSeconds(123); + + pump.SetStopWhenMessagePumpIsIdle(true); + pump.SetAllowTimeToAutoAdvanceUntil(kAdvanceUntil); + EXPECT_CALL(delegate, DoSomeWork) + .WillRepeatedly(Return(NextWorkInfo(TimeTicks::Max()))); + EXPECT_CALL(delegate, DoIdleWork).WillRepeatedly(Return(false)); + + pump.Run(&delegate); + + EXPECT_THAT(mock_clock.NowTicks(), Eq(kAdvanceUntil)); +} + +} // namespace +} // namespace sequence_manager +} // namespace base
diff --git a/base/task/sequence_manager/thread_controller_with_message_pump_impl.cc b/base/task/sequence_manager/thread_controller_with_message_pump_impl.cc index f8e2aef3..2082ad89 100644 --- a/base/task/sequence_manager/thread_controller_with_message_pump_impl.cc +++ b/base/task/sequence_manager/thread_controller_with_message_pump_impl.cc
@@ -82,6 +82,7 @@ std::unique_ptr<MessagePump> message_pump) { associated_thread_->BindToCurrentThread(); pump_ = std::move(message_pump); + work_id_provider_ = WorkIdProvider::GetForCurrentThread(); RunLoop::RegisterDelegateForCurrentThread(this); scoped_set_sequence_local_storage_map_for_current_thread_ = std::make_unique< base::internal::ScopedSetSequenceLocalStorageMapForCurrentThread>( @@ -216,6 +217,10 @@ return associated_thread_; } +void ThreadControllerWithMessagePumpImpl::BeforeDoInternalWork() { + work_id_provider_->IncrementWorkId(); +} + MessagePump::Delegate::NextWorkInfo ThreadControllerWithMessagePumpImpl::DoSomeWork() { main_thread_only().immediate_do_work_posted = false; @@ -327,6 +332,7 @@ // Execute the task and assume the worst: it is probably not reentrant. main_thread_only().task_execution_allowed = false; + work_id_provider_->IncrementWorkId(); TRACE_TASK_EXECUTION("ThreadController::Task", *task); // Trace-parsing tools (Lighthouse, etc) consume this event to determine // long tasks. See https://crbug.com/874982 @@ -360,6 +366,7 @@ } bool ThreadControllerWithMessagePumpImpl::DoIdleWork() { + work_id_provider_->IncrementWorkId(); #if defined(OS_WIN) bool need_high_res_mode = main_thread_only().task_source->HasPendingHighResolutionTasks();
diff --git a/base/task/sequence_manager/thread_controller_with_message_pump_impl.h b/base/task/sequence_manager/thread_controller_with_message_pump_impl.h index 1d1f26b..faf151f 100644 --- a/base/task/sequence_manager/thread_controller_with_message_pump_impl.h +++ b/base/task/sequence_manager/thread_controller_with_message_pump_impl.h
@@ -9,6 +9,7 @@ #include "base/debug/task_annotator.h" #include "base/message_loop/message_pump.h" +#include "base/message_loop/work_id_provider.h" #include "base/run_loop.h" #include "base/task/common/operations_controller.h" #include "base/task/sequence_manager/associated_thread_id.h" @@ -74,6 +75,7 @@ explicit ThreadControllerWithMessagePumpImpl(const TickClock* time_source); // MessagePump::Delegate implementation. + void BeforeDoInternalWork() override; MessagePump::Delegate::NextWorkInfo DoSomeWork() override; bool DoWork() override; bool DoDelayedWork(TimeTicks* next_run_time) override; @@ -166,6 +168,11 @@ debug::TaskAnnotator task_annotator_; const TickClock* time_source_; // Not owned. + // Non-null provider of id state for identifying distinct work items executed + // by the message loop (task, event, etc.). Cached on the class to avoid TLS + // lookups on task execution. + WorkIdProvider* work_id_provider_ = nullptr; + // Required to register the current thread as a sequence. base::internal::SequenceLocalStorageMap sequence_local_storage_map_; std::unique_ptr<
diff --git a/base/task/sequence_manager/time_domain.cc b/base/task/sequence_manager/time_domain.cc index 4874b6f..69d35c2 100644 --- a/base/task/sequence_manager/time_domain.cc +++ b/base/task/sequence_manager/time_domain.cc
@@ -43,7 +43,7 @@ } void TimeDomain::RequestDoWork() { - sequence_manager_->MaybeScheduleImmediateWork(FROM_HERE); + sequence_manager_->ScheduleWork(); } void TimeDomain::UnregisterQueue(internal::TaskQueueImpl* queue) {
diff --git a/base/task/task_features.cc b/base/task/task_features.cc index cf56afb..632d7021 100644 --- a/base/task/task_features.cc +++ b/base/task/task_features.cc
@@ -11,11 +11,8 @@ const Feature kAllTasksUserBlocking{"AllTasksUserBlocking", FEATURE_DISABLED_BY_DEFAULT}; -// This experiment no longer has any impact, but remains enabled by default -// because script streamer depends on it. -// TODO(etiennep): Cleanup this experiment. const Feature kMergeBlockingNonBlockingPools = { - "MergeBlockingNonBlockingPools", base::FEATURE_ENABLED_BY_DEFAULT}; + "MergeBlockingNonBlockingPools", base::FEATURE_DISABLED_BY_DEFAULT}; const Feature kNoDetachBelowInitialCapacity = { "NoDetachBelowInitialCapacity", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/base/task/task_scheduler/environment_config.h b/base/task/task_scheduler/environment_config.h index 5280cd7a..4ca8416 100644 --- a/base/task/task_scheduler/environment_config.h +++ b/base/task/task_scheduler/environment_config.h
@@ -14,18 +14,19 @@ namespace base { namespace internal { -// TODO(etiennep): This is now specific to -// SchedulerSingleThreadTaskRunnerManager, move it there. enum EnvironmentType { FOREGROUND = 0, FOREGROUND_BLOCKING, - BACKGROUND, + // Pools will only be created for the environment above on platforms that + // don't support SchedulerWorkers running with a background priority. + ENVIRONMENT_COUNT_WITHOUT_BACKGROUND_PRIORITY, + BACKGROUND = ENVIRONMENT_COUNT_WITHOUT_BACKGROUND_PRIORITY, BACKGROUND_BLOCKING, ENVIRONMENT_COUNT // Always last. }; // Order must match the EnvironmentType enum. -struct EnvironmentParams { +constexpr struct { // The threads and histograms of this environment will be labeled with // the task scheduler name concatenated to this. const char* name_suffix; @@ -33,9 +34,7 @@ // Preferred priority for threads in this environment; the actual thread // priority depends on shutdown state and platform capabilities. ThreadPriority priority_hint; -}; - -constexpr EnvironmentParams kEnvironmentParams[] = { +} kEnvironmentParams[] = { {"Foreground", base::ThreadPriority::NORMAL}, {"ForegroundBlocking", base::ThreadPriority::NORMAL}, {"Background", base::ThreadPriority::BACKGROUND},
diff --git a/base/task/task_scheduler/priority_queue.cc b/base/task/task_scheduler/priority_queue.cc index 7b31a31a5..7fa78e6 100644 --- a/base/task/task_scheduler/priority_queue.cc +++ b/base/task/task_scheduler/priority_queue.cc
@@ -8,6 +8,7 @@ #include "base/logging.h" #include "base/memory/ptr_util.h" +#include "base/stl_util.h" namespace base { namespace internal { @@ -92,6 +93,7 @@ void PriorityQueue::Push(scoped_refptr<Sequence> sequence, const SequenceSortKey& sequence_sort_key) { container_.insert(SequenceAndSortKey(std::move(sequence), sequence_sort_key)); + IncrementNumSequencesForPriority(sequence_sort_key.priority()); } const SequenceSortKey& PriorityQueue::PeekSortKey() const { @@ -102,12 +104,13 @@ scoped_refptr<Sequence> PriorityQueue::PopSequence() { DCHECK(!IsEmpty()); - // The const_cast on top() is okay since the SequenceAndSortKey is + // The const_cast on Min() is okay since the SequenceAndSortKey is // transactionally being popped from |container_| right after and taking its // Sequence does not alter its sort order. - scoped_refptr<Sequence> sequence = - const_cast<PriorityQueue::SequenceAndSortKey&>(container_.Min()) - .take_sequence(); + auto& sequence_and_sort_key = + const_cast<PriorityQueue::SequenceAndSortKey&>(container_.Min()); + DecrementNumSequencesForPriority(sequence_and_sort_key.sort_key().priority()); + scoped_refptr<Sequence> sequence = sequence_and_sort_key.take_sequence(); container_.Pop(); return sequence; } @@ -122,7 +125,10 @@ if (!heap_handle.IsValid()) return false; - DCHECK_EQ(container_.at(heap_handle).sequence(), sequence.get()); + const SequenceAndSortKey& sequence_and_sort_key = container_.at(heap_handle); + DCHECK_EQ(sequence_and_sort_key.sequence(), sequence.get()); + + DecrementNumSequencesForPriority(sequence_and_sort_key.sort_key().priority()); container_.erase(heap_handle); return true; } @@ -139,10 +145,16 @@ if (!heap_handle.IsValid()) return; - auto sort_key = sequence_and_transaction.transaction.GetSortKey(); + auto old_sort_key = container_.at(heap_handle).sort_key(); + auto new_sort_key = sequence_and_transaction.transaction.GetSortKey(); + + DecrementNumSequencesForPriority(old_sort_key.priority()); + IncrementNumSequencesForPriority(new_sort_key.priority()); + container_.ChangeKey( - heap_handle, SequenceAndSortKey( - std::move(sequence_and_transaction.sequence), sort_key)); + heap_handle, + SequenceAndSortKey(std::move(sequence_and_transaction.sequence), + new_sort_key)); } bool PriorityQueue::IsEmpty() const { @@ -158,5 +170,14 @@ is_flush_sequences_on_destroy_enabled_ = true; } +void PriorityQueue::DecrementNumSequencesForPriority(TaskPriority priority) { + DCHECK_GT(num_sequences_per_priority_[static_cast<int>(priority)], 0U); + --num_sequences_per_priority_[static_cast<int>(priority)]; +} + +void PriorityQueue::IncrementNumSequencesForPriority(TaskPriority priority) { + ++num_sequences_per_priority_[static_cast<int>(priority)]; +} + } // namespace internal } // namespace base
diff --git a/base/task/task_scheduler/priority_queue.h b/base/task/task_scheduler/priority_queue.h index da7e461..0571de69 100644 --- a/base/task/task_scheduler/priority_queue.h +++ b/base/task/task_scheduler/priority_queue.h
@@ -58,6 +58,11 @@ // Returns the number of Sequences in the PriorityQueue. size_t Size() const; + // Returns the number of Sequences with |priority|. + size_t GetNumSequencesWithPriority(TaskPriority priority) const { + return num_sequences_per_priority_[static_cast<int>(priority)]; + } + // Set the PriorityQueue to empty all its Sequences of Tasks when it is // destroyed; needed to prevent memory leaks caused by a reference cycle // (Sequence -> Task -> TaskRunner -> Sequence...) during test teardown. @@ -70,8 +75,14 @@ using ContainerType = IntrusiveHeap<SequenceAndSortKey>; + void DecrementNumSequencesForPriority(TaskPriority priority); + void IncrementNumSequencesForPriority(TaskPriority priority); + ContainerType container_; + size_t num_sequences_per_priority_[static_cast<int>(TaskPriority::HIGHEST) + + 1] = {}; + // Should only be enabled by EnableFlushSequencesOnDestroyForTesting(). bool is_flush_sequences_on_destroy_enabled_ = false;
diff --git a/base/task/task_scheduler/priority_queue_unittest.cc b/base/task/task_scheduler/priority_queue_unittest.cc index 241e42f4..e34d090 100644 --- a/base/task/task_scheduler/priority_queue_unittest.cc +++ b/base/task/task_scheduler/priority_queue_unittest.cc
@@ -33,6 +33,17 @@ class TaskSchedulerPriorityQueueWithSequencesTest : public testing::Test { protected: + void ExpectNumSequences(size_t num_best_effort, + size_t num_user_visible, + size_t num_user_blocking) { + EXPECT_EQ(pq.GetNumSequencesWithPriority(TaskPriority::BEST_EFFORT), + num_best_effort); + EXPECT_EQ(pq.GetNumSequencesWithPriority(TaskPriority::USER_VISIBLE), + num_user_visible); + EXPECT_EQ(pq.GetNumSequencesWithPriority(TaskPriority::USER_BLOCKING), + num_user_blocking); + } + scoped_refptr<Sequence> sequence_a = MakeSequenceWithTraitsAndTask(TaskTraits(TaskPriority::USER_VISIBLE)); SequenceSortKey sort_key_a = sequence_a->BeginTransaction().GetSortKey(); @@ -56,45 +67,54 @@ TEST_F(TaskSchedulerPriorityQueueWithSequencesTest, PushPopPeek) { EXPECT_TRUE(pq.IsEmpty()); + ExpectNumSequences(0U, 0U, 0U); // Push |sequence_a| in the PriorityQueue. It becomes the sequence with the // highest priority. pq.Push(sequence_a, sort_key_a); EXPECT_EQ(sort_key_a, pq.PeekSortKey()); + ExpectNumSequences(0U, 1U, 0U); // Push |sequence_b| in the PriorityQueue. It becomes the sequence with the // highest priority. pq.Push(sequence_b, sort_key_b); EXPECT_EQ(sort_key_b, pq.PeekSortKey()); + ExpectNumSequences(0U, 1U, 1U); // Push |sequence_c| in the PriorityQueue. |sequence_b| is still the sequence // with the highest priority. pq.Push(sequence_c, sort_key_c); EXPECT_EQ(sort_key_b, pq.PeekSortKey()); + ExpectNumSequences(0U, 1U, 2U); // Push |sequence_d| in the PriorityQueue. |sequence_b| is still the sequence // with the highest priority. pq.Push(sequence_d, sort_key_d); EXPECT_EQ(sort_key_b, pq.PeekSortKey()); + ExpectNumSequences(1U, 1U, 2U); // Pop |sequence_b| from the PriorityQueue. |sequence_c| becomes the sequence // with the highest priority. EXPECT_EQ(sequence_b, pq.PopSequence()); EXPECT_EQ(sort_key_c, pq.PeekSortKey()); + ExpectNumSequences(1U, 1U, 1U); // Pop |sequence_c| from the PriorityQueue. |sequence_a| becomes the sequence // with the highest priority. EXPECT_EQ(sequence_c, pq.PopSequence()); EXPECT_EQ(sort_key_a, pq.PeekSortKey()); + ExpectNumSequences(1U, 1U, 0U); // Pop |sequence_a| from the PriorityQueue. |sequence_d| becomes the sequence // with the highest priority. EXPECT_EQ(sequence_a, pq.PopSequence()); EXPECT_EQ(sort_key_d, pq.PeekSortKey()); + ExpectNumSequences(1U, 0U, 0U); // Pop |sequence_d| from the PriorityQueue. It is now empty. EXPECT_EQ(sequence_d, pq.PopSequence()); EXPECT_TRUE(pq.IsEmpty()); + ExpectNumSequences(0U, 0U, 0U); } TEST_F(TaskSchedulerPriorityQueueWithSequencesTest, RemoveSequence) { @@ -107,32 +127,39 @@ pq.Push(sequence_c, sort_key_c); pq.Push(sequence_d, sort_key_d); EXPECT_EQ(sort_key_b, pq.PeekSortKey()); + ExpectNumSequences(1U, 1U, 2U); // Remove |sequence_a| from the PriorityQueue. |sequence_b| is still the // sequence with the highest priority. EXPECT_TRUE(pq.RemoveSequence(sequence_a)); EXPECT_EQ(sort_key_b, pq.PeekSortKey()); + ExpectNumSequences(1U, 0U, 2U); // RemoveSequence() should return false if called on a sequence not in the // PriorityQueue. EXPECT_FALSE(pq.RemoveSequence(sequence_a)); + ExpectNumSequences(1U, 0U, 2U); // Remove |sequence_b| from the PriorityQueue. |sequence_c| becomes the // sequence with the highest priority. EXPECT_TRUE(pq.RemoveSequence(sequence_b)); EXPECT_EQ(sort_key_c, pq.PeekSortKey()); + ExpectNumSequences(1U, 0U, 1U); // Remove |sequence_d| from the PriorityQueue. |sequence_c| is still the // sequence with the highest priority. EXPECT_TRUE(pq.RemoveSequence(sequence_d)); EXPECT_EQ(sort_key_c, pq.PeekSortKey()); + ExpectNumSequences(0U, 0U, 1U); // Remove |sequence_c| from the PriorityQueue, making it empty. EXPECT_TRUE(pq.RemoveSequence(sequence_c)); EXPECT_TRUE(pq.IsEmpty()); + ExpectNumSequences(0U, 0U, 0U); // Return false if RemoveSequence() is called on an empty PriorityQueue. EXPECT_FALSE(pq.RemoveSequence(sequence_c)); + ExpectNumSequences(0U, 0U, 0U); } TEST_F(TaskSchedulerPriorityQueueWithSequencesTest, UpdateSortKey) { @@ -145,6 +172,7 @@ pq.Push(sequence_c, sort_key_c); pq.Push(sequence_d, sort_key_d); EXPECT_EQ(sort_key_b, pq.PeekSortKey()); + ExpectNumSequences(1U, 1U, 2U); { // Downgrade |sequence_b| from USER_BLOCKING to BEST_EFFORT. |sequence_c| @@ -156,6 +184,7 @@ pq.UpdateSortKey(std::move(sequence_b_and_transaction)); EXPECT_EQ(sort_key_c, pq.PeekSortKey()); + ExpectNumSequences(2U, 1U, 1U); } { @@ -168,12 +197,14 @@ TaskPriority::USER_BLOCKING); pq.UpdateSortKey(std::move(sequence_c_and_transaction)); + ExpectNumSequences(2U, 1U, 1U); // Note: |sequence_c| is popped for comparison as |sort_key_c| becomes // obsolete. |sequence_a| (USER_VISIBLE priority) becomes the sequence with // the highest priority. EXPECT_EQ(sequence_c, pq.PopSequence()); EXPECT_EQ(sort_key_a, pq.PeekSortKey()); + ExpectNumSequences(2U, 1U, 0U); } { @@ -185,6 +216,7 @@ TaskPriority::USER_BLOCKING); pq.UpdateSortKey(std::move(sequence_d_and_transaction)); + ExpectNumSequences(1U, 1U, 1U); // Note: |sequence_d| is popped for comparison as |sort_key_d| becomes // obsolete. @@ -192,6 +224,7 @@ // No-op if UpdateSortKey() is called on a Sequence not in the // PriorityQueue. EXPECT_EQ(sort_key_a, pq.PeekSortKey()); + ExpectNumSequences(1U, 1U, 0U); } { @@ -199,8 +232,11 @@ SequenceAndTransaction::FromSequence(sequence_d); pq.UpdateSortKey(std::move(sequence_d_and_transaction)); + ExpectNumSequences(1U, 1U, 0U); EXPECT_EQ(sequence_a, pq.PopSequence()); + ExpectNumSequences(1U, 0U, 0U); EXPECT_EQ(sequence_b, pq.PopSequence()); + ExpectNumSequences(0U, 0U, 0U); } { @@ -209,6 +245,7 @@ SequenceAndTransaction::FromSequence(sequence_b); pq.UpdateSortKey(std::move(sequence_b_and_transaction)); EXPECT_TRUE(pq.IsEmpty()); + ExpectNumSequences(0U, 0U, 0U); } }
diff --git a/base/task/task_scheduler/task_scheduler.cc b/base/task/task_scheduler/task_scheduler.cc index 02c9297..d98a4f26 100644 --- a/base/task/task_scheduler/task_scheduler.cc +++ b/base/task/task_scheduler/task_scheduler.cc
@@ -25,10 +25,16 @@ TaskScheduler::InitParams::InitParams( const SchedulerWorkerPoolParams& background_worker_pool_params_in, + const SchedulerWorkerPoolParams& background_blocking_worker_pool_params_in, const SchedulerWorkerPoolParams& foreground_worker_pool_params_in, + const SchedulerWorkerPoolParams& foreground_blocking_worker_pool_params_in, SharedWorkerPoolEnvironment shared_worker_pool_environment_in) : background_worker_pool_params(background_worker_pool_params_in), + background_blocking_worker_pool_params( + background_blocking_worker_pool_params_in), foreground_worker_pool_params(foreground_worker_pool_params_in), + foreground_blocking_worker_pool_params( + foreground_blocking_worker_pool_params_in), shared_worker_pool_environment(shared_worker_pool_environment_in) {} TaskScheduler::InitParams::~InitParams() = default; @@ -58,15 +64,17 @@ // * The main thread is assumed to be busy, cap foreground workers at // |num_cores - 1|. const int num_cores = SysInfo::NumberOfProcessors(); - - // TODO(etiennep): Change this to 2. - constexpr int kBackgroundMaxThreads = 3; - const int kForegroundMaxThreads = std::max(3, num_cores - 1); + constexpr int kBackgroundMaxThreads = 1; + constexpr int kBackgroundBlockingMaxThreads = 2; + const int kForegroundMaxThreads = std::max(1, num_cores - 1); + const int kForegroundBlockingMaxThreads = std::max(2, num_cores - 1); constexpr TimeDelta kSuggestedReclaimTime = TimeDelta::FromSeconds(30); Start({{kBackgroundMaxThreads, kSuggestedReclaimTime}, - {kForegroundMaxThreads, kSuggestedReclaimTime}}); + {kBackgroundBlockingMaxThreads, kSuggestedReclaimTime}, + {kForegroundMaxThreads, kSuggestedReclaimTime}, + {kForegroundBlockingMaxThreads, kSuggestedReclaimTime}}); } #endif // !defined(OS_NACL)
diff --git a/base/task/task_scheduler/task_scheduler.h b/base/task/task_scheduler/task_scheduler.h index 63b776a..03cc1d9 100644 --- a/base/task/task_scheduler/task_scheduler.h +++ b/base/task/task_scheduler/task_scheduler.h
@@ -64,13 +64,19 @@ InitParams( const SchedulerWorkerPoolParams& background_worker_pool_params_in, + const SchedulerWorkerPoolParams& + background_blocking_worker_pool_params_in, const SchedulerWorkerPoolParams& foreground_worker_pool_params_in, + const SchedulerWorkerPoolParams& + foreground_blocking_worker_pool_params_in, SharedWorkerPoolEnvironment shared_worker_pool_environment_in = SharedWorkerPoolEnvironment::DEFAULT); ~InitParams(); SchedulerWorkerPoolParams background_worker_pool_params; + SchedulerWorkerPoolParams background_blocking_worker_pool_params; SchedulerWorkerPoolParams foreground_worker_pool_params; + SchedulerWorkerPoolParams foreground_blocking_worker_pool_params; SharedWorkerPoolEnvironment shared_worker_pool_environment; };
diff --git a/base/task/task_scheduler/task_scheduler_impl.cc b/base/task/task_scheduler/task_scheduler_impl.cc index f483f47..f1491c3 100644 --- a/base/task/task_scheduler/task_scheduler_impl.cc +++ b/base/task/task_scheduler/task_scheduler_impl.cc
@@ -32,11 +32,19 @@ namespace { -constexpr EnvironmentParams kForegroundPoolEnvironmentParams{ - "Foreground", base::ThreadPriority::NORMAL}; +// Returns worker pool EnvironmentType for given arguments |is_background| and +// |is_blocking|. +EnvironmentType GetEnvironmentIndex(bool is_background, bool is_blocking) { + if (is_background) { + if (is_blocking) + return BACKGROUND_BLOCKING; + return BACKGROUND; + } -constexpr EnvironmentParams kBackgroundPoolEnvironmentParams{ - "Background", base::ThreadPriority::BACKGROUND}; + if (is_blocking) + return FOREGROUND_BLOCKING; + return FOREGROUND; +} } // namespace @@ -58,22 +66,42 @@ tracked_ref_factory_(this) { DCHECK(!histogram_label.empty()); - foreground_pool_.emplace( - JoinString( - {histogram_label, kForegroundPoolEnvironmentParams.name_suffix}, "."), - kForegroundPoolEnvironmentParams.name_suffix, - kForegroundPoolEnvironmentParams.priority_hint, - task_tracker_->GetTrackedRef(), tracked_ref_factory_.GetTrackedRef()); + static_assert( + std::extent<decltype(environment_to_worker_pool_)>() == ENVIRONMENT_COUNT, + "The size of |environment_to_worker_pool_| must match " + "ENVIRONMENT_COUNT."); + static_assert( + size(kEnvironmentParams) == ENVIRONMENT_COUNT, + "The size of |kEnvironmentParams| must match ENVIRONMENT_COUNT."); - if (CanUseBackgroundPriorityForSchedulerWorker()) { - background_pool_.emplace( + int num_pools_to_create = CanUseBackgroundPriorityForSchedulerWorker() + ? ENVIRONMENT_COUNT + : ENVIRONMENT_COUNT_WITHOUT_BACKGROUND_PRIORITY; + for (int environment_type = 0; environment_type < num_pools_to_create; + ++environment_type) { + worker_pools_.emplace_back(std::make_unique<SchedulerWorkerPoolImpl>( JoinString( - {histogram_label, kBackgroundPoolEnvironmentParams.name_suffix}, + {histogram_label, kEnvironmentParams[environment_type].name_suffix}, "."), - kBackgroundPoolEnvironmentParams.name_suffix, - kBackgroundPoolEnvironmentParams.priority_hint, - task_tracker_->GetTrackedRef(), tracked_ref_factory_.GetTrackedRef()); + kEnvironmentParams[environment_type].name_suffix, + kEnvironmentParams[environment_type].priority_hint, + task_tracker_->GetTrackedRef(), tracked_ref_factory_.GetTrackedRef())); } + + // Map environment indexes to pools. |kMergeBlockingNonBlockingPools| is + // assumed to be disabled. + environment_to_worker_pool_[FOREGROUND] = + worker_pools_[GetEnvironmentIndex(false, false)].get(); + environment_to_worker_pool_[FOREGROUND_BLOCKING] = + worker_pools_[GetEnvironmentIndex(false, true)].get(); + environment_to_worker_pool_[BACKGROUND] = + worker_pools_[GetEnvironmentIndex( + CanUseBackgroundPriorityForSchedulerWorker(), false)] + .get(); + environment_to_worker_pool_[BACKGROUND_BLOCKING] = + worker_pools_[GetEnvironmentIndex( + CanUseBackgroundPriorityForSchedulerWorker(), true)] + .get(); } TaskSchedulerImpl::~TaskSchedulerImpl() { @@ -81,9 +109,8 @@ DCHECK(join_for_testing_returned_.IsSet()); #endif - // Reset worker pools to release held TrackedRefs, which block teardown. - foreground_pool_.reset(); - background_pool_.reset(); + // Clear |worker_pools_| to release held TrackedRefs, which block teardown. + worker_pools_.clear(); } void TaskSchedulerImpl::Start( @@ -96,6 +123,27 @@ if (FeatureList::IsEnabled(kAllTasksUserBlocking)) all_tasks_user_blocking_.Set(); + const bool use_blocking_pools = + !base::FeatureList::IsEnabled(kMergeBlockingNonBlockingPools); + + // Remap environment indexes to pools with |use_blocking_pools|. + // TODO(etiennep): This is only necessary because of the + // kMergeBlockingNonBlockingPools experiment. Remove this after the + // experiment. + environment_to_worker_pool_[FOREGROUND] = + worker_pools_[GetEnvironmentIndex(false, false)].get(); + environment_to_worker_pool_[FOREGROUND_BLOCKING] = + worker_pools_[GetEnvironmentIndex(false, use_blocking_pools)].get(); + environment_to_worker_pool_[BACKGROUND] = + worker_pools_[GetEnvironmentIndex( + CanUseBackgroundPriorityForSchedulerWorker(), false)] + .get(); + environment_to_worker_pool_[BACKGROUND_BLOCKING] = + worker_pools_[GetEnvironmentIndex( + CanUseBackgroundPriorityForSchedulerWorker(), + use_blocking_pools)] + .get(); + // Start the service thread. On platforms that support it (POSIX except NaCL // SFI), the service thread runs a MessageLoopForIO which is used to support // FileDescriptorWatcher in the scope in which tasks run. @@ -140,17 +188,32 @@ const int max_best_effort_tasks_in_foreground_pool = std::max( 1, std::min(init_params.background_worker_pool_params.max_tasks(), init_params.foreground_worker_pool_params.max_tasks() / 2)); - foreground_pool_->Start(init_params.foreground_worker_pool_params, - max_best_effort_tasks_in_foreground_pool, - service_thread_task_runner, scheduler_worker_observer, - worker_environment); + worker_pools_[FOREGROUND]->Start( + init_params.foreground_worker_pool_params, + max_best_effort_tasks_in_foreground_pool, service_thread_task_runner, + scheduler_worker_observer, worker_environment); + const int max_best_effort_tasks_in_foreground_blocking_pool = std::max( + 1, + std::min( + init_params.background_blocking_worker_pool_params.max_tasks(), + init_params.foreground_blocking_worker_pool_params.max_tasks() / 2)); + worker_pools_[FOREGROUND_BLOCKING]->Start( + init_params.foreground_blocking_worker_pool_params, + max_best_effort_tasks_in_foreground_blocking_pool, + service_thread_task_runner, scheduler_worker_observer, + worker_environment); - if (background_pool_.has_value()) { - background_pool_->Start( + if (CanUseBackgroundPriorityForSchedulerWorker()) { + worker_pools_[BACKGROUND]->Start( init_params.background_worker_pool_params, init_params.background_worker_pool_params.max_tasks(), service_thread_task_runner, scheduler_worker_observer, worker_environment); + worker_pools_[BACKGROUND_BLOCKING]->Start( + init_params.background_blocking_worker_pool_params, + init_params.background_blocking_worker_pool_params.max_tasks(), + service_thread_task_runner, scheduler_worker_observer, + worker_environment); } } @@ -205,9 +268,8 @@ std::vector<const HistogramBase*> TaskSchedulerImpl::GetHistograms() const { std::vector<const HistogramBase*> histograms; - foreground_pool_->GetHistograms(&histograms); - if (background_pool_.has_value()) - background_pool_->GetHistograms(&histograms); + for (const auto& worker_pool : worker_pools_) + worker_pool->GetHistograms(&histograms); return histograms; } @@ -243,9 +305,8 @@ // https://crbug.com/771701. service_thread_->Stop(); single_thread_task_runner_manager_.JoinForTesting(); - foreground_pool_->JoinForTesting(); - if (background_pool_.has_value()) - background_pool_->JoinForTesting(); + for (const auto& worker_pool : worker_pools_) + worker_pool->JoinForTesting(); #if DCHECK_IS_ON() join_for_testing_returned_.Set(); #endif @@ -324,12 +385,8 @@ } SchedulerWorkerPoolImpl* TaskSchedulerImpl::GetWorkerPoolImplForTraits( - const TaskTraits& traits) { - if (traits.priority() == TaskPriority::BEST_EFFORT && - background_pool_.has_value()) { - return &background_pool_.value(); - } - return &foreground_pool_.value(); + const TaskTraits& traits) const { + return environment_to_worker_pool_[GetEnvironmentIndexForTraits(traits)]; } SchedulerWorkerPool* TaskSchedulerImpl::GetWorkerPoolForTraits( @@ -345,9 +402,9 @@ } void TaskSchedulerImpl::ReportHeartbeatMetrics() const { - foreground_pool_->ReportHeartbeatMetrics(); - if (background_pool_.has_value()) - background_pool_->ReportHeartbeatMetrics(); + for (const auto& worker_pool : worker_pools_) + worker_pool->ReportHeartbeatMetrics(); + delayed_task_manager_.ReportHeartbeatMetrics(); } } // namespace internal
diff --git a/base/task/task_scheduler/task_scheduler_impl.h b/base/task/task_scheduler/task_scheduler_impl.h index 2528653..ab4152f 100644 --- a/base/task/task_scheduler/task_scheduler_impl.h +++ b/base/task/task_scheduler/task_scheduler_impl.h
@@ -103,12 +103,8 @@ // TODO(fdoray): Move all methods used by TaskSchedulerImpl to the // SchedulerWorkerPool interface and remove the SchedulerWorkerPool*Impl* // accessors. - SchedulerWorkerPoolImpl* GetWorkerPoolImplForTraits(const TaskTraits& traits); - const SchedulerWorkerPoolImpl* GetWorkerPoolImplForTraits( - const TaskTraits& traits) const { - return const_cast<TaskSchedulerImpl*>(this)->GetWorkerPoolImplForTraits( - traits); - } + SchedulerWorkerPoolImpl* GetWorkerPoolImplForTraits( + const TaskTraits& traits) const; // Returns |traits|, with priority set to TaskPriority::USER_BLOCKING if // |all_tasks_user_blocking_| is set. @@ -140,8 +136,12 @@ // TODO(fdoray): Remove after experiment. https://crbug.com/757022 AtomicFlag all_tasks_user_blocking_; - Optional<SchedulerWorkerPoolImpl> foreground_pool_; - Optional<SchedulerWorkerPoolImpl> background_pool_; + // Owns all the pools managed by this TaskScheduler. + std::vector<std::unique_ptr<SchedulerWorkerPoolImpl>> worker_pools_; + + // Maps an environment from EnvironmentType to a pool in |worker_pools_|. + SchedulerWorkerPoolImpl* environment_to_worker_pool_[static_cast<int>( + EnvironmentType::ENVIRONMENT_COUNT)]; #if DCHECK_IS_ON() // Set once JoinForTesting() has returned.
diff --git a/base/task/task_scheduler/task_scheduler_impl_unittest.cc b/base/task/task_scheduler/task_scheduler_impl_unittest.cc index 0e7388bf..9d78749a 100644 --- a/base/task/task_scheduler/task_scheduler_impl_unittest.cc +++ b/base/task/task_scheduler/task_scheduler_impl_unittest.cc
@@ -59,6 +59,11 @@ namespace { +enum class PoolConfiguration { + kDefault, + kMergeBlockingNonBlocking, +}; + enum class SchedulerState { // TaskScheduler::Start() was not called yet, no thread was created. kBeforeSchedulerStart, @@ -68,11 +73,15 @@ struct TaskSchedulerImplTestParams { TaskSchedulerImplTestParams(const TaskTraits& traits, - test::ExecutionMode execution_mode) - : traits(traits), execution_mode(execution_mode) {} + test::ExecutionMode execution_mode, + PoolConfiguration pool_config) + : traits(traits), + execution_mode(execution_mode), + pool_config(pool_config) {} TaskTraits traits; test::ExecutionMode execution_mode; + PoolConfiguration pool_config; }; #if DCHECK_IS_ON() @@ -121,10 +130,15 @@ ? "Background" : "Foreground")); } - if (current_thread_name.find("SingleThread") == std::string::npos) { + // TaskScheduler only handles |kMergeBlockingNonBlockingPools| once started + // (early task runners are not merged for this experiment). + // TODO(etiennep): Simplify this after the experiment. + // Merging pools does not affect SingleThread workers. + if (base::FeatureList::IsEnabled(kMergeBlockingNonBlockingPools) && + state == SchedulerState::kAfterSchedulerStart && + current_thread_name.find("SingleThread") == std::string::npos) { EXPECT_EQ(std::string::npos, current_thread_name.find("Blocking")); } else { - // SingleThread workers discriminate blocking/non-blocking tasks. EXPECT_EQ(traits.may_block(), current_thread_name.find("Blocking") != std::string::npos); } @@ -229,9 +243,17 @@ priority_index <= static_cast<size_t>(TaskPriority::HIGHEST); ++priority_index) { const TaskPriority priority = static_cast<TaskPriority>(priority_index); - params.push_back(TaskSchedulerImplTestParams({priority}, execution_mode)); - params.push_back( - TaskSchedulerImplTestParams({priority, MayBlock()}, execution_mode)); + params.push_back(TaskSchedulerImplTestParams( + {priority}, execution_mode, PoolConfiguration::kDefault)); + params.push_back(TaskSchedulerImplTestParams( + {MayBlock()}, execution_mode, PoolConfiguration::kDefault)); + + params.push_back(TaskSchedulerImplTestParams( + {priority}, execution_mode, + PoolConfiguration::kMergeBlockingNonBlocking)); + params.push_back(TaskSchedulerImplTestParams( + {MayBlock()}, execution_mode, + PoolConfiguration::kMergeBlockingNonBlocking)); } } @@ -241,10 +263,17 @@ class TaskSchedulerImplTest : public testing::TestWithParam<TaskSchedulerImplTestParams> { protected: - TaskSchedulerImplTest() : scheduler_("Test") {} + TaskSchedulerImplTest() : scheduler_("Test") { + feature_list_.emplace(); + feature_list_->InitWithFeatures(GetFeaturesEnabledByConstructor(), {}); + } void EnableAllTasksUserBlocking() { - feature_list_.InitWithFeatures({kAllTasksUserBlocking}, {}); + feature_list_.reset(); + feature_list_.emplace(); + std::vector<Feature> enabled_features = GetFeaturesEnabledByConstructor(); + enabled_features.push_back(kAllTasksUserBlocking); + feature_list_->InitWithFeatures(enabled_features, {}); } void set_scheduler_worker_observer( @@ -254,10 +283,14 @@ void StartTaskScheduler(TimeDelta reclaim_time = TimeDelta::FromSeconds(30)) { constexpr int kMaxNumBackgroundThreads = 1; + constexpr int kMaxNumBackgroundBlockingThreads = 3; constexpr int kMaxNumForegroundThreads = 4; + constexpr int kMaxNumForegroundBlockingThreads = 12; scheduler_.Start({{kMaxNumBackgroundThreads, reclaim_time}, - {kMaxNumForegroundThreads, reclaim_time}}, + {kMaxNumBackgroundBlockingThreads, reclaim_time}, + {kMaxNumForegroundThreads, reclaim_time}, + {kMaxNumForegroundBlockingThreads, reclaim_time}}, scheduler_worker_observer_); } @@ -273,7 +306,14 @@ TaskSchedulerImpl scheduler_; private: - base::test::ScopedFeatureList feature_list_; + std::vector<Feature> GetFeaturesEnabledByConstructor() { + if (GetParam().pool_config == PoolConfiguration::kMergeBlockingNonBlocking) + return {kMergeBlockingNonBlockingPools}; + else + return {}; + } + + Optional<base::test::ScopedFeatureList> feature_list_; SchedulerWorkerObserver* scheduler_worker_observer_ = nullptr; bool did_tear_down_ = false; @@ -473,7 +513,7 @@ // TaskTraits and ExecutionModes. Verifies that each Task runs on a thread with // the expected priority and I/O restrictions and respects the characteristics // of its ExecutionMode. -TEST_F(TaskSchedulerImplTest, MultipleTaskSchedulerImplTestParams) { +TEST_P(TaskSchedulerImplTest, MultipleTaskSchedulerImplTestParams) { StartTaskScheduler(); std::vector<std::unique_ptr<ThreadPostingTasks>> threads_posting_tasks; for (const auto& test_params : GetTaskSchedulerImplTestParams()) { @@ -489,7 +529,7 @@ } } -TEST_F(TaskSchedulerImplTest, +TEST_P(TaskSchedulerImplTest, GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated) { StartTaskScheduler(); @@ -505,19 +545,32 @@ {MayBlock(), TaskPriority::BEST_EFFORT}); }); - EXPECT_EQ(4, scheduler_.GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( - {TaskPriority::USER_VISIBLE})); - EXPECT_EQ(4, scheduler_.GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( - {MayBlock(), TaskPriority::USER_VISIBLE})); - EXPECT_EQ(4, scheduler_.GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( - {TaskPriority::USER_BLOCKING})); - EXPECT_EQ(4, scheduler_.GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( - {MayBlock(), TaskPriority::USER_BLOCKING})); + if (GetParam().pool_config == PoolConfiguration::kMergeBlockingNonBlocking) { + EXPECT_EQ(4, scheduler_.GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( + {TaskPriority::USER_VISIBLE})); + EXPECT_EQ(4, scheduler_.GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( + {MayBlock(), TaskPriority::USER_VISIBLE})); + EXPECT_EQ(4, scheduler_.GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( + {TaskPriority::USER_BLOCKING})); + EXPECT_EQ(4, scheduler_.GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( + {MayBlock(), TaskPriority::USER_BLOCKING})); + } else { + EXPECT_EQ(4, scheduler_.GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( + {TaskPriority::USER_VISIBLE})); + EXPECT_EQ(12, + scheduler_.GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( + {MayBlock(), TaskPriority::USER_VISIBLE})); + EXPECT_EQ(4, scheduler_.GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( + {TaskPriority::USER_BLOCKING})); + EXPECT_EQ(12, + scheduler_.GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( + {MayBlock(), TaskPriority::USER_BLOCKING})); + } } // Verify that the RunsTasksInCurrentSequence() method of a SequencedTaskRunner // returns false when called from a task that isn't part of the sequence. -TEST_F(TaskSchedulerImplTest, SequencedRunsTasksInCurrentSequence) { +TEST_P(TaskSchedulerImplTest, SequencedRunsTasksInCurrentSequence) { StartTaskScheduler(); auto single_thread_task_runner = scheduler_.CreateSingleThreadTaskRunnerWithTraits( @@ -541,7 +594,7 @@ // Verify that the RunsTasksInCurrentSequence() method of a // SingleThreadTaskRunner returns false when called from a task that isn't part // of the sequence. -TEST_F(TaskSchedulerImplTest, SingleThreadRunsTasksInCurrentSequence) { +TEST_P(TaskSchedulerImplTest, SingleThreadRunsTasksInCurrentSequence) { StartTaskScheduler(); auto sequenced_task_runner = scheduler_.CreateSequencedTaskRunnerWithTraits(TaskTraits()); @@ -564,7 +617,7 @@ } #if defined(OS_WIN) -TEST_F(TaskSchedulerImplTest, COMSTATaskRunnersRunWithCOMSTA) { +TEST_P(TaskSchedulerImplTest, COMSTATaskRunnersRunWithCOMSTA) { StartTaskScheduler(); auto com_sta_task_runner = scheduler_.CreateCOMSTATaskRunnerWithTraits( TaskTraits(), SingleThreadTaskRunnerThreadMode::SHARED); @@ -581,7 +634,7 @@ } #endif // defined(OS_WIN) -TEST_F(TaskSchedulerImplTest, DelayedTasksNotRunAfterShutdown) { +TEST_P(TaskSchedulerImplTest, DelayedTasksNotRunAfterShutdown) { StartTaskScheduler(); // As with delayed tasks in general, this is racy. If the task does happen to // run after Shutdown within the timeout, it will fail this test. @@ -604,7 +657,7 @@ #if defined(OS_POSIX) -TEST_F(TaskSchedulerImplTest, FileDescriptorWatcherNoOpsAfterShutdown) { +TEST_P(TaskSchedulerImplTest, FileDescriptorWatcherNoOpsAfterShutdown) { StartTaskScheduler(); int pipes[2]; @@ -651,7 +704,7 @@ // Verify that tasks posted on the same sequence access the same values on // SequenceLocalStorage, and tasks on different sequences see different values. -TEST_F(TaskSchedulerImplTest, SequenceLocalStorage) { +TEST_P(TaskSchedulerImplTest, SequenceLocalStorage) { StartTaskScheduler(); SequenceLocalStorageSlot<int> slot; @@ -682,7 +735,7 @@ scheduler_.FlushForTesting(); } -TEST_F(TaskSchedulerImplTest, FlushAsyncNoTasks) { +TEST_P(TaskSchedulerImplTest, FlushAsyncNoTasks) { StartTaskScheduler(); bool called_back = false; scheduler_.FlushAsyncForTesting( @@ -726,7 +779,7 @@ // Integration test that verifies that workers have a frame on their stacks // which easily identifies the type of worker and shutdown behavior (useful to // diagnose issues from logs without memory dumps). -TEST_F(TaskSchedulerImplTest, MAYBE_IdentifiableStacks) { +TEST_P(TaskSchedulerImplTest, MAYBE_IdentifiableStacks) { StartTaskScheduler(); // Shutdown behaviors and expected stack frames. @@ -806,14 +859,14 @@ scheduler_.FlushForTesting(); } -TEST_F(TaskSchedulerImplTest, SchedulerWorkerObserver) { +TEST_P(TaskSchedulerImplTest, SchedulerWorkerObserver) { testing::StrictMock<test::MockSchedulerWorkerObserver> observer; set_scheduler_worker_observer(&observer); // A worker should be created for each pool. After that, 4 threads should be // created for each SingleThreadTaskRunnerThreadMode (8 on Windows). const int kExpectedNumPoolWorkers = - CanUseBackgroundPriorityForSchedulerWorker() ? 2 : 1; + CanUseBackgroundPriorityForSchedulerWorker() ? 4 : 2; #if defined(OS_WIN) const int kExpectedNumSingleThreadedWorkersPerMode = 8; #else @@ -931,6 +984,8 @@ constexpr TimeDelta kSuggestedReclaimTime = TimeDelta::FromSeconds(30); scheduler_.Start({{threads_per_pool, kSuggestedReclaimTime}, + {threads_per_pool, kSuggestedReclaimTime}, + {threads_per_pool, kSuggestedReclaimTime}, {threads_per_pool, kSuggestedReclaimTime}}, nullptr); } @@ -988,9 +1043,13 @@ pool_blocking_events.push_back(std::make_unique<PoolBlockingEvents>( TaskTraits({TaskPriority::USER_BLOCKING}))); + pool_blocking_events.push_back(std::make_unique<PoolBlockingEvents>( + TaskTraits({TaskPriority::USER_BLOCKING, MayBlock()}))); if (CanUseBackgroundPriorityForSchedulerWorker()) { pool_blocking_events.push_back(std::make_unique<PoolBlockingEvents>( TaskTraits({TaskPriority::BEST_EFFORT}))); + pool_blocking_events.push_back(std::make_unique<PoolBlockingEvents>( + TaskTraits({TaskPriority::BEST_EFFORT, MayBlock()}))); } // When all blocking tasks signal |scheduled|, there is a task blocked in @@ -1037,6 +1096,10 @@ for (auto& task_runner_and_events : task_runners_and_events_) { test::WaitWithoutBlockingObserver(&task_runner_and_events->task_ran); } + + // Make sure to coalesce tasks from |pool_blocking_events| (they are not + // guaranteed to all have picked up the Signal() to unblock at this point). + scheduler_.FlushForTesting(); } // Update the priority of a sequence when it is scheduled, i.e. not currently
diff --git a/base/task/task_scheduler/task_scheduler_perftest.cc b/base/task/task_scheduler/task_scheduler_perftest.cc index 5976687f..b83cffd 100644 --- a/base/task/task_scheduler/task_scheduler_perftest.cc +++ b/base/task/task_scheduler/task_scheduler_perftest.cc
@@ -122,10 +122,14 @@ base::RepeatingClosure post_action) { constexpr TimeDelta kSuggestedReclaimTime = TimeDelta::FromSeconds(30); constexpr int kMaxNumBackgroundThreads = 1; + constexpr int kMaxNumBackgroundBlockingThreads = 1; + constexpr int kMaxNumForegroundBlockingThreads = 1; TaskScheduler::GetInstance()->Start( {{kMaxNumBackgroundThreads, kSuggestedReclaimTime}, - {num_running_threads, kSuggestedReclaimTime}}, + {kMaxNumBackgroundBlockingThreads, kSuggestedReclaimTime}, + {num_running_threads, kSuggestedReclaimTime}, + {kMaxNumForegroundBlockingThreads, kSuggestedReclaimTime}}, nullptr); base::RepeatingClosure done = BarrierClosure(
diff --git a/base/test/BUILD.gn b/base/test/BUILD.gn index 513b172..7c3632a 100644 --- a/base/test/BUILD.gn +++ b/base/test/BUILD.gn
@@ -32,6 +32,8 @@ "../task/sequence_manager/test/fake_task.h", "../task/sequence_manager/test/mock_time_domain.cc", "../task/sequence_manager/test/mock_time_domain.h", + "../task/sequence_manager/test/mock_time_message_pump.cc", + "../task/sequence_manager/test/mock_time_message_pump.h", "../task/sequence_manager/test/sequence_manager_for_test.cc", "../task/sequence_manager/test/sequence_manager_for_test.h", "../task/sequence_manager/test/test_task_queue.cc",
diff --git a/base/test/launcher/test_launcher.cc b/base/test/launcher/test_launcher.cc index a25bec59..206064ba 100644 --- a/base/test/launcher/test_launcher.cc +++ b/base/test/launcher/test_launcher.cc
@@ -139,14 +139,18 @@ void CreateAndStartTaskScheduler(int num_parallel_jobs) { // These values are taken from TaskScheduler::StartWithDefaultParams(), which // is not used directly to allow a custom number of threads in the foreground - // pool. - // TODO(etiennep): Change this to 2 in future CL. - constexpr int kMaxBackgroundThreads = 3; + // blocking pool. + constexpr int kMaxBackgroundThreads = 1; + constexpr int kMaxBackgroundBlockingThreads = 2; + const int max_foreground_threads = + std::max(1, base::SysInfo::NumberOfProcessors()); constexpr base::TimeDelta kSuggestedReclaimTime = base::TimeDelta::FromSeconds(30); base::TaskScheduler::Create("TestLauncher"); base::TaskScheduler::GetInstance()->Start( {{kMaxBackgroundThreads, kSuggestedReclaimTime}, + {kMaxBackgroundBlockingThreads, kSuggestedReclaimTime}, + {max_foreground_threads, kSuggestedReclaimTime}, {num_parallel_jobs, kSuggestedReclaimTime}}); }
diff --git a/base/test/scoped_task_environment.cc b/base/test/scoped_task_environment.cc index a47cca8..75331ca 100644 --- a/base/test/scoped_task_environment.cc +++ b/base/test/scoped_task_environment.cc
@@ -38,9 +38,6 @@ namespace { -LazyInstance<ThreadLocalPointer<ScopedTaskEnvironment::LifetimeObserver>>::Leaky - environment_lifetime_observer; - base::Optional<MessageLoop::Type> GetMessageLoopTypeForMainThreadType( ScopedTaskEnvironment::MainThreadType main_thread_type) { switch (main_thread_type) { @@ -337,7 +334,7 @@ CHECK(base::ThreadTaskRunnerHandle::IsSet()) << "ThreadTaskRunnerHandle should've been set now."; - // Instantiate a TaskScheduler with 2 threads in each of its pools. Threads + // Instantiate a TaskScheduler with 2 threads in each of its 4 pools. Threads // stay alive even when they don't have work. // Each pool uses two threads to prevent deadlocks in unit tests that have a // sequence that uses WithBaseSyncPrimitives() to wait on the result of @@ -353,7 +350,8 @@ "ScopedTaskEnvironment", WrapUnique(task_tracker_))); task_scheduler_ = TaskScheduler::GetInstance(); TaskScheduler::GetInstance()->Start({ - worker_pool_params, worker_pool_params + worker_pool_params, worker_pool_params, worker_pool_params, + worker_pool_params #if defined(OS_WIN) , // Enable the MTA in unit tests to match the browser process' @@ -373,12 +371,6 @@ if (execution_control_mode_ == ExecutionMode::QUEUED) CHECK(task_tracker_->DisallowRunTasks()); - - LifetimeObserver* observer = environment_lifetime_observer.Get().Get(); - if (observer) { - observer->OnScopedTaskEnvironmentCreated(main_thread_type, - GetMainThreadTaskRunner()); - } } ScopedTaskEnvironment::ScopedTaskEnvironment(ScopedTaskEnvironment&& other) = @@ -415,10 +407,6 @@ if (!sequence_manager_) return; - LifetimeObserver* observer = environment_lifetime_observer.Get().Get(); - if (observer) - observer->OnScopedTaskEnvironmentDestroyed(); - if (mock_time_domain_) sequence_manager_->UnregisterTimeDomain(mock_time_domain_.get()); @@ -435,12 +423,6 @@ .SetTimeDomain(mock_time_domain_.get())); } -void ScopedTaskEnvironment::SetLifetimeObserver( - ScopedTaskEnvironment::LifetimeObserver* lifetime_observer) { - DCHECK_NE(!!environment_lifetime_observer.Get().Get(), !!lifetime_observer); - environment_lifetime_observer.Get().Set(lifetime_observer); -} - scoped_refptr<base::SingleThreadTaskRunner> ScopedTaskEnvironment::GetMainThreadTaskRunner() { return task_queue_->task_runner();
diff --git a/base/test/scoped_task_environment.h b/base/test/scoped_task_environment.h index e5ae30d..cc21d00 100644 --- a/base/test/scoped_task_environment.h +++ b/base/test/scoped_task_environment.h
@@ -141,22 +141,6 @@ // TaskScheduler and the (Thread|Sequenced)TaskRunnerHandle. virtual ~ScopedTaskEnvironment(); - class LifetimeObserver { - public: - virtual ~LifetimeObserver() = default; - - virtual void OnScopedTaskEnvironmentCreated( - MainThreadType main_thread_type, - scoped_refptr<SingleThreadTaskRunner> task_runner) = 0; - virtual void OnScopedTaskEnvironmentDestroyed() = 0; - }; - - // Set a thread-local observer which will get notifications when - // a new ScopedTaskEnvironment is created or destroyed. - // This is needed due to peculiarities of Blink initialisation - // (Blink is per-test suite and ScopedTaskEnvironment is per-test). - static void SetLifetimeObserver(LifetimeObserver* lifetime_observer); - // Returns a TaskRunner that schedules tasks on the main thread. scoped_refptr<base::SingleThreadTaskRunner> GetMainThreadTaskRunner();
diff --git a/base/test/scoped_task_environment_unittest.cc b/base/test/scoped_task_environment_unittest.cc index 89d777e..33bbb8dd 100644 --- a/base/test/scoped_task_environment_unittest.cc +++ b/base/test/scoped_task_environment_unittest.cc
@@ -356,37 +356,6 @@ } #endif // defined(OS_WIN) -namespace { - -class MockLifetimeObserver : public ScopedTaskEnvironment::LifetimeObserver { - public: - MockLifetimeObserver() = default; - ~MockLifetimeObserver() override = default; - - MOCK_METHOD2(OnScopedTaskEnvironmentCreated, - void(ScopedTaskEnvironment::MainThreadType, - scoped_refptr<SingleThreadTaskRunner>)); - MOCK_METHOD0(OnScopedTaskEnvironmentDestroyed, void()); -}; - -} // namespace - -TEST_F(ScopedTaskEnvironmentTest, LifetimeObserver) { - testing::StrictMock<MockLifetimeObserver> lifetime_observer; - ScopedTaskEnvironment::SetLifetimeObserver(&lifetime_observer); - - EXPECT_CALL(lifetime_observer, - OnScopedTaskEnvironmentCreated(testing::_, testing::_)); - std::unique_ptr<ScopedTaskEnvironment> task_environment( - std::make_unique<ScopedTaskEnvironment>()); - testing::Mock::VerifyAndClearExpectations(&lifetime_observer); - - EXPECT_CALL(lifetime_observer, OnScopedTaskEnvironmentDestroyed()); - task_environment.reset(); - testing::Mock::VerifyAndClearExpectations(&lifetime_observer); - ScopedTaskEnvironment::SetLifetimeObserver(nullptr); -} - TEST_F(ScopedTaskEnvironmentTest, SetsDefaultRunTimeout) { const RunLoop::ScopedRunTimeoutForTest* old_run_timeout = RunLoop::ScopedRunTimeoutForTest::Current();
diff --git a/base/threading/sequence_bound.h b/base/threading/sequence_bound.h index 683bc42c..84d19db 100644 --- a/base/threading/sequence_bound.h +++ b/base/threading/sequence_bound.h
@@ -110,8 +110,9 @@ // constructed, except by posting such a access to |impl_task_runner_| after // posting construction there as well. template <typename... Args> + NO_SANITIZE("cfi-unrelated-cast") SequenceBound(scoped_refptr<base::SequencedTaskRunner> task_runner, - Args&&... args) NO_SANITIZE("cfi-unrelated-cast") + Args&&... args) : impl_task_runner_(std::move(task_runner)) { // Allocate space for but do not construct an instance of |T|. storage_ = AlignedAlloc(sizeof(T), alignof(T)); @@ -159,7 +160,7 @@ // non-virtual base classes are allowed before construction by the standard. // See http://eel.is/c++draft/basic.life#6 for more information. template <typename From> - void MoveRecordFrom(From&& other) NO_SANITIZE("cfi-unrelated-cast") { + void NO_SANITIZE("cfi-unrelated-cast") MoveRecordFrom(From&& other) { // |other| might be is_null(), but that's okay. impl_task_runner_ = std::move(other.impl_task_runner_);
diff --git a/base/trace_event/trace_event_system_stats_monitor.h b/base/trace_event/trace_event_system_stats_monitor.h deleted file mode 100644 index 14aa568..0000000 --- a/base/trace_event/trace_event_system_stats_monitor.h +++ /dev/null
@@ -1,76 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TRACE_EVENT_TRACE_EVENT_SYSTEM_STATS_MONITOR_H_ -#define BASE_TRACE_EVENT_TRACE_EVENT_SYSTEM_STATS_MONITOR_H_ - -#include "base/base_export.h" -#include "base/gtest_prod_util.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/process/process_metrics.h" -#include "base/timer/timer.h" -#include "base/trace_event/trace_log.h" - -namespace base { - -class SingleThreadTaskRunner; - -namespace trace_event { - -// Watches for chrome://tracing to be enabled or disabled. When tracing is -// enabled, also enables system events profiling. This class is the preferred -// way to turn system tracing on and off. -class BASE_EXPORT TraceEventSystemStatsMonitor - : public TraceLog::EnabledStateObserver { - public: - // Length of time interval between stat profiles. - static const int kSamplingIntervalMilliseconds = 2000; - - // |task_runner| must be the primary thread for the client - // process, e.g. the UI thread in a browser. - explicit TraceEventSystemStatsMonitor( - scoped_refptr<SingleThreadTaskRunner> task_runner); - - ~TraceEventSystemStatsMonitor() override; - - // base::trace_event::TraceLog::EnabledStateChangedObserver overrides: - void OnTraceLogEnabled() override; - void OnTraceLogDisabled() override; - - // Retrieves system profiling at the current time. - void DumpSystemStats(); - - private: - FRIEND_TEST_ALL_PREFIXES(TraceSystemStatsMonitorTest, - TraceEventSystemStatsMonitor); - - bool IsTimerRunningForTest() const; - - void StartProfiling(); - - void StopProfiling(); - - // Ensures the observer starts and stops tracing on the primary thread. - scoped_refptr<SingleThreadTaskRunner> task_runner_; - - // Timer to schedule system profile dumps. - RepeatingTimer dump_timer_; - - WeakPtrFactory<TraceEventSystemStatsMonitor> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(TraceEventSystemStatsMonitor); -}; - -// Converts system memory profiling stats in |input| to -// trace event compatible JSON and appends to |output|. Visible for testing. -BASE_EXPORT void AppendSystemProfileAsTraceFormat(const SystemMetrics& - system_stats, - std::string* output); - -} // namespace trace_event -} // namespace base - -#endif // BASE_TRACE_EVENT_TRACE_EVENT_SYSTEM_STATS_MONITOR_H_
diff --git a/base/trace_event/trace_event_system_stats_monitor_unittest.cc b/base/trace_event/trace_event_system_stats_monitor_unittest.cc deleted file mode 100644 index 8688d717..0000000 --- a/base/trace_event/trace_event_system_stats_monitor_unittest.cc +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/trace_event/trace_event_system_stats_monitor.h" - -#include <sstream> -#include <string> - -#include "base/macros.h" -#include "base/run_loop.h" -#include "base/test/scoped_task_environment.h" -#include "base/threading/thread_task_runner_handle.h" -#include "base/trace_event/trace_event_impl.h" -#include "build/build_config.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace base { -namespace trace_event { - -#if !defined(OS_IOS) -// Tests for the system stats monitor. -// Exists as a class so it can be a friend of TraceEventSystemStatsMonitor. -class TraceSystemStatsMonitorTest : public testing::Test { - public: - TraceSystemStatsMonitorTest() = default; - ~TraceSystemStatsMonitorTest() override = default; - - private: - DISALLOW_COPY_AND_ASSIGN(TraceSystemStatsMonitorTest); -}; - -////////////////////////////////////////////////////////////////////////////// - -TEST_F(TraceSystemStatsMonitorTest, TraceEventSystemStatsMonitor) { - test::ScopedTaskEnvironment scoped_task_environment; - - // Start with no observers of the TraceLog. - EXPECT_EQ(0u, TraceLog::GetInstance()->GetObserverCountForTest()); - - // Creating a system stats monitor adds it to the TraceLog observer list. - std::unique_ptr<TraceEventSystemStatsMonitor> system_stats_monitor( - new TraceEventSystemStatsMonitor(ThreadTaskRunnerHandle::Get())); - EXPECT_EQ(1u, TraceLog::GetInstance()->GetObserverCountForTest()); - EXPECT_TRUE( - TraceLog::GetInstance()->HasEnabledStateObserver( - system_stats_monitor.get())); - - // By default the observer isn't dumping memory profiles. - EXPECT_FALSE(system_stats_monitor->IsTimerRunningForTest()); - - // Simulate enabling tracing. - system_stats_monitor->StartProfiling(); - RunLoop().RunUntilIdle(); - EXPECT_TRUE(system_stats_monitor->IsTimerRunningForTest()); - - // Simulate disabling tracing. - system_stats_monitor->StopProfiling(); - RunLoop().RunUntilIdle(); - EXPECT_FALSE(system_stats_monitor->IsTimerRunningForTest()); - - // Deleting the observer removes it from the TraceLog observer list. - system_stats_monitor.reset(); - EXPECT_EQ(0u, TraceLog::GetInstance()->GetObserverCountForTest()); -} -#endif // !defined(OS_IOS) - -} // namespace trace_event -} // namespace base
diff --git a/build/android/gyp/assert_static_initializers.py b/build/android/gyp/assert_static_initializers.py index 717861b7..019bafa 100755 --- a/build/android/gyp/assert_static_initializers.py +++ b/build/android/gyp/assert_static_initializers.py
@@ -7,17 +7,116 @@ import argparse import os +import re +import subprocess import sys - -sys.path.append(os.path.join(os.path.dirname(__file__), '..')) -import resource_sizes +import tempfile +import zipfile from util import build_utils +_DUMP_STATIC_INITIALIZERS_PATH = os.path.join(build_utils.DIR_SOURCE_ROOT, + 'tools', 'linux', + 'dump-static-initializers.py') + + +def _RunReadelf(so_path, options, tool_prefix=''): + return subprocess.check_output([tool_prefix + 'readelf'] + options + + [so_path]) + + +def _ParseLibBuildId(so_path, tool_prefix): + """Returns the Build ID of the given native library.""" + stdout = _RunReadelf(so_path, ['-n'], tool_prefix) + match = re.search(r'Build ID: (\w+)', stdout) + return match.group(1) if match else None + + +def _VerifyLibBuildIdsMatch(tool_prefix, *so_files): + if len(set(_ParseLibBuildId(f, tool_prefix) for f in so_files)) > 1: + raise Exception('Found differing build ids in output directory and apk. ' + 'Your output directory is likely stale.') + + +def _GetStaticInitializers(so_path, tool_prefix): + output = subprocess.check_output( + [_DUMP_STATIC_INITIALIZERS_PATH, '-d', so_path, '-t', tool_prefix]) + summary = re.search(r'Found \d+ static initializers in (\d+) files.', output) + return output.splitlines()[:-1], int(summary.group(1)) + + +def _PrintDumpSIsCount(apk_so_name, unzipped_so, out_dir, tool_prefix): + lib_name = os.path.basename(apk_so_name).replace('crazy.', '') + so_with_symbols_path = os.path.join(out_dir, 'lib.unstripped', lib_name) + if not os.path.exists(so_with_symbols_path): + raise Exception('Unstripped .so not found. Looked here: %s', + so_with_symbols_path) + _VerifyLibBuildIdsMatch(tool_prefix, unzipped_so, so_with_symbols_path) + sis, _ = _GetStaticInitializers(so_with_symbols_path, tool_prefix) + for si in sis: + print si + + +# Mostly copied from //infra/scripts/legacy/scripts/slave/chromium/sizes.py. +def _ReadInitArray(so_path, tool_prefix): + stdout = _RunReadelf(so_path, ['-SW'], tool_prefix) + # Matches: .ctors PROGBITS 000000000516add0 5169dd0 000010 00 WA 0 0 8 + match = re.search(r'\.init_array.*$', stdout, re.MULTILINE) + if not match: + raise Exception('Did not find section: .init_array in:\n' + stdout) + size_str = re.split(r'\W+', match.group(0))[5] + return int(size_str, 16) + + +def _CountStaticInitializers(so_path, tool_prefix): + # Find the number of files with at least one static initializer. + # First determine if we're 32 or 64 bit + stdout = _RunReadelf(so_path, ['-h'], tool_prefix) + elf_class_line = re.search('Class:.*$', stdout, re.MULTILINE).group(0) + elf_class = re.split(r'\W+', elf_class_line)[1] + if elf_class == 'ELF32': + word_size = 4 + else: + word_size = 8 + + # Then find the number of files with global static initializers. + # NOTE: this is very implementation-specific and makes assumptions + # about how compiler and linker implement global static initializers. + init_array_size = _ReadInitArray(so_path, tool_prefix) + return init_array_size / word_size + + +def _AnalyzeStaticInitializers(apk_filename, tool_prefix, dump_sis, out_dir, + ignored_libs): + # Static initializer counting mostly copies logic in + # infra/scripts/legacy/scripts/slave/chromium/sizes.py. + with zipfile.ZipFile(apk_filename) as z: + so_files = [ + f for f in z.infolist() if f.filename.endswith('.so') + and f.file_size > 0 and os.path.basename(f.filename) not in ignored_libs + ] + # Skip checking static initializers for secondary abi libs. They will be + # checked by 32-bit bots. This avoids the complexity of finding 32 bit .so + # files in the output directory in 64 bit builds. + has_64 = any('64' in f.filename for f in so_files) + files_to_check = [f for f in so_files if not has_64 or '64' in f.filename] + + si_count = 0 + for f in files_to_check: + with tempfile.NamedTemporaryFile() as temp: + temp.write(z.read(f)) + temp.flush() + si_count += _CountStaticInitializers(temp.name, tool_prefix) + if dump_sis: + # Print count and list of SIs reported by dump-static-initializers.py. + # Doesn't work well on all archs (particularly arm), which is why + # the readelf method is used for tracking SI counts. + _PrintDumpSIsCount(f.filename, temp.name, out_dir, tool_prefix) + return si_count + def main(): parser = argparse.ArgumentParser() - build_utils.AddDepfileOption(parser) parser.add_argument('--touch', help='File to touch upon success') parser.add_argument('--tool-prefix', required=True, help='Prefix for nm and friends') @@ -30,8 +129,8 @@ #TODO(crbug.com/838414): add support for files included via loadable_modules. ignored_libs = ['libarcore_sdk_c.so'] - si_count = resource_sizes.AnalyzeStaticInitializers( - args.apk, args.tool_prefix, False, '.', ignored_libs) + si_count = _AnalyzeStaticInitializers(args.apk, args.tool_prefix, False, '.', + ignored_libs) if si_count != args.expected_count: print 'Expected {} static initializers, but found {}.'.format( args.expected_count, si_count) @@ -42,8 +141,8 @@ else: print 'Dumping static initializers via dump-static-initializers.py:' sys.stdout.flush() - resource_sizes.AnalyzeStaticInitializers( - args.apk, args.tool_prefix, True, '.', ignored_libs) + _AnalyzeStaticInitializers(args.apk, args.tool_prefix, True, '.', + ignored_libs) print print 'If the above list is not useful, consider listing them with:' print ' //tools/binary_size/diagnose_bloat.py' @@ -53,8 +152,6 @@ 'static_initializers.md') sys.exit(1) - if args.depfile: - build_utils.WriteDepfile(args.depfile, args.touch) if args.touch: open(args.touch, 'w')
diff --git a/build/android/gyp/assert_static_initializers.pydeps b/build/android/gyp/assert_static_initializers.pydeps new file mode 100644 index 0000000..e031668 --- /dev/null +++ b/build/android/gyp/assert_static_initializers.pydeps
@@ -0,0 +1,7 @@ +# Generated by running: +# build/print_python_deps.py --root build/android/gyp --output build/android/gyp/assert_static_initializers.pydeps build/android/gyp/assert_static_initializers.py +../../gn_helpers.py +assert_static_initializers.py +util/__init__.py +util/build_utils.py +util/md5_check.py
diff --git a/build/android/lint/suppressions.xml b/build/android/lint/suppressions.xml index d7004a1d..70879b1 100644 --- a/build/android/lint/suppressions.xml +++ b/build/android/lint/suppressions.xml
@@ -296,6 +296,7 @@ <issue id="StringFormatInvalid" severity="Error"> <ignore regexp="chrome/android/chrome_strings_grd.resources.zip/values-cs/android_chrome_strings.xml"/> <ignore regexp="chrome/android/chrome_strings_grd.resources.zip/values-da/android_chrome_strings.xml"/> + <ignore regexp="chrome/android/chrome_strings_grd.resources.zip/values-et/android_chrome_strings.xml"/> <ignore regexp="chrome/android/chrome_strings_grd.resources.zip/values-pl/android_chrome_strings.xml"/> <ignore regexp="chrome/android/chrome_strings_grd.resources.zip/values-pt-rBR/android_chrome_strings.xml"/> <ignore regexp="chrome/android/chrome_strings_grd.resources.zip/values-sv/android_chrome_strings.xml"/> @@ -319,6 +320,7 @@ <ignore regexp="chrome/android/chrome_strings_grd.resources.zip/values-ja/android_chrome_strings.xml"/> <ignore regexp="chrome/android/chrome_strings_grd.resources.zip/values-ko/android_chrome_strings.xml"/> <ignore regexp="chrome/android/chrome_strings_grd.resources.zip/values-lt/android_chrome_strings.xml"/> + <ignore regexp="chrome/android/chrome_strings_grd.resources.zip/values-ms/android_chrome_strings.xml"/> <ignore regexp="chrome/android/chrome_strings_grd.resources.zip/values-sk/android_chrome_strings.xml"/> <ignore regexp="chrome/android/chrome_strings_grd.resources.zip/values-th/android_chrome_strings.xml"/> <ignore regexp="chrome/android/chrome_strings_grd.resources.zip/values-vi/android_chrome_strings.xml"/>
diff --git a/build/android/resource_sizes.py b/build/android/resource_sizes.py index 3901c71..c986962 100755 --- a/build/android/resource_sizes.py +++ b/build/android/resource_sizes.py
@@ -3,7 +3,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -"""Reports binary size and static initializer metrics for an APK. +"""Reports binary size metrics for an APK. More information at //docs/speed/binary_size/metrics.md. """ @@ -20,6 +20,7 @@ import re import struct import sys +import tempfile import zipfile import zlib @@ -103,8 +104,6 @@ 'trace_rerun_options': [], 'charts': {} } -_DUMP_STATIC_INITIALIZERS_PATH = os.path.join( - host_paths.DIR_SOURCE_ROOT, 'tools', 'linux', 'dump-static-initializers.py') # Macro definitions look like (something, 123) when # enable_resource_whitelist_generation=true. _RC_HEADER_RE = re.compile(r'^#define (?P<name>\w+).* (?P<id>\d+)\)?$') @@ -173,13 +172,6 @@ return section_sizes -def _ParseLibBuildId(so_path, tool_prefix): - """Returns the Build ID of the given native library.""" - stdout = _RunReadelf(so_path, ['-n'], tool_prefix) - match = re.search(r'Build ID: (\w+)', stdout) - return match.group(1) if match else None - - def _ParseManifestAttributes(apk_path): # Check if the manifest specifies whether or not to extract native libs. skip_extract_lib = False @@ -196,46 +188,6 @@ return sdk_version, skip_extract_lib -def CountStaticInitializers(so_path, tool_prefix): - # Mostly copied from //infra/scripts/legacy/scripts/slave/chromium/sizes.py. - def get_elf_section_size(readelf_stdout, section_name): - # Matches: .ctors PROGBITS 000000000516add0 5169dd0 000010 00 WA 0 0 8 - match = re.search(r'\.%s.*$' % re.escape(section_name), - readelf_stdout, re.MULTILINE) - if not match: - return (False, -1) - size_str = re.split(r'\W+', match.group(0))[5] - return (True, int(size_str, 16)) - - # Find the number of files with at least one static initializer. - # First determine if we're 32 or 64 bit - stdout = _RunReadelf(so_path, ['-h'], tool_prefix) - elf_class_line = re.search('Class:.*$', stdout, re.MULTILINE).group(0) - elf_class = re.split(r'\W+', elf_class_line)[1] - if elf_class == 'ELF32': - word_size = 4 - else: - word_size = 8 - - # Then find the number of files with global static initializers. - # NOTE: this is very implementation-specific and makes assumptions - # about how compiler and linker implement global static initializers. - si_count = 0 - stdout = _RunReadelf(so_path, ['-SW'], tool_prefix) - has_init_array, init_array_size = get_elf_section_size(stdout, 'init_array') - if has_init_array: - si_count = init_array_size / word_size - si_count = max(si_count, 0) - return si_count - - -def GetStaticInitializers(so_path, tool_prefix): - output = cmd_helper.GetCmdOutput([_DUMP_STATIC_INITIALIZERS_PATH, '-d', - so_path, '-t', tool_prefix]) - summary = re.search(r'Found \d+ static initializers in (\d+) files.', output) - return output.splitlines()[:-1], int(summary.group(1)) - - def _NormalizeLanguagePaks(translations, normalized_apk_size, factor): english_pak = translations.FindByPattern(r'.*/en[-_][Uu][Ss]\.l?pak') num_translations = translations.GetNumEntries() @@ -345,8 +297,7 @@ return self.ComputeExtractedSize() + self.ComputeZippedSize() -def GenerateApkAnalysis(apk_filename, tool_prefix, out_dir, - unknown_handler=None): +def _DoApkAnalysis(apk_filename, is_bundle, tool_prefix, out_dir, report_func): """Analyse APK to determine size contributions of different file classes.""" file_groups = [] @@ -449,20 +400,22 @@ total_install_size += extracted_size zip_overhead -= actual_size - yield ('Breakdown', group.name + ' size', actual_size, 'bytes') - yield ('InstallBreakdown', group.name + ' size', int(install_size), 'bytes') + report_func('Breakdown', group.name + ' size', actual_size, 'bytes') + report_func('InstallBreakdown', group.name + ' size', int(install_size), + 'bytes') # Only a few metrics are compressed in the first place. # To avoid over-reporting, track uncompressed size only for compressed # entries. if uncompressed_size != actual_size: - yield ('Uncompressed', group.name + ' size', uncompressed_size, 'bytes') + report_func('Uncompressed', group.name + ' size', uncompressed_size, + 'bytes') if group is java_code and is_shared_apk: # Updates are compiled using quicken, but system image uses speed-profile. extracted_size = uncompressed_size * speed_profile_dex_multiplier total_install_size_android_go += extracted_size - yield ('InstallBreakdownGo', group.name + ' size', - actual_size + extracted_size, 'bytes') + report_func('InstallBreakdownGo', group.name + ' size', + actual_size + extracted_size, 'bytes') else: total_install_size_android_go += extracted_size @@ -470,23 +423,23 @@ # * 30 byte entry header + len(file name) # * 46 byte central directory entry + len(file name) # * 0-3 bytes for zipalign. - yield ('Breakdown', 'Zip Overhead', zip_overhead, 'bytes') - yield ('InstallSize', 'APK size', total_apk_size, 'bytes') - yield ('InstallSize', 'Estimated installed size', int(total_install_size), - 'bytes') + report_func('Breakdown', 'Zip Overhead', zip_overhead, 'bytes') + report_func('InstallSize', 'APK size', total_apk_size, 'bytes') + report_func('InstallSize', 'Estimated installed size', + int(total_install_size), 'bytes') if is_shared_apk: - yield ('InstallSize', 'Estimated installed size (Android Go)', - int(total_install_size_android_go), 'bytes') + report_func('InstallSize', 'Estimated installed size (Android Go)', + int(total_install_size_android_go), 'bytes') transfer_size = _CalculateCompressedSize(apk_filename) - yield ('TransferSize', 'Transfer size (deflate)', transfer_size, 'bytes') + report_func('TransferSize', 'Transfer size (deflate)', transfer_size, 'bytes') # Size of main dex vs remaining. main_dex_info = java_code.FindByPattern('classes.dex') if main_dex_info: main_dex_size = main_dex_info.file_size - yield ('Specifics', 'main dex size', main_dex_size, 'bytes') + report_func('Specifics', 'main dex size', main_dex_size, 'bytes') secondary_size = java_code.ComputeUncompressedSize() - main_dex_size - yield ('Specifics', 'secondary dex size', secondary_size, 'bytes') + report_func('Specifics', 'secondary dex size', secondary_size, 'bytes') main_lib_info = native_code.FindLargest() native_code_unaligned_size = 0 @@ -498,12 +451,12 @@ # Size of main .so vs remaining. if lib_info == main_lib_info: main_lib_size = lib_info.file_size - yield ('Specifics', 'main lib size', main_lib_size, 'bytes') + report_func('Specifics', 'main lib size', main_lib_size, 'bytes') secondary_size = native_code.ComputeUncompressedSize() - main_lib_size - yield ('Specifics', 'other lib size', secondary_size, 'bytes') + report_func('Specifics', 'other lib size', secondary_size, 'bytes') for metric_name, size in section_sizes.iteritems(): - yield ('MainLibInfo', metric_name, size, 'bytes') + report_func('MainLibInfo', metric_name, size, 'bytes') # Main metric that we want to monitor for jumps. normalized_apk_size = total_apk_size @@ -521,56 +474,45 @@ # Normalized dex size: size within the zip + size on disk for Android Go # devices (which ~= uncompressed dex size). normalized_apk_size += java_code.ComputeUncompressedSize() - # Avoid noise caused when strings change and translations haven't yet been - # updated. - num_translations = translations.GetNumEntries() - num_stored_translations = stored_translations.GetNumEntries() + if not is_bundle: + # Avoid noise caused when strings change and translations haven't yet been + # updated. + num_translations = translations.GetNumEntries() + num_stored_translations = stored_translations.GetNumEntries() - if num_translations > 1: - # Multipliers found by looking at MonochromePublic.apk and seeing how much - # smaller en-US.pak is relative to the average locale.pak. - normalized_apk_size = _NormalizeLanguagePaks( - translations, normalized_apk_size, 1.17) - if num_stored_translations > 1: - normalized_apk_size = _NormalizeLanguagePaks( - stored_translations, normalized_apk_size, 1.43) - if num_translations + num_stored_translations > 1: - if num_translations == 0: - # WebView stores all locale paks uncompressed. - num_arsc_translations = num_stored_translations - else: - # Monochrome has more configurations than Chrome since it includes - # WebView (which supports more locales), but these should mostly be empty - # so ignore them here. - num_arsc_translations = num_translations - normalized_apk_size += int(_NormalizeResourcesArsc( - apk_filename, arsc.GetNumEntries(), num_arsc_translations, out_dir)) + if num_translations > 1: + # Multipliers found by looking at MonochromePublic.apk and seeing how much + # smaller en-US.pak is relative to the average locale.pak. + normalized_apk_size = _NormalizeLanguagePaks(translations, + normalized_apk_size, 1.17) + if num_stored_translations > 1: + normalized_apk_size = _NormalizeLanguagePaks(stored_translations, + normalized_apk_size, 1.43) + if num_translations + num_stored_translations > 1: + if num_translations == 0: + # WebView stores all locale paks uncompressed. + num_arsc_translations = num_stored_translations + else: + # Monochrome has more configurations than Chrome since it includes + # WebView (which supports more locales), but these should mostly be + # empty so ignore them here. + num_arsc_translations = num_translations + normalized_apk_size += int( + _NormalizeResourcesArsc(apk_filename, arsc.GetNumEntries(), + num_arsc_translations, out_dir)) - yield ('Specifics', 'normalized apk size', normalized_apk_size, 'bytes') + report_func('Specifics', 'normalized apk size', normalized_apk_size, 'bytes') # The "file count" metric cannot be grouped with any other metrics when the # end result is going to be uploaded to the perf dashboard in the HistogramSet # format due to mixed units (bytes vs. zip entries) causing malformed # summaries to be generated. # TODO(https://crbug.com/903970): Remove this workaround if unit mixing is # ever supported. - yield ('FileCount', 'file count', len(apk_contents), 'zip entries') + report_func('FileCount', 'file count', len(apk_contents), 'zip entries') - if unknown_handler is not None: - for info in unknown.AllEntries(): - unknown_handler(info) - - -def PrintApkAnalysis(apk_filename, tool_prefix, out_dir, chartjson=None): - """Calls GenerateApkAnalysis() and report the value.""" - - def PrintUnknown(info): - print('Unknown entry: %s %d' % (info.filename, info.compress_size)) - - title_prefix = os.path.basename(apk_filename) + '_' - for data in GenerateApkAnalysis(apk_filename, tool_prefix, out_dir, - PrintUnknown): - title = title_prefix + data[0] - perf_tests_results_helper.ReportPerfResult(chartjson, title, *data[1:]) + for info in unknown.AllEntries(): + sys.stderr.write( + 'Unknown entry: %s %d\n' % (info.filename, info.compress_size)) def _AnnotatePakResources(out_dir): @@ -600,48 +542,6 @@ return id_name_map, id_header_map -# This method also used by //build/android/gyp/assert_static_initializers.py -def AnalyzeStaticInitializers(apk_filename, tool_prefix, dump_sis, out_dir, - ignored_libs): - # Static initializer counting mostly copies logic in - # infra/scripts/legacy/scripts/slave/chromium/sizes.py. - with zipfile.ZipFile(apk_filename) as z: - so_files = [f for f in z.infolist() - if f.filename.endswith('.so') and f.file_size > 0 - and os.path.basename(f.filename) not in ignored_libs] - # Skip checking static initializers for 32 bit .so files when 64 bit .so files - # are present since the 32 bit versions will be checked by bots that only - # build the 32 bit version. This avoids the complexity of finding 32 bit .so - # files in the output directory in 64 bit builds. - has_64 = any('64' in f.filename for f in so_files) - files_to_check = [f for f in so_files if not has_64 or '64' in f.filename] - - si_count = 0 - for f in files_to_check: - with Unzip(apk_filename, filename=f.filename) as unzipped_so: - si_count += CountStaticInitializers(unzipped_so, tool_prefix) - if dump_sis: - # Print count and list of SIs reported by dump-static-initializers.py. - # Doesn't work well on all archs (particularly arm), which is why - # the readelf method is used for tracking SI counts. - _PrintDumpSIsCount(f.filename, unzipped_so, out_dir, tool_prefix) - return si_count - - -def _PrintDumpSIsCount(apk_so_name, unzipped_so, out_dir, tool_prefix): - lib_name = os.path.basename(apk_so_name).replace('crazy.', '') - so_with_symbols_path = os.path.join(out_dir, 'lib.unstripped', lib_name) - if os.path.exists(so_with_symbols_path): - _VerifyLibBuildIdsMatch(tool_prefix, unzipped_so, so_with_symbols_path) - sis, _ = GetStaticInitializers( - so_with_symbols_path, tool_prefix) - for si in sis: - print(si) - else: - raise Exception('Unstripped .so not found. Looked here: %s', - so_with_symbols_path) - - def _CalculateCompressedSize(file_path): CHUNK_SIZE = 256 * 1024 compressor = zlib.compressobj() @@ -653,7 +553,7 @@ return total_size -def GenerateDexAnalysis(apk_filename): +def _DoDexAnalysis(apk_filename, report_func): sizes, total_size = method_count.ExtractSizesFromZip(apk_filename) dex_metrics = method_count.CONTRIBUTORS_TO_DEX_CACHE @@ -662,21 +562,13 @@ for key in dex_metrics: cumulative_sizes[key] += classes_dex_sizes[key] for key, label in dex_metrics.iteritems(): - yield ('Dex', label, cumulative_sizes[key], 'entries') + report_func('Dex', label, cumulative_sizes[key], 'entries') - yield ('DexCache', 'DexCache', total_size, 'bytes') + report_func('DexCache', 'DexCache', total_size, 'bytes') -def _PrintDexAnalysis(apk_filename, chartjson=None): - title_prefix = os.path.basename(apk_filename) + '_' - for data in GenerateDexAnalysis(apk_filename): - title = title_prefix + data[0] - perf_tests_results_helper.ReportPerfResult(chartjson, title, *data[1:]) - - -def _PrintPatchSizeEstimate(new_apk, builder, bucket, chartjson=None): +def _PrintPatchSizeEstimate(new_apk, builder, bucket, report_func): apk_name = os.path.basename(new_apk) - title = apk_name + '_PatchSizeEstimate' # Reference APK paths have spaces replaced by underscores. builder = builder.replace(' ', '_') old_apk = apk_downloader.MaybeDownloadApk( @@ -688,12 +580,10 @@ tmp_name = os.path.join(tmp, 'patch.tmp') bsdiff = apk_patch_size_estimator.calculate_bsdiff( old_apk, new_apk, None, tmp_name) - perf_tests_results_helper.ReportPerfResult(chartjson, title, - 'BSDiff (gzipped)', bsdiff, 'bytes') + report_func('PatchSizeEstimate', 'BSDiff (gzipped)', bsdiff, 'bytes') fbf = apk_patch_size_estimator.calculate_filebyfile( old_apk, new_apk, None, tmp_name) - perf_tests_results_helper.ReportPerfResult(chartjson, title, - 'FileByFile (gzipped)', fbf, 'bytes') + report_func('PatchSizeEstimate', 'FileByFile (gzipped)', fbf, 'bytes') @contextmanager @@ -708,12 +598,6 @@ yield unzipped_files[0] -def _VerifyLibBuildIdsMatch(tool_prefix, *so_files): - if len(set(_ParseLibBuildId(f, tool_prefix) for f in so_files)) > 1: - raise Exception('Found differing build ids in output directory and apk. ' - 'Your output directory is likely stale.') - - def _ConfigOutDirAndToolsPrefix(out_dir): if out_dir: constants.SetOutputDirectory(os.path.abspath(out_dir)) @@ -732,6 +616,25 @@ return out_dir, tool_prefix +def _Analyze(apk_path, chartjson, args): + metric_prefix = os.path.basename(args.input) + '_' + metric_prefix = metric_prefix.replace('.minimal.apks', '.apk') + + def report_func(title, *args): + # Do not add any new metrics without also documenting them in: + # //docs/speed/binary_size/metrics.md. + title = metric_prefix + title + perf_tests_results_helper.ReportPerfResult(chartjson, title, *args) + + out_dir, tool_prefix = _ConfigOutDirAndToolsPrefix(args.out_dir) + is_bundle = args.input.endswith('.apks') + _DoApkAnalysis(apk_path, is_bundle, tool_prefix, out_dir, report_func) + _DoDexAnalysis(apk_path, report_func) + if args.estimate_patch_size: + _PrintPatchSizeEstimate(apk_path, args.reference_apk_builder, + args.reference_apk_bucket, report_func) + + def main(): argparser = argparse.ArgumentParser(description='Print APK size metrics.') argparser.add_argument('--min-pak-resource-size', @@ -752,14 +655,7 @@ argparser.add_argument('--output-dir', default='.', help='Directory to save chartjson to.') - argparser.add_argument('--dump-static-initializers', - action='store_true', - dest='dump_sis', - help='Run dump-static-initializers.py to get the list' - 'of static initializers (slow).') - argparser.add_argument('--loadable_module', - action='append', - help='Use for libraries added via loadable_modules') + argparser.add_argument('--loadable_module', help='Obsolete (ignored).') argparser.add_argument('--estimate-patch-size', action='store_true', help='Include patch size estimates. Useful for perf ' @@ -772,7 +668,7 @@ argparser.add_argument('--reference-apk-bucket', default=apk_downloader.DEFAULT_BUCKET, help='Storage bucket holding reference APKs.') - argparser.add_argument('apk', help='APK file path.') + argparser.add_argument('input', help='Path to .apk or .apks file to measure.') args = argparser.parse_args() # TODO(bsheedy): Remove this once uses of --chartjson have been removed. @@ -780,27 +676,17 @@ args.output_format = 'chartjson' chartjson = _BASE_CHART.copy() if args.output_format else None - out_dir, tool_prefix = _ConfigOutDirAndToolsPrefix(args.out_dir) - if args.dump_sis and not out_dir: - argparser.error( - '--dump-static-initializers requires --chromium-output-directory') - # Do not add any new metrics without also documenting them in: - # //docs/speed/binary_size/metrics.md. - - PrintApkAnalysis(args.apk, tool_prefix, out_dir, chartjson=chartjson) - _PrintDexAnalysis(args.apk, chartjson=chartjson) - - ignored_libs = args.loadable_module if args.loadable_module else [] - - si_count = AnalyzeStaticInitializers( - args.apk, tool_prefix, args.dump_sis, out_dir, ignored_libs) - perf_tests_results_helper.ReportPerfResult( - chartjson, 'StaticInitializersCount', 'count', si_count, 'count') - - if args.estimate_patch_size: - _PrintPatchSizeEstimate(args.apk, args.reference_apk_builder, - args.reference_apk_bucket, chartjson=chartjson) + if args.input.endswith('.apk'): + _Analyze(args.input, chartjson, args) + elif args.input.endswith('.apks'): + with tempfile.NamedTemporaryFile(suffix='.apk') as f: + with zipfile.ZipFile(args.input) as z: + f.write(z.read('splits/base-master.apk')) + f.flush() + _Analyze(f.name, chartjson, args) + else: + raise Exception('Unknown file type: ' + args.input) if chartjson: results_path = os.path.join(args.output_dir, 'results-chart.json')
diff --git a/build/config/android/internal_rules.gni b/build/config/android/internal_rules.gni index 7bd38f6..20e0b0ff 100644 --- a/build/config/android/internal_rules.gni +++ b/build/config/android/internal_rules.gni
@@ -1106,11 +1106,19 @@ _proguard_enabled && (!defined(invoker.proguard_jar_path) || use_r8) _enable_multidex = defined(invoker.enable_multidex) && invoker.enable_multidex + _enable_main_dex_list = + _enable_multidex && + (!defined(invoker.min_sdk_version) || invoker.min_sdk_version < 21) + if (!_enable_main_dex_list) { + if (defined(invoker.negative_main_dex_globs)) { + not_needed(invoker, [ "negative_main_dex_globs" ]) + } + } assert(!(defined(invoker.input_jars) && _proguard_enabled), "input_jars can't be specified when proguarding a dex.") - if (_enable_multidex) { + if (_enable_main_dex_list) { _main_dex_rules = "//build/android/main_dex_classes.flags" } @@ -1122,11 +1130,6 @@ } if (_proguard_enabled) { - if (defined(invoker.enable_multidex)) { - if (defined(invoker.negative_main_dex_globs)) { - assert(invoker.negative_main_dex_globs != []) - } - } if (_proguarding_with_r8) { _proguard_output_path = invoker.output _proguard_target_name = target_name @@ -1179,8 +1182,7 @@ } if (_enable_multidex && _proguarding_with_r8) { - if (!defined(invoker.min_sdk_version) || - invoker.min_sdk_version < 21) { + if (_enable_main_dex_list) { if (defined(invoker.extra_main_dex_proguard_config)) { args += [ "--main-dex-rules-path", @@ -1195,8 +1197,9 @@ ] inputs += [ _main_dex_rules ] } else { - not_needed(invoker, [ "extra_main_dex_proguard_config" ]) - not_needed([ "_main_dex_rules" ]) + if (defined(invoker.extra_main_dex_proguard_config)) { + not_needed(invoker, [ "extra_main_dex_proguard_config" ]) + } } } @@ -1208,7 +1211,7 @@ } if (!_proguarding_with_r8) { - if (_enable_multidex) { + if (_enable_main_dex_list) { _main_dex_list_path = invoker.output + ".main_dex_list" _main_dex_list_target_name = "${target_name}__main_dex_list" action_with_pydeps(_main_dex_list_target_name) { @@ -1316,13 +1319,15 @@ } if (_enable_multidex) { - args += [ - "--multi-dex", - "--main-dex-list-path", - rebase_path(_main_dex_list_path, root_build_dir), - ] - deps += [ ":${_main_dex_list_target_name}" ] - inputs += [ _main_dex_list_path ] + args += [ "--multi-dex" ] + if (_enable_main_dex_list) { + args += [ + "--main-dex-list-path", + rebase_path(_main_dex_list_path, root_build_dir), + ] + deps += [ ":${_main_dex_list_target_name}" ] + inputs += [ _main_dex_list_path ] + } } if (defined(invoker.input_dex_classpath)) {
diff --git a/build/config/android/rules.gni b/build/config/android/rules.gni index eaf6967..033e297 100644 --- a/build/config/android/rules.gni +++ b/build/config/android/rules.gni
@@ -304,6 +304,8 @@ # jni_package: subdirectory path for generated bindings # jar_file: the path to the .jar. If not provided, will default to the sdk's # android.jar + # always_mangle: Mangle all generated method names. By default, the script + # only mangles methods that cause ambiguity due to method overload. # # deps, public_deps: As normal # @@ -323,6 +325,8 @@ _jar_file = android_sdk_jar } + _always_mangle = defined(invoker.always_mangle) && invoker.always_mangle + _base_output_dir = "${target_gen_dir}/${target_name}/${invoker.jni_package}" _jni_output_dir = "${_base_output_dir}/jni" @@ -369,6 +373,9 @@ if (enable_jni_tracing) { args += [ "--enable_tracing" ] } + if (_always_mangle) { + args += [ "--always_mangle" ] + } } } @@ -2182,7 +2189,10 @@ _final_deps = [] - if (_enable_multidex) { + _enable_main_dex_list = + _enable_multidex && + (!defined(invoker.min_sdk_version) || invoker.min_sdk_version < 21) + if (_enable_main_dex_list) { _generated_proguard_main_dex_config = "$_base_path.resources.main-dex-proguard.txt" } @@ -2248,7 +2258,7 @@ srcjar_path = "${target_gen_dir}/${target_name}.srcjar" r_text_out_path = _compile_resources_rtxt_out proguard_file = _generated_proguard_config - if (_enable_multidex) { + if (_enable_main_dex_list) { proguard_file_main_dex = _generated_proguard_main_dex_config } output = _packaged_resources_path @@ -2595,7 +2605,7 @@ input_jars = [ _lib_dex_path ] input_dex_classpath = "${_rebased_build_config}:final_dex:dependency_dex_files" - if (_enable_multidex) { + if (_enable_main_dex_list) { input_jar_classpath = "${_rebased_build_config}:deps_info:java_runtime_classpath" } @@ -2604,10 +2614,14 @@ output = _final_dex_path enable_multidex = _enable_multidex - if (_enable_multidex) { + if (_enable_main_dex_list) { forward_variables_from(invoker, [ "negative_main_dex_globs" ]) extra_main_dex_proguard_config = _generated_proguard_main_dex_config deps += [ ":$_compile_resources_target" ] + } else if (_enable_multidex) { + if (defined(invoker.negative_main_dex_globs)) { + not_needed(invoker, [ "negative_main_dex_globs" ]) + } } } } else {
diff --git a/build/config/fuchsia/BUILD.gn b/build/config/fuchsia/BUILD.gn index f002df8..59da62e 100644 --- a/build/config/fuchsia/BUILD.gn +++ b/build/config/fuchsia/BUILD.gn
@@ -10,7 +10,7 @@ assert(!is_posix) config("compiler") { - sdk_version_file = rebase_path("${fuchsia_sdk}/.hash") + sdk_version_file = "${fuchsia_sdk}/.hash" sdk_version = read_file(sdk_version_file, "trim string") defines = [ # To force full builds after SDK updates in case of ABI changes. @@ -47,7 +47,7 @@ ] # Add SDK lib dir for -lfdio above. - lib_dirs = [ rebase_path("${fuchsia_sdk}/arch/${current_cpu}/lib") ] + lib_dirs = [ "${fuchsia_sdk}/arch/${current_cpu}/lib" ] # TODO(crbug.com/821951): Clang enables SafeStack by default when targeting # Fuchsia, but it breaks some tests, notably in V8. @@ -77,9 +77,9 @@ ] args = [ - rebase_path("${fuchsia_sdk}/tools/fvm"), - rebase_path("${_target_dir}/fvm.blk"), - rebase_path(blobstore_extended_path), + rebase_path("${fuchsia_sdk}/tools/fvm", root_build_dir), + rebase_path("${_target_dir}/fvm.blk", root_build_dir), + rebase_path(blobstore_extended_path, root_build_dir), _extend_size, ] } @@ -117,8 +117,8 @@ "-O", "qcow2", "-c", - rebase_path(blobstore_extended_path), - rebase_path(blobstore_qcow_path), + rebase_path(blobstore_extended_path, root_build_dir), + rebase_path(blobstore_qcow_path, root_build_dir), ] }
diff --git a/build/config/fuchsia/fidl_library.gni b/build/config/fuchsia/fidl_library.gni index 8243317..acb1132 100644 --- a/build/config/fuchsia/fidl_library.gni +++ b/build/config/fuchsia/fidl_library.gni
@@ -134,7 +134,7 @@ inputs = [ # Depend on the SDK hash, to ensure rebuild if the SDK tools change. - rebase_path("$fuchsia_sdk/.hash"), + "${fuchsia_sdk}/.hash", _response_file, ] @@ -161,7 +161,7 @@ inputs = [ # Depend on the SDK hash, to ensure rebuild if the SDK tools change. - rebase_path("$fuchsia_sdk/.hash"), + "${fuchsia_sdk}/.hash", _json_representation, ] @@ -177,11 +177,11 @@ "-generators", "cpp", "-json", - rebase_path(_json_representation), + rebase_path(_json_representation, root_build_dir), "-include-base", - rebase_path(_output_gen_dir), + rebase_path(_output_gen_dir, root_build_dir), "-output-base", - rebase_path("${_output_base}"), + rebase_path("${_output_base}", root_build_dir), ] } } @@ -198,7 +198,7 @@ inputs = [ # Depend on the SDK hash, to ensure rebuild if the SDK tools change. - rebase_path("$fuchsia_sdk/.hash"), + "${fuchsia_sdk}/.hash", _json_representation, "//build/fuchsia/fidlgen_js/fidl.py", # The schema helper file. ] @@ -210,14 +210,14 @@ script = "//build/fuchsia/fidlgen_js/gen.py" args = [ - rebase_path(_json_representation), + rebase_path(_json_representation, root_build_dir), "--output", - rebase_path("${_output_js_path}"), + rebase_path("${_output_js_path}", root_build_dir), ] data = [] foreach(o, outputs) { - data += [ rebase_path(o) ] + data += [ o ] } } }
diff --git a/build/config/fuchsia/package.gni b/build/config/fuchsia/package.gni index 924eb0a..dc36498 100644 --- a/build/config/fuchsia/package.gni +++ b/build/config/fuchsia/package.gni
@@ -35,7 +35,7 @@ _pm_tool_path = "${fuchsia_sdk}/tools/pm" - _pkg_out_dir = "$root_out_dir/gen/" + get_label_info(pkg.package_name, "dir") + _pkg_out_dir = "${target_gen_dir}/${pkg.package_name}" _runtime_deps_file = "$_pkg_out_dir/${pkg.package_name}.runtime_deps" _archive_manifest = "$_pkg_out_dir/${pkg.package_name}.archive_manifest" _component_manifest = "$_pkg_out_dir/${pkg.package_name}.cmx" @@ -122,7 +122,7 @@ inputs = [ # Depend on the SDK hash, to ensure rebuild if the SDK tools change. - rebase_path("$fuchsia_sdk/.hash"), + "${fuchsia_sdk}/.hash", ] outputs = [ @@ -132,7 +132,7 @@ args = [ rebase_path(_pm_tool_path, root_build_dir), "-k", - rebase_path(_key_file), + rebase_path(_key_file, root_build_dir), "genkey", ] } @@ -150,7 +150,7 @@ inputs = [ # Depend on the SDK hash, to ensure rebuild if the SDK tools change. - rebase_path("$fuchsia_sdk/.hash"), + "${fuchsia_sdk}/.hash", _key_file, ] @@ -161,11 +161,11 @@ args = [ rebase_path(_pm_tool_path, root_build_dir), "-o", - rebase_path(_pkg_out_dir), + rebase_path(_pkg_out_dir, root_build_dir), "-k", - rebase_path(_key_file), + rebase_path(_key_file, root_build_dir), "-m", - rebase_path(_archive_manifest), + rebase_path(_archive_manifest, root_build_dir), "build", ] } @@ -183,7 +183,7 @@ inputs = [ # Depend on the SDK hash, to ensure rebuild if the SDK tools change. - rebase_path("$fuchsia_sdk/.hash"), + "${fuchsia_sdk}/.hash", _meta_far_file, _archive_manifest, ] @@ -195,9 +195,9 @@ args = [ rebase_path(_pm_tool_path, root_build_dir), "-o", - rebase_path(_pkg_out_dir), + rebase_path(_pkg_out_dir, root_build_dir), "-m", - rebase_path(_archive_manifest), + rebase_path(_archive_manifest, root_build_dir), "archive", ] }
diff --git a/build/config/fuchsia/rules.gni b/build/config/fuchsia/rules.gni index 59921c9..5087edd 100644 --- a/build/config/fuchsia/rules.gni +++ b/build/config/fuchsia/rules.gni
@@ -97,7 +97,7 @@ # Arguments used at build time by the runner script generator. args = [ "--script-output-path", - rebase_path(script_path, root_build_dir, root_out_dir), + rebase_path(script_path, root_build_dir), ] if (defined(invoker.use_test_server) && invoker.use_test_server) { @@ -108,11 +108,11 @@ foreach(cur_package, invoker.package_deps) { deps += [ cur_package[0] ] dep_package_path = - "$root_out_dir/gen/" + get_label_info(cur_package[0], "dir") + - "/" + cur_package[1] + "/" + cur_package[1] + ".far" + get_label_info(cur_package[0], "target_gen_dir") + "/" + + cur_package[1] + "/" + cur_package[1] + ".far" args += [ "--package-dep", - rebase_path(dep_package_path, root_out_dir, root_build_dir), + rebase_path(dep_package_path, root_build_dir), ] } } @@ -120,17 +120,17 @@ # Arguments used at runtime by the test runner. args += [ "--runner-script", - rebase_path(runner_script, root_out_dir), + rebase_path(runner_script, root_build_dir), "--output-directory", - rebase_path(root_build_dir, root_build_dir), + ".", "--target-cpu", target_cpu, "--package", - rebase_path(_package_path, root_out_dir, root_build_dir), + rebase_path(_package_path, root_build_dir), "--package-name", _pkg_shortname, "--package-manifest", - rebase_path(_manifest_path), + rebase_path(_manifest_path, root_build_dir), ] if (defined(install_only) && install_only) {
diff --git a/build/config/python.gni b/build/config/python.gni index 4e71e87..81a1690 100644 --- a/build/config/python.gni +++ b/build/config/python.gni
@@ -72,6 +72,11 @@ # # build/print_python_deps.py --inplace build/android/gyp/foo.py # +# Example +# action_with_pydeps("create_foo") { +# script = "myscript.py" +# args = [...] +# } template("action_with_pydeps") { # Read the .pydeps file now. Note that this is done everytime this # template is called, but benchmarking doesn't show any impact on overall @@ -80,16 +85,10 @@ _pydeps_raw = read_file(_pydeps_file, "list lines") # Filter out comments. - # This is a bit convoluted to preserve the value of sources if defined. - _old_sources = [] - if (defined(sources)) { - _old_sources = sources - } set_sources_assignment_filter([ "#*" ]) sources = _pydeps_raw _pydeps = sources - set_sources_assignment_filter([]) - sources = _old_sources + sources = [] action(target_name) { # Forward all variables. Ensure that testonly and visibility are forwarded @@ -115,7 +114,7 @@ # Dependencies are listed relative to the script directory, but inputs # expects paths that are relative to the current BUILD.gn - _script_dir = get_path_info(script, "dir") + _script_dir = get_path_info(_pydeps_file, "dir") inputs += rebase_path(_pydeps, ".", _script_dir) } }
diff --git a/build/config/sanitizers/BUILD.gn b/build/config/sanitizers/BUILD.gn index 9779c983..ddf1abdc 100644 --- a/build/config/sanitizers/BUILD.gn +++ b/build/config/sanitizers/BUILD.gn
@@ -300,19 +300,22 @@ "-asan-globals=0", ] } - if (is_win) { - if (!defined(asan_win_blacklist_path)) { - asan_win_blacklist_path = - rebase_path("//tools/memory/asan/blacklist_win.txt", root_build_dir) + if (asan_use_blacklist) { + if (is_win) { + if (!defined(asan_win_blacklist_path)) { + asan_win_blacklist_path = + rebase_path("//tools/memory/asan/blacklist_win.txt", + root_build_dir) + } + cflags += [ "-fsanitize-blacklist=$asan_win_blacklist_path" ] + } else { + # TODO(rnk): Remove this as discussed in http://crbug.com/427202. + if (!defined(asan_blacklist_path)) { + asan_blacklist_path = + rebase_path("//tools/memory/asan/blacklist.txt", root_build_dir) + } + cflags += [ "-fsanitize-blacklist=$asan_blacklist_path" ] } - cflags += [ "-fsanitize-blacklist=$asan_win_blacklist_path" ] - } else { - # TODO(rnk): Remove this as discussed in http://crbug.com/427202. - if (!defined(asan_blacklist_path)) { - asan_blacklist_path = - rebase_path("//tools/memory/asan/blacklist.txt", root_build_dir) - } - cflags += [ "-fsanitize-blacklist=$asan_blacklist_path" ] } } }
diff --git a/build/config/sanitizers/sanitizers.gni b/build/config/sanitizers/sanitizers.gni index 8c47865..d7b5f25 100644 --- a/build/config/sanitizers/sanitizers.gni +++ b/build/config/sanitizers/sanitizers.gni
@@ -109,6 +109,9 @@ # Default value when unset and use_sanitizer_coverage=true: # trace-pc-guard,indirect-calls sanitizer_coverage_flags = "" + + # Use blacklists from tools/memory/asan when compiling with asan. + asan_use_blacklist = true } # Disable sanitizers for non-default toolchains.
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index c73caa0..91d076b 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -a2bdd07b4fc24dee870c575469c482bbe1f19036 \ No newline at end of file +c0913f45105efa9685a2367400babb72ff6c13cd \ No newline at end of file
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index c355af1..5f39dd2 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -e040dc5d6088c9876f3013a667035093ad0e5092 \ No newline at end of file +f8d3014a84247254f3310e093798d4f902afe1f0 \ No newline at end of file
diff --git a/build/symlink.py b/build/symlink.py index 5a261dc..12942aa 100755 --- a/build/symlink.py +++ b/build/symlink.py
@@ -3,25 +3,32 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -"""Make a symlink and optionally touch a file (to handle dependencies). - -Usage: - symlink.py [options] sources... target - -A sym link to source is created at target. If multiple sources are specfied, -then target is assumed to be a directory, and will contain all the links to +description = """ +Make a symlink and optionally touch a file (to handle dependencies). +""" +usage = "%prog [options] source[ source ...] linkname" +epilog = """ +A sym link to source is created at linkname. If multiple sources are specfied, +then linkname is assumed to be a directory, and will contain all the links to the sources (basenames identical to their source). + +On Windows, this will use hard links (mklink /H) to avoid requiring elevation. +This means that if the original is deleted and replaced, the link will still +have the old contents. This is not expected to interfere with the Chromium +build. """ import errno import optparse import os.path import shutil +import subprocess import sys def Main(argv): - parser = optparse.OptionParser() + parser = optparse.OptionParser(usage=usage, description=description, + epilog=epilog) parser.add_option('-f', '--force', action='store_true') parser.add_option('--touch') @@ -36,10 +43,23 @@ if len(sources) == 1 and not os.path.isdir(target): t = target t = os.path.expanduser(t) - if os.path.realpath(t) == s: + if os.path.realpath(t) == os.path.realpath(s): continue try: - os.symlink(s, t) + # N.B. Python 2.x does not have os.symlink for Windows. + # Python 3 has os.symlink for Windows, but requires either the admin- + # granted privilege SeCreateSymbolicLinkPrivilege or, as of Windows 10 + # 1703, that Developer Mode be enabled. Hard links and junctions do not + # require any extra privileges to create. + if os.name == 'nt': + # mklink does not tolerate /-delimited path names. + t = t.replace('/', '\\') + s = s.replace('/', '\\') + # N.B. This tool only handles file hardlinks, not directory junctions. + subprocess.check_output(['cmd.exe', '/c', 'mklink', '/H', t, s], + stderr=subprocess.STDOUT) + else: + os.symlink(s, t) except OSError, e: if e.errno == errno.EEXIST and options.force: if os.path.isdir(t): @@ -49,6 +69,18 @@ os.symlink(s, t) else: raise + except subprocess.CalledProcessError, e: + # Since subprocess.check_output does not return an easily checked error + # number, in the 'force' case always assume it is 'file already exists' + # and retry. + if options.force: + if os.path.isdir(t): + shutil.rmtree(t, ignore_errors=True) + else: + os.remove(t) + subprocess.check_output(e.cmd, stderr=subprocess.STDOUT) + else: + raise if options.touch:
diff --git a/build/win/BUILD.gn b/build/win/BUILD.gn index 99871f8..9479363 100644 --- a/build/win/BUILD.gn +++ b/build/win/BUILD.gn
@@ -144,6 +144,10 @@ "$root_out_dir/api-ms-win-crt-utility-l1-1-0.dll", "$root_out_dir/ucrtbase${vcrt_suffix}.dll", ] + if (is_debug) { + # For debug builds we also need ucrtbase.dll for d3dcompiler_47.dll + data += [ "$root_out_dir/ucrtbase.dll" ] + } if (is_asan) { if (current_cpu == "x64") { data += [ "$clang_base_path/lib/clang/$clang_version/lib/windows/clang_rt.asan_dynamic-x86_64.dll" ]
diff --git a/cc/paint/paint_canvas.h b/cc/paint/paint_canvas.h index 2577a4f..342e20e4 100644 --- a/cc/paint/paint_canvas.h +++ b/cc/paint/paint_canvas.h
@@ -12,9 +12,12 @@ #include "cc/paint/paint_export.h" #include "cc/paint/paint_image.h" #include "third_party/skia/include/core/SkCanvas.h" -#include "third_party/skia/include/core/SkMetaData.h" #include "third_party/skia/include/core/SkTextBlob.h" +namespace printing { +class MetafileSkia; +} // namespace printing + namespace cc { class SkottieWrapper; class PaintFlags; @@ -42,8 +45,6 @@ PaintCanvas() {} virtual ~PaintCanvas() {} - SkMetaData& getMetaData() { return metadata_; } - // TODO(enne): this only appears to mostly be used to determine if this is // recording or not, so could be simplified or removed. virtual SkImageInfo imageInfo() const = 0; @@ -173,6 +174,7 @@ virtual bool isClipRect() const = 0; virtual const SkMatrix& getTotalMatrix() const = 0; + // Used for printing enum class AnnotationType { URL, NAMED_DESTINATION, @@ -181,12 +183,16 @@ virtual void Annotate(AnnotationType type, const SkRect& rect, sk_sp<SkData> data) = 0; + printing::MetafileSkia* GetPrintingMetafile() const { return metafile_; } + void SetPrintingMetafile(printing::MetafileSkia* metafile) { + metafile_ = metafile; + } // Subclasses can override to handle custom data. virtual void recordCustomData(uint32_t id) {} private: - SkMetaData metadata_; + printing::MetafileSkia* metafile_ = nullptr; DISALLOW_COPY_AND_ASSIGN(PaintCanvas); };
diff --git a/chrome/BUILD.gn b/chrome/BUILD.gn index 51a34b51..475e595 100644 --- a/chrome/BUILD.gn +++ b/chrome/BUILD.gn
@@ -16,6 +16,7 @@ import("//chrome/chrome_paks.gni") import("//chrome/common/features.gni") import("//chrome/process_version_rc_template.gni") +import("//components/gwp_asan/buildflags/buildflags.gni") import("//components/nacl/features.gni") import("//extensions/buildflags/buildflags.gni") import("//media/media_options.gni") @@ -407,7 +408,6 @@ "//chrome/install_static:secondary_module", "//chrome_elf", "//components/crash/content/app", - "//components/gwp_asan/client", "//components/policy:generated", "//content/app/resources", "//content/public/common:service_names", @@ -514,7 +514,6 @@ "//chrome_elf", "//components/browser_watcher:browser_watcher_client", "//components/crash/content/app", - "//components/gwp_asan/client", "//content/public/app:child", "//content/public/common:service_names", "//headless:headless_shell_child_lib", @@ -844,7 +843,7 @@ bundle_data("chrome_framework_helpers") { sources = [ - "$root_out_dir/crashpad_handler", + "$root_out_dir/chrome_crashpad_handler", ] outputs = [ @@ -852,7 +851,7 @@ ] public_deps = [ - "//third_party/crashpad/crashpad/handler:crashpad_handler", + "//components/crash/content/app:chrome_crashpad_handler", ] if (using_sanitizer) { @@ -1334,7 +1333,7 @@ "$root_out_dir/AlertNotificationService.xpc/Contents/MacOS/AlertNotificationService", "$root_out_dir/$chrome_helper_name.app/Contents/MacOS/$chrome_helper_name", "$root_out_dir/$chrome_product_full_name.app/Contents/MacOS/$chrome_product_full_name", - "$root_out_dir/crashpad_handler", + "$root_out_dir/chrome_crashpad_handler", "$root_out_dir/libswiftshader_libEGL.dylib", "$root_out_dir/libswiftshader_libGLESv2.dylib", ] @@ -1365,8 +1364,8 @@ ":chrome_framework", ":chrome_helper_app", "//chrome/browser/ui/cocoa/notifications:alert_notification_xpc_service", + "//components/crash/content/app:chrome_crashpad_handler", "//third_party/breakpad:dump_syms", - "//third_party/crashpad/crashpad/handler:crashpad_handler", "//third_party/swiftshader/src/OpenGL/libEGL:swiftshader_libEGL", "//third_party/swiftshader/src/OpenGL/libGLESv2:swiftshader_libGLESv2", ] @@ -1384,7 +1383,7 @@ "$root_out_dir/$chrome_framework_name.dSYM", "$root_out_dir/$chrome_helper_name.dSYM", "$root_out_dir/$chrome_product_full_name.dSYM", - "$root_out_dir/crashpad_handler.dSYM", + "$root_out_dir/chrome_crashpad_handler.dSYM", "$root_out_dir/libswiftshader_libEGL.dylib.dSYM", "$root_out_dir/libswiftshader_libGLESv2.dylib.dSYM", ] @@ -1405,7 +1404,7 @@ ":chrome_framework", ":chrome_helper_app", "//chrome/browser/ui/cocoa/notifications:alert_notification_xpc_service", - "//third_party/crashpad/crashpad/handler:crashpad_handler", + "//components/crash/content/app:chrome_crashpad_handler", "//third_party/swiftshader/src/OpenGL/libEGL:swiftshader_libEGL", "//third_party/swiftshader/src/OpenGL/libGLESv2:swiftshader_libGLESv2", ] @@ -1422,6 +1421,7 @@ public_deps = [ "//chrome/browser", "//chrome/common", + "//components/gwp_asan/buildflags", "//components/sync", "//components/tracing", ] @@ -1436,6 +1436,10 @@ } } + if (enable_gwp_asan) { + public_deps += [ "//components/gwp_asan/client" ] + } + if (!is_component_build) { assert_no_deps = [ # Blink should not be used in the browser process. In component build this @@ -1463,6 +1467,7 @@ "//chrome/gpu", "//chrome/renderer", "//chrome/utility", + "//components/gwp_asan/buildflags", "//components/services/heap_profiling", "//components/sync", "//components/tracing", @@ -1474,6 +1479,10 @@ if (enable_nacl) { public_deps += [ "//components/nacl/renderer/plugin:nacl_trusted_plugin" ] } + + if (enable_gwp_asan) { + public_deps += [ "//components/gwp_asan/client" ] + } } if (is_win) { @@ -1793,6 +1802,7 @@ "//chrome/gpu", "//chrome/renderer", "//chrome/utility", + "//components/gwp_asan/buildflags", "//components/minidump_uploader", "//components/safe_browsing/android:safe_browsing_mobile", "//components/services/heap_profiling", @@ -1815,6 +1825,10 @@ if (enable_vr) { deps += [ "//third_party/gvr-android-sdk:gvr_shim" ] } + + if (enable_gwp_asan) { + deps += [ "//components/gwp_asan/client" ] + } } }
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index 54bf89a76..6cf74e0 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -5,6 +5,7 @@ import("//build/config/android/chrome_version.gni") import("//build/config/android/config.gni") import("//build/config/android/rules.gni") +import("//build/config/python.gni") import("//build/util/process_version.gni") import("//chrome/android/chrome_common_shared_library.gni") import("//chrome/android/chrome_public_apk_tmpl.gni") @@ -142,22 +143,24 @@ defines = chrome_grit_defines grd_file = "java/strings/android_chrome_strings.grd" outputs = [ + "values/android_chrome_strings.xml", "values-am/android_chrome_strings.xml", "values-ar/android_chrome_strings.xml", "values-bg/android_chrome_strings.xml", + "values-bn/android_chrome_strings.xml", "values-ca/android_chrome_strings.xml", "values-cs/android_chrome_strings.xml", "values-da/android_chrome_strings.xml", "values-de/android_chrome_strings.xml", "values-el/android_chrome_strings.xml", - "values/android_chrome_strings.xml", "values-en-rGB/android_chrome_strings.xml", "values-es/android_chrome_strings.xml", "values-es-rUS/android_chrome_strings.xml", + "values-et/android_chrome_strings.xml", "values-fa/android_chrome_strings.xml", "values-fi/android_chrome_strings.xml", - "values-tl/android_chrome_strings.xml", "values-fr/android_chrome_strings.xml", + "values-gu/android_chrome_strings.xml", "values-hi/android_chrome_strings.xml", "values-hr/android_chrome_strings.xml", "values-hu/android_chrome_strings.xml", @@ -165,11 +168,15 @@ "values-it/android_chrome_strings.xml", "values-iw/android_chrome_strings.xml", "values-ja/android_chrome_strings.xml", + "values-kn/android_chrome_strings.xml", "values-ko/android_chrome_strings.xml", "values-lt/android_chrome_strings.xml", "values-lv/android_chrome_strings.xml", - "values-nl/android_chrome_strings.xml", + "values-ml/android_chrome_strings.xml", + "values-mr/android_chrome_strings.xml", + "values-ms/android_chrome_strings.xml", "values-nb/android_chrome_strings.xml", + "values-nl/android_chrome_strings.xml", "values-pl/android_chrome_strings.xml", "values-pt-rBR/android_chrome_strings.xml", "values-pt-rPT/android_chrome_strings.xml", @@ -180,7 +187,10 @@ "values-sr/android_chrome_strings.xml", "values-sv/android_chrome_strings.xml", "values-sw/android_chrome_strings.xml", + "values-ta/android_chrome_strings.xml", + "values-te/android_chrome_strings.xml", "values-th/android_chrome_strings.xml", + "values-tl/android_chrome_strings.xml", "values-tr/android_chrome_strings.xml", "values-uk/android_chrome_strings.xml", "values-vi/android_chrome_strings.xml", @@ -1803,7 +1813,7 @@ } if (defined(expected_static_initializer_count)) { - action("monochrome_static_initializers") { + action_with_pydeps("monochrome_static_initializers") { script = "//build/android/gyp/assert_static_initializers.py" inputs = [ "$root_build_dir/apks/MonochromePublic.apk",
diff --git a/chrome/android/java/res/drawable/ic_arrow_back_24dp.xml b/chrome/android/java/res/drawable/ic_arrow_back_24dp.xml new file mode 100644 index 0000000..ac26f0e --- /dev/null +++ b/chrome/android/java/res/drawable/ic_arrow_back_24dp.xml
@@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- 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. --> + +<vector xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + tools:targetApi="21" + android:width="24dp" + android:height="24dp" + android:viewportWidth="24" + android:viewportHeight="24" + android:tint="?attr/colorControlNormal"> + <path + android:pathData="M20,11H7.83l5.59,-5.59L12,4l-8,8 8,8 1.41,-1.41L7.83,13H20v-2z" + android:fillColor="@android:color/white"/> +</vector>
diff --git a/chrome/android/java/res/drawable/ic_keyboard.xml b/chrome/android/java/res/drawable/ic_keyboard.xml deleted file mode 100644 index b626cbf..0000000 --- a/chrome/android/java/res/drawable/ic_keyboard.xml +++ /dev/null
@@ -1,16 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- 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. --> - -<vector xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:tools="http://schemas.android.com/tools" - tools:targetApi="21" - android:width="24dp" - android:height="24dp" - android:viewportWidth="24.0" - android:viewportHeight="24.0"> - <path - android:fillColor="@color/default_icon_color" - android:pathData="M 21.55 3.12 L 2.464 3.12 C 1.145 3.12 0.087 4.19 0.087 5.505 L 0.075 17.436 C 0.075 18.755 1.145 19.821 2.464 19.821 L 21.55 19.821 C 22.869 19.821 23.939 18.755 23.939 17.436 L 23.939 5.505 C 23.939 4.19 22.869 3.12 21.55 3.12 Z M 10.814 6.701 L 13.199 6.701 L 13.199 9.086 L 10.814 9.086 L 10.814 6.701 Z M 10.814 10.278 L 13.199 10.278 L 13.199 12.663 L 10.814 12.663 L 10.814 10.278 Z M 7.233 6.701 L 9.622 6.701 L 9.622 9.086 L 7.233 9.086 L 7.233 6.701 Z M 7.233 10.278 L 9.622 10.278 L 9.622 12.663 L 7.233 12.663 L 7.233 10.278 Z M 6.041 12.663 L 3.657 12.663 L 3.657 10.278 L 6.041 10.278 L 6.041 12.663 Z M 6.041 9.086 L 3.657 9.086 L 3.657 6.701 L 6.041 6.701 L 6.041 9.086 Z M 16.78 17.436 L 7.233 17.436 L 7.233 15.052 L 16.78 15.052 L 16.78 17.436 Z M 16.78 12.663 L 14.392 12.663 L 14.392 10.278 L 16.78 10.278 L 16.78 12.663 Z M 16.78 9.086 L 14.392 9.086 L 14.392 6.701 L 16.78 6.701 L 16.78 9.086 Z M 20.357 12.663 L 17.973 12.663 L 17.973 10.278 L 20.357 10.278 L 20.357 12.663 Z M 20.357 9.086 L 17.973 9.086 L 17.973 6.701 L 20.357 6.701 L 20.357 9.086 Z M 12.007 26.983"/> -</vector>
diff --git a/chrome/android/java/res/layout/keyboard_accessory.xml b/chrome/android/java/res/layout/keyboard_accessory.xml index ae44cc1..78fe1cf 100644 --- a/chrome/android/java/res/layout/keyboard_accessory.xml +++ b/chrome/android/java/res/layout/keyboard_accessory.xml
@@ -35,7 +35,8 @@ android:orientation="horizontal" android:background="@color/modern_grey_100"> - <include layout="@layout/keyboard_accessory_tabs"/> + <include layout="@layout/keyboard_accessory_tabs" + android:id="@+id/tabs"/> <View style="@style/VerticalDivider" />
diff --git a/chrome/android/java/res/layout/keyboard_accessory_action.xml b/chrome/android/java/res/layout/keyboard_accessory_action.xml index 07724e3..da345ac 100644 --- a/chrome/android/java/res/layout/keyboard_accessory_action.xml +++ b/chrome/android/java/res/layout/keyboard_accessory_action.xml
@@ -8,12 +8,8 @@ android:gravity="center" android:layout_height="@dimen/keyboard_accessory_bar_item_height" android:layout_width="wrap_content" - android:minHeight="0dp" - android:minWidth="0dp" - android:paddingBottom="0dp" - android:paddingEnd="@dimen/keyboard_accessory_bar_item_padding" - android:paddingStart="@dimen/keyboard_accessory_bar_item_padding" - android:paddingTop="0dp" + android:paddingEnd="@dimen/keyboard_accessory_suggestion_padding" + android:paddingStart="@dimen/keyboard_accessory_suggestion_padding" android:layout_marginBottom="@dimen/keyboard_accessory_half_padding" android:layout_marginTop="@dimen/keyboard_accessory_half_padding" android:textAlignment="center"
diff --git a/chrome/android/java/res/layout/keyboard_accessory_action_modern.xml b/chrome/android/java/res/layout/keyboard_accessory_action_modern.xml new file mode 100644 index 0000000..918d9c9 --- /dev/null +++ b/chrome/android/java/res/layout/keyboard_accessory_action_modern.xml
@@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- 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. --> + +<org.chromium.ui.widget.ButtonCompat + xmlns:android="http://schemas.android.com/apk/res/android" + android:gravity="center" + android:layout_height="@dimen/keyboard_accessory_bar_item_height" + android:layout_width="wrap_content" + android:minHeight="0dp" + android:minWidth="0dp" + android:paddingEnd="@dimen/keyboard_accessory_suggestion_padding" + android:paddingStart="@dimen/keyboard_accessory_suggestion_padding" + android:layout_marginBottom="@dimen/keyboard_accessory_half_padding" + android:layout_marginTop="@dimen/keyboard_accessory_half_padding" + android:layout_marginEnd="@dimen/keyboard_accessory_bar_item_padding" + android:textAlignment="center" + style="@style/FilledButton.Flat" />
diff --git a/chrome/android/java/res/layout/keyboard_accessory_modern.xml b/chrome/android/java/res/layout/keyboard_accessory_modern.xml index f59ae95..236ce961 100644 --- a/chrome/android/java/res/layout/keyboard_accessory_modern.xml +++ b/chrome/android/java/res/layout/keyboard_accessory_modern.xml
@@ -5,7 +5,6 @@ <org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryModernView xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/keyboard_accessory" android:layout_gravity="start|bottom" @@ -40,12 +39,11 @@ <ImageView android:id="@+id/show_keyboard" android:layout_width="wrap_content" - android:layout_weight="0" android:layout_height="match_parent" android:paddingStart="@dimen/keyboard_accessory_bar_item_padding" android:paddingEnd="@dimen/keyboard_accessory_bar_item_padding" - android:paddingTop="@dimen/keyboard_accessory_padding" - android:paddingBottom="@dimen/keyboard_accessory_padding" + android:paddingTop="@dimen/keyboard_accessory_image_top_padding" + android:paddingBottom="@dimen/keyboard_accessory_image_top_padding" android:clickable="true" android:focusable="true" android:contentDescription="@string/keyboard_accessory_sheet_hide" @@ -53,23 +51,9 @@ <android.support.v7.widget.RecyclerView android:id="@+id/bar_items_view" - android:layout_weight="1" android:layout_width="match_parent" - android:layout_height="match_parent"/> - - <View - android:id="@+id/tabs_items_spacer" - android:layout_weight="1" android:layout_height="match_parent" - android:layout_width="match_parent" - android:background="@null" /> - - <View - android:id="@+id/tabs_items_divider" - android:layout_weight="0" - style="@style/VerticalDivider" /> - - <include layout="@layout/keyboard_accessory_tabs" /> + android:clipToPadding="false"/> </LinearLayout> </org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryModernView>
diff --git a/chrome/android/java/res/layout/keyboard_accessory_suggestion.xml b/chrome/android/java/res/layout/keyboard_accessory_suggestion.xml index e3c9287..c79494d 100644 --- a/chrome/android/java/res/layout/keyboard_accessory_suggestion.xml +++ b/chrome/android/java/res/layout/keyboard_accessory_suggestion.xml
@@ -3,16 +3,14 @@ Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> -<TextView +<org.chromium.ui.widget.ChipView xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:app="http://schemas.android.com/apk/res-auto" android:gravity="center" - android:minHeight="@dimen/keyboard_accessory_bar_item_height" android:layout_height="wrap_content" android:layout_width="wrap_content" - android:paddingBottom="0dp" - android:paddingEnd="@dimen/keyboard_accessory_half_padding" - android:paddingStart="@dimen/keyboard_accessory_half_padding" - android:paddingTop="0dp" - android:layout_marginBottom="@dimen/keyboard_accessory_half_padding" - android:layout_marginTop="@dimen/keyboard_accessory_half_padding" - android:textAppearance="@style/TextAppearance.BlackTitle2"/> + android:layout_marginEnd="@dimen/keyboard_accessory_bar_item_padding" + android:layout_marginBottom="@dimen/keyboard_accessory_suggestion_top_bottom_margin" + android:layout_marginTop="@dimen/keyboard_accessory_suggestion_top_bottom_margin" + app:iconWidth="@dimen/keyboard_accessory_bar_item_cc_icon_width" + style="@style/AssistiveChip" />
diff --git a/chrome/android/java/res/layout/keyboard_accessory_suggestion_modern.xml b/chrome/android/java/res/layout/keyboard_accessory_suggestion_modern.xml deleted file mode 100644 index 5d22bdf..0000000 --- a/chrome/android/java/res/layout/keyboard_accessory_suggestion_modern.xml +++ /dev/null
@@ -1,17 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- 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. --> - -<org.chromium.ui.widget.ChipView - xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto" - android:gravity="center" - android:layout_height="wrap_content" - android:layout_width="wrap_content" - android:layout_marginEnd="@dimen/keyboard_accessory_half_padding" - android:layout_marginStart="@dimen/keyboard_accessory_half_padding" - android:layout_marginBottom="@dimen/keyboard_accessory_suggestion_top_bottom_margin" - android:layout_marginTop="@dimen/keyboard_accessory_suggestion_top_bottom_margin" - app:iconWidth="32dp" - style="@style/AssistiveChip" />
diff --git a/chrome/android/java/res/layout/keyboard_accessory_tabs.xml b/chrome/android/java/res/layout/keyboard_accessory_tabs.xml index 21e37655..4aa193f2 100644 --- a/chrome/android/java/res/layout/keyboard_accessory_tabs.xml +++ b/chrome/android/java/res/layout/keyboard_accessory_tabs.xml
@@ -6,11 +6,9 @@ <org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryTabLayoutView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" - android:id="@+id/tabs" - app:tabIndicatorHeight="0dp" + app:tabIndicatorHeight="@dimen/divider_height" app:tabTextColor="@color/default_icon_color" app:tabSelectedTextColor="@color/default_icon_color_blue" android:layout_gravity="end" android:layout_width="wrap_content" - android:layout_weight="0" - android:layout_height="match_parent"/> \ No newline at end of file + android:layout_height="@dimen/keyboard_accessory_tab_size"/>
diff --git a/chrome/android/java/res/layout/signin_view.xml b/chrome/android/java/res/layout/signin_view.xml index 7d91af6..7fed00f 100644 --- a/chrome/android/java/res/layout/signin_view.xml +++ b/chrome/android/java/res/layout/signin_view.xml
@@ -105,7 +105,7 @@ android:layout_height="wrap_content" android:layout_below="@id/signin_account_picker" android:layout_marginStart="16dp" - android:layout_marginTop="28dp" + android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:textAppearance="@style/TextAppearance.BlackTitle1" tools:text="@string/signin_sync_title"/> @@ -123,7 +123,7 @@ style="@style/HorizontalDivider" android:layout_below="@id/signin_sync_description" android:layout_marginStart="16dp" - android:layout_marginTop="12dp" + android:layout_marginTop="16dp" android:layout_marginEnd="16dp"/> <TextView android:id="@+id/signin_details_description"
diff --git a/chrome/android/java/res/values-v17/styles.xml b/chrome/android/java/res/values-v17/styles.xml index da76acec..e874173 100644 --- a/chrome/android/java/res/values-v17/styles.xml +++ b/chrome/android/java/res/values-v17/styles.xml
@@ -828,6 +828,41 @@ <item name="android:textColor">@color/suggestion_url_dark_modern</item> </style> + <style name="TextAppearance.OmniboxAnswerTextLarge"> + <item name="android:textSize">@dimen/text_size_large_leading</item> + <item name="android:textColor">@color/answers_answer_text</item> + </style> + + <style name="TextAppearance.OmniboxAnswerTextMedium"> + <item name="android:textSize">@dimen/text_size_medium_leading</item> + <item name="android:textColor">@color/answers_answer_text</item> + </style> + + <style name="TextAppearance.OmniboxAnswerTextSmall"> + <item name="android:textSize">@dimen/text_size_small</item> + <item name="android:textColor">@color/answers_answer_text</item> + </style> + + <style name="TextAppearance.OmniboxAnswerDescriptionNegative"> + <item name="android:textSize">@dimen/text_size_small_leading</item> + <item name="android:textColor">@color/answers_description_text_negative</item> + </style> + + <style name="TextAppearance.OmniboxAnswerDescriptionPositive"> + <item name="android:textSize">@dimen/text_size_small_leading</item> + <item name="android:textColor">@color/answers_description_text_positive</item> + </style> + + <style name="TextAppearance.OmniboxAnswerDescriptionNegativeSmall"> + <item name="android:textSize">@dimen/text_size_small</item> + <item name="android:textColor">@color/answers_description_text_negative</item> + </style> + + <style name="TextAppearance.OmniboxAnswerDescriptionPositiveSmall"> + <item name="android:textSize">@dimen/text_size_small</item> + <item name="android:textColor">@color/answers_description_text_positive</item> + </style> + <style name="OmniboxSuggestionIconButton"> <item name="android:background">?attr/selectableItemBackground</item> <item name="android:layout_width">@dimen/min_touch_target_size</item>
diff --git a/chrome/android/java/res/values/dimens.xml b/chrome/android/java/res/values/dimens.xml index 42403e8..c993ac5 100644 --- a/chrome/android/java/res/values/dimens.xml +++ b/chrome/android/java/res/values/dimens.xml
@@ -130,11 +130,11 @@ <!-- Autofill keyboard accessory dimensions --> <dimen name="keyboard_accessory_bar_item_height">36dp</dimen> - <dimen name="keyboard_accessory_bar_item_padding">16dp</dimen> + <dimen name="keyboard_accessory_bar_item_padding">8dp</dimen> <dimen name="keyboard_accessory_half_padding">6dp</dimen> <dimen name="keyboard_accessory_height">48dp</dimen> <dimen name="keyboard_accessory_height_with_shadow">56dp</dimen> - <dimen name="keyboard_accessory_padding">6dp</dimen> + <dimen name="keyboard_accessory_image_top_padding">12dp</dimen> <dimen name="keyboard_accessory_shadow">5dp</dimen> <dimen name="keyboard_accessory_sheet_height">330dp</dimen> <dimen name="keyboard_accessory_sheet_padding">8dp</dimen> @@ -143,6 +143,8 @@ <dimen name="keyboard_accessory_suggestion_offset">12dp</dimen> <dimen name="keyboard_accessory_suggestion_height">48dp</dimen> <dimen name="keyboard_accessory_suggestion_icon_size">20dp</dimen> + <dimen name="keyboard_accessory_bar_item_cc_icon_width">32dp</dimen> + <dimen name="keyboard_accessory_tab_size">@dimen/keyboard_accessory_height</dimen> <!-- Password generation popup dimensions --> <dimen name="password_generation_divider_height">1dp</dimen>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ItemChooserDialog.java b/chrome/android/java/src/org/chromium/chrome/browser/ItemChooserDialog.java index 591fa49..d2f03c92 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ItemChooserDialog.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ItemChooserDialog.java
@@ -97,10 +97,10 @@ if (icon == null ^ mIcon == null) return false; - // On Android O and above, Drawable#getConstantState() always returns a different value, - // so it does not make sense to compare it. + // On Android NMR1 and above, Drawable#getConstantState() always returns a different + // value, so it does not make sense to compare it. // TODO(crbug.com/773043): Find a way to compare the icons. - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O && mIcon != null + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1 && mIcon != null && !mIcon.getConstantState().equals(icon.getConstantState())) { return false; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/LaunchIntentDispatcher.java b/chrome/android/java/src/org/chromium/chrome/browser/LaunchIntentDispatcher.java index 3c0cd76..50e7f90 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/LaunchIntentDispatcher.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/LaunchIntentDispatcher.java
@@ -442,7 +442,7 @@ Intent newIntent = new Intent(mIntent); Class<?> tabbedActivityClass = null; - if (CommandLine.getInstance().hasSwitch(ChromeSwitches.NO_TOUCH_MODE)) { + if (FeatureUtilities.isNoTouchModeEnabled()) { // When in No Touch Mode we don't support tabs, and replace the TabbedActivity with the // NoTouchActivity. tabbedActivityClass = NoTouchActivity.class;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryCoordinator.java index b2d3019..77e41e5 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryCoordinator.java
@@ -8,6 +8,7 @@ import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.BOTTOM_OFFSET_PX; import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.KEYBOARD_TOGGLE_VISIBLE; import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.SHOW_KEYBOARD_CALLBACK; +import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.TAB_LAYOUT_ITEM; import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.VISIBLE; import android.support.annotation.Nullable; @@ -118,16 +119,19 @@ */ public KeyboardAccessoryCoordinator(VisibilityDelegate visibilityDelegate, ViewProvider<KeyboardAccessoryView> viewProvider) { - PropertyModel model = new PropertyModel - .Builder(BAR_ITEMS, VISIBLE, BOTTOM_OFFSET_PX, - KEYBOARD_TOGGLE_VISIBLE, SHOW_KEYBOARD_CALLBACK) - .with(BAR_ITEMS, new ListModel<>()) - .with(VISIBLE, false) - .with(KEYBOARD_TOGGLE_VISIBLE, false) - .build(); + PropertyModel model = + new PropertyModel + .Builder(BAR_ITEMS, VISIBLE, BOTTOM_OFFSET_PX, TAB_LAYOUT_ITEM, + KEYBOARD_TOGGLE_VISIBLE, SHOW_KEYBOARD_CALLBACK) + .with(BAR_ITEMS, new ListModel<>()) + .with(VISIBLE, false) + .with(KEYBOARD_TOGGLE_VISIBLE, false) + .build(); mMediator = new KeyboardAccessoryMediator( - model, visibilityDelegate, mTabLayout.getTabSwitchingDelegate()); - viewProvider.whenLoaded(barView -> mTabLayout.assignNewView(barView.getTabLayout())); + model, visibilityDelegate, mTabLayout.getTabSwitchingDelegate(), mTabLayout); + if (!ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_KEYBOARD_ACCESSORY)) { + viewProvider.whenLoaded(barView -> mTabLayout.assignNewView(barView.getTabLayout())); + } mTabLayout.setTabObserver(mMediator); PropertyModelChangeProcessor
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryMediator.java index 35fa048..8485d57 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryMediator.java
@@ -9,17 +9,21 @@ import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.BOTTOM_OFFSET_PX; import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.KEYBOARD_TOGGLE_VISIBLE; import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.SHOW_KEYBOARD_CALLBACK; +import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.TAB_LAYOUT_ITEM; import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.VISIBLE; import android.support.annotation.Nullable; import android.support.annotation.Px; import org.chromium.base.VisibleForTesting; +import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryCoordinator.TabSwitchingDelegate; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryCoordinator.VisibilityDelegate; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.Action; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.AutofillBarItem; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.BarItem; +import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.TabLayoutBarItem; +import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.TabLayoutBarItem.TabLayoutCallbacks; import org.chromium.components.autofill.AutofillDelegate; import org.chromium.components.autofill.AutofillSuggestion; import org.chromium.components.autofill.PopupItemId; @@ -51,13 +55,17 @@ private boolean mShowIfNotEmpty; KeyboardAccessoryMediator(PropertyModel model, VisibilityDelegate visibilityDelegate, - TabSwitchingDelegate tabSwitcher) { + TabSwitchingDelegate tabSwitcher, TabLayoutCallbacks tabLayoutCallbacks) { mModel = model; mVisibilityDelegate = visibilityDelegate; mTabSwitcher = tabSwitcher; // Add mediator as observer so it can use model changes as signal for accessory visibility. mModel.set(SHOW_KEYBOARD_CALLBACK, this::closeSheet); + mModel.set(TAB_LAYOUT_ITEM, new TabLayoutBarItem(tabLayoutCallbacks)); + if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_KEYBOARD_ACCESSORY)) { + mModel.get(BAR_ITEMS).add(mModel.get(TAB_LAYOUT_ITEM)); + } mModel.get(BAR_ITEMS).addObserver(this); mModel.addObserver(this); } @@ -78,6 +86,9 @@ + typeId; List<BarItem> retainedItems = collectItemsToRetain(AccessoryAction.AUTOFILL_SUGGESTION); retainedItems.addAll(toBarItems(suggestions, delegate)); + if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_KEYBOARD_ACCESSORY)) { + retainedItems.add(retainedItems.size(), mModel.get(TAB_LAYOUT_ITEM)); + } mModel.get(BAR_ITEMS).set(retainedItems); }; } @@ -88,6 +99,9 @@ assert typeId != DEFAULT_TYPE : "Did not specify which Action type has been updated."; List<BarItem> retainedItems = collectItemsToRetain(typeId); retainedItems.addAll(0, toBarItems(actions)); + if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_KEYBOARD_ACCESSORY)) { + retainedItems.add(retainedItems.size(), mModel.get(TAB_LAYOUT_ITEM)); + } mModel.get(BAR_ITEMS).set(retainedItems); } @@ -205,7 +219,7 @@ return; } if (propertyKey == BOTTOM_OFFSET_PX || propertyKey == SHOW_KEYBOARD_CALLBACK - || propertyKey == KEYBOARD_TOGGLE_VISIBLE) { + || propertyKey == KEYBOARD_TOGGLE_VISIBLE || propertyKey == TAB_LAYOUT_ITEM) { return; } assert false : "Every property update needs to be handled explicitly!"; @@ -241,6 +255,10 @@ } boolean hasContents() { + if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_KEYBOARD_ACCESSORY)) { + return mModel.get(BAR_ITEMS).size() > 1 + || mTabSwitcher.hasTabs(); // Ignore tab switcher item. + } return mModel.get(BAR_ITEMS).size() > 0 || mTabSwitcher.hasTabs(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryMetricsRecorder.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryMetricsRecorder.java index 9d2a0d5..b87f89c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryMetricsRecorder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryMetricsRecorder.java
@@ -76,8 +76,7 @@ recordFirstImpression(); maybeRecordBarBucket(AccessoryBarContents.WITH_AUTOFILL_SUGGESTIONS); maybeRecordBarBucket(AccessoryBarContents.WITH_TABS); - recordUnrecordedList(mModel.get(KeyboardAccessoryProperties.BAR_ITEMS), 0, - mModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size()); + recordGeneralActionTypes(); } else { mRecordedBarBuckets.clear(); mRecordedActionImpressions.clear(); @@ -100,17 +99,12 @@ * @param count Number of elements starting with |first| that were added or changed. */ private void recordUnrecordedList(ListObservable list, int first, int count) { - if (!mModel.get(KeyboardAccessoryProperties.VISIBLE)) return; - if (list != mModel.get(BAR_ITEMS)) return; - // Remove all changed items, so changes are treated as new recordings. - for (int index = first; index < first + count; ++index) { - BarItem barItem = mModel.get(BAR_ITEMS).get(index); - mRecordedActionImpressions.remove(barItem.getViewType()); - } + assert list + == mModel.get(BAR_ITEMS) : "Tried to record metrics for unknown list " + list; // Record any unrecorded type, but not more than once (i.e. one set of suggestion). for (int index = first; index < first + count; ++index) { KeyboardAccessoryData.Action action = mModel.get(BAR_ITEMS).get(index).getAction(); - if (action == null) continue; // Ignore! + if (action == null) continue; // Item is no relevant action. maybeRecordBarBucket(action.getActionType() == AccessoryAction.AUTOFILL_SUGGESTION ? AccessoryBarContents.WITH_AUTOFILL_SUGGESTIONS : AccessoryBarContents.WITH_ACTIONS);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryModernView.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryModernView.java index 58e4612..7d5b8d4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryModernView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryModernView.java
@@ -5,9 +5,12 @@ package org.chromium.chrome.browser.autofill.keyboard_accessory; import android.content.Context; +import android.support.v4.view.ViewCompat; import android.support.v7.content.res.AppCompatResources; +import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.View; +import android.view.ViewGroup; import android.widget.ImageView; import org.chromium.chrome.R; @@ -17,11 +20,76 @@ * suggestions and manual entry points assisting the user in filling forms. */ class KeyboardAccessoryModernView extends KeyboardAccessoryView { - private View mTabsItemsDivider; - private View mTabsItemsSpacer; private ImageView mKeyboardToggle; /** + * This decoration ensures that the last item is right-aligned. + * To do this, it subtracts the widths, margins and offsets of all items in the recycler view + * from the RecyclerView's total width. If the items fill the whole recycler view, the last item + * uses the same offset as all other items. + */ + private class StickyLastItemDecoration extends HorizontalDividerItemDecoration { + StickyLastItemDecoration() { + super(0); + } + + @Override + protected int getItemOffsetInternal( + final View view, final RecyclerView parent, RecyclerView.State state) { + int minimalOffset = super.getItemOffsetInternal(view, parent, state); + if (!isLastItem(parent, view, parent.getAdapter().getItemCount())) return minimalOffset; + if (view.getWidth() == 0 && state.didStructureChange()) { + // When the RecyclerView is first created, its children aren't measured yet and miss + // dimensions. Therefore, estimate the offset and recalculate after UI has loaded. + view.post(parent::invalidateItemDecorations); + return parent.getWidth() - estimateLastElementWidth(view); + } + return Math.max(getSpaceLeftInParent(parent), minimalOffset); + } + + private int getSpaceLeftInParent(RecyclerView parent) { + int spaceLeftInParent = parent.getWidth(); + spaceLeftInParent -= getOccupiedSpaceByChildren(parent); + spaceLeftInParent -= getOccupiedSpaceByChildrenOffsets(parent); + spaceLeftInParent -= parent.getPaddingEnd() + parent.getPaddingStart(); + return spaceLeftInParent; + } + + private int estimateLastElementWidth(View view) { + assert view instanceof ViewGroup; + return ((ViewGroup) view).getChildCount() + * getContext().getResources().getDimensionPixelSize( + R.dimen.keyboard_accessory_tab_size); + } + + private int getOccupiedSpaceByChildren(RecyclerView parent) { + int occupiedSpace = 0; + for (int i = 0; i < parent.getChildCount(); i++) { + occupiedSpace += getOccupiedSpaceForView(parent.getChildAt(i)); + } + return occupiedSpace; + } + + private int getOccupiedSpaceForView(View view) { + int occupiedSpace = view.getWidth(); + ViewGroup.LayoutParams lp = view.getLayoutParams(); + if (lp instanceof MarginLayoutParams) { + occupiedSpace += ((MarginLayoutParams) lp).leftMargin; + occupiedSpace += ((MarginLayoutParams) lp).rightMargin; + } + return occupiedSpace; + } + + private int getOccupiedSpaceByChildrenOffsets(RecyclerView parent) { + return (parent.getChildCount() - 1) * super.getItemOffsetInternal(null, null, null); + } + + private boolean isLastItem(RecyclerView parent, View view, int itemCount) { + return parent.getChildAdapterPosition(view) == itemCount - 1; + } + } + + /** * Constructor for inflating from XML. */ public KeyboardAccessoryModernView(Context context, AttributeSet attrs) { @@ -31,17 +99,18 @@ @Override protected void onFinishInflate() { super.onFinishInflate(); - mTabsItemsDivider = findViewById(R.id.tabs_items_divider); - mTabsItemsSpacer = findViewById(R.id.tabs_items_spacer); mKeyboardToggle = findViewById(R.id.show_keyboard); mKeyboardToggle.setImageDrawable( - AppCompatResources.getDrawable(getContext(), R.drawable.ic_keyboard)); + AppCompatResources.getDrawable(getContext(), R.drawable.ic_arrow_back_24dp)); + + int pad = getResources().getDimensionPixelSize(R.dimen.keyboard_accessory_bar_item_padding); + // Ensure the last element (although scrollable) is always end-aligned. + mBarItemsView.addItemDecoration(new StickyLastItemDecoration()); + ViewCompat.setPaddingRelative(mBarItemsView, pad, 0, 0, 0); } void setKeyboardToggleVisibility(boolean hasActiveTab) { mKeyboardToggle.setVisibility(hasActiveTab ? VISIBLE : GONE); - mTabsItemsSpacer.setVisibility(hasActiveTab ? VISIBLE : GONE); - mTabsItemsDivider.setVisibility(hasActiveTab ? GONE : VISIBLE); mBarItemsView.setVisibility(hasActiveTab ? GONE : VISIBLE); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryModernViewBinder.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryModernViewBinder.java index 5a8384ab..f8e1c05d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryModernViewBinder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryModernViewBinder.java
@@ -6,6 +6,7 @@ import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.KEYBOARD_TOGGLE_VISIBLE; import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.SHOW_KEYBOARD_CALLBACK; +import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.TAB_LAYOUT_ITEM; import android.view.View; import android.view.ViewGroup; @@ -13,6 +14,7 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.AutofillBarItem; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.BarItem; +import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.TabLayoutBarItem; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryViewBinder.BarItemViewHolder; import org.chromium.ui.modelutil.PropertyKey; import org.chromium.ui.modelutil.PropertyModel; @@ -27,9 +29,11 @@ switch (viewType) { case BarItem.Type.SUGGESTION: return new BarItemChipViewHolder(parent); - case BarItem.Type.TAB_SWITCHER: + case BarItem.Type.TAB_LAYOUT: return new TabItemViewHolder(parent); - case BarItem.Type.ACTION_BUTTON: // Intentional fallthrough. Use legacy handling. + case BarItem.Type.ACTION_BUTTON: + return new KeyboardAccessoryViewBinder.BarItemTextViewHolder( + parent, R.layout.keyboard_accessory_action_modern); case BarItem.Type.COUNT: // Intentional fallthrough. Use legacy handling. break; } @@ -38,7 +42,7 @@ static class BarItemChipViewHolder extends BarItemViewHolder<AutofillBarItem, ChipView> { BarItemChipViewHolder(ViewGroup parent) { - super(parent, R.layout.keyboard_accessory_suggestion_modern); + super(parent, R.layout.keyboard_accessory_suggestion); } @Override @@ -56,15 +60,25 @@ } static class TabItemViewHolder - extends BarItemViewHolder<BarItem, KeyboardAccessoryTabLayoutView> { + extends BarItemViewHolder<TabLayoutBarItem, KeyboardAccessoryTabLayoutView> { + private TabLayoutBarItem mTabItem; private KeyboardAccessoryTabLayoutView mTabLayout; TabItemViewHolder(ViewGroup parent) { - super(parent, R.layout.keyboard_accessory_suggestion); + super(parent, R.layout.keyboard_accessory_tabs); } @Override - protected void bind(BarItem item, KeyboardAccessoryTabLayoutView view) {} + protected void bind(TabLayoutBarItem tabItem, KeyboardAccessoryTabLayoutView tabLayout) { + mTabItem = tabItem; + mTabLayout = tabLayout; + tabItem.notifyAboutViewCreation(tabLayout); + } + + @Override + protected void recycle() { + mTabItem.notifyAboutViewDestruction(mTabLayout); + } } public static void bind( @@ -76,6 +90,8 @@ modernView.setKeyboardToggleVisibility(model.get(KEYBOARD_TOGGLE_VISIBLE)); } else if (propertyKey == SHOW_KEYBOARD_CALLBACK) { modernView.setShowKeyboardCallback(model.get(SHOW_KEYBOARD_CALLBACK)); + } else if (propertyKey == TAB_LAYOUT_ITEM) { + // No binding required. } else { assert wasBound : "Every possible property update needs to be handled!"; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryProperties.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryProperties.java index cfdb3fb..2b4ede2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryProperties.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryProperties.java
@@ -33,6 +33,8 @@ static final WritableIntPropertyKey BOTTOM_OFFSET_PX = new WritableIntPropertyKey("offset"); static final WritableBooleanPropertyKey KEYBOARD_TOGGLE_VISIBLE = new WritableBooleanPropertyKey("toggle_visible"); + static final WritableObjectPropertyKey<TabLayoutBarItem> TAB_LAYOUT_ITEM = + new WritableObjectPropertyKey<>("tab_layout_item"); static final WritableObjectPropertyKey<Runnable> SHOW_KEYBOARD_CALLBACK = new WritableObjectPropertyKey<>("keyboard_callback"); @@ -44,12 +46,12 @@ /** * This type is used to infer which type of view will represent this item. */ - @IntDef({Type.ACTION_BUTTON, Type.SUGGESTION, Type.TAB_SWITCHER, Type.COUNT}) + @IntDef({Type.ACTION_BUTTON, Type.SUGGESTION, Type.TAB_LAYOUT, Type.COUNT}) @Retention(RetentionPolicy.SOURCE) public @interface Type { int ACTION_BUTTON = 0; int SUGGESTION = 1; - int TAB_SWITCHER = 2; + int TAB_LAYOUT = 2; int COUNT = 3; } private @Type int mType; @@ -91,8 +93,8 @@ case Type.SUGGESTION: typeName = "SUGGESTION"; break; - case Type.TAB_SWITCHER: - typeName = "TAB_SWITCHER"; + case Type.TAB_LAYOUT: + typeName = "TAB_LAYOUT"; break; } return typeName + ": " + mAction; @@ -126,5 +128,47 @@ } } + /** + * A tab layout in a {@link RecyclerView} can be destroyed and recreated whenever it is + * scrolled out of/into view. This wrapper allows to trigger a callback whenever the view is + * recreated so it can be bound to its component. + */ + public static final class TabLayoutBarItem extends BarItem { + /** + * These callbacks are triggered when the view corresponding to the tab layout is bound or + * unbound which provides opportunity to initialize and clean up. + */ + public interface TabLayoutCallbacks { + /** + * Called when the this item is bound to a view. It's useful for setting up MCPs that + * need the view for initialization. + * @param tabs The {@link KeyboardAccessoryTabLayoutView} representing this item. + */ + void onTabLayoutBound(KeyboardAccessoryTabLayoutView tabs); + + /** + * Called right before the view currently representing this item gets recycled. + * It's useful for cleaning up Adapters and MCPs. + * @param tabs The {@link KeyboardAccessoryTabLayoutView} representing this item. + */ + void onTabLayoutUnbound(KeyboardAccessoryTabLayoutView tabs); + } + + private final TabLayoutCallbacks mTabLayoutCallbacks; + + public TabLayoutBarItem(TabLayoutCallbacks tabLayoutCallbacks) { + super(Type.TAB_LAYOUT, null); + mTabLayoutCallbacks = tabLayoutCallbacks; + } + + public void notifyAboutViewCreation(KeyboardAccessoryTabLayoutView tabs) { + mTabLayoutCallbacks.onTabLayoutBound(tabs); + } + + public void notifyAboutViewDestruction(KeyboardAccessoryTabLayoutView tabs) { + mTabLayoutCallbacks.onTabLayoutUnbound(tabs); + } + } + private KeyboardAccessoryProperties() {} }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryTabLayoutCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryTabLayoutCoordinator.java index 4a3b6b4..7140cf6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryTabLayoutCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryTabLayoutCoordinator.java
@@ -17,11 +17,14 @@ import org.chromium.ui.modelutil.PropertyModel; import org.chromium.ui.modelutil.PropertyModelChangeProcessor; +import java.util.HashMap; + /** * This component reflects the state of selected tabs in the keyboard accessory. It can be assigned * to multiple {@link TabLayout}s and will keep them in sync. */ -class KeyboardAccessoryTabLayoutCoordinator { +class KeyboardAccessoryTabLayoutCoordinator + implements KeyboardAccessoryProperties.TabLayoutBarItem.TabLayoutCallbacks { private final PropertyModel mModel = new PropertyModel.Builder(TABS, ACTIVE_TAB, TAB_SELECTION_CALLBACKS) .with(TABS, new ListModel<>()) @@ -29,6 +32,8 @@ .build(); private final KeyboardAccessoryTabLayoutMediator mMediator; + private final HashMap<TabLayout, TemporaryTabLayoutBindings> mBindings = new HashMap<>(); + /** * This observer gets notified when a tab get selected, reselected or when any tab changes. */ @@ -53,6 +58,24 @@ void onTabsChanged(); } + private class TemporaryTabLayoutBindings { + private PropertyModelChangeProcessor mMcp; + private TabLayout.TabLayoutOnPageChangeListener mOnPageChangeListener; + + TemporaryTabLayoutBindings(KeyboardAccessoryTabLayoutView tabLayout) { + mMcp = PropertyModelChangeProcessor.create( + mModel, tabLayout, KeyboardAccessoryTabLayoutViewBinder::bind); + mOnPageChangeListener = new TabLayout.TabLayoutOnPageChangeListener(tabLayout); + mMediator.addPageChangeListener(mOnPageChangeListener); + } + + void destroy() { + mMediator.removePageChangeListener(mOnPageChangeListener); + mMcp.destroy(); + mOnPageChangeListener = null; + } + } + /** * Creates the {@link KeyboardAccessoryTabLayoutViewBinder} that is linked to the * {@link ListModelChangeProcessor} that connects the given @@ -77,12 +100,25 @@ mMediator = new KeyboardAccessoryTabLayoutMediator(mModel); } + @Override + public void onTabLayoutBound(KeyboardAccessoryTabLayoutView tabLayout) { + if (!mBindings.containsKey(tabLayout)) { + mBindings.put(tabLayout, new TemporaryTabLayoutBindings(tabLayout)); + } + } + + @Override + public void onTabLayoutUnbound(KeyboardAccessoryTabLayoutView tabLayout) { + TemporaryTabLayoutBindings binding = mBindings.remove(tabLayout); + if (binding != null) binding.destroy(); + } + /** * Binds the given view to its model using the {@link KeyboardAccessoryTabLayoutViewBinder}. * @param tabLayout A {@link TabLayout}. */ public void assignNewView(TabLayout tabLayout) { - mMediator.setPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); + mMediator.addPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); PropertyModelChangeProcessor.create(mModel, (KeyboardAccessoryTabLayoutView) tabLayout, KeyboardAccessoryTabLayoutViewBinder::bind); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryTabLayoutMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryTabLayoutMediator.java index a8ad3cc5..5b8417b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryTabLayoutMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryTabLayoutMediator.java
@@ -18,6 +18,9 @@ import org.chromium.ui.modelutil.PropertyModel; import org.chromium.ui.modelutil.PropertyObservable; +import java.util.HashSet; +import java.util.Set; + /** * This mediator observes and changes a {@link PropertyModel} that contains the visual appearance of * a {@link TabLayout}. It manages {@link ViewPager.OnPageChangeListener}s. @@ -28,7 +31,7 @@ KeyboardAccessoryCoordinator.TabSwitchingDelegate { private final PropertyModel mModel; private @Nullable AccessoryTabObserver mAccessoryTabObserver; - private ViewPager.OnPageChangeListener mPageChangeListener; + private Set<TabLayout.TabLayoutOnPageChangeListener> mPageChangeListeners = new HashSet<>(); KeyboardAccessoryTabLayoutMediator(PropertyModel model) { mModel = model; @@ -37,25 +40,27 @@ mModel.set(TAB_SELECTION_CALLBACKS, this); } - void setPageChangeListener(ViewPager.OnPageChangeListener onPageChangeListener) { - mPageChangeListener = onPageChangeListener; - } - ViewPager.OnPageChangeListener getStableOnPageChangeListener() { return new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int j) { - if (mPageChangeListener != null) mPageChangeListener.onPageScrolled(i, v, j); + for (TabLayout.TabLayoutOnPageChangeListener listener : mPageChangeListeners) { + listener.onPageScrolled(i, v, j); + } } @Override public void onPageSelected(int i) { - if (mPageChangeListener != null) mPageChangeListener.onPageSelected(i); + for (TabLayout.TabLayoutOnPageChangeListener listener : mPageChangeListeners) { + listener.onPageSelected(i); + } } @Override public void onPageScrollStateChanged(int i) { - if (mPageChangeListener != null) mPageChangeListener.onPageScrollStateChanged(i); + for (TabLayout.TabLayoutOnPageChangeListener listener : mPageChangeListeners) { + listener.onPageScrollStateChanged(i); + } } }; } @@ -145,4 +150,13 @@ public void setTabObserver(AccessoryTabObserver accessoryTabObserver) { mAccessoryTabObserver = accessoryTabObserver; } + + public void addPageChangeListener(TabLayout.TabLayoutOnPageChangeListener pageChangeListener) { + mPageChangeListeners.add(pageChangeListener); + } + + public void removePageChangeListener( + TabLayout.TabLayoutOnPageChangeListener pageChangeListener) { + mPageChangeListeners.remove(pageChangeListener); + } } \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryTabLayoutView.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryTabLayoutView.java index 75f5074..f79c14c0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryTabLayoutView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryTabLayoutView.java
@@ -66,11 +66,20 @@ * @param activeTab The active tab to change. If null, all tabs are reset. */ void setActiveTabColor(@Nullable Integer activeTab) { + setSelectedTabIndicatorHeight(activeTab == null + ? 0 + : getResources().getDimensionPixelSize(R.dimen.divider_height)); for (int i = getTabCount() - 1; i >= 0; i--) { TabLayout.Tab t = getTabAt(i); if (t == null || t.getIcon() == null) continue; int activeState = android.R.attr.state_selected; - if (activeTab == null || i != activeTab) activeState *= -1; // This means unselected. + if (activeTab == null || i != activeTab) { // This means unselected. + activeState *= -1; + } else if (!t.isSelected()) { + // If the active tab was set by the model, reflect that in the TabLayout's state. + // This triggers the tab observer but as the active tab doesn't change, it's a noop. + t.select(); + } DrawableCompat.setTint(t.getIcon(), getTabTextColors().getColorForState( new int[] {activeState}, getTabTextColors().getDefaultColor()));
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryView.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryView.java index 5d84451e..8b7125a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryView.java
@@ -8,6 +8,7 @@ import android.content.Context; import android.graphics.Rect; +import android.support.v4.view.ViewCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; @@ -17,6 +18,7 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; +import org.chromium.chrome.browser.ChromeFeatureList; /** * The Accessory sitting above the keyboard and below the content area. It is used for autofill @@ -24,17 +26,28 @@ */ class KeyboardAccessoryView extends LinearLayout { protected RecyclerView mBarItemsView; - private KeyboardAccessoryTabLayoutView mTabLayout; + protected KeyboardAccessoryTabLayoutView mTabLayout; - private static class HorizontalDividerItemDecoration extends RecyclerView.ItemDecoration { + protected static class HorizontalDividerItemDecoration extends RecyclerView.ItemDecoration { private final int mHorizontalMargin; + HorizontalDividerItemDecoration(int horizontalMargin) { this.mHorizontalMargin = horizontalMargin; } + @Override public void getItemOffsets( Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { - outRect.right = mHorizontalMargin; + if (isLayoutRtl()) { + outRect.right = getItemOffsetInternal(view, parent, state); + } else { + outRect.left = getItemOffsetInternal(view, parent, state); + } + } + + protected int getItemOffsetInternal( + final View view, final RecyclerView parent, RecyclerView.State state) { + return mHorizontalMargin; } } @@ -53,8 +66,6 @@ mBarItemsView = findViewById(R.id.bar_items_view); initializeHorizontalRecyclerView(mBarItemsView); - mTabLayout = findViewById(R.id.tabs); - // Apply RTL layout changes to the view's children: ApiCompatibilityUtils.setLayoutDirection(findViewById(R.id.accessory_bar_contents), isLayoutRtl() ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR); @@ -72,6 +83,9 @@ } KeyboardAccessoryTabLayoutView getTabLayout() { + if (mTabLayout == null) { + mTabLayout = findViewById(R.id.tabs); + } return mTabLayout; } @@ -108,13 +122,15 @@ recyclerView.setLayoutManager( new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false)); - int pad = getResources().getDimensionPixelSize(R.dimen.keyboard_accessory_padding); + int pad = getResources().getDimensionPixelSize(R.dimen.keyboard_accessory_half_padding); // Create margins between every element. - recyclerView.addItemDecoration(new HorizontalDividerItemDecoration(pad)); + if (!ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_KEYBOARD_ACCESSORY)) { + recyclerView.addItemDecoration(new HorizontalDividerItemDecoration(pad)); + } // Remove all animations - the accessory shouldn't be visibly built anyway. recyclerView.setItemAnimator(null); - recyclerView.setPadding(isLayoutRtl() ? 0 : pad, 0, isLayoutRtl() ? pad : 0, 0); + ViewCompat.setPaddingRelative(recyclerView, pad, 0, 0, 0); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryViewBinder.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryViewBinder.java index 2445d42..119a7ce 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryViewBinder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryViewBinder.java
@@ -8,6 +8,7 @@ import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.BOTTOM_OFFSET_PX; import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.KEYBOARD_TOGGLE_VISIBLE; import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.SHOW_KEYBOARD_CALLBACK; +import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.TAB_LAYOUT_ITEM; import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.VISIBLE; import android.os.Build; @@ -35,7 +36,7 @@ return new BarItemTextViewHolder(parent, R.layout.keyboard_accessory_action); case BarItem.Type.SUGGESTION: return new BarItemTextViewHolder(parent, R.layout.keyboard_accessory_chip); - case BarItem.Type.TAB_SWITCHER: // Intentional fallthrough. Not supported. + case BarItem.Type.TAB_LAYOUT: // Intentional fallthrough. Not supported. case BarItem.Type.COUNT: assert false : "Type " + viewType + " is not a valid accessory bar action!"; } @@ -108,6 +109,8 @@ // No binding required. } else if (propertyKey == KEYBOARD_TOGGLE_VISIBLE) { // No binding required. + } else if (propertyKey == TAB_LAYOUT_ITEM) { + // No binding required. } else { return false; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/animation/CompositorAnimationHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/animation/CompositorAnimationHandler.java index b65af7e1..ab913f8 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/animation/CompositorAnimationHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/animation/CompositorAnimationHandler.java
@@ -18,6 +18,9 @@ * CompositorAnimators. */ public class CompositorAnimationHandler { + /** Whether or not testing mode is enabled. In this mode, animations end immediately. */ + private static boolean sIsInTestingMode; + /** A list of all the handler's animators. */ private final ArrayList<CompositorAnimator> mAnimators = new ArrayList<>(); @@ -36,9 +39,6 @@ */ private boolean mWasUpdateRequestedForAnimationStart; - /** Whether or not testing mode is enabled. In this mode, animations end immediately. */ - private boolean mIsInTestingMode; - /** The last time that an update was pushed to animations. */ private long mLastUpdateTimeMs; @@ -76,7 +76,7 @@ } // If in testing mode, immediately push an update and end the animation. - if (mIsInTestingMode) pushUpdate(animator.getDuration()); + if (sIsInTestingMode) pushUpdate(animator.getDuration()); } /** @@ -134,10 +134,19 @@ } /** - * Enable testing mode. This causes any animations to end immediately. + * Enable or disable testing mode. This causes any animations to end immediately. + * @param enabled Whether testing mode is enabled or disabled. */ @VisibleForTesting - public void enableTestingMode() { - mIsInTestingMode = true; + public static void setTestingMode(boolean enabled) { + sIsInTestingMode = enabled; + } + + /** + * @return Whether we are in testing mode or not. + */ + @VisibleForTesting + public static boolean isInTestingMode() { + return sIsInTestingMode; } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/dynamicmodule/ModuleLoader.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/dynamicmodule/ModuleLoader.java index a0f3dcb..36bfd84 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/dynamicmodule/ModuleLoader.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/dynamicmodule/ModuleLoader.java
@@ -12,7 +12,6 @@ import android.content.pm.PackageManager; import android.os.Bundle; import android.os.IBinder; -import android.os.Process; import android.support.annotation.Nullable; import dalvik.system.DexClassLoader; @@ -24,6 +23,8 @@ import org.chromium.base.ObserverList; import org.chromium.base.VisibleForTesting; import org.chromium.base.task.AsyncTask; +import org.chromium.base.task.TaskPriority; +import org.chromium.base.task.TaskTraits; import org.chromium.chrome.browser.ChromeApplication; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.customtabs.dynamicmodule.ModuleMetrics.DestructionReason; @@ -154,7 +155,9 @@ ModuleMetrics.registerLifecycleState(ModuleMetrics.LifecycleState.NOT_LOADED); mIsModuleLoading = true; - new LoadClassTask(moduleContext).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new LoadClassTask(moduleContext) + .executeWithTaskTraits( + new TaskTraits().taskPriority(TaskPriority.USER_VISIBLE).mayBlock(true)); } /** @@ -326,16 +329,7 @@ @Override @Nullable protected Class<?> doInBackground() { - int oldPriority = Process.getThreadPriority(0); try { - // We don't want to block the UI thread, but we don't want to be really slow either. - // The AsyncTask class sets the thread priority quite low - // (THREAD_PRIORITY_BACKGROUND) and does not distinguish between user-visible - // user-invisible tasks. - // TODO(crbug.com/863457): Replace this with something like a task trait that - // influences priority once we have a task scheduler in Java. - Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); - boolean loadFromDex = updateModuleDexInDiskIfNeeded(); long entryPointLoadClassStartTime = ModuleMetrics.now(); Class<?> clazz = @@ -349,8 +343,6 @@ Log.e(TAG, "Could not copy dex to local storage", e); ModuleMetrics.recordLoadResult( ModuleMetrics.LoadResult.FAILED_TO_COPY_DEX_EXCEPTION); - } finally { - Process.setThreadPriority(oldPriority); } return null; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBackgroundTask.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBackgroundTask.java index 0bcd054..12297a3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBackgroundTask.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBackgroundTask.java
@@ -63,7 +63,7 @@ protected void onStartTaskWithNative( Context context, TaskParameters taskParameters, TaskFinishedCallback callback) { assert taskParameters.getTaskId() == TaskIds.EXPLORE_SITES_REFRESH_JOB_ID; - if (ExploreSitesBridge.isEnabled(ExploreSitesBridge.getVariation())) { + if (!ExploreSitesBridge.isEnabled(ExploreSitesBridge.getVariation())) { cancelTask(); return; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryTileView.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryTileView.java index e3d4a625..dfcd215b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryTileView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryTileView.java
@@ -13,7 +13,7 @@ import android.widget.ImageView; import org.chromium.chrome.R; -import org.chromium.chrome.browser.compositor.layouts.ChromeAnimation; +import org.chromium.chrome.browser.compositor.animation.CompositorAnimationHandler; import org.chromium.chrome.browser.ntp.TitleUtil; import org.chromium.chrome.browser.widget.tile.TileWithTextView; @@ -81,11 +81,10 @@ } private void fadeThumbnailIn(Drawable thumbnail) { - int duration = - (int) (FADE_ANIMATION_TIME_MS * ChromeAnimation.Animation.getAnimationMultiplier()); + int duration = FADE_ANIMATION_TIME_MS; // If animations are disabled, just show the thumbnail. - if (duration == 0) { + if (CompositorAnimationHandler.isInTestingMode()) { setIconDrawable(thumbnail); return; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryPage.java b/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryPage.java index d9152fe7..12e43ba9 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryPage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryPage.java
@@ -14,7 +14,6 @@ import org.chromium.chrome.browser.native_page.BasicNativePage; import org.chromium.chrome.browser.native_page.NativePageHost; import org.chromium.chrome.browser.snackbar.SnackbarManager.SnackbarManageable; -import org.chromium.chrome.browser.util.ColorUtils; /** * Native page for managing browsing history. @@ -22,7 +21,6 @@ public class HistoryPage extends BasicNativePage { private HistoryManager mHistoryManager; private String mTitle; - private int mThemeColor; /** * Create a new instance of the history page. @@ -32,10 +30,6 @@ */ public HistoryPage(ChromeActivity activity, NativePageHost host) { super(activity, host); - - mThemeColor = !host.isIncognito() - ? super.getThemeColor() - : ColorUtils.getDefaultThemeColor(activity.getResources(), true); } @Override @@ -67,11 +61,6 @@ super.destroy(); } - @Override - public int getThemeColor() { - return mThemeColor; - } - @VisibleForTesting public HistoryManager getHistoryManagerForTesting() { return mHistoryManager;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/native_page/BasicNativePage.java b/chrome/android/java/src/org/chromium/chrome/browser/native_page/BasicNativePage.java index 9f3bdf7..1b9cfa4f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/native_page/BasicNativePage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/native_page/BasicNativePage.java
@@ -9,7 +9,6 @@ import android.view.View; import android.widget.FrameLayout.LayoutParams; -import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.tab.EmptyTabObserver; @@ -25,25 +24,16 @@ private final Activity mActivity; private final NativePageHost mHost; private final int mBackgroundColor; - private final int mThemeColor; private int mTopMargin; private int mBottomMargin; private String mUrl; public BasicNativePage(ChromeActivity activity, NativePageHost host) { - this(activity, host, false); - } - - public BasicNativePage(ChromeActivity activity, NativePageHost host, boolean isIncognito) { initialize(activity, host); mActivity = activity; mHost = host; - - mThemeColor = ColorUtils.getDefaultThemeColor(activity.getResources(), isIncognito); - mBackgroundColor = isIncognito - ? ApiCompatibilityUtils.getColor(activity.getResources(), R.color.ntp_bg_incognito) - : mThemeColor; + mBackgroundColor = ColorUtils.getDefaultThemeColor(activity.getResources(), false); Resources res = mActivity.getResources(); @@ -84,11 +74,6 @@ } @Override - public int getThemeColor() { - return mThemeColor; - } - - @Override public boolean needsToolbarShadow() { return true; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/native_page/FrozenNativePage.java b/chrome/android/java/src/org/chromium/chrome/browser/native_page/FrozenNativePage.java index d25172e3..1d4e911 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/native_page/FrozenNativePage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/native_page/FrozenNativePage.java
@@ -18,7 +18,6 @@ private final String mHost; private final String mTitle; private final int mBackgroundColor; - private final int mThemeColor; /** * Creates a FrozenNativePage to replace the given NativePage and destroys the NativePage. @@ -34,7 +33,6 @@ mUrl = nativePage.getUrl(); mTitle = nativePage.getTitle(); mBackgroundColor = nativePage.getBackgroundColor(); - mThemeColor = nativePage.getThemeColor(); } @Override @@ -64,11 +62,6 @@ } @Override - public int getThemeColor() { - return mThemeColor; - } - - @Override public boolean needsToolbarShadow() { return true; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/native_page/NativePage.java b/chrome/android/java/src/org/chromium/chrome/browser/native_page/NativePage.java index dd7f761f..155c630 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/native_page/NativePage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/native_page/NativePage.java
@@ -36,11 +36,6 @@ int getBackgroundColor(); /** - * @return The theme color of the page. - */ - int getThemeColor(); - - /** * @return True if the native page needs the toolbar shadow to be drawn. */ boolean needsToolbarShadow();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPage.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPage.java index 2b29330f..dc1a15b4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPage.java
@@ -11,6 +11,7 @@ import android.view.View; import android.widget.TextView; +import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.VisibleForTesting; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; @@ -38,6 +39,8 @@ private IncognitoNewTabPageManager mIncognitoNewTabPageManager; + private final int mIncognitoNTPBackgroundColor; + private void showIncognitoLearnMore() { HelpAndFeedback.getInstance(mActivity).show(mActivity, mActivity.getString(R.string.help_context_incognito_learn_more), @@ -49,7 +52,10 @@ * @param activity The activity used to create the new tab page's View. */ public IncognitoNewTabPage(ChromeActivity activity, NativePageHost host) { - super(activity, host, true); + super(activity, host); + + mIncognitoNTPBackgroundColor = + ApiCompatibilityUtils.getColor(activity.getResources(), R.color.ntp_bg_incognito); } @Override @@ -136,6 +142,11 @@ } @Override + public int getBackgroundColor() { + return mIncognitoNTPBackgroundColor; + } + + @Override public String getTitle() { return mTitle; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java index c9c3ceb..fcba454 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java
@@ -54,7 +54,6 @@ import org.chromium.chrome.browser.tab.TabObserver; import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.tabmodel.TabSelectionType; -import org.chromium.chrome.browser.util.ColorUtils; import org.chromium.chrome.browser.util.FeatureUtilities; import org.chromium.chrome.browser.util.UrlUtilities; import org.chromium.chrome.browser.vr.VrModuleProvider; @@ -84,7 +83,6 @@ private final String mTitle; private final int mBackgroundColor; - private final int mThemeColor; protected final NewTabPageManagerImpl mNewTabPageManager; protected final TileGroup.Delegate mTileGroupDelegate; private final boolean mIsTablet; @@ -293,7 +291,6 @@ mTitle = activity.getResources().getString(R.string.button_new_tab); mBackgroundColor = ApiCompatibilityUtils.getColor( activity.getResources(), R.color.modern_primary_color); - mThemeColor = ColorUtils.getDefaultThemeColor(activity.getResources(), false); mIsTablet = activity.isTablet(); TemplateUrlService.getInstance().addObserver(this); @@ -628,11 +625,6 @@ } @Override - public int getThemeColor() { - return isLocationBarShownInNTP() ? mBackgroundColor : mThemeColor; - } - - @Override public boolean needsToolbarShadow() { return !mSearchProviderHasLogo; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/RecentTabsPage.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/RecentTabsPage.java index 1d314d1e..6d435db 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/RecentTabsPage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/RecentTabsPage.java
@@ -25,7 +25,6 @@ import org.chromium.chrome.browser.UrlConstants; import org.chromium.chrome.browser.compositor.layouts.content.InvalidationAwareThumbnailProvider; import org.chromium.chrome.browser.native_page.NativePage; -import org.chromium.chrome.browser.util.ColorUtils; import org.chromium.chrome.browser.util.ViewUtils; import java.util.concurrent.TimeUnit; @@ -152,11 +151,6 @@ } @Override - public int getThemeColor() { - return ColorUtils.getDefaultThemeColor(mActivity.getResources(), false); - } - - @Override public boolean needsToolbarShadow() { return true; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerSuggestionProcessor.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerSuggestionProcessor.java index 810d0c0..9cc5902 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerSuggestionProcessor.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerSuggestionProcessor.java
@@ -136,36 +136,27 @@ if (numAnswerLines == -1) numAnswerLines = 1; model.set(SuggestionViewProperties.IS_ANSWER, true); - // New answer layout is specific to all definitions except dictionary. - // There are few changes when compared to classic layout, most notably the order - // of the items on the card is reverse. - boolean applyNewLayout = - mEnableNewAnswerLayout && answer.getType() != AnswerType.DICTIONARY; - if (applyNewLayout) { - SuggestionAnswer.ImageLine temp = firstLine; - firstLine = secondLine; - secondLine = temp; + AnswerText[] details; + if (mEnableNewAnswerLayout) { + details = AnswerTextNewLayout.from(mContext, answer); + } else { + details = AnswerTextClassic.from(mContext, answer, density); } model.set(SuggestionViewProperties.TEXT_LINE_1_SIZING, - Pair.create(TypedValue.COMPLEX_UNIT_SP, - (float) AnswerTextBuilder.getMaxTextHeightSp(firstLine))); + Pair.create(TypedValue.COMPLEX_UNIT_SP, details[0].mHeightSp)); model.set(SuggestionViewProperties.TEXT_LINE_2_SIZING, - Pair.create(TypedValue.COMPLEX_UNIT_SP, - (float) AnswerTextBuilder.getMaxTextHeightSp(secondLine))); + Pair.create(TypedValue.COMPLEX_UNIT_SP, details[1].mHeightSp)); model.set(SuggestionViewProperties.TEXT_LINE_1_TEXT, - new SuggestionTextContainer( - AnswerTextBuilder.buildSpannable(firstLine, density, applyNewLayout))); + new SuggestionTextContainer(details[0].mText)); model.set(SuggestionViewProperties.TEXT_LINE_2_TEXT, - new SuggestionTextContainer( - AnswerTextBuilder.buildSpannable(secondLine, density, applyNewLayout))); + new SuggestionTextContainer(details[1].mText)); - model.set(SuggestionViewProperties.TEXT_LINE_1_MAX_LINES, - applyNewLayout ? 1 : numAnswerLines); - model.set(SuggestionViewProperties.TEXT_LINE_2_MAX_LINES, - applyNewLayout ? numAnswerLines : 1); + model.set(SuggestionViewProperties.TEXT_LINE_1_MAX_LINES, details[0].mMaxLines); + model.set(SuggestionViewProperties.TEXT_LINE_2_MAX_LINES, details[1].mMaxLines); + // TODO(ender): The color setting here is likely redundant; details include attributes. model.set(SuggestionViewProperties.TEXT_LINE_1_TEXT_COLOR, SuggestionViewViewBinder.getStandardFontColor( mContext, model.get(SuggestionCommonProperties.USE_DARK_COLORS)));
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerText.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerText.java new file mode 100644 index 0000000..f6e0944 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerText.java
@@ -0,0 +1,102 @@ +// 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. + +package org.chromium.chrome.browser.omnibox.suggestions.basic; + +import android.content.Context; +import android.text.Html; +import android.text.Spannable; +import android.text.SpannableStringBuilder; +import android.text.style.MetricAffectingSpan; +import android.text.style.TextAppearanceSpan; + +import org.chromium.components.omnibox.AnswerTextType; +import org.chromium.components.omnibox.SuggestionAnswer; + +import java.util.List; + +/** + * AnswerText specifies details to be presented in a single line of omnibox suggestion. + */ +abstract class AnswerText { + Context mContext; + /** Content of the line of text in omnibox suggestion. */ + SpannableStringBuilder mText; + /** Max height of the text. */ + int mHeightSp; + /** Whether content can wrap around to present more details. */ + int mMaxLines; + + /** + * Create new instance of AnswerText. + * + * @param context Current context. + */ + AnswerText(Context context) { + mContext = context; + } + + /** + * Builds a Spannable containing all of the styled text in the supplied ImageLine. + * + * @param line All text fields within this line will be used to build the resulting content. + * @param delegate Callback converting AnswerTextType to an array of TextAppearanceSpan objects. + */ + protected void build(SuggestionAnswer.ImageLine line) { + mText = new SpannableStringBuilder(); + mMaxLines = 1; + + List<SuggestionAnswer.TextField> textFields = line.getTextFields(); + for (int i = 0; i < textFields.size(); i++) { + appendAndStyleText(textFields.get(i)); + if (textFields.get(i).hasNumLines()) { + mMaxLines = Math.max(mMaxLines, Math.min(3, textFields.get(i).getNumLines())); + } + } + + if (line.hasAdditionalText()) { + mText.append(" "); + appendAndStyleText(line.getAdditionalText()); + } + if (line.hasStatusText()) { + mText.append(" "); + appendAndStyleText(line.getStatusText()); + } + } + + /** + * Append the styled text in textField to the supplied builder. + * + * @param textField The text field (with text and type) to append. + */ + @SuppressWarnings("deprecation") // Update usage of Html.fromHtml when API min is 24 + private void appendAndStyleText(SuggestionAnswer.TextField textField) { + MetricAffectingSpan[] styles = getAppearanceForText(textField.getType()); + for (MetricAffectingSpan style : styles) { + if (!(style instanceof TextAppearanceSpan)) continue; + TextAppearanceSpan textStyle = (TextAppearanceSpan) style; + if (mHeightSp < textStyle.getTextSize()) mHeightSp = textStyle.getTextSize(); + } + + // Unescape HTML entities (e.g. """, ">"). + String text = Html.fromHtml(textField.getText()).toString(); + + // Append as HTML (answer responses contain simple markup). + int start = mText.length(); + mText.append(Html.fromHtml(text)); + int end = mText.length(); + + for (MetricAffectingSpan style : styles) { + mText.setSpan(style, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + } + + /** + * Return the TextAppearanceSpan array specifying text decorations for a given field type. + * + * @param type The answer type as specified at http://goto.google.com/ais_api. + * @return TextAppearanceSpan array specifying styles to be used to present text field. + */ + protected abstract MetricAffectingSpan[] getAppearanceForText(@AnswerTextType int type); +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerTextBuilder.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerTextBuilder.java deleted file mode 100644 index 7c10e89..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerTextBuilder.java +++ /dev/null
@@ -1,275 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.omnibox.suggestions.basic; - -import android.content.res.Resources; -import android.graphics.Paint; -import android.text.Html; -import android.text.Spannable; -import android.text.SpannableStringBuilder; -import android.text.TextPaint; -import android.text.style.AbsoluteSizeSpan; -import android.text.style.ForegroundColorSpan; -import android.text.style.MetricAffectingSpan; - -import org.chromium.base.ApiCompatibilityUtils; -import org.chromium.base.ContextUtils; -import org.chromium.base.Log; -import org.chromium.chrome.R; -import org.chromium.components.omnibox.AnswerTextType; -import org.chromium.components.omnibox.SuggestionAnswer; - -import java.util.List; - -/** - * Helper class that builds Spannables to represent the styled text in answers from Answers in - * Suggest. - */ -class AnswerTextBuilder { - private static final String TAG = "AnswerTextBuilder"; - - private static final int ANSWERS_TOP_ALIGNED_TEXT_SIZE_SP = 12; - private static final int ANSWERS_DESCRIPTION_TEXT_NEGATIVE_SIZE_SP = 16; - private static final int ANSWERS_DESCRIPTION_TEXT_POSITIVE_SIZE_SP = 16; - private static final int ANSWERS_SUGGESTION_TEXT_SIZE_SP = 16; - private static final int ANSWERS_PERSONALIZED_SUGGESTION_TEXT_SIZE_SP = 15; - private static final int ANSWERS_ANSWER_TEXT_MEDIUM_SIZE_SP = 20; - private static final int ANSWERS_ANSWER_TEXT_LARGE_SIZE_SP = 24; - private static final int ANSWERS_SECONDARY_TEXT_SMALL_SIZE_SP = 12; - private static final int ANSWERS_SECONDARY_TEXT_MEDIUM_SIZE_SP = 14; - - /** - * Builds a Spannable containing all of the styled text in the supplied ImageLine. - * - * @param line All text fields within this line will be added to the returned Spannable. - * types. - * @param density Screen density which will be used to properly size and layout images and top- - * aligned text. - */ - static Spannable buildSpannable( - SuggestionAnswer.ImageLine line, float density, boolean useNewAnswerLayout) { - SpannableStringBuilder builder = new SpannableStringBuilder(); - - // Determine the height of the largest text element in the line. This - // will be used to top-align text and scale images. - int maxTextHeightSp = getMaxTextHeightSp(line); - - List<SuggestionAnswer.TextField> textFields = line.getTextFields(); - for (int i = 0; i < textFields.size(); i++) { - appendAndStyleText( - builder, textFields.get(i), maxTextHeightSp, density, useNewAnswerLayout); - } - if (line.hasAdditionalText()) { - builder.append(" "); - SuggestionAnswer.TextField additionalText = line.getAdditionalText(); - appendAndStyleText( - builder, additionalText, maxTextHeightSp, density, useNewAnswerLayout); - } - if (line.hasStatusText()) { - builder.append(" "); - SuggestionAnswer.TextField statusText = line.getStatusText(); - appendAndStyleText(builder, statusText, maxTextHeightSp, density, useNewAnswerLayout); - } - - return builder; - } - - /** - * Determine the height of the largest text field in the entire line. - * - * @param line An ImageLine containing the text fields. - * @return The height in SP. - */ - static int getMaxTextHeightSp(SuggestionAnswer.ImageLine line) { - int maxHeightSp = 0; - - List<SuggestionAnswer.TextField> textFields = line.getTextFields(); - for (int i = 0; i < textFields.size(); i++) { - int height = getAnswerTextSizeSp(textFields.get(i).getType()); - if (height > maxHeightSp) { - maxHeightSp = height; - } - } - if (line.hasAdditionalText()) { - int height = getAnswerTextSizeSp(line.getAdditionalText().getType()); - if (height > maxHeightSp) { - maxHeightSp = height; - } - } - if (line.hasStatusText()) { - int height = getAnswerTextSizeSp(line.getStatusText().getType()); - if (height > maxHeightSp) { - maxHeightSp = height; - } - } - - return maxHeightSp; - } - - /** - * Append the styled text in textField to the supplied builder. - * - * @param builder The builder to append the text to. - * @param textField The text field (with text and type) to append. - * @param maxTextHeightSp The height in SP of the largest text field in the entire line. Used to - * top-align text when specified. - * @param density Screen density which will be used to properly size and layout images and top- - * aligned text. - */ - @SuppressWarnings("deprecation") // Update usage of Html.fromHtml when API min is 24 - private static void appendAndStyleText(SpannableStringBuilder builder, - SuggestionAnswer.TextField textField, int maxTextHeightSp, float density, - boolean useNewAnswerLayout) { - String text = textField.getText(); - int type = textField.getType(); - - // Unescape HTML entities (e.g. """, ">"). - text = Html.fromHtml(text).toString(); - - // Append as HTML (answer responses contain simple markup). - int start = builder.length(); - builder.append(Html.fromHtml(text)); - int end = builder.length(); - - // Apply styles according to the type. - AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(getAnswerTextSizeSp(type), true); - builder.setSpan(sizeSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); - - ForegroundColorSpan colorSpan = - new ForegroundColorSpan(getAnswerTextColor(type, useNewAnswerLayout)); - builder.setSpan(colorSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); - - if (type == AnswerTextType.TOP_ALIGNED) { - TopAlignedSpan topAlignedSpan = - new TopAlignedSpan(ANSWERS_TOP_ALIGNED_TEXT_SIZE_SP, maxTextHeightSp, density); - builder.setSpan(topAlignedSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); - } - } - - /** - * Return the SP text height for the specified answer text type. - * - * @param type The answer type as specified at http://goto.google.com/ais_api. - */ - private static int getAnswerTextSizeSp(@AnswerTextType int type) { - switch (type) { - case AnswerTextType.TOP_ALIGNED: - return ANSWERS_TOP_ALIGNED_TEXT_SIZE_SP; - case AnswerTextType.DESCRIPTION_NEGATIVE: - return ANSWERS_DESCRIPTION_TEXT_NEGATIVE_SIZE_SP; - case AnswerTextType.DESCRIPTION_POSITIVE: - return ANSWERS_DESCRIPTION_TEXT_POSITIVE_SIZE_SP; - case AnswerTextType.SUGGESTION: - return ANSWERS_SUGGESTION_TEXT_SIZE_SP; - case AnswerTextType.PERSONALIZED_SUGGESTION: - return ANSWERS_PERSONALIZED_SUGGESTION_TEXT_SIZE_SP; - case AnswerTextType.ANSWER_TEXT_MEDIUM: - return ANSWERS_ANSWER_TEXT_MEDIUM_SIZE_SP; - case AnswerTextType.ANSWER_TEXT_LARGE: - return ANSWERS_ANSWER_TEXT_LARGE_SIZE_SP; - case AnswerTextType.SUGGESTION_SECONDARY_TEXT_SMALL: - return ANSWERS_SECONDARY_TEXT_SMALL_SIZE_SP; - case AnswerTextType.SUGGESTION_SECONDARY_TEXT_MEDIUM: - return ANSWERS_SECONDARY_TEXT_MEDIUM_SIZE_SP; - default: - Log.w(TAG, "Unknown answer type: " + type); - return ANSWERS_SUGGESTION_TEXT_SIZE_SP; - } - } - - /** - * Return the color code for the specified answer text type. - * - * @param type The answer type as specified at http://goto.google.com/ais_api. - */ - private static int getAnswerTextColor(@AnswerTextType int type, boolean useNewAnswerLayout) { - Resources resources = ContextUtils.getApplicationContext().getResources(); - switch (type) { - case AnswerTextType.DESCRIPTION_NEGATIVE: - return ApiCompatibilityUtils.getColor( - resources, R.color.answers_description_text_negative); - - case AnswerTextType.DESCRIPTION_POSITIVE: - return ApiCompatibilityUtils.getColor( - resources, R.color.answers_description_text_positive); - - case AnswerTextType.SUGGESTION: - case AnswerTextType.PERSONALIZED_SUGGESTION: - if (useNewAnswerLayout) { - return ApiCompatibilityUtils.getColor(resources, R.color.answers_answer_text); - } else { - return ApiCompatibilityUtils.getColor( - resources, R.color.url_emphasis_default_text); - } - - case AnswerTextType.TOP_ALIGNED: - case AnswerTextType.ANSWER_TEXT_MEDIUM: - case AnswerTextType.ANSWER_TEXT_LARGE: - case AnswerTextType.SUGGESTION_SECONDARY_TEXT_SMALL: - case AnswerTextType.SUGGESTION_SECONDARY_TEXT_MEDIUM: - if (useNewAnswerLayout) { - return ApiCompatibilityUtils.getColor( - resources, R.color.url_emphasis_default_text); - } else { - return ApiCompatibilityUtils.getColor(resources, R.color.answers_answer_text); - } - - default: - Log.w(TAG, "Unknown answer type: " + type); - return ApiCompatibilityUtils.getColor(resources, R.color.url_emphasis_default_text); - } - } - - /** - * Aligns the top of the spanned text with the top of some other specified text height. This is - * done by calculating the ascent of both text heights and shifting the baseline of the spanned - * text by the difference. As a result, "top aligned" means the top of the ascents are - * aligned, which looks as expected in most cases (some glyphs in some fonts are drawn above - * the top of the ascent). - */ - private static class TopAlignedSpan extends MetricAffectingSpan { - private final int mTextHeightSp; - private final int mMaxTextHeightSp; - private final float mDensity; - - private Integer mBaselineShift; - - /** - * Constructor for TopAlignedSpan. - * - * @param textHeightSp The total height in SP of the text covered by this span. - * @param maxTextHeightSp The total height in SP of the text we wish to top-align with. - * @param density The display density. - */ - public TopAlignedSpan(int textHeightSp, int maxTextHeightSp, float density) { - mTextHeightSp = textHeightSp; - mMaxTextHeightSp = maxTextHeightSp; - mDensity = density; - } - - @Override - public void updateDrawState(TextPaint tp) { - initBaselineShift(tp); - tp.baselineShift += mBaselineShift; - } - - @Override - public void updateMeasureState(TextPaint tp) { - initBaselineShift(tp); - tp.baselineShift += mBaselineShift; - } - - private void initBaselineShift(TextPaint tp) { - if (mBaselineShift != null) return; - Paint.FontMetrics metrics = tp.getFontMetrics(); - float ascentProportion = metrics.ascent / (metrics.top - metrics.bottom); - - int textAscentPx = (int) (mTextHeightSp * ascentProportion * mDensity); - int maxTextAscentPx = (int) (mMaxTextHeightSp * ascentProportion * mDensity); - - mBaselineShift = -(maxTextAscentPx - textAscentPx); // Up is -y. - } - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerTextClassic.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerTextClassic.java new file mode 100644 index 0000000..5293077d --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerTextClassic.java
@@ -0,0 +1,169 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.omnibox.suggestions.basic; + +import android.content.Context; +import android.graphics.Paint; +import android.support.annotation.StyleRes; +import android.text.TextPaint; +import android.text.style.MetricAffectingSpan; +import android.text.style.TextAppearanceSpan; + +import org.chromium.base.Log; +import org.chromium.chrome.R; +import org.chromium.components.omnibox.AnswerTextType; +import org.chromium.components.omnibox.SuggestionAnswer; + +/** + * AnswerTextNewLayout builds Omnibox styled Answer suggestion texts for classic answer layouts. + */ +class AnswerTextClassic extends AnswerText { + private static final String TAG = "AnswerTextClassic"; + private final float mDensity; + + /** + * Convert SuggestionAnswer to array of elements that directly translate to user-presented + * content. + * + * @param context Current context. + * @param answer Specifies answer to be converted. + * @param density Screen density which will be used to properly size and layout images and top- + * aligned text. + * @return array of AnswerText elements to use to construct suggestion item. + */ + static AnswerText[] from(Context context, SuggestionAnswer answer, final float density) { + AnswerText[] result = new AnswerText[2]; + + result[0] = new AnswerTextClassic(context, answer.getFirstLine(), density); + result[1] = new AnswerTextClassic(context, answer.getSecondLine(), density); + + // Trim number of presented query lines. + result[0].mMaxLines = 1; + + return result; + } + + /** + * Create new instance of AnswerTextClassic. + * + * @param context Current context. + * @param line Suggestion line that will be converted to Answer Text. + * @param density Screen density. + */ + AnswerTextClassic(Context context, SuggestionAnswer.ImageLine line, float density) { + super(context); + mDensity = density; + build(line); + } + + /** + * Return the TextAppearanceSpan array specifying text decorations for a given field type. + * + * @param type The answer type as specified at http://goto.google.com/ais_api. + * @return TextAppearanceSpan array specifying styles to be used to present text field. + */ + @Override + protected MetricAffectingSpan[] getAppearanceForText(@AnswerTextType int type) { + @StyleRes + int res = 0; + switch (type) { + case AnswerTextType.TOP_ALIGNED: + TextAppearanceSpan style = new TextAppearanceSpan( + mContext, R.style.TextAppearance_OmniboxAnswerTextSmall); + return new MetricAffectingSpan[] { + style, new TopAlignedSpan(style.getTextSize(), mHeightSp, mDensity)}; + + case AnswerTextType.DESCRIPTION_NEGATIVE: + res = R.style.TextAppearance_OmniboxAnswerDescriptionNegative; + break; + + case AnswerTextType.DESCRIPTION_POSITIVE: + res = R.style.TextAppearance_OmniboxAnswerDescriptionPositive; + break; + + case AnswerTextType.SUGGESTION: + res = R.style.TextAppearance_BlackTitle1; + break; + + case AnswerTextType.PERSONALIZED_SUGGESTION: + res = R.style.TextAppearance_BlackTitle1; + break; + + case AnswerTextType.ANSWER_TEXT_MEDIUM: + res = R.style.TextAppearance_OmniboxAnswerTextMedium; + break; + + case AnswerTextType.ANSWER_TEXT_LARGE: + res = R.style.TextAppearance_OmniboxAnswerTextLarge; + break; + + case AnswerTextType.SUGGESTION_SECONDARY_TEXT_SMALL: + res = R.style.TextAppearance_BlackCaption; + break; + + case AnswerTextType.SUGGESTION_SECONDARY_TEXT_MEDIUM: + res = R.style.TextAppearance_BlackHint2; + break; + + default: + Log.w(TAG, "Unknown answer type: " + type); + res = R.style.TextAppearance_BlackHint2; + break; + } + + return new TextAppearanceSpan[] {new TextAppearanceSpan(mContext, res)}; + } + + /** + * Aligns the top of the spanned text with the top of some other specified text height. This is + * done by calculating the ascent of both text heights and shifting the baseline of the spanned + * text by the difference. As a result, "top aligned" means the top of the ascents are + * aligned, which looks as expected in most cases (some glyphs in some fonts are drawn above + * the top of the ascent). + */ + private static class TopAlignedSpan extends MetricAffectingSpan { + private final int mTextHeightSp; + private final int mMaxTextHeightSp; + private final float mDensity; + + private Integer mBaselineShift; + + /** + * Constructor for TopAlignedSpan. + * + * @param textHeightSp The total height in SP of the text covered by this span. + * @param maxTextHeightSp The total height in SP of the text we wish to top-align with. + * @param density The display density. + */ + public TopAlignedSpan(int textHeightSp, int maxTextHeightSp, float density) { + mTextHeightSp = textHeightSp; + mMaxTextHeightSp = maxTextHeightSp; + mDensity = density; + } + + @Override + public void updateDrawState(TextPaint tp) { + initBaselineShift(tp); + tp.baselineShift += mBaselineShift; + } + + @Override + public void updateMeasureState(TextPaint tp) { + initBaselineShift(tp); + tp.baselineShift += mBaselineShift; + } + + private void initBaselineShift(TextPaint tp) { + if (mBaselineShift != null) return; + Paint.FontMetrics metrics = tp.getFontMetrics(); + float ascentProportion = metrics.ascent / (metrics.top - metrics.bottom); + + int textAscentPx = (int) (mTextHeightSp * ascentProportion * mDensity); + int maxTextAscentPx = (int) (mMaxTextHeightSp * ascentProportion * mDensity); + + mBaselineShift = -(maxTextAscentPx - textAscentPx); // Up is -y. + } + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerTextNewLayout.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerTextNewLayout.java new file mode 100644 index 0000000..fce29c0 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerTextNewLayout.java
@@ -0,0 +1,125 @@ +// 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. + +package org.chromium.chrome.browser.omnibox.suggestions.basic; + +import android.content.Context; +import android.support.annotation.StyleRes; +import android.text.style.MetricAffectingSpan; +import android.text.style.TextAppearanceSpan; + +import org.chromium.base.Log; +import org.chromium.chrome.R; +import org.chromium.components.omnibox.AnswerTextType; +import org.chromium.components.omnibox.AnswerType; +import org.chromium.components.omnibox.SuggestionAnswer; + +/** + * AnswerTextNewLayout builds Omnibox styled Answer suggestion texts for revamped answer layouts. + */ +class AnswerTextNewLayout extends AnswerText { + private static final String TAG = "AnswerTextNewLayout"; + private final boolean mIsAnswer; + + /** + * Convert SuggestionAnswer to array of elements that directly translate to user-presented + * content. + * + * @param context Current context. + * @param answer Specifies answer to be converted. + * @return array of AnswerText elements to use to construct suggestion item. + */ + static AnswerText[] from(Context context, SuggestionAnswer answer) { + AnswerText[] result = new AnswerText[2]; + + if (answer.getType() == AnswerType.DICTIONARY) { + result[0] = new AnswerTextNewLayout(context, answer.getFirstLine(), true); + result[1] = new AnswerTextNewLayout(context, answer.getSecondLine(), false); + result[0].mMaxLines = 1; + + } else { + result[0] = new AnswerTextNewLayout(context, answer.getSecondLine(), true); + result[1] = new AnswerTextNewLayout(context, answer.getFirstLine(), false); + result[1].mMaxLines = 1; + } + + return result; + } + + /** + * Create new instance of AnswerTextNewLayout. + * + * @param context Current context. + * @param line Suggestion line that will be converted to Answer Text. + * @param isAnswerLine True, whether this instance holds answer. + */ + AnswerTextNewLayout(Context context, SuggestionAnswer.ImageLine line, boolean isAnswerLine) { + super(context); + mIsAnswer = isAnswerLine; + build(line); + } + + /** + * Return the TextAppearanceSpan array specifying text decorations for a given field type. + * + * @param type The answer type as specified at http://goto.google.com/ais_api. + * @return TextAppearanceSpan array specifying styles to be used to present text field. + */ + @Override + protected MetricAffectingSpan[] getAppearanceForText(@AnswerTextType int type) { + return mIsAnswer ? getAppearanceForAnswerText(type) : getAppearanceForQueryText(type); + } + + /** + * Return text styles for elements in main line holding answer. + * + * @param type The answer type as specified at http://goto.google.com/ais_api. + * @return array of TextAppearanceSpan objects defining style for the text. + */ + private MetricAffectingSpan[] getAppearanceForAnswerText(@AnswerTextType int type) { + @StyleRes + int res = 0; + + switch (type) { + case AnswerTextType.DESCRIPTION_NEGATIVE: + res = R.style.TextAppearance_OmniboxAnswerDescriptionNegativeSmall; + break; + + case AnswerTextType.DESCRIPTION_POSITIVE: + res = R.style.TextAppearance_OmniboxAnswerDescriptionPositiveSmall; + break; + + case AnswerTextType.SUGGESTION_SECONDARY_TEXT_MEDIUM: + res = R.style.TextAppearance_BlackDisabledText2; + break; + + case AnswerTextType.SUGGESTION: + case AnswerTextType.PERSONALIZED_SUGGESTION: + case AnswerTextType.ANSWER_TEXT_MEDIUM: + case AnswerTextType.ANSWER_TEXT_LARGE: + case AnswerTextType.TOP_ALIGNED: + case AnswerTextType.SUGGESTION_SECONDARY_TEXT_SMALL: + res = R.style.TextAppearance_BlackTitle1; + break; + + default: + Log.w(TAG, "Unknown answer type: " + type); + res = R.style.TextAppearance_BlackTitle1; + break; + } + + return new TextAppearanceSpan[] {new TextAppearanceSpan(mContext, res)}; + } + + /** + * Return text styles for elements in second line holding query. + * + * @param type The answer type as specified at http://goto.google.com/ais_api. + * @return array of TextAppearanceSpan objects defining style for the text. + */ + private MetricAffectingSpan[] getAppearanceForQueryText(@AnswerTextType int type) { + return new TextAppearanceSpan[] { + new TextAppearanceSpan(mContext, R.style.TextAppearance_BlackHint2)}; + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/BasicSuggestionProcessor.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/BasicSuggestionProcessor.java index 3c098ca..ebaff9b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/BasicSuggestionProcessor.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/BasicSuggestionProcessor.java
@@ -156,7 +156,7 @@ SuggestionViewProperties.TEXT_LINE_1_TEXT, new SuggestionTextContainer(textLine1)); model.set(SuggestionViewProperties.TEXT_LINE_1_SIZING, Pair.create(TypedValue.COMPLEX_UNIT_PX, - mContext.getResources().getDimension( + (int) mContext.getResources().getDimension( org.chromium.chrome.R.dimen .omnibox_suggestion_first_line_text_size))); @@ -166,7 +166,7 @@ model.set(SuggestionViewProperties.TEXT_LINE_2_TEXT_DIRECTION, textLine2Direction); model.set(SuggestionViewProperties.TEXT_LINE_2_SIZING, Pair.create(TypedValue.COMPLEX_UNIT_PX, - mContext.getResources().getDimension( + (int) mContext.getResources().getDimension( org.chromium.chrome.R.dimen .omnibox_suggestion_second_line_text_size))); model.set(SuggestionViewProperties.TEXT_LINE_1_MAX_LINES, 1);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/SuggestionViewProperties.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/SuggestionViewProperties.java index 233ab82..7641eaa 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/SuggestionViewProperties.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/SuggestionViewProperties.java
@@ -126,7 +126,7 @@ * The first item is the unit of size (e.g. TypedValue.COMPLEX_UNIT_PX), and the second item * is the size itself. */ - public static final WritableObjectPropertyKey<Pair<Integer, Float>> TEXT_LINE_1_SIZING = + public static final WritableObjectPropertyKey<Pair<Integer, Integer>> TEXT_LINE_1_SIZING = new WritableObjectPropertyKey<>(); /** The maximum number of lines to be shown for the first line of text. */ public static final WritableIntPropertyKey TEXT_LINE_1_MAX_LINES = new WritableIntPropertyKey(); @@ -146,7 +146,7 @@ * The first item is the unit of size (e.g. TypedValue.COMPLEX_UNIT_PX), and the second item * is the size itself. */ - public static final WritableObjectPropertyKey<Pair<Integer, Float>> TEXT_LINE_2_SIZING = + public static final WritableObjectPropertyKey<Pair<Integer, Integer>> TEXT_LINE_2_SIZING = new WritableObjectPropertyKey<>(); /** The maximum number of lines to be shown for the second line of text. */ public static final WritableIntPropertyKey TEXT_LINE_2_MAX_LINES = new WritableIntPropertyKey();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/SuggestionViewViewBinder.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/SuggestionViewViewBinder.java index dca5eab..40b617c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/SuggestionViewViewBinder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/SuggestionViewViewBinder.java
@@ -126,7 +126,7 @@ view.setSuggestionIconDrawable( drawableId, model.get(SuggestionCommonProperties.USE_DARK_COLORS), allowTint); } else if (SuggestionViewProperties.TEXT_LINE_1_SIZING.equals(propertyKey)) { - Pair<Integer, Float> sizing = model.get(SuggestionViewProperties.TEXT_LINE_1_SIZING); + Pair<Integer, Integer> sizing = model.get(SuggestionViewProperties.TEXT_LINE_1_SIZING); view.getTextLine1().setTextSize(sizing.first, sizing.second); } else if (SuggestionViewProperties.TEXT_LINE_1_MAX_LINES.equals(propertyKey)) { updateSuggestionLayoutType(view, model); @@ -141,7 +141,7 @@ } else if (SuggestionViewProperties.TEXT_LINE_1_TEXT.equals(propertyKey)) { view.getTextLine1().setText(model.get(SuggestionViewProperties.TEXT_LINE_1_TEXT).text); } else if (SuggestionViewProperties.TEXT_LINE_2_SIZING.equals(propertyKey)) { - Pair<Integer, Float> sizing = model.get(SuggestionViewProperties.TEXT_LINE_2_SIZING); + Pair<Integer, Integer> sizing = model.get(SuggestionViewProperties.TEXT_LINE_2_SIZING); view.getTextLine2().setTextSize(sizing.first, sizing.second); } else if (SuggestionViewProperties.TEXT_LINE_2_MAX_LINES.equals(propertyKey)) { updateSuggestionLayoutType(view, model);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/editurl/EditUrlSuggestionProcessor.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/editurl/EditUrlSuggestionProcessor.java index 64dedfc..3f25431 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/editurl/EditUrlSuggestionProcessor.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/editurl/EditUrlSuggestionProcessor.java
@@ -119,6 +119,12 @@ /** Whether a timing event should be recorded. This will be true once per omnibox focus. */ private boolean mShouldRecordTimingEvent; + /** Whether the first suggestion after an omnibox focus event has been processed. */ + private boolean mFirstSuggestionProcessedForCurrentOmniboxFocus; + + /** Whether this processor should ignore all subsequent suggestion. */ + private boolean mIgnoreSuggestions; + /** * @param locationBarDelegate A means of modifying the location bar. * @param selectionHandler A mechanism for handling selection of the edit URL suggestion item. @@ -143,8 +149,19 @@ @Override public boolean doesProcessSuggestion(OmniboxSuggestion suggestion) { Tab activeTab = mTabProvider != null ? mTabProvider.getActivityTab() : null; - if (OmniboxSuggestionType.URL_WHAT_YOU_TYPED != suggestion.getType() || activeTab == null - || activeTab.isIncognito() || activeTab.isNativePage()) { + + // The what-you-typed suggestion can potentially appear as the second suggestion in some + // cases. If the first suggestion isn't the one we want, ignore all subsequent suggestions. + if (!mFirstSuggestionProcessedForCurrentOmniboxFocus) { + mFirstSuggestionProcessedForCurrentOmniboxFocus = true; + mIgnoreSuggestions = activeTab == null || activeTab.isNativePage() + || activeTab.isIncognito() + || OmniboxSuggestionType.URL_WHAT_YOU_TYPED != suggestion.getType() + || !TextUtils.equals(suggestion.getUrl(), activeTab.getUrl()); + } + + if (OmniboxSuggestionType.URL_WHAT_YOU_TYPED != suggestion.getType() + || mIgnoreSuggestions) { return false; } mLastProcessedSuggestion = suggestion; @@ -231,6 +248,8 @@ mOriginalTitle = null; mHasClearedOmniboxForFocus = false; mLastProcessedSuggestion = null; + mFirstSuggestionProcessedForCurrentOmniboxFocus = false; + mIgnoreSuggestions = false; } mShouldRecordTimingEvent = hasFocus; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/SyncPreferenceUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/SyncPreferenceUtils.java index 978c2ad..7741be32 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/SyncPreferenceUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/SyncPreferenceUtils.java
@@ -10,6 +10,7 @@ import org.chromium.base.BuildInfo; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.sync.GoogleServiceAuthError; import org.chromium.chrome.browser.sync.ProfileSyncService; @@ -60,11 +61,11 @@ Resources res = context.getResources(); if (!AndroidSyncSettings.get().isMasterSyncEnabled()) { - return res.getString(org.chromium.chrome.R.string.sync_android_master_sync_disabled); + return res.getString(R.string.sync_android_master_sync_disabled); } if (profileSyncService == null) { - return res.getString(org.chromium.chrome.R.string.sync_is_disabled); + return res.getString(R.string.sync_is_disabled); } if (profileSyncService.getAuthError() != GoogleServiceAuthError.State.NONE) { @@ -74,33 +75,31 @@ if (profileSyncService.getProtocolErrorClientAction() == ProtocolErrorClientAction.UPGRADE_CLIENT) { - return res.getString(org.chromium.chrome.R.string.sync_error_upgrade_client, - BuildInfo.getInstance().hostPackageLabel); + return res.getString( + R.string.sync_error_upgrade_client, BuildInfo.getInstance().hostPackageLabel); } if (profileSyncService.hasUnrecoverableError()) { - return res.getString(org.chromium.chrome.R.string.sync_error_generic); + return res.getString(R.string.sync_error_generic); } String accountName = ChromeSigninController.get().getSignedInAccountName(); boolean syncEnabled = AndroidSyncSettings.get().isSyncEnabled(); if (syncEnabled) { if (!profileSyncService.isSyncActive()) { - return res.getString(org.chromium.chrome.R.string.sync_setup_progress); + return res.getString(R.string.sync_setup_progress); } if (profileSyncService.isPassphraseRequiredForDecryption()) { - return res.getString(org.chromium.chrome.R.string.sync_need_passphrase); + return res.getString(R.string.sync_need_passphrase); } - return context.getString( - org.chromium.chrome.R.string.account_management_sync_summary, accountName); + return context.getString(R.string.account_management_sync_summary, accountName); } if (ChromeFeatureList.isEnabled(ChromeFeatureList.UNIFIED_CONSENT)) { - return context.getString( - org.chromium.chrome.R.string.account_management_sync_off_summary, accountName); + return context.getString(R.string.account_management_sync_off_summary, accountName); } - return context.getString(org.chromium.chrome.R.string.sync_is_disabled); + return context.getString(R.string.sync_is_disabled); } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsBinder.java b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsBinder.java index 4b110118..b2a44a3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsBinder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsBinder.java
@@ -30,7 +30,7 @@ import org.chromium.base.SysUtils; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList; -import org.chromium.chrome.browser.compositor.layouts.ChromeAnimation; +import org.chromium.chrome.browser.compositor.animation.CompositorAnimationHandler; import org.chromium.chrome.browser.download.DownloadUtils; import org.chromium.chrome.browser.download.ui.DownloadFilter; import org.chromium.chrome.browser.ntp.cards.NewTabPageViewHolder; @@ -336,9 +336,8 @@ mThumbnailView.setScaleType(ImageView.ScaleType.CENTER_CROP); mThumbnailView.setBackground(null); if (!mIsContextual) ApiCompatibilityUtils.setImageTintList(mThumbnailView, null); - int duration = (int) (FADE_IN_ANIMATION_TIME_MS - * ChromeAnimation.Animation.getAnimationMultiplier()); - if (duration == 0) { + int duration = FADE_IN_ANIMATION_TIME_MS; + if (CompositorAnimationHandler.isInTestingMode()) { mThumbnailView.setImageDrawable(thumbnail); return; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabThemeColorHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabThemeColorHelper.java index aee1e2d..2e3774a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabThemeColorHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabThemeColorHelper.java
@@ -72,8 +72,6 @@ * @return The theme color that should be used for this tab. */ private int calculateThemeColor(boolean didWebContentsThemeColorChange) { - if (mTab.isNativePage()) return mTab.getNativePage().getThemeColor(); - // Start by assuming the current theme color is that one that should be used. This will // either be transparent, the last theme color, or the color restored from TabState. int themeColor = @@ -93,6 +91,7 @@ themeColor = getDefaultColor(); } + if (mTab.isNativePage()) themeColor = getDefaultColor(); if (mTab.isShowingInterstitialPage()) themeColor = getDefaultColor(); if (themeColor == Color.TRANSPARENT) themeColor = getDefaultColor();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/features.gni b/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/features.gni index ea90369..cee4777 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/features.gni +++ b/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/features.gni
@@ -3,7 +3,9 @@ # found in the LICENSE file. import("//build/config/android/config.gni") +import("//chrome/android/channel.gni") declare_args() { - enable_usage_stats = android_sdk_release == "q" + enable_usage_stats = android_channel == "default" || + android_channel == "canary" || android_channel == "dev" }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/util/FeatureUtilities.java b/chrome/android/java/src/org/chromium/chrome/browser/util/FeatureUtilities.java index 46829e9..583ce3be 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/util/FeatureUtilities.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/util/FeatureUtilities.java
@@ -480,6 +480,13 @@ && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O; } + /** + * @return Whether no-touch-mode is enabled. + */ + public static boolean isNoTouchModeEnabled() { + return CommandLine.getInstance().hasSwitch(ChromeSwitches.NO_TOUCH_MODE); + } + private static native void nativeSetCustomTabVisible(boolean visible); private static native void nativeSetIsInMultiWindowMode(boolean isInMultiWindowMode); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/vr/VrDelegateFallback.java b/chrome/android/java/src/org/chromium/chrome/browser/vr/VrDelegateFallback.java index b34df98..c79129be 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/vr/VrDelegateFallback.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/vr/VrDelegateFallback.java
@@ -133,6 +133,20 @@ // more details in {VrShellDelegate#maybeHandleVrIntentPreNative}. addBlackOverlayViewForActivity(activity); setSystemUiVisibilityForVr(activity); + + // Flag whether enter VR flow is handled already. + AtomicBoolean enterVrHandled = new AtomicBoolean(false); + + VrModuleProvider.installModule((success) -> { + if (enterVrHandled.getAndSet(true)) return; + onVrModuleInstallFinished(success); + }); + + PostTask.postDelayedTask(UiThreadTaskTraits.DEFAULT, () -> { + if (enterVrHandled.getAndSet(true)) return; + assert !VrModuleProvider.isModuleInstalled(); + onVrModuleInstallFailure(activity); + }, WAITING_FOR_MODULE_TIMEOUT_MS); } @Override @@ -149,20 +163,6 @@ activity.finish(); return; } - - // Flag whether enter VR flow is handled already. - AtomicBoolean enterVrHandled = new AtomicBoolean(false); - - VrModuleProvider.installModule((success) -> { - if (enterVrHandled.getAndSet(true)) return; - onVrModuleInstallFinished(success); - }); - - PostTask.postDelayedTask(UiThreadTaskTraits.DEFAULT, () -> { - if (enterVrHandled.getAndSet(true)) return; - assert !VrModuleProvider.isModuleInstalled(); - onVrModuleInstallFailure(activity); - }, WAITING_FOR_MODULE_TIMEOUT_MS); } @Override
diff --git a/chrome/android/java/strings/android_chrome_strings.grd b/chrome/android/java/strings/android_chrome_strings.grd index 35ee974..032a65b 100644 --- a/chrome/android/java/strings/android_chrome_strings.grd +++ b/chrome/android/java/strings/android_chrome_strings.grd
@@ -35,6 +35,7 @@ <output filename="values-am/android_chrome_strings.xml" lang="am" type="android" /> <output filename="values-ar/android_chrome_strings.xml" lang="ar" type="android" /> <output filename="values-bg/android_chrome_strings.xml" lang="bg" type="android" /> + <output filename="values-bn/android_chrome_strings.xml" lang="bn" type="android" /> <output filename="values-ca/android_chrome_strings.xml" lang="ca" type="android" /> <output filename="values-cs/android_chrome_strings.xml" lang="cs" type="android" /> <output filename="values-da/android_chrome_strings.xml" lang="da" type="android" /> @@ -44,10 +45,12 @@ <output filename="values-en-rGB/android_chrome_strings.xml" lang="en-GB" type="android" /> <output filename="values-es/android_chrome_strings.xml" lang="es" type="android" /> <output filename="values-es-rUS/android_chrome_strings.xml" lang="es-419" type="android" /> + <output filename="values-et/android_chrome_strings.xml" lang="et" type="android" /> <output filename="values-fa/android_chrome_strings.xml" lang="fa" type="android" /> <output filename="values-fi/android_chrome_strings.xml" lang="fi" type="android" /> <output filename="values-tl/android_chrome_strings.xml" lang="fil" type="android" /> <output filename="values-fr/android_chrome_strings.xml" lang="fr" type="android" /> + <output filename="values-gu/android_chrome_strings.xml" lang="gu" type="android" /> <output filename="values-hi/android_chrome_strings.xml" lang="hi" type="android" /> <output filename="values-hr/android_chrome_strings.xml" lang="hr" type="android" /> <output filename="values-hu/android_chrome_strings.xml" lang="hu" type="android" /> @@ -55,9 +58,13 @@ <output filename="values-it/android_chrome_strings.xml" lang="it" type="android" /> <output filename="values-iw/android_chrome_strings.xml" lang="iw" type="android" /> <output filename="values-ja/android_chrome_strings.xml" lang="ja" type="android" /> + <output filename="values-kn/android_chrome_strings.xml" lang="kn" type="android" /> <output filename="values-ko/android_chrome_strings.xml" lang="ko" type="android" /> <output filename="values-lt/android_chrome_strings.xml" lang="lt" type="android" /> <output filename="values-lv/android_chrome_strings.xml" lang="lv" type="android" /> + <output filename="values-ml/android_chrome_strings.xml" lang="ml" type="android" /> + <output filename="values-mr/android_chrome_strings.xml" lang="mr" type="android" /> + <output filename="values-ms/android_chrome_strings.xml" lang="ms" type="android" /> <output filename="values-nl/android_chrome_strings.xml" lang="nl" type="android" /> <output filename="values-nb/android_chrome_strings.xml" lang="no" type="android" /> <output filename="values-pl/android_chrome_strings.xml" lang="pl" type="android" /> @@ -70,6 +77,8 @@ <output filename="values-sr/android_chrome_strings.xml" lang="sr" type="android" /> <output filename="values-sv/android_chrome_strings.xml" lang="sv" type="android" /> <output filename="values-sw/android_chrome_strings.xml" lang="sw" type="android" /> + <output filename="values-ta/android_chrome_strings.xml" lang="ta" type="android" /> + <output filename="values-te/android_chrome_strings.xml" lang="te" type="android" /> <output filename="values-th/android_chrome_strings.xml" lang="th" type="android" /> <output filename="values-tr/android_chrome_strings.xml" lang="tr" type="android" /> <output filename="values-uk/android_chrome_strings.xml" lang="uk" type="android" />
diff --git a/chrome/android/java_sources.gni b/chrome/android/java_sources.gni index 54d75c73..794333aa 100644 --- a/chrome/android/java_sources.gni +++ b/chrome/android/java_sources.gni
@@ -1165,7 +1165,9 @@ "java/src/org/chromium/chrome/browser/omnibox/suggestions/SuggestionListViewBinder.java", "java/src/org/chromium/chrome/browser/omnibox/suggestions/VoiceSuggestionProvider.java", "java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerSuggestionProcessor.java", - "java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerTextBuilder.java", + "java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerText.java", + "java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerTextClassic.java", + "java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/AnswerTextNewLayout.java", "java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/BasicSuggestionProcessor.java", "java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/SuggestionHost.java", "java/src/org/chromium/chrome/browser/omnibox/suggestions/basic/SuggestionView.java",
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/BluetoothChooserDialogTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/BluetoothChooserDialogTest.java index be8dcf4..b60c7b0 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/BluetoothChooserDialogTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/BluetoothChooserDialogTest.java
@@ -38,6 +38,8 @@ import org.chromium.ui.base.WindowAndroid; import org.chromium.ui.widget.TextViewWithClickableSpans; +import java.util.concurrent.Callable; + /** * Tests for the BluetoothChooserDialog class. */ @@ -135,18 +137,7 @@ final ListView items = (ListView) dialog.findViewById(R.id.items); final Button button = (Button) dialog.findViewById(R.id.positive); - CriteriaHelper.pollUiThread(new Criteria() { - @Override - public boolean isSatisfied() { - return items.getChildAt(0) != null; - } - }); - - Assert.assertEquals("Not all items have a view; positions may be incorrect.", - items.getChildCount(), items.getAdapter().getCount()); - - // Verify first item selected gets selected. - TouchCommon.singleClickView(items.getChildAt(position - 1)); + clickItemAtPosition(items, position - 1); CriteriaHelper.pollUiThread(new Criteria() { @Override @@ -165,6 +156,26 @@ }); } + private static void clickItemAtPosition(ListView listView, int position) { + CriteriaHelper.pollUiThread(() -> listView.getChildAt(0) != null); + + Callable<Boolean> isVisible = () -> { + int visibleStart = listView.getFirstVisiblePosition(); + int visibleEnd = visibleStart + listView.getChildCount() - 1; + return position >= visibleStart && position <= visibleEnd; + }; + + if (!ThreadUtils.runOnUiThreadBlockingNoException(isVisible)) { + ThreadUtils.runOnUiThreadBlocking(() -> listView.setSelection(position)); + CriteriaHelper.pollUiThread(isVisible); + } + + ThreadUtils.runOnUiThreadBlocking(() -> { + TouchCommon.singleClickView( + listView.getChildAt(position - listView.getFirstVisiblePosition())); + }); + } + /** * The messages include <*link*> ... </*link*> sections that are used to create clickable spans. * For testing the messages, this function returns the raw string without the tags.
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/TabThemeTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/TabThemeTest.java index 345b564..4cdb4158 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/TabThemeTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/TabThemeTest.java
@@ -121,9 +121,7 @@ // Navigate to a native page from a themed page. mActivityTestRule.loadUrl("chrome://newtab/"); // WebContents does not set theme color for native pages, so don't wait for the call. - int nativePageThemeColor = ThreadUtils.runOnUiThreadBlocking( - () -> tab.getNativePage().getThemeColor()); - assertColorsEqual(nativePageThemeColor, getThemeColor(tab)); + assertColorsEqual(getDefaultThemeColor(tab), getThemeColor(tab)); // Navigate to a themed page from a native page. curCallCount = themeColorHelper.getCallCount();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/TabsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/TabsTest.java index 277b0799..b4fb256 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/TabsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/TabsTest.java
@@ -164,10 +164,8 @@ return; } mActivityTestRule.startMainActivityOnBlankPage(); - mActivityTestRule.getActivity() - .getLayoutManager() - .getAnimationHandler() - .enableTestingMode(); + mActivityTestRule.getActivity().getLayoutManager().getAnimationHandler().setTestingMode( + true); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryViewTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryViewTest.java index f2b10c40..db4c2b7 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryViewTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryViewTest.java
@@ -22,6 +22,8 @@ import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.BAR_ITEMS; import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.BOTTOM_OFFSET_PX; import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.KEYBOARD_TOGGLE_VISIBLE; +import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.SHOW_KEYBOARD_CALLBACK; +import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.TAB_LAYOUT_ITEM; import static org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.VISIBLE; import static org.chromium.chrome.test.util.ViewUtils.VIEW_GONE; import static org.chromium.chrome.test.util.ViewUtils.VIEW_INVISIBLE; @@ -46,6 +48,7 @@ import org.chromium.chrome.browser.ChromeTabbedActivity; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.AutofillBarItem; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.BarItem; +import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.TabLayoutBarItem; import org.chromium.chrome.test.ChromeActivityTestRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.chrome.test.util.browser.Features; @@ -79,12 +82,23 @@ public void setUp() throws InterruptedException { mActivityTestRule.startMainActivityOnBlankPage(); ThreadUtils.runOnUiThreadBlocking(() -> { - mModel = new PropertyModel - .Builder(BAR_ITEMS, VISIBLE, KEYBOARD_TOGGLE_VISIBLE, BOTTOM_OFFSET_PX) - .with(BAR_ITEMS, new ListModel<>()) - .with(VISIBLE, false) - .with(KEYBOARD_TOGGLE_VISIBLE, false) - .build(); + mModel = + new PropertyModel + .Builder(BAR_ITEMS, VISIBLE, BOTTOM_OFFSET_PX, TAB_LAYOUT_ITEM, + KEYBOARD_TOGGLE_VISIBLE, SHOW_KEYBOARD_CALLBACK) + .with(BAR_ITEMS, new ListModel<>()) + .with(VISIBLE, false) + .with(KEYBOARD_TOGGLE_VISIBLE, false) + .with(TAB_LAYOUT_ITEM, + new TabLayoutBarItem(new TabLayoutBarItem.TabLayoutCallbacks() { + @Override + public void onTabLayoutBound( + KeyboardAccessoryTabLayoutView tabs) {} + @Override + public void onTabLayoutUnbound( + KeyboardAccessoryTabLayoutView tabs) {} + })) + .build(); ViewStub viewStub = mActivityTestRule.getActivity().findViewById(R.id.keyboard_accessory_stub);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingIntegrationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingIntegrationTest.java index 81969149..3f35d94 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingIntegrationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingIntegrationTest.java
@@ -5,6 +5,7 @@ package org.chromium.chrome.browser.autofill.keyboard_accessory; import static android.support.test.espresso.Espresso.onView; +import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.assertion.ViewAssertions.doesNotExist; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.assertThat; @@ -195,6 +196,7 @@ @Test @SmallTest + @Features.DisableFeatures({ChromeFeatureList.AUTOFILL_KEYBOARD_ACCESSORY}) public void testHidingSheetBringsBackKeyboard() throws InterruptedException, TimeoutException { mHelper.loadTestPage(false); @@ -228,12 +230,13 @@ // Focus the field to bring up the autofill popup. We force a accessory here because the // autofill popup doesn't trigger on password fields. - mHelper.clickEmailField(true); + mHelper.clickEmailField(); mHelper.waitForKeyboard(); DropdownPopupWindowInterface popup = mHelper.waitForAutofillPopup("a.tu"); assertThat(popup.isShowing(), is(true)); + mHelper.requestShowKeyboardAccessory(); // Override hiding requested by bridge. // Click the tab to show the sheet and hide keyboard and popup. whenDisplayed(allOf(isDisplayed(), isAssignableFrom(KeyboardAccessoryTabLayoutView.class))) @@ -257,7 +260,7 @@ whenDisplayed(allOf(isDisplayed(), isAssignableFrom(KeyboardAccessoryTabLayoutView.class))); // Clicking the email field hides the accessory again. - mHelper.clickEmailField(false); + mHelper.clickEmailField(); mHelper.waitToBeHidden(withId(R.id.keyboard_accessory)); } @@ -374,7 +377,7 @@ assertThat(mActivityTestRule.getInfoBarContainer().getVisibility(), is(not(View.VISIBLE))); // Clicking another field hides the accessory, but the InfoBar should remain invisible. - mHelper.clickEmailField(false); + mHelper.clickEmailField(); assertThat(mActivityTestRule.getInfoBarContainer().getVisibility(), is(not(View.VISIBLE))); // Close the keyboard to bring back the InfoBar. @@ -422,8 +425,7 @@ assertThat(mActivityTestRule.getInfoBarContainer().getVisibility(), is(not(View.VISIBLE))); // Reopen the keyboard, then close it. - whenDisplayed(allOf(isDisplayed(), isAssignableFrom(KeyboardAccessoryTabLayoutView.class))) - .perform(selectTabAtPosition(0)); + whenDisplayed(withId(R.id.show_keyboard)).perform(click()); mHelper.waitForKeyboard(); ThreadUtils.runOnUiThreadBlocking(() -> { mActivityTestRule.getKeyboardDelegate().hideKeyboard( @@ -468,7 +470,7 @@ onView(withText(kSnackbarText)).check(matches(isCompletelyDisplayed())); // Click into the email field to dismiss the keyboard accessory. - mHelper.clickEmailField(false); + mHelper.clickEmailField(); mHelper.waitToBeHidden(withId(R.id.keyboard_accessory)); onView(withText(kSnackbarText)).check(matches(isCompletelyDisplayed())); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingTestHelper.java b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingTestHelper.java index e2ea569..9338e798 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingTestHelper.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingTestHelper.java
@@ -132,14 +132,9 @@ getKeyboard().showKeyboard(mActivityTestRule.getActivity().getCurrentFocus()); } - public void clickEmailField(boolean forceAccessory) - throws TimeoutException, InterruptedException { + public void clickEmailField() throws TimeoutException, InterruptedException { DOMUtils.clickNode(mWebContentsRef.get(), "email"); - if (forceAccessory) { - requestShowKeyboardAccessory(); - } else { - requestHideKeyboardAccessory(); - } + requestHideKeyboardAccessory(); getKeyboard().showKeyboard(mActivityTestRule.getActivity().getCurrentFocus()); } @@ -274,7 +269,7 @@ * In order to make sure the keyboard accessory is only shown on appropriate fields, a request * to show is usually sent from the native side. This method simulates that request. */ - private void requestShowKeyboardAccessory() { + public void requestShowKeyboardAccessory() { ThreadUtils.runOnUiThreadBlocking(() -> { mActivityTestRule.getActivity() .getManualFillingController()
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingUiCaptureTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingUiCaptureTest.java index 0231dcd..8146941 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingUiCaptureTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingUiCaptureTest.java
@@ -5,24 +5,20 @@ package org.chromium.chrome.browser.autofill.keyboard_accessory; import static android.support.test.espresso.Espresso.onView; +import static android.support.test.espresso.contrib.RecyclerViewActions.actionOnItem; +import static android.support.test.espresso.contrib.RecyclerViewActions.scrollTo; import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom; -import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withParent; -import static org.hamcrest.core.AllOf.allOf; - import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout; import static org.chromium.chrome.browser.autofill.keyboard_accessory.ManualFillingTestHelper.createTestCredentials; import static org.chromium.chrome.browser.autofill.keyboard_accessory.ManualFillingTestHelper.scrollToLastElement; import static org.chromium.chrome.browser.autofill.keyboard_accessory.ManualFillingTestHelper.selectTabAtPosition; import static org.chromium.chrome.browser.autofill.keyboard_accessory.ManualFillingTestHelper.whenDisplayed; -import android.support.annotation.Nullable; -import android.support.test.espresso.NoMatchingViewException; import android.support.test.filters.MediumTest; import android.support.v7.widget.RecyclerView; -import android.view.View; import org.junit.After; import org.junit.Rule; @@ -40,7 +36,7 @@ import org.chromium.chrome.test.ChromeTabbedActivityTestRule; import org.chromium.chrome.test.util.browser.Features.DisableFeatures; import org.chromium.chrome.test.util.browser.Features.EnableFeatures; -import org.chromium.content_public.browser.test.util.CriteriaHelper; +import org.chromium.chrome.test.util.browser.RecyclerViewTestUtils; import java.util.concurrent.TimeoutException; @@ -87,8 +83,7 @@ mHelper.sendCredentials(createTestCredentials()); - whenDisplayed(allOf(isDisplayed(), isAssignableFrom(KeyboardAccessoryTabLayoutView.class))) - .perform(selectTabAtPosition(0)); + whenDisplayed(withId(R.id.tabs)).perform(selectTabAtPosition(0)); waitForSuggestionsInSheet(); waitForUnrelatedChromeUi(); mScreenShooter.shoot("AccessorySheetPasswords"); @@ -116,8 +111,7 @@ mHelper.sendCredentials(createTestCredentials()); - whenDisplayed(allOf(isDisplayed(), isAssignableFrom(KeyboardAccessoryTabLayoutView.class))) - .perform(selectTabAtPosition(0)); + whenDisplayed(withId(R.id.tabs)).perform(selectTabAtPosition(0)); waitForSuggestionsInSheet(); waitForUnrelatedChromeUi(); mScreenShooter.shoot("AccessorySheetPasswordsRTL"); @@ -145,9 +139,11 @@ mScreenShooter.shoot("AccessoryBarV2"); mHelper.sendCredentials(createTestCredentials()); + whenDisplayed(withId(R.id.bar_items_view)) + .perform(scrollTo(isAssignableFrom(KeyboardAccessoryTabLayoutView.class)), + actionOnItem(isAssignableFrom(KeyboardAccessoryTabLayoutView.class), + selectTabAtPosition(0))); - whenDisplayed(allOf(isDisplayed(), isAssignableFrom(KeyboardAccessoryTabLayoutView.class))) - .perform(selectTabAtPosition(0)); waitForSuggestionsInSheet(); waitForUnrelatedChromeUi(); mScreenShooter.shoot("AccessorySheetPasswordsV2"); @@ -176,8 +172,11 @@ mHelper.sendCredentials(createTestCredentials()); - whenDisplayed(allOf(isDisplayed(), isAssignableFrom(KeyboardAccessoryTabLayoutView.class))) - .perform(selectTabAtPosition(0)); + whenDisplayed(withId(R.id.bar_items_view)) + .perform(scrollTo(isAssignableFrom(KeyboardAccessoryTabLayoutView.class)), + actionOnItem(isAssignableFrom(KeyboardAccessoryTabLayoutView.class), + selectTabAtPosition(0))); + waitForSuggestionsInSheet(); waitForUnrelatedChromeUi(); mScreenShooter.shoot("AccessorySheetPasswordsV2RTL"); @@ -188,28 +187,23 @@ mScreenShooter.shoot("AccessorySheetPasswordsV2ScrolledRTL"); } - private void waitUntilFilled(View view, @Nullable NoMatchingViewException noViewFound) { - if (noViewFound != null) throw noViewFound; - assert view instanceof RecyclerView; - final RecyclerView recyclerView = (RecyclerView) view; - CriteriaHelper.pollUiThread(() -> { - if (recyclerView.getChildCount() <= 0) return false; - View firstChild = recyclerView.getChildAt(0); - return firstChild.isShown() && !firstChild.isDirty() && !firstChild.isLayoutRequested(); - }); - } - private void waitForUnrelatedChromeUi() throws InterruptedException { Thread.sleep(scaleTimeout(50)); // Reduces flakiness due to delayed events. } private void waitForActionsInAccessory() { whenDisplayed(withId(R.id.bar_items_view)); - onView(withId(R.id.bar_items_view)).check(this::waitUntilFilled); + onView(withId(R.id.bar_items_view)).check((view, noViewFound) -> { + if (noViewFound != null) throw noViewFound; + RecyclerViewTestUtils.waitForStableRecyclerView((RecyclerView) view); + }); } private void waitForSuggestionsInSheet() { whenDisplayed(withId(R.id.keyboard_accessory_sheet)); - onView(withParent(withId(R.id.keyboard_accessory_sheet))).check(this::waitUntilFilled); + onView(withParent(withId(R.id.keyboard_accessory_sheet))).check((view, noViewFound) -> { + if (noViewFound != null) throw noViewFound; + RecyclerViewTestUtils.waitForStableRecyclerView((RecyclerView) view); + }); } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerTest.java index 4e78309..78c8e91 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerTest.java
@@ -134,7 +134,7 @@ mManagerPhone = new LayoutManagerChromePhone(layoutManagerHost); mManager = mManagerPhone; - mManager.getAnimationHandler().enableTestingMode(); + mManager.getAnimationHandler().setTestingMode(true); mManager.init(mTabModelSelector, null, null, container, null, null); initializeMotionEvent(); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java index bf24f33a4..05ad186 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java
@@ -2951,7 +2951,7 @@ @Feature({"ContextualSearch"}) @Features.DisableFeatures({ChromeFeatureList.CONTEXTUAL_SUGGESTIONS_BUTTON}) public void testQuickActionCaptionAndImage() throws InterruptedException, TimeoutException { - mPanel.getAnimationHandler().enableTestingMode(); + mPanel.getAnimationHandler().setTestingMode(true); // Simulate a tap to show the Bar, then set the quick action data. simulateTapSearch("search");
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/offlinepages/OfflinePageAutoFetchTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/offlinepages/OfflinePageAutoFetchTest.java index 15efea11..4f78044 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/offlinepages/OfflinePageAutoFetchTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/offlinepages/OfflinePageAutoFetchTest.java
@@ -48,6 +48,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; @@ -58,6 +59,7 @@ "enable-features=AutoFetchOnNetErrorPage", "disable-features=NewNetErrorPageUI"}) public class OfflinePageAutoFetchTest { private static final String TAG = "AutoFetchTest"; + private static final long WAIT_TIMEOUT_MS = 20000; @Rule public ChromeActivityTestRule<ChromeActivity> mActivityTestRule = new ChromeActivityTestRule<>(ChromeActivity.class); @@ -156,7 +158,6 @@ @Test @MediumTest @Feature({"OfflineAutoFetch"}) - @DisabledTest(message = "Flaky: https://crbug.com/883486#c20") public void testAutoFetchOnDinoPage() throws Exception { startWebServer(); final String testUrl = mWebServer.getBaseUrl(); @@ -189,7 +190,7 @@ waitForHistogram("OfflinePages.AutoFetch.CompleteNotificationAction:TAPPED", 1); // A new tab should open, and it should load the offline page. - CriteriaHelper.pollInstrumentationThread(() -> { + pollInstrumentationThread(() -> { return getCurrentTabModel().getCount() == 2 && getCurrentTab().getTitle().equals("MyTestPage"); }); @@ -198,7 +199,6 @@ @Test @MediumTest @Feature({"OfflineAutoFetch"}) - @DisabledTest(message = "Flaky: https://crbug.com/883486#c20") public void testSwipeAwayCompleteNotification() throws Exception { // Standard setup to trigger auto-fetch. startWebServer(); @@ -224,7 +224,6 @@ @Test @MediumTest @Feature({"OfflineAutoFetch"}) - @DisabledTest(message = "Flaky: https://crbug.com/883486#c20") public void testAutoFetchCancelOnLoad() throws Exception { startWebServer(); final String testUrl = mWebServer.getBaseUrl(); @@ -275,7 +274,6 @@ @Test @MediumTest @Feature({"OfflineAutoFetch"}) - @DisabledTest(message = "Flaky: https://crbug.com/883486#c20") public void testAutoFetchNotifyOnTabClose() throws Exception { final String testUrl = "http://www.offline.com"; // Make |testUrl| return an offline error and attempt to load the page. @@ -292,7 +290,6 @@ @Test @MediumTest @Feature({"OfflineAutoFetch"}) - @DisabledTest(message = "Flaky: https://crbug.com/883486#c20") public void testAutoFetchSwipeInProgressNotification() throws Exception { // Trigger an auto-fetch request, and then an in-progress notification. final String testUrl = "http://www.offline.com"; @@ -312,7 +309,6 @@ @Test @MediumTest @Feature({"OfflineAutoFetch"}) - @DisabledTest(message = "Flaky: https://crbug.com/883486#c20") public void testAutoFetchTwoRequestsCancel() throws Exception { // Trigger two auto-fetch requests. final String testUrl1 = "http://www.offline1.com"; @@ -340,7 +336,7 @@ } private void waitForRequestCount(int requestCount) { - CriteriaHelper.pollInstrumentationThread( + pollInstrumentationThread( () -> OfflineTestUtil.getRequestsInQueue().length == requestCount); } @@ -350,7 +346,7 @@ } private void waitForPageAdded() throws Exception { - mPageAddedHelper.waitForCallback(0, 1, 10000, TimeUnit.MILLISECONDS); + mPageAddedHelper.waitForCallback(0, 1, WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS); } private Tab activityTab() { @@ -399,9 +395,8 @@ } private void waitForHistogram(String histogramAndEnum, int delta) { - CriteriaHelper.pollInstrumentationThread( - () - -> histogramSnapshot().get(histogramAndEnum) + pollInstrumentationThread(() + -> histogramSnapshot().get(histogramAndEnum) - mInitialHistograms.get(histogramAndEnum) >= delta); } @@ -480,4 +475,8 @@ } catch (TimeoutException | InterruptedException e) { } } + private void pollInstrumentationThread(final Callable<Boolean> criteria) { + CriteriaHelper.pollInstrumentationThread( + criteria, "Criteria not met", WAIT_TIMEOUT_MS, 100); + } }
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryControllerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryControllerTest.java index ff40fc67..3d12e95 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryControllerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryControllerTest.java
@@ -76,9 +76,7 @@ public void setUp() { ShadowRecordHistogram.reset(); MockitoAnnotations.initMocks(this); - HashMap<String, Boolean> features = new HashMap<>(); - features.put(ChromeFeatureList.AUTOFILL_KEYBOARD_ACCESSORY, true); - ChromeFeatureList.setTestFeatures(features); + setAutofillFeature(false); when(mMockView.getTabLayout()).thenReturn(mMockTabSwitcherView); mCoordinator = new KeyboardAccessoryCoordinator( @@ -87,6 +85,12 @@ mModel = mMediator.getModelForTesting(); } + private void setAutofillFeature(boolean enabled) { + HashMap<String, Boolean> features = new HashMap<>(); + features.put(ChromeFeatureList.AUTOFILL_KEYBOARD_ACCESSORY, enabled); + ChromeFeatureList.setTestFeatures(features); + } + @Test public void testCreatesValidSubComponents() { assertThat(mCoordinator, is(notNullValue())); @@ -112,6 +116,9 @@ @Test public void testModelNotifiesAboutActionsChangedByProvider() { + // Set a default tab to prevent visibility changes to trigger now: + mCoordinator.setTabs(new KeyboardAccessoryData.Tab[] { + new KeyboardAccessoryData.Tab(null, null, 0, AccessoryTabType.PASSWORDS, null)}); mModel.get(BAR_ITEMS).addObserver(mMockActionListObserver); PropertyProvider<Action[]> testProvider = @@ -144,6 +151,46 @@ } @Test + public void testModelNotifiesAboutActionsChangedByProviderForRedesign() { + setAutofillFeature(true); + // Set a default tab to prevent visibility changes to trigger now: + mCoordinator.setTabs(new KeyboardAccessoryData.Tab[] { + new KeyboardAccessoryData.Tab(null, null, 0, AccessoryTabType.PASSWORDS, null)}); + mModel.get(BAR_ITEMS).addObserver(mMockActionListObserver); + + PropertyProvider<Action[]> testProvider = + new PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC); + mCoordinator.registerActionProvider(testProvider); + + // If the coordinator receives an initial action, the model should report an insertion. + mCoordinator.requestShowing(); + + Action testAction = new Action(null, 0, null); + testProvider.notifyObservers(new Action[] {testAction}); + verify(mMockActionListObserver).onItemRangeInserted(mModel.get(BAR_ITEMS), 0, 2); + assertThat(mModel.get(BAR_ITEMS).size(), is(2)); // Plus tab switcher. + assertThat(mModel.get(BAR_ITEMS).get(0).getAction(), is(equalTo(testAction))); + + // If the coordinator receives a new set of actions, the model should report a change. + testProvider.notifyObservers(new Action[] {testAction}); + verify(mMockActionListObserver).onItemRangeChanged(mModel.get(BAR_ITEMS), 0, 2, null); + assertThat(mModel.get(BAR_ITEMS).size(), is(2)); // Plus tab switcher. + assertThat(mModel.get(BAR_ITEMS).get(0).getAction(), is(equalTo(testAction))); + + // If the coordinator receives an empty set of actions, the model should report a deletion. + testProvider.notifyObservers(new Action[] {}); + // First call of onItemRangeChanged(mModel.get(BAR_ITEMS), 0, 1, null); + verify(mMockActionListObserver).onItemRangeRemoved(mModel.get(BAR_ITEMS), 1, 1); + assertThat(mModel.get(BAR_ITEMS).size(), is(1)); // Only the tab switcher. + + // There should be no notification if no actions are reported repeatedly. + testProvider.notifyObservers(new Action[] {}); + verify(mMockActionListObserver, times(2)) + .onItemRangeChanged(mModel.get(BAR_ITEMS), 0, 1, null); + verifyNoMoreInteractions(mMockActionListObserver); + } + + @Test public void testModelDoesntNotifyUnchangedVisibility() { mModel.addObserver(mMockPropertyObserver); @@ -240,7 +287,7 @@ new AutofillSuggestion[] {suggestion1, suggestion2}); generationProvider.notifyObservers(new Action[] {generationAction}); - // Autofill suggestions should always come last, independent of when they were added. + // Autofill suggestions should always come last before mandatory tab switcher. assertThat(mModel.get(BAR_ITEMS).size(), is(3)); assertThat(mModel.get(BAR_ITEMS).get(0).getAction(), is(generationAction)); assertThat(mModel.get(BAR_ITEMS).get(1), instanceOf(AutofillBarItem.class)); @@ -252,6 +299,31 @@ } @Test + public void testMovesTabSwitcherToEndForRedesign() { + setAutofillFeature(true); + KeyboardAccessoryData.PropertyProvider<Action[]> generationProvider = + new KeyboardAccessoryData.PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC); + KeyboardAccessoryData.PropertyProvider<Action[]> autofillSuggestionProvider = + new KeyboardAccessoryData.PropertyProvider<>(AUTOFILL_SUGGESTION); + + mCoordinator.registerActionProvider(generationProvider); + mCoordinator.registerActionProvider(autofillSuggestionProvider); + + Action suggestion1 = new Action("FirstSuggestion", AUTOFILL_SUGGESTION, (a) -> {}); + Action suggestion2 = new Action("SecondSuggestion", AUTOFILL_SUGGESTION, (a) -> {}); + Action generationAction = new Action("Generate", GENERATE_PASSWORD_AUTOMATIC, (a) -> {}); + autofillSuggestionProvider.notifyObservers(new Action[] {suggestion1, suggestion2}); + generationProvider.notifyObservers(new Action[] {generationAction}); + + // Autofill suggestions should always come last, independent of when they were added. + assertThat(mModel.get(BAR_ITEMS).size(), is(4)); // Additional tab switcher + assertThat(mModel.get(BAR_ITEMS).get(0).getAction(), is(generationAction)); + assertThat(mModel.get(BAR_ITEMS).get(1).getAction(), is(suggestion1)); + assertThat(mModel.get(BAR_ITEMS).get(2).getAction(), is(suggestion2)); + assertThat(mModel.get(BAR_ITEMS).get(3).getViewType(), is(BarItem.Type.TAB_LAYOUT)); + } + + @Test public void testDeletingActionsAffectsOnlyOneType() { KeyboardAccessoryData.PropertyProvider<Action[]> generationProvider = new KeyboardAccessoryData.PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC); @@ -322,8 +394,8 @@ // Adding an action contributes to the actions bucket. Tabs and total are logged again. mCoordinator.close(); // Hide, so it's brought up again. - mModel.get(BAR_ITEMS).add( - new BarItem(BarItem.Type.ACTION_BUTTON, new Action(null, 0, null))); + mModel.get(BAR_ITEMS).add(new BarItem( + BarItem.Type.ACTION_BUTTON, new Action(null, GENERATE_PASSWORD_AUTOMATIC, null))); mCoordinator.requestShowing(); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_ACTIONS), is(1)); @@ -363,16 +435,16 @@ KeyboardAccessoryMetricsRecorder.UMA_KEYBOARD_ACCESSORY_BAR_SHOWN), is(0)); - // First showing contains actions only. + // First showing contains tabs only. mCoordinator.addTab(mTestTab); mCoordinator.requestShowing(); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_TABS), is(1)); assertThat(getShownMetricsCount(AccessoryBarContents.ANY_CONTENTS), is(1)); - // Adding a tabs doesn't change the total impression count but the specific bucket. - mModel.get(BAR_ITEMS).add( - new BarItem(BarItem.Type.ACTION_BUTTON, new Action(null, 0, null))); + // New actions are recorded in specific buckets but don't affect the general ANY_CONTENTS. + mModel.get(BAR_ITEMS).add(new BarItem( + BarItem.Type.ACTION_BUTTON, new Action(null, GENERATE_PASSWORD_AUTOMATIC, null))); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_ACTIONS), is(1)); assertThat(getShownMetricsCount(AccessoryBarContents.ANY_CONTENTS), is(1)); @@ -401,22 +473,22 @@ mCoordinator.requestShowing(); // Adding an action fills the bar impression bucket and the actions set once. - mModel.get(BAR_ITEMS).set(new BarItem[] { - new BarItem(BarItem.Type.ACTION_BUTTON, - new Action("One", AccessoryAction.GENERATE_PASSWORD_AUTOMATIC, null)), - new BarItem(BarItem.Type.ACTION_BUTTON, - new Action("Two", AccessoryAction.GENERATE_PASSWORD_AUTOMATIC, null))}); - assertThat(getActionImpressionCount(AccessoryAction.GENERATE_PASSWORD_AUTOMATIC), is(1)); + mModel.get(BAR_ITEMS).set( + new BarItem[] {new BarItem(BarItem.Type.ACTION_BUTTON, + new Action("One", GENERATE_PASSWORD_AUTOMATIC, null)), + new BarItem(BarItem.Type.ACTION_BUTTON, + new Action("Two", GENERATE_PASSWORD_AUTOMATIC, null))}); + assertThat(getActionImpressionCount(GENERATE_PASSWORD_AUTOMATIC), is(1)); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_ACTIONS), is(1)); // Adding another action leaves bar impressions unchanged but affects the actions bucket. - mModel.get(BAR_ITEMS).set(new BarItem[] { - new BarItem(BarItem.Type.ACTION_BUTTON, - new Action("Uno", AccessoryAction.GENERATE_PASSWORD_AUTOMATIC, null)), - new BarItem(BarItem.Type.ACTION_BUTTON, - new Action("Dos", AccessoryAction.GENERATE_PASSWORD_AUTOMATIC, null))}); + mModel.get(BAR_ITEMS).set( + new BarItem[] {new BarItem(BarItem.Type.ACTION_BUTTON, + new Action("Uno", GENERATE_PASSWORD_AUTOMATIC, null)), + new BarItem(BarItem.Type.ACTION_BUTTON, + new Action("Dos", GENERATE_PASSWORD_AUTOMATIC, null))}); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_ACTIONS), is(1)); - assertThat(getActionImpressionCount(AccessoryAction.GENERATE_PASSWORD_AUTOMATIC), is(2)); + assertThat(getActionImpressionCount(GENERATE_PASSWORD_AUTOMATIC), is(2)); } private int getActionImpressionCount(@AccessoryAction int bucket) {
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingControllerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingControllerTest.java index 05856127..aea3b25 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingControllerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingControllerTest.java
@@ -177,12 +177,12 @@ Map<Tab, ManualFillingMediator.AccessoryState> model = mediator.getModelForTesting(); assertThat(model.size(), is(0)); - // Emulate adding a tab. Expect the model to have another entry. + // Emulate adding a browser tab. Expect the model to have another entry. Tab firstTab = addTab(mediator, 1111, null); assertThat(model.size(), is(1)); assertThat(model.get(firstTab), notNullValue()); - // Emulate adding a second tab. Expect the model to have another entry. + // Emulate adding a second browser tab. Expect the model to have another entry. Tab secondTab = addTab(mediator, 2222, firstTab); assertThat(model.size(), is(2)); assertThat(model.get(secondTab), notNullValue()); @@ -235,7 +235,7 @@ mController.registerActionProvider(firstTabProvider); firstTabProvider.notifyObservers(new Action[] { new Action("Generate Password", GENERATE_PASSWORD_AUTOMATIC, p -> {})}); - mMockItemListObserver.onItemRangeInserted(keyboardActions, 0, 1); + mMockItemListObserver.onItemRangeInserted(keyboardActions, 0, 2); assertThat(getFirstKeyboardActionTitle(), is("Generate Password")); // Simulate creating a second tab: @@ -243,7 +243,7 @@ mController.registerActionProvider(secondTabProvider); secondTabProvider.notifyObservers(new Action[0]); mMockItemListObserver.onItemRangeRemoved(keyboardActions, 0, 1); - assertThat(keyboardActions.size(), is(0)); // No actions on this tab. + assertThat(keyboardActions.size(), is(1)); // tab switcher is only item on this browser tab. // Simulate switching back to the first tab: switchTab(mediator, /*from=*/secondTab, /*to=*/firstTab); @@ -253,7 +253,7 @@ // And back to the second: switchTab(mediator, /*from=*/firstTab, /*to=*/secondTab); mMockItemListObserver.onItemRangeRemoved(keyboardActions, 0, 1); - assertThat(keyboardActions.size(), is(0)); // Still no actions on this tab. + assertThat(keyboardActions.size(), is(1)); // tab switcher is only item on this browser tab. } @Test @@ -342,7 +342,7 @@ Tab tab = addTab(mediator, 1111, null); // Add an action provider that never provided actions. mController.registerActionProvider(new PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC)); - assertThat(keyboardAccessoryModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size(), is(0)); + assertThat(keyboardAccessoryModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size(), is(1)); // Create a new tab with an action: Tab secondTab = addTab(mediator, 1111, tab); @@ -350,10 +350,10 @@ mController.registerActionProvider(provider); provider.notifyObservers(new Action[] { new Action("Test Action", GENERATE_PASSWORD_AUTOMATIC, (action) -> {})}); - assertThat(keyboardAccessoryModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size(), is(1)); + assertThat(keyboardAccessoryModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size(), is(2)); switchTab(mediator, secondTab, tab); - assertThat(keyboardAccessoryModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size(), is(0)); + assertThat(keyboardAccessoryModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size(), is(1)); } @Test @@ -368,27 +368,27 @@ PropertyProvider<Action[]> delayedProvider = new PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC); mController.registerActionProvider(delayedProvider); - assertThat(keyboardAccessoryModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size(), is(0)); + assertThat(keyboardAccessoryModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size(), is(1)); // Create and switch to a new tab: Tab secondTab = addTab(mediator, 1111, tab); PropertyProvider<Action[]> provider = new PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC); mController.registerActionProvider(provider); - // And provide data to the active tab. + // And provide data to the active browser tab. provider.notifyObservers(new Action[] { new Action("Test Action", GENERATE_PASSWORD_AUTOMATIC, (action) -> {})}); - // Now, have the delayed provider provide data for the backgrounded tab. + // Now, have the delayed provider provide data for the backgrounded browser tab. delayedProvider.notifyObservers( new Action[] {new Action("Delayed", GENERATE_PASSWORD_AUTOMATIC, (action) -> {})}); // The current tab should not be influenced by the delayed provider. - assertThat(keyboardAccessoryModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size(), is(1)); + assertThat(keyboardAccessoryModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size(), is(2)); assertThat(getFirstKeyboardActionTitle(), is("Test Action")); // Switching tabs back should only show the action that was received in the background. switchTab(mediator, secondTab, tab); - assertThat(keyboardAccessoryModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size(), is(1)); + assertThat(keyboardAccessoryModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size(), is(2)); assertThat(getFirstKeyboardActionTitle(), is("Delayed")); } @@ -428,7 +428,7 @@ // The current tab should be valid. assertThat(getTabLayout().getModelForTesting().get(TABS).size(), is(1)); assertThat(accessorySheetModel.get(AccessorySheetProperties.TABS).size(), is(1)); - assertThat(keyboardAccessoryModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size(), is(1)); + assertThat(keyboardAccessoryModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size(), is(2)); assertThat(getFirstKeyboardActionTitle(), is("2BKept")); // Request destruction of the first Tab: @@ -437,7 +437,7 @@ // The current tab should not be influenced by the destruction. assertThat(getTabLayout().getModelForTesting().get(TABS).size(), is(1)); assertThat(accessorySheetModel.get(AccessorySheetProperties.TABS).size(), is(1)); - assertThat(keyboardAccessoryModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size(), is(1)); + assertThat(keyboardAccessoryModel.get(KeyboardAccessoryProperties.BAR_ITEMS).size(), is(2)); assertThat(getFirstKeyboardActionTitle(), is("2BKept")); // The other tabs data should be gone. @@ -536,7 +536,7 @@ /** * Creates a tab and calls the observer events as if it was just created and switched to. * @param mediator The {@link ManualFillingMediator} whose observers should be triggered. - * @param id The id of the new tab. + * @param id The id of the new browser tab. * @param lastTab A previous mocked {@link Tab} to be hidden. Needs |getId()|. May be null. * @return Returns a mock of the newly added {@link Tab}. Provides |getId()|. */ @@ -651,12 +651,16 @@ } private String getFirstKeyboardActionTitle() { + int firstNonTabSwitcherAction = 1; + if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_KEYBOARD_ACCESSORY)) { + firstNonTabSwitcherAction = 0; + } return mController.getMediatorForTesting() .getKeyboardAccessory() .getMediatorForTesting() .getModelForTesting() .get(KeyboardAccessoryProperties.BAR_ITEMS) - .get(0) + .get(firstNonTabSwitcherAction) .getAction() .getCaption(); }
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBackgroundTaskUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBackgroundTaskUnitTest.java index 0174eae..964bec1 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBackgroundTaskUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBackgroundTaskUnitTest.java
@@ -33,6 +33,7 @@ import org.chromium.base.Callback; import org.chromium.base.library_loader.ProcessInitException; +import org.chromium.base.metrics.test.ShadowRecordHistogram; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.browser.background_task_scheduler.NativeBackgroundTask; import org.chromium.chrome.browser.init.BrowserParts; @@ -54,13 +55,15 @@ /** Unit tests for {@link ExploreSitesBackgroundTask}. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE, - shadows = {ShadowMultiDex.class, ShadowDeviceConditions.class, + shadows = {ShadowMultiDex.class, ShadowDeviceConditions.class, ShadowRecordHistogram.class, ExploreSitesBackgroundTaskUnitTest.ShadowExploreSitesBridge.class}) public class ExploreSitesBackgroundTaskUnitTest { /** Implementation of ExploreSitesBridge which does not rely on native. */ @Implements(ExploreSitesBridge.class) public static class ShadowExploreSitesBridge { public static Callback<Void> mUpdateCatalogFinishedCallback; + public static int mVariation = ExploreSitesVariation.ENABLED; + @Implementation public static void getEspCatalog( Profile profile, Callback<List<ExploreSitesCategory>> callback) {} @@ -70,6 +73,12 @@ Profile profile, boolean isImmediateFetch, Callback<Void> finishedCallback) { mUpdateCatalogFinishedCallback = finishedCallback; } + + @Implementation + @ExploreSitesVariation + public static int getVariation() { + return mVariation; + } } /** @@ -120,8 +129,13 @@ ArgumentCaptor<BrowserParts> mBrowserParts; private FakeBackgroundTaskScheduler mFakeTaskScheduler; + public void disableExploreSites() { + ShadowExploreSitesBridge.mVariation = ExploreSitesVariation.DISABLED; + } + @Before public void setUp() { + ShadowRecordHistogram.reset(); MockitoAnnotations.initMocks(this); doNothing().when(mChromeBrowserInitializer).handlePreNativeStartup(any(BrowserParts.class)); try { @@ -140,6 +154,8 @@ mFakeTaskScheduler = new FakeBackgroundTaskScheduler(); BackgroundTaskSchedulerFactory.setSchedulerForTesting(mFakeTaskScheduler); doReturn(null).when(mExploreSitesBackgroundTask).getProfile(); + + ShadowExploreSitesBridge.mVariation = ExploreSitesVariation.ENABLED; } @Test @@ -207,4 +223,52 @@ mFakeTaskScheduler.getTaskInfo(TaskIds.DEPRECATED_EXPLORE_SITES_REFRESH_JOB_ID); assertNull(deprecatedTask); } + + @Test + public void testRemovesTaskIfFeatureIsDisabled() throws Exception { + disableExploreSites(); + + TaskInfo.Builder taskInfoBuilder = + TaskInfo.createPeriodicTask(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID, + ExploreSitesBackgroundTask.class, TimeUnit.HOURS.toMillis(4), + TimeUnit.HOURS.toMillis(1)) + .setRequiredNetworkType(TaskInfo.NetworkType.ANY) + .setIsPersisted(true) + .setUpdateCurrent(false); + mFakeTaskScheduler.schedule(RuntimeEnvironment.application, taskInfoBuilder.build()); + TaskInfo task = mFakeTaskScheduler.getTaskInfo(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID); + assertNotNull(task); + + TaskParameters params = TaskParameters.create(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID).build(); + mExploreSitesBackgroundTask.onStartTaskWithNative( + RuntimeEnvironment.application, params, (boolean needsReschedule) -> { + fail("Finished callback should not be run, the task should be cancelled."); + }); + + TaskInfo scheduledTask = + mFakeTaskScheduler.getTaskInfo(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID); + assertNull(scheduledTask); + } + + @Test + public void testDoesNotRemoveTaskIfFeatureIsEnabled() throws Exception { + TaskInfo.Builder taskInfoBuilder = + TaskInfo.createPeriodicTask(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID, + ExploreSitesBackgroundTask.class, TimeUnit.HOURS.toMillis(4), + TimeUnit.HOURS.toMillis(1)) + .setRequiredNetworkType(TaskInfo.NetworkType.ANY) + .setIsPersisted(true) + .setUpdateCurrent(false); + mFakeTaskScheduler.schedule(RuntimeEnvironment.application, taskInfoBuilder.build()); + TaskInfo task = mFakeTaskScheduler.getTaskInfo(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID); + assertNotNull(task); + + TaskParameters params = TaskParameters.create(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID).build(); + mExploreSitesBackgroundTask.onStartTaskWithNative(RuntimeEnvironment.application, params, + (boolean needsReschedule) -> { fail("Finished callback should not be run"); }); + + TaskInfo scheduledTask = + mFakeTaskScheduler.getTaskInfo(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID); + assertNotNull(scheduledTask); + } }
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/native_page/NativePageFactoryTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/native_page/NativePageFactoryTest.java index b0172be8..e6359ad 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/native_page/NativePageFactoryTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/native_page/NativePageFactoryTest.java
@@ -72,11 +72,6 @@ } @Override - public int getThemeColor() { - return 0; - } - - @Override public boolean needsToolbarShadow() { return true; }
diff --git a/chrome/android/webapk/shell_apk/BUILD.gn b/chrome/android/webapk/shell_apk/BUILD.gn index 893a605..d7ef39e 100644 --- a/chrome/android/webapk/shell_apk/BUILD.gn +++ b/chrome/android/webapk/shell_apk/BUILD.gn
@@ -181,22 +181,24 @@ grd_file = "//chrome/android/webapk/strings/android_webapk_strings.grd" outputs = [ + "values/android_webapk_strings.xml", "values-am/android_webapk_strings.xml", "values-ar/android_webapk_strings.xml", "values-bg/android_webapk_strings.xml", + "values-bn/android_webapk_strings.xml", "values-ca/android_webapk_strings.xml", "values-cs/android_webapk_strings.xml", "values-da/android_webapk_strings.xml", "values-de/android_webapk_strings.xml", "values-el/android_webapk_strings.xml", - "values/android_webapk_strings.xml", "values-en-rGB/android_webapk_strings.xml", "values-es/android_webapk_strings.xml", "values-es-rUS/android_webapk_strings.xml", + "values-et/android_webapk_strings.xml", "values-fa/android_webapk_strings.xml", "values-fi/android_webapk_strings.xml", - "values-tl/android_webapk_strings.xml", "values-fr/android_webapk_strings.xml", + "values-gu/android_webapk_strings.xml", "values-hi/android_webapk_strings.xml", "values-hr/android_webapk_strings.xml", "values-hu/android_webapk_strings.xml", @@ -204,11 +206,15 @@ "values-it/android_webapk_strings.xml", "values-iw/android_webapk_strings.xml", "values-ja/android_webapk_strings.xml", + "values-kn/android_webapk_strings.xml", "values-ko/android_webapk_strings.xml", "values-lt/android_webapk_strings.xml", "values-lv/android_webapk_strings.xml", - "values-nl/android_webapk_strings.xml", + "values-ml/android_webapk_strings.xml", + "values-mr/android_webapk_strings.xml", + "values-ms/android_webapk_strings.xml", "values-nb/android_webapk_strings.xml", + "values-nl/android_webapk_strings.xml", "values-pl/android_webapk_strings.xml", "values-pt-rBR/android_webapk_strings.xml", "values-pt-rPT/android_webapk_strings.xml", @@ -219,7 +225,10 @@ "values-sr/android_webapk_strings.xml", "values-sv/android_webapk_strings.xml", "values-sw/android_webapk_strings.xml", + "values-ta/android_webapk_strings.xml", + "values-te/android_webapk_strings.xml", "values-th/android_webapk_strings.xml", + "values-tl/android_webapk_strings.xml", "values-tr/android_webapk_strings.xml", "values-uk/android_webapk_strings.xml", "values-vi/android_webapk_strings.xml",
diff --git a/chrome/android/webapk/strings/android_webapk_strings.grd b/chrome/android/webapk/strings/android_webapk_strings.grd index d651ab8..ba03347 100644 --- a/chrome/android/webapk/strings/android_webapk_strings.grd +++ b/chrome/android/webapk/strings/android_webapk_strings.grd
@@ -4,6 +4,7 @@ <output filename="values-am/android_webapk_strings.xml" lang="am" type="android" /> <output filename="values-ar/android_webapk_strings.xml" lang="ar" type="android" /> <output filename="values-bg/android_webapk_strings.xml" lang="bg" type="android" /> + <output filename="values-bn/android_webapk_strings.xml" lang="bn" type="android" /> <output filename="values-ca/android_webapk_strings.xml" lang="ca" type="android" /> <output filename="values-cs/android_webapk_strings.xml" lang="cs" type="android" /> <output filename="values-da/android_webapk_strings.xml" lang="da" type="android" /> @@ -13,10 +14,12 @@ <output filename="values-en-rGB/android_webapk_strings.xml" lang="en-GB" type="android" /> <output filename="values-es/android_webapk_strings.xml" lang="es" type="android" /> <output filename="values-es-rUS/android_webapk_strings.xml" lang="es-419" type="android" /> + <output filename="values-et/android_webapk_strings.xml" lang="et" type="android" /> <output filename="values-fa/android_webapk_strings.xml" lang="fa" type="android" /> <output filename="values-fi/android_webapk_strings.xml" lang="fi" type="android" /> <output filename="values-tl/android_webapk_strings.xml" lang="fil" type="android" /> <output filename="values-fr/android_webapk_strings.xml" lang="fr" type="android" /> + <output filename="values-gu/android_webapk_strings.xml" lang="gu" type="android" /> <output filename="values-hi/android_webapk_strings.xml" lang="hi" type="android" /> <output filename="values-hr/android_webapk_strings.xml" lang="hr" type="android" /> <output filename="values-hu/android_webapk_strings.xml" lang="hu" type="android" /> @@ -24,9 +27,13 @@ <output filename="values-it/android_webapk_strings.xml" lang="it" type="android" /> <output filename="values-iw/android_webapk_strings.xml" lang="iw" type="android" /> <output filename="values-ja/android_webapk_strings.xml" lang="ja" type="android" /> + <output filename="values-kn/android_webapk_strings.xml" lang="kn" type="android" /> <output filename="values-ko/android_webapk_strings.xml" lang="ko" type="android" /> <output filename="values-lt/android_webapk_strings.xml" lang="lt" type="android" /> <output filename="values-lv/android_webapk_strings.xml" lang="lv" type="android" /> + <output filename="values-ml/android_webapk_strings.xml" lang="ml" type="android" /> + <output filename="values-mr/android_webapk_strings.xml" lang="mr" type="android" /> + <output filename="values-ms/android_webapk_strings.xml" lang="ms" type="android" /> <output filename="values-nl/android_webapk_strings.xml" lang="nl" type="android" /> <output filename="values-nb/android_webapk_strings.xml" lang="no" type="android" /> <output filename="values-pl/android_webapk_strings.xml" lang="pl" type="android" /> @@ -39,6 +46,8 @@ <output filename="values-sr/android_webapk_strings.xml" lang="sr" type="android" /> <output filename="values-sv/android_webapk_strings.xml" lang="sv" type="android" /> <output filename="values-sw/android_webapk_strings.xml" lang="sw" type="android" /> + <output filename="values-ta/android_webapk_strings.xml" lang="ta" type="android" /> + <output filename="values-te/android_webapk_strings.xml" lang="te" type="android" /> <output filename="values-th/android_webapk_strings.xml" lang="th" type="android" /> <output filename="values-tr/android_webapk_strings.xml" lang="tr" type="android" /> <output filename="values-uk/android_webapk_strings.xml" lang="uk" type="android" />
diff --git a/chrome/app/BUILD.gn b/chrome/app/BUILD.gn index 39cfe2b..219bfcf1 100644 --- a/chrome/app/BUILD.gn +++ b/chrome/app/BUILD.gn
@@ -5,6 +5,7 @@ import("//build/config/ui.gni") import("//chrome/common/features.gni") import("//chromeos/assistant/assistant.gni") +import("//components/gwp_asan/buildflags/buildflags.gni") import("//components/nacl/features.gni") import("//device/vr/buildflags/buildflags.gni") import("//ppapi/buildflags/buildflags.gni") @@ -64,17 +65,20 @@ "java/res/values-am/generated_resources.xml", "java/res/values-ar/generated_resources.xml", "java/res/values-bg/generated_resources.xml", + "java/res/values-bn/generated_resources.xml", "java/res/values-ca/generated_resources.xml", "java/res/values-cs/generated_resources.xml", "java/res/values-da/generated_resources.xml", "java/res/values-de/generated_resources.xml", "java/res/values-el/generated_resources.xml", "java/res/values-en-rGB/generated_resources.xml", - "java/res/values-es-rUS/generated_resources.xml", "java/res/values-es/generated_resources.xml", + "java/res/values-es-rUS/generated_resources.xml", + "java/res/values-et/generated_resources.xml", "java/res/values-fa/generated_resources.xml", "java/res/values-fi/generated_resources.xml", "java/res/values-fr/generated_resources.xml", + "java/res/values-gu/generated_resources.xml", "java/res/values-hi/generated_resources.xml", "java/res/values-hr/generated_resources.xml", "java/res/values-hu/generated_resources.xml", @@ -82,9 +86,13 @@ "java/res/values-it/generated_resources.xml", "java/res/values-iw/generated_resources.xml", "java/res/values-ja/generated_resources.xml", + "java/res/values-kn/generated_resources.xml", "java/res/values-ko/generated_resources.xml", "java/res/values-lt/generated_resources.xml", "java/res/values-lv/generated_resources.xml", + "java/res/values-ml/generated_resources.xml", + "java/res/values-mr/generated_resources.xml", + "java/res/values-ms/generated_resources.xml", "java/res/values-nb/generated_resources.xml", "java/res/values-nl/generated_resources.xml", "java/res/values-pl/generated_resources.xml", @@ -97,6 +105,8 @@ "java/res/values-sr/generated_resources.xml", "java/res/values-sv/generated_resources.xml", "java/res/values-sw/generated_resources.xml", + "java/res/values-ta/generated_resources.xml", + "java/res/values-te/generated_resources.xml", "java/res/values-th/generated_resources.xml", "java/res/values-tl/generated_resources.xml", "java/res/values-tr/generated_resources.xml", @@ -331,6 +341,7 @@ "//chrome/gpu", "//chrome/renderer", "//chrome/utility", + "//components/gwp_asan/buildflags", "//components/nacl/common:buildflags", "//components/startup_metric_utils/browser:lib", "//components/tracing", @@ -364,7 +375,6 @@ "//chrome:chrome_initial", "//chrome/install_static:install_static_util", "//chrome_elf:test_stubs", - "//components/gwp_asan/client", "//sandbox/win:sandbox", ] } @@ -386,6 +396,10 @@ "//services/ws/public/mojom:constants", ] } + + if (enable_gwp_asan) { + deps += [ "//components/gwp_asan/client" ] + } } source_set("chrome_content_browser_overlay_manifest") {
diff --git a/chrome/app/DEPS b/chrome/app/DEPS index a5833e3d..2e97375 100644 --- a/chrome/app/DEPS +++ b/chrome/app/DEPS
@@ -17,6 +17,7 @@ "+components/component_updater", "+components/content_settings/core/common/content_settings_pattern.h", "+components/crash", + "+components/gwp_asan/buildflags/buildflags.h", "+components/gwp_asan/client/gwp_asan.h", "+components/nacl/common", "+components/nacl/renderer/plugin/ppapi_entrypoints.h",
diff --git a/chrome/app/chrome_content_browser_overlay_manifest.cc b/chrome/app/chrome_content_browser_overlay_manifest.cc index 6e506e4..786da692 100644 --- a/chrome/app/chrome_content_browser_overlay_manifest.cc +++ b/chrome/app/chrome_content_browser_overlay_manifest.cc
@@ -172,7 +172,6 @@ .RequireCapability("proxy_resolver", "factory") .RequireCapability("removable_storage_writer", "removable_storage_writer") - .RequireCapability("resource_coordinator", "webui_graph_dump") .RequireCapability("secure_channel", "secure_channel") .RequireCapability("ui", "ime_registrar") .RequireCapability("ui", "input_device_controller")
diff --git a/chrome/app/chrome_main_delegate.cc b/chrome/app/chrome_main_delegate.cc index dd3df67d..8d13f4d7 100644 --- a/chrome/app/chrome_main_delegate.cc +++ b/chrome/app/chrome_main_delegate.cc
@@ -47,6 +47,7 @@ #include "components/crash/content/app/crash_reporter_client.h" #include "components/crash/core/common/crash_key.h" #include "components/crash/core/common/crash_keys.h" +#include "components/gwp_asan/buildflags/buildflags.h" #include "components/nacl/common/buildflags.h" #include "components/services/heap_profiling/public/cpp/sampling_profiler_wrapper.h" #include "components/services/heap_profiling/public/cpp/stream.h" @@ -78,7 +79,6 @@ #include "chrome/child/v8_crashpad_support_win.h" #include "chrome/common/child_process_logging.h" #include "chrome_elf/chrome_elf_main.h" -#include "components/gwp_asan/client/gwp_asan.h" // nogncheck #include "sandbox/win/src/sandbox.h" #include "ui/base/resource/resource_bundle_win.h" #endif @@ -164,6 +164,10 @@ #include "chrome/child/pdf_child_init.h" #endif +#if BUILDFLAG(ENABLE_GWP_ASAN) +#include "components/gwp_asan/client/gwp_asan.h" // nogncheck +#endif + #if !defined(CHROME_MULTIPLE_DLL_BROWSER) base::LazyInstance<ChromeContentGpuClient>::DestructorAtExit g_chrome_content_gpu_client = LAZY_INSTANCE_INITIALIZER; @@ -530,7 +534,7 @@ #endif void ChromeMainDelegate::PostFieldTrialInitialization() { -#if defined(OS_WIN) +#if BUILDFLAG(ENABLE_GWP_ASAN) version_info::Channel channel = chrome::GetChannel(); bool is_canary_dev = (channel == version_info::Channel::CANARY || channel == version_info::Channel::DEV);
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 6bf6329c..5ec7886 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -22,8 +22,8 @@ <output filename="generated_resources_da.pak" type="data_package" lang="da" /> <output filename="generated_resources_de.pak" type="data_package" lang="de" /> <output filename="generated_resources_el.pak" type="data_package" lang="el" /> - <output filename="generated_resources_en-GB.pak" type="data_package" lang="en-GB" /> <output filename="generated_resources_en-US.pak" type="data_package" lang="en" /> + <output filename="generated_resources_en-GB.pak" type="data_package" lang="en-GB" /> <output filename="generated_resources_es.pak" type="data_package" lang="es" /> <output filename="generated_resources_es-419.pak" type="data_package" lang="es-419" /> <output filename="generated_resources_et.pak" type="data_package" lang="et" /> @@ -76,6 +76,7 @@ <output filename="java/res/values-am/generated_resources.xml" lang="am" type="android" context="android_java" /> <output filename="java/res/values-ar/generated_resources.xml" lang="ar" type="android" context="android_java" /> <output filename="java/res/values-bg/generated_resources.xml" lang="bg" type="android" context="android_java" /> + <output filename="java/res/values-bn/generated_resources.xml" lang="bn" type="android" context="android_java" /> <output filename="java/res/values-ca/generated_resources.xml" lang="ca" type="android" context="android_java" /> <output filename="java/res/values-cs/generated_resources.xml" lang="cs" type="android" context="android_java" /> <output filename="java/res/values-da/generated_resources.xml" lang="da" type="android" context="android_java" /> @@ -85,20 +86,26 @@ <output filename="java/res/values-en-rGB/generated_resources.xml" lang="en-GB" type="android" context="android_java" /> <output filename="java/res/values-es/generated_resources.xml" lang="es" type="android" context="android_java" /> <output filename="java/res/values-es-rUS/generated_resources.xml" lang="es-419" type="android" context="android_java" /> + <output filename="java/res/values-et/generated_resources.xml" lang="et" type="android" context="android_java" /> <output filename="java/res/values-fa/generated_resources.xml" lang="fa" type="android" context="android_java" /> <output filename="java/res/values-fi/generated_resources.xml" lang="fi" type="android" context="android_java" /> <output filename="java/res/values-tl/generated_resources.xml" lang="fil" type="android" context="android_java" /> <output filename="java/res/values-fr/generated_resources.xml" lang="fr" type="android" context="android_java" /> + <output filename="java/res/values-gu/generated_resources.xml" lang="gu" type="android" context="android_java" /> + <output filename="java/res/values-iw/generated_resources.xml" lang="he" type="android" context="android_java" /> <output filename="java/res/values-hi/generated_resources.xml" lang="hi" type="android" context="android_java" /> <output filename="java/res/values-hr/generated_resources.xml" lang="hr" type="android" context="android_java" /> <output filename="java/res/values-hu/generated_resources.xml" lang="hu" type="android" context="android_java" /> <output filename="java/res/values-in/generated_resources.xml" lang="id" type="android" context="android_java" /> <output filename="java/res/values-it/generated_resources.xml" lang="it" type="android" context="android_java" /> - <output filename="java/res/values-iw/generated_resources.xml" lang="he" type="android" context="android_java" /> <output filename="java/res/values-ja/generated_resources.xml" lang="ja" type="android" context="android_java" /> + <output filename="java/res/values-kn/generated_resources.xml" lang="kn" type="android" context="android_java" /> <output filename="java/res/values-ko/generated_resources.xml" lang="ko" type="android" context="android_java" /> <output filename="java/res/values-lt/generated_resources.xml" lang="lt" type="android" context="android_java" /> <output filename="java/res/values-lv/generated_resources.xml" lang="lv" type="android" context="android_java" /> + <output filename="java/res/values-ml/generated_resources.xml" lang="ml" type="android" context="android_java" /> + <output filename="java/res/values-mr/generated_resources.xml" lang="mr" type="android" context="android_java" /> + <output filename="java/res/values-ms/generated_resources.xml" lang="ms" type="android" context="android_java" /> <output filename="java/res/values-nl/generated_resources.xml" lang="nl" type="android" context="android_java" /> <output filename="java/res/values-nb/generated_resources.xml" lang="no" type="android" context="android_java" /> <output filename="java/res/values-pl/generated_resources.xml" lang="pl" type="android" context="android_java" /> @@ -111,6 +118,8 @@ <output filename="java/res/values-sr/generated_resources.xml" lang="sr" type="android" context="android_java" /> <output filename="java/res/values-sv/generated_resources.xml" lang="sv" type="android" context="android_java" /> <output filename="java/res/values-sw/generated_resources.xml" lang="sw" type="android" context="android_java" /> + <output filename="java/res/values-ta/generated_resources.xml" lang="ta" type="android" context="android_java" /> + <output filename="java/res/values-te/generated_resources.xml" lang="te" type="android" context="android_java" /> <output filename="java/res/values-th/generated_resources.xml" lang="th" type="android" context="android_java" /> <output filename="java/res/values-tr/generated_resources.xml" lang="tr" type="android" context="android_java" /> <output filename="java/res/values-uk/generated_resources.xml" lang="uk" type="android" context="android_java" /> @@ -6683,27 +6692,12 @@ <message name="IDS_SYNC_CONFIRMATION_DICE_TITLE" desc="Title of the sync confirmation dialog in the tab modal signin flow when Dice is enabled"> Turn on sync? </message> - <message name="IDS_SYNC_CONFIRMATION_UNITY_TITLE" desc="Title of the sync confirmation dialog in the tab modal signin flow when Unity is enabled"> - Get Google smarts in Chrome - </message> <message name="IDS_SYNC_CONFIRMATION_UNITY_SYNC_INFO_TITLE" desc="Title in the information about sync on the sync confirmation dialog when Unity is enabled"> Sync your bookmarks, passwords, history, and more on all your devices </message> <message name="IDS_SYNC_CONFIRMATION_UNITY_SYNC_INFO_DESC" desc="Description in the information about sync on the sync confirmation dialog when Unity is enabled"> Google may use your history to personalize Search, ads, and other Google services </message> - <message name="IDS_SYNC_CONFIRMATION_UNITY_SPELLCHECK_INFO_TITLE" desc="Title in the information about spellcheck on the sync confirmation dialog when Unity is enabled"> - Fix spelling errors with enhanced spell check - </message> - <message name="IDS_SYNC_CONFIRMATION_UNITY_SPELLCHECK_INFO_DESC" desc="Description in the information about spellcheck on the sync confirmation dialog when Unity is enabled"> - The text you type in text fields will be sent to Google - </message> - <message name="IDS_SYNC_CONFIRMATION_UNITY_IMPROVE_CHROME_INFO_TITLE" desc="Title in the information about improving Chrome on the sync confirmation dialog when Unity is enabled"> - Help improve Chrome and its security - </message> - <message name="IDS_SYNC_CONFIRMATION_UNITY_IMPROVE_CHROME_INFO_DESC" desc="Description in the information about improving Chrome on the sync confirmation dialog when Unity is enabled"> - Sends some system information and page content to Google anonymously - </message> <message name="IDS_SYNC_CONFIRMATION_UNITY_SETTINGS_INFO" desc="Information about customizing Sync settings in the sync confirmation dialog when Unity is enabled"> You can customize these settings anytime </message>
diff --git a/chrome/app/settings_chromium_strings.grdp b/chrome/app/settings_chromium_strings.grdp index 8811407e..3a5787b 100644 --- a/chrome/app/settings_chromium_strings.grdp +++ b/chrome/app/settings_chromium_strings.grdp
@@ -113,7 +113,7 @@ <!-- Languages Page --> <if expr="chromeos"> <message name="IDS_SETTINGS_LANGUAGES_IS_DISPLAYED_IN_THIS_LANGUAGE" desc="The label for a language that is currently used as the UI display language."> - Chromium OS is displayed in this language + This language is used to display the Chromium OS UI </message> <message name="IDS_SETTINGS_LANGUAGES_DISPLAY_IN_THIS_LANGUAGE" desc="The label used for a button that changes the UI language."> Display Chromium OS in this language @@ -121,7 +121,7 @@ </if> <if expr="not chromeos"> <message name="IDS_SETTINGS_LANGUAGES_IS_DISPLAYED_IN_THIS_LANGUAGE" desc="The label for a language that is currently used as the UI display language."> - Chromium is displayed in this language + This language is used to display the Chromium UI </message> <message name="IDS_SETTINGS_LANGUAGES_DISPLAY_IN_THIS_LANGUAGE" desc="The label used for a button that changes the UI language."> Display Chromium in this language
diff --git a/chrome/app/settings_chromium_strings_grdp/IDS_SETTINGS_LANGUAGES_IS_DISPLAYED_IN_THIS_LANGUAGE.png.sha1 b/chrome/app/settings_chromium_strings_grdp/IDS_SETTINGS_LANGUAGES_IS_DISPLAYED_IN_THIS_LANGUAGE.png.sha1 new file mode 100644 index 0000000..f4697a660 --- /dev/null +++ b/chrome/app/settings_chromium_strings_grdp/IDS_SETTINGS_LANGUAGES_IS_DISPLAYED_IN_THIS_LANGUAGE.png.sha1
@@ -0,0 +1 @@ +f05276f2ceb2f6dab464dcc7b4a5e14a49ffb25f \ No newline at end of file
diff --git a/chrome/app/settings_google_chrome_strings.grdp b/chrome/app/settings_google_chrome_strings.grdp index 8dca4b1..f88cc98 100644 --- a/chrome/app/settings_google_chrome_strings.grdp +++ b/chrome/app/settings_google_chrome_strings.grdp
@@ -113,7 +113,7 @@ <!-- Languages Page --> <if expr="chromeos"> <message name="IDS_SETTINGS_LANGUAGES_IS_DISPLAYED_IN_THIS_LANGUAGE" desc="The label for a language that is currently used as the UI display language."> - Chrome OS is displayed in this language + This language is used to display the Chrome OS UI </message> <message name="IDS_SETTINGS_LANGUAGES_DISPLAY_IN_THIS_LANGUAGE" desc="The label used for a button that changes the UI language."> Display Chrome OS in this language @@ -121,7 +121,7 @@ </if> <if expr="not chromeos"> <message name="IDS_SETTINGS_LANGUAGES_IS_DISPLAYED_IN_THIS_LANGUAGE" desc="The label for a language that is currently used as the UI display language."> - Google Chrome is displayed in this language + This language is used to display the Google Chrome UI </message> <message name="IDS_SETTINGS_LANGUAGES_DISPLAY_IN_THIS_LANGUAGE" desc="The label used for a button that changes the UI language."> Display Google Chrome in this language
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index 426f7836..f24abdd 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -2381,6 +2381,9 @@ <message name="IDS_SETTINGS_LANGUAGES_OFFER_TO_ENABLE_TRANSLATE" desc="The label of the check-box that enables the prompt to translate a page."> Offer to translate pages that aren't in a language you read </message> + <message name="IDS_SETTINGS_LANGUAGES_TRANSLATE_TARGET" desc="The label under a language's name in a list of enabled languages indicating that pages will be translated to this language."> + This language is used when translating pages + </message> <if expr="chromeos"> <message name="IDS_SETTINGS_LANGUAGES_INPUT_METHODS_LIST_TITLE" desc="Title for the current input method in the header for the collapsible list of enabled input methods (keyboard layouts and input method editors)."> Input method
diff --git a/chrome/app/settings_strings_grdp/IDS_SETTINGS_LANGUAGES_TRANSLATE_TARGET.png.sha1 b/chrome/app/settings_strings_grdp/IDS_SETTINGS_LANGUAGES_TRANSLATE_TARGET.png.sha1 new file mode 100644 index 0000000..3b8a127 --- /dev/null +++ b/chrome/app/settings_strings_grdp/IDS_SETTINGS_LANGUAGES_TRANSLATE_TARGET.png.sha1
@@ -0,0 +1 @@ +2953448037f432e9c08cc90bcc07dbe1792d8722 \ No newline at end of file
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index d2d704c2..113d3835 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -1052,6 +1052,46 @@ "payments/payment_handler_permission_context.cc", "payments/payment_handler_permission_context.h", "payments/ssl_validity_checker.cc", + "performance_manager/coordination_unit/coordination_unit_base.cc", + "performance_manager/coordination_unit/coordination_unit_base.h", + "performance_manager/coordination_unit/coordination_unit_graph.cc", + "performance_manager/coordination_unit/coordination_unit_graph.h", + "performance_manager/coordination_unit/coordination_unit_introspector_impl.cc", + "performance_manager/coordination_unit/coordination_unit_introspector_impl.h", + "performance_manager/coordination_unit/coordination_unit_provider_impl.cc", + "performance_manager/coordination_unit/coordination_unit_provider_impl.h", + "performance_manager/coordination_unit/frame_coordination_unit_impl.cc", + "performance_manager/coordination_unit/frame_coordination_unit_impl.h", + "performance_manager/coordination_unit/page_coordination_unit_impl.cc", + "performance_manager/coordination_unit/page_coordination_unit_impl.h", + "performance_manager/coordination_unit/process_coordination_unit_impl.cc", + "performance_manager/coordination_unit/process_coordination_unit_impl.h", + "performance_manager/coordination_unit/system_coordination_unit_impl.cc", + "performance_manager/coordination_unit/system_coordination_unit_impl.h", + "performance_manager/frame_resource_coordinator.cc", + "performance_manager/frame_resource_coordinator.h", + "performance_manager/observers/background_metrics_reporter.h", + "performance_manager/observers/coordination_unit_graph_observer.cc", + "performance_manager/observers/coordination_unit_graph_observer.h", + "performance_manager/observers/metrics_collector.cc", + "performance_manager/observers/metrics_collector.h", + "performance_manager/observers/page_signal_generator_impl.cc", + "performance_manager/observers/page_signal_generator_impl.h", + "performance_manager/observers/working_set_trimmer_win.cc", + "performance_manager/observers/working_set_trimmer_win.h", + "performance_manager/page_resource_coordinator.cc", + "performance_manager/page_resource_coordinator.h", + "performance_manager/performance_manager.cc", + "performance_manager/performance_manager.h", + "performance_manager/process_resource_coordinator.cc", + "performance_manager/process_resource_coordinator.h", + "performance_manager/resource_coordinator_clock.cc", + "performance_manager/resource_coordinator_clock.h", + "performance_manager/resource_coordinator_interface.h", + "performance_manager/system_resource_coordinator.cc", + "performance_manager/system_resource_coordinator.h", + "performance_manager/webui_graph_dump_impl.cc", + "performance_manager/webui_graph_dump_impl.h", "performance_monitor/process_metrics_history.cc", "performance_monitor/process_metrics_history.h", "performance_monitor/process_monitor.cc", @@ -1633,6 +1673,8 @@ "tracing/crash_service_uploader.h", "tracing/navigation_tracing.cc", "tracing/navigation_tracing.h", + "tracing/trace_event_system_stats_monitor.cc", + "tracing/trace_event_system_stats_monitor.h", "translate/android/translate_utils.cc", "translate/android/translate_utils.h", "translate/chrome_translate_client.cc", @@ -2567,6 +2609,9 @@ "password_manager/password_accessory_controller_impl.cc", "password_manager/password_accessory_controller_impl.h", "password_manager/password_accessory_metrics_util.h", + "password_manager/password_generation_controller.h", + "password_manager/password_generation_controller_impl.cc", + "password_manager/password_generation_controller_impl.h", "password_manager/password_generation_dialog_view_interface.h", "password_manager/password_manager_infobar_delegate_android.cc", "password_manager/password_manager_infobar_delegate_android.h", @@ -5292,6 +5337,8 @@ visibility = [ "//chrome/test:test_support" ] sources = [ + "autofill/mock_manual_filling_controller.cc", + "autofill/mock_manual_filling_controller.h", "browsing_data/mock_browsing_data_appcache_helper.cc", "browsing_data/mock_browsing_data_appcache_helper.h", "browsing_data/mock_browsing_data_cache_storage_helper.cc",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index c1e6961..bf2938bab 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -2026,6 +2026,10 @@ flag_descriptions::kEnableLitePageServerPreviewsDescription, kOsAndroid, FEATURE_VALUE_TYPE(previews::features::kLitePageServerPreviews)}, #endif // OS_ANDROID + {"enable-lite-mode-rebrand", + flag_descriptions::kEnableDataSaverLiteModeRebrandName, + flag_descriptions::kEnableDataSaverLiteModeRebrandDescription, kOsAll, + FEATURE_VALUE_TYPE(previews::features::kDataSaverLiteModeRebranding)}, {"enable-client-lo-fi", flag_descriptions::kEnableClientLoFiName, flag_descriptions::kEnableClientLoFiDescription, kOsAll, FEATURE_VALUE_TYPE(previews::features::kClientLoFi)}, @@ -3848,9 +3852,6 @@ FEATURE_VALUE_TYPE(features::kCSSFragmentIdentifiers)}, #if !defined(OS_ANDROID) - {"infinite-session-restore", flag_descriptions::kInfiniteSessionRestoreName, - flag_descriptions::kInfiniteSessionRestoreDescription, kOsDesktop, - FEATURE_VALUE_TYPE(features::kInfiniteSessionRestore)}, {"page-almost-idle", flag_descriptions::kPageAlmostIdleName, flag_descriptions::kPageAlmostIdleDescription, kOsDesktop, FEATURE_VALUE_TYPE(features::kPageAlmostIdle)}, @@ -4293,6 +4294,12 @@ autofill_assistant::features::kAutofillAssistantChromeEntry)}, #endif // defined(OS_ANDROID) + {"enable-sync-uss-passwords", + flag_descriptions::kEnableSyncUSSPasswordsName, + flag_descriptions::kEnableSyncUSSPasswordsDescription, + kOsMac | kOsWin | kOsCrOS | kOsAndroid, + FEATURE_VALUE_TYPE(switches::kSyncUSSPasswords)}, + // NOTE: Adding a new flag requires adding a corresponding entry to enum // "LoginCustomFlags" in tools/metrics/histograms/enums.xml. See "Flag // Histograms" in tools/metrics/histograms/README.md (run the
diff --git a/chrome/browser/android/cached_image_fetcher/cached_image_fetcher_bridge.cc b/chrome/browser/android/cached_image_fetcher/cached_image_fetcher_bridge.cc index 88f79b9..bf1524c 100644 --- a/chrome/browser/android/cached_image_fetcher/cached_image_fetcher_bridge.cc +++ b/chrome/browser/android/cached_image_fetcher/cached_image_fetcher_bridge.cc
@@ -17,8 +17,8 @@ #include "chrome/browser/profiles/profile_android.h" #include "components/image_fetcher/core/cache/cached_image_fetcher_metrics_reporter.h" #include "components/image_fetcher/core/cache/image_cache.h" -#include "components/image_fetcher/core/cached_image_fetcher.h" #include "components/image_fetcher/core/cached_image_fetcher_service.h" +#include "components/image_fetcher/core/image_fetcher.h" #include "jni/CachedImageFetcherBridge_jni.h" #include "ui/gfx/android/java_bitmap.h" #include "ui/gfx/image/image.h" @@ -36,6 +36,7 @@ const base::FilePath::CharType kPathPostfix[] = FILE_PATH_LITERAL("image_data_storage"); +// TODO(wylieb): Allow java clients to map to a traffic_annotation here. constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation = net::DefineNetworkTrafficAnnotation("cached_image_fetcher", R"( semantics { @@ -70,14 +71,14 @@ CachedImageFetcherService* cif_service = CachedImageFetcherServiceFactory::GetForBrowserContext(profile); CachedImageFetcherBridge* native_cif_bridge = new CachedImageFetcherBridge( - cif_service->CreateCachedImageFetcher(), file_path); + cif_service->GetCachedImageFetcher(), file_path); return reinterpret_cast<intptr_t>(native_cif_bridge); } CachedImageFetcherBridge::CachedImageFetcherBridge( - std::unique_ptr<CachedImageFetcher> cached_image_fetcher, + ImageFetcher* cached_image_fetcher, base::FilePath base_file_path) - : cached_image_fetcher_(std::move(cached_image_fetcher)), + : cached_image_fetcher_(cached_image_fetcher), base_file_path_(base_file_path), weak_ptr_factory_(this) {} @@ -106,15 +107,17 @@ const JavaRef<jobject>& j_callback) { ScopedJavaGlobalRef<jobject> callback(j_callback); std::string url = base::android::ConvertJavaStringToUTF8(j_url); - cached_image_fetcher_->SetDesiredImageFrameSize( - gfx::Size(width_px, height_px)); + + ImageFetcherParams params(kTrafficAnnotation); + params.set_frame_size(gfx::Size(width_px, height_px)); + // TODO(wylieb): We checked disk in Java, so provide a way to tell // CachedImageFetcher to skip checking disk in native. cached_image_fetcher_->FetchImage( - url, GURL(url), + GURL(url), base::BindOnce(&CachedImageFetcherBridge::OnImageFetched, weak_ptr_factory_.GetWeakPtr(), callback), - kTrafficAnnotation); + std::move(params)); } void CachedImageFetcherBridge::ReportEvent( @@ -136,7 +139,6 @@ void CachedImageFetcherBridge::OnImageFetched( base::android::ScopedJavaGlobalRef<jobject> callback, - const std::string& id, const gfx::Image& image, const RequestMetadata& request_metadata) { ScopedJavaLocalRef<jobject> j_bitmap;
diff --git a/chrome/browser/android/cached_image_fetcher/cached_image_fetcher_bridge.h b/chrome/browser/android/cached_image_fetcher/cached_image_fetcher_bridge.h index e999569..8869732 100644 --- a/chrome/browser/android/cached_image_fetcher/cached_image_fetcher_bridge.h +++ b/chrome/browser/android/cached_image_fetcher/cached_image_fetcher_bridge.h
@@ -16,15 +16,13 @@ namespace image_fetcher { -class CachedImageFetcher; +class ImageFetcher; -// Native counterpart of CachedImageFetcherBridge.java. Owns an instance of -// CachedImageFetcher. +// Native counterpart of CachedImageFetcherBridge.java. class CachedImageFetcherBridge { public: - explicit CachedImageFetcherBridge( - std::unique_ptr<CachedImageFetcher> cached_image_fetcher, - base::FilePath base_file_path); + CachedImageFetcherBridge(ImageFetcher* cached_image_fetcher, + base::FilePath base_file_path); ~CachedImageFetcherBridge(); void Destroy(JNIEnv* j_env, const base::android::JavaRef<jobject>& j_this); @@ -51,11 +49,11 @@ private: void OnImageFetched(base::android::ScopedJavaGlobalRef<jobject> callback, - const std::string& id, const gfx::Image& image, const RequestMetadata& request_metadata); - std::unique_ptr<CachedImageFetcher> cached_image_fetcher_; + // Owned by CachedImageFetcherService. + ImageFetcher* cached_image_fetcher_; base::FilePath base_file_path_; base::WeakPtrFactory<CachedImageFetcherBridge> weak_ptr_factory_;
diff --git a/chrome/browser/android/explore_sites/explore_sites_bridge_experimental.cc b/chrome/browser/android/explore_sites/explore_sites_bridge_experimental.cc index 8606351d..9adb58b 100644 --- a/chrome/browser/android/explore_sites/explore_sites_bridge_experimental.cc +++ b/chrome/browser/android/explore_sites/explore_sites_bridge_experimental.cc
@@ -77,7 +77,6 @@ void OnGetIconDone(std::unique_ptr<image_fetcher::ImageFetcher> image_fetcher, const ScopedJavaGlobalRef<jobject>& j_callback_obj, - const std::string& id, const gfx::Image& image, const image_fetcher::RequestMetadata& metadata) { ScopedJavaLocalRef<jobject> j_bitmap; @@ -132,7 +131,7 @@ // of the callback. image_fetcher::ImageFetcher* image_fetcher_ptr = image_fetcher.get(); image_fetcher_ptr->FetchImage( - icon_url.spec(), icon_url, + icon_url, base::BindOnce(&OnGetIconDone, std::move(image_fetcher), ScopedJavaGlobalRef<jobject>(j_callback_obj)), kTrafficAnnotation);
diff --git a/chrome/browser/android/password_manager/password_generation_dialog_view_android.cc b/chrome/browser/android/password_manager/password_generation_dialog_view_android.cc index d3ac99b..c83d2e66 100644 --- a/chrome/browser/android/password_manager/password_generation_dialog_view_android.cc +++ b/chrome/browser/android/password_manager/password_generation_dialog_view_android.cc
@@ -7,7 +7,7 @@ #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/strings/string16.h" -#include "chrome/browser/password_manager/password_accessory_controller.h" +#include "chrome/browser/password_manager/password_generation_controller_impl.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/strings/grit/components_strings.h" @@ -16,9 +16,9 @@ #include "ui/base/l10n/l10n_util.h" PasswordGenerationDialogViewAndroid::PasswordGenerationDialogViewAndroid( - PasswordAccessoryController* controller) + PasswordGenerationController* controller) : controller_(controller) { - ui::WindowAndroid* window_android = controller_->native_window(); + ui::WindowAndroid* window_android = controller_->top_level_native_window(); DCHECK(window_android); java_object_.Reset(Java_PasswordGenerationDialogBridge_create( @@ -60,6 +60,6 @@ // static std::unique_ptr<PasswordGenerationDialogViewInterface> PasswordGenerationDialogViewInterface::Create( - PasswordAccessoryController* controller) { + PasswordGenerationController* controller) { return std::make_unique<PasswordGenerationDialogViewAndroid>(controller); }
diff --git a/chrome/browser/android/password_manager/password_generation_dialog_view_android.h b/chrome/browser/android/password_manager/password_generation_dialog_view_android.h index a7bdffb..905854c 100644 --- a/chrome/browser/android/password_manager/password_generation_dialog_view_android.h +++ b/chrome/browser/android/password_manager/password_generation_dialog_view_android.h
@@ -11,18 +11,17 @@ #include "base/strings/string16.h" #include "chrome/browser/password_manager/password_generation_dialog_view_interface.h" -class PasswordAccessoryController; +class PasswordGenerationController; // Modal dialog displaying a generated password with options to accept or // reject it. Communicates events to its Java counterpart and passes responses -// back to the |PasswordAccessoryController|. -// TODO(crbug.com/835234): Add a specialized dialog controller. +// back to the |PasswordGenerationController|. class PasswordGenerationDialogViewAndroid : public PasswordGenerationDialogViewInterface { public: // Builds the UI for the |controller| explicit PasswordGenerationDialogViewAndroid( - PasswordAccessoryController* controller); + PasswordGenerationController* controller); ~PasswordGenerationDialogViewAndroid() override; @@ -40,7 +39,7 @@ private: // The controller provides data for this view and owns it. - PasswordAccessoryController* controller_; + PasswordGenerationController* controller_; // The corresponding java object. base::android::ScopedJavaGlobalRef<jobject> java_object_;
diff --git a/chrome/browser/autofill/manual_filling_controller_impl.cc b/chrome/browser/autofill/manual_filling_controller_impl.cc index f2ba92b..c5575bd 100644 --- a/chrome/browser/autofill/manual_filling_controller_impl.cc +++ b/chrome/browser/autofill/manual_filling_controller_impl.cc
@@ -11,6 +11,7 @@ #include "base/strings/utf_string_conversions.h" #include "chrome/browser/password_manager/password_accessory_controller.h" #include "chrome/browser/password_manager/password_accessory_metrics_util.h" +#include "chrome/browser/password_manager/password_generation_controller.h" #include "chrome/browser/profiles/profile.h" #include "components/autofill/core/common/autofill_features.h" #include "content/public/browser/web_contents.h" @@ -30,16 +31,19 @@ void ManualFillingControllerImpl::CreateForWebContentsForTesting( content::WebContents* web_contents, base::WeakPtr<PasswordAccessoryController> pwd_controller, + PasswordGenerationController* pwd_generation_controller_for_testing, std::unique_ptr<ManualFillingViewInterface> view) { DCHECK(web_contents) << "Need valid WebContents to attach controller to!"; DCHECK(!FromWebContents(web_contents)) << "Controller already attached!"; DCHECK(pwd_controller); + DCHECK(pwd_generation_controller_for_testing); DCHECK(view); web_contents->SetUserData( UserDataKey(), - std::make_unique<ManualFillingControllerImpl>( - web_contents, std::move(pwd_controller), std::move(view))); + base::WrapUnique(new ManualFillingControllerImpl( + web_contents, std::move(pwd_controller), + pwd_generation_controller_for_testing, std::move(view)))); } void ManualFillingControllerImpl::OnAutomaticGenerationStatusChanged( @@ -107,8 +111,13 @@ } void ManualFillingControllerImpl::OnGenerationRequested() { - DCHECK(pwd_controller_); - pwd_controller_->OnGenerationRequested(); + PasswordGenerationController* pwd_generation_controller = + pwd_generation_controller_for_testing_ + ? pwd_generation_controller_for_testing_ + : PasswordGenerationController::GetIfExisting(web_contents_); + + DCHECK(pwd_generation_controller); + pwd_generation_controller->OnGenerationRequested(); } void ManualFillingControllerImpl::GetFavicon( @@ -143,9 +152,12 @@ ManualFillingControllerImpl::ManualFillingControllerImpl( content::WebContents* web_contents, base::WeakPtr<PasswordAccessoryController> pwd_controller, + PasswordGenerationController* pwd_generation_controller_for_testing, std::unique_ptr<ManualFillingViewInterface> view) : web_contents_(web_contents), pwd_controller_(std::move(pwd_controller)), + pwd_generation_controller_for_testing_( + pwd_generation_controller_for_testing), view_(std::move(view)), weak_factory_(this) {}
diff --git a/chrome/browser/autofill/manual_filling_controller_impl.h b/chrome/browser/autofill/manual_filling_controller_impl.h index 4795c3b..f0f1b36 100644 --- a/chrome/browser/autofill/manual_filling_controller_impl.h +++ b/chrome/browser/autofill/manual_filling_controller_impl.h
@@ -15,17 +15,13 @@ #include "content/public/browser/web_contents_user_data.h" class PasswordAccessoryController; +class PasswordGenerationController; // Use ManualFillingController::GetOrCreate to obtain instances of this class. class ManualFillingControllerImpl : public ManualFillingController, public content::WebContentsUserData<ManualFillingControllerImpl> { public: - // Constructor that allows to inject a mock or fake view. - ManualFillingControllerImpl( - content::WebContents* web_contents, - base::WeakPtr<PasswordAccessoryController> pwd_controller, - std::unique_ptr<ManualFillingViewInterface> view); ~ManualFillingControllerImpl() override; // ManualFillingController: @@ -54,6 +50,7 @@ static void CreateForWebContentsForTesting( content::WebContents* web_contents, base::WeakPtr<PasswordAccessoryController> pwd_controller, + PasswordGenerationController* pwd_generation_controller_for_testing, std::unique_ptr<ManualFillingViewInterface> test_view); #if defined(UNIT_TEST) @@ -67,6 +64,13 @@ // Required for construction via |CreateForWebContents|: explicit ManualFillingControllerImpl(content::WebContents* contents); + // Constructor that allows to inject a mock or fake view. + ManualFillingControllerImpl( + content::WebContents* web_contents, + base::WeakPtr<PasswordAccessoryController> pwd_controller, + PasswordGenerationController* pwd_generation_controller_for_testing, + std::unique_ptr<ManualFillingViewInterface> view); + // The tab for which this class is scoped. content::WebContents* web_contents_; @@ -76,6 +80,11 @@ // The password accessory controller object to forward view requests to. base::WeakPtr<PasswordAccessoryController> pwd_controller_; + // A password generation controller used in tests which receives requests + // from the view. + PasswordGenerationController* pwd_generation_controller_for_testing_ = + nullptr; + // Hold the native instance of the view. Must be last declared and initialized // member so the view can be created in the constructor with a fully set up // controller instance.
diff --git a/chrome/browser/autofill/manual_filling_controller_impl_unittest.cc b/chrome/browser/autofill/manual_filling_controller_impl_unittest.cc index 06c671e..b6a75f6 100644 --- a/chrome/browser/autofill/manual_filling_controller_impl_unittest.cc +++ b/chrome/browser/autofill/manual_filling_controller_impl_unittest.cc
@@ -14,6 +14,7 @@ #include "base/test/scoped_feature_list.h" #include "chrome/browser/autofill/manual_filling_view_interface.h" #include "chrome/browser/password_manager/password_accessory_controller.h" +#include "chrome/browser/password_manager/password_generation_controller.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "components/autofill/core/common/autofill_features.h" #include "testing/gmock/include/gmock/gmock.h" @@ -34,12 +35,6 @@ SavePasswordsForOrigin, void(const std::map<base::string16, const autofill::PasswordForm*>&, const url::Origin&)); - MOCK_METHOD3( - OnAutomaticGenerationStatusChanged, - void(bool, - const base::Optional< - autofill::password_generation::PasswordGenerationUIData>&, - const base::WeakPtr<password_manager::PasswordManagerDriver>&)); MOCK_METHOD1(OnFilledIntoFocusedField, void(autofill::FillingStatus)); MOCK_METHOD3(RefreshSuggestionsForField, void(const url::Origin&, bool, bool)); @@ -48,10 +43,20 @@ void(int, base::OnceCallback<void(const gfx::Image&)>)); MOCK_METHOD2(OnFillingTriggered, void(bool, const base::string16&)); MOCK_CONST_METHOD1(OnOptionSelected, void(const base::string16&)); +}; + +class MockPasswordGenerationController : public PasswordGenerationController { + public: + MOCK_METHOD3( + OnAutomaticGenerationStatusChanged, + void(bool, + const base::Optional< + autofill::password_generation::PasswordGenerationUIData>&, + const base::WeakPtr<password_manager::PasswordManagerDriver>&)); MOCK_METHOD0(OnGenerationRequested, void()); MOCK_METHOD1(GeneratedPasswordAccepted, void(const base::string16&)); MOCK_METHOD0(GeneratedPasswordRejected, void()); - MOCK_CONST_METHOD0(native_window, gfx::NativeWindow()); + MOCK_CONST_METHOD0(top_level_native_window, gfx::NativeWindow()); }; // The mock view mocks the platform-specific implementation. That also means @@ -91,6 +96,7 @@ NavigateAndCommit(GURL(kExampleSite)); ManualFillingControllerImpl::CreateForWebContentsForTesting( web_contents(), mock_pwd_controller_.AsWeakPtr(), + &mock_pwd_generation_controller_, std::make_unique<StrictMock<MockPasswordAccessoryView>>()); NavigateAndCommit(GURL(kExampleSite)); } @@ -105,6 +111,7 @@ protected: NiceMock<MockPasswordAccessoryController> mock_pwd_controller_; + NiceMock<MockPasswordGenerationController> mock_pwd_generation_controller_; }; TEST_F(ManualFillingControllerTest, IsNotRecreatedForSameWebContents) { @@ -202,7 +209,7 @@ } TEST_F(ManualFillingControllerTest, OnGenerationRequested) { - EXPECT_CALL(mock_pwd_controller_, OnGenerationRequested()); + EXPECT_CALL(mock_pwd_generation_controller_, OnGenerationRequested()); controller()->OnGenerationRequested(); }
diff --git a/chrome/browser/autofill/mock_manual_filling_controller.cc b/chrome/browser/autofill/mock_manual_filling_controller.cc new file mode 100644 index 0000000..3bc4130a --- /dev/null +++ b/chrome/browser/autofill/mock_manual_filling_controller.cc
@@ -0,0 +1,8 @@ +// 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. + +#include "chrome/browser/autofill/mock_manual_filling_controller.h" + +MockManualFillingController::MockManualFillingController() = default; +MockManualFillingController::~MockManualFillingController() = default;
diff --git a/chrome/browser/autofill/mock_manual_filling_controller.h b/chrome/browser/autofill/mock_manual_filling_controller.h new file mode 100644 index 0000000..98d84da --- /dev/null +++ b/chrome/browser/autofill/mock_manual_filling_controller.h
@@ -0,0 +1,34 @@ +// 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. + +#ifndef CHROME_BROWSER_AUTOFILL_MOCK_MANUAL_FILLING_CONTROLLER_H_ +#define CHROME_BROWSER_AUTOFILL_MOCK_MANUAL_FILLING_CONTROLLER_H_ + +#include "chrome/browser/autofill/manual_filling_controller.h" +#include "testing/gmock/include/gmock/gmock.h" + +class MockManualFillingController + : public ManualFillingController, + public base::SupportsWeakPtr<MockManualFillingController> { + public: + MockManualFillingController(); + ~MockManualFillingController() override; + + MOCK_METHOD1(OnAutomaticGenerationStatusChanged, void(bool)); + MOCK_METHOD1(OnFilledIntoFocusedField, void(autofill::FillingStatus)); + MOCK_METHOD2(RefreshSuggestionsForField, + void(bool, const autofill::AccessorySheetData&)); + MOCK_METHOD1(ShowWhenKeyboardIsVisible, + void(ManualFillingController::FillingSource)); + MOCK_METHOD1(Hide, void(ManualFillingController::FillingSource)); + MOCK_METHOD2(GetFavicon, + void(int, base::OnceCallback<void(const gfx::Image&)>)); + MOCK_METHOD2(OnFillingTriggered, + void(bool is_password, const base::string16&)); + MOCK_CONST_METHOD1(OnOptionSelected, void(const base::string16&)); + MOCK_METHOD0(OnGenerationRequested, void()); + MOCK_CONST_METHOD0(container_view, gfx::NativeView()); +}; + +#endif // CHROME_BROWSER_AUTOFILL_MOCK_MANUAL_FILLING_CONTROLLER_H_
diff --git a/chrome/browser/browser_process_platform_part_chromeos.cc b/chrome/browser/browser_process_platform_part_chromeos.cc index 359eb81..b3c5504f 100644 --- a/chrome/browser/browser_process_platform_part_chromeos.cc +++ b/chrome/browser/browser_process_platform_part_chromeos.cc
@@ -43,7 +43,6 @@ #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "services/service_manager/public/cpp/service.h" -#include "services/service_manager/runner/common/client_util.h" #include "services/ws/public/cpp/input_devices/input_device_controller.h" #include "services/ws/public/cpp/input_devices/input_device_controller_client.h" #include "services/ws/public/mojom/constants.mojom.h"
diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index 781a93dc..11ea62d5 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd
@@ -476,7 +476,6 @@ <include name="IDR_DICE_SYNC_CONFIRMATION_BROWSER_PROXY_JS" file="resources\signin\dice_sync_confirmation\sync_confirmation_browser_proxy.js" type="BINDATA" /> <include name="IDR_DICE_SYNC_CONFIRMATION_APP_HTML" file="resources\signin\dice_sync_confirmation\sync_confirmation_app.html" type="BINDATA" flattenhtml="true" allowexternalscript="true" /> <include name="IDR_DICE_SYNC_CONFIRMATION_APP_JS" file="resources\signin\dice_sync_confirmation\sync_confirmation_app.js" type="BINDATA" /> - <include name="IDR_DICE_SYNC_CONFIRMATION_ICONS_HTML" file="resources\signin\dice_sync_confirmation\icons.html" type="BINDATA" /> <include name="IDR_SIGNIN_EMAIL_CONFIRMATION_HTML" file="resources\signin\signin_email_confirmation\signin_email_confirmation.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> <include name="IDR_SIGNIN_EMAIL_CONFIRMATION_JS" file="resources\signin\signin_email_confirmation\signin_email_confirmation.js" type="BINDATA" /> <include name="IDR_SIGNIN_ERROR_HTML" file="resources\signin\signin_error\signin_error.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
diff --git a/chrome/browser/browser_switcher/browser_switcher_navigation_throttle.cc b/chrome/browser/browser_switcher/browser_switcher_navigation_throttle.cc index e28fbbcb..548197e 100644 --- a/chrome/browser/browser_switcher/browser_switcher_navigation_throttle.cc +++ b/chrome/browser/browser_switcher/browser_switcher_navigation_throttle.cc
@@ -16,6 +16,9 @@ #include "chrome/browser/browser_switcher/browser_switcher_sitelist.h" #include "chrome/browser/prerender/prerender_contents.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_list.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" #include "components/navigation_interception/intercept_navigation_throttle.h" #include "components/navigation_interception/navigation_params.h" #include "content/public/browser/browser_thread.h" @@ -27,6 +30,21 @@ namespace { +// Returns true if there's only 1 tab left open in this profile. Incognito +// window tabs count as the same profile. +bool IsLastTab(const Profile* profile) { + profile = profile->GetOriginalProfile(); + int tab_count = 0; + for (const Browser* browser : *BrowserList::GetInstance()) { + if (browser->profile()->GetOriginalProfile() != profile) + continue; + tab_count += browser->tab_strip_model()->count(); + if (tab_count > 1) + return false; + } + return true; +} + bool MaybeLaunchAlternativeBrowser( content::WebContents* web_contents, const navigation_interception::NavigationParams& params) { @@ -64,9 +82,15 @@ UMA_HISTOGRAM_BOOLEAN("BrowserSwitcher.LaunchSuccess", success); } if (success) { - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(&content::WebContents::ClosePage, - base::Unretained(web_contents))); + const Profile* profile = + Profile::FromBrowserContext(web_contents->GetBrowserContext()); + if (service->prefs().KeepLastTab() && IsLastTab(profile)) { + // TODO(nicolaso): Show the NTP after cancelling the navigation. + } else { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(&content::WebContents::ClosePage, + base::Unretained(web_contents))); + } return true; }
diff --git a/chrome/browser/browser_switcher/browser_switcher_prefs.cc b/chrome/browser/browser_switcher/browser_switcher_prefs.cc index 5b0afb9..9a6cecb 100644 --- a/chrome/browser/browser_switcher/browser_switcher_prefs.cc +++ b/chrome/browser/browser_switcher/browser_switcher_prefs.cc
@@ -50,6 +50,7 @@ registry->RegisterBooleanPref(prefs::kEnabled, false); registry->RegisterStringPref(prefs::kAlternativeBrowserPath, ""); registry->RegisterListPref(prefs::kAlternativeBrowserParameters); + registry->RegisterBooleanPref(prefs::kKeepLastTab, true); registry->RegisterListPref(prefs::kUrlList); registry->RegisterListPref(prefs::kUrlGreylist); registry->RegisterStringPref(prefs::kExternalSitelistUrl, ""); @@ -72,6 +73,10 @@ return alt_browser_params_; } +bool BrowserSwitcherPrefs::KeepLastTab() const { + return prefs_->GetBoolean(prefs::kKeepLastTab); +} + const RuleSet& BrowserSwitcherPrefs::GetRules() const { return rules_; } @@ -161,6 +166,9 @@ const char kAlternativeBrowserParameters[] = "browser_switcher.alternative_browser_parameters"; +// If true, always keep at least one tab open after switching. +const char kKeepLastTab[] = "browser_switcher.keep_last_tab"; + // List of host domain names to be opened in an alternative browser. const char kUrlList[] = "browser_switcher.url_list"; @@ -178,8 +186,5 @@ // Disable browser_switcher unless this is set to true. const char kEnabled[] = "browser_switcher.enabled"; -void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { -} - } // namespace prefs } // namespace browser_switcher
diff --git a/chrome/browser/browser_switcher/browser_switcher_prefs.h b/chrome/browser/browser_switcher/browser_switcher_prefs.h index 837fc3d..e15f078 100644 --- a/chrome/browser/browser_switcher/browser_switcher_prefs.h +++ b/chrome/browser/browser_switcher/browser_switcher_prefs.h
@@ -52,6 +52,9 @@ // substitutions. If the pref is not managed, returns the empty string. const std::vector<std::string>& GetAlternativeBrowserParameters() const; + // Returns true if Chrome should keep at least one tab open after switching. + bool KeepLastTab() const; + // Returns the sitelist + greylist configured directly through Chrome // policies. If the pref is not managed, returns an empty vector. const RuleSet& GetRules() const; @@ -91,6 +94,7 @@ extern const char kEnabled[]; extern const char kAlternativeBrowserPath[]; extern const char kAlternativeBrowserParameters[]; +extern const char kKeepLastTab[]; extern const char kUrlList[]; extern const char kUrlGreylist[]; extern const char kExternalSitelistUrl[];
diff --git a/chrome/browser/cached_image_fetcher/cached_image_fetcher_service_factory.cc b/chrome/browser/cached_image_fetcher/cached_image_fetcher_service_factory.cc index af590a7..fff90ec 100644 --- a/chrome/browser/cached_image_fetcher/cached_image_fetcher_service_factory.cc +++ b/chrome/browser/cached_image_fetcher/cached_image_fetcher_service_factory.cc
@@ -33,10 +33,6 @@ const base::FilePath::CharType kImageCacheSubdir[] = FILE_PATH_LITERAL("image_cache"); -std::unique_ptr<ImageDecoder> CreateImageDecoderImpl() { - return std::make_unique<suggestions::ImageDecoderImpl>(); -} - } // namespace // static @@ -92,7 +88,7 @@ ->GetURLLoaderFactoryForBrowserProcess(); return new CachedImageFetcherService( - base::BindRepeating(CreateImageDecoderImpl), + std::make_unique<suggestions::ImageDecoderImpl>(), std::move(url_loader_factory), std::move(image_cache), context->IsOffTheRecord()); }
diff --git a/chrome/browser/chrome_browser_main.cc b/chrome/browser/chrome_browser_main.cc index 1ac2e6f..cb11972a 100644 --- a/chrome/browser/chrome_browser_main.cc +++ b/chrome/browser/chrome_browser_main.cc
@@ -96,6 +96,7 @@ #include "chrome/browser/shell_integration.h" #include "chrome/browser/tracing/background_tracing_field_trial.h" #include "chrome/browser/tracing/navigation_tracing.h" +#include "chrome/browser/tracing/trace_event_system_stats_monitor.h" #include "chrome/browser/translate/translate_service.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" @@ -312,7 +313,6 @@ #endif // BUILDFLAG(ENABLE_WIDEVINE_CDM_COMPONENT) #if defined(USE_AURA) -#include "services/service_manager/runner/common/client_util.h" #include "ui/aura/env.h" #endif @@ -839,6 +839,11 @@ heap_profiler_controller_->StartIfEnabled(); + // TODO(sebmarchand): Allow this to be created earlier if startup tracing is + // enabled. + trace_event_system_stats_monitor_ = + std::make_unique<tracing::TraceEventSystemStatsMonitor>(); + // device_event_log must be initialized after the message loop. Calls to // {DEVICE}_LOG prior to here will only be logged with VLOG. Some // platforms (e.g. chromeos) may have already initialized this. @@ -1166,13 +1171,6 @@ } void ChromeBrowserMainParts::PreMainMessageLoopRun() { -#if defined(USE_AURA) - if (content::ServiceManagerConnection::GetForProcess() && - service_manager::ServiceManagerIsRemote()) { - content::ServiceManagerConnection::GetForProcess()-> - SetConnectionLostClosure(base::Bind(&chrome::SessionEnding)); - } -#endif TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun"); result_code_ = PreMainMessageLoopRunImpl();
diff --git a/chrome/browser/chrome_browser_main.h b/chrome/browser/chrome_browser_main.h index 919e417..280ba2a 100644 --- a/chrome/browser/chrome_browser_main.h +++ b/chrome/browser/chrome_browser_main.h
@@ -29,6 +29,10 @@ class ThreadProfiler; class WebUsbDetector; +namespace tracing { +class TraceEventSystemStatsMonitor; +} + class ChromeBrowserMainParts : public content::BrowserMainParts { public: ~ChromeBrowserMainParts() override; @@ -155,6 +159,11 @@ // the reporting pipeline. std::unique_ptr<HeapProfilerController> heap_profiler_controller_; + // The system stats monitor used by chrome://tracing. This doesn't do anything + // until tracing of the |system_stats| category is enabled. + std::unique_ptr<tracing::TraceEventSystemStatsMonitor> + trace_event_system_stats_monitor_; + // Whether PerformPreMainMessageLoopStartup() is called on VariationsService. // Initialized to true if |MainFunctionParams::ui_task| is null (meaning not // running browser_tests), but may be forced to true for tests.
diff --git a/chrome/browser/chrome_security_exploit_browsertest.cc b/chrome/browser/chrome_security_exploit_browsertest.cc index a0d97a67..7bafd37c 100644 --- a/chrome/browser/chrome_security_exploit_browsertest.cc +++ b/chrome/browser/chrome_security_exploit_browsertest.cc
@@ -101,8 +101,12 @@ DISALLOW_COPY_AND_ASSIGN(ChromeWebSecurityDisabledBrowserTest); }; +// TODO(nasko): This test as written is incompatible with Site Isolation +// restrictions, which disallow the cross-origin pushState call. +// Find a different way to implement issuing the illegal request or just +// delete the test if we have coverage elsewhere. See https://crbug.com/929161. IN_PROC_BROWSER_TEST_F(ChromeWebSecurityDisabledBrowserTest, - ChromeExtensionResources) { + DISABLED_ChromeExtensionResources) { // Load a page that requests a chrome-extension:// image through XHR. We // expect this load to fail, as it is an illegal request. GURL foo = embedded_test_server()->GetURL("foo.com",
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index c21a9aa..ab9d645cb 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -214,7 +214,6 @@ "//services/preferences/public/mojom", "//services/resource_coordinator/public/cpp:resource_coordinator_cpp", "//services/service_manager/public/cpp", - "//services/service_manager/runner/common", "//services/ws/public/cpp", "//services/ws/public/cpp/input_devices", "//skia",
diff --git a/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.cc b/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.cc index 63535a3..5340715 100644 --- a/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.cc +++ b/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.cc
@@ -88,7 +88,7 @@ // We're currently tracing, so start the new bridge, too. // |this| never gets destructed, so it's OK to bind an unretained pointer. bridge->StartTracing( - data_source_config_.trace_config, + data_source_config_.chrome_config().trace_config(), base::BindOnce(&ArcTracingDataSource::OnTracingStartedOnUI, base::Unretained(this))); } @@ -120,7 +120,7 @@ // tracing::ProducerClient::DataSourceBase. void StartTracing( tracing::ProducerClient* producer_client, - const tracing::mojom::DataSourceConfig& data_source_config) override { + const perfetto::DataSourceConfig& data_source_config) override { // |this| never gets destructed, so it's OK to bind an unretained pointer. // |producer_client| is a singleton that is never destroyed. base::PostTaskWithTraits( @@ -145,9 +145,8 @@ } // Starts all registered bridges. - void StartTracingOnUI( - tracing::ProducerClient* producer_client, - const tracing::mojom::DataSourceConfig& data_source_config) { + void StartTracingOnUI(tracing::ProducerClient* producer_client, + const perfetto::DataSourceConfig& data_source_config) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(!producer_client_); @@ -157,7 +156,7 @@ for (ArcTracingBridge* bridge : bridges_) { // |this| never gets destructed, so it's OK to bind an unretained pointer. bridge->StartTracing( - data_source_config_.trace_config, + data_source_config_.chrome_config().trace_config(), base::BindOnce(&ArcTracingDataSource::OnTracingStartedOnUI, base::Unretained(this))); } @@ -223,7 +222,7 @@ if (!data.empty()) { std::unique_ptr<perfetto::TraceWriter> trace_writer = producer_client_->CreateTraceWriter( - data_source_config_.target_buffer); + data_source_config_.target_buffer()); DCHECK(trace_writer); perfetto::TraceWriter::TracePacketHandle trace_packet_handle = trace_writer->NewTracePacket(); @@ -267,7 +266,7 @@ // Called when all bridges have completed stopping, notifying ProducerClient. base::OnceClosure stop_complete_callback_; tracing::ProducerClient* producer_client_ = nullptr; - tracing::mojom::DataSourceConfig data_source_config_; + perfetto::DataSourceConfig data_source_config_; DISALLOW_COPY_AND_ASSIGN(ArcTracingDataSource); };
diff --git a/chrome/browser/chromeos/crostini/crostini_pref_names.cc b/chrome/browser/chromeos/crostini/crostini_pref_names.cc index 5289b69..6e43048 100644 --- a/chrome/browser/chromeos/crostini/crostini_pref_names.cc +++ b/chrome/browser/chromeos/crostini/crostini_pref_names.cc
@@ -57,11 +57,10 @@ default_container.SetKey("container_name", base::Value(kCrostiniDefaultContainerName)); - auto default_containers_list = - std::make_unique<base::Value>(base::Value::Type::LIST); - default_containers_list->GetList().push_back(std::move(default_container)); + base::Value::ListStorage default_containers_list; + default_containers_list.push_back(std::move(default_container)); registry->RegisterListPref(kCrostiniContainers, - std::move(default_containers_list)); + base::Value(std::move(default_containers_list))); registry->RegisterBooleanPref(crostini::prefs::kReportCrostiniUsageEnabled, false);
diff --git a/chrome/browser/chromeos/login/enrollment/mock_auto_enrollment_check_screen.cc b/chrome/browser/chromeos/login/enrollment/mock_auto_enrollment_check_screen.cc index ad384c5..da9add60 100644 --- a/chrome/browser/chromeos/login/enrollment/mock_auto_enrollment_check_screen.cc +++ b/chrome/browser/chromeos/login/enrollment/mock_auto_enrollment_check_screen.cc
@@ -4,9 +4,6 @@ #include "chrome/browser/chromeos/login/enrollment/mock_auto_enrollment_check_screen.h" -using ::testing::AtLeast; -using ::testing::NotNull; - namespace chromeos { MockAutoEnrollmentCheckScreen::MockAutoEnrollmentCheckScreen( @@ -16,11 +13,13 @@ MockAutoEnrollmentCheckScreen::~MockAutoEnrollmentCheckScreen() {} -MockAutoEnrollmentCheckScreenView::MockAutoEnrollmentCheckScreenView() - : screen_(NULL) { - EXPECT_CALL(*this, MockSetDelegate(NotNull())).Times(AtLeast(1)); +void MockAutoEnrollmentCheckScreen::RealShow() { + AutoEnrollmentCheckScreen::Show(); } +MockAutoEnrollmentCheckScreenView::MockAutoEnrollmentCheckScreenView() = + default; + MockAutoEnrollmentCheckScreenView::~MockAutoEnrollmentCheckScreenView() { if (screen_) screen_->OnViewDestroyed(this);
diff --git a/chrome/browser/chromeos/login/enrollment/mock_auto_enrollment_check_screen.h b/chrome/browser/chromeos/login/enrollment/mock_auto_enrollment_check_screen.h index ecd7f7f7..08122e1 100644 --- a/chrome/browser/chromeos/login/enrollment/mock_auto_enrollment_check_screen.h +++ b/chrome/browser/chromeos/login/enrollment/mock_auto_enrollment_check_screen.h
@@ -16,6 +16,11 @@ MockAutoEnrollmentCheckScreen(BaseScreenDelegate* base_screen_delegate, AutoEnrollmentCheckScreenView* view); ~MockAutoEnrollmentCheckScreen() override; + + MOCK_METHOD0(Show, void()); + MOCK_METHOD0(Hide, void()); + + void RealShow(); }; class MockAutoEnrollmentCheckScreenView : public AutoEnrollmentCheckScreenView { @@ -29,7 +34,7 @@ MOCK_METHOD0(Show, void()); private: - Delegate* screen_; + Delegate* screen_ = nullptr; }; } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/enrollment/mock_enrollment_screen.h b/chrome/browser/chromeos/login/enrollment/mock_enrollment_screen.h index 8b7383c..af391399 100644 --- a/chrome/browser/chromeos/login/enrollment/mock_enrollment_screen.h +++ b/chrome/browser/chromeos/login/enrollment/mock_enrollment_screen.h
@@ -19,6 +19,9 @@ MockEnrollmentScreen(BaseScreenDelegate* base_screen_delegate, EnrollmentScreenView* view); ~MockEnrollmentScreen() override; + + MOCK_METHOD0(Show, void()); + MOCK_METHOD0(Hide, void()); }; class MockEnrollmentScreenView : public EnrollmentScreenView {
diff --git a/chrome/browser/chromeos/login/screen_manager.cc b/chrome/browser/chromeos/login/screen_manager.cc index 5a2e9a91..b433fb6 100644 --- a/chrome/browser/chromeos/login/screen_manager.cc +++ b/chrome/browser/chromeos/login/screen_manager.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/chromeos/login/screen_manager.h" +#include <utility> + #include "base/memory/ptr_util.h" #include "chrome/browser/chromeos/login/wizard_controller.h" @@ -30,4 +32,15 @@ return screens_.count(screen) > 0; } +void ScreenManager::SetScreenForTesting(std::unique_ptr<BaseScreen> value) { + // Capture screen id to avoid using `value` after moving it; = is not a + // sequence point. + auto id = value->screen_id(); + screens_[id] = std::move(value); +} + +void ScreenManager::DeleteScreenForTesting(OobeScreen screen) { + screens_[screen] = nullptr; +} + } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/screen_manager.h b/chrome/browser/chromeos/login/screen_manager.h index 8221e0a..2e9b9e75 100644 --- a/chrome/browser/chromeos/login/screen_manager.h +++ b/chrome/browser/chromeos/login/screen_manager.h
@@ -26,15 +26,10 @@ bool HasScreen(OobeScreen screen); - private: - FRIEND_TEST_ALL_PREFIXES(EnrollmentScreenTest, TestCancel); - FRIEND_TEST_ALL_PREFIXES(WizardControllerFlowTest, Accelerators); - friend class WizardControllerFlowTest; - friend class WizardControllerOobeResumeTest; - friend class WizardControllerBrokenLocalStateTest; - friend class WizardControllerOobeConfigurationTest; - friend class WizardControllerSupervisionTransitionOobeTest; + void SetScreenForTesting(std::unique_ptr<BaseScreen> value); + void DeleteScreenForTesting(OobeScreen screen); + private: // Created screens. std::map<OobeScreen, std::unique_ptr<BaseScreen>> screens_;
diff --git a/chrome/browser/chromeos/login/screens/mock_arc_terms_of_service_screen.cc b/chrome/browser/chromeos/login/screens/mock_arc_terms_of_service_screen.cc index d88e53c..98d582e 100644 --- a/chrome/browser/chromeos/login/screens/mock_arc_terms_of_service_screen.cc +++ b/chrome/browser/chromeos/login/screens/mock_arc_terms_of_service_screen.cc
@@ -4,9 +4,6 @@ #include "chrome/browser/chromeos/login/screens/mock_arc_terms_of_service_screen.h" -using ::testing::AtLeast; -using ::testing::NotNull; - namespace chromeos { MockArcTermsOfServiceScreen::MockArcTermsOfServiceScreen( @@ -29,4 +26,11 @@ MockAddObserver(observer); } +void MockArcTermsOfServiceScreenView::RemoveObserver( + ArcTermsOfServiceScreenViewObserver* observer) { + if (observer_ == observer) + observer_ = nullptr; + MockRemoveObserver(observer); +} + } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/screens/mock_arc_terms_of_service_screen.h b/chrome/browser/chromeos/login/screens/mock_arc_terms_of_service_screen.h index b9b1a97c..c16ef28e 100644 --- a/chrome/browser/chromeos/login/screens/mock_arc_terms_of_service_screen.h +++ b/chrome/browser/chromeos/login/screens/mock_arc_terms_of_service_screen.h
@@ -16,6 +16,9 @@ MockArcTermsOfServiceScreen(BaseScreenDelegate* base_screen_delegate, ArcTermsOfServiceScreenView* view); ~MockArcTermsOfServiceScreen() override; + + MOCK_METHOD0(Show, void()); + MOCK_METHOD0(Hide, void()); }; class MockArcTermsOfServiceScreenView : public ArcTermsOfServiceScreenView { @@ -24,17 +27,18 @@ ~MockArcTermsOfServiceScreenView() override; void AddObserver(ArcTermsOfServiceScreenViewObserver* observer) override; + void RemoveObserver(ArcTermsOfServiceScreenViewObserver* observer) override; MOCK_METHOD0(Show, void()); MOCK_METHOD0(Hide, void()); MOCK_METHOD1(Bind, void(ArcTermsOfServiceScreen* screen)); MOCK_METHOD1(MockAddObserver, void(ArcTermsOfServiceScreenViewObserver* observer)); - MOCK_METHOD1(RemoveObserver, + MOCK_METHOD1(MockRemoveObserver, void(ArcTermsOfServiceScreenViewObserver* observer)); private: - ArcTermsOfServiceScreenViewObserver* observer_; + ArcTermsOfServiceScreenViewObserver* observer_ = nullptr; }; } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/screens/mock_demo_preferences_screen.cc b/chrome/browser/chromeos/login/screens/mock_demo_preferences_screen.cc index 933e4e5c..98ab448 100644 --- a/chrome/browser/chromeos/login/screens/mock_demo_preferences_screen.cc +++ b/chrome/browser/chromeos/login/screens/mock_demo_preferences_screen.cc
@@ -4,9 +4,6 @@ #include "chrome/browser/chromeos/login/screens/mock_demo_preferences_screen.h" -using ::testing::AtLeast; -using ::testing::NotNull; - namespace chromeos { MockDemoPreferencesScreen::MockDemoPreferencesScreen( @@ -16,9 +13,7 @@ MockDemoPreferencesScreen::~MockDemoPreferencesScreen() = default; -MockDemoPreferencesScreenView::MockDemoPreferencesScreenView() { - EXPECT_CALL(*this, MockBind(NotNull())).Times(AtLeast(1)); -} +MockDemoPreferencesScreenView::MockDemoPreferencesScreenView() = default; MockDemoPreferencesScreenView::~MockDemoPreferencesScreenView() { if (screen_)
diff --git a/chrome/browser/chromeos/login/screens/mock_demo_preferences_screen.h b/chrome/browser/chromeos/login/screens/mock_demo_preferences_screen.h index 6721c50d..d1c1038 100644 --- a/chrome/browser/chromeos/login/screens/mock_demo_preferences_screen.h +++ b/chrome/browser/chromeos/login/screens/mock_demo_preferences_screen.h
@@ -18,6 +18,9 @@ DemoPreferencesScreenView* view); ~MockDemoPreferencesScreen() override; + MOCK_METHOD0(Show, void()); + MOCK_METHOD0(Hide, void()); + private: DISALLOW_COPY_AND_ASSIGN(MockDemoPreferencesScreen); }; @@ -34,7 +37,7 @@ void Bind(DemoPreferencesScreen* screen) override; private: - DemoPreferencesScreen* screen_; + DemoPreferencesScreen* screen_ = nullptr; DISALLOW_COPY_AND_ASSIGN(MockDemoPreferencesScreenView); };
diff --git a/chrome/browser/chromeos/login/screens/mock_demo_setup_screen.cc b/chrome/browser/chromeos/login/screens/mock_demo_setup_screen.cc index d22a651..ccd9252 100644 --- a/chrome/browser/chromeos/login/screens/mock_demo_setup_screen.cc +++ b/chrome/browser/chromeos/login/screens/mock_demo_setup_screen.cc
@@ -4,9 +4,6 @@ #include "chrome/browser/chromeos/login/screens/mock_demo_setup_screen.h" -using ::testing::AtLeast; -using ::testing::NotNull; - namespace chromeos { MockDemoSetupScreen::MockDemoSetupScreen( @@ -16,9 +13,7 @@ MockDemoSetupScreen::~MockDemoSetupScreen() = default; -MockDemoSetupScreenView::MockDemoSetupScreenView() { - EXPECT_CALL(*this, MockBind(NotNull())).Times(AtLeast(1)); -} +MockDemoSetupScreenView::MockDemoSetupScreenView() = default; MockDemoSetupScreenView::~MockDemoSetupScreenView() { if (screen_)
diff --git a/chrome/browser/chromeos/login/screens/mock_demo_setup_screen.h b/chrome/browser/chromeos/login/screens/mock_demo_setup_screen.h index ceac213..007df29 100644 --- a/chrome/browser/chromeos/login/screens/mock_demo_setup_screen.h +++ b/chrome/browser/chromeos/login/screens/mock_demo_setup_screen.h
@@ -17,6 +17,9 @@ MockDemoSetupScreen(BaseScreenDelegate* base_screen_delegate, DemoSetupScreenView* view); ~MockDemoSetupScreen() override; + + MOCK_METHOD0(Show, void()); + MOCK_METHOD0(Hide, void()); }; class MockDemoSetupScreenView : public DemoSetupScreenView { @@ -34,7 +37,7 @@ void Bind(DemoSetupScreen* screen) override; private: - DemoSetupScreen* screen_; + DemoSetupScreen* screen_ = nullptr; }; } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/screens/mock_enable_debugging_screen.cc b/chrome/browser/chromeos/login/screens/mock_enable_debugging_screen.cc index e19d5598..aed23fc 100644 --- a/chrome/browser/chromeos/login/screens/mock_enable_debugging_screen.cc +++ b/chrome/browser/chromeos/login/screens/mock_enable_debugging_screen.cc
@@ -4,9 +4,6 @@ #include "chrome/browser/chromeos/login/screens/mock_enable_debugging_screen.h" -using ::testing::AtLeast; -using ::testing::NotNull; - namespace chromeos { MockEnableDebuggingScreen::MockEnableDebuggingScreen( @@ -16,9 +13,7 @@ MockEnableDebuggingScreen::~MockEnableDebuggingScreen() {} -MockEnableDebuggingScreenView::MockEnableDebuggingScreenView() { - EXPECT_CALL(*this, MockSetDelegate(NotNull())).Times(AtLeast(1)); -} +MockEnableDebuggingScreenView::MockEnableDebuggingScreenView() = default; MockEnableDebuggingScreenView::~MockEnableDebuggingScreenView() { if (delegate_)
diff --git a/chrome/browser/chromeos/login/screens/mock_enable_debugging_screen.h b/chrome/browser/chromeos/login/screens/mock_enable_debugging_screen.h index 862b59a..16159c9 100644 --- a/chrome/browser/chromeos/login/screens/mock_enable_debugging_screen.h +++ b/chrome/browser/chromeos/login/screens/mock_enable_debugging_screen.h
@@ -17,6 +17,9 @@ MockEnableDebuggingScreen(BaseScreenDelegate* base_screen_delegate, EnableDebuggingScreenView* view); ~MockEnableDebuggingScreen() override; + + MOCK_METHOD0(Show, void()); + MOCK_METHOD0(Hide, void()); }; class MockEnableDebuggingScreenView : public EnableDebuggingScreenView {
diff --git a/chrome/browser/chromeos/login/screens/mock_eula_screen.h b/chrome/browser/chromeos/login/screens/mock_eula_screen.h index 5d71201..37caac4d 100644 --- a/chrome/browser/chromeos/login/screens/mock_eula_screen.h +++ b/chrome/browser/chromeos/login/screens/mock_eula_screen.h
@@ -18,6 +18,9 @@ Delegate* delegate, EulaView* view); ~MockEulaScreen() override; + + MOCK_METHOD0(Show, void()); + MOCK_METHOD0(Hide, void()); }; class MockEulaView : public EulaView {
diff --git a/chrome/browser/chromeos/login/screens/mock_supervision_transition_screen.cc b/chrome/browser/chromeos/login/screens/mock_supervision_transition_screen.cc index 1d9e7459..4b29528 100644 --- a/chrome/browser/chromeos/login/screens/mock_supervision_transition_screen.cc +++ b/chrome/browser/chromeos/login/screens/mock_supervision_transition_screen.cc
@@ -4,9 +4,6 @@ #include "chrome/browser/chromeos/login/screens/mock_supervision_transition_screen.h" -using ::testing::_; -using ::testing::AtLeast; - namespace chromeos { MockSupervisionTransitionScreen::MockSupervisionTransitionScreen( @@ -16,9 +13,8 @@ MockSupervisionTransitionScreen::~MockSupervisionTransitionScreen() = default; -MockSupervisionTransitionScreenView::MockSupervisionTransitionScreenView() { - EXPECT_CALL(*this, MockBind(_)).Times(AtLeast(1)); -} +MockSupervisionTransitionScreenView::MockSupervisionTransitionScreenView() = + default; MockSupervisionTransitionScreenView::~MockSupervisionTransitionScreenView() { if (screen_)
diff --git a/chrome/browser/chromeos/login/screens/mock_update_screen.h b/chrome/browser/chromeos/login/screens/mock_update_screen.h index d69cfe2..d4bd6e89 100644 --- a/chrome/browser/chromeos/login/screens/mock_update_screen.h +++ b/chrome/browser/chromeos/login/screens/mock_update_screen.h
@@ -17,6 +17,8 @@ MockUpdateScreen(BaseScreenDelegate* base_screen_delegate, UpdateView* view); virtual ~MockUpdateScreen(); + MOCK_METHOD0(Show, void()); + MOCK_METHOD0(Hide, void()); MOCK_METHOD0(StartNetworkCheck, void()); };
diff --git a/chrome/browser/chromeos/login/screens/mock_welcome_screen.cc b/chrome/browser/chromeos/login/screens/mock_welcome_screen.cc index 439143d..71c7dc4 100644 --- a/chrome/browser/chromeos/login/screens/mock_welcome_screen.cc +++ b/chrome/browser/chromeos/login/screens/mock_welcome_screen.cc
@@ -6,9 +6,6 @@ namespace chromeos { -using ::testing::AtLeast; -using ::testing::_; - MockWelcomeScreen::MockWelcomeScreen(BaseScreenDelegate* base_screen_delegate, Delegate* delegate, WelcomeView* view) @@ -16,9 +13,7 @@ MockWelcomeScreen::~MockWelcomeScreen() = default; -MockWelcomeView::MockWelcomeView() { - EXPECT_CALL(*this, MockBind(_)).Times(AtLeast(1)); -} +MockWelcomeView::MockWelcomeView() = default; MockWelcomeView::~MockWelcomeView() { if (screen_)
diff --git a/chrome/browser/chromeos/login/screens/mock_wrong_hwid_screen.cc b/chrome/browser/chromeos/login/screens/mock_wrong_hwid_screen.cc index d6b6604..d49f3df1 100644 --- a/chrome/browser/chromeos/login/screens/mock_wrong_hwid_screen.cc +++ b/chrome/browser/chromeos/login/screens/mock_wrong_hwid_screen.cc
@@ -4,9 +4,6 @@ #include "chrome/browser/chromeos/login/screens/mock_wrong_hwid_screen.h" -using testing::AtLeast; -using testing::NotNull; - namespace chromeos { MockWrongHWIDScreen::MockWrongHWIDScreen( @@ -16,9 +13,7 @@ MockWrongHWIDScreen::~MockWrongHWIDScreen() {} -MockWrongHWIDScreenView::MockWrongHWIDScreenView() : delegate_(nullptr) { - EXPECT_CALL(*this, MockSetDelegate(NotNull())).Times(AtLeast(1)); -} +MockWrongHWIDScreenView::MockWrongHWIDScreenView() = default; MockWrongHWIDScreenView::~MockWrongHWIDScreenView() { if (delegate_)
diff --git a/chrome/browser/chromeos/login/screens/mock_wrong_hwid_screen.h b/chrome/browser/chromeos/login/screens/mock_wrong_hwid_screen.h index 66dd49c..61a01c5 100644 --- a/chrome/browser/chromeos/login/screens/mock_wrong_hwid_screen.h +++ b/chrome/browser/chromeos/login/screens/mock_wrong_hwid_screen.h
@@ -18,6 +18,9 @@ MockWrongHWIDScreen(BaseScreenDelegate* base_screen_delegate, WrongHWIDScreenView* view); ~MockWrongHWIDScreen() override; + + MOCK_METHOD0(Show, void()); + MOCK_METHOD0(Hide, void()); }; class MockWrongHWIDScreenView : public WrongHWIDScreenView { @@ -32,7 +35,7 @@ MOCK_METHOD1(MockSetDelegate, void(Delegate*)); private: - Delegate* delegate_; + Delegate* delegate_ = nullptr; }; } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/wizard_controller_browsertest.cc b/chrome/browser/chromeos/login/wizard_controller_browsertest.cc index 69585de4..f4060b4 100644 --- a/chrome/browser/chromeos/login/wizard_controller_browsertest.cc +++ b/chrome/browser/chromeos/login/wizard_controller_browsertest.cc
@@ -106,12 +106,13 @@ #include "ui/base/l10n/l10n_util.h" using ::testing::_; +using ::testing::AtLeast; using ::testing::Exactly; using ::testing::Invoke; +using ::testing::IsNull; using ::testing::Mock; using ::testing::Not; using ::testing::NotNull; -using ::testing::IsNull; using ::testing::Return; namespace chromeos { @@ -309,52 +310,44 @@ return rlz_embargo_end_date_string; } +template <typename View> +void ExpectBind(View* view) { + // TODO(jdufault): The view* api should follow the bind/unbind pattern instead + // of bind(ptr), bind(nullptr). + EXPECT_CALL(*view, MockBind(NotNull())).Times(1); + EXPECT_CALL(*view, MockBind(IsNull())).Times(1); +} + +template <typename View> +void ExpectBindUnbind(View* view) { + EXPECT_CALL(*view, MockBind(NotNull())).Times(1); + EXPECT_CALL(*view, MockUnbind()).Times(1); +} + +template <typename View> +void ExpectSetDelegate(View* view) { + EXPECT_CALL(*view, MockSetDelegate(NotNull())).Times(1); + EXPECT_CALL(*view, MockSetDelegate(IsNull())).Times(1); +} + +template <typename Mock> +Mock* MockScreen(std::unique_ptr<Mock> mock) { + auto mock0 = mock.get(); + WizardController::default_controller()->screen_manager()->SetScreenForTesting( + std::move(mock)); + return mock0; +} + +template <typename Mock> +Mock* MockScreenExpectLifecycle(std::unique_ptr<Mock> mock) { + auto mock0 = MockScreen(std::move(mock)); + EXPECT_CALL(*mock0, Show()).Times(0); + EXPECT_CALL(*mock0, Hide()).Times(0); + return mock0; +} + } // namespace -using ::testing::_; - -template <class T, class H> -class MockOutShowHide : public T { - public: - template <class P> - explicit MockOutShowHide(P p) : T(p) {} - template <class P> - MockOutShowHide(P p, H* view) : T(p, view), view_(view) {} - template <class P, class Q> - MockOutShowHide(P p, Q q, H* view) : T(p, q, view), view_(view) {} - - H* view() const { return view_.get(); } - - MOCK_METHOD0(Show, void()); - MOCK_METHOD0(Hide, void()); - - void RealShow() { T::Show(); } - - void RealHide() { T::Hide(); } - - private: - std::unique_ptr<H> view_; -}; - -#define MOCK(mock_var, screen_name, mocked_class, view_class) \ - mock_var = new MockOutShowHide<mocked_class, view_class>( \ - WizardController::default_controller(), new view_class); \ - WizardController::default_controller() \ - ->screen_manager() \ - ->screens_[screen_name] = base::WrapUnique(mock_var); \ - EXPECT_CALL(*mock_var, Show()).Times(0); \ - EXPECT_CALL(*mock_var, Hide()).Times(0); - -#define MOCK_WITH_DELEGATE(mock_var, screen_name, mocked_class, view_class) \ - mock_var = new MockOutShowHide<mocked_class, view_class>( \ - WizardController::default_controller(), \ - WizardController::default_controller(), new view_class); \ - WizardController::default_controller() \ - ->screen_manager() \ - ->screens_[screen_name] = base::WrapUnique(mock_var); \ - EXPECT_CALL(*mock_var, Show()).Times(0); \ - EXPECT_CALL(*mock_var, Hide()).Times(0); - class WizardControllerTest : public InProcessBrowserTest { protected: WizardControllerTest() = default; @@ -506,10 +499,16 @@ // Pretend OOBE was complete. StartupUtils::MarkOobeCompleted(); - WizardController::default_controller()->is_official_build_ = true; - MOCK(mock_supervision_transition_screen_, - OobeScreen::SCREEN_SUPERVISION_TRANSITION, - MockSupervisionTransitionScreen, MockSupervisionTransitionScreenView); + WizardController* wizard_controller = + WizardController::default_controller(); + wizard_controller->is_official_build_ = true; + + mock_supervision_transition_screen_view_ = + std::make_unique<MockSupervisionTransitionScreenView>(); + ExpectBindUnbind(mock_supervision_transition_screen_view_.get()); + mock_supervision_transition_screen_ = MockScreenExpectLifecycle( + std::make_unique<MockSupervisionTransitionScreen>( + wizard_controller, mock_supervision_transition_screen_view_.get())); } void SetUpCommandLine(base::CommandLine* command_line) override { @@ -523,9 +522,9 @@ ScreenExitCode::SUPERVISION_TRANSITION_FINISHED); } - MockOutShowHide<MockSupervisionTransitionScreen, - MockSupervisionTransitionScreenView>* - mock_supervision_transition_screen_; + MockSupervisionTransitionScreen* mock_supervision_transition_screen_; + std::unique_ptr<MockSupervisionTransitionScreenView> + mock_supervision_transition_screen_view_; private: DISALLOW_COPY_AND_ASSIGN(WizardControllerSupervisionTransitionOobeTest); @@ -578,47 +577,88 @@ NetworkHandler::Get()->network_state_handler()->SetCheckPortalList(""); // Set up the mocks for all screens. - mock_welcome_screen_ = new MockWelcomeScreen( - WizardController::default_controller(), - WizardController::default_controller(), GetOobeUI()->GetWelcomeView()); - WizardController::default_controller() - ->screen_manager() - ->screens_[OobeScreen::SCREEN_OOBE_WELCOME] - .reset(mock_welcome_screen_); - EXPECT_CALL(*mock_welcome_screen_, Show()).Times(0); - EXPECT_CALL(*mock_welcome_screen_, Hide()).Times(0); + mock_welcome_screen_ = + MockScreenExpectLifecycle(std::make_unique<MockWelcomeScreen>( + wizard_controller, wizard_controller, + GetOobeUI()->GetWelcomeView())); - MOCK(mock_network_screen_, OobeScreen::SCREEN_OOBE_NETWORK, - MockNetworkScreen, MockNetworkScreenView); - MOCK(mock_update_screen_, OobeScreen::SCREEN_OOBE_UPDATE, MockUpdateScreen, - MockUpdateView); - MOCK_WITH_DELEGATE(mock_eula_screen_, OobeScreen::SCREEN_OOBE_EULA, - MockEulaScreen, MockEulaView); - MOCK(mock_enrollment_screen_, OobeScreen::SCREEN_OOBE_ENROLLMENT, - MockEnrollmentScreen, MockEnrollmentScreenView); - MOCK(mock_auto_enrollment_check_screen_, - OobeScreen::SCREEN_AUTO_ENROLLMENT_CHECK, - MockAutoEnrollmentCheckScreen, MockAutoEnrollmentCheckScreenView); - MOCK(mock_wrong_hwid_screen_, OobeScreen::SCREEN_WRONG_HWID, - MockWrongHWIDScreen, MockWrongHWIDScreenView); - MOCK(mock_enable_debugging_screen_, - OobeScreen::SCREEN_OOBE_ENABLE_DEBUGGING, MockEnableDebuggingScreen, - MockEnableDebuggingScreenView); - MOCK(mock_demo_setup_screen_, OobeScreen::SCREEN_OOBE_DEMO_SETUP, - MockDemoSetupScreen, MockDemoSetupScreenView); - MOCK(mock_demo_preferences_screen_, - OobeScreen::SCREEN_OOBE_DEMO_PREFERENCES, MockDemoPreferencesScreen, - MockDemoPreferencesScreenView); - MOCK(mock_arc_terms_of_service_screen_, - OobeScreen::SCREEN_ARC_TERMS_OF_SERVICE, MockArcTermsOfServiceScreen, - MockArcTermsOfServiceScreenView); - device_disabled_screen_view_.reset(new MockDeviceDisabledScreenView); - wizard_controller->screen_manager() - ->screens_[OobeScreen::SCREEN_DEVICE_DISABLED] = - std::make_unique<DeviceDisabledScreen>( - wizard_controller, device_disabled_screen_view_.get()); + mock_demo_preferences_screen_view_ = + std::make_unique<MockDemoPreferencesScreenView>(); + mock_demo_preferences_screen_ = + MockScreenExpectLifecycle(std::make_unique<MockDemoPreferencesScreen>( + wizard_controller, mock_demo_preferences_screen_view_.get())); + + mock_arc_terms_of_service_screen_view_ = + std::make_unique<MockArcTermsOfServiceScreenView>(); + mock_arc_terms_of_service_screen_ = + MockScreenExpectLifecycle(std::make_unique<MockArcTermsOfServiceScreen>( + wizard_controller, mock_arc_terms_of_service_screen_view_.get())); + + device_disabled_screen_view_ = + std::make_unique<MockDeviceDisabledScreenView>(); + MockScreen(std::make_unique<DeviceDisabledScreen>( + wizard_controller, device_disabled_screen_view_.get())); EXPECT_CALL(*device_disabled_screen_view_, Show()).Times(0); + mock_network_screen_view_ = std::make_unique<MockNetworkScreenView>(); + mock_network_screen_ = + MockScreenExpectLifecycle(std::make_unique<MockNetworkScreen>( + wizard_controller, mock_network_screen_view_.get())); + + mock_update_view_ = std::make_unique<MockUpdateView>(); + mock_update_screen_ = + MockScreenExpectLifecycle(std::make_unique<MockUpdateScreen>( + wizard_controller, mock_update_view_.get())); + + mock_eula_view_ = std::make_unique<MockEulaView>(); + mock_eula_screen_ = + MockScreenExpectLifecycle(std::make_unique<MockEulaScreen>( + wizard_controller, wizard_controller, mock_eula_view_.get())); + + mock_enrollment_screen_view_ = std::make_unique<MockEnrollmentScreenView>(); + mock_enrollment_screen_ = + MockScreenExpectLifecycle(std::make_unique<MockEnrollmentScreen>( + wizard_controller, mock_enrollment_screen_view_.get())); + + mock_auto_enrollment_check_screen_view_ = + std::make_unique<MockAutoEnrollmentCheckScreenView>(); + ExpectSetDelegate(mock_auto_enrollment_check_screen_view_.get()); + mock_auto_enrollment_check_screen_ = MockScreenExpectLifecycle( + std::make_unique<MockAutoEnrollmentCheckScreen>( + wizard_controller, mock_auto_enrollment_check_screen_view_.get())); + + mock_wrong_hwid_screen_view_ = std::make_unique<MockWrongHWIDScreenView>(); + ExpectSetDelegate(mock_wrong_hwid_screen_view_.get()); + mock_wrong_hwid_screen_ = + MockScreenExpectLifecycle(std::make_unique<MockWrongHWIDScreen>( + wizard_controller, mock_wrong_hwid_screen_view_.get())); + + mock_enable_debugging_screen_view_ = + std::make_unique<MockEnableDebuggingScreenView>(); + ExpectSetDelegate(mock_enable_debugging_screen_view_.get()); + mock_enable_debugging_screen_ = + MockScreenExpectLifecycle(std::make_unique<MockEnableDebuggingScreen>( + wizard_controller, mock_enable_debugging_screen_view_.get())); + + mock_demo_setup_screen_view_ = std::make_unique<MockDemoSetupScreenView>(); + ExpectBind(mock_demo_setup_screen_view_.get()); + mock_demo_setup_screen_ = + MockScreenExpectLifecycle(std::make_unique<MockDemoSetupScreen>( + wizard_controller, mock_demo_setup_screen_view_.get())); + + mock_demo_preferences_screen_view_ = + std::make_unique<MockDemoPreferencesScreenView>(); + ExpectBind(mock_demo_preferences_screen_view_.get()); + mock_demo_preferences_screen_ = + MockScreenExpectLifecycle(std::make_unique<MockDemoPreferencesScreen>( + wizard_controller, mock_demo_preferences_screen_view_.get())); + + mock_arc_terms_of_service_screen_view_ = + std::make_unique<MockArcTermsOfServiceScreenView>(); + mock_arc_terms_of_service_screen_ = + MockScreenExpectLifecycle(std::make_unique<MockArcTermsOfServiceScreen>( + wizard_controller, mock_arc_terms_of_service_screen_view_.get())); + // Switch to the initial screen. EXPECT_EQ(NULL, wizard_controller->current_screen()); EXPECT_CALL(*mock_welcome_screen_, SetConfiguration(NotNull(), _)).Times(1); @@ -672,8 +712,9 @@ } void ResetAutoEnrollmentCheckScreen() { - WizardController::default_controller()->screen_manager()->screens_.erase( - OobeScreen::SCREEN_AUTO_ENROLLMENT_CHECK); + WizardController::default_controller() + ->screen_manager() + ->DeleteScreenForTesting(OobeScreen::SCREEN_AUTO_ENROLLMENT_CHECK); } void TestControlFlowMain() { @@ -744,32 +785,48 @@ ->GetCurrentTimezoneID())); } - MockWelcomeScreen* mock_welcome_screen_; // Unowned ptr. - MockOutShowHide<MockNetworkScreen, MockNetworkScreenView>* - mock_network_screen_; - MockOutShowHide<MockUpdateScreen, MockUpdateView>* mock_update_screen_; - MockOutShowHide<MockEulaScreen, MockEulaView>* mock_eula_screen_; - MockOutShowHide<MockEnrollmentScreen, MockEnrollmentScreenView>* - mock_enrollment_screen_; - MockOutShowHide<MockAutoEnrollmentCheckScreen, - MockAutoEnrollmentCheckScreenView>* - mock_auto_enrollment_check_screen_; - MockOutShowHide<MockWrongHWIDScreen, MockWrongHWIDScreenView>* - mock_wrong_hwid_screen_; - MockOutShowHide<MockEnableDebuggingScreen, MockEnableDebuggingScreenView>* - mock_enable_debugging_screen_; - MockOutShowHide<MockDemoSetupScreen, MockDemoSetupScreenView>* - mock_demo_setup_screen_; - MockOutShowHide<MockDemoPreferencesScreen, MockDemoPreferencesScreenView>* - mock_demo_preferences_screen_; + // All of the *Screen types are owned by WizardController. The views are owned + // by this test class. + MockWelcomeScreen* mock_welcome_screen_ = nullptr; - MockOutShowHide<MockArcTermsOfServiceScreen, MockArcTermsOfServiceScreenView>* - mock_arc_terms_of_service_screen_; + MockNetworkScreen* mock_network_screen_ = nullptr; + std::unique_ptr<MockNetworkScreenView> mock_network_screen_view_; + + MockUpdateScreen* mock_update_screen_ = nullptr; + std::unique_ptr<MockUpdateView> mock_update_view_; + + MockEulaScreen* mock_eula_screen_ = nullptr; + std::unique_ptr<MockEulaView> mock_eula_view_; + + MockEnrollmentScreen* mock_enrollment_screen_ = nullptr; + std::unique_ptr<MockEnrollmentScreenView> mock_enrollment_screen_view_; + + MockAutoEnrollmentCheckScreen* mock_auto_enrollment_check_screen_ = nullptr; + std::unique_ptr<MockAutoEnrollmentCheckScreenView> + mock_auto_enrollment_check_screen_view_; + + MockWrongHWIDScreen* mock_wrong_hwid_screen_ = nullptr; + std::unique_ptr<MockWrongHWIDScreenView> mock_wrong_hwid_screen_view_; + + MockEnableDebuggingScreen* mock_enable_debugging_screen_ = nullptr; + std::unique_ptr<MockEnableDebuggingScreenView> + mock_enable_debugging_screen_view_; + + MockDemoSetupScreen* mock_demo_setup_screen_ = nullptr; + std::unique_ptr<MockDemoSetupScreenView> mock_demo_setup_screen_view_; + + MockDemoPreferencesScreen* mock_demo_preferences_screen_ = nullptr; + std::unique_ptr<MockDemoPreferencesScreenView> + mock_demo_preferences_screen_view_; + + MockArcTermsOfServiceScreen* mock_arc_terms_of_service_screen_ = nullptr; + std::unique_ptr<MockArcTermsOfServiceScreenView> + mock_arc_terms_of_service_screen_view_; std::unique_ptr<MockDeviceDisabledScreenView> device_disabled_screen_view_; private: - NetworkPortalDetectorTestImpl* network_portal_detector_; + NetworkPortalDetectorTestImpl* network_portal_detector_ = nullptr; network::TestURLLoaderFactory test_url_loader_factory_; @@ -912,7 +969,7 @@ EXPECT_CALL(*mock_update_screen_, StartNetworkCheck()).Times(0); EXPECT_CALL(*mock_update_screen_, Show()).Times(0); WizardController::default_controller()->SkipUpdateEnrollAfterEula(); - EXPECT_CALL(*mock_enrollment_screen_->view(), + EXPECT_CALL(*mock_enrollment_screen_view_, SetEnrollmentConfig( mock_enrollment_screen_, EnrollmentModeMatches(policy::EnrollmentConfig::MODE_MANUAL))) @@ -959,7 +1016,7 @@ ControlFlowEnrollmentCompleted) { CheckCurrentScreen(OobeScreen::SCREEN_OOBE_WELCOME); EXPECT_CALL(*mock_update_screen_, StartNetworkCheck()).Times(0); - EXPECT_CALL(*mock_enrollment_screen_->view(), + EXPECT_CALL(*mock_enrollment_screen_view_, SetEnrollmentConfig( mock_enrollment_screen_, EnrollmentModeMatches(policy::EnrollmentConfig::MODE_MANUAL))) @@ -1357,7 +1414,7 @@ device_state); EXPECT_CALL(*mock_enrollment_screen_, Show()).Times(1); EXPECT_CALL( - *mock_enrollment_screen_->view(), + *mock_enrollment_screen_view_, SetEnrollmentConfig( mock_enrollment_screen_, EnrollmentModeMatches(policy::EnrollmentConfig::MODE_SERVER_FORCED))) @@ -1450,7 +1507,7 @@ device_state); EXPECT_CALL(*mock_enrollment_screen_, Show()).Times(1); EXPECT_CALL( - *mock_enrollment_screen_->view(), + *mock_enrollment_screen_view_, SetEnrollmentConfig(mock_enrollment_screen_, EnrollmentModeMatches( policy::EnrollmentConfig::MODE_SERVER_FORCED))) @@ -1583,7 +1640,7 @@ device_state); EXPECT_CALL(*mock_enrollment_screen_, Show()).Times(1); EXPECT_CALL( - *mock_enrollment_screen_->view(), + *mock_enrollment_screen_view_, SetEnrollmentConfig( mock_enrollment_screen_, EnrollmentModeMatches(policy::EnrollmentConfig::MODE_SERVER_FORCED))) @@ -1675,7 +1732,7 @@ device_state); EXPECT_CALL(*mock_enrollment_screen_, Show()).Times(1); EXPECT_CALL( - *mock_enrollment_screen_->view(), + *mock_enrollment_screen_view_, SetEnrollmentConfig( mock_enrollment_screen_, EnrollmentModeMatches(policy::EnrollmentConfig::MODE_SERVER_FORCED))) @@ -1916,7 +1973,7 @@ EXPECT_CALL(*mock_enrollment_screen_, Show()).Times(1); EXPECT_CALL( - *mock_enrollment_screen_->view(), + *mock_enrollment_screen_view_, SetEnrollmentConfig( mock_enrollment_screen_, EnrollmentModeMatches(policy::EnrollmentConfig::MODE_SERVER_FORCED))) @@ -2107,7 +2164,7 @@ IN_PROC_BROWSER_TEST_F(WizardControllerKioskFlowTest, ControlFlowKioskForcedEnrollment) { EXPECT_CALL( - *mock_enrollment_screen_->view(), + *mock_enrollment_screen_view_, SetEnrollmentConfig( mock_enrollment_screen_, EnrollmentModeMatches(policy::EnrollmentConfig::MODE_LOCAL_FORCED))) @@ -2154,7 +2211,7 @@ IN_PROC_BROWSER_TEST_F(WizardControllerKioskFlowTest, ControlFlowEnrollmentBack) { EXPECT_CALL( - *mock_enrollment_screen_->view(), + *mock_enrollment_screen_view_, SetEnrollmentConfig( mock_enrollment_screen_, EnrollmentModeMatches(policy::EnrollmentConfig::MODE_LOCAL_FORCED))) @@ -2256,8 +2313,8 @@ testing::Mock::VerifyAndClearExpectations(mock_welcome_screen_); } - template <class T, class H> - void SkipToScreen(OobeScreen screen, MockOutShowHide<T, H>* screen_mock) { + template <class T> + void SkipToScreen(OobeScreen screen, T* screen_mock) { EXPECT_CALL(*screen_mock, Show()).Times(1); auto* const wizard_controller = WizardController::default_controller(); wizard_controller->SimulateDemoModeSetupForTesting(); @@ -2657,16 +2714,24 @@ WizardControllerTest::SetUpOnMainThread(); // Make sure that OOBE is run as an "official" build. - WizardController::default_controller()->is_official_build_ = true; + WizardController* wizard_controller = + WizardController::default_controller(); + wizard_controller->is_official_build_ = true; // Clear portal list (as it is by default in OOBE). NetworkHandler::Get()->network_state_handler()->SetCheckPortalList(""); // Set up the mocks for all screens. - MOCK_WITH_DELEGATE(mock_welcome_screen_, OobeScreen::SCREEN_OOBE_WELCOME, - MockWelcomeScreen, MockWelcomeView); - MOCK(mock_enrollment_screen_, OobeScreen::SCREEN_OOBE_ENROLLMENT, - MockEnrollmentScreen, MockEnrollmentScreenView); + mock_welcome_view_ = std::make_unique<MockWelcomeView>(); + ExpectBindUnbind(mock_welcome_view_.get()); + mock_welcome_screen_ = + MockScreenExpectLifecycle(std::make_unique<MockWelcomeScreen>( + wizard_controller, wizard_controller, mock_welcome_view_.get())); + + mock_enrollment_screen_view_ = std::make_unique<MockEnrollmentScreenView>(); + mock_enrollment_screen_ = + MockScreenExpectLifecycle(std::make_unique<MockEnrollmentScreen>( + wizard_controller, mock_enrollment_screen_view_.get())); } void OnExit(ScreenExitCode exit_code) { @@ -2677,9 +2742,11 @@ return WizardController::default_controller()->first_screen(); } - MockOutShowHide<MockWelcomeScreen, MockWelcomeView>* mock_welcome_screen_; - MockOutShowHide<MockEnrollmentScreen, MockEnrollmentScreenView>* - mock_enrollment_screen_; + std::unique_ptr<MockWelcomeView> mock_welcome_view_; + MockWelcomeScreen* mock_welcome_screen_; + + std::unique_ptr<MockEnrollmentScreenView> mock_enrollment_screen_view_; + MockEnrollmentScreen* mock_enrollment_screen_; private: DISALLOW_COPY_AND_ASSIGN(WizardControllerOobeResumeTest); @@ -2693,7 +2760,7 @@ WizardController::default_controller()->AdvanceToScreen( OobeScreen::SCREEN_OOBE_WELCOME); CheckCurrentScreen(OobeScreen::SCREEN_OOBE_WELCOME); - EXPECT_CALL(*mock_enrollment_screen_->view(), + EXPECT_CALL(*mock_enrollment_screen_view_, SetEnrollmentConfig( mock_enrollment_screen_, EnrollmentModeMatches(policy::EnrollmentConfig::MODE_MANUAL))) @@ -2756,8 +2823,10 @@ // Clear portal list (as it is by default in OOBE). NetworkHandler::Get()->network_state_handler()->SetCheckPortalList(""); - MOCK_WITH_DELEGATE(mock_welcome_screen_, OobeScreen::SCREEN_OOBE_WELCOME, - MockWelcomeScreen, MockWelcomeView); + mock_welcome_view_ = std::make_unique<MockWelcomeView>(); + mock_welcome_screen_ = + MockScreenExpectLifecycle(std::make_unique<MockWelcomeScreen>( + wizard_controller, wizard_controller, mock_welcome_view_.get())); } void WaitForConfigurationLoaded() { @@ -2769,7 +2838,8 @@ } protected: - MockOutShowHide<MockWelcomeScreen, MockWelcomeView>* mock_welcome_screen_; + std::unique_ptr<MockWelcomeView> mock_welcome_view_; + MockWelcomeScreen* mock_welcome_screen_ = nullptr; private: DISALLOW_COPY_AND_ASSIGN(WizardControllerOobeConfigurationTest);
diff --git a/chrome/browser/chromeos/net/network_portal_detector_impl.cc b/chrome/browser/chromeos/net/network_portal_detector_impl.cc index 2ca549b..eb4e857 100644 --- a/chrome/browser/chromeos/net/network_portal_detector_impl.cc +++ b/chrome/browser/chromeos/net/network_portal_detector_impl.cc
@@ -168,6 +168,13 @@ } } +void SetNetworkPortalDetected(const NetworkState* network, + bool portal_detected) { + NetworkHandler::Get() + ->network_state_handler() + ->SetNetworkChromePortalDetected(network->path(), portal_detected); +} + } // namespace //////////////////////////////////////////////////////////////////////////////// @@ -294,6 +301,7 @@ return; NET_LOG(EVENT) << "Starting detection attempt:" << " name=" << network->name() << " id=" << network->guid(); + SetNetworkPortalDetected(network, false /* portal_detected */); portal_state_map_.erase(network->guid()); StartDetection(); } @@ -339,7 +347,7 @@ CaptivePortalState state; state.status = CAPTIVE_PORTAL_STATUS_OFFLINE; - OnDetectionCompleted(nullptr, state); + DetectionCompleted(nullptr, state); return; } @@ -579,10 +587,10 @@ if (state.status != CAPTIVE_PORTAL_STATUS_OFFLINE || same_detection_result_count_ >= kMaxOfflineResultsBeforeReport) { - OnDetectionCompleted(network, state); + DetectionCompleted(network, state); } - // Observers (via OnDetectionCompleted) may already schedule new attempt. + // Observers (via DetectionCompleted) may already schedule new attempt. if (is_idle()) ScheduleAttempt(results.retry_after_delta); } @@ -600,7 +608,7 @@ } } -void NetworkPortalDetectorImpl::OnDetectionCompleted( +void NetworkPortalDetectorImpl::DetectionCompleted( const NetworkState* network, const CaptivePortalState& state) { if (!network) { @@ -622,6 +630,9 @@ RecordPortalToOnlineTransition(state.time - it->second.time); } + SetNetworkPortalDetected( + network, + state.status == NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_PORTAL); portal_state_map_[network->guid()] = state; } NotifyDetectionCompleted(network, state);
diff --git a/chrome/browser/chromeos/net/network_portal_detector_impl.h b/chrome/browser/chromeos/net/network_portal_detector_impl.h index e4cec2d..18a3ebc4 100644 --- a/chrome/browser/chromeos/net/network_portal_detector_impl.h +++ b/chrome/browser/chromeos/net/network_portal_detector_impl.h
@@ -145,9 +145,10 @@ const content::NotificationSource& source, const content::NotificationDetails& details) override; - // Stores captive portal state for a |network| and notifies observers. - void OnDetectionCompleted(const NetworkState* network, - const CaptivePortalState& results); + // Called synchronously from OnAttemptCompleted with the current default + // network. Stores the captive portal state and notifies observers. + void DetectionCompleted(const NetworkState* network, + const CaptivePortalState& results); // Notifies observers that portal detection is completed for a |network|. void NotifyDetectionCompleted(const NetworkState* network,
diff --git a/chrome/browser/chromeos/smb_client/smb_file_system.h b/chrome/browser/chromeos/smb_client/smb_file_system.h index 3f9971b..08915ae 100644 --- a/chrome/browser/chromeos/smb_client/smb_file_system.h +++ b/chrome/browser/chromeos/smb_client/smb_file_system.h
@@ -52,6 +52,11 @@ base::RepeatingCallback<void(const std::string& /* share_path */, int32_t /* mount_id */, base::OnceClosure /* reply */)>; + using RequestUpdatedSharePathCallback = + base::RepeatingCallback<void(const std::string& /* share_path */, + int32_t /* mount_id */, + SmbService::StartReadDirIfSuccessfulCallback + /* reply */)>; SmbFileSystem( const file_system_provider::ProvidedFileSystemInfo& file_system_info,
diff --git a/chrome/browser/chromeos/smb_client/smb_provider.cc b/chrome/browser/chromeos/smb_client/smb_provider.cc index ca78c15..1a4e26e 100644 --- a/chrome/browser/chromeos/smb_client/smb_provider.cc +++ b/chrome/browser/chromeos/smb_client/smb_provider.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/chromeos/smb_client/smb_provider.h" +#include <utility> + #include "chrome/browser/chromeos/file_system_provider/provided_file_system_info.h" #include "chrome/browser/chromeos/file_system_provider/provided_file_system_interface.h" #include "chrome/browser/chromeos/file_system_provider/service.h" @@ -20,7 +22,8 @@ SmbProvider::SmbProvider( UnmountCallback unmount_callback, - SmbFileSystem::RequestCredentialsCallback request_creds_callback) + SmbFileSystem::RequestCredentialsCallback request_creds_callback, + SmbFileSystem::RequestUpdatedSharePathCallback request_path_callback) : provider_id_(ProviderId::CreateFromNativeId("smb")), capabilities_(false /* configurable */, false /* watchable */, @@ -28,7 +31,8 @@ extensions::SOURCE_NETWORK), name_(l10n_util::GetStringUTF8(IDS_SMB_SHARES_ADD_SERVICE_MENU_OPTION)), unmount_callback_(std::move(unmount_callback)), - request_creds_callback_(std::move(request_creds_callback)) { + request_creds_callback_(std::move(request_creds_callback)), + request_path_callback_(std::move(request_path_callback)) { icon_set_.SetIcon(IconSet::IconSize::SIZE_16x16, GURL("chrome://theme/IDR_SMB_ICON")); icon_set_.SetIcon(IconSet::IconSize::SIZE_32x32,
diff --git a/chrome/browser/chromeos/smb_client/smb_provider.h b/chrome/browser/chromeos/smb_client/smb_provider.h index 944c77545..b747db2 100644 --- a/chrome/browser/chromeos/smb_client/smb_provider.h +++ b/chrome/browser/chromeos/smb_client/smb_provider.h
@@ -31,8 +31,10 @@ using UnmountCallback = base::RepeatingCallback<base::File::Error( const std::string&, file_system_provider::Service::UnmountReason)>; - SmbProvider(UnmountCallback unmount_callback, - SmbFileSystem::RequestCredentialsCallback request_creds_callback); + SmbProvider( + UnmountCallback unmount_callback, + SmbFileSystem::RequestCredentialsCallback request_creds_callback, + SmbFileSystem::RequestUpdatedSharePathCallback request_path_callback); ~SmbProvider() override; // ProviderInterface overrides. std::unique_ptr<ProvidedFileSystemInterface> CreateProvidedFileSystem( @@ -52,6 +54,7 @@ UnmountCallback unmount_callback_; SmbFileSystem::RequestCredentialsCallback request_creds_callback_; + SmbFileSystem::RequestUpdatedSharePathCallback request_path_callback_; DISALLOW_COPY_AND_ASSIGN(SmbProvider); };
diff --git a/chrome/browser/chromeos/smb_client/smb_service.cc b/chrome/browser/chromeos/smb_client/smb_service.cc index ac6a1bc..5aef176 100644 --- a/chrome/browser/chromeos/smb_client/smb_service.cc +++ b/chrome/browser/chromeos/smb_client/smb_service.cc
@@ -488,6 +488,8 @@ GetProviderService()->RegisterProvider(std::make_unique<SmbProvider>( base::BindRepeating(&SmbService::Unmount, base::Unretained(this)), base::BindRepeating(&SmbService::RequestCredentials, + base::Unretained(this)), + base::BindRepeating(&SmbService::RequestUpdatedSharePath, base::Unretained(this)))); RestoreMounts(); } @@ -582,6 +584,13 @@ return GetPreconfiguredSharePaths(kModePreMountValue); } +void SmbService::RequestUpdatedSharePath( + const std::string& share_path, + int32_t mount_id, + StartReadDirIfSuccessfulCallback reply) { + NOTREACHED(); +} + void SmbService::RecordMountCount() const { const std::vector<ProvidedFileSystemInfo> file_systems = GetProviderService()->GetProvidedFileSystemInfoList(provider_id_);
diff --git a/chrome/browser/chromeos/smb_client/smb_service.h b/chrome/browser/chromeos/smb_client/smb_service.h index e5e6e60..3c956ef 100644 --- a/chrome/browser/chromeos/smb_client/smb_service.h +++ b/chrome/browser/chromeos/smb_client/smb_service.h
@@ -10,6 +10,7 @@ #include <string> #include <vector> +#include "base/callback.h" #include "base/files/file.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" @@ -18,6 +19,7 @@ #include "chrome/browser/chromeos/file_system_provider/service.h" #include "chrome/browser/chromeos/smb_client/smb_errors.h" #include "chrome/browser/chromeos/smb_client/smb_share_finder.h" +#include "chrome/browser/chromeos/smb_client/smb_task_queue.h" #include "chrome/browser/chromeos/smb_client/temp_file_manager.h" #include "chrome/browser/profiles/profile.h" #include "chromeos/dbus/smb_provider_client.h" @@ -46,6 +48,8 @@ public base::SupportsWeakPtr<SmbService> { public: using MountResponse = base::OnceCallback<void(SmbMountResult result)>; + using StartReadDirIfSuccessfulCallback = + base::OnceCallback<void(bool should_retry_start_read_dir)>; explicit SmbService(Profile* profile); ~SmbService() override; @@ -207,6 +211,13 @@ void OnUpdateCredentialsResponse(int32_t mount_id, smbprovider::ErrorType error); + // Requests an updated share path via running + // ShareFinder::DiscoverHostsInNetwork. |reply| is stored. Once the share path + // has been successfully updated, |reply| is run. + void RequestUpdatedSharePath(const std::string& share_path, + int32_t mount_id, + StartReadDirIfSuccessfulCallback reply); + // Records metrics on the number of SMB mounts a user has. void RecordMountCount() const;
diff --git a/chrome/browser/download/download_browsertest.cc b/chrome/browser/download/download_browsertest.cc index a820398..5bff3e2 100644 --- a/chrome/browser/download/download_browsertest.cc +++ b/chrome/browser/download/download_browsertest.cc
@@ -3563,6 +3563,67 @@ .WaitForEvent(); } +// Checks that the navigation resulting from a cross origin download navigates +// the correct iframe. +IN_PROC_BROWSER_TEST_F(DownloadTest, CrossOriginDownloadNavigatesIframe) { + EmbeddedTestServer origin_one; + EmbeddedTestServer origin_two; + EmbeddedTestServer origin_three; + + origin_one.ServeFilesFromDirectory(GetTestDataDirectory()); + origin_two.ServeFilesFromDirectory(GetTestDataDirectory()); + origin_three.ServeFilesFromDirectory(GetTestDataDirectory()); + ASSERT_TRUE(origin_one.InitializeAndListen()); + ASSERT_TRUE(origin_two.InitializeAndListen()); + ASSERT_TRUE(origin_three.InitializeAndListen()); + + // We load a page on origin_one which iframes a page from origin_two which + // downloads a file that redirects to origin_three. + GURL download_url = + origin_two.GetURL(std::string("/redirect?") + + origin_three.GetURL("/downloads/message.html").spec()); + GURL referrer_url = origin_two.GetURL( + std::string("/downloads/download-attribute.html?target=") + + download_url.spec()); + GURL main_url = + origin_one.GetURL(std::string("/downloads/page-with-frame.html?url=") + + referrer_url.spec()); + + origin_two.RegisterRequestHandler( + base::BindRepeating(&ServerRedirectRequestHandler)); + + origin_one.StartAcceptingConnections(); + origin_two.StartAcceptingConnections(); + origin_three.StartAcceptingConnections(); + + ui_test_utils::NavigateToURL(browser(), main_url); + + WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(web_contents != NULL); + content::RenderFrameHost* render_frame_host = web_contents->GetMainFrame(); + ASSERT_TRUE(render_frame_host != NULL); + + // Clicking the <a download> in the iframe should navigate the iframe, + // not the main frame. + base::string16 expected_title(base::UTF8ToUTF16("Loaded as iframe")); + base::string16 failed_title(base::UTF8ToUTF16("Loaded as main frame")); + content::TitleWatcher title_watcher(web_contents, expected_title); + title_watcher.AlsoWaitForTitle(failed_title); + render_frame_host->ExecuteJavaScriptForTests( + base::ASCIIToUTF16("runTest();")); + ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle()); + + // Also verify that there's no download. + std::vector<DownloadItem*> downloads; + DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads); + ASSERT_EQ(0u, downloads.size()); + + ASSERT_TRUE(origin_one.ShutdownAndWaitUntilComplete()); + ASSERT_TRUE(origin_two.ShutdownAndWaitUntilComplete()); + ASSERT_TRUE(origin_three.ShutdownAndWaitUntilComplete()); +} + #if defined(FULL_SAFE_BROWSING) namespace {
diff --git a/chrome/browser/extensions/api/declarative_net_request/rule_indexing_unittest.cc b/chrome/browser/extensions/api/declarative_net_request/rule_indexing_unittest.cc index bb209fc..ae9133b 100644 --- a/chrome/browser/extensions/api/declarative_net_request/rule_indexing_unittest.cc +++ b/chrome/browser/extensions/api/declarative_net_request/rule_indexing_unittest.cc
@@ -8,6 +8,7 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" +#include "base/json/json_reader.h" #include "base/memory/ref_counted.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" @@ -312,26 +313,30 @@ extension()->install_warnings(); ASSERT_EQ(1u + kMaxUnparsedRulesWarnings, expected_warnings.size()); - InstallWarning warning(ErrorUtils::FormatErrorMessage( - kTooManyParseFailuresWarning, - std::to_string(kMaxUnparsedRulesWarnings))); + InstallWarning warning(""); warning.key = manifest_keys::kDeclarativeNetRequestKey; warning.specific = manifest_keys::kDeclarativeRuleResourcesKey; - EXPECT_EQ(warning, expected_warnings[0]); - // The subsequent warnings should correspond to the first + // The initial warnings should correspond to the first // |kMaxUnparsedRulesWarnings| rules, which couldn't be parsed. for (size_t i = 0; i < kMaxUnparsedRulesWarnings; i++) { - warning.message = ErrorUtils::FormatErrorMessage(kRuleNotParsedWarning, - std::to_string(i)); - EXPECT_EQ(expected_warnings[i + 1], warning); + warning.message = ErrorUtils::FormatErrorMessage( + kRuleNotParsedWarning, std::to_string(i), + "'RuleActionType': expected \"block\" or \"redirect\" or \"allow\", " + "got \"invalid_action_type\""); + EXPECT_EQ(expected_warnings[i], warning); } + + warning.message = ErrorUtils::FormatErrorMessage( + kTooManyParseFailuresWarning, + std::to_string(kMaxUnparsedRulesWarnings)); + EXPECT_EQ(warning, expected_warnings[kMaxUnparsedRulesWarnings]); } } // Ensures that rules which can't be parsed are ignored and cause an install // warning. -TEST_P(RuleIndexingTest, InvalidJSONRule) { +TEST_P(RuleIndexingTest, InvalidJSONRules_StrongTypes) { { TestRule rule = CreateGenericRule(); rule.id = 1; @@ -368,11 +373,76 @@ std::vector<InstallWarning> expected_warnings; expected_warnings.emplace_back( - ErrorUtils::FormatErrorMessage(kRuleNotParsedWarning, "1"), + ErrorUtils::FormatErrorMessage( + kRuleNotParsedWarning, "1", + "'RuleActionType': expected \"block\" or \"redirect\" or \"allow\"," + " got \"invalid action\""), manifest_keys::kDeclarativeNetRequestKey, manifest_keys::kDeclarativeRuleResourcesKey); expected_warnings.emplace_back( - ErrorUtils::FormatErrorMessage(kRuleNotParsedWarning, "3"), + ErrorUtils::FormatErrorMessage( + kRuleNotParsedWarning, "3", + "'DomainType': expected \"firstParty\" or \"thirdParty\", got " + "\"invalid_domain_type\""), + manifest_keys::kDeclarativeNetRequestKey, + manifest_keys::kDeclarativeRuleResourcesKey); + EXPECT_EQ(expected_warnings, extension()->install_warnings()); + } +} + +// Ensures that rules which can't be parsed are ignored and cause an install +// warning. +TEST_P(RuleIndexingTest, InvalidJSONRules_Parsed) { + const char* kRules = R"( + [ + { + "id" : 1, + "condition" : [], + "action" : {"type" : "block" } + }, + { + "id" : 2, + "condition" : {"urlFilter" : "abc"}, + "action" : {"type" : "block" } + }, + { + "id" : 3, + "invalidKey" : "invalidKeyValue", + "condition" : {"urlFilter" : "example"}, + "action" : {"type" : "block" } + }, + { + "id" : "4", + "condition" : {"urlFilter" : "google"}, + "action" : {"type" : "block" } + } + ] + )"; + SetRules(base::JSONReader::Read(kRules)); + + extension_loader()->set_ignore_manifest_warnings(true); + LoadAndExpectSuccess(1 /* rules count */); + + // TODO(crbug.com/879355): CrxInstaller reloads the extension after moving it, + // which causes it to lose the install warning. This should be fixed. + if (GetParam() != ExtensionLoadType::PACKED) { + ASSERT_EQ(3u, extension()->install_warnings().size()); + std::vector<InstallWarning> expected_warnings; + + expected_warnings.emplace_back( + ErrorUtils::FormatErrorMessage( + kRuleNotParsedWarning, "0", + "'condition': expected dictionary, got list"), + manifest_keys::kDeclarativeNetRequestKey, + manifest_keys::kDeclarativeRuleResourcesKey); + expected_warnings.emplace_back( + ErrorUtils::FormatErrorMessage(kRuleNotParsedWarning, "2", + "found unexpected key 'invalidKey'"), + manifest_keys::kDeclarativeNetRequestKey, + manifest_keys::kDeclarativeRuleResourcesKey); + expected_warnings.emplace_back( + ErrorUtils::FormatErrorMessage(kRuleNotParsedWarning, "3", + "'id': expected id, got string"), manifest_keys::kDeclarativeNetRequestKey, manifest_keys::kDeclarativeRuleResourcesKey); EXPECT_EQ(expected_warnings, extension()->install_warnings());
diff --git a/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc b/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc index d585d359..6145a859 100644 --- a/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc +++ b/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc
@@ -4,16 +4,18 @@ #include "chrome/browser/extensions/api/identity/identity_get_accounts_function.h" -#include "base/bind.h" +#include <memory> +#include <utility> +#include <vector> + #include "chrome/browser/extensions/api/identity/identity_api.h" #include "chrome/browser/extensions/api/identity/identity_constants.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/common/extensions/api/identity.h" +#include "components/signin/core/browser/account_info.h" #include "content/public/browser/browser_context.h" -#include "content/public/common/service_manager_connection.h" -#include "services/identity/public/mojom/account.mojom.h" -#include "services/identity/public/mojom/constants.mojom.h" -#include "services/service_manager/public/cpp/connector.h" +#include "services/identity/public/cpp/identity_manager.h" namespace extensions { @@ -28,23 +30,14 @@ return RespondNow(Error(identity_constants::kOffTheRecord)); } - content::BrowserContext::GetConnectorFor(browser_context()) - ->BindInterface(identity::mojom::kServiceName, - mojo::MakeRequest(&identity_manager_)); - - identity_manager_->GetAccounts( - base::BindOnce(&IdentityGetAccountsFunction::OnGotAccounts, this)); - - return RespondLater(); -} - -void IdentityGetAccountsFunction::OnGotAccounts( - std::vector<identity::mojom::AccountPtr> accounts) { + std::vector<AccountInfo> accounts = + IdentityManagerFactory::GetForProfile( + Profile::FromBrowserContext(browser_context())) + ->GetAccountsWithRefreshTokens(); std::unique_ptr<base::ListValue> infos(new base::ListValue()); if (accounts.empty()) { - Respond(OneArgument(std::move(infos))); - return; + return RespondNow(OneArgument(std::move(infos))); } Profile* profile = Profile::FromBrowserContext(browser_context()); @@ -52,26 +45,23 @@ ->Get(profile) ->AreExtensionsRestrictedToPrimaryAccount(); - // If extensions are restricted to the primary account and there is no valid - // primary account, short-circuit out. - if (primary_account_only && (!accounts[0]->state.is_primary_account || - !accounts[0]->state.has_refresh_token)) { - Respond(OneArgument(std::move(infos))); - return; + auto* identity_manager = IdentityManagerFactory::GetForProfile(profile); + api::identity::AccountInfo account_info; + if (primary_account_only) { + // If extensions are restricted to the primary account, only return the + // account info when there is a valid primary account. + if (identity_manager->HasPrimaryAccountWithRefreshToken()) { + account_info.id = identity_manager->GetPrimaryAccountInfo().gaia; + infos->Append(account_info.ToValue()); + } + } else { + for (const auto& account : accounts) { + account_info.id = account.gaia; + infos->Append(account_info.ToValue()); + } } - for (const auto& account : accounts) { - api::identity::AccountInfo account_info; - account_info.id = account->info.gaia; - infos->Append(account_info.ToValue()); - - // Stop after the primary account if extensions are restricted to the - // primary account. - if (primary_account_only) - break; - } - - Respond(OneArgument(std::move(infos))); + return RespondNow(OneArgument(std::move(infos))); } } // namespace extensions
diff --git a/chrome/browser/extensions/api/identity/identity_get_accounts_function.h b/chrome/browser/extensions/api/identity/identity_get_accounts_function.h index 9f9aab7b..db096c9 100644 --- a/chrome/browser/extensions/api/identity/identity_get_accounts_function.h +++ b/chrome/browser/extensions/api/identity/identity_get_accounts_function.h
@@ -7,7 +7,6 @@ #include "extensions/browser/extension_function.h" #include "extensions/browser/extension_function_histogram_value.h" -#include "services/identity/public/mojom/identity_manager.mojom.h" namespace extensions { @@ -21,13 +20,8 @@ private: ~IdentityGetAccountsFunction() override; - // Invoked in response to IdentityManager::GetAccounts(). - void OnGotAccounts(std::vector<identity::mojom::AccountPtr> accounts); - // UIThreadExtensionFunction implementation. ExtensionFunction::ResponseAction Run() override; - - identity::mojom::IdentityManagerPtr identity_manager_; }; } // namespace extensions
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index ca74b55..dbe5a24 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -1433,6 +1433,11 @@ "expiry_milestone": 76 }, { + "name": "enable-lite-mode-rebrand", + "owners": [ "robertogden@chromium.org" ], + "expiry_milestone": 75 + }, + { "name": "enable-lite-page-server-previews", // "owners": [ "your-team" ], "expiry_milestone": 76 @@ -1969,6 +1974,11 @@ "expiry_milestone": 76 }, { + "name": "enable-sync-uss-passwords", + "owners": [ "mamir", "//components/sync/OWNERS" ], + "expiry_milestone": 77 + }, + { "name": "enable-sync-uss-sessions", "owners": [ "mastiz", "//components/sync/OWNERS" ], "expiry_milestone": 76
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index bb495f09..f022200 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -509,6 +509,11 @@ const char kEnableChromevoxDeveloperOptionDescription[] = "This option provides tools for developing in chromevox."; +const char kEnableDataSaverLiteModeRebrandName[] = + "Data Saver Lite Mode Rebranding"; +const char kEnableDataSaverLiteModeRebrandDescription[] = + "Enable the Data Saver rebranding to Lite Mode."; + const char kEnableClientLoFiName[] = "Client-side Lo-Fi previews"; const char kEnableClientLoFiDescription[] = @@ -917,6 +922,10 @@ const char kEnableSyncUSSBookmarksDescription[] = "Enables the new, experimental implementation of bookmark sync"; +const char kEnableSyncUSSPasswordsName[] = "Enable USS for passwords sync"; +const char kEnableSyncUSSPasswordsDescription[] = + "Enables the new, experimental implementation of passwords sync"; + const char kEnableSyncUSSSessionsName[] = "Enable USS for sessions sync"; const char kEnableSyncUSSSessionsDescription[] = "Enables the new, experimental implementation of session sync (aka tab " @@ -2833,12 +2842,6 @@ const char kHappinessTrackingSurveysForDesktopDescription[] = "Enable showing Happiness Tracking Surveys to users on Desktop"; -const char kInfiniteSessionRestoreName[] = "Infinite Session Restore"; -const char kInfiniteSessionRestoreDescription[] = - "Reduces the number of tabs being loaded simultaneously during session " - "restore, to improve responsiveness of the foreground tab. This requires " - "#enable-page-almost-idle."; - const char kOmniboxDriveSuggestionsName[] = "Omnibox Google Drive Document suggestions"; const char kOmniboxDriveSuggestionsDescriptions[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index baaac56..2de65a6 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -340,6 +340,9 @@ extern const char kEnableChromevoxDeveloperOptionName[]; extern const char kEnableChromevoxDeveloperOptionDescription[]; +extern const char kEnableDataSaverLiteModeRebrandName[]; +extern const char kEnableDataSaverLiteModeRebrandDescription[]; + extern const char kEnableClientLoFiName[]; extern const char kEnableClientLoFiDescription[]; @@ -549,6 +552,9 @@ extern const char kEnableSyncUSSBookmarksName[]; extern const char kEnableSyncUSSBookmarksDescription[]; +extern const char kEnableSyncUSSPasswordsName[]; +extern const char kEnableSyncUSSPasswordsDescription[]; + extern const char kEnableSyncUSSSessionsName[]; extern const char kEnableSyncUSSSessionsDescription[]; @@ -1678,9 +1684,6 @@ extern const char kHappinessTrackingSurveysForDesktopName[]; extern const char kHappinessTrackingSurveysForDesktopDescription[]; -extern const char kInfiniteSessionRestoreName[]; -extern const char kInfiniteSessionRestoreDescription[]; - extern const char kOmniboxDriveSuggestionsName[]; extern const char kOmniboxDriveSuggestionsDescriptions[];
diff --git a/chrome/browser/media/webrtc/webrtc_getdisplaymedia_browsertest.cc b/chrome/browser/media/webrtc/webrtc_getdisplaymedia_browsertest.cc index 5a13b4e..3b41f1f 100644 --- a/chrome/browser/media/webrtc/webrtc_getdisplaymedia_browsertest.cc +++ b/chrome/browser/media/webrtc/webrtc_getdisplaymedia_browsertest.cc
@@ -5,6 +5,7 @@ #include <string> #include "base/strings/stringprintf.h" +#include "build/build_config.h" #include "chrome/browser/media/webrtc/webrtc_browsertest_base.h" #include "chrome/common/chrome_switches.h" #include "content/public/browser/web_contents.h" @@ -20,6 +21,7 @@ const char* display_surface; const char* logical_surface; const char* cursor; + bool expect_audio; }; } // namespace @@ -60,7 +62,7 @@ #define MAYBE_GetDisplayMediaVideo DISABLED_GetDisplayMediaVideo #else #define MAYBE_GetDisplayMediaVideo GetDisplayMediaVideo -#endif +#endif // defined(OS_CHROMEOS) || defined(OS_WIN) IN_PROC_BROWSER_TEST_F(WebRtcGetDisplayMediaBrowserTestWithPicker, MAYBE_GetDisplayMediaVideo) { ASSERT_TRUE(embedded_test_server()->Start()); @@ -70,6 +72,21 @@ RunGetDisplayMedia(tab, constraints); } +// Real desktop capture is flaky on below platforms. +#if defined(OS_CHROMEOS) || defined(OS_WIN) +#define MAYBE_GetDisplayMediaVideoAndAudio DISABLED_GetDisplayMediaVideoAndAudio +#else +#define MAYBE_GetDisplayMediaVideoAndAudio GetDisplayMediaVideoAndAudio +#endif // defined(OS_CHROMEOS) || defined(OS_WIN) +IN_PROC_BROWSER_TEST_F(WebRtcGetDisplayMediaBrowserTestWithPicker, + MAYBE_GetDisplayMediaVideoAndAudio) { + ASSERT_TRUE(embedded_test_server()->Start()); + + content::WebContents* tab = OpenTestPageInNewTab(kMainHtmlPage); + std::string constraints("{video:true, audio:true}"); + RunGetDisplayMedia(tab, constraints); +} + // Top level test for getDisplayMedia(). Skips picker UI and uses fake device // with specified type. class WebRtcGetDisplayMediaBrowserTestWithFakeUI @@ -88,6 +105,8 @@ switches::kUseFakeDeviceForMediaStream, base::StringPrintf("display-media-type=%s", test_config_.display_surface)); + if (!test_config_.expect_audio) + command_line->AppendSwitch(switches::kDisableAudioSupportForDesktopShare); } protected: @@ -95,7 +114,7 @@ }; IN_PROC_BROWSER_TEST_P(WebRtcGetDisplayMediaBrowserTestWithFakeUI, - GetDisplayMedia) { + GetDisplayMediaVideo) { ASSERT_TRUE(embedded_test_server()->Start()); content::WebContents* tab = OpenTestPageInNewTab(kMainHtmlPage); @@ -117,6 +136,20 @@ } IN_PROC_BROWSER_TEST_P(WebRtcGetDisplayMediaBrowserTestWithFakeUI, + GetDisplayMediaVideoAndAudio) { + ASSERT_TRUE(embedded_test_server()->Start()); + + content::WebContents* tab = OpenTestPageInNewTab(kMainHtmlPage); + std::string constraints("{video:true, audio:true}"); + RunGetDisplayMedia(tab, constraints); + + std::string result; + EXPECT_TRUE(content::ExecuteScriptAndExtractString( + tab->GetMainFrame(), "hasAudioTrack();", &result)); + EXPECT_EQ(result, test_config_.expect_audio ? "true" : "false"); +} + +IN_PROC_BROWSER_TEST_P(WebRtcGetDisplayMediaBrowserTestWithFakeUI, GetDisplayMediaWithConstraints) { ASSERT_TRUE(embedded_test_server()->Start()); @@ -138,9 +171,10 @@ EXPECT_EQ(result, base::StringPrintf("%d", kMaxFrameRate)); } -INSTANTIATE_TEST_CASE_P(, - WebRtcGetDisplayMediaBrowserTestWithFakeUI, - testing::Values(TestConfig{"monitor", "true", "never"}, - TestConfig{"window", "true", "never"}, - TestConfig{"browser", "true", - "never"})); +INSTANTIATE_TEST_CASE_P( + , + WebRtcGetDisplayMediaBrowserTestWithFakeUI, + testing::Values(TestConfig{"monitor", "true", "never", false}, + TestConfig{"window", "true", "never", false}, + TestConfig{"browser", "true", "never", false}, + TestConfig{"browser", "true", "never", true}));
diff --git a/chrome/browser/metrics/chrome_metrics_service_client.cc b/chrome/browser/metrics/chrome_metrics_service_client.cc index 4b3a5a7..a728cff 100644 --- a/chrome/browser/metrics/chrome_metrics_service_client.cc +++ b/chrome/browser/metrics/chrome_metrics_service_client.cc
@@ -747,13 +747,13 @@ metrics::MetricsLogUploader::UKM)); #endif // !defined(OS_CHROMEOS) - ukm_service_->RegisterMetricsProvider( + metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::GPUMetricsProvider>()); - ukm_service_->RegisterMetricsProvider( + metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::CPUMetricsProvider>()); - ukm_service_->RegisterMetricsProvider( + metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::ScreenInfoMetricsProvider>()); // TODO(rkaplow): Support synthetic trials for UKM.
diff --git a/chrome/browser/metrics/chrome_metrics_service_client_unittest.cc b/chrome/browser/metrics/chrome_metrics_service_client_unittest.cc index f5b6752..fee2129c 100644 --- a/chrome/browser/metrics/chrome_metrics_service_client_unittest.cc +++ b/chrome/browser/metrics/chrome_metrics_service_client_unittest.cc
@@ -7,19 +7,10 @@ #include "base/files/file_path.h" #include "base/metrics/persistent_histogram_allocator.h" #include "base/process/process_handle.h" -#include "base/test/metrics/user_action_tester.h" #include "base/test/scoped_task_environment.h" -#include "build/build_config.h" -#include "chrome/common/buildflags.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile_manager.h" -#include "components/metrics/client_info.h" #include "components/metrics/file_metrics_provider.h" -#include "components/metrics/metrics_service.h" -#include "components/metrics/metrics_state_manager.h" -#include "components/metrics/test_enabled_state_provider.h" -#include "components/prefs/testing_pref_service.h" -#include "components/ukm/ukm_service.h" #include "content/public/test/test_browser_thread_bundle.h" #include "extensions/buildflags/buildflags.h" #include "testing/gtest/include/gtest/gtest.h" @@ -30,53 +21,6 @@ #include "extensions/common/extension_builder.h" #endif -#if defined(OS_CHROMEOS) -#include "chromeos/assistant/buildflags.h" -#include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/login/login_state/login_state.h" -#endif - -class ChromeMetricsServiceClientTest : public testing::Test { - public: - ChromeMetricsServiceClientTest() - : profile_manager_(TestingBrowserProcess::GetGlobal()), - enabled_state_provider_(false /* consent */, false /* enabled */) { - metrics::MetricsService::RegisterPrefs(prefs_.registry()); - metrics_state_manager_ = metrics::MetricsStateManager::Create( - &prefs_, &enabled_state_provider_, base::string16(), - base::BindRepeating( - &ChromeMetricsServiceClientTest::FakeStoreClientInfoBackup, - base::Unretained(this)), - base::BindRepeating( - &ChromeMetricsServiceClientTest::LoadFakeClientInfoBackup, - base::Unretained(this))); - DCHECK(profile_manager_.SetUp()); -#if defined(OS_CHROMEOS) - // ChromeOs Metrics Provider require g_login_state and dbus initialized - // before they can be instantiated. - chromeos::LoginState::Initialize(); - chromeos::DBusThreadManager::Initialize(); -#endif // defined(OS_CHROMEOS) - } - - protected: - void FakeStoreClientInfoBackup(const metrics::ClientInfo& client_info) {} - - std::unique_ptr<metrics::ClientInfo> LoadFakeClientInfoBackup() { - return std::make_unique<metrics::ClientInfo>(); - } - - content::TestBrowserThreadBundle thread_bundle_; - TestingPrefServiceSimple prefs_; - TestingProfileManager profile_manager_; - base::UserActionTester user_action_runner_; - std::unique_ptr<metrics::MetricsStateManager> metrics_state_manager_; - metrics::TestEnabledStateProvider enabled_state_provider_; - - private: - DISALLOW_COPY_AND_ASSIGN(ChromeMetricsServiceClientTest); -}; - namespace { bool TestIsProcessRunning(base::ProcessId pid) { @@ -84,7 +28,7 @@ return (pid & 1) == 1; } -TEST_F(ChromeMetricsServiceClientTest, FilterFiles) { +TEST(ChromeMetricsServiceClientTest, FilterFiles) { ChromeMetricsServiceClient::SetIsProcessRunningForTesting( &TestIsProcessRunning); @@ -111,98 +55,21 @@ } // namespace -TEST_F(ChromeMetricsServiceClientTest, TestRegisterUKMProviders) { - // Test that UKM service has initialized its metrics providers. - // Currently there are 5 providers for all platform except ChromeOS. - // NetworkMetricsProvider, GPUMetricsProvider, CPUMetricsProvider - // and ScreenInfoMetricsProvider. - size_t expected_providers = 5; - -#if defined(OS_CHROMEOS) - expected_providers++; // ChromeOSMetricsProvider -#endif // defined(OS_CHROMEOS) - - std::unique_ptr<ChromeMetricsServiceClient> chrome_metrics_service_client = - ChromeMetricsServiceClient::Create(metrics_state_manager_.get()); - size_t observed_count = chrome_metrics_service_client->GetUkmService() - ->metrics_providers_.GetProviders() - .size(); - if (base::FeatureList::IsEnabled(ukm::kUkmFeature)) { - EXPECT_EQ(expected_providers, observed_count); - } else { - EXPECT_EQ(0ul, observed_count); - } -} - -TEST_F(ChromeMetricsServiceClientTest, TestRegisterMetricsServiceProviders) { - // This is the metrics provider added in MetricsService constructor. - // StabilityMetricsProvider, FieldTrialsProvider and - // MetricsStateMetricsProvider. - size_t expected_providers = 3; - - // This is the number of metrics providers that are outside any #if macros. - expected_providers += 16; - -#if BUILDFLAG(ENABLE_EXTENSIONS) - expected_providers++; // ExtensionsMetricsProvider. -#endif // defined(ENABLE_EXTENSIONS) - -#if defined(OS_ANDROID) - // AndroidMetricsProvider and PageLoadMetricsProvider. - expected_providers += 2; -#endif // defined(OS_ANDROID) - -#if defined(OS_WIN) - // GoogleUpdateMetricsProviderWin, WatcherMetricsProviderWin and - // AntiVirusMetricsProvider. - expected_providers += 3; -#endif // defined(OS_WIN) - -#if BUILDFLAG(ENABLE_PLUGINS) - // PluginMetricsProvider. - expected_providers++; -#endif // BUILDFLAG(ENABLE_PLUGINS) - -#if defined(OS_CHROMEOS) -#if BUILDFLAG(ENABLE_CROS_ASSISTANT) - expected_providers++; // AssistantServiceMetricsProvider. -#endif // BUILDFLAG(ENABLE_CROS_ASSISTANT) - // ChromeOSMetricsProvider, SigninStatusMetricsProviderChromeOS and - // PrinterMetricsProvider. - expected_providers += 3; -#endif // defined(OS_CHROMEOS) - -#if !defined(OS_CHROMEOS) - // ChromeSigninStatusMetricsProvider (for non ChromeOS). - expected_providers++; -#endif // !defined(OS_CHROMEOS) - -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) - expected_providers++; // UpgradeMetricsProvider -#endif //! defined(OS_ANDROID) && !defined(OS_CHROMEOS) - -#if defined(OS_MACOSX) - expected_providers++; // PowerMetricsProvider -#endif // defined(OS_MACOSX) - - std::unique_ptr<ChromeMetricsServiceClient> chrome_metrics_service_client = - ChromeMetricsServiceClient::Create(metrics_state_manager_.get()); - EXPECT_EQ(expected_providers, - chrome_metrics_service_client->GetMetricsService() - ->delegating_provider_.GetProviders() - .size()); -} - // This can't be a MAYBE test because it won't compile without the extensions // header files but those can't even be included if this build flag is not // set. This can't be in the anonymous namespace because it is a "friend" of // the ChromeMetricsServiceClient class. #if BUILDFLAG(ENABLE_EXTENSIONS) -TEST_F(ChromeMetricsServiceClientTest, IsWebstoreExtension) { +TEST(ChromeMetricsServiceClientTest, IsWebstoreExtension) { static const char test_extension_id1[] = "abcdefghijklmnopqrstuvwxyzabcdef"; static const char test_extension_id2[] = "bhcnanendmgjjeghamaccjnochlnhcgj"; - TestingProfile* test_profile = profile_manager_.CreateTestingProfile("p1"); + content::TestBrowserThreadBundle thread_bundle; + TestingProfileManager testing_profile_manager( + TestingBrowserProcess::GetGlobal()); + ASSERT_TRUE(testing_profile_manager.SetUp()); + TestingProfile* test_profile = + testing_profile_manager.CreateTestingProfile("p1"); extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(test_profile); ASSERT_TRUE(registry);
diff --git a/chrome/browser/metrics/process_memory_metrics_emitter.cc b/chrome/browser/metrics/process_memory_metrics_emitter.cc index fe14146..6457faf2 100644 --- a/chrome/browser/metrics/process_memory_metrics_emitter.cc +++ b/chrome/browser/metrics/process_memory_metrics_emitter.cc
@@ -12,18 +12,16 @@ #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/metrics/tab_footprint_aggregator.h" +#include "chrome/browser/performance_manager/performance_manager.h" #include "chrome/browser/profiles/profile_manager.h" #include "content/public/browser/audio_service_info.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/content_switches.h" -#include "content/public/common/service_manager_connection.h" #include "content/public/common/service_names.mojom.h" #include "extensions/buildflags/buildflags.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_recorder.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" -#include "services/resource_coordinator/public/mojom/service_constants.mojom.h" -#include "services/service_manager/public/cpp/connector.h" #include "url/gurl.h" #if BUILDFLAG(ENABLE_EXTENSIONS) @@ -462,10 +460,9 @@ } // The callback keeps this object alive until the callback is invoked. - service_manager::Connector* connector = - content::ServiceManagerConnection::GetForProcess()->GetConnector(); - connector->BindInterface(resource_coordinator::mojom::kServiceName, - mojo::MakeRequest(&introspector_)); + performance_manager::PerformanceManager* performance_manager = + performance_manager::PerformanceManager::GetInstance(); + performance_manager->BindInterface(mojo::MakeRequest(&introspector_)); auto callback2 = base::Bind(&ProcessMemoryMetricsEmitter::ReceivedProcessInfos, this); introspector_->GetProcessToURLMap(callback2);
diff --git a/chrome/browser/net/errorpage_browsertest.cc b/chrome/browser/net/errorpage_browsertest.cc index ed2b3bc..9467f98 100644 --- a/chrome/browser/net/errorpage_browsertest.cc +++ b/chrome/browser/net/errorpage_browsertest.cc
@@ -199,6 +199,17 @@ return l10n_util::GetStringUTF8(IDS_ERRORPAGES_BUTTON_SHOW_SAVED_COPY); } +// Returns true if the platform has support for a diagnostics tool, and it +// can be launched from |web_contents|. +bool WebContentsCanShowDiagnosticsTool(content::WebContents* web_contents) { +#if defined(OS_CHROMEOS) + // ChromeOS uses an extension instead of a diagnostics dialog. + return true; +#else + return CanShowNetworkDiagnosticsDialog(web_contents); +#endif +} + class ErrorPageTest : public InProcessBrowserTest { public: enum HistoryNavigationDirection { @@ -1004,6 +1015,34 @@ EXPECT_EQ(1, result); } +// Test error page in incognito mode. The two major things are that navigation +// corrections are not fetched (Only one navigation, display local error page), +// and that no network diagnostic link is included, except on ChromeOS. +IN_PROC_BROWSER_TEST_F(DNSErrorPageTest, Incognito) { + Browser* incognito_browser = CreateIncognitoBrowser(); + + ui_test_utils::NavigateToURLBlockUntilNavigationsComplete( + incognito_browser, + URLRequestFailedJob::GetMockHttpUrl(net::ERR_NAME_NOT_RESOLVED), 1); + + // Verify that the expected error page is being displayed. + ExpectDisplayingLocalErrorPage( + embedded_test_server()->GetURL("mock.http", "/title2.html").spec(), + incognito_browser, net::ERR_NAME_NOT_RESOLVED); + +#if !defined(OS_CHROMEOS) + // Can't currently show the diagnostics in incognito on any platform but + // ChromeOS. + EXPECT_FALSE(WebContentsCanShowDiagnosticsTool( + incognito_browser->tab_strip_model()->GetActiveWebContents())); +#endif + + // Diagnostics button should be displayed, if available. + EXPECT_EQ(WebContentsCanShowDiagnosticsTool( + incognito_browser->tab_strip_model()->GetActiveWebContents()), + IsDisplayingDiagnosticsLink(incognito_browser)); +} + class ErrorPageAutoReloadTest : public InProcessBrowserTest { public: void SetUpCommandLine(base::CommandLine* command_line) override { @@ -1168,23 +1207,12 @@ void TearDownOnMainThread() override { url_loader_interceptor_.reset(); } - // Returns true if the platform has support for a diagnostics tool, which - // can be launched from the error page. - bool PlatformSupportsDiagnosticsTool() { -#if defined(OS_CHROMEOS) - // ChromeOS uses an extension instead of a diagnostics dialog. - return true; -#else - return CanShowNetworkDiagnosticsDialog(); -#endif - } - private: std::unique_ptr<content::URLLoaderInterceptor> url_loader_interceptor_; }; // Make sure that when corrections fail to load, the network error page is -// successfully loaded. +// successfully loaded and shows a link to the diagnostics too, if appropriate. IN_PROC_BROWSER_TEST_F(ErrorPageNavigationCorrectionsFailTest, FetchCorrectionsFails) { ASSERT_TRUE(embedded_test_server()->Start()); @@ -1198,8 +1226,9 @@ embedded_test_server()->GetURL("mock.http", "/title2.html").spec(), browser(), net::ERR_NAME_NOT_RESOLVED); - // Diagnostics button should be displayed, if available on this platform. - EXPECT_EQ(PlatformSupportsDiagnosticsTool(), + // Diagnostics button should be displayed, if available. + EXPECT_EQ(WebContentsCanShowDiagnosticsTool( + browser()->tab_strip_model()->GetActiveWebContents()), IsDisplayingDiagnosticsLink(browser())); }
diff --git a/chrome/browser/net/net_error_diagnostics_dialog.h b/chrome/browser/net/net_error_diagnostics_dialog.h index 2d3089a..6b2f88c 100644 --- a/chrome/browser/net/net_error_diagnostics_dialog.h +++ b/chrome/browser/net/net_error_diagnostics_dialog.h
@@ -11,9 +11,11 @@ class WebContents; } -// Returns true if the platform has a supported tool for diagnosing network -// errors encountered when requesting URLs. -bool CanShowNetworkDiagnosticsDialog(); +// Returns true if a tool for diagnosing network errors encountered when +// requesting URLs can be shown for the provided WebContents. The ability to +// show the diagnostic tool depends on the host platform, and whether the +// WebContents is incognito. +bool CanShowNetworkDiagnosticsDialog(content::WebContents* web_contents); // Shows a dialog for investigating an error received when requesting // |failed_url|. May only be called when CanShowNetworkDiagnosticsDialog()
diff --git a/chrome/browser/net/net_error_diagnostics_dialog_posix.cc b/chrome/browser/net/net_error_diagnostics_dialog_posix.cc index e2866f8..2c21794 100644 --- a/chrome/browser/net/net_error_diagnostics_dialog_posix.cc +++ b/chrome/browser/net/net_error_diagnostics_dialog_posix.cc
@@ -6,7 +6,7 @@ #include "base/logging.h" -bool CanShowNetworkDiagnosticsDialog() { +bool CanShowNetworkDiagnosticsDialog(content::WebContents* web_contents) { return false; }
diff --git a/chrome/browser/net/net_error_diagnostics_dialog_win.cc b/chrome/browser/net/net_error_diagnostics_dialog_win.cc index 4a3768f..ea046e11 100644 --- a/chrome/browser/net/net_error_diagnostics_dialog_win.cc +++ b/chrome/browser/net/net_error_diagnostics_dialog_win.cc
@@ -24,6 +24,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/task_runner.h" #include "base/threading/thread.h" +#include "chrome/browser/profiles/profile.h" #include "content/public/browser/web_contents.h" #include "ui/gfx/native_widget_types.h" #include "ui/shell_dialogs/base_shell_dialog_win.h" @@ -82,13 +83,17 @@ } // namespace -bool CanShowNetworkDiagnosticsDialog() { - return true; +bool CanShowNetworkDiagnosticsDialog(content::WebContents* web_contents) { + Profile* profile = + Profile::FromBrowserContext(web_contents->GetBrowserContext()); + // The Windows diagnostic tool logs URLs it's run with, so it shouldn't be + // used with incognito or guest profiles. See https://crbug.com/929141 + return !profile->IsOffTheRecord() && !profile->IsGuestSession(); } void ShowNetworkDiagnosticsDialog(content::WebContents* web_contents, const std::string& failed_url) { - DCHECK(CanShowNetworkDiagnosticsDialog()); + DCHECK(CanShowNetworkDiagnosticsDialog(web_contents)); NetErrorDiagnosticsDialog* dialog = new NetErrorDiagnosticsDialog(); dialog->Show(
diff --git a/chrome/browser/net/net_error_tab_helper.cc b/chrome/browser/net/net_error_tab_helper.cc index 8c74486..5a551c3 100644 --- a/chrome/browser/net/net_error_tab_helper.cc +++ b/chrome/browser/net/net_error_tab_helper.cc
@@ -89,7 +89,8 @@ chrome::mojom::NetworkDiagnosticsClientAssociatedPtr client; render_frame_host->GetRemoteAssociatedInterfaces()->GetInterface(&client); - client->SetCanShowNetworkDiagnosticsDialog(CanShowNetworkDiagnosticsDialog()); + client->SetCanShowNetworkDiagnosticsDialog( + CanShowNetworkDiagnosticsDialog(web_contents())); } void NetErrorTabHelper::DidStartNavigation( @@ -293,6 +294,11 @@ void NetErrorTabHelper::RunNetworkDiagnosticsHelper( const std::string& sanitized_url) { + // The button shouldn't even be shown in this case, but still best to be safe, + // since the renderer isn't trusted. + if (!CanShowNetworkDiagnosticsDialog(web_contents())) + return; + if (network_diagnostics_bindings_.GetCurrentTargetFrame() != web_contents()->GetMainFrame()) { return;
diff --git a/chrome/browser/net/network_context_configuration_browsertest.cc b/chrome/browser/net/network_context_configuration_browsertest.cc index da84369f..6e9ec11 100644 --- a/chrome/browser/net/network_context_configuration_browsertest.cc +++ b/chrome/browser/net/network_context_configuration_browsertest.cc
@@ -1886,76 +1886,56 @@ // tested, and a suffix of "/0" if the network service is disabled, "/1" if it's // enabled, and "/2" if it's enabled and restarted. +#if defined(OS_CHROMEOS) +// There's an extra network change event on ChromeOS, likely from +// NetworkChangeNotifierChromeos that makes these tests flaky on ChromeOS when +// there's an out of process network stack. +// +// TODO(https://crbug.com/927293): Fix that, and enable these tests on ChromeOS. +#define TEST_CASES(network_context_type) \ + TestCase({NetworkServiceState::kDisabled, network_context_type}) +#else // !defined(OS_CHROMEOS) +#define TEST_CASES(network_context_type) \ + TestCase({NetworkServiceState::kDisabled, network_context_type}), \ + TestCase({NetworkServiceState::kEnabled, network_context_type}), \ + TestCase({NetworkServiceState::kRestarted, network_context_type}) +#endif // !defined(OS_CHROMEOS) + #if BUILDFLAG(ENABLE_EXTENSIONS) -#define INSTANTIATE_EXTENSION_TESTS(TestFixture) \ - INSTANTIATE_TEST_SUITE_P( \ - OnDiskApp, TestFixture, \ - ::testing::Values(TestCase({NetworkServiceState::kDisabled, \ - NetworkContextType::kOnDiskApp}), \ - TestCase({NetworkServiceState::kEnabled, \ - NetworkContextType::kOnDiskApp}), \ - TestCase({NetworkServiceState::kRestarted, \ - NetworkContextType::kOnDiskApp}))); \ - \ - INSTANTIATE_TEST_SUITE_P( \ - InMemoryApp, TestFixture, \ - ::testing::Values(TestCase({NetworkServiceState::kDisabled, \ - NetworkContextType::kInMemoryApp}), \ - TestCase({NetworkServiceState::kEnabled, \ - NetworkContextType::kInMemoryApp}), \ - TestCase({NetworkServiceState::kRestarted, \ - NetworkContextType::kInMemoryApp}))); \ - \ - INSTANTIATE_TEST_SUITE_P( \ - OnDiskAppWithIncognitoProfile, TestFixture, \ - ::testing::Values( \ - TestCase({NetworkServiceState::kDisabled, \ - NetworkContextType::kOnDiskAppWithIncognitoProfile}), \ - TestCase({NetworkServiceState::kEnabled, \ - NetworkContextType::kOnDiskAppWithIncognitoProfile}), \ - TestCase({NetworkServiceState::kRestarted, \ - NetworkContextType::kOnDiskAppWithIncognitoProfile}))); +#define INSTANTIATE_EXTENSION_TESTS(TestFixture) \ + INSTANTIATE_TEST_SUITE_P( \ + OnDiskApp, TestFixture, \ + ::testing::Values(TEST_CASES(NetworkContextType::kOnDiskApp))); \ + \ + INSTANTIATE_TEST_SUITE_P( \ + InMemoryApp, TestFixture, \ + ::testing::Values(TEST_CASES(NetworkContextType::kInMemoryApp))); \ + \ + INSTANTIATE_TEST_SUITE_P( \ + OnDiskAppWithIncognitoProfile, TestFixture, \ + ::testing::Values( \ + TEST_CASES(NetworkContextType::kOnDiskAppWithIncognitoProfile))); #else // !BUILDFLAG(ENABLE_EXTENSIONS) #define INSTANTIATE_EXTENSION_TESTS(TestFixture) #endif // !BUILDFLAG(ENABLE_EXTENSIONS) -#define INSTANTIATE_TEST_CASES_FOR_TEST_FIXTURE(TestFixture) \ - INSTANTIATE_EXTENSION_TESTS(TestFixture) \ - INSTANTIATE_TEST_SUITE_P( \ - SystemNetworkContext, TestFixture, \ - ::testing::Values(TestCase({NetworkServiceState::kDisabled, \ - NetworkContextType::kSystem}), \ - TestCase({NetworkServiceState::kEnabled, \ - NetworkContextType::kSystem}), \ - TestCase({NetworkServiceState::kRestarted, \ - NetworkContextType::kSystem}))); \ - \ - INSTANTIATE_TEST_SUITE_P( \ - SafeBrowsingNetworkContext, TestFixture, \ - ::testing::Values(TestCase({NetworkServiceState::kDisabled, \ - NetworkContextType::kSafeBrowsing}), \ - TestCase({NetworkServiceState::kEnabled, \ - NetworkContextType::kSafeBrowsing}), \ - TestCase({NetworkServiceState::kRestarted, \ - NetworkContextType::kSafeBrowsing}))); \ - \ - INSTANTIATE_TEST_SUITE_P( \ - ProfileMainNetworkContext, TestFixture, \ - ::testing::Values(TestCase({NetworkServiceState::kDisabled, \ - NetworkContextType::kProfile}), \ - TestCase({NetworkServiceState::kEnabled, \ - NetworkContextType::kProfile}), \ - TestCase({NetworkServiceState::kRestarted, \ - NetworkContextType::kProfile}))); \ - \ - INSTANTIATE_TEST_SUITE_P( \ - IncognitoProfileMainNetworkContext, TestFixture, \ - ::testing::Values(TestCase({NetworkServiceState::kDisabled, \ - NetworkContextType::kIncognitoProfile}), \ - TestCase({NetworkServiceState::kEnabled, \ - NetworkContextType::kIncognitoProfile}), \ - TestCase({NetworkServiceState::kRestarted, \ - NetworkContextType::kIncognitoProfile}))); +#define INSTANTIATE_TEST_CASES_FOR_TEST_FIXTURE(TestFixture) \ + INSTANTIATE_EXTENSION_TESTS(TestFixture) \ + INSTANTIATE_TEST_SUITE_P( \ + SystemNetworkContext, TestFixture, \ + ::testing::Values(TEST_CASES(NetworkContextType::kSystem))); \ + \ + INSTANTIATE_TEST_SUITE_P( \ + SafeBrowsingNetworkContext, TestFixture, \ + ::testing::Values(TEST_CASES(NetworkContextType::kSafeBrowsing))); \ + \ + INSTANTIATE_TEST_SUITE_P( \ + ProfileMainNetworkContext, TestFixture, \ + ::testing::Values(TEST_CASES(NetworkContextType::kProfile))); \ + \ + INSTANTIATE_TEST_SUITE_P( \ + IncognitoProfileMainNetworkContext, TestFixture, \ + ::testing::Values(TEST_CASES(NetworkContextType::kIncognitoProfile))); INSTANTIATE_TEST_CASES_FOR_TEST_FIXTURE(NetworkContextConfigurationBrowserTest); INSTANTIATE_TEST_CASES_FOR_TEST_FIXTURE(
diff --git a/chrome/browser/offline_pages/android/offline_page_auto_fetcher_service.cc b/chrome/browser/offline_pages/android/offline_page_auto_fetcher_service.cc index e91ab8b..18dab2f 100644 --- a/chrome/browser/offline_pages/android/offline_page_auto_fetcher_service.cc +++ b/chrome/browser/offline_pages/android/offline_page_auto_fetcher_service.cc
@@ -215,31 +215,20 @@ void OfflinePageAutoFetcherService::CancelScheduleStep1(const GURL& url, TaskToken token) { - // Get all requests, and proceed to step 2. - request_coordinator_->GetAllRequests(base::BindOnce( - &OfflinePageAutoFetcherService::CancelScheduleStep2, GetWeakPtr(), - std::move(token), url, request_coordinator_)); + auto predicate = base::BindRepeating( + [](const GURL& url, const SavePageRequest& request) { + return request.client_id().name_space == kAutoAsyncNamespace && + URLMatches(request.url(), url); + }, + url); + request_coordinator_->RemoveRequestsIf( + predicate, + base::BindOnce(&OfflinePageAutoFetcherService::CancelScheduleStep2, + GetWeakPtr(), std::move(token))); } void OfflinePageAutoFetcherService::CancelScheduleStep2( TaskToken token, - const GURL& url, - RequestCoordinator* coordinator, - std::vector<std::unique_ptr<SavePageRequest>> requests) { - // Cancel the request if it's found in the list of all requests. - SavePageRequest* matching_request = FindRequest(requests, url); - if (matching_request) { - coordinator->RemoveRequests( - {matching_request->request_id()}, - base::BindOnce(&OfflinePageAutoFetcherService::CancelScheduleStep3, - GetWeakPtr(), std::move(token))); - return; - } - TaskComplete(std::move(token)); -} - -void OfflinePageAutoFetcherService::CancelScheduleStep3( - TaskToken token, const MultipleItemStatuses&) { TaskComplete(std::move(token)); }
diff --git a/chrome/browser/offline_pages/android/offline_page_auto_fetcher_service.h b/chrome/browser/offline_pages/android/offline_page_auto_fetcher_service.h index e73027b1..ac69081 100644 --- a/chrome/browser/offline_pages/android/offline_page_auto_fetcher_service.h +++ b/chrome/browser/offline_pages/android/offline_page_auto_fetcher_service.h
@@ -137,12 +137,7 @@ AddRequestResult result); void CancelScheduleStep1(const GURL& url, TaskToken token); - void CancelScheduleStep2( - TaskToken token, - const GURL& url, - RequestCoordinator* coordinator, - std::vector<std::unique_ptr<SavePageRequest>> requests); - void CancelScheduleStep3(TaskToken token, const MultipleItemStatuses&); + void CancelScheduleStep2(TaskToken token, const MultipleItemStatuses&); void CancelAllStep1(base::OnceClosure callback, TaskToken token); void CancelAllStep2(TaskToken token,
diff --git a/chrome/browser/offline_pages/prefetch/prefetch_service_factory.cc b/chrome/browser/offline_pages/prefetch/prefetch_service_factory.cc index e50d079..c254f63e 100644 --- a/chrome/browser/offline_pages/prefetch/prefetch_service_factory.cc +++ b/chrome/browser/offline_pages/prefetch/prefetch_service_factory.cc
@@ -99,7 +99,7 @@ std::unique_ptr<SuggestedArticlesObserver> suggested_articles_observer; std::unique_ptr<ThumbnailFetcherImpl> thumbnail_fetcher; // Conditional components for Feed. Not created when using Zine. - std::unique_ptr<image_fetcher::ImageFetcher> thumbnail_image_fetcher; + image_fetcher::ImageFetcher* thumbnail_image_fetcher = nullptr; if (!feed_enabled) { suggested_articles_observer = std::make_unique<SuggestedArticlesObserver>(); thumbnail_fetcher = std::make_unique<ThumbnailFetcherImpl>(); @@ -108,7 +108,7 @@ image_fetcher::CachedImageFetcherServiceFactory::GetForBrowserContext( context); DCHECK(image_fetcher_service); - thumbnail_image_fetcher = image_fetcher_service->CreateCachedImageFetcher(); + thumbnail_image_fetcher = image_fetcher_service->GetCachedImageFetcher(); } auto prefetch_downloader = std::make_unique<PrefetchDownloaderImpl>( @@ -128,7 +128,7 @@ std::move(prefetch_store), std::move(suggested_articles_observer), std::move(prefetch_downloader), std::move(prefetch_importer), std::move(prefetch_background_task_handler), std::move(thumbnail_fetcher), - std::move(thumbnail_image_fetcher)); + thumbnail_image_fetcher); } } // namespace offline_pages
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc index 44d2de3..a174f6b2 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc
@@ -370,6 +370,9 @@ "PageLoad.Clients.Ads.Visible.Bytes.AdFrames.PerFrame.Total", 0); } +// TODO(https://crbug.com/929136): Investigate why setting display: none on the +// frame will cause size updates to not be received. Verify that we record the +// correct sizes for display: none iframes. IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverBrowserTest, FramePixelSize) { base::HistogramTester histogram_tester; auto waiter = CreatePageLoadMetricsTestWaiter(); @@ -397,20 +400,9 @@ "frame = createAdIframe(); frame.width=10; frame.height = 1000; " "frame.src = '/ads_observer/pixel.png';")); - // Create a 300x300 iframe with display none that should also be recorded. - ASSERT_TRUE(ExecJs(web_contents, - "frame = createAdIframe(); frame.width=300; frame.height " - "= 300; frame.src " - "= '/ads_observer/pixel.png';")); - - // Set the frame to display none. - // TODO(johnidel): Investigate why setting display: none on the frame will - // cause size updates to not be received. - ASSERT_TRUE(ExecJs(web_contents, "frame.style.display = 'none';")); - // Wait for each frames resource to load so that they will have non-zero // bytes. - waiter->AddMinimumCompleteResourcesExpectation(7); + waiter->AddMinimumCompleteResourcesExpectation(6); waiter->Wait(); // Navigate away to force the histogram recording. @@ -420,10 +412,6 @@ histogram_tester.ExpectBucketCount(kSmallestDimensionHistogramId, 0, 1); histogram_tester.ExpectBucketCount(kSmallestDimensionHistogramId, 10, 1); histogram_tester.ExpectBucketCount(kSmallestDimensionHistogramId, 100, 1); - - // Verify the display: none frame is recorded. - histogram_tester.ExpectBucketCount(kSqrtNumberOfPixelsHistogramId, 300, 1); - histogram_tester.ExpectBucketCount(kSmallestDimensionHistogramId, 300, 1); } IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverBrowserTest,
diff --git a/chrome/browser/password_manager/chrome_password_manager_client.cc b/chrome/browser/password_manager/chrome_password_manager_client.cc index ff3b34a..a72cf34 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client.cc
@@ -95,6 +95,7 @@ #include "chrome/browser/password_manager/auto_signin_first_run_dialog_android.h" #include "chrome/browser/password_manager/generated_password_saved_infobar_delegate_android.h" #include "chrome/browser/password_manager/password_accessory_controller.h" +#include "chrome/browser/password_manager/password_generation_controller.h" #include "chrome/browser/password_manager/save_password_infobar_delegate_android.h" #include "chrome/browser/password_manager/update_password_infobar_delegate_android.h" #include "chrome/browser/ui/android/snackbars/auto_signin_prompt_controller.h" @@ -657,7 +658,7 @@ return; #if defined(OS_ANDROID) // Either #passwords-keyboards-accessory or #experimental-ui must be enabled. - if (PasswordAccessoryController::AllowedForWebContents(web_contents())) { + if (PasswordGenerationController::AllowedForWebContents(web_contents())) { if (available) { password_manager::PasswordManagerDriver* driver = driver_factory_->GetDriverForFrame( @@ -667,7 +668,7 @@ driver, ui_data.value().password_form, ui_data.value().generation_element, false /* is_manually_triggered */); - PasswordAccessoryController::GetOrCreate(web_contents()) + PasswordGenerationController::GetOrCreate(web_contents()) ->OnAutomaticGenerationStatusChanged(true, ui_data, driver->AsWeakPtr()); gfx::RectF element_bounds_in_screen_space = TransformToRootCoordinates( @@ -676,11 +677,11 @@ driver->GetPasswordAutofillManager()->MaybeShowPasswordSuggestions( element_bounds_in_screen_space, ui_data.value().text_direction); } else { - PasswordAccessoryController* accessory = - PasswordAccessoryController::GetIfExisting(web_contents()); - if (accessory) { - accessory->OnAutomaticGenerationStatusChanged(false, base::nullopt, - nullptr); + PasswordGenerationController* generation_controller = + PasswordGenerationController::GetIfExisting(web_contents()); + if (generation_controller) { + generation_controller->OnAutomaticGenerationStatusChanged( + false, base::nullopt, nullptr); } } }
diff --git a/chrome/browser/password_manager/password_accessory_controller.h b/chrome/browser/password_manager/password_accessory_controller.h index e0b73bb..c17752a 100644 --- a/chrome/browser/password_manager/password_accessory_controller.h +++ b/chrome/browser/password_manager/password_accessory_controller.h
@@ -22,10 +22,6 @@ struct PasswordForm; } // namespace autofill -namespace password_manager { -class PasswordManagerDriver; -} // namespace password_manager - // Interface for password-specific keyboard accessory controller between the // ManualFillingController and PasswordManagerClient. // @@ -65,12 +61,6 @@ best_matches, const url::Origin& origin) = 0; - // Notifies the view that automatic password generation status changed. - virtual void OnAutomaticGenerationStatusChanged( - bool available, - const base::Optional< - autofill::password_generation::PasswordGenerationUIData>& ui_data, - const base::WeakPtr<password_manager::PasswordManagerDriver>& driver) = 0; // Completes a filling attempt by recording metrics, giving feedback to the // user and dismissing the accessory sheet. @@ -110,22 +100,6 @@ virtual void OnOptionSelected( const base::string16& selected_option) const = 0; - // Called by the UI code to signal that the user requested password - // generation. This should prompt a modal dialog with the generated password. - virtual void OnGenerationRequested() = 0; - - // Called from the modal dialog if the user accepted the generated password. - virtual void GeneratedPasswordAccepted(const base::string16& password) = 0; - - // Called from the modal dialog if the user rejected the generated password. - virtual void GeneratedPasswordRejected() = 0; - - // ----------------- - // Member accessors: - // ----------------- - - virtual gfx::NativeWindow native_window() const = 0; - private: DISALLOW_COPY_AND_ASSIGN(PasswordAccessoryController); };
diff --git a/chrome/browser/password_manager/password_accessory_controller_impl.cc b/chrome/browser/password_manager/password_accessory_controller_impl.cc index f6c94ad..fac1ca5 100644 --- a/chrome/browser/password_manager/password_accessory_controller_impl.cc +++ b/chrome/browser/password_manager/password_accessory_controller_impl.cc
@@ -14,7 +14,6 @@ #include "chrome/browser/autofill/manual_filling_controller.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/password_manager/password_accessory_metrics_util.h" -#include "chrome/browser/password_manager/password_generation_dialog_view_interface.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/passwords/manage_passwords_view_utils.h" #include "chrome/browser/vr/vr_tab_helper.h" @@ -37,14 +36,6 @@ using autofill::UserInfo; using FillingSource = ManualFillingController::FillingSource; -namespace { - -void RecordGenerationDialogDismissal(bool accepted) { - UMA_HISTOGRAM_BOOLEAN("KeyboardAccessory.GeneratedPasswordDialog", accepted); -} - -} // namespace - PasswordAccessoryControllerImpl::~PasswordAccessoryControllerImpl() = default; // static @@ -75,29 +66,6 @@ return PasswordAccessoryControllerImpl::FromWebContents(web_contents); } -struct PasswordAccessoryControllerImpl::GenerationElementData { - GenerationElementData(autofill::PasswordForm form, - autofill::FormSignature form_signature, - autofill::FieldSignature field_signature, - uint32_t max_password_length) - : form(std::move(form)), - form_signature(form_signature), - field_signature(field_signature), - max_password_length(max_password_length) {} - - // Form for which password generation is triggered. - autofill::PasswordForm form; - - // Signature of the form for which password generation is triggered. - autofill::FormSignature form_signature; - - // Signature of the field for which password generation is triggered. - autofill::FieldSignature field_signature; - - // Maximum length of the generated password. - uint32_t max_password_length; -}; - struct PasswordAccessoryControllerImpl::SuggestionElementData { SuggestionElementData(base::string16 password, base::string16 username, @@ -128,16 +96,15 @@ void PasswordAccessoryControllerImpl::CreateForWebContentsForTesting( content::WebContents* web_contents, base::WeakPtr<ManualFillingController> mf_controller, - CreateDialogFactory create_dialog_factory, favicon::FaviconService* favicon_service) { DCHECK(web_contents) << "Need valid WebContents to attach controller to!"; DCHECK(!FromWebContents(web_contents)) << "Controller already attached!"; DCHECK(mf_controller); web_contents->SetUserData( - UserDataKey(), base::WrapUnique(new PasswordAccessoryControllerImpl( - web_contents, std::move(mf_controller), - create_dialog_factory, favicon_service))); + UserDataKey(), + base::WrapUnique(new PasswordAccessoryControllerImpl( + web_contents, std::move(mf_controller), favicon_service))); } void PasswordAccessoryControllerImpl::SavePasswordsForOrigin( @@ -153,28 +120,6 @@ } } -void PasswordAccessoryControllerImpl::OnAutomaticGenerationStatusChanged( - bool available, - const base::Optional< - autofill::password_generation::PasswordGenerationUIData>& ui_data, - const base::WeakPtr<password_manager::PasswordManagerDriver>& driver) { - target_frame_driver_ = driver; - if (available) { - DCHECK(ui_data.has_value()); - generation_element_data_ = std::make_unique<GenerationElementData>( - ui_data.value().password_form, - autofill::CalculateFormSignature( - ui_data.value().password_form.form_data), - autofill::CalculateFieldSignatureByNameAndType( - ui_data.value().generation_element, "password"), - ui_data.value().max_length); - } else { - generation_element_data_.reset(); - } - - GetManualFillingController()->OnAutomaticGenerationStatusChanged(available); -} - void PasswordAccessoryControllerImpl::OnFilledIntoFocusedField( autofill::FillingStatus status) { GetManualFillingController()->OnFilledIntoFocusedField(status); @@ -275,50 +220,9 @@ base::AsWeakPtr<PasswordAccessoryControllerImpl>(this))); } -void PasswordAccessoryControllerImpl::OnGenerationRequested() { - if (!target_frame_driver_) - return; - // TODO(crbug.com/835234): Take the modal dialog logic out of the accessory - // controller. - dialog_view_ = create_dialog_factory_.Run(this); - uint32_t spec_priority = 0; - base::string16 password = - target_frame_driver_->GetPasswordGenerationManager()->GeneratePassword( - web_contents_->GetLastCommittedURL().GetOrigin(), - generation_element_data_->form_signature, - generation_element_data_->field_signature, - generation_element_data_->max_password_length, &spec_priority); - if (target_frame_driver_ && target_frame_driver_->GetPasswordManager()) { - target_frame_driver_->GetPasswordManager() - ->ReportSpecPriorityForGeneratedPassword(generation_element_data_->form, - spec_priority); - } - dialog_view_->Show(password); -} - -void PasswordAccessoryControllerImpl::GeneratedPasswordAccepted( - const base::string16& password) { - if (!target_frame_driver_) - return; - RecordGenerationDialogDismissal(true); - target_frame_driver_->GeneratedPasswordAccepted(password); - dialog_view_.reset(); -} - -void PasswordAccessoryControllerImpl::GeneratedPasswordRejected() { - RecordGenerationDialogDismissal(false); - dialog_view_.reset(); -} - -gfx::NativeWindow PasswordAccessoryControllerImpl::native_window() const { - return web_contents_->GetTopLevelNativeWindow(); -} - PasswordAccessoryControllerImpl::PasswordAccessoryControllerImpl( content::WebContents* web_contents) : web_contents_(web_contents), - create_dialog_factory_( - base::BindRepeating(&PasswordGenerationDialogViewInterface::Create)), favicon_service_(FaviconServiceFactory::GetForProfile( Profile::FromBrowserContext(web_contents->GetBrowserContext()), ServiceAccessType::EXPLICIT_ACCESS)) { @@ -328,11 +232,9 @@ PasswordAccessoryControllerImpl::PasswordAccessoryControllerImpl( content::WebContents* web_contents, base::WeakPtr<ManualFillingController> mf_controller, - CreateDialogFactory create_dialog_factory, favicon::FaviconService* favicon_service) : web_contents_(web_contents), mf_controller_(std::move(mf_controller)), - create_dialog_factory_(create_dialog_factory), favicon_service_(favicon_service) {} // static
diff --git a/chrome/browser/password_manager/password_accessory_controller_impl.h b/chrome/browser/password_manager/password_accessory_controller_impl.h index 4c0f9228..3f87a90a 100644 --- a/chrome/browser/password_manager/password_accessory_controller_impl.h +++ b/chrome/browser/password_manager/password_accessory_controller_impl.h
@@ -28,12 +28,7 @@ class FaviconService; } // namespace favicon -namespace password_manager { -class PasswordManagerDriver; -} // namespace password_manager - class ManualFillingController; -class PasswordGenerationDialogViewInterface; // Use either PasswordAccessoryController::GetOrCreate or // PasswordAccessoryController::GetIfExisting to obtain instances of this class. @@ -44,9 +39,6 @@ : public PasswordAccessoryController, public content::WebContentsUserData<PasswordAccessoryControllerImpl> { public: - using CreateDialogFactory = base::RepeatingCallback<std::unique_ptr< - PasswordGenerationDialogViewInterface>(PasswordAccessoryController*)>; - ~PasswordAccessoryControllerImpl() override; // PasswordAccessoryController: @@ -54,12 +46,6 @@ const std::map<base::string16, const autofill::PasswordForm*>& best_matches, const url::Origin& origin) override; - void OnAutomaticGenerationStatusChanged( - bool available, - const base::Optional< - autofill::password_generation::PasswordGenerationUIData>& ui_data, - const base::WeakPtr<password_manager::PasswordManagerDriver>& driver) - override; void OnFilledIntoFocusedField(autofill::FillingStatus status) override; void RefreshSuggestionsForField(const url::Origin& origin, bool is_fillable, @@ -71,10 +57,6 @@ void OnFillingTriggered(bool is_password, const base::string16& text_to_fill) override; void OnOptionSelected(const base::string16& selected_option) const override; - void OnGenerationRequested() override; - void GeneratedPasswordAccepted(const base::string16& password) override; - void GeneratedPasswordRejected() override; - gfx::NativeWindow native_window() const override; // Like |CreateForWebContents|, it creates the controller and attaches it to // the given |web_contents|. Additionally, it allows inject a manual filling @@ -82,14 +64,9 @@ static void CreateForWebContentsForTesting( content::WebContents* web_contents, base::WeakPtr<ManualFillingController> mf_controller, - CreateDialogFactory create_dialog_callback, favicon::FaviconService* favicon_service); private: - // Data including the form and field for which generation was requested, - // their signatures and the maximum password size. - struct GenerationElementData; - // Data for a credential pair that is transformed into a suggestion. struct SuggestionElementData; @@ -105,7 +82,6 @@ PasswordAccessoryControllerImpl( content::WebContents* web_contents, base::WeakPtr<ManualFillingController> mf_controller, - CreateDialogFactory create_dialog_callback, favicon::FaviconService* favicon_service); // Creates the view items based on the given |suggestions|. @@ -131,9 +107,6 @@ // The tab for which this class is scoped. content::WebContents* web_contents_; - // Data for the generation element used to generate the password. - std::unique_ptr<GenerationElementData> generation_element_data_; - // The origin of the currently focused frame. It's used to ensure that // favicons are not displayed across origins. url::Origin current_origin_; @@ -147,22 +120,13 @@ // object aborts the request. Upon destruction, requests are cancelled, too. base::CancelableTaskTracker favicon_tracker_; - // Password manager driver for the target frame used for password generation. - base::WeakPtr<password_manager::PasswordManagerDriver> target_frame_driver_; - // The password accessory controller object to forward client requests to. base::WeakPtr<ManualFillingController> mf_controller_; - // Modal dialog view meant to display the generated password. - std::unique_ptr<PasswordGenerationDialogViewInterface> dialog_view_; - // Remembers whether the last focused field was a password field. That way, // the reconstructed elements have the correct type. bool last_focused_field_was_for_passwords_ = false; - // Creation callback for the modal dialog view meant to facilitate testing. - CreateDialogFactory create_dialog_factory_; - // The favicon service used to make retrieve icons for a given origin. favicon::FaviconService* favicon_service_;
diff --git a/chrome/browser/password_manager/password_accessory_controller_impl_unittest.cc b/chrome/browser/password_manager/password_accessory_controller_impl_unittest.cc index 8f2096a..fde2278 100644 --- a/chrome/browser/password_manager/password_accessory_controller_impl_unittest.cc +++ b/chrome/browser/password_manager/password_accessory_controller_impl_unittest.cc
@@ -15,14 +15,12 @@ #include "base/strings/utf_string_conversions.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/mock_callback.h" -#include "chrome/browser/autofill/manual_filling_controller.h" -#include "chrome/browser/password_manager/password_generation_dialog_view_interface.h" +#include "chrome/browser/autofill/mock_manual_filling_controller.h" #include "chrome/grit/generated_resources.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "components/autofill/core/common/password_form.h" #include "components/autofill/core/common/signatures_util.h" #include "components/favicon/core/test/mock_favicon_service.h" -#include "components/password_manager/core/browser/password_generation_manager.h" #include "components/password_manager/core/browser/stub_password_manager_driver.h" #include "components/strings/grit/components_strings.h" #include "testing/gmock/include/gmock/gmock.h" @@ -37,7 +35,6 @@ using autofill::FooterCommand; using autofill::PasswordForm; using autofill::UserInfo; -using autofill::password_generation::PasswordGenerationUIData; using base::ASCIIToUTF16; using testing::_; using testing::ByMove; @@ -51,67 +48,6 @@ constexpr char kExampleDomain[] = "example.com"; constexpr int kIconSize = 75; // An example size for favicons (=> 3.5*20px). -class MockManualFillingController - : public ManualFillingController, - public base::SupportsWeakPtr<MockManualFillingController> { - public: - MOCK_METHOD1(OnAutomaticGenerationStatusChanged, void(bool)); - MOCK_METHOD1(OnFilledIntoFocusedField, void(FillingStatus)); - MOCK_METHOD2(RefreshSuggestionsForField, - void(bool, const AccessorySheetData&)); - MOCK_METHOD1(ShowWhenKeyboardIsVisible, void(FillingSource)); - MOCK_METHOD1(Hide, void(FillingSource)); - MOCK_METHOD2(GetFavicon, - void(int, base::OnceCallback<void(const gfx::Image&)>)); - MOCK_METHOD2(OnFillingTriggered, - void(bool is_password, const base::string16&)); - MOCK_CONST_METHOD1(OnOptionSelected, void(const base::string16&)); - MOCK_METHOD0(OnGenerationRequested, void()); - MOCK_CONST_METHOD0(container_view, gfx::NativeView()); -}; - -class MockPasswordManagerDriver - : public password_manager::StubPasswordManagerDriver { - public: - MockPasswordManagerDriver() = default; - - MOCK_METHOD0(GetPasswordGenerationManager, - password_manager::PasswordGenerationManager*()); - - private: - DISALLOW_COPY_AND_ASSIGN(MockPasswordManagerDriver); -}; - -class MockPasswordGenerationManager - : public password_manager::PasswordGenerationManager { - public: - MockPasswordGenerationManager(password_manager::PasswordManagerClient* client, - password_manager::PasswordManagerDriver* driver) - : password_manager::PasswordGenerationManager(client, driver) {} - - MOCK_METHOD5(GeneratePassword, - base::string16(const GURL&, - autofill::FormSignature, - autofill::FieldSignature, - uint32_t, - uint32_t*)); - - private: - DISALLOW_COPY_AND_ASSIGN(MockPasswordGenerationManager); -}; - -// Mock modal dialog view used to bypass the need of a valid top level window. -class MockPasswordGenerationDialogView - : public PasswordGenerationDialogViewInterface { - public: - MockPasswordGenerationDialogView() = default; - - MOCK_METHOD1(Show, void(base::string16&)); - - private: - DISALLOW_COPY_AND_ASSIGN(MockPasswordGenerationDialogView); -}; - // Helper class for AccessorySheetData objects creation. // // Example that creates a AccessorySheetData object with two UserInfo objects; @@ -216,30 +152,6 @@ return builder; } -PasswordGenerationUIData GetTestGenerationUIData1() { - PasswordForm form; - form.form_data = autofill::FormData(); - form.form_data.action = GURL("http://www.example1.com/accounts/Login"); - form.form_data.origin = GURL("http://www.example1.com/accounts/LoginAuth"); - PasswordGenerationUIData data; - data.password_form = form; - data.generation_element = ASCIIToUTF16("testelement1"); - data.max_length = 10; - return data; -} - -PasswordGenerationUIData GetTestGenerationUIData2() { - PasswordForm form; - form.form_data = autofill::FormData(); - form.form_data.action = GURL("http://www.example2.com/accounts/Login"); - form.form_data.origin = GURL("http://www.example2.com/accounts/LoginAuth"); - PasswordGenerationUIData data; - data.password_form = form; - data.generation_element = ASCIIToUTF16("testelement2"); - data.max_length = 11; - return data; -} - } // namespace // Automagically used to pretty-print UserInfo::Field. Must be in same @@ -295,74 +207,27 @@ NavigateAndCommit(GURL(kExampleSite)); PasswordAccessoryControllerImpl::CreateForWebContentsForTesting( web_contents(), mock_manual_filling_controller_.AsWeakPtr(), - mock_dialog_factory_.Get(), favicon_service()); + favicon_service()); NavigateAndCommit(GURL(kExampleSite)); - - // Mock objects needed by password generation - mock_password_manager_driver_ = - std::make_unique<NiceMock<MockPasswordManagerDriver>>(); - mock_generation_manager_ = - std::make_unique<NiceMock<MockPasswordGenerationManager>>( - nullptr, mock_password_manager_driver_.get()); - mock_dialog_ = - std::make_unique<NiceMock<MockPasswordGenerationDialogView>>(); } PasswordAccessoryController* controller() { return PasswordAccessoryControllerImpl::FromWebContents(web_contents()); } - const base::MockCallback< - PasswordAccessoryControllerImpl::CreateDialogFactory>& - mock_dialog_factory() { - return mock_dialog_factory_; - } favicon::MockFaviconService* favicon_service() { return mock_favicon_service_.get(); } protected: - // Sets up mocks needed by the generation flow and signals the - // |PasswordAccessoryControllerImpl| that generation is available. - void InitializeGeneration(const base::string16& password); - StrictMock<MockManualFillingController> mock_manual_filling_controller_; - std::unique_ptr<NiceMock<MockPasswordManagerDriver>> - mock_password_manager_driver_; - std::unique_ptr<NiceMock<MockPasswordGenerationManager>> - mock_generation_manager_; - std::unique_ptr<NiceMock<MockPasswordGenerationDialogView>> mock_dialog_; - private: - NiceMock< - base::MockCallback<PasswordAccessoryControllerImpl::CreateDialogFactory>> - mock_dialog_factory_; std::unique_ptr<StrictMock<favicon::MockFaviconService>> mock_favicon_service_; }; -void PasswordAccessoryControllerTest::InitializeGeneration( - const base::string16& password) { - ON_CALL(*(mock_password_manager_driver_.get()), - GetPasswordGenerationManager()) - .WillByDefault(Return(mock_generation_manager_.get())); - - EXPECT_CALL(mock_manual_filling_controller_, - OnAutomaticGenerationStatusChanged(true)); - - controller()->OnAutomaticGenerationStatusChanged( - true, GetTestGenerationUIData1(), - mock_password_manager_driver_->AsWeakPtr()); - - ON_CALL(*(mock_generation_manager_.get()), GeneratePassword(_, _, _, _, _)) - .WillByDefault(Return(password)); - - ON_CALL(mock_dialog_factory(), Run) - .WillByDefault(Return(ByMove(std::move(mock_dialog_)))); -} - TEST_F(PasswordAccessoryControllerTest, IsNotRecreatedForSameWebContents) { PasswordAccessoryControllerImpl* initial_controller = PasswordAccessoryControllerImpl::FromWebContents(web_contents()); @@ -375,7 +240,6 @@ TEST_F(PasswordAccessoryControllerTest, TransformsMatchesToSuggestions) { controller()->SavePasswordsForOrigin({CreateEntry("Ben", "S3cur3").first}, url::Origin::Create(GURL(kExampleSite))); - EXPECT_CALL( mock_manual_filling_controller_, RefreshSuggestionsForField( @@ -512,58 +376,6 @@ controller()->OnFilledIntoFocusedField(FillingStatus::SUCCESS); } -TEST_F(PasswordAccessoryControllerTest, RelaysAutomaticGenerationAvailable) { - EXPECT_CALL(mock_manual_filling_controller_, - OnAutomaticGenerationStatusChanged(true)); - controller()->OnAutomaticGenerationStatusChanged( - true, GetTestGenerationUIData1(), nullptr); -} - -TEST_F(PasswordAccessoryControllerTest, RelaysAutmaticGenerationUnavailable) { - EXPECT_CALL(mock_manual_filling_controller_, - OnAutomaticGenerationStatusChanged(false)); - controller()->OnAutomaticGenerationStatusChanged(false, base::nullopt, - nullptr); -} - -// Tests that if AutomaticGenerationStatusChanged(true) is called for different -// password forms, the form and field signatures used for password generation -// are updated. -TEST_F(PasswordAccessoryControllerTest, - UpdatesSignaturesForDifferentGenerationForms) { - // Called twice for different forms. - EXPECT_CALL(mock_manual_filling_controller_, - OnAutomaticGenerationStatusChanged(true)) - .Times(2); - controller()->OnAutomaticGenerationStatusChanged( - true, GetTestGenerationUIData1(), - mock_password_manager_driver_->AsWeakPtr()); - PasswordGenerationUIData new_ui_data = GetTestGenerationUIData2(); - controller()->OnAutomaticGenerationStatusChanged( - true, new_ui_data, mock_password_manager_driver_->AsWeakPtr()); - - autofill::FormSignature form_signature = - autofill::CalculateFormSignature(new_ui_data.password_form.form_data); - autofill::FieldSignature field_signature = - autofill::CalculateFieldSignatureByNameAndType( - new_ui_data.generation_element, "password"); - - MockPasswordGenerationDialogView* raw_dialog_view = mock_dialog_.get(); - - base::string16 generated_password = ASCIIToUTF16("t3stp@ssw0rd"); - EXPECT_CALL(mock_dialog_factory(), Run) - .WillOnce(Return(ByMove(std::move(mock_dialog_)))); - EXPECT_CALL(*(mock_password_manager_driver_.get()), - GetPasswordGenerationManager()) - .WillOnce(Return(mock_generation_manager_.get())); - EXPECT_CALL(*(mock_generation_manager_.get()), - GeneratePassword(_, form_signature, field_signature, - uint32_t(new_ui_data.max_length), _)) - .WillOnce(Return(generated_password)); - EXPECT_CALL(*raw_dialog_view, Show(generated_password)); - controller()->OnGenerationRequested(); -} - TEST_F(PasswordAccessoryControllerTest, PasswordFieldChangesSuggestionType) { controller()->SavePasswordsForOrigin({CreateEntry("Ben", "S3cur3").first}, url::Origin::Create(GURL(kExampleSite))); @@ -866,31 +678,3 @@ base::RunLoop().RunUntilIdle(); } - -TEST_F(PasswordAccessoryControllerTest, RecordsGeneratedPasswordRejected) { - base::string16 test_password = ASCIIToUTF16("t3stp@ssw0rd"); - - InitializeGeneration(test_password); - - base::HistogramTester histogram_tester; - - controller()->OnGenerationRequested(); - controller()->GeneratedPasswordRejected(); - - histogram_tester.ExpectUniqueSample( - "KeyboardAccessory.GeneratedPasswordDialog", false, 1); -} - -TEST_F(PasswordAccessoryControllerTest, RecordsGeneratedPasswordAccepted) { - base::string16 test_password = ASCIIToUTF16("t3stp@ssw0rd"); - - InitializeGeneration(test_password); - - base::HistogramTester histogram_tester; - - controller()->OnGenerationRequested(); - controller()->GeneratedPasswordAccepted(test_password); - - histogram_tester.ExpectUniqueSample( - "KeyboardAccessory.GeneratedPasswordDialog", true, 1); -}
diff --git a/chrome/browser/password_manager/password_generation_controller.h b/chrome/browser/password_manager/password_generation_controller.h new file mode 100644 index 0000000..b7446be7 --- /dev/null +++ b/chrome/browser/password_manager/password_generation_controller.h
@@ -0,0 +1,86 @@ +// 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. + +#ifndef CHROME_BROWSER_PASSWORD_MANAGER_PASSWORD_GENERATION_CONTROLLER_H_ +#define CHROME_BROWSER_PASSWORD_MANAGER_PASSWORD_GENERATION_CONTROLLER_H_ + +#include <memory> + +#include "base/memory/weak_ptr.h" +#include "components/autofill/core/common/password_generation_util.h" +#include "content/public/browser/web_contents.h" + +namespace password_manager { +class PasswordManagerDriver; +} // namespace password_manager + +// Interface for the controller responsible for overseeing the UI flow for +// password generation. +// +// As part of this, it communicates with the PasswordAccessoryController and +// it manages the modal dialog used to display the generated password. +// +// There is a single instance per WebContents that can be accessed by calling: +// PasswordAccessoryController::GetOrCreate(web_contents); +// On the first call, an instance is attached to |web_contents|, so it can be +// returned by subsequent calls. +class PasswordGenerationController { + public: + PasswordGenerationController() = default; + virtual ~PasswordGenerationController() = default; + + // Returns true if the generation controller may exist for |web_contents|. + // Otherwise (e.g. if the keyboard accessory is not allowed), + // it returns false. + static bool AllowedForWebContents(content::WebContents* web_contents); + + // Returns a reference to the unique PasswordGenerationController associated + // with |web_contents|. A new instance is created if the first time this + // function is called. + static PasswordGenerationController* GetOrCreate( + content::WebContents* web_contents); + + // Returns a reference to the PasswordGenerationController associated with the + // |web_contents| or null if there is no such instance. + static PasswordGenerationController* GetIfExisting( + content::WebContents* web_contents); + + // -------------------------------------------------- + // Methods called by the ChromePasswordManagerClient: + // -------------------------------------------------- + + // Notifies the UI that the automatic password generation status changed. + // If |available| is true, then a button should be displayed in the accessory + // bar. The button should be removed from the bar when |available| is false. + virtual void OnAutomaticGenerationStatusChanged( + bool available, + const base::Optional< + autofill::password_generation::PasswordGenerationUIData>& ui_data, + const base::WeakPtr<password_manager::PasswordManagerDriver>& driver) = 0; + + // ------------------------- + // Methods called by the UI: + // ------------------------- + + // Called by the UI code to signal that the user requested password + // generation. This should prompt a modal dialog with the generated password. + virtual void OnGenerationRequested() = 0; + + // Called from the modal dialog if the user accepted the generated password. + virtual void GeneratedPasswordAccepted(const base::string16& password) = 0; + + // Called from the modal dialog if the user rejected the generated password. + virtual void GeneratedPasswordRejected() = 0; + + // ----------------- + // Member accessors: + // ----------------- + + virtual gfx::NativeWindow top_level_native_window() const = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(PasswordGenerationController); +}; + +#endif // CHROME_BROWSER_PASSWORD_MANAGER_PASSWORD_GENERATION_CONTROLLER_H_
diff --git a/chrome/browser/password_manager/password_generation_controller_impl.cc b/chrome/browser/password_manager/password_generation_controller_impl.cc new file mode 100644 index 0000000..88be480 --- /dev/null +++ b/chrome/browser/password_manager/password_generation_controller_impl.cc
@@ -0,0 +1,171 @@ +// 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. + +#include "chrome/browser/password_manager/password_generation_controller_impl.h" + +#include <utility> + +#include "base/bind.h" +#include "base/callback.h" +#include "base/metrics/histogram_macros.h" +#include "chrome/browser/autofill/manual_filling_controller.h" +#include "chrome/browser/password_manager/password_accessory_controller.h" +#include "chrome/browser/password_manager/password_generation_dialog_view_interface.h" +#include "components/autofill/core/common/password_form.h" +#include "components/autofill/core/common/password_generation_util.h" +#include "components/autofill/core/common/signatures_util.h" +#include "components/password_manager/core/browser/password_generation_manager.h" +#include "components/password_manager/core/browser/password_manager.h" +#include "components/password_manager/core/browser/password_manager_driver.h" + +namespace { + +void RecordGenerationDialogDismissal(bool accepted) { + UMA_HISTOGRAM_BOOLEAN("KeyboardAccessory.GeneratedPasswordDialog", accepted); +} + +} // namespace + +PasswordGenerationControllerImpl::~PasswordGenerationControllerImpl() = default; + +// static +bool PasswordGenerationController::AllowedForWebContents( + content::WebContents* web_contents) { + return PasswordAccessoryController::AllowedForWebContents(web_contents); +} + +// static +PasswordGenerationController* PasswordGenerationController::GetOrCreate( + content::WebContents* web_contents) { + DCHECK(PasswordGenerationController::AllowedForWebContents(web_contents)); + + PasswordGenerationControllerImpl::CreateForWebContents(web_contents); + return PasswordGenerationControllerImpl::FromWebContents(web_contents); +} + +// static +PasswordGenerationController* PasswordGenerationController::GetIfExisting( + content::WebContents* web_contents) { + return PasswordGenerationControllerImpl::FromWebContents(web_contents); +} + +struct PasswordGenerationControllerImpl::GenerationElementData { + GenerationElementData(autofill::PasswordForm form, + autofill::FormSignature form_signature, + autofill::FieldSignature field_signature, + uint32_t max_password_length) + : form(std::move(form)), + form_signature(form_signature), + field_signature(field_signature), + max_password_length(max_password_length) {} + + // Form for which password generation is triggered. + autofill::PasswordForm form; + + // Signature of the form for which password generation is triggered. + autofill::FormSignature form_signature; + + // Signature of the field for which password generation is triggered. + autofill::FieldSignature field_signature; + + // Maximum length of the generated password. + uint32_t max_password_length; +}; + +void PasswordGenerationControllerImpl::OnAutomaticGenerationStatusChanged( + bool available, + const base::Optional< + autofill::password_generation::PasswordGenerationUIData>& ui_data, + const base::WeakPtr<password_manager::PasswordManagerDriver>& driver) { + target_frame_driver_ = driver; + if (available) { + DCHECK(ui_data.has_value()); + generation_element_data_ = std::make_unique<GenerationElementData>( + ui_data.value().password_form, + autofill::CalculateFormSignature( + ui_data.value().password_form.form_data), + autofill::CalculateFieldSignatureByNameAndType( + ui_data.value().generation_element, "password"), + ui_data.value().max_length); + } else { + generation_element_data_.reset(); + } + if (!manual_filling_controller_) { + manual_filling_controller_ = + ManualFillingController::GetOrCreate(web_contents_); + } + + DCHECK(manual_filling_controller_); + manual_filling_controller_->OnAutomaticGenerationStatusChanged(available); +} + +void PasswordGenerationControllerImpl::OnGenerationRequested() { + if (!target_frame_driver_) + return; + dialog_view_ = create_dialog_factory_.Run(this); + uint32_t spec_priority = 0; + base::string16 password = + target_frame_driver_->GetPasswordGenerationManager()->GeneratePassword( + web_contents_->GetLastCommittedURL().GetOrigin(), + generation_element_data_->form_signature, + generation_element_data_->field_signature, + generation_element_data_->max_password_length, &spec_priority); + if (target_frame_driver_ && target_frame_driver_->GetPasswordManager()) { + target_frame_driver_->GetPasswordManager() + ->ReportSpecPriorityForGeneratedPassword(generation_element_data_->form, + spec_priority); + } + dialog_view_->Show(password); +} + +void PasswordGenerationControllerImpl::GeneratedPasswordAccepted( + const base::string16& password) { + if (!target_frame_driver_) + return; + RecordGenerationDialogDismissal(true); + target_frame_driver_->GeneratedPasswordAccepted(password); + dialog_view_.reset(); +} + +void PasswordGenerationControllerImpl::GeneratedPasswordRejected() { + RecordGenerationDialogDismissal(false); + dialog_view_.reset(); +} + +gfx::NativeWindow PasswordGenerationControllerImpl::top_level_native_window() + const { + return web_contents_->GetTopLevelNativeWindow(); +} + +// static +void PasswordGenerationControllerImpl::CreateForWebContentsForTesting( + content::WebContents* web_contents, + base::WeakPtr<ManualFillingController> manual_filling_controller_, + CreateDialogFactory create_dialog_factory) { + DCHECK(web_contents) << "Need valid WebContents to attach controller to!"; + DCHECK(!FromWebContents(web_contents)) << "Controller already attached!"; + DCHECK(manual_filling_controller_); + + web_contents->SetUserData( + UserDataKey(), base::WrapUnique(new PasswordGenerationControllerImpl( + web_contents, std::move(manual_filling_controller_), + create_dialog_factory))); +} + +PasswordGenerationControllerImpl::PasswordGenerationControllerImpl( + content::WebContents* web_contents) + : web_contents_(web_contents), + create_dialog_factory_( + base::BindRepeating(&PasswordGenerationDialogViewInterface::Create)) { +} + +PasswordGenerationControllerImpl::PasswordGenerationControllerImpl( + content::WebContents* web_contents, + base::WeakPtr<ManualFillingController> manual_filling_controller_, + CreateDialogFactory create_dialog_factory) + : web_contents_(web_contents), + manual_filling_controller_(std::move(manual_filling_controller_)), + create_dialog_factory_(create_dialog_factory) {} + +WEB_CONTENTS_USER_DATA_KEY_IMPL(PasswordGenerationControllerImpl);
diff --git a/chrome/browser/password_manager/password_generation_controller_impl.h b/chrome/browser/password_manager/password_generation_controller_impl.h new file mode 100644 index 0000000..35a66ef --- /dev/null +++ b/chrome/browser/password_manager/password_generation_controller_impl.h
@@ -0,0 +1,91 @@ +// 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. + +#ifndef CHROME_BROWSER_PASSWORD_MANAGER_PASSWORD_GENERATION_CONTROLLER_IMPL_H_ +#define CHROME_BROWSER_PASSWORD_MANAGER_PASSWORD_GENERATION_CONTROLLER_IMPL_H_ + +#include <memory> + +#include "base/memory/weak_ptr.h" +#include "chrome/browser/password_manager/password_generation_controller.h" +#include "components/autofill/core/common/password_generation_util.h" +#include "content/public/browser/web_contents_user_data.h" + +class ManualFillingController; +class PasswordGenerationDialogViewInterface; + +// In its current state, this class is not involved in the editing flow for +// a generated password. +// +// Use either PasswordGenerationController::GetOrCreate or +// PasswordGenerationController::GetIfExisting to obtain instances of this +// class. +class PasswordGenerationControllerImpl + : public PasswordGenerationController, + public content::WebContentsUserData<PasswordGenerationControllerImpl> { + public: + using CreateDialogFactory = base::RepeatingCallback<std::unique_ptr< + PasswordGenerationDialogViewInterface>(PasswordGenerationController*)>; + + ~PasswordGenerationControllerImpl() override; + + // PasswordGenerationController: + void OnAutomaticGenerationStatusChanged( + bool available, + const base::Optional< + autofill::password_generation::PasswordGenerationUIData>& ui_data, + const base::WeakPtr<password_manager::PasswordManagerDriver>& driver) + override; + void OnGenerationRequested() override; + void GeneratedPasswordAccepted(const base::string16& password) override; + void GeneratedPasswordRejected() override; + gfx::NativeWindow top_level_native_window() const override; + + // Like |CreateForWebContents|, it creates the controller and attaches it to + // the given |web_contents|. Additionally, it allows injecting mocks for + // testing. + static void CreateForWebContentsForTesting( + content::WebContents* web_contents, + base::WeakPtr<ManualFillingController> manual_filling_controller, + CreateDialogFactory create_dialog_callback); + + private: + // Data including the form and field for which generation was requested, + // their signatures and the maximum password size. + struct GenerationElementData; + + friend class content::WebContentsUserData<PasswordGenerationControllerImpl>; + + explicit PasswordGenerationControllerImpl(content::WebContents* web_contents); + + // Constructor that allows to inject a mock or fake view. + PasswordGenerationControllerImpl( + content::WebContents* web_contents, + base::WeakPtr<ManualFillingController> manual_filling_controller, + CreateDialogFactory create_dialog_callback); + + // The tab for which this class is scoped. + content::WebContents* web_contents_; + + // Data for the generation element used to generate the password. + std::unique_ptr<GenerationElementData> generation_element_data_; + + // Password manager driver for the target frame used for password generation. + base::WeakPtr<password_manager::PasswordManagerDriver> target_frame_driver_; + + // The manual filling controller object to forward client requests to. + base::WeakPtr<ManualFillingController> manual_filling_controller_; + + // Modal dialog view meant to display the generated password. + std::unique_ptr<PasswordGenerationDialogViewInterface> dialog_view_; + + // Creation callback for the modal dialog view meant to facilitate testing. + CreateDialogFactory create_dialog_factory_; + + WEB_CONTENTS_USER_DATA_KEY_DECL(); + + DISALLOW_COPY_AND_ASSIGN(PasswordGenerationControllerImpl); +}; + +#endif // CHROME_BROWSER_PASSWORD_MANAGER_PASSWORD_GENERATION_CONTROLLER_IMPL_H_
diff --git a/chrome/browser/password_manager/password_generation_controller_impl_unittest.cc b/chrome/browser/password_manager/password_generation_controller_impl_unittest.cc new file mode 100644 index 0000000..603a1b4 --- /dev/null +++ b/chrome/browser/password_manager/password_generation_controller_impl_unittest.cc
@@ -0,0 +1,259 @@ +// 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. +#include "chrome/browser/password_manager/password_generation_controller_impl.h" + +#include <map> +#include <utility> + +#include "base/callback.h" +#include "base/optional.h" +#include "base/strings/utf_string_conversions.h" +#include "base/test/metrics/histogram_tester.h" +#include "base/test/mock_callback.h" +#include "chrome/browser/autofill/mock_manual_filling_controller.h" +#include "chrome/browser/password_manager/password_generation_dialog_view_interface.h" +#include "chrome/test/base/chrome_render_view_host_test_harness.h" +#include "components/password_manager/core/browser/password_generation_manager.h" +#include "components/password_manager/core/browser/stub_password_manager_driver.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { +using autofill::FooterCommand; +using autofill::PasswordForm; +using autofill::password_generation::PasswordGenerationUIData; +using base::ASCIIToUTF16; +using testing::_; +using testing::ByMove; +using testing::Eq; +using testing::Mock; +using testing::NiceMock; +using testing::Return; +using testing::StrictMock; + +class MockPasswordManagerDriver + : public password_manager::StubPasswordManagerDriver { + public: + MockPasswordManagerDriver() = default; + + MOCK_METHOD0(GetPasswordGenerationManager, + password_manager::PasswordGenerationManager*()); + + private: + DISALLOW_COPY_AND_ASSIGN(MockPasswordManagerDriver); +}; + +class MockPasswordGenerationManager + : public password_manager::PasswordGenerationManager { + public: + MockPasswordGenerationManager(password_manager::PasswordManagerClient* client, + password_manager::PasswordManagerDriver* driver) + : password_manager::PasswordGenerationManager(client, driver) {} + + MOCK_METHOD5(GeneratePassword, + base::string16(const GURL&, + autofill::FormSignature, + autofill::FieldSignature, + uint32_t, + uint32_t*)); + + private: + DISALLOW_COPY_AND_ASSIGN(MockPasswordGenerationManager); +}; + +// Mock modal dialog view used to bypass the need of a valid top level window. +class MockPasswordGenerationDialogView + : public PasswordGenerationDialogViewInterface { + public: + MockPasswordGenerationDialogView() = default; + + MOCK_METHOD1(Show, void(base::string16&)); + + private: + DISALLOW_COPY_AND_ASSIGN(MockPasswordGenerationDialogView); +}; + +PasswordGenerationUIData GetTestGenerationUIData1() { + PasswordGenerationUIData data; + + PasswordForm& form = data.password_form; + form.form_data = autofill::FormData(); + form.form_data.action = GURL("http://www.example1.com/accounts/Login"); + form.form_data.origin = GURL("http://www.example1.com/accounts/LoginAuth"); + + data.generation_element = ASCIIToUTF16("testelement1"); + data.max_length = 10; + + return data; +} + +PasswordGenerationUIData GetTestGenerationUIData2() { + PasswordGenerationUIData data; + + PasswordForm& form = data.password_form; + form.form_data = autofill::FormData(); + form.form_data.action = GURL("http://www.example2.com/accounts/Login"); + form.form_data.origin = GURL("http://www.example2.com/accounts/LoginAuth"); + + data.generation_element = ASCIIToUTF16("testelement2"); + data.max_length = 10; + + return data; +} + +} // namespace + +class PasswordGenerationControllerTest + : public ChromeRenderViewHostTestHarness { + public: + void SetUp() override { + ChromeRenderViewHostTestHarness::SetUp(); + PasswordGenerationControllerImpl::CreateForWebContentsForTesting( + web_contents(), mock_manual_filling_controller_.AsWeakPtr(), + mock_dialog_factory_.Get()); + + mock_password_manager_driver_ = + std::make_unique<NiceMock<MockPasswordManagerDriver>>(); + mock_generation_manager_ = + std::make_unique<NiceMock<MockPasswordGenerationManager>>( + nullptr, mock_password_manager_driver_.get()); + mock_dialog_ = + std::make_unique<NiceMock<MockPasswordGenerationDialogView>>(); + } + + PasswordGenerationController* controller() { + return PasswordGenerationControllerImpl::FromWebContents(web_contents()); + } + + const base::MockCallback< + PasswordGenerationControllerImpl::CreateDialogFactory>& + mock_dialog_factory() { + return mock_dialog_factory_; + } + + protected: + // Sets up mocks needed by the generation flow and signals the + // |PasswordGenerationController| that generation is available. + void InitializeGeneration(const base::string16& password); + + StrictMock<MockManualFillingController> mock_manual_filling_controller_; + + std::unique_ptr<NiceMock<MockPasswordManagerDriver>> + mock_password_manager_driver_; + std::unique_ptr<NiceMock<MockPasswordGenerationManager>> + mock_generation_manager_; + std::unique_ptr<NiceMock<MockPasswordGenerationDialogView>> mock_dialog_; + + private: + NiceMock< + base::MockCallback<PasswordGenerationControllerImpl::CreateDialogFactory>> + mock_dialog_factory_; +}; + +void PasswordGenerationControllerTest::InitializeGeneration( + const base::string16& password) { + ON_CALL(*mock_password_manager_driver_, GetPasswordGenerationManager()) + .WillByDefault(Return(mock_generation_manager_.get())); + + EXPECT_CALL(mock_manual_filling_controller_, + OnAutomaticGenerationStatusChanged(true)); + + controller()->OnAutomaticGenerationStatusChanged( + true, GetTestGenerationUIData1(), + mock_password_manager_driver_->AsWeakPtr()); + + ON_CALL(*mock_generation_manager_, GeneratePassword(_, _, _, _, _)) + .WillByDefault(Return(password)); + + ON_CALL(mock_dialog_factory(), Run) + .WillByDefault(Return(ByMove(std::move(mock_dialog_)))); +} + +TEST_F(PasswordGenerationControllerTest, IsNotRecreatedForSameWebContents) { + PasswordGenerationController* initial_controller = + PasswordGenerationControllerImpl::FromWebContents(web_contents()); + EXPECT_NE(nullptr, initial_controller); + PasswordGenerationControllerImpl::CreateForWebContents(web_contents()); + EXPECT_EQ(PasswordGenerationControllerImpl::FromWebContents(web_contents()), + initial_controller); +} + +TEST_F(PasswordGenerationControllerTest, RelaysAutomaticGenerationAvailable) { + EXPECT_CALL(mock_manual_filling_controller_, + OnAutomaticGenerationStatusChanged(true)); + controller()->OnAutomaticGenerationStatusChanged( + true, GetTestGenerationUIData1(), nullptr); +} + +TEST_F(PasswordGenerationControllerTest, RelaysAutmaticGenerationUnavailable) { + EXPECT_CALL(mock_manual_filling_controller_, + OnAutomaticGenerationStatusChanged(false)); + controller()->OnAutomaticGenerationStatusChanged(false, base::nullopt, + nullptr); +} + +// Tests that if AutomaticGenerationStatusChanged(true) is called for different +// password forms, the form and field signatures used for password generation +// are updated. +TEST_F(PasswordGenerationControllerTest, + UpdatesSignaturesForDifferentGenerationForms) { + // Called twice for different forms. + EXPECT_CALL(mock_manual_filling_controller_, + OnAutomaticGenerationStatusChanged(true)) + .Times(2); + controller()->OnAutomaticGenerationStatusChanged( + true, GetTestGenerationUIData1(), + mock_password_manager_driver_->AsWeakPtr()); + PasswordGenerationUIData new_ui_data = GetTestGenerationUIData2(); + controller()->OnAutomaticGenerationStatusChanged( + true, new_ui_data, mock_password_manager_driver_->AsWeakPtr()); + + autofill::FormSignature form_signature = + autofill::CalculateFormSignature(new_ui_data.password_form.form_data); + autofill::FieldSignature field_signature = + autofill::CalculateFieldSignatureByNameAndType( + new_ui_data.generation_element, "password"); + + MockPasswordGenerationDialogView* raw_dialog_view = mock_dialog_.get(); + + base::string16 generated_password = ASCIIToUTF16("t3stp@ssw0rd"); + EXPECT_CALL(mock_dialog_factory(), Run) + .WillOnce(Return(ByMove(std::move(mock_dialog_)))); + EXPECT_CALL(*mock_password_manager_driver_, GetPasswordGenerationManager()) + .WillOnce(Return(mock_generation_manager_.get())); + EXPECT_CALL(*mock_generation_manager_, + GeneratePassword(_, form_signature, field_signature, + uint32_t(new_ui_data.max_length), _)) + .WillOnce(Return(generated_password)); + EXPECT_CALL(*raw_dialog_view, Show(generated_password)); + controller()->OnGenerationRequested(); +} + +TEST_F(PasswordGenerationControllerTest, RecordsGeneratedPasswordRejected) { + base::string16 test_password = ASCIIToUTF16("t3stp@ssw0rd"); + + InitializeGeneration(test_password); + + base::HistogramTester histogram_tester; + + controller()->OnGenerationRequested(); + controller()->GeneratedPasswordRejected(); + + histogram_tester.ExpectUniqueSample( + "KeyboardAccessory.GeneratedPasswordDialog", false, 1); +} + +TEST_F(PasswordGenerationControllerTest, RecordsGeneratedPasswordAccepted) { + base::string16 test_password = ASCIIToUTF16("t3stp@ssw0rd"); + + InitializeGeneration(test_password); + + base::HistogramTester histogram_tester; + + controller()->OnGenerationRequested(); + controller()->GeneratedPasswordAccepted(test_password); + + histogram_tester.ExpectUniqueSample( + "KeyboardAccessory.GeneratedPasswordDialog", true, 1); +}
diff --git a/chrome/browser/password_manager/password_generation_dialog_view_interface.h b/chrome/browser/password_manager/password_generation_dialog_view_interface.h index 7b1b058..3e64708 100644 --- a/chrome/browser/password_manager/password_generation_dialog_view_interface.h +++ b/chrome/browser/password_manager/password_generation_dialog_view_interface.h
@@ -7,7 +7,7 @@ #include "base/strings/string16.h" -class PasswordAccessoryController; +class PasswordGenerationController; class PasswordGenerationDialogViewInterface { public: @@ -17,10 +17,11 @@ virtual void Show(base::string16& password) = 0; private: - friend class PasswordAccessoryControllerImpl; + friend class PasswordGenerationControllerImpl; + // Factory function used to create a concrete instance of this view. static std::unique_ptr<PasswordGenerationDialogViewInterface> Create( - PasswordAccessoryController* controller); + PasswordGenerationController* controller); }; #endif // CHROME_BROWSER_PASSWORD_MANAGER_PASSWORD_GENERATION_DIALOG_VIEW_INTERFACE_H_
diff --git a/chrome/browser/password_manager/password_manager_browsertest.cc b/chrome/browser/password_manager/password_manager_browsertest.cc index b8d8e49..8081368 100644 --- a/chrome/browser/password_manager/password_manager_browsertest.cc +++ b/chrome/browser/password_manager/password_manager_browsertest.cc
@@ -1549,60 +1549,78 @@ IN_PROC_BROWSER_TEST_F( PasswordManagerBrowserTest, NoPromptForSeperateLoginFormWhenSwitchingFromHttpsToHttp) { - std::string path = "/password/password_form.html"; - GURL https_url(https_test_server().GetURL(path)); - ASSERT_TRUE(https_url.SchemeIs(url::kHttpsScheme)); + for (bool use_new_parsing_for_saving : {false, true}) { + SCOPED_TRACE(testing::Message() << "use_new_parsing_for_saving = " + << use_new_parsing_for_saving); + base::test::ScopedFeatureList scoped_feature_list; + SetNewParsingForSaving(&scoped_feature_list, use_new_parsing_for_saving); - NavigationObserver form_observer(WebContents()); - ui_test_utils::NavigateToURL(browser(), https_url); - form_observer.Wait(); + std::string path = "/password/password_form.html"; + GURL https_url(https_test_server().GetURL(path)); + ASSERT_TRUE(https_url.SchemeIs(url::kHttpsScheme)); - std::string fill_and_submit_redirect = - "document.getElementById('username_redirect').value = 'user';" - "document.getElementById('password_redirect').value = 'password';" - "document.getElementById('submit_redirect').click()"; - ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit_redirect)); + NavigationObserver form_observer(WebContents()); + ui_test_utils::NavigateToURL(browser(), https_url); + form_observer.Wait(); - NavigationObserver redirect_observer(WebContents()); - redirect_observer.SetPathToWaitFor("/password/redirect.html"); - redirect_observer.Wait(); + std::string fill_and_submit_redirect = + "document.getElementById('username_redirect').value = 'user';" + "document.getElementById('password_redirect').value = 'password';" + "document.getElementById('submit_redirect').click()"; + ASSERT_TRUE( + content::ExecuteScript(WebContents(), fill_and_submit_redirect)); - WaitForPasswordStore(); - BubbleObserver prompt_observer(WebContents()); - EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); + NavigationObserver redirect_observer(WebContents()); + redirect_observer.SetPathToWaitFor("/password/redirect.html"); + redirect_observer.Wait(); - // Normally the redirect happens to done.html. Here an attack is simulated - // that hijacks the redirect to a attacker controlled page. - GURL http_url( - embedded_test_server()->GetURL("/password/simple_password.html")); - std::string attacker_redirect = - "window.location.href = '" + http_url.spec() + "';"; - ASSERT_TRUE(content::ExecuteScriptWithoutUserGesture(RenderFrameHost(), - attacker_redirect)); + WaitForPasswordStore(); + BubbleObserver prompt_observer(WebContents()); + EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); - NavigationObserver attacker_observer(WebContents()); - attacker_observer.SetPathToWaitFor("/password/simple_password.html"); - attacker_observer.Wait(); + // Normally the redirect happens to done.html. Here an attack is simulated + // that hijacks the redirect to a attacker controlled page. + GURL http_url( + embedded_test_server()->GetURL("/password/simple_password.html")); + std::string attacker_redirect = + "window.location.href = '" + http_url.spec() + "';"; + ASSERT_TRUE(content::ExecuteScriptWithoutUserGesture(RenderFrameHost(), + attacker_redirect)); - EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); + NavigationObserver attacker_observer(WebContents()); + attacker_observer.SetPathToWaitFor("/password/simple_password.html"); + attacker_observer.Wait(); - std::string fill_and_submit_attacker_form = - "document.getElementById('username_field').value = 'attacker_username';" - "document.getElementById('password_field').value = 'attacker_password';" - "document.getElementById('input_submit_button').click()"; - ASSERT_TRUE( - content::ExecuteScript(WebContents(), fill_and_submit_attacker_form)); + EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); - NavigationObserver done_observer(WebContents()); - done_observer.SetPathToWaitFor("/password/done.html"); - done_observer.Wait(); + std::string fill_and_submit_attacker_form = + "document.getElementById('username_field').value = 'attacker_username';" + "document.getElementById('password_field').value = 'attacker_password';" + "document.getElementById('input_submit_button').click()"; + ASSERT_TRUE( + content::ExecuteScript(WebContents(), fill_and_submit_attacker_form)); - EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); - prompt_observer.AcceptSavePrompt(); + NavigationObserver done_observer(WebContents()); + done_observer.SetPathToWaitFor("/password/done.html"); + done_observer.Wait(); - // Wait for password store and check that credentials are stored. - WaitForPasswordStore(); - CheckThatCredentialsStored("user", "password"); + EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); + prompt_observer.AcceptSavePrompt(); + + // Wait for password store and check that credentials are stored. + WaitForPasswordStore(); + CheckThatCredentialsStored("user", "password"); + + // Password store clearing is required because there are 2 test iterations. + // TODO(https://crbug.com/831123): Remove store clearing when the old parser + // is gone and there is only one iteration in this test. + scoped_refptr<password_manager::TestPasswordStore> password_store = + static_cast<password_manager::TestPasswordStore*>( + PasswordStoreFactory::GetForProfile( + browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) + .get()); + password_store->Clear(); + } } // Tests that after HTTP -> HTTPS migration the credential is autofilled.
diff --git a/chrome/browser/password_manager/password_store_signin_notifier_impl_unittest.cc b/chrome/browser/password_manager/password_store_signin_notifier_impl_unittest.cc index 7c24f2a..37001c9 100644 --- a/chrome/browser/password_manager/password_store_signin_notifier_impl_unittest.cc +++ b/chrome/browser/password_manager/password_store_signin_notifier_impl_unittest.cc
@@ -6,9 +6,7 @@ #include "base/bind.h" #include "chrome/browser/signin/account_fetcher_service_factory.h" -#include "chrome/browser/signin/fake_signin_manager_builder.h" -#include "chrome/browser/signin/identity_manager_factory.h" -#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/signin/identity_test_environment_profile_adaptor.h" #include "chrome/test/base/testing_profile.h" #include "components/password_manager/core/browser/mock_password_store.h" #include "components/signin/core/browser/account_fetcher_service.h" @@ -25,13 +23,12 @@ class PasswordStoreSigninNotifierImplTest : public testing::Test { public: PasswordStoreSigninNotifierImplTest() { - TestingProfile::Builder builder; - builder.AddTestingFactory( - SigninManagerFactory::GetInstance(), - base::BindRepeating(&BuildFakeSigninManagerForTesting)); - testing_profile_.reset(builder.Build().release()); - fake_signin_manager_ = static_cast<FakeSigninManagerForTesting*>( - SigninManagerFactory::GetForProfile(testing_profile_.get())); + testing_profile_ = IdentityTestEnvironmentProfileAdaptor:: + CreateProfileForIdentityTestEnvironment(); + + identity_test_env_adaptor_ = + std::make_unique<IdentityTestEnvironmentProfileAdaptor>( + testing_profile_.get()); store_ = new MockPasswordStore(); } @@ -39,10 +36,15 @@ store_->ShutdownOnUIThread(); } + identity::IdentityTestEnvironment* identity_test_env() { + return identity_test_env_adaptor_->identity_test_env(); + } + protected: content::TestBrowserThreadBundle thread_bundle; std::unique_ptr<TestingProfile> testing_profile_; - FakeSigninManagerForTesting* fake_signin_manager_; // Weak + std::unique_ptr<IdentityTestEnvironmentProfileAdaptor> + identity_test_env_adaptor_; scoped_refptr<MockPasswordStore> store_; }; @@ -51,10 +53,10 @@ TEST_F(PasswordStoreSigninNotifierImplTest, Subscribed) { PasswordStoreSigninNotifierImpl notifier(testing_profile_.get()); notifier.SubscribeToSigninEvents(store_.get()); - fake_signin_manager_->SignIn("accountid", "username"); + identity_test_env()->MakePrimaryAccountAvailable("test@example.com"); testing::Mock::VerifyAndClearExpectations(store_.get()); EXPECT_CALL(*store_, ClearAllGaiaPasswordHash()); - fake_signin_manager_->ForceSignOut(); + identity_test_env()->ClearPrimaryAccount(); notifier.UnsubscribeFromSigninEvents(); } @@ -65,8 +67,8 @@ notifier.SubscribeToSigninEvents(store_.get()); notifier.UnsubscribeFromSigninEvents(); EXPECT_CALL(*store_, ClearAllGaiaPasswordHash()).Times(0); - fake_signin_manager_->SignIn("accountid", "username"); - fake_signin_manager_->ForceSignOut(); + identity_test_env()->MakePrimaryAccountAvailable("test@example.com"); + identity_test_env()->ClearPrimaryAccount(); } // Checks that if a notifier is unsubscribed on sign-in events, then @@ -75,42 +77,28 @@ PasswordStoreSigninNotifierImpl notifier(testing_profile_.get()); notifier.SubscribeToSigninEvents(store_.get()); - identity::IdentityManager* identity_manager = - IdentityManagerFactory::GetForProfileIfExists(testing_profile_.get()); - identity::PrimaryAccountMutator* primary_account_mutator = - identity_manager->GetPrimaryAccountMutator(); - DCHECK(primary_account_mutator); - primary_account_mutator->LegacyStartSigninWithRefreshTokenForPrimaryAccount( - /*refresh_token=*/"refresh_token", - /*gaia_id=*/"primary_account_id", - /*username=*/"username", base::OnceCallback<void(const std::string&)>()); - primary_account_mutator->LegacyCompletePendingPrimaryAccountSignin(); - + identity_test_env()->MakePrimaryAccountAvailable("username"); testing::Mock::VerifyAndClearExpectations(store_.get()); - EXPECT_CALL(*store_, ClearGaiaPasswordHash("username2")); - + auto* identity_manager = identity_test_env()->identity_manager(); AccountFetcherService* account_fetcher_service = AccountFetcherServiceFactory::GetForProfile(testing_profile_.get()); - // This call is necessary to ensure that the account removal is fully - // processed in this testing context. - account_fetcher_service->EnableNetworkFetchesForTest(); identity_manager->GetAccountsMutator()->AddOrUpdateAccount( /*gaia_id=*/"secondary_account_id", /*email=*/"username2", /*refresh_token=*/"refresh_token", /*is_under_advanced_protection=*/false, signin_metrics::SourceForRefreshTokenOperation::kUnknown); + // This call is necessary to ensure that the account removal is fully + // processed in this testing context. + account_fetcher_service->EnableNetworkFetchesForTest(); identity_manager->GetAccountsMutator()->RemoveAccount( "secondary_account_id", signin_metrics::SourceForRefreshTokenOperation::kUserMenu_RemoveAccount); testing::Mock::VerifyAndClearExpectations(store_.get()); EXPECT_CALL(*store_, ClearAllGaiaPasswordHash()); - primary_account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kRemoveAll, - signin_metrics::FORCE_SIGNOUT_ALWAYS_ALLOWED_FOR_TEST, - signin_metrics::SignoutDelete::IGNORE_METRIC); + identity_test_env()->ClearPrimaryAccount(); notifier.UnsubscribeFromSigninEvents(); }
diff --git a/chrome/browser/performance_manager/OWNERS b/chrome/browser/performance_manager/OWNERS new file mode 100644 index 0000000..24d881e8 --- /dev/null +++ b/chrome/browser/performance_manager/OWNERS
@@ -0,0 +1,6 @@ +chrisha@chromium.org +fdoray@chromium.org +siggi@chromium.org + +# TEAM: catan-team@chromium.org +# COMPONENT: Internals>ResourceCoordinator
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_base.cc b/chrome/browser/performance_manager/coordination_unit/coordination_unit_base.cc similarity index 63% rename from services/resource_coordinator/coordination_unit/coordination_unit_base.cc rename to chrome/browser/performance_manager/coordination_unit/coordination_unit_base.cc index 1f45ff2..14fb3ee 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_base.cc +++ b/chrome/browser/performance_manager/coordination_unit/coordination_unit_base.cc
@@ -2,16 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/coordination_unit/coordination_unit_base.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_base.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_graph.h" -#include "services/resource_coordinator/observers/coordination_unit_graph_observer.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.h" +#include "chrome/browser/performance_manager/observers/coordination_unit_graph_observer.h" #include "services/resource_coordinator/public/cpp/coordination_unit_id.h" -namespace resource_coordinator { +namespace performance_manager { -CoordinationUnitBase::CoordinationUnitBase(const CoordinationUnitID& id, - CoordinationUnitGraph* graph) +CoordinationUnitBase::CoordinationUnitBase( + const resource_coordinator::CoordinationUnitID& id, + CoordinationUnitGraph* graph) : graph_(graph), id_(id.type, id.id) {} CoordinationUnitBase::~CoordinationUnitBase() = default; @@ -35,8 +36,9 @@ observers_.RemoveObserver(observer); } -bool CoordinationUnitBase::GetProperty(const mojom::PropertyType property_type, - int64_t* result) const { +bool CoordinationUnitBase::GetProperty( + const resource_coordinator::mojom::PropertyType property_type, + int64_t* result) const { auto value_it = properties_.find(property_type); if (value_it != properties_.end()) { *result = value_it->second; @@ -46,30 +48,34 @@ } int64_t CoordinationUnitBase::GetPropertyOrDefault( - const mojom::PropertyType property_type, int64_t default_value) const { + const resource_coordinator::mojom::PropertyType property_type, + int64_t default_value) const { int64_t value = 0; if (GetProperty(property_type, &value)) return value; return default_value; } -void CoordinationUnitBase::OnEventReceived(mojom::Event event) { +void CoordinationUnitBase::OnEventReceived( + resource_coordinator::mojom::Event event) { for (auto& observer : observers()) observer.OnEventReceived(this, event); } -void CoordinationUnitBase::OnPropertyChanged(mojom::PropertyType property_type, - int64_t value) { +void CoordinationUnitBase::OnPropertyChanged( + resource_coordinator::mojom::PropertyType property_type, + int64_t value) { for (auto& observer : observers()) observer.OnPropertyChanged(this, property_type, value); } -void CoordinationUnitBase::SendEvent(mojom::Event event) { +void CoordinationUnitBase::SendEvent(resource_coordinator::mojom::Event event) { OnEventReceived(event); } -void CoordinationUnitBase::SetProperty(mojom::PropertyType property_type, - int64_t value) { +void CoordinationUnitBase::SetProperty( + resource_coordinator::mojom::PropertyType property_type, + int64_t value) { // The |CoordinationUnitGraphObserver| API specification dictates that // the property is guarranteed to be set on the |CoordinationUnitBase| // and propagated to the appropriate associated |CoordianationUnitBase| @@ -84,4 +90,4 @@ return new_cu->graph()->AddNewCoordinationUnit(std::move(new_cu)); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_base.h b/chrome/browser/performance_manager/coordination_unit/coordination_unit_base.h similarity index 70% rename from services/resource_coordinator/coordination_unit/coordination_unit_base.h rename to chrome/browser/performance_manager/coordination_unit/coordination_unit_base.h index dc297a66..be345327 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_base.h +++ b/chrome/browser/performance_manager/coordination_unit/coordination_unit_base.h
@@ -2,25 +2,26 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_BASE_H_ -#define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_BASE_H_ +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_COORDINATION_UNIT_BASE_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_COORDINATION_UNIT_BASE_H_ +#include <map> #include <memory> #include "base/callback.h" #include "base/macros.h" #include "base/observer_list.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.h" +#include "chrome/browser/performance_manager/observers/coordination_unit_graph_observer.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/public/cpp/bindings/strong_binding.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_graph.h" -#include "services/resource_coordinator/observers/coordination_unit_graph_observer.h" #include "services/resource_coordinator/public/cpp/coordination_unit_types.h" #include "services/resource_coordinator/public/mojom/coordination_unit.mojom.h" #include "services/resource_coordinator/public/mojom/coordination_unit_provider.mojom.h" #include "services/service_manager/public/cpp/service_keepalive.h" -namespace resource_coordinator { +namespace performance_manager { class CoordinationUnitGraph; @@ -29,7 +30,7 @@ // this class and can override shared funtionality when needed. class CoordinationUnitBase { public: - CoordinationUnitBase(const CoordinationUnitID& id, + CoordinationUnitBase(const resource_coordinator::CoordinationUnitID& id, CoordinationUnitGraph* graph); virtual ~CoordinationUnitBase(); @@ -37,12 +38,14 @@ void BeforeDestroyed(); void AddObserver(CoordinationUnitGraphObserver* observer); void RemoveObserver(CoordinationUnitGraphObserver* observer); - bool GetProperty(const mojom::PropertyType property_type, - int64_t* result) const; - int64_t GetPropertyOrDefault(const mojom::PropertyType property_type, - int64_t default_value) const; + bool GetProperty( + const resource_coordinator::mojom::PropertyType property_type, + int64_t* result) const; + int64_t GetPropertyOrDefault( + const resource_coordinator::mojom::PropertyType property_type, + int64_t default_value) const; - const CoordinationUnitID& id() const { return id_; } + const resource_coordinator::CoordinationUnitID& id() const { return id_; } CoordinationUnitGraph* graph() const { return graph_; } const base::ObserverList<CoordinationUnitGraphObserver>::Unchecked& @@ -51,31 +54,34 @@ } void SetPropertyForTesting(int64_t value) { - SetProperty(mojom::PropertyType::kTest, value); + SetProperty(resource_coordinator::mojom::PropertyType::kTest, value); } - const std::map<mojom::PropertyType, int64_t>& properties_for_testing() const { + const std::map<resource_coordinator::mojom::PropertyType, int64_t>& + properties_for_testing() const { return properties_; } protected: - virtual void OnEventReceived(mojom::Event event); - virtual void OnPropertyChanged(mojom::PropertyType property_type, - int64_t value); + virtual void OnEventReceived(resource_coordinator::mojom::Event event); + virtual void OnPropertyChanged( + resource_coordinator::mojom::PropertyType property_type, + int64_t value); - void SendEvent(mojom::Event event); - void SetProperty(mojom::PropertyType property_type, int64_t value); + void SendEvent(resource_coordinator::mojom::Event event); + void SetProperty(resource_coordinator::mojom::PropertyType property_type, + int64_t value); // Passes the ownership of the newly created |new_cu| to its graph. static CoordinationUnitBase* PassOwnershipToGraph( std::unique_ptr<CoordinationUnitBase> new_cu); CoordinationUnitGraph* const graph_; - const CoordinationUnitID id_; + const resource_coordinator::CoordinationUnitID id_; private: base::ObserverList<CoordinationUnitGraphObserver>::Unchecked observers_; - std::map<mojom::PropertyType, int64_t> properties_; + std::map<resource_coordinator::mojom::PropertyType, int64_t> properties_; DISALLOW_COPY_AND_ASSIGN(CoordinationUnitBase); }; @@ -87,7 +93,7 @@ public MojoInterfaceClass { public: static CoordinationUnitClass* Create( - const CoordinationUnitID& id, + const resource_coordinator::CoordinationUnitID& id, CoordinationUnitGraph* graph, std::unique_ptr<service_manager::ServiceKeepaliveRef> keepalive_ref) { std::unique_ptr<CoordinationUnitClass> new_cu = @@ -110,7 +116,7 @@ } CoordinationUnitInterface( - const CoordinationUnitID& id, + const resource_coordinator::CoordinationUnitID& id, CoordinationUnitGraph* graph, std::unique_ptr<service_manager::ServiceKeepaliveRef> keepalive_ref) @@ -133,7 +139,7 @@ static CoordinationUnitClass* GetCoordinationUnitByID( CoordinationUnitGraph* graph, - const CoordinationUnitID cu_id) { + const resource_coordinator::CoordinationUnitID cu_id) { DCHECK(cu_id.type == CoordinationUnitClass::Type()); auto* cu = graph->GetCoordinationUnitByID(cu_id); if (!cu) @@ -151,6 +157,6 @@ DISALLOW_COPY_AND_ASSIGN(CoordinationUnitInterface); }; -} // namespace resource_coordinator +} // namespace performance_manager -#endif // SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_BASE_H_ +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_COORDINATION_UNIT_BASE_H_
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_base_unittest.cc b/chrome/browser/performance_manager/coordination_unit/coordination_unit_base_unittest.cc similarity index 84% rename from services/resource_coordinator/coordination_unit/coordination_unit_base_unittest.cc rename to chrome/browser/performance_manager/coordination_unit/coordination_unit_base_unittest.cc index 78e03e9..57246da 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_base_unittest.cc +++ b/chrome/browser/performance_manager/coordination_unit/coordination_unit_base_unittest.cc
@@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/coordination_unit/coordination_unit_base.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_provider_impl.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_test_harness.h" -#include "services/resource_coordinator/coordination_unit/mock_coordination_unit_graphs.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_base.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_provider_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.h" +#include "chrome/browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" #include "services/resource_coordinator/public/mojom/coordination_unit.mojom.h" #include "testing/gtest/include/gtest/gtest.h" -namespace resource_coordinator { +namespace performance_manager { namespace { @@ -26,14 +26,14 @@ // An empty value should be returned if property is not found int64_t test_value; - EXPECT_FALSE( - coordination_unit->GetProperty(mojom::PropertyType::kTest, &test_value)); + EXPECT_FALSE(coordination_unit->GetProperty( + resource_coordinator::mojom::PropertyType::kTest, &test_value)); // Perform a valid storage property set coordination_unit->SetPropertyForTesting(41); EXPECT_EQ(1u, coordination_unit->properties_for_testing().size()); - EXPECT_TRUE( - coordination_unit->GetProperty(mojom::PropertyType::kTest, &test_value)); + EXPECT_TRUE(coordination_unit->GetProperty( + resource_coordinator::mojom::PropertyType::kTest, &test_value)); EXPECT_EQ(41, test_value); } @@ -129,4 +129,4 @@ cu_graph.other_process.get())); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_graph.cc b/chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.cc similarity index 83% rename from services/resource_coordinator/coordination_unit/coordination_unit_graph.cc rename to chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.cc index af71a9e..3630d519 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_graph.cc +++ b/chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.cc
@@ -2,20 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/coordination_unit/coordination_unit_graph.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.h" #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/macros.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_base.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_provider_impl.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/system_coordination_unit_impl.h" -#include "services/resource_coordinator/observers/coordination_unit_graph_observer.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_base.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_provider_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/observers/coordination_unit_graph_observer.h" #include "services/resource_coordinator/public/cpp/coordination_unit_types.h" #include "services/service_manager/public/cpp/bind_source_info.h" #include "services/service_manager/public/cpp/binder_registry.h" @@ -24,11 +24,12 @@ class UkmEntryBuilder; } // namespace ukm -namespace resource_coordinator { +namespace performance_manager { CoordinationUnitGraph::CoordinationUnitGraph() - : system_coordination_unit_id_(CoordinationUnitType::kSystem, - CoordinationUnitID::RANDOM_ID) {} + : system_coordination_unit_id_( + resource_coordinator::CoordinationUnitType::kSystem, + resource_coordinator::CoordinationUnitID::RANDOM_ID) {} CoordinationUnitGraph::~CoordinationUnitGraph() { // Because the graph has ownership of the CUs, and because the process CUs @@ -78,20 +79,20 @@ } FrameCoordinationUnitImpl* CoordinationUnitGraph::CreateFrameCoordinationUnit( - const CoordinationUnitID& id, + const resource_coordinator::CoordinationUnitID& id, std::unique_ptr<service_manager::ServiceKeepaliveRef> service_ref) { return FrameCoordinationUnitImpl::Create(id, this, std::move(service_ref)); } PageCoordinationUnitImpl* CoordinationUnitGraph::CreatePageCoordinationUnit( - const CoordinationUnitID& id, + const resource_coordinator::CoordinationUnitID& id, std::unique_ptr<service_manager::ServiceKeepaliveRef> service_ref) { return PageCoordinationUnitImpl::Create(id, this, std::move(service_ref)); } ProcessCoordinationUnitImpl* CoordinationUnitGraph::CreateProcessCoordinationUnit( - const CoordinationUnitID& id, + const resource_coordinator::CoordinationUnitID& id, std::unique_ptr<service_manager::ServiceKeepaliveRef> service_ref) { return ProcessCoordinationUnitImpl::Create(id, this, std::move(service_ref)); } @@ -110,7 +111,7 @@ } CoordinationUnitBase* CoordinationUnitGraph::GetCoordinationUnitByID( - const CoordinationUnitID cu_id) { + const resource_coordinator::CoordinationUnitID cu_id) { const auto& it = coordination_units_.find(cu_id); if (it == coordination_units_.end()) return nullptr; @@ -187,4 +188,4 @@ return ret; } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_graph.h b/chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.h similarity index 84% rename from services/resource_coordinator/coordination_unit/coordination_unit_graph.h rename to chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.h index 4cf60a54..bf7d307 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_graph.h +++ b/chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.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 SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_GRAPH_H_ -#define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_GRAPH_H_ +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_COORDINATION_UNIT_GRAPH_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_COORDINATION_UNIT_GRAPH_H_ #include <stdint.h> @@ -25,7 +25,7 @@ struct BindSourceInfo; } // namespace service_manager -namespace resource_coordinator { +namespace performance_manager { class CoordinationUnitBase; class CoordinationUnitGraphObserver; @@ -59,13 +59,13 @@ CoordinationUnitBase* coordination_unit); FrameCoordinationUnitImpl* CreateFrameCoordinationUnit( - const CoordinationUnitID& id, + const resource_coordinator::CoordinationUnitID& id, std::unique_ptr<service_manager::ServiceKeepaliveRef> service_ref); PageCoordinationUnitImpl* CreatePageCoordinationUnit( - const CoordinationUnitID& id, + const resource_coordinator::CoordinationUnitID& id, std::unique_ptr<service_manager::ServiceKeepaliveRef> service_ref); ProcessCoordinationUnitImpl* CreateProcessCoordinationUnit( - const CoordinationUnitID& id, + const resource_coordinator::CoordinationUnitID& id, std::unique_ptr<service_manager::ServiceKeepaliveRef> service_ref); SystemCoordinationUnitImpl* FindOrCreateSystemCoordinationUnit( std::unique_ptr<service_manager::ServiceKeepaliveRef> service_ref); @@ -77,7 +77,8 @@ // Retrieves the process CU with PID |pid|, if any. ProcessCoordinationUnitImpl* GetProcessCoordinationUnitByPid( base::ProcessId pid); - CoordinationUnitBase* GetCoordinationUnitByID(const CoordinationUnitID cu_id); + CoordinationUnitBase* GetCoordinationUnitByID( + const resource_coordinator::CoordinationUnitID cu_id); std::vector<std::unique_ptr<CoordinationUnitGraphObserver>>& observers_for_testing() { @@ -85,7 +86,7 @@ } private: - using CUIDMap = std::unordered_map<CoordinationUnitID, + using CUIDMap = std::unordered_map<resource_coordinator::CoordinationUnitID, std::unique_ptr<CoordinationUnitBase>>; using ProcessByPidMap = std::unordered_map<base::ProcessId, ProcessCoordinationUnitImpl*>; @@ -104,7 +105,7 @@ template <typename CUType> std::vector<CUType*> GetAllCoordinationUnitsOfType(); - CoordinationUnitID system_coordination_unit_id_; + resource_coordinator::CoordinationUnitID system_coordination_unit_id_; CUIDMap coordination_units_; ProcessByPidMap processes_by_pid_; std::vector<std::unique_ptr<CoordinationUnitGraphObserver>> observers_; @@ -116,6 +117,6 @@ DISALLOW_COPY_AND_ASSIGN(CoordinationUnitGraph); }; -} // namespace resource_coordinator +} // namespace performance_manager -#endif // SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_GRAPH_H_ +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_COORDINATION_UNIT_GRAPH_H_
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_graph_unittest.cc b/chrome/browser/performance_manager/coordination_unit/coordination_unit_graph_unittest.cc similarity index 82% rename from services/resource_coordinator/coordination_unit/coordination_unit_graph_unittest.cc rename to chrome/browser/performance_manager/coordination_unit/coordination_unit_graph_unittest.cc index 84929d3..0d10bd6 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_graph_unittest.cc +++ b/chrome/browser/performance_manager/coordination_unit/coordination_unit_graph_unittest.cc
@@ -2,21 +2,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/coordination_unit/coordination_unit_graph.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/mock_coordination_unit_graphs.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/system_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl.h" #include "testing/gtest/include/gtest/gtest.h" -namespace resource_coordinator { +namespace performance_manager { namespace { ProcessCoordinationUnitImpl* CreateProcessCU(CoordinationUnitGraph* graph) { return graph->CreateProcessCoordinationUnit( - CoordinationUnitID(CoordinationUnitType::kProcess, - CoordinationUnitID::RANDOM_ID), + resource_coordinator::CoordinationUnitID( + resource_coordinator::CoordinationUnitType::kProcess, + resource_coordinator::CoordinationUnitID::RANDOM_ID), nullptr); } @@ -117,4 +118,4 @@ EXPECT_NE(nullptr, pages[1]); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_introspector_impl.cc b/chrome/browser/performance_manager/coordination_unit/coordination_unit_introspector_impl.cc similarity index 72% rename from services/resource_coordinator/coordination_unit/coordination_unit_introspector_impl.cc rename to chrome/browser/performance_manager/coordination_unit/coordination_unit_introspector_impl.cc index f8b4929..b40c96f 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_introspector_impl.cc +++ b/chrome/browser/performance_manager/coordination_unit/coordination_unit_introspector_impl.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 "services/resource_coordinator/coordination_unit/coordination_unit_introspector_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_introspector_impl.h" #include <set> #include <utility> @@ -10,17 +10,17 @@ #include "base/process/process_handle.h" #include "base/time/time.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_graph.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" #include "services/service_manager/public/cpp/bind_source_info.h" namespace { -using resource_coordinator::ProcessCoordinationUnitImpl; -using resource_coordinator::PageCoordinationUnitImpl; -using resource_coordinator::FrameCoordinationUnitImpl; +using performance_manager::FrameCoordinationUnitImpl; +using performance_manager::PageCoordinationUnitImpl; +using performance_manager::ProcessCoordinationUnitImpl; // Returns true iff the given |process| is responsible for hosting the // main-frame of the given |page|. @@ -37,7 +37,7 @@ } // namespace -namespace resource_coordinator { +namespace performance_manager { CoordinationUnitIntrospectorImpl::CoordinationUnitIntrospectorImpl( CoordinationUnitGraph* graph) @@ -52,10 +52,12 @@ graph_->GetAllProcessCoordinationUnits(); for (auto* process_cu : process_cus) { int64_t pid; - if (!process_cu->GetProperty(mojom::PropertyType::kPID, &pid)) + if (!process_cu->GetProperty( + resource_coordinator::mojom::PropertyType::kPID, &pid)) continue; - mojom::ProcessInfoPtr process_info(mojom::ProcessInfo::New()); + resource_coordinator::mojom::ProcessInfoPtr process_info( + resource_coordinator::mojom::ProcessInfo::New()); process_info->pid = base::checked_cast<base::ProcessId>(pid); DCHECK_NE(base::kNullProcessId, process_info->pid); process_info->launch_time = process_cu->launch_time(); @@ -67,7 +69,8 @@ if (page_cu->GetProperty( resource_coordinator::mojom::PropertyType::kUKMSourceId, &ukm_source_id)) { - mojom::PageInfoPtr page_info(mojom::PageInfo::New()); + resource_coordinator::mojom::PageInfoPtr page_info( + resource_coordinator::mojom::PageInfo::New()); page_info->ukm_source_id = ukm_source_id; page_info->tab_id = page_cu->id().id; page_info->hosts_main_frame = HostsMainFrame(process_cu, page_cu); @@ -90,4 +93,4 @@ bindings_.AddBinding(this, std::move(request)); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_introspector_impl.h b/chrome/browser/performance_manager/coordination_unit/coordination_unit_introspector_impl.h similarity index 62% rename from services/resource_coordinator/coordination_unit/coordination_unit_introspector_impl.h rename to chrome/browser/performance_manager/coordination_unit/coordination_unit_introspector_impl.h index ad54257..cec5c5a 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_introspector_impl.h +++ b/chrome/browser/performance_manager/coordination_unit/coordination_unit_introspector_impl.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_INTROSPECTOR_IMPL_H_ -#define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_INTROSPECTOR_IMPL_H_ +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_COORDINATION_UNIT_INTROSPECTOR_IMPL_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_COORDINATION_UNIT_INTROSPECTOR_IMPL_H_ #include "mojo/public/cpp/bindings/binding_set.h" #include "services/resource_coordinator/public/mojom/coordination_unit_introspector.mojom.h" @@ -13,12 +13,12 @@ struct BindSourceInfo; } // namespace service_manager -namespace resource_coordinator { +namespace performance_manager { class CoordinationUnitGraph; class CoordinationUnitIntrospectorImpl - : public mojom::CoordinationUnitIntrospector { + : public resource_coordinator::mojom::CoordinationUnitIntrospector { public: explicit CoordinationUnitIntrospectorImpl(CoordinationUnitGraph* graph); ~CoordinationUnitIntrospectorImpl() override; @@ -27,16 +27,17 @@ resource_coordinator::mojom::CoordinationUnitIntrospectorRequest request, const service_manager::BindSourceInfo& source_info); - // Overridden from mojom::CoordinationUnitIntrospector: + // Overridden from resource_coordinator::mojom::CoordinationUnitIntrospector: void GetProcessToURLMap(GetProcessToURLMapCallback callback) override; private: CoordinationUnitGraph* const graph_; - mojo::BindingSet<mojom::CoordinationUnitIntrospector> bindings_; + mojo::BindingSet<resource_coordinator::mojom::CoordinationUnitIntrospector> + bindings_; DISALLOW_COPY_AND_ASSIGN(CoordinationUnitIntrospectorImpl); }; -} // namespace resource_coordinator +} // namespace performance_manager -#endif // SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_INTROSPECTOR_IMPL_H_ +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_COORDINATION_UNIT_INTROSPECTOR_IMPL_H_
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_provider_impl.cc b/chrome/browser/performance_manager/coordination_unit/coordination_unit_provider_impl.cc similarity index 75% rename from services/resource_coordinator/coordination_unit/coordination_unit_provider_impl.cc rename to chrome/browser/performance_manager/coordination_unit/coordination_unit_provider_impl.cc index 75e75dc..32d374e 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_provider_impl.cc +++ b/chrome/browser/performance_manager/coordination_unit/coordination_unit_provider_impl.cc
@@ -2,20 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/coordination_unit/coordination_unit_provider_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_provider_impl.h" #include <memory> #include <utility> #include "base/bind.h" #include "base/macros.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/system_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl.h" #include "services/service_manager/public/cpp/bind_source_info.h" -namespace resource_coordinator { +namespace performance_manager { CoordinationUnitProviderImpl::CoordinationUnitProviderImpl( service_manager::ServiceKeepalive* service_keepalive, @@ -34,8 +34,8 @@ } void CoordinationUnitProviderImpl::CreateFrameCoordinationUnit( - mojom::FrameCoordinationUnitRequest request, - const CoordinationUnitID& id) { + resource_coordinator::mojom::FrameCoordinationUnitRequest request, + const resource_coordinator::CoordinationUnitID& id) { FrameCoordinationUnitImpl* frame_cu = coordination_unit_graph_->CreateFrameCoordinationUnit( id, service_keepalive_->CreateRef()); @@ -49,8 +49,8 @@ } void CoordinationUnitProviderImpl::CreatePageCoordinationUnit( - mojom::PageCoordinationUnitRequest request, - const CoordinationUnitID& id) { + resource_coordinator::mojom::PageCoordinationUnitRequest request, + const resource_coordinator::CoordinationUnitID& id) { PageCoordinationUnitImpl* page_cu = coordination_unit_graph_->CreatePageCoordinationUnit( id, service_keepalive_->CreateRef()); @@ -64,8 +64,8 @@ } void CoordinationUnitProviderImpl::CreateProcessCoordinationUnit( - mojom::ProcessCoordinationUnitRequest request, - const CoordinationUnitID& id) { + resource_coordinator::mojom::ProcessCoordinationUnitRequest request, + const resource_coordinator::CoordinationUnitID& id) { ProcessCoordinationUnitImpl* process_cu = coordination_unit_graph_->CreateProcessCoordinationUnit( id, service_keepalive_->CreateRef()); @@ -92,4 +92,4 @@ bindings_.AddBinding(this, std::move(request)); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_provider_impl.h b/chrome/browser/performance_manager/coordination_unit/coordination_unit_provider_impl.h similarity index 63% rename from services/resource_coordinator/coordination_unit/coordination_unit_provider_impl.h rename to chrome/browser/performance_manager/coordination_unit/coordination_unit_provider_impl.h index 5bac980..4706bd8 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_provider_impl.h +++ b/chrome/browser/performance_manager/coordination_unit/coordination_unit_provider_impl.h
@@ -2,25 +2,26 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_PROVIDER_IMPL_H_ -#define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_PROVIDER_IMPL_H_ +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_COORDINATION_UNIT_PROVIDER_IMPL_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_COORDINATION_UNIT_PROVIDER_IMPL_H_ #include <memory> #include <vector> +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "mojo/public/cpp/bindings/interface_request.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_graph.h" #include "services/resource_coordinator/public/mojom/coordination_unit_provider.mojom.h" #include "services/service_manager/public/cpp/service_keepalive.h" namespace service_manager { struct BindSourceInfo; -} // service_manager +} // namespace service_manager -namespace resource_coordinator { +namespace performance_manager { -class CoordinationUnitProviderImpl : public mojom::CoordinationUnitProvider { +class CoordinationUnitProviderImpl + : public resource_coordinator::mojom::CoordinationUnitProvider { public: CoordinationUnitProviderImpl( service_manager::ServiceKeepalive* service_keepalive, @@ -33,16 +34,16 @@ void OnConnectionError(CoordinationUnitBase* coordination_unit); - // Overridden from mojom::CoordinationUnitProvider: + // Overridden from resource_coordinator::mojom::CoordinationUnitProvider: void CreateFrameCoordinationUnit( resource_coordinator::mojom::FrameCoordinationUnitRequest request, - const CoordinationUnitID& id) override; + const resource_coordinator::CoordinationUnitID& id) override; void CreatePageCoordinationUnit( resource_coordinator::mojom::PageCoordinationUnitRequest request, - const CoordinationUnitID& id) override; + const resource_coordinator::CoordinationUnitID& id) override; void CreateProcessCoordinationUnit( resource_coordinator::mojom::ProcessCoordinationUnitRequest request, - const CoordinationUnitID& id) override; + const resource_coordinator::CoordinationUnitID& id) override; void GetSystemCoordinationUnit( resource_coordinator::mojom::SystemCoordinationUnitRequest request) override; @@ -51,11 +52,12 @@ service_manager::ServiceKeepalive* const service_keepalive_; std::unique_ptr<service_manager::ServiceKeepaliveRef> keepalive_ref_; CoordinationUnitGraph* coordination_unit_graph_; - mojo::BindingSet<mojom::CoordinationUnitProvider> bindings_; + mojo::BindingSet<resource_coordinator::mojom::CoordinationUnitProvider> + bindings_; DISALLOW_COPY_AND_ASSIGN(CoordinationUnitProviderImpl); }; -} // namespace resource_coordinator +} // namespace performance_manager -#endif // SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_PROVIDER_IMPL_H_ +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_COORDINATION_UNIT_PROVIDER_IMPL_H_
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_test_harness.cc b/chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.cc similarity index 82% rename from services/resource_coordinator/coordination_unit/coordination_unit_test_harness.cc rename to chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.cc index cfa7953..e71cd7d 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_test_harness.cc +++ b/chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.cc
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/coordination_unit/coordination_unit_test_harness.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.h" #include "base/bind.h" #include "base/run_loop.h" -namespace resource_coordinator { +namespace performance_manager { CoordinationUnitTestHarness::CoordinationUnitTestHarness() : task_env_(base::test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME, @@ -22,4 +22,4 @@ base::RunLoop().RunUntilIdle(); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_test_harness.h b/chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.h similarity index 68% rename from services/resource_coordinator/coordination_unit/coordination_unit_test_harness.h rename to chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.h index ece34575..b0dca41f 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_test_harness.h +++ b/chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.h
@@ -2,23 +2,26 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_TEST_HARNESS_H_ -#define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_TEST_HARNESS_H_ +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_COORDINATION_UNIT_TEST_HARNESS_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_COORDINATION_UNIT_TEST_HARNESS_H_ #include <stdint.h> #include <string> #include "base/test/scoped_task_environment.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_base.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_graph.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_provider_impl.h" -#include "services/resource_coordinator/coordination_unit/system_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_base.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_provider_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl.h" #include "services/service_manager/public/cpp/service_keepalive.h" #include "testing/gtest/include/gtest/gtest.h" namespace resource_coordinator { - struct CoordinationUnitID; +} // namespace resource_coordinator + +namespace performance_manager { + class SystemCoordinationUnitImpl; template <class CoordinationUnitClass> @@ -26,13 +29,15 @@ public: static TestCoordinationUnitWrapper<CoordinationUnitClass> Create( CoordinationUnitGraph* graph) { - CoordinationUnitID cu_id(CoordinationUnitClass::Type(), - CoordinationUnitID::RANDOM_ID); + resource_coordinator::CoordinationUnitID cu_id( + CoordinationUnitClass::Type(), + resource_coordinator::CoordinationUnitID::RANDOM_ID); return TestCoordinationUnitWrapper<CoordinationUnitClass>( CoordinationUnitClass::Create(cu_id, graph, nullptr)); } - TestCoordinationUnitWrapper(CoordinationUnitClass* impl) : impl_(impl) { + explicit TestCoordinationUnitWrapper(CoordinationUnitClass* impl) + : impl_(impl) { DCHECK(impl); } ~TestCoordinationUnitWrapper() { reset(); } @@ -64,7 +69,7 @@ template <class CoordinationUnitClass> TestCoordinationUnitWrapper<CoordinationUnitClass> CreateCoordinationUnit( - CoordinationUnitID cu_id) { + resource_coordinator::CoordinationUnitID cu_id) { return TestCoordinationUnitWrapper<CoordinationUnitClass>( CoordinationUnitClass::Create(cu_id, coordination_unit_graph(), service_keepalive_.CreateRef())); @@ -72,8 +77,9 @@ template <class CoordinationUnitClass> TestCoordinationUnitWrapper<CoordinationUnitClass> CreateCoordinationUnit() { - CoordinationUnitID cu_id(CoordinationUnitClass::Type(), - CoordinationUnitID::RANDOM_ID); + resource_coordinator::CoordinationUnitID cu_id( + CoordinationUnitClass::Type(), + resource_coordinator::CoordinationUnitID::RANDOM_ID); return CreateCoordinationUnit<CoordinationUnitClass>(cu_id); } @@ -88,9 +94,7 @@ void TearDown() override; protected: - base::test::ScopedTaskEnvironment& task_env() { - return task_env_; - } + base::test::ScopedTaskEnvironment& task_env() { return task_env_; } CoordinationUnitGraph* coordination_unit_graph() { return &coordination_unit_graph_; } @@ -103,6 +107,6 @@ CoordinationUnitProviderImpl provider_; }; -} // namespace resource_coordinator +} // namespace performance_manager -#endif // SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_TEST_HARNESS_H_ +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_COORDINATION_UNIT_TEST_HARNESS_H_
diff --git a/services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.cc b/chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.cc similarity index 74% rename from services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.cc rename to chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.cc index fb96641..ca2e913 100644 --- a/services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.cc +++ b/chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.cc
@@ -2,17 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" -#include "services/resource_coordinator/observers/coordination_unit_graph_observer.h" -#include "services/resource_coordinator/resource_coordinator_clock.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/observers/coordination_unit_graph_observer.h" +#include "chrome/browser/performance_manager/resource_coordinator_clock.h" -namespace resource_coordinator { +namespace performance_manager { FrameCoordinationUnitImpl::FrameCoordinationUnitImpl( - const CoordinationUnitID& id, + const resource_coordinator::CoordinationUnitID& id, CoordinationUnitGraph* graph, std::unique_ptr<service_manager::ServiceKeepaliveRef> keepalive_ref) : CoordinationUnitInterface(id, graph, std::move(keepalive_ref)), @@ -20,7 +20,8 @@ page_coordination_unit_(nullptr), process_coordination_unit_(nullptr) { for (size_t i = 0; i < base::size(intervention_policy_); ++i) - intervention_policy_[i] = mojom::InterventionPolicy::kUnknown; + intervention_policy_[i] = + resource_coordinator::mojom::InterventionPolicy::kUnknown; } FrameCoordinationUnitImpl::~FrameCoordinationUnitImpl() { @@ -34,7 +35,8 @@ child_frame->RemoveParentFrame(this); } -void FrameCoordinationUnitImpl::SetProcess(const CoordinationUnitID& cu_id) { +void FrameCoordinationUnitImpl::SetProcess( + const resource_coordinator::CoordinationUnitID& cu_id) { ProcessCoordinationUnitImpl* process_cu = ProcessCoordinationUnitImpl::GetCoordinationUnitByID(graph_, cu_id); if (!process_cu) @@ -44,7 +46,8 @@ process_cu->AddFrame(this); } -void FrameCoordinationUnitImpl::AddChildFrame(const CoordinationUnitID& cu_id) { +void FrameCoordinationUnitImpl::AddChildFrame( + const resource_coordinator::CoordinationUnitID& cu_id) { DCHECK(cu_id != id()); FrameCoordinationUnitImpl* frame_cu = FrameCoordinationUnitImpl::GetCoordinationUnitByID(graph_, cu_id); @@ -61,7 +64,7 @@ } void FrameCoordinationUnitImpl::RemoveChildFrame( - const CoordinationUnitID& cu_id) { + const resource_coordinator::CoordinationUnitID& cu_id) { DCHECK(cu_id != id()); FrameCoordinationUnitImpl* frame_cu = FrameCoordinationUnitImpl::GetCoordinationUnitByID(graph_, cu_id); @@ -73,14 +76,16 @@ } void FrameCoordinationUnitImpl::SetNetworkAlmostIdle(bool idle) { - SetProperty(mojom::PropertyType::kNetworkAlmostIdle, idle); + SetProperty(resource_coordinator::mojom::PropertyType::kNetworkAlmostIdle, + idle); } -void FrameCoordinationUnitImpl::SetLifecycleState(mojom::LifecycleState state) { +void FrameCoordinationUnitImpl::SetLifecycleState( + resource_coordinator::mojom::LifecycleState state) { if (state == lifecycle_state_) return; - mojom::LifecycleState old_state = lifecycle_state_; + resource_coordinator::mojom::LifecycleState old_state = lifecycle_state_; lifecycle_state_ = state; // Notify parents of this change. @@ -96,24 +101,26 @@ } void FrameCoordinationUnitImpl::SetInterventionPolicy( - mojom::PolicyControlledIntervention intervention, - mojom::InterventionPolicy policy) { + resource_coordinator::mojom::PolicyControlledIntervention intervention, + resource_coordinator::mojom::InterventionPolicy policy) { size_t i = static_cast<size_t>(intervention); DCHECK_LT(i, base::size(intervention_policy_)); // This can only be called to set a policy, but not to revert a policy to the // unset state. - DCHECK_NE(mojom::InterventionPolicy::kUnknown, policy); + DCHECK_NE(resource_coordinator::mojom::InterventionPolicy::kUnknown, policy); // We expect intervention policies to be initially set in order, and rely on // that as a synchronization primitive. Ensure this is the case. DCHECK(i == 0 || - intervention_policy_[i - 1] != mojom::InterventionPolicy::kUnknown); + intervention_policy_[i - 1] != + resource_coordinator::mojom::InterventionPolicy::kUnknown); if (policy == intervention_policy_[i]) return; // Only notify of actual changes. - mojom::InterventionPolicy old_policy = intervention_policy_[i]; + resource_coordinator::mojom::InterventionPolicy old_policy = + intervention_policy_[i]; intervention_policy_[i] = policy; if (auto* page_cu = GetPageCoordinationUnit()) { page_cu->OnFrameInterventionPolicyChanged(this, intervention, old_policy, @@ -122,7 +129,8 @@ } void FrameCoordinationUnitImpl::OnNonPersistentNotificationCreated() { - SendEvent(mojom::Event::kNonPersistentNotificationCreated); + SendEvent( + resource_coordinator::mojom::Event::kNonPersistentNotificationCreated); } FrameCoordinationUnitImpl* @@ -153,34 +161,39 @@ for (size_t i = 0; i < base::size(intervention_policy_); ++i) { if (!seen_unset_policy) { seen_unset_policy = - intervention_policy_[i] != mojom::InterventionPolicy::kUnknown; + intervention_policy_[i] != + resource_coordinator::mojom::InterventionPolicy::kUnknown; } else { // Once a first unset policy is seen, all subsequent policies must be // unset. - DCHECK_NE(mojom::InterventionPolicy::kUnknown, intervention_policy_[i]); + DCHECK_NE(resource_coordinator::mojom::InterventionPolicy::kUnknown, + intervention_policy_[i]); } } #endif return intervention_policy_[base::size(intervention_policy_) - 1] != - mojom::InterventionPolicy::kUnknown; -} // namespace resource_coordinator + resource_coordinator::mojom::InterventionPolicy::kUnknown; +} // namespace performance_manager void FrameCoordinationUnitImpl::SetAllInterventionPoliciesForTesting( - mojom::InterventionPolicy policy) { + resource_coordinator::mojom::InterventionPolicy policy) { for (size_t i = 0; i < base::size(intervention_policy_); ++i) { - SetInterventionPolicy(static_cast<mojom::PolicyControlledIntervention>(i), - policy); + SetInterventionPolicy( + static_cast<resource_coordinator::mojom::PolicyControlledIntervention>( + i), + policy); } } -void FrameCoordinationUnitImpl::OnEventReceived(mojom::Event event) { +void FrameCoordinationUnitImpl::OnEventReceived( + resource_coordinator::mojom::Event event) { for (auto& observer : observers()) observer.OnFrameEventReceived(this, event); } void FrameCoordinationUnitImpl::OnPropertyChanged( - mojom::PropertyType property_type, + resource_coordinator::mojom::PropertyType property_type, int64_t value) { for (auto& observer : observers()) observer.OnFramePropertyChanged(this, property_type, value); @@ -249,4 +262,4 @@ process_coordination_unit_ = nullptr; } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h b/chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h new file mode 100644 index 0000000..db0e54f --- /dev/null +++ b/chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h
@@ -0,0 +1,123 @@ +// Copyright 2017 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_PERFORMANCE_MANAGER_COORDINATION_UNIT_FRAME_COORDINATION_UNIT_IMPL_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_FRAME_COORDINATION_UNIT_IMPL_H_ + +#include "base/macros.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_base.h" + +namespace performance_manager { + +class PageCoordinationUnitImpl; +class ProcessCoordinationUnitImpl; + +// Frame Coordination Units form a tree structure, each FrameCoordinationUnit at +// most has one parent that is a FrameCoordinationUnit. +// A Frame Coordination Unit will have parents only if navigation committed. +class FrameCoordinationUnitImpl + : public CoordinationUnitInterface< + FrameCoordinationUnitImpl, + resource_coordinator::mojom::FrameCoordinationUnit, + resource_coordinator::mojom::FrameCoordinationUnitRequest> { + public: + static resource_coordinator::CoordinationUnitType Type() { + return resource_coordinator::CoordinationUnitType::kFrame; + } + + FrameCoordinationUnitImpl( + const resource_coordinator::CoordinationUnitID& id, + CoordinationUnitGraph* graph, + std::unique_ptr<service_manager::ServiceKeepaliveRef> keepalive_ref); + ~FrameCoordinationUnitImpl() override; + + // FrameCoordinationUnit implementation. + void SetProcess( + const resource_coordinator::CoordinationUnitID& cu_id) override; + void AddChildFrame( + const resource_coordinator::CoordinationUnitID& cu_id) override; + void RemoveChildFrame( + const resource_coordinator::CoordinationUnitID& cu_id) override; + void SetNetworkAlmostIdle(bool idle) override; + void SetLifecycleState( + resource_coordinator::mojom::LifecycleState state) override; + void SetHasNonEmptyBeforeUnload(bool has_nonempty_beforeunload) override; + void SetInterventionPolicy( + resource_coordinator::mojom::PolicyControlledIntervention intervention, + resource_coordinator::mojom::InterventionPolicy policy) override; + void OnNonPersistentNotificationCreated() override; + + FrameCoordinationUnitImpl* GetParentFrameCoordinationUnit() const; + PageCoordinationUnitImpl* GetPageCoordinationUnit() const; + ProcessCoordinationUnitImpl* GetProcessCoordinationUnit() const; + bool IsMainFrame() const; + + resource_coordinator::mojom::LifecycleState lifecycle_state() const { + return lifecycle_state_; + } + bool has_nonempty_beforeunload() const { return has_nonempty_beforeunload_; } + + // Returns true if all intervention policies have been set for this frame. + bool AreAllInterventionPoliciesSet() const; + + const std::set<FrameCoordinationUnitImpl*>& + child_frame_coordination_units_for_testing() const { + return child_frame_coordination_units_; + } + + // Sets the same policy for all intervention types in this frame. Causes + // Page::OnFrameInterventionPolicyChanged to be invoked. + void SetAllInterventionPoliciesForTesting( + resource_coordinator::mojom::InterventionPolicy policy); + + private: + friend class PageCoordinationUnitImpl; + friend class ProcessCoordinationUnitImpl; + + // CoordinationUnitInterface implementation. + void OnEventReceived(resource_coordinator::mojom::Event event) override; + void OnPropertyChanged( + resource_coordinator::mojom::PropertyType property_type, + int64_t value) override; + + bool HasFrameCoordinationUnitInAncestors( + FrameCoordinationUnitImpl* frame_cu) const; + bool HasFrameCoordinationUnitInDescendants( + FrameCoordinationUnitImpl* frame_cu) const; + + // The following methods will be called by other FrameCoordinationUnitImpl, + // PageCoordinationUnitImpl and ProcessCoordinationUnitImpl respectively to + // manipulate their relationship. + void AddParentFrame(FrameCoordinationUnitImpl* parent_frame_cu); + bool AddChildFrame(FrameCoordinationUnitImpl* child_frame_cu); + void RemoveParentFrame(FrameCoordinationUnitImpl* parent_frame_cu); + bool RemoveChildFrame(FrameCoordinationUnitImpl* child_frame_cu); + void AddPageCoordinationUnit(PageCoordinationUnitImpl* page_cu); + void AddProcessCoordinationUnit(ProcessCoordinationUnitImpl* process_cu); + void RemovePageCoordinationUnit(PageCoordinationUnitImpl* page_cu); + void RemoveProcessCoordinationUnit(ProcessCoordinationUnitImpl* process_cu); + + FrameCoordinationUnitImpl* parent_frame_coordination_unit_; + PageCoordinationUnitImpl* page_coordination_unit_; + ProcessCoordinationUnitImpl* process_coordination_unit_; + std::set<FrameCoordinationUnitImpl*> child_frame_coordination_units_; + + resource_coordinator::mojom::LifecycleState lifecycle_state_ = + resource_coordinator::mojom::LifecycleState::kRunning; + bool has_nonempty_beforeunload_ = false; + + // Intervention policy for this frame. These are communicated from the + // renderer process and are controlled by origin trials. + resource_coordinator::mojom::InterventionPolicy + intervention_policy_[static_cast<size_t>( + resource_coordinator::mojom:: + PolicyControlledIntervention::kMaxValue) + + 1]; + + DISALLOW_COPY_AND_ASSIGN(FrameCoordinationUnitImpl); +}; + +} // namespace performance_manager + +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_FRAME_COORDINATION_UNIT_IMPL_H_
diff --git a/services/resource_coordinator/coordination_unit/frame_coordination_unit_impl_unittest.cc b/chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl_unittest.cc similarity index 75% rename from services/resource_coordinator/coordination_unit/frame_coordination_unit_impl_unittest.cc rename to chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl_unittest.cc index a9f6f0a..387af8c 100644 --- a/services/resource_coordinator/coordination_unit/frame_coordination_unit_impl_unittest.cc +++ b/chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl_unittest.cc
@@ -2,17 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" #include "base/test/simple_test_tick_clock.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_test_harness.h" -#include "services/resource_coordinator/coordination_unit/mock_coordination_unit_graphs.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" -#include "services/resource_coordinator/resource_coordinator_clock.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.h" +#include "chrome/browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/resource_coordinator_clock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace resource_coordinator { +namespace performance_manager { namespace { @@ -25,9 +25,7 @@ clock_.SetNowTicks(base::TimeTicks::Now()); } - void TearDown() override { - ResourceCoordinatorClock::ResetClockForTesting(); - } + void TearDown() override { ResourceCoordinatorClock::ResetClockForTesting(); } protected: void AdvanceClock(base::TimeDelta delta) { clock_.Advance(delta); } @@ -116,17 +114,21 @@ int64_t GetLifecycleState(PageCoordinationUnitImpl* cu) { int64_t value; - if (cu->GetProperty(mojom::PropertyType::kLifecycleState, &value)) + if (cu->GetProperty( + resource_coordinator::mojom::PropertyType::kLifecycleState, &value)) return value; // Initial state is running. - return static_cast<int64_t>(mojom::LifecycleState::kRunning); + return static_cast<int64_t>( + resource_coordinator::mojom::LifecycleState::kRunning); } -#define EXPECT_FROZEN(cu) \ - EXPECT_EQ(static_cast<int64_t>(mojom::LifecycleState::kFrozen), \ +#define EXPECT_FROZEN(cu) \ + EXPECT_EQ(static_cast<int64_t>( \ + resource_coordinator::mojom::LifecycleState::kFrozen), \ GetLifecycleState(cu.get())) -#define EXPECT_RUNNING(cu) \ - EXPECT_EQ(static_cast<int64_t>(mojom::LifecycleState::kRunning), \ +#define EXPECT_RUNNING(cu) \ + EXPECT_EQ(static_cast<int64_t>( \ + resource_coordinator::mojom::LifecycleState::kRunning), \ GetLifecycleState(cu.get())) TEST_F(FrameCoordinationUnitImplTest, LifecycleStatesTransitions) { @@ -143,45 +145,53 @@ cu_graph.other_page.get()); // Freezing a child frame should not affect the page state. - cu_graph.child_frame->SetLifecycleState(mojom::LifecycleState::kFrozen); + cu_graph.child_frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kFrozen); EXPECT_RUNNING(cu_graph.page); EXPECT_RUNNING(cu_graph.other_page); // Freezing the only frame in a page should freeze that page. - cu_graph.frame->SetLifecycleState(mojom::LifecycleState::kFrozen); + cu_graph.frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kFrozen); EXPECT_FROZEN(cu_graph.page); EXPECT_RUNNING(cu_graph.other_page); // Unfreeze the child frame in the other page. - cu_graph.child_frame->SetLifecycleState(mojom::LifecycleState::kRunning); + cu_graph.child_frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kRunning); EXPECT_FROZEN(cu_graph.page); EXPECT_RUNNING(cu_graph.other_page); // Freezing the main frame in the other page should not alter that pages // state, as there is still a child frame that is running. - cu_graph.other_frame->SetLifecycleState(mojom::LifecycleState::kFrozen); + cu_graph.other_frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kFrozen); EXPECT_FROZEN(cu_graph.page); EXPECT_RUNNING(cu_graph.other_page); // Refreezing the child frame should freeze the page. - cu_graph.child_frame->SetLifecycleState(mojom::LifecycleState::kFrozen); + cu_graph.child_frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kFrozen); EXPECT_FROZEN(cu_graph.page); EXPECT_FROZEN(cu_graph.other_page); // Unfreezing a main frame should unfreeze the associated page. - cu_graph.frame->SetLifecycleState(mojom::LifecycleState::kRunning); + cu_graph.frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kRunning); EXPECT_RUNNING(cu_graph.page); EXPECT_FROZEN(cu_graph.other_page); // Unfreezing the child frame should unfreeze the associated page. - cu_graph.child_frame->SetLifecycleState(mojom::LifecycleState::kRunning); + cu_graph.child_frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kRunning); EXPECT_RUNNING(cu_graph.page); EXPECT_RUNNING(cu_graph.other_page); // Unfreezing the main frame shouldn't change anything. - cu_graph.other_frame->SetLifecycleState(mojom::LifecycleState::kRunning); + cu_graph.other_frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kRunning); EXPECT_RUNNING(cu_graph.page); EXPECT_RUNNING(cu_graph.other_page); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/coordination_unit/mock_coordination_unit_graphs.cc b/chrome/browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.cc similarity index 79% rename from services/resource_coordinator/coordination_unit/mock_coordination_unit_graphs.cc rename to chrome/browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.cc index 10c775a..3360605 100644 --- a/services/resource_coordinator/coordination_unit/mock_coordination_unit_graphs.cc +++ b/chrome/browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.cc
@@ -2,19 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/coordination_unit/mock_coordination_unit_graphs.h" +#include "chrome/browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.h" #include <string> -#include "services/resource_coordinator/coordination_unit/coordination_unit_base.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/system_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_base.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl.h" #include "services/resource_coordinator/public/cpp/coordination_unit_id.h" #include "services/resource_coordinator/public/cpp/coordination_unit_types.h" -namespace resource_coordinator { +namespace performance_manager { MockSinglePageInSingleProcessCoordinationUnitGraph:: MockSinglePageInSingleProcessCoordinationUnitGraph( @@ -28,7 +28,7 @@ page(TestCoordinationUnitWrapper<PageCoordinationUnitImpl>::Create( graph)) { frame->SetAllInterventionPoliciesForTesting( - mojom::InterventionPolicy::kDefault); + resource_coordinator::mojom::InterventionPolicy::kDefault); page->AddFrame(frame->id()); frame->SetProcess(process->id()); process->SetPID(1); @@ -47,7 +47,7 @@ other_page(TestCoordinationUnitWrapper<PageCoordinationUnitImpl>::Create( graph)) { other_frame->SetAllInterventionPoliciesForTesting( - mojom::InterventionPolicy::kDefault); + resource_coordinator::mojom::InterventionPolicy::kDefault); other_page->AddFrame(other_frame->id()); other_frame->SetProcess(process->id()); } @@ -66,7 +66,7 @@ TestCoordinationUnitWrapper<ProcessCoordinationUnitImpl>::Create( graph)) { child_frame->SetAllInterventionPoliciesForTesting( - mojom::InterventionPolicy::kDefault); + resource_coordinator::mojom::InterventionPolicy::kDefault); frame->AddChildFrame(child_frame->id()); page->AddFrame(child_frame->id()); child_frame->SetProcess(other_process->id()); @@ -87,7 +87,7 @@ TestCoordinationUnitWrapper<ProcessCoordinationUnitImpl>::Create( graph)) { child_frame->SetAllInterventionPoliciesForTesting( - mojom::InterventionPolicy::kDefault); + resource_coordinator::mojom::InterventionPolicy::kDefault); other_frame->AddChildFrame(child_frame->id()); other_page->AddFrame(child_frame->id()); child_frame->SetProcess(other_process->id()); @@ -97,4 +97,4 @@ MockMultiplePagesWithMultipleProcessesCoordinationUnitGraph:: ~MockMultiplePagesWithMultipleProcessesCoordinationUnitGraph() = default; -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/coordination_unit/mock_coordination_unit_graphs.h b/chrome/browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.h similarity index 88% rename from services/resource_coordinator/coordination_unit/mock_coordination_unit_graphs.h rename to chrome/browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.h index 8fa30155..dfe2c6b 100644 --- a/services/resource_coordinator/coordination_unit/mock_coordination_unit_graphs.h +++ b/chrome/browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.h
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_MOCK_COORDINATION_UNIT_GRAPHS_H_ -#define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_MOCK_COORDINATION_UNIT_GRAPHS_H_ +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_MOCK_COORDINATION_UNIT_GRAPHS_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_MOCK_COORDINATION_UNIT_GRAPHS_H_ -#include "services/resource_coordinator/coordination_unit/coordination_unit_test_harness.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.h" -namespace resource_coordinator { +namespace performance_manager { class CoordinationUnitGraph; class FrameCoordinationUnitImpl; @@ -110,6 +110,6 @@ TestCoordinationUnitWrapper<ProcessCoordinationUnitImpl> other_process; }; -} // namespace resource_coordinator +} // namespace performance_manager -#endif // SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_MOCK_COORDINATION_UNIT_GRAPHS_H_ +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_MOCK_COORDINATION_UNIT_GRAPHS_H_
diff --git a/services/resource_coordinator/coordination_unit/page_coordination_unit_impl.cc b/chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.cc similarity index 67% rename from services/resource_coordinator/coordination_unit/page_coordination_unit_impl.cc rename to chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.cc index 25bdd8f..a0470c44 100644 --- a/services/resource_coordinator/coordination_unit/page_coordination_unit_impl.cc +++ b/chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.cc
@@ -2,23 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" #include "base/logging.h" #include "base/time/default_tick_clock.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" -#include "services/resource_coordinator/observers/coordination_unit_graph_observer.h" -#include "services/resource_coordinator/resource_coordinator_clock.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/observers/coordination_unit_graph_observer.h" +#include "chrome/browser/performance_manager/resource_coordinator_clock.h" -namespace resource_coordinator { +namespace performance_manager { namespace { -constexpr size_t kMaxInterventionIndex = - static_cast<size_t>(mojom::PolicyControlledIntervention::kMaxValue); +constexpr size_t kMaxInterventionIndex = static_cast<size_t>( + resource_coordinator::mojom::PolicyControlledIntervention::kMaxValue); -size_t ToIndex(mojom::PolicyControlledIntervention intervention) { +size_t ToIndex( + resource_coordinator::mojom::PolicyControlledIntervention intervention) { const size_t kIndex = static_cast<size_t>(intervention); DCHECK(kIndex <= kMaxInterventionIndex); return kIndex; @@ -27,7 +28,7 @@ } // namespace PageCoordinationUnitImpl::PageCoordinationUnitImpl( - const CoordinationUnitID& id, + const resource_coordinator::CoordinationUnitID& id, CoordinationUnitGraph* graph, std::unique_ptr<service_manager::ServiceKeepaliveRef> keepalive_ref) : CoordinationUnitInterface(id, graph, std::move(keepalive_ref)) { @@ -39,8 +40,9 @@ child_frame->RemovePageCoordinationUnit(this); } -void PageCoordinationUnitImpl::AddFrame(const CoordinationUnitID& cu_id) { - DCHECK(cu_id.type == CoordinationUnitType::kFrame); +void PageCoordinationUnitImpl::AddFrame( + const resource_coordinator::CoordinationUnitID& cu_id) { + DCHECK(cu_id.type == resource_coordinator::CoordinationUnitType::kFrame); FrameCoordinationUnitImpl* frame_cu = FrameCoordinationUnitImpl::GetCoordinationUnitByID(graph_, cu_id); if (!frame_cu) @@ -49,7 +51,8 @@ frame_cu->AddPageCoordinationUnit(this); } -void PageCoordinationUnitImpl::RemoveFrame(const CoordinationUnitID& cu_id) { +void PageCoordinationUnitImpl::RemoveFrame( + const resource_coordinator::CoordinationUnitID& cu_id) { DCHECK(cu_id != id()); FrameCoordinationUnitImpl* frame_cu = FrameCoordinationUnitImpl::GetCoordinationUnitByID(graph_, cu_id); @@ -60,23 +63,25 @@ } void PageCoordinationUnitImpl::SetIsLoading(bool is_loading) { - SetProperty(mojom::PropertyType::kIsLoading, is_loading); + SetProperty(resource_coordinator::mojom::PropertyType::kIsLoading, + is_loading); } void PageCoordinationUnitImpl::SetVisibility(bool visible) { - SetProperty(mojom::PropertyType::kVisible, visible); + SetProperty(resource_coordinator::mojom::PropertyType::kVisible, visible); } void PageCoordinationUnitImpl::SetUKMSourceId(int64_t ukm_source_id) { - SetProperty(mojom::PropertyType::kUKMSourceId, ukm_source_id); + SetProperty(resource_coordinator::mojom::PropertyType::kUKMSourceId, + ukm_source_id); } void PageCoordinationUnitImpl::OnFaviconUpdated() { - SendEvent(mojom::Event::kFaviconUpdated); + SendEvent(resource_coordinator::mojom::Event::kFaviconUpdated); } void PageCoordinationUnitImpl::OnTitleUpdated() { - SendEvent(mojom::Event::kTitleUpdated); + SendEvent(resource_coordinator::mojom::Event::kTitleUpdated); } void PageCoordinationUnitImpl::OnMainFrameNavigationCommitted( @@ -86,7 +91,7 @@ navigation_committed_time_ = navigation_committed_time; main_frame_url_ = url; navigation_id_ = navigation_id; - SendEvent(mojom::Event::kNavigationCommitted); + SendEvent(resource_coordinator::mojom::Event::kNavigationCommitted); } std::set<ProcessCoordinationUnitImpl*> @@ -103,7 +108,8 @@ bool PageCoordinationUnitImpl::IsVisible() const { int64_t is_visible = 0; - bool has_property = GetProperty(mojom::PropertyType::kVisible, &is_visible); + bool has_property = GetProperty( + resource_coordinator::mojom::PropertyType::kVisible, &is_visible); DCHECK(has_property && (is_visible == 0 || is_visible == 1)); return is_visible; } @@ -117,8 +123,9 @@ DCHECK_LE(1u, pages_in_process); int64_t process_cpu_usage = 0; - if (process_cu->GetProperty(mojom::PropertyType::kCPUUsage, - &process_cpu_usage)) { + if (process_cu->GetProperty( + resource_coordinator::mojom::PropertyType::kCPUUsage, + &process_cpu_usage)) { cpu_usage += static_cast<double>(process_cpu_usage) / pages_in_process; } } @@ -137,7 +144,8 @@ if (!process_cu) return false; return process_cu->GetProperty( - mojom::PropertyType::kExpectedTaskQueueingDuration, output); + resource_coordinator::mojom::PropertyType::kExpectedTaskQueueingDuration, + output); } base::TimeDelta PageCoordinationUnitImpl::TimeSinceLastNavigation() const { @@ -162,14 +170,15 @@ void PageCoordinationUnitImpl::OnFrameLifecycleStateChanged( FrameCoordinationUnitImpl* frame_cu, - mojom::LifecycleState old_state) { + resource_coordinator::mojom::LifecycleState old_state) { DCHECK(base::ContainsKey(frame_coordination_units_, frame_cu)); DCHECK_NE(old_state, frame_cu->lifecycle_state()); int delta = 0; - if (old_state == mojom::LifecycleState::kFrozen) + if (old_state == resource_coordinator::mojom::LifecycleState::kFrozen) delta = -1; - else if (frame_cu->lifecycle_state() == mojom::LifecycleState::kFrozen) + else if (frame_cu->lifecycle_state() == + resource_coordinator::mojom::LifecycleState::kFrozen) delta = 1; if (delta != 0) OnNumFrozenFramesStateChange(delta); @@ -177,57 +186,62 @@ void PageCoordinationUnitImpl::OnFrameInterventionPolicyChanged( FrameCoordinationUnitImpl* frame, - mojom::PolicyControlledIntervention intervention, - mojom::InterventionPolicy old_policy, - mojom::InterventionPolicy new_policy) { + resource_coordinator::mojom::PolicyControlledIntervention intervention, + resource_coordinator::mojom::InterventionPolicy old_policy, + resource_coordinator::mojom::InterventionPolicy new_policy) { const size_t kIndex = ToIndex(intervention); // Invalidate the local policy aggregation for this intervention. It will be // recomputed on the next query to GetInterventionPolicy. - intervention_policy_[kIndex] = mojom::InterventionPolicy::kUnknown; + intervention_policy_[kIndex] = + resource_coordinator::mojom::InterventionPolicy::kUnknown; // The first time a frame transitions away from kUnknown for the last policy, // then that frame is considered to have checked in. Frames always provide // initial policy values in order, ensuring this works. - if (old_policy == mojom::InterventionPolicy::kUnknown && - new_policy != mojom::InterventionPolicy::kUnknown && - intervention == mojom::PolicyControlledIntervention::kMaxValue) { + if (old_policy == resource_coordinator::mojom::InterventionPolicy::kUnknown && + new_policy != resource_coordinator::mojom::InterventionPolicy::kUnknown && + intervention == resource_coordinator::mojom:: + PolicyControlledIntervention::kMaxValue) { ++intervention_policy_frames_reported_; DCHECK_LE(intervention_policy_frames_reported_, frame_coordination_units_.size()); } } -mojom::InterventionPolicy PageCoordinationUnitImpl::GetInterventionPolicy( - mojom::PolicyControlledIntervention intervention) { +resource_coordinator::mojom::InterventionPolicy +PageCoordinationUnitImpl::GetInterventionPolicy( + resource_coordinator::mojom::PolicyControlledIntervention intervention) { // If there are no frames, or they've not all reported, then return kUnknown. if (frame_coordination_units_.empty() || intervention_policy_frames_reported_ != frame_coordination_units_.size()) { - return mojom::InterventionPolicy::kUnknown; + return resource_coordinator::mojom::InterventionPolicy::kUnknown; } // Recompute the policy if it is currently invalid. const size_t kIndex = ToIndex(intervention); DCHECK_LE(kIndex, kMaxInterventionIndex); - if (intervention_policy_[kIndex] == mojom::InterventionPolicy::kUnknown) { + if (intervention_policy_[kIndex] == + resource_coordinator::mojom::InterventionPolicy::kUnknown) { RecomputeInterventionPolicy(intervention); - DCHECK_NE(mojom::InterventionPolicy::kUnknown, + DCHECK_NE(resource_coordinator::mojom::InterventionPolicy::kUnknown, intervention_policy_[kIndex]); } return intervention_policy_[kIndex]; } -void PageCoordinationUnitImpl::OnEventReceived(mojom::Event event) { +void PageCoordinationUnitImpl::OnEventReceived( + resource_coordinator::mojom::Event event) { for (auto& observer : observers()) observer.OnPageEventReceived(this, event); } void PageCoordinationUnitImpl::OnPropertyChanged( - const mojom::PropertyType property_type, + const resource_coordinator::mojom::PropertyType property_type, int64_t value) { - if (property_type == mojom::PropertyType::kVisible) + if (property_type == resource_coordinator::mojom::PropertyType::kVisible) visibility_change_time_ = ResourceCoordinatorClock::NowTicks(); for (auto& observer : observers()) observer.OnPagePropertyChanged(this, property_type, value); @@ -237,7 +251,10 @@ const bool inserted = frame_coordination_units_.insert(frame_cu).second; if (inserted) { OnNumFrozenFramesStateChange( - frame_cu->lifecycle_state() == mojom::LifecycleState::kFrozen ? 1 : 0); + frame_cu->lifecycle_state() == + resource_coordinator::mojom::LifecycleState::kFrozen + ? 1 + : 0); MaybeInvalidateInterventionPolicies(frame_cu, true /* adding_frame */); } return inserted; @@ -248,7 +265,10 @@ bool removed = frame_coordination_units_.erase(frame_cu) > 0; if (removed) { OnNumFrozenFramesStateChange( - frame_cu->lifecycle_state() == mojom::LifecycleState::kFrozen ? -1 : 0); + frame_cu->lifecycle_state() == + resource_coordinator::mojom::LifecycleState::kFrozen + ? -1 + : 0); MaybeInvalidateInterventionPolicies(frame_cu, false /* adding_frame */); } @@ -260,16 +280,18 @@ num_frozen_frames_ += num_frozen_frames_delta; DCHECK_LE(num_frozen_frames_, frame_coordination_units_.size()); - const int64_t kRunning = - static_cast<int64_t>(mojom::LifecycleState::kRunning); - const int64_t kFrozen = static_cast<int64_t>(mojom::LifecycleState::kFrozen); + const int64_t kRunning = static_cast<int64_t>( + resource_coordinator::mojom::LifecycleState::kRunning); + const int64_t kFrozen = static_cast<int64_t>( + resource_coordinator::mojom::LifecycleState::kFrozen); // We are interested in knowing when we have transitioned to or from // "fully frozen". A page with no frames is considered to be running by // default. bool was_fully_frozen = - GetPropertyOrDefault(mojom::PropertyType::kLifecycleState, kRunning) == - kFrozen; + GetPropertyOrDefault( + resource_coordinator::mojom::PropertyType::kLifecycleState, + kRunning) == kFrozen; bool is_fully_frozen = frame_coordination_units_.size() > 0 && num_frozen_frames_ == frame_coordination_units_.size(); if (was_fully_frozen == is_fully_frozen) @@ -290,13 +312,14 @@ // TODO(fdoray): Store the lifecycle state as a member on the // PageCoordinationUnit rather than as a non-typed property. - SetProperty(mojom::PropertyType::kLifecycleState, + SetProperty(resource_coordinator::mojom::PropertyType::kLifecycleState, is_fully_frozen ? kFrozen : kRunning); } void PageCoordinationUnitImpl::InvalidateAllInterventionPolicies() { for (size_t i = 0; i <= kMaxInterventionIndex; ++i) - intervention_policy_[i] = mojom::InterventionPolicy::kUnknown; + intervention_policy_[i] = + resource_coordinator::mojom::InterventionPolicy::kUnknown; } void PageCoordinationUnitImpl::MaybeInvalidateInterventionPolicies( @@ -330,35 +353,37 @@ } void PageCoordinationUnitImpl::RecomputeInterventionPolicy( - mojom::PolicyControlledIntervention intervention) { + resource_coordinator::mojom::PolicyControlledIntervention intervention) { const size_t kIndex = ToIndex(intervention); // This should never be called with an empty frame tree. DCHECK(!frame_coordination_units_.empty()); - mojom::InterventionPolicy policy = mojom::InterventionPolicy::kDefault; + resource_coordinator::mojom::InterventionPolicy policy = + resource_coordinator::mojom::InterventionPolicy::kDefault; for (auto* frame : frame_coordination_units_) { // No frame should have an unknown policy, as aggregation should only be // invoked after all frames have checked in. - DCHECK_NE(mojom::InterventionPolicy::kUnknown, + DCHECK_NE(resource_coordinator::mojom::InterventionPolicy::kUnknown, frame->intervention_policy_[kIndex]); // If any frame opts out then the whole frame tree opts out, even if other // frames have opted in. if (frame->intervention_policy_[kIndex] == - mojom::InterventionPolicy::kOptOut) { - intervention_policy_[kIndex] = mojom::InterventionPolicy::kOptOut; + resource_coordinator::mojom::InterventionPolicy::kOptOut) { + intervention_policy_[kIndex] = + resource_coordinator::mojom::InterventionPolicy::kOptOut; return; } // If any frame opts in and none opt out, then the whole tree opts in. if (frame->intervention_policy_[kIndex] == - mojom::InterventionPolicy::kOptIn) { - policy = mojom::InterventionPolicy::kOptIn; + resource_coordinator::mojom::InterventionPolicy::kOptIn) { + policy = resource_coordinator::mojom::InterventionPolicy::kOptIn; } } intervention_policy_[kIndex] = policy; } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h b/chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h similarity index 76% rename from services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h rename to chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h index 3202166..a77b659 100644 --- a/services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h +++ b/chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h
@@ -2,34 +2,38 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_PAGE_COORDINATION_UNIT_IMPL_H_ -#define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_PAGE_COORDINATION_UNIT_IMPL_H_ +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_PAGE_COORDINATION_UNIT_IMPL_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_PAGE_COORDINATION_UNIT_IMPL_H_ #include "base/macros.h" #include "base/time/time.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_base.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_base.h" -namespace resource_coordinator { +namespace performance_manager { class FrameCoordinationUnitImpl; class ProcessCoordinationUnitImpl; class PageCoordinationUnitImpl - : public CoordinationUnitInterface<PageCoordinationUnitImpl, - mojom::PageCoordinationUnit, - mojom::PageCoordinationUnitRequest> { + : public CoordinationUnitInterface< + PageCoordinationUnitImpl, + resource_coordinator::mojom::PageCoordinationUnit, + resource_coordinator::mojom::PageCoordinationUnitRequest> { public: - static CoordinationUnitType Type() { return CoordinationUnitType::kPage; } + static resource_coordinator::CoordinationUnitType Type() { + return resource_coordinator::CoordinationUnitType::kPage; + } PageCoordinationUnitImpl( - const CoordinationUnitID& id, + const resource_coordinator::CoordinationUnitID& id, CoordinationUnitGraph* graph, std::unique_ptr<service_manager::ServiceKeepaliveRef> keepalive_ref); ~PageCoordinationUnitImpl() override; - // mojom::PageCoordinationUnit implementation. - void AddFrame(const CoordinationUnitID& cu_id) override; - void RemoveFrame(const CoordinationUnitID& cu_id) override; + // resource_coordinator::mojom::PageCoordinationUnit implementation. + void AddFrame(const resource_coordinator::CoordinationUnitID& cu_id) override; + void RemoveFrame( + const resource_coordinator::CoordinationUnitID& cu_id) override; void SetIsLoading(bool is_loading) override; void SetVisibility(bool visible) override; void SetUKMSourceId(int64_t ukm_source_id) override; @@ -94,25 +98,28 @@ int64_t navigation_id() const { return navigation_id_; } // Invoked when the state of a frame in this page changes. - void OnFrameLifecycleStateChanged(FrameCoordinationUnitImpl* frame_cu, - mojom::LifecycleState old_state); + void OnFrameLifecycleStateChanged( + FrameCoordinationUnitImpl* frame_cu, + resource_coordinator::mojom::LifecycleState old_state); void OnFrameInterventionPolicyChanged( FrameCoordinationUnitImpl* frame, - mojom::PolicyControlledIntervention intervention, - mojom::InterventionPolicy old_policy, - mojom::InterventionPolicy new_policy); + resource_coordinator::mojom::PolicyControlledIntervention intervention, + resource_coordinator::mojom::InterventionPolicy old_policy, + resource_coordinator::mojom::InterventionPolicy new_policy); // Gets the current policy for the specified |intervention|, recomputing it // from individual frame policies if necessary. Returns kUnknown until there // are 1 or more frames, and they have all computed their local policy // settings. - mojom::InterventionPolicy GetInterventionPolicy( - mojom::PolicyControlledIntervention intervention); + resource_coordinator::mojom::InterventionPolicy GetInterventionPolicy( + resource_coordinator::mojom::PolicyControlledIntervention intervention); // Similar to GetInterventionPolicy, but doesn't trigger recomputes. - mojom::InterventionPolicy GetRawInterventionPolicyForTesting( - mojom::PolicyControlledIntervention intervention) const { + resource_coordinator::mojom::InterventionPolicy + GetRawInterventionPolicyForTesting( + resource_coordinator::mojom::PolicyControlledIntervention intervention) + const { return intervention_policy_[static_cast<size_t>(intervention)]; } @@ -124,9 +131,10 @@ friend class FrameCoordinationUnitImpl; // CoordinationUnitInterface implementation. - void OnEventReceived(mojom::Event event) override; - void OnPropertyChanged(mojom::PropertyType property_type, - int64_t value) override; + void OnEventReceived(resource_coordinator::mojom::Event event) override; + void OnPropertyChanged( + resource_coordinator::mojom::PropertyType property_type, + int64_t value) override; bool AddFrame(FrameCoordinationUnitImpl* frame_cu); bool RemoveFrame(FrameCoordinationUnitImpl* frame_cu); @@ -152,7 +160,7 @@ // Recomputes intervention policy aggregation. This is invoked on demand when // a policy is queried. void RecomputeInterventionPolicy( - mojom::PolicyControlledIntervention intervention); + resource_coordinator::mojom::PolicyControlledIntervention intervention); std::set<FrameCoordinationUnitImpl*> frame_coordination_units_; @@ -191,8 +199,11 @@ // aggregated from the corresponding per-frame values. If an individual value // is kUnknown then a frame in the frame tree has changed values and // a new aggregation is required. - mojom::InterventionPolicy intervention_policy_ - [static_cast<size_t>(mojom::PolicyControlledIntervention::kMaxValue) + 1]; + resource_coordinator::mojom::InterventionPolicy + intervention_policy_[static_cast<size_t>( + resource_coordinator::mojom:: + PolicyControlledIntervention::kMaxValue) + + 1]; // The number of child frames that have checked in with initial intervention // policy values. If this doesn't match the number of known child frames, then @@ -204,6 +215,6 @@ DISALLOW_COPY_AND_ASSIGN(PageCoordinationUnitImpl); }; -} // namespace resource_coordinator +} // namespace performance_manager -#endif // SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_PAGE_COORDINATION_UNIT_IMPL_H_ +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_PAGE_COORDINATION_UNIT_IMPL_H_
diff --git a/chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl_unittest.cc b/chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl_unittest.cc new file mode 100644 index 0000000..056e780e --- /dev/null +++ b/chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl_unittest.cc
@@ -0,0 +1,494 @@ +// Copyright 2017 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/performance_manager/coordination_unit/page_coordination_unit_impl.h" + +#include "base/test/simple_test_tick_clock.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/resource_coordinator_clock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace performance_manager { + +namespace { + +class PageCoordinationUnitImplTest : public CoordinationUnitTestHarness { + public: + void SetUp() override { + ResourceCoordinatorClock::SetClockForTesting(&clock_); + + // Sets a valid starting time. + clock_.SetNowTicks(base::TimeTicks::Now()); + } + + void TearDown() override { ResourceCoordinatorClock::ResetClockForTesting(); } + + protected: + void AdvanceClock(base::TimeDelta delta) { clock_.Advance(delta); } + + private: + base::SimpleTestTickClock clock_; +}; + +} // namespace + +TEST_F(PageCoordinationUnitImplTest, AddFrameBasic) { + auto page_cu = CreateCoordinationUnit<PageCoordinationUnitImpl>(); + auto frame1_cu = CreateCoordinationUnit<FrameCoordinationUnitImpl>(); + auto frame2_cu = CreateCoordinationUnit<FrameCoordinationUnitImpl>(); + auto frame3_cu = CreateCoordinationUnit<FrameCoordinationUnitImpl>(); + + page_cu->AddFrame(frame1_cu->id()); + page_cu->AddFrame(frame2_cu->id()); + page_cu->AddFrame(frame3_cu->id()); + EXPECT_EQ(3u, page_cu->GetFrameCoordinationUnits().size()); +} + +TEST_F(PageCoordinationUnitImplTest, AddReduplicativeFrame) { + auto page_cu = CreateCoordinationUnit<PageCoordinationUnitImpl>(); + auto frame1_cu = CreateCoordinationUnit<FrameCoordinationUnitImpl>(); + auto frame2_cu = CreateCoordinationUnit<FrameCoordinationUnitImpl>(); + + page_cu->AddFrame(frame1_cu->id()); + page_cu->AddFrame(frame2_cu->id()); + page_cu->AddFrame(frame1_cu->id()); + EXPECT_EQ(2u, page_cu->GetFrameCoordinationUnits().size()); +} + +TEST_F(PageCoordinationUnitImplTest, RemoveFrame) { + auto page_cu = CreateCoordinationUnit<PageCoordinationUnitImpl>(); + auto frame_cu = CreateCoordinationUnit<FrameCoordinationUnitImpl>(); + + // Parent-child relationships have not been established yet. + EXPECT_EQ(0u, page_cu->GetFrameCoordinationUnits().size()); + EXPECT_FALSE(frame_cu->GetPageCoordinationUnit()); + + page_cu->AddFrame(frame_cu->id()); + + // Ensure correct Parent-child relationships have been established. + EXPECT_EQ(1u, page_cu->GetFrameCoordinationUnits().size()); + EXPECT_EQ(1u, page_cu->GetFrameCoordinationUnits().count(frame_cu.get())); + EXPECT_EQ(page_cu.get(), frame_cu->GetPageCoordinationUnit()); + + page_cu->RemoveFrame(frame_cu->id()); + + // Parent-child relationships should no longer exist. + EXPECT_EQ(0u, page_cu->GetFrameCoordinationUnits().size()); + EXPECT_FALSE(frame_cu->GetPageCoordinationUnit()); +} + +TEST_F(PageCoordinationUnitImplTest, + CalculatePageCPUUsageForSinglePageInSingleProcess) { + MockSinglePageInSingleProcessCoordinationUnitGraph cu_graph( + coordination_unit_graph()); + cu_graph.process->SetCPUUsage(40); + EXPECT_EQ(40, cu_graph.page->GetCPUUsage()); +} + +TEST_F(PageCoordinationUnitImplTest, + CalculatePageCPUUsageForMultiplePagesInSingleProcess) { + MockMultiplePagesInSingleProcessCoordinationUnitGraph cu_graph( + coordination_unit_graph()); + cu_graph.process->SetCPUUsage(40); + EXPECT_EQ(20, cu_graph.page->GetCPUUsage()); + EXPECT_EQ(20, cu_graph.other_page->GetCPUUsage()); +} + +TEST_F(PageCoordinationUnitImplTest, + CalculatePageCPUUsageForSinglePageWithMultipleProcesses) { + MockSinglePageWithMultipleProcessesCoordinationUnitGraph cu_graph( + coordination_unit_graph()); + cu_graph.process->SetCPUUsage(40); + cu_graph.other_process->SetCPUUsage(30); + EXPECT_EQ(70, cu_graph.page->GetCPUUsage()); +} + +TEST_F(PageCoordinationUnitImplTest, + CalculatePageCPUUsageForMultiplePagesWithMultipleProcesses) { + MockMultiplePagesWithMultipleProcessesCoordinationUnitGraph cu_graph( + coordination_unit_graph()); + cu_graph.process->SetCPUUsage(40); + cu_graph.other_process->SetCPUUsage(30); + EXPECT_EQ(20, cu_graph.page->GetCPUUsage()); + EXPECT_EQ(50, cu_graph.other_page->GetCPUUsage()); +} + +TEST_F(PageCoordinationUnitImplTest, + CalculatePageEQTForSinglePageInSingleProcess) { + MockSinglePageInSingleProcessCoordinationUnitGraph cu_graph( + coordination_unit_graph()); + + cu_graph.process->SetExpectedTaskQueueingDuration( + base::TimeDelta::FromMilliseconds(1)); + + int64_t eqt; + EXPECT_TRUE(cu_graph.page->GetExpectedTaskQueueingDuration(&eqt)); + EXPECT_EQ(1, eqt); +} + +TEST_F(PageCoordinationUnitImplTest, + CalculatePageEQTForMultiplePagesInSingleProcess) { + MockMultiplePagesInSingleProcessCoordinationUnitGraph cu_graph( + coordination_unit_graph()); + + cu_graph.process->SetExpectedTaskQueueingDuration( + base::TimeDelta::FromMilliseconds(1)); + + int64_t eqt; + EXPECT_TRUE(cu_graph.page->GetExpectedTaskQueueingDuration(&eqt)); + EXPECT_EQ(1, eqt); + eqt = 0; + EXPECT_TRUE(cu_graph.other_page->GetExpectedTaskQueueingDuration(&eqt)); + EXPECT_EQ(1, eqt); +} + +TEST_F(PageCoordinationUnitImplTest, TimeSinceLastVisibilityChange) { + MockSinglePageInSingleProcessCoordinationUnitGraph cu_graph( + coordination_unit_graph()); + + cu_graph.page->SetVisibility(true); + EXPECT_TRUE(cu_graph.page->IsVisible()); + AdvanceClock(base::TimeDelta::FromSeconds(42)); + EXPECT_EQ(base::TimeDelta::FromSeconds(42), + cu_graph.page->TimeSinceLastVisibilityChange()); + + cu_graph.page->SetVisibility(false); + AdvanceClock(base::TimeDelta::FromSeconds(23)); + EXPECT_EQ(base::TimeDelta::FromSeconds(23), + cu_graph.page->TimeSinceLastVisibilityChange()); + EXPECT_FALSE(cu_graph.page->IsVisible()); +} + +TEST_F(PageCoordinationUnitImplTest, TimeSinceLastNavigation) { + MockSinglePageInSingleProcessCoordinationUnitGraph cu_graph( + coordination_unit_graph()); + // Before any commit events, timedelta should be 0. + EXPECT_TRUE(cu_graph.page->TimeSinceLastNavigation().is_zero()); + + // 1st navigation. + cu_graph.page->OnMainFrameNavigationCommitted( + ResourceCoordinatorClock::NowTicks(), 10u, "http://www.example.org"); + EXPECT_EQ("http://www.example.org", cu_graph.page->main_frame_url()); + EXPECT_EQ(10u, cu_graph.page->navigation_id()); + AdvanceClock(base::TimeDelta::FromSeconds(11)); + EXPECT_EQ(base::TimeDelta::FromSeconds(11), + cu_graph.page->TimeSinceLastNavigation()); + + // 2nd navigation. + cu_graph.page->OnMainFrameNavigationCommitted( + ResourceCoordinatorClock::NowTicks(), 20u, + "http://www.example.org/bobcat"); + EXPECT_EQ("http://www.example.org/bobcat", cu_graph.page->main_frame_url()); + EXPECT_EQ(20u, cu_graph.page->navigation_id()); + AdvanceClock(base::TimeDelta::FromSeconds(17)); + EXPECT_EQ(base::TimeDelta::FromSeconds(17), + cu_graph.page->TimeSinceLastNavigation()); +} + +TEST_F(PageCoordinationUnitImplTest, IsLoading) { + MockSinglePageInSingleProcessCoordinationUnitGraph cu_graph( + coordination_unit_graph()); + auto* page_cu = cu_graph.page.get(); + + // First attempt should fail, as the property is unset. + int64_t loading = 0; + EXPECT_FALSE(page_cu->GetProperty( + resource_coordinator::mojom::PropertyType::kIsLoading, &loading)); + + // Set to false and the property should read false. + page_cu->SetIsLoading(false); + EXPECT_TRUE(page_cu->GetProperty( + resource_coordinator::mojom::PropertyType::kIsLoading, &loading)); + EXPECT_EQ(0u, loading); + + // Set to true and the property should read true. + page_cu->SetIsLoading(true); + EXPECT_TRUE(page_cu->GetProperty( + resource_coordinator::mojom::PropertyType::kIsLoading, &loading)); + EXPECT_EQ(1u, loading); + + // Set to false and the property should read false again. + page_cu->SetIsLoading(false); + EXPECT_TRUE(page_cu->GetProperty( + resource_coordinator::mojom::PropertyType::kIsLoading, &loading)); + EXPECT_EQ(0u, loading); +} + +TEST_F(PageCoordinationUnitImplTest, OnAllFramesInPageFrozen) { + const int64_t kRunning = static_cast<int64_t>( + resource_coordinator::mojom::LifecycleState::kRunning); + const int64_t kFrozen = static_cast<int64_t>( + resource_coordinator::mojom::LifecycleState::kFrozen); + + MockSinglePageWithMultipleProcessesCoordinationUnitGraph cu_graph( + coordination_unit_graph()); + + EXPECT_EQ(kRunning, + cu_graph.page->GetPropertyOrDefault( + resource_coordinator::mojom::PropertyType::kLifecycleState, + kRunning)); + + // 1/2 frames in the page is frozen. Expect the page to still be running. + cu_graph.frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kFrozen); + EXPECT_EQ(kRunning, + cu_graph.page->GetPropertyOrDefault( + resource_coordinator::mojom::PropertyType::kLifecycleState, + kRunning)); + + // 2/2 frames in the process are frozen. We expect the page to be frozen. + cu_graph.child_frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kFrozen); + EXPECT_EQ(kFrozen, + cu_graph.page->GetPropertyOrDefault( + resource_coordinator::mojom::PropertyType::kLifecycleState, + kRunning)); + + // Unfreeze a frame and expect the page to be running again. + cu_graph.frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kRunning); + EXPECT_EQ(kRunning, + cu_graph.page->GetPropertyOrDefault( + resource_coordinator::mojom::PropertyType::kLifecycleState, + kRunning)); + + // Refreeze that frame and expect the page to be frozen again. + cu_graph.frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kFrozen); + EXPECT_EQ(kFrozen, + cu_graph.page->GetPropertyOrDefault( + resource_coordinator::mojom::PropertyType::kLifecycleState, + kRunning)); +} + +namespace { + +const size_t kInterventionCount = + static_cast<size_t>( + resource_coordinator::mojom::PolicyControlledIntervention::kMaxValue) + + 1; + +void ExpectRawInterventionPolicy( + resource_coordinator::mojom::InterventionPolicy policy, + const PageCoordinationUnitImpl* page_cu) { + for (size_t i = 0; i < kInterventionCount; ++i) { + EXPECT_EQ( + policy, + page_cu->GetRawInterventionPolicyForTesting( + static_cast< + resource_coordinator::mojom::PolicyControlledIntervention>(i))); + } +} + +void ExpectInterventionPolicy( + resource_coordinator::mojom::InterventionPolicy policy, + PageCoordinationUnitImpl* page_cu) { + for (size_t i = 0; i < kInterventionCount; ++i) { + EXPECT_EQ( + policy, + page_cu->GetInterventionPolicy( + static_cast< + resource_coordinator::mojom::PolicyControlledIntervention>(i))); + } +} + +void ExpectInitialInterventionPolicyAggregationWorks( + CoordinationUnitGraph* cu_graph, + resource_coordinator::mojom::InterventionPolicy f0_policy, + resource_coordinator::mojom::InterventionPolicy f1_policy, + resource_coordinator::mojom::InterventionPolicy f0_policy_aggregated, + resource_coordinator::mojom::InterventionPolicy f0f1_policy_aggregated) { + // Create two frames not tied to any page. + TestCoordinationUnitWrapper<FrameCoordinationUnitImpl> f0 = + TestCoordinationUnitWrapper<FrameCoordinationUnitImpl>::Create(cu_graph); + TestCoordinationUnitWrapper<FrameCoordinationUnitImpl> f1 = + TestCoordinationUnitWrapper<FrameCoordinationUnitImpl>::Create(cu_graph); + + // Set frame policies before attaching to a page CU. + f0->SetAllInterventionPoliciesForTesting(f0_policy); + f1->SetAllInterventionPoliciesForTesting(f1_policy); + + // Check the initial values before any frames are added. + TestCoordinationUnitWrapper<PageCoordinationUnitImpl> page = + TestCoordinationUnitWrapper<PageCoordinationUnitImpl>::Create(cu_graph); + EXPECT_EQ(0u, page->GetInterventionPolicyFramesReportedForTesting()); + ExpectRawInterventionPolicy( + resource_coordinator::mojom::InterventionPolicy::kUnknown, page.get()); + ExpectInterventionPolicy( + resource_coordinator::mojom::InterventionPolicy::kUnknown, page.get()); + + // Add a frame and expect the values to be invalidated. Reaggregate and + // ensure the appropriate value results. + page->AddFrame(f0->id()); + EXPECT_EQ(1u, page->GetInterventionPolicyFramesReportedForTesting()); + ExpectRawInterventionPolicy( + resource_coordinator::mojom::InterventionPolicy::kUnknown, page.get()); + ExpectInterventionPolicy(f0_policy_aggregated, page.get()); + + // Do it again. This time the raw values should be the same as the + // aggregated values above. + page->AddFrame(f1->id()); + EXPECT_EQ(2u, page->GetInterventionPolicyFramesReportedForTesting()); + ExpectRawInterventionPolicy( + resource_coordinator::mojom::InterventionPolicy::kUnknown, page.get()); + ExpectInterventionPolicy(f0f1_policy_aggregated, page.get()); + + // Remove a frame and expect the values to be invalidated again. + f1.reset(); + EXPECT_EQ(1u, page->GetInterventionPolicyFramesReportedForTesting()); + ExpectRawInterventionPolicy( + resource_coordinator::mojom::InterventionPolicy::kUnknown, page.get()); + ExpectInterventionPolicy(f0_policy_aggregated, page.get()); +} + +} // namespace + +TEST_F(PageCoordinationUnitImplTest, InitialInterventionPolicy) { + auto* cu_graph = coordination_unit_graph(); + + // Tests all possible transitions where the frame CU has its policy values + // set before being attached to the page CU. This affectively tests the + // aggregation logic in isolation. + + // Default x [Default, OptIn, OptOut] + + ExpectInitialInterventionPolicyAggregationWorks( + cu_graph, + resource_coordinator::mojom::InterventionPolicy::kDefault /* f0_policy */, + resource_coordinator::mojom::InterventionPolicy::kDefault /* f1_policy */, + resource_coordinator::mojom::InterventionPolicy:: + kDefault /* f0_policy_aggregated */, + resource_coordinator::mojom::InterventionPolicy:: + kDefault /* f0f1_policy_aggregated */); + + ExpectInitialInterventionPolicyAggregationWorks( + cu_graph, + resource_coordinator::mojom::InterventionPolicy::kDefault /* f0_policy */, + resource_coordinator::mojom::InterventionPolicy::kOptIn /* f1_policy */, + resource_coordinator::mojom::InterventionPolicy:: + kDefault /* f0_policy_aggregated */, + resource_coordinator::mojom::InterventionPolicy:: + kOptIn /* f0f1_policy_aggregated */); + + ExpectInitialInterventionPolicyAggregationWorks( + cu_graph, + resource_coordinator::mojom::InterventionPolicy::kDefault /* f0_policy */, + resource_coordinator::mojom::InterventionPolicy::kOptOut /* f1_policy */, + resource_coordinator::mojom::InterventionPolicy:: + kDefault /* f0_policy_aggregated */, + resource_coordinator::mojom::InterventionPolicy:: + kOptOut /* f0f1_policy_aggregated */); + + // OptIn x [Default, OptIn, OptOut] + + ExpectInitialInterventionPolicyAggregationWorks( + cu_graph, + resource_coordinator::mojom::InterventionPolicy::kOptIn /* f0_policy */, + resource_coordinator::mojom::InterventionPolicy::kDefault /* f1_policy */, + resource_coordinator::mojom::InterventionPolicy:: + kOptIn /* f0_policy_aggregated */, + resource_coordinator::mojom::InterventionPolicy:: + kOptIn /* f0f1_policy_aggregated */); + + ExpectInitialInterventionPolicyAggregationWorks( + cu_graph, + resource_coordinator::mojom::InterventionPolicy::kOptIn /* f0_policy */, + resource_coordinator::mojom::InterventionPolicy::kOptIn /* f1_policy */, + resource_coordinator::mojom::InterventionPolicy:: + kOptIn /* f0_policy_aggregated */, + resource_coordinator::mojom::InterventionPolicy:: + kOptIn /* f0f1_policy_aggregated */); + + ExpectInitialInterventionPolicyAggregationWorks( + cu_graph, + resource_coordinator::mojom::InterventionPolicy::kOptIn /* f0_policy */, + resource_coordinator::mojom::InterventionPolicy::kOptOut /* f1_policy */, + resource_coordinator::mojom::InterventionPolicy:: + kOptIn /* f0_policy_aggregated */, + resource_coordinator::mojom::InterventionPolicy:: + kOptOut /* f0f1_policy_aggregated */); + + // OptOut x [Default, OptIn, OptOut] + + ExpectInitialInterventionPolicyAggregationWorks( + cu_graph, + resource_coordinator::mojom::InterventionPolicy::kOptOut /* f0_policy */, + resource_coordinator::mojom::InterventionPolicy::kDefault /* f1_policy */, + resource_coordinator::mojom::InterventionPolicy:: + kOptOut /* f0_policy_aggregated */, + resource_coordinator::mojom::InterventionPolicy:: + kOptOut /* f0f1_policy_aggregated */); + + ExpectInitialInterventionPolicyAggregationWorks( + cu_graph, + resource_coordinator::mojom::InterventionPolicy::kOptOut /* f0_policy */, + resource_coordinator::mojom::InterventionPolicy::kOptIn /* f1_policy */, + resource_coordinator::mojom::InterventionPolicy:: + kOptOut /* f0_policy_aggregated */, + resource_coordinator::mojom::InterventionPolicy:: + kOptOut /* f0f1_policy_aggregated */); + + ExpectInitialInterventionPolicyAggregationWorks( + cu_graph, + resource_coordinator::mojom::InterventionPolicy::kOptOut /* f0_policy */, + resource_coordinator::mojom::InterventionPolicy::kOptOut /* f1_policy */, + resource_coordinator::mojom::InterventionPolicy:: + kOptOut /* f0_policy_aggregated */, + resource_coordinator::mojom::InterventionPolicy:: + kOptOut /* f0f1_policy_aggregated */); +} + +TEST_F(PageCoordinationUnitImplTest, IncrementalInterventionPolicy) { + auto* cu_graph = coordination_unit_graph(); + + TestCoordinationUnitWrapper<PageCoordinationUnitImpl> page = + TestCoordinationUnitWrapper<PageCoordinationUnitImpl>::Create(cu_graph); + + // Create two frames and immediately attach them to the page. + TestCoordinationUnitWrapper<FrameCoordinationUnitImpl> f0 = + TestCoordinationUnitWrapper<FrameCoordinationUnitImpl>::Create(cu_graph); + TestCoordinationUnitWrapper<FrameCoordinationUnitImpl> f1 = + TestCoordinationUnitWrapper<FrameCoordinationUnitImpl>::Create(cu_graph); + EXPECT_EQ(0u, page->GetInterventionPolicyFramesReportedForTesting()); + page->AddFrame(f0->id()); + EXPECT_EQ(0u, page->GetInterventionPolicyFramesReportedForTesting()); + page->AddFrame(f1->id()); + EXPECT_EQ(0u, page->GetInterventionPolicyFramesReportedForTesting()); + + // Set the policies on the first frame. This should be observed by the page + // CU, but aggregation should still not be possible. + f0->SetAllInterventionPoliciesForTesting( + resource_coordinator::mojom::InterventionPolicy::kDefault); + EXPECT_EQ(1u, page->GetInterventionPolicyFramesReportedForTesting()); + ExpectRawInterventionPolicy( + resource_coordinator::mojom::InterventionPolicy::kUnknown, page.get()); + ExpectInterventionPolicy( + resource_coordinator::mojom::InterventionPolicy::kUnknown, page.get()); + + // Now set the policy on the second frame. This should be observed and an + // aggregated page policy value should now be available. + f1->SetAllInterventionPoliciesForTesting( + resource_coordinator::mojom::InterventionPolicy::kDefault); + EXPECT_EQ(2u, page->GetInterventionPolicyFramesReportedForTesting()); + ExpectRawInterventionPolicy( + resource_coordinator::mojom::InterventionPolicy::kUnknown, page.get()); + ExpectInterventionPolicy( + resource_coordinator::mojom::InterventionPolicy::kDefault, page.get()); + + // Change the policy value on a frame and expect a new aggregation to be + // required. + f1->SetAllInterventionPoliciesForTesting( + resource_coordinator::mojom::InterventionPolicy::kOptIn); + EXPECT_EQ(2u, page->GetInterventionPolicyFramesReportedForTesting()); + ExpectRawInterventionPolicy( + resource_coordinator::mojom::InterventionPolicy::kUnknown, page.get()); + ExpectInterventionPolicy( + resource_coordinator::mojom::InterventionPolicy::kOptIn, page.get()); +} + +} // namespace performance_manager
diff --git a/services/resource_coordinator/coordination_unit/process_coordination_unit_impl.cc b/chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.cc similarity index 74% rename from services/resource_coordinator/coordination_unit/process_coordination_unit_impl.cc rename to chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.cc index 4b482b4..1e15dec 100644 --- a/services/resource_coordinator/coordination_unit/process_coordination_unit_impl.cc +++ b/chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.cc
@@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" #include "base/logging.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" -namespace resource_coordinator { +namespace performance_manager { ProcessCoordinationUnitImpl::ProcessCoordinationUnitImpl( - const CoordinationUnitID& id, + const resource_coordinator::CoordinationUnitID& id, CoordinationUnitGraph* graph, std::unique_ptr<service_manager::ServiceKeepaliveRef> keepalive_ref) : CoordinationUnitInterface(id, graph, std::move(keepalive_ref)) {} @@ -30,18 +30,21 @@ FrameCoordinationUnitImpl* frame_cu) { const bool inserted = frame_coordination_units_.insert(frame_cu).second; DCHECK(inserted); - if (frame_cu->lifecycle_state() == mojom::LifecycleState::kFrozen) + if (frame_cu->lifecycle_state() == + resource_coordinator::mojom::LifecycleState::kFrozen) IncrementNumFrozenFrames(); } void ProcessCoordinationUnitImpl::SetCPUUsage(double cpu_usage) { - SetProperty(mojom::PropertyType::kCPUUsage, cpu_usage * 1000); + SetProperty(resource_coordinator::mojom::PropertyType::kCPUUsage, + cpu_usage * 1000); } void ProcessCoordinationUnitImpl::SetExpectedTaskQueueingDuration( base::TimeDelta duration) { - SetProperty(mojom::PropertyType::kExpectedTaskQueueingDuration, - duration.InMilliseconds()); + SetProperty( + resource_coordinator::mojom::PropertyType::kExpectedTaskQueueingDuration, + duration.InMilliseconds()); } void ProcessCoordinationUnitImpl::SetLaunchTime(base::Time launch_time) { @@ -51,8 +54,9 @@ void ProcessCoordinationUnitImpl::SetMainThreadTaskLoadIsLow( bool main_thread_task_load_is_low) { - SetProperty(mojom::PropertyType::kMainThreadTaskLoadIsLow, - main_thread_task_load_is_low); + SetProperty( + resource_coordinator::mojom::PropertyType::kMainThreadTaskLoadIsLow, + main_thread_task_load_is_low); } void ProcessCoordinationUnitImpl::SetPID(base::ProcessId pid) { @@ -74,7 +78,7 @@ private_footprint_kb_ = 0; cumulative_cpu_usage_ = base::TimeDelta(); - SetProperty(mojom::PropertyType::kPID, pid); + SetProperty(resource_coordinator::mojom::PropertyType::kPID, pid); } void ProcessCoordinationUnitImpl::SetProcessExitStatus(int32_t exit_status) { @@ -82,7 +86,7 @@ } void ProcessCoordinationUnitImpl::OnRendererIsBloated() { - SendEvent(mojom::Event::kRendererIsBloated); + SendEvent(resource_coordinator::mojom::Event::kRendererIsBloated); } const std::set<FrameCoordinationUnitImpl*>& @@ -106,23 +110,25 @@ void ProcessCoordinationUnitImpl::OnFrameLifecycleStateChanged( FrameCoordinationUnitImpl* frame_cu, - mojom::LifecycleState old_state) { + resource_coordinator::mojom::LifecycleState old_state) { DCHECK(base::ContainsKey(frame_coordination_units_, frame_cu)); DCHECK_NE(old_state, frame_cu->lifecycle_state()); - if (old_state == mojom::LifecycleState::kFrozen) + if (old_state == resource_coordinator::mojom::LifecycleState::kFrozen) DecrementNumFrozenFrames(); - else if (frame_cu->lifecycle_state() == mojom::LifecycleState::kFrozen) + else if (frame_cu->lifecycle_state() == + resource_coordinator::mojom::LifecycleState::kFrozen) IncrementNumFrozenFrames(); } -void ProcessCoordinationUnitImpl::OnEventReceived(mojom::Event event) { +void ProcessCoordinationUnitImpl::OnEventReceived( + resource_coordinator::mojom::Event event) { for (auto& observer : observers()) observer.OnProcessEventReceived(this, event); } void ProcessCoordinationUnitImpl::OnPropertyChanged( - const mojom::PropertyType property_type, + const resource_coordinator::mojom::PropertyType property_type, int64_t value) { for (auto& observer : observers()) observer.OnProcessPropertyChanged(this, property_type, value); @@ -133,7 +139,8 @@ DCHECK(base::ContainsKey(frame_coordination_units_, frame_cu)); frame_coordination_units_.erase(frame_cu); - if (frame_cu->lifecycle_state() == mojom::LifecycleState::kFrozen) + if (frame_cu->lifecycle_state() == + resource_coordinator::mojom::LifecycleState::kFrozen) DecrementNumFrozenFrames(); } @@ -154,4 +161,4 @@ } } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h b/chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h similarity index 71% rename from services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h rename to chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h index cc0dd32..5d5c1e1 100644 --- a/services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h +++ b/chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h
@@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_PROCESS_COORDINATION_UNIT_IMPL_H_ -#define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_PROCESS_COORDINATION_UNIT_IMPL_H_ +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_PROCESS_COORDINATION_UNIT_IMPL_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_PROCESS_COORDINATION_UNIT_IMPL_H_ #include "base/macros.h" #include "base/optional.h" #include "base/process/process_handle.h" #include "base/time/time.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_base.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_base.h" -namespace resource_coordinator { +namespace performance_manager { class FrameCoordinationUnitImpl; @@ -26,19 +26,22 @@ // 3. Process died or falied to start, have exit status. // 4. Back to 2. class ProcessCoordinationUnitImpl - : public CoordinationUnitInterface<ProcessCoordinationUnitImpl, - mojom::ProcessCoordinationUnit, - mojom::ProcessCoordinationUnitRequest> { + : public CoordinationUnitInterface< + ProcessCoordinationUnitImpl, + resource_coordinator::mojom::ProcessCoordinationUnit, + resource_coordinator::mojom::ProcessCoordinationUnitRequest> { public: - static CoordinationUnitType Type() { return CoordinationUnitType::kProcess; } + static resource_coordinator::CoordinationUnitType Type() { + return resource_coordinator::CoordinationUnitType::kProcess; + } ProcessCoordinationUnitImpl( - const CoordinationUnitID& id, + const resource_coordinator::CoordinationUnitID& id, CoordinationUnitGraph* graph, std::unique_ptr<service_manager::ServiceKeepaliveRef> keepalive_ref); ~ProcessCoordinationUnitImpl() override; - // mojom::ProcessCoordinationUnit implementation. + // resource_coordinator::mojom::ProcessCoordinationUnit implementation. void SetCPUUsage(double cpu_usage) override; void SetExpectedTaskQueueingDuration(base::TimeDelta duration) override; void SetLaunchTime(base::Time launch_time) override; @@ -72,14 +75,16 @@ void RemoveFrame(FrameCoordinationUnitImpl* frame_cu); // Invoked when the state of a frame hosted by this process changes. - void OnFrameLifecycleStateChanged(FrameCoordinationUnitImpl* frame_cu, - mojom::LifecycleState old_state); + void OnFrameLifecycleStateChanged( + FrameCoordinationUnitImpl* frame_cu, + resource_coordinator::mojom::LifecycleState old_state); private: // CoordinationUnitInterface implementation. - void OnEventReceived(mojom::Event event) override; - void OnPropertyChanged(mojom::PropertyType property_type, - int64_t value) override; + void OnEventReceived(resource_coordinator::mojom::Event event) override; + void OnPropertyChanged( + resource_coordinator::mojom::PropertyType property_type, + int64_t value) override; void DecrementNumFrozenFrames(); void IncrementNumFrozenFrames(); @@ -99,6 +104,6 @@ DISALLOW_COPY_AND_ASSIGN(ProcessCoordinationUnitImpl); }; -} // namespace resource_coordinator +} // namespace performance_manager -#endif // SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_PROCESS_COORDINATION_UNIT_IMPL_H_ +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_PROCESS_COORDINATION_UNIT_IMPL_H_
diff --git a/services/resource_coordinator/coordination_unit/process_coordination_unit_impl_unittest.cc b/chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl_unittest.cc similarity index 77% rename from services/resource_coordinator/coordination_unit/process_coordination_unit_impl_unittest.cc rename to chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl_unittest.cc index 697f13a..6dd141d 100644 --- a/services/resource_coordinator/coordination_unit/process_coordination_unit_impl_unittest.cc +++ b/chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl_unittest.cc
@@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_test_harness.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/mock_coordination_unit_graphs.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace resource_coordinator { +namespace performance_manager { namespace { @@ -38,8 +38,8 @@ auto process_cu = CreateCoordinationUnit<ProcessCoordinationUnitImpl>(); process_cu->SetCPUUsage(1); int64_t cpu_usage; - EXPECT_TRUE( - process_cu->GetProperty(mojom::PropertyType::kCPUUsage, &cpu_usage)); + EXPECT_TRUE(process_cu->GetProperty( + resource_coordinator::mojom::PropertyType::kCPUUsage, &cpu_usage)); EXPECT_EQ(1, cpu_usage / 1000.0); } @@ -53,22 +53,27 @@ // 1/2 frame in the process is frozen. // No call to OnAllFramesInProcessFrozen() is expected. - cu_graph.frame->SetLifecycleState(mojom::LifecycleState::kFrozen); + cu_graph.frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kFrozen); // 2/2 frames in the process are frozen. EXPECT_CALL(*observer, OnAllFramesInProcessFrozen(cu_graph.process.get())); - cu_graph.other_frame->SetLifecycleState(mojom::LifecycleState::kFrozen); + cu_graph.other_frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kFrozen); testing::Mock::VerifyAndClear(observer); // A frame is unfrozen and frozen. - cu_graph.frame->SetLifecycleState(mojom::LifecycleState::kRunning); + cu_graph.frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kRunning); EXPECT_CALL(*observer, OnAllFramesInProcessFrozen(cu_graph.process.get())); - cu_graph.frame->SetLifecycleState(mojom::LifecycleState::kFrozen); + cu_graph.frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kFrozen); testing::Mock::VerifyAndClear(observer); // A frozen frame is frozen again. // No call to OnAllFramesInProcessFrozen() is expected. - cu_graph.frame->SetLifecycleState(mojom::LifecycleState::kFrozen); + cu_graph.frame->SetLifecycleState( + resource_coordinator::mojom::LifecycleState::kFrozen); } TEST_F(ProcessCoordinationUnitImplTest, ProcessLifeCycle) { @@ -112,4 +117,4 @@ EXPECT_EQ(base::TimeDelta(), process_cu->cumulative_cpu_usage()); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/coordination_unit/system_coordination_unit_impl.cc b/chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl.cc similarity index 88% rename from services/resource_coordinator/coordination_unit/system_coordination_unit_impl.cc rename to chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl.cc index 0588c7e..4c0fb81 100644 --- a/services/resource_coordinator/coordination_unit/system_coordination_unit_impl.cc +++ b/chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl.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 "services/resource_coordinator/coordination_unit/system_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" #include <algorithm> #include <iterator> @@ -14,10 +14,10 @@ #include "base/macros.h" #include "base/process/process_handle.h" -namespace resource_coordinator { +namespace performance_manager { SystemCoordinationUnitImpl::SystemCoordinationUnitImpl( - const CoordinationUnitID& id, + const resource_coordinator::CoordinationUnitID& id, CoordinationUnitGraph* graph, std::unique_ptr<service_manager::ServiceKeepaliveRef> keepalive_ref) : CoordinationUnitInterface(id, graph, std::move(keepalive_ref)) {} @@ -25,11 +25,12 @@ SystemCoordinationUnitImpl::~SystemCoordinationUnitImpl() = default; void SystemCoordinationUnitImpl::OnProcessCPUUsageReady() { - SendEvent(mojom::Event::kProcessCPUUsageReady); + SendEvent(resource_coordinator::mojom::Event::kProcessCPUUsageReady); } void SystemCoordinationUnitImpl::DistributeMeasurementBatch( - mojom::ProcessResourceMeasurementBatchPtr measurement_batch) { + resource_coordinator::mojom::ProcessResourceMeasurementBatchPtr + measurement_batch) { base::TimeDelta time_since_last_measurement; if (!last_measurement_end_time_.is_null()) { // Use the end of the measurement batch as a proxy for when every @@ -159,16 +160,17 @@ OnProcessCPUUsageReady(); } -void SystemCoordinationUnitImpl::OnEventReceived(mojom::Event event) { +void SystemCoordinationUnitImpl::OnEventReceived( + resource_coordinator::mojom::Event event) { for (auto& observer : observers()) observer.OnSystemEventReceived(this, event); } void SystemCoordinationUnitImpl::OnPropertyChanged( - mojom::PropertyType property_type, + resource_coordinator::mojom::PropertyType property_type, int64_t value) { for (auto& observer : observers()) observer.OnSystemPropertyChanged(this, property_type, value); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl.h b/chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl.h new file mode 100644 index 0000000..8ce6ba3 --- /dev/null +++ b/chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl.h
@@ -0,0 +1,60 @@ +// 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. + +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_SYSTEM_COORDINATION_UNIT_IMPL_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_SYSTEM_COORDINATION_UNIT_IMPL_H_ + +#include "base/macros.h" +#include "base/time/time.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_base.h" + +namespace performance_manager { + +class SystemCoordinationUnitImpl + : public CoordinationUnitInterface< + SystemCoordinationUnitImpl, + resource_coordinator::mojom::SystemCoordinationUnit, + resource_coordinator::mojom::SystemCoordinationUnitRequest> { + public: + static resource_coordinator::CoordinationUnitType Type() { + return resource_coordinator::CoordinationUnitType::kSystem; + } + + SystemCoordinationUnitImpl( + const resource_coordinator::CoordinationUnitID& id, + CoordinationUnitGraph* graph, + std::unique_ptr<service_manager::ServiceKeepaliveRef> keepalive_ref); + ~SystemCoordinationUnitImpl() override; + + // resource_coordinator::mojom::SystemCoordinationUnit implementation: + void OnProcessCPUUsageReady() override; + void DistributeMeasurementBatch( + resource_coordinator::mojom::ProcessResourceMeasurementBatchPtr + measurement_batch) override; + + // Accessors for the start/end times bracketing when the last performance + // measurement occurred. + base::TimeTicks last_measurement_start_time() const { + return last_measurement_start_time_; + } + base::TimeTicks last_measurement_end_time() const { + return last_measurement_end_time_; + } + + private: + base::TimeTicks last_measurement_start_time_; + base::TimeTicks last_measurement_end_time_; + + // CoordinationUnitInterface implementation: + void OnEventReceived(resource_coordinator::mojom::Event event) override; + void OnPropertyChanged( + resource_coordinator::mojom::PropertyType property_type, + int64_t value) override; + + DISALLOW_COPY_AND_ASSIGN(SystemCoordinationUnitImpl); +}; + +} // namespace performance_manager + +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_COORDINATION_UNIT_SYSTEM_COORDINATION_UNIT_IMPL_H_
diff --git a/services/resource_coordinator/coordination_unit/system_coordination_unit_impl_unittest.cc b/chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl_unittest.cc similarity index 71% rename from services/resource_coordinator/coordination_unit/system_coordination_unit_impl_unittest.cc rename to chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl_unittest.cc index 6c35ff4..f4db7e5 100644 --- a/services/resource_coordinator/coordination_unit/system_coordination_unit_impl_unittest.cc +++ b/chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl_unittest.cc
@@ -2,20 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/coordination_unit/system_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl.h" #include "base/test/simple_test_tick_clock.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_test_harness.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/mock_coordination_unit_graphs.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/system_coordination_unit_impl.h" -#include "services/resource_coordinator/observers/coordination_unit_graph_observer.h" -#include "services/resource_coordinator/resource_coordinator_clock.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/observers/coordination_unit_graph_observer.h" +#include "chrome/browser/performance_manager/resource_coordinator_clock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace resource_coordinator { +namespace performance_manager { namespace { @@ -25,18 +25,20 @@ // CoordinationUnitGraphObserver implementation: bool ShouldObserve(const CoordinationUnitBase* coordination_unit) override { auto cu_type = coordination_unit->id().type; - return cu_type == CoordinationUnitType::kSystem; + return cu_type == resource_coordinator::CoordinationUnitType::kSystem; } - void OnSystemEventReceived(const SystemCoordinationUnitImpl* system_cu, - const mojom::Event event) override { - EXPECT_EQ(mojom::Event::kProcessCPUUsageReady, event); + void OnSystemEventReceived( + const SystemCoordinationUnitImpl* system_cu, + const resource_coordinator::mojom::Event event) override { + EXPECT_EQ(resource_coordinator::mojom::Event::kProcessCPUUsageReady, event); ++system_event_seen_count_; } - void OnProcessPropertyChanged(const ProcessCoordinationUnitImpl* process_cu, - const mojom::PropertyType property, - int64_t value) override { + void OnProcessPropertyChanged( + const ProcessCoordinationUnitImpl* process_cu, + const resource_coordinator::mojom::PropertyType property, + int64_t value) override { ++process_property_change_seen_count_; } @@ -68,18 +70,18 @@ base::SimpleTestTickClock clock_; }; -mojom::ProcessResourceMeasurementBatchPtr CreateMeasurementBatch( - base::TimeTicks start_end_time, - size_t num_processes, - base::TimeDelta additional_cpu_time) { - mojom::ProcessResourceMeasurementBatchPtr batch = - mojom::ProcessResourceMeasurementBatch::New(); +resource_coordinator::mojom::ProcessResourceMeasurementBatchPtr +CreateMeasurementBatch(base::TimeTicks start_end_time, + size_t num_processes, + base::TimeDelta additional_cpu_time) { + resource_coordinator::mojom::ProcessResourceMeasurementBatchPtr batch = + resource_coordinator::mojom::ProcessResourceMeasurementBatch::New(); batch->batch_started_time = start_end_time; batch->batch_ended_time = start_end_time; for (size_t i = 1; i <= num_processes; ++i) { - mojom::ProcessResourceMeasurementPtr measurement = - mojom::ProcessResourceMeasurement::New(); + resource_coordinator::mojom::ProcessResourceMeasurementPtr measurement = + resource_coordinator::mojom::ProcessResourceMeasurement::New(); measurement->pid = i; measurement->cpu_usage = base::TimeDelta::FromMicroseconds(i * 10) + additional_cpu_time; @@ -127,15 +129,15 @@ // The first measurement batch results in a zero CPU usage for the processes. int64_t cpu_usage; - EXPECT_TRUE(cu_graph.process->GetProperty(mojom::PropertyType::kCPUUsage, - &cpu_usage)); + EXPECT_TRUE(cu_graph.process->GetProperty( + resource_coordinator::mojom::PropertyType::kCPUUsage, &cpu_usage)); EXPECT_EQ(0, cpu_usage); EXPECT_EQ(100u, cu_graph.process->private_footprint_kb()); EXPECT_EQ(base::TimeDelta::FromMicroseconds(10u), cu_graph.process->cumulative_cpu_usage()); EXPECT_TRUE(cu_graph.other_process->GetProperty( - mojom::PropertyType::kCPUUsage, &cpu_usage)); + resource_coordinator::mojom::PropertyType::kCPUUsage, &cpu_usage)); EXPECT_EQ(0, cpu_usage); EXPECT_EQ(200u, cu_graph.other_process->private_footprint_kb()); EXPECT_EQ(base::TimeDelta::FromMicroseconds(20u), @@ -153,13 +155,13 @@ cu_graph.system->DistributeMeasurementBatch( CreateMeasurementBatch(start_time + base::TimeDelta::FromMicroseconds(10), 3, base::TimeDelta::FromMicroseconds(10))); - EXPECT_TRUE(cu_graph.process->GetProperty(mojom::PropertyType::kCPUUsage, - &cpu_usage)); + EXPECT_TRUE(cu_graph.process->GetProperty( + resource_coordinator::mojom::PropertyType::kCPUUsage, &cpu_usage)); EXPECT_EQ(100000, cpu_usage); EXPECT_EQ(base::TimeDelta::FromMicroseconds(20u), cu_graph.process->cumulative_cpu_usage()); EXPECT_TRUE(cu_graph.other_process->GetProperty( - mojom::PropertyType::kCPUUsage, &cpu_usage)); + resource_coordinator::mojom::PropertyType::kCPUUsage, &cpu_usage)); EXPECT_EQ(100000, cpu_usage); EXPECT_EQ(base::TimeDelta::FromMicroseconds(30u), cu_graph.other_process->cumulative_cpu_usage()); @@ -179,15 +181,15 @@ CreateMeasurementBatch(start_time + base::TimeDelta::FromMicroseconds(20), 1, base::TimeDelta::FromMicroseconds(310))); - EXPECT_TRUE(cu_graph.process->GetProperty(mojom::PropertyType::kCPUUsage, - &cpu_usage)); + EXPECT_TRUE(cu_graph.process->GetProperty( + resource_coordinator::mojom::PropertyType::kCPUUsage, &cpu_usage)); EXPECT_EQ(3000000, cpu_usage); EXPECT_EQ(100u, cu_graph.process->private_footprint_kb()); EXPECT_EQ(base::TimeDelta::FromMicroseconds(320u), cu_graph.process->cumulative_cpu_usage()); EXPECT_TRUE(cu_graph.other_process->GetProperty( - mojom::PropertyType::kCPUUsage, &cpu_usage)); + resource_coordinator::mojom::PropertyType::kCPUUsage, &cpu_usage)); EXPECT_EQ(0, cpu_usage); EXPECT_EQ(0u, cu_graph.other_process->private_footprint_kb()); EXPECT_EQ(base::TimeDelta::FromMicroseconds(30u), @@ -202,4 +204,4 @@ EXPECT_EQ(50u, cu_graph.other_page->private_footprint_kb_estimate()); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/public/cpp/frame_resource_coordinator.cc b/chrome/browser/performance_manager/frame_resource_coordinator.cc similarity index 69% rename from services/resource_coordinator/public/cpp/frame_resource_coordinator.cc rename to chrome/browser/performance_manager/frame_resource_coordinator.cc index 0a380057..a9d6caea 100644 --- a/services/resource_coordinator/public/cpp/frame_resource_coordinator.cc +++ b/chrome/browser/performance_manager/frame_resource_coordinator.cc
@@ -2,19 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/public/cpp/frame_resource_coordinator.h" +#include "chrome/browser/performance_manager/frame_resource_coordinator.h" #include "base/bind.h" -#include "services/resource_coordinator/public/cpp/process_resource_coordinator.h" +#include "chrome/browser/performance_manager/process_resource_coordinator.h" -namespace resource_coordinator { +namespace performance_manager { FrameResourceCoordinator::FrameResourceCoordinator( - service_manager::Connector* connector) + PerformanceManager* performance_manager) : ResourceCoordinatorInterface(), weak_ptr_factory_(this) { - CoordinationUnitID new_cu_id(CoordinationUnitType::kFrame, - CoordinationUnitID::RANDOM_ID); - ResourceCoordinatorInterface::ConnectToService(connector, new_cu_id); + resource_coordinator::CoordinationUnitID new_cu_id( + resource_coordinator::CoordinationUnitType::kFrame, + resource_coordinator::CoordinationUnitID::RANDOM_ID); + ResourceCoordinatorInterface::ConnectToService(performance_manager, + new_cu_id); } FrameResourceCoordinator::~FrameResourceCoordinator() = default; @@ -51,30 +53,30 @@ } void FrameResourceCoordinator::ConnectToService( - mojom::CoordinationUnitProviderPtr& provider, - const CoordinationUnitID& cu_id) { + resource_coordinator::mojom::CoordinationUnitProviderPtr& provider, + const resource_coordinator::CoordinationUnitID& cu_id) { provider->CreateFrameCoordinationUnit(mojo::MakeRequest(&service_), cu_id); } void FrameResourceCoordinator::SetProcessByID( - const CoordinationUnitID& process_id) { + const resource_coordinator::CoordinationUnitID& process_id) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (service_) service_->SetProcess(process_id); } void FrameResourceCoordinator::AddChildFrameByID( - const CoordinationUnitID& child_id) { + const resource_coordinator::CoordinationUnitID& child_id) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (service_) service_->AddChildFrame(child_id); } void FrameResourceCoordinator::RemoveChildFrameByID( - const CoordinationUnitID& child_id) { + const resource_coordinator::CoordinationUnitID& child_id) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (service_) service_->RemoveChildFrame(child_id); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/chrome/browser/performance_manager/frame_resource_coordinator.h b/chrome/browser/performance_manager/frame_resource_coordinator.h new file mode 100644 index 0000000..3176f7d --- /dev/null +++ b/chrome/browser/performance_manager/frame_resource_coordinator.h
@@ -0,0 +1,55 @@ +// Copyright 2017 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_PERFORMANCE_MANAGER_FRAME_RESOURCE_COORDINATOR_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_FRAME_RESOURCE_COORDINATOR_H_ + +#include "base/memory/weak_ptr.h" +#include "base/threading/thread_checker.h" +#include "chrome/browser/performance_manager/resource_coordinator_interface.h" +#include "services/resource_coordinator/public/mojom/coordination_unit.mojom.h" + +namespace performance_manager { + +class ProcessResourceCoordinator; + +class FrameResourceCoordinator + : public ResourceCoordinatorInterface< + resource_coordinator::mojom::FrameCoordinationUnitPtr, + resource_coordinator::mojom::FrameCoordinationUnitRequest> { + public: + explicit FrameResourceCoordinator(PerformanceManager* performance_manager); + ~FrameResourceCoordinator() override; + + void SetProcess(const ProcessResourceCoordinator& process); + void AddChildFrame(const FrameResourceCoordinator& child); + void RemoveChildFrame(const FrameResourceCoordinator& child); + + // Closes the connection to the service. + void reset() { service_.reset(); } + + private: + void ConnectToService( + resource_coordinator::mojom::CoordinationUnitProviderPtr& provider, + const resource_coordinator::CoordinationUnitID& cu_id) override; + + void SetProcessByID( + const resource_coordinator::CoordinationUnitID& process_id); + void AddChildFrameByID( + const resource_coordinator::CoordinationUnitID& child_id); + void RemoveChildFrameByID( + const resource_coordinator::CoordinationUnitID& child_id); + + THREAD_CHECKER(thread_checker_); + + // The WeakPtrFactory should come last so the weak ptrs are invalidated + // before the rest of the member variables. + base::WeakPtrFactory<FrameResourceCoordinator> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(FrameResourceCoordinator); +}; + +} // namespace performance_manager + +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_FRAME_RESOURCE_COORDINATOR_H_
diff --git a/services/resource_coordinator/observers/background_metrics_reporter.h b/chrome/browser/performance_manager/observers/background_metrics_reporter.h similarity index 92% rename from services/resource_coordinator/observers/background_metrics_reporter.h rename to chrome/browser/performance_manager/observers/background_metrics_reporter.h index e14287c..d513cf8c 100644 --- a/services/resource_coordinator/observers/background_metrics_reporter.h +++ b/chrome/browser/performance_manager/observers/background_metrics_reporter.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 SERVICES_RESOURCE_COORDINATOR_OBSERVER_BACKGROUND_METRICS_REPORTER_H_ -#define SERVICES_RESOURCE_COORDINATOR_OBSERVER_BACKGROUND_METRICS_REPORTER_H_ +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_OBSERVERS_BACKGROUND_METRICS_REPORTER_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_OBSERVERS_BACKGROUND_METRICS_REPORTER_H_ #include "base/macros.h" #include "base/metrics/histogram_macros.h" @@ -19,7 +19,7 @@ UMA_HISTOGRAM_CUSTOM_TIMES(name, sample, base::TimeDelta::FromSeconds(1), \ base::TimeDelta::FromHours(48), 100) -namespace resource_coordinator { +namespace performance_manager { namespace internal { @@ -128,6 +128,6 @@ ukm_reporter_; }; -} // namespace resource_coordinator +} // namespace performance_manager -#endif // SERVICES_RESOURCE_COORDINATOR_OBSERVER_BACKGROUND_METRICS_REPORTER_H_ +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_OBSERVERS_BACKGROUND_METRICS_REPORTER_H_
diff --git a/services/resource_coordinator/observers/coordination_unit_graph_observer.cc b/chrome/browser/performance_manager/observers/coordination_unit_graph_observer.cc similarity index 66% rename from services/resource_coordinator/observers/coordination_unit_graph_observer.cc rename to chrome/browser/performance_manager/observers/coordination_unit_graph_observer.cc index 7e752f1a..871d1647 100644 --- a/services/resource_coordinator/observers/coordination_unit_graph_observer.cc +++ b/chrome/browser/performance_manager/observers/coordination_unit_graph_observer.cc
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/observers/coordination_unit_graph_observer.h" +#include "chrome/browser/performance_manager/observers/coordination_unit_graph_observer.h" -namespace resource_coordinator { +namespace performance_manager { CoordinationUnitGraphObserver::CoordinationUnitGraphObserver() = default; CoordinationUnitGraphObserver::~CoordinationUnitGraphObserver() = default; -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/observers/coordination_unit_graph_observer.h b/chrome/browser/performance_manager/observers/coordination_unit_graph_observer.h similarity index 70% rename from services/resource_coordinator/observers/coordination_unit_graph_observer.h rename to chrome/browser/performance_manager/observers/coordination_unit_graph_observer.h index 078c33f4..c4f5aa3 100644 --- a/services/resource_coordinator/observers/coordination_unit_graph_observer.h +++ b/chrome/browser/performance_manager/observers/coordination_unit_graph_observer.h
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_GRAPH_OBSERVER_H_ -#define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_GRAPH_OBSERVER_H_ +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_OBSERVERS_COORDINATION_UNIT_GRAPH_OBSERVER_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_OBSERVERS_COORDINATION_UNIT_GRAPH_OBSERVER_H_ #include "base/macros.h" #include "services/resource_coordinator/public/mojom/coordination_unit.mojom.h" -namespace resource_coordinator { +namespace performance_manager { class CoordinationUnitBase; class CoordinationUnitGraph; @@ -50,46 +50,52 @@ // Called whenever a property of the |coordination_unit| is changed if the // |coordination_unit| doesn't implement its own PropertyChanged handler. - virtual void OnPropertyChanged(const CoordinationUnitBase* coordination_unit, - const mojom::PropertyType property_type, - int64_t value) {} + virtual void OnPropertyChanged( + const CoordinationUnitBase* coordination_unit, + const resource_coordinator::mojom::PropertyType property_type, + int64_t value) {} // Called whenever a property of the FrameCoordinationUnit is changed. - virtual void OnFramePropertyChanged(const FrameCoordinationUnitImpl* frame_cu, - const mojom::PropertyType property_type, - int64_t value) {} + virtual void OnFramePropertyChanged( + const FrameCoordinationUnitImpl* frame_cu, + const resource_coordinator::mojom::PropertyType property_type, + int64_t value) {} // Called whenever a property of the PageCoordinationUnit is changed. - virtual void OnPagePropertyChanged(const PageCoordinationUnitImpl* page_cu, - const mojom::PropertyType property_type, - int64_t value) {} + virtual void OnPagePropertyChanged( + const PageCoordinationUnitImpl* page_cu, + const resource_coordinator::mojom::PropertyType property_type, + int64_t value) {} // Called whenever a property of the ProcessCoordinationUnit is changed. virtual void OnProcessPropertyChanged( const ProcessCoordinationUnitImpl* process_cu, - const mojom::PropertyType property_type, + const resource_coordinator::mojom::PropertyType property_type, int64_t value) {} // Called whenever a property of the SystemCoordinationUnit is changed. virtual void OnSystemPropertyChanged( const SystemCoordinationUnitImpl* system_cu, - const mojom::PropertyType property_type, + const resource_coordinator::mojom::PropertyType property_type, int64_t value) {} // Called whenever an event is received in |coordination_unit| if the // |coordination_unit| doesn't implement its own EventReceived handler. virtual void OnEventReceived(const CoordinationUnitBase* coordination_unit, - const mojom::Event event) {} - virtual void OnFrameEventReceived(const FrameCoordinationUnitImpl* frame_cu, - const mojom::Event event) {} - virtual void OnPageEventReceived(const PageCoordinationUnitImpl* page_cu, - const mojom::Event event) {} + const resource_coordinator::mojom::Event event) { + } + virtual void OnFrameEventReceived( + const FrameCoordinationUnitImpl* frame_cu, + const resource_coordinator::mojom::Event event) {} + virtual void OnPageEventReceived( + const PageCoordinationUnitImpl* page_cu, + const resource_coordinator::mojom::Event event) {} virtual void OnProcessEventReceived( const ProcessCoordinationUnitImpl* process_cu, - const mojom::Event event) {} + const resource_coordinator::mojom::Event event) {} virtual void OnSystemEventReceived( const SystemCoordinationUnitImpl* system_cu, - const mojom::Event event) {} + const resource_coordinator::mojom::Event event) {} // Called when all the frames in a process become frozen. virtual void OnAllFramesInProcessFrozen( @@ -110,6 +116,6 @@ DISALLOW_COPY_AND_ASSIGN(CoordinationUnitGraphObserver); }; -} // namespace resource_coordinator +} // namespace performance_manager -#endif // SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_GRAPH_OBSERVER_H_ +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_OBSERVERS_COORDINATION_UNIT_GRAPH_OBSERVER_H_
diff --git a/services/resource_coordinator/observers/coordination_unit_graph_observer_unittest.cc b/chrome/browser/performance_manager/observers/coordination_unit_graph_observer_unittest.cc similarity index 77% rename from services/resource_coordinator/observers/coordination_unit_graph_observer_unittest.cc rename to chrome/browser/performance_manager/observers/coordination_unit_graph_observer_unittest.cc index e4bb924..5dc930a 100644 --- a/services/resource_coordinator/observers/coordination_unit_graph_observer_unittest.cc +++ b/chrome/browser/performance_manager/observers/coordination_unit_graph_observer_unittest.cc
@@ -2,19 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/observers/coordination_unit_graph_observer.h" +#include "chrome/browser/performance_manager/observers/coordination_unit_graph_observer.h" #include "base/process/process_handle.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_graph.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_test_harness.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" #include "services/resource_coordinator/public/cpp/coordination_unit_id.h" #include "services/resource_coordinator/public/cpp/coordination_unit_types.h" #include "services/resource_coordinator/public/mojom/coordination_unit.mojom.h" #include "testing/gtest/include/gtest/gtest.h" -namespace resource_coordinator { +namespace performance_manager { namespace { @@ -37,7 +37,8 @@ // Overridden from CoordinationUnitGraphObserver. bool ShouldObserve(const CoordinationUnitBase* coordination_unit) override { - return coordination_unit->id().type == CoordinationUnitType::kFrame; + return coordination_unit->id().type == + resource_coordinator::CoordinationUnitType::kFrame; } void OnCoordinationUnitCreated( const CoordinationUnitBase* coordination_unit) override { @@ -49,7 +50,7 @@ } void OnFramePropertyChanged( const FrameCoordinationUnitImpl* frame_coordination_unit, - const mojom::PropertyType property_type, + const resource_coordinator::mojom::PropertyType property_type, int64_t value) override { ++property_changed_count_; } @@ -81,8 +82,8 @@ // The registered observer will only observe the events that happen to // |root_frame_coordination_unit| and |frame_coordination_unit| because - // they are CoordinationUnitType::kFrame, so OnPropertyChanged - // will only be called for |root_frame_coordination_unit|. + // they are resource_coordinator::CoordinationUnitType::kFrame, so + // OnPropertyChanged will only be called for |root_frame_coordination_unit|. root_frame_cu->SetPropertyForTesting(42); process_cu->SetPropertyForTesting(42); EXPECT_EQ(1u, observer->property_changed_count()); @@ -91,4 +92,4 @@ EXPECT_EQ(2u, observer->coordination_unit_destroyed_count()); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/observers/metrics_collector.cc b/chrome/browser/performance_manager/observers/metrics_collector.cc similarity index 75% rename from services/resource_coordinator/observers/metrics_collector.cc rename to chrome/browser/performance_manager/observers/metrics_collector.cc index acf4a169..2fe7532 100644 --- a/services/resource_coordinator/observers/metrics_collector.cc +++ b/chrome/browser/performance_manager/observers/metrics_collector.cc
@@ -2,19 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/observers/metrics_collector.h" +#include "chrome/browser/performance_manager/observers/metrics_collector.h" #include "base/metrics/field_trial_params.h" #include "base/metrics/histogram_macros.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_graph.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/resource_coordinator_clock.h" #include "services/resource_coordinator/public/cpp/coordination_unit_id.h" #include "services/resource_coordinator/public/cpp/resource_coordinator_features.h" -#include "services/resource_coordinator/resource_coordinator_clock.h" -namespace resource_coordinator { +namespace performance_manager { // Delay the metrics report from GRC to UMA/UKM for 5 minutes from when the main // frame navigation is committed. @@ -32,7 +32,8 @@ const int kDefaultFrequencyUkmEQTReported = 5u; // Gets the number of tabs that are co-resident in all of the render processes -// associated with a |CoordinationUnitType::kPage| coordination unit. +// associated with a |resource_coordinator::CoordinationUnitType::kPage| +// coordination unit. size_t GetNumCoresidentTabs(const PageCoordinationUnitImpl* page_cu) { std::set<CoordinationUnitBase*> coresident_tabs; for (auto* process_cu : page_cu->GetAssociatedProcessCoordinationUnits()) { @@ -53,14 +54,18 @@ bool MetricsCollector::ShouldObserve( const CoordinationUnitBase* coordination_unit) { - return coordination_unit->id().type == CoordinationUnitType::kFrame || - coordination_unit->id().type == CoordinationUnitType::kPage || - coordination_unit->id().type == CoordinationUnitType::kProcess; + return coordination_unit->id().type == + resource_coordinator::CoordinationUnitType::kFrame || + coordination_unit->id().type == + resource_coordinator::CoordinationUnitType::kPage || + coordination_unit->id().type == + resource_coordinator::CoordinationUnitType::kProcess; } void MetricsCollector::OnCoordinationUnitCreated( const CoordinationUnitBase* coordination_unit) { - if (coordination_unit->id().type == CoordinationUnitType::kPage) { + if (coordination_unit->id().type == + resource_coordinator::CoordinationUnitType::kPage) { metrics_report_record_map_.emplace(coordination_unit->id(), MetricsReportRecord()); } @@ -68,7 +73,8 @@ void MetricsCollector::OnBeforeCoordinationUnitDestroyed( const CoordinationUnitBase* coordination_unit) { - if (coordination_unit->id().type == CoordinationUnitType::kPage) { + if (coordination_unit->id().type == + resource_coordinator::CoordinationUnitType::kPage) { metrics_report_record_map_.erase(coordination_unit->id()); ukm_collection_state_map_.erase(coordination_unit->id()); } @@ -76,17 +82,18 @@ void MetricsCollector::OnPagePropertyChanged( const PageCoordinationUnitImpl* page_cu, - const mojom::PropertyType property_type, + const resource_coordinator::mojom::PropertyType property_type, int64_t value) { const auto page_cu_id = page_cu->id(); - if (property_type == mojom::PropertyType::kVisible) { + if (property_type == resource_coordinator::mojom::PropertyType::kVisible) { if (value) { // The page becomes visible again, clear all records in order to // report metrics when page becomes invisible next time. ResetMetricsReportRecord(page_cu_id); return; } - } else if (property_type == mojom::PropertyType::kUKMSourceId) { + } else if (property_type == + resource_coordinator::mojom::PropertyType::kUKMSourceId) { ukm::SourceId ukm_source_id = value; UpdateUkmSourceIdForPage(page_cu_id, ukm_source_id); MetricsReportRecord& record = @@ -97,9 +104,10 @@ void MetricsCollector::OnProcessPropertyChanged( const ProcessCoordinationUnitImpl* process_cu, - const mojom::PropertyType property_type, + const resource_coordinator::mojom::PropertyType property_type, int64_t value) { - if (property_type == mojom::PropertyType::kExpectedTaskQueueingDuration) { + if (property_type == resource_coordinator::mojom::PropertyType:: + kExpectedTaskQueueingDuration) { for (auto* page_cu : process_cu->GetAssociatedPageCoordinationUnits()) { if (IsCollectingExpectedQueueingTimeForUkm(page_cu->id())) { int64_t expected_queueing_time; @@ -114,8 +122,9 @@ void MetricsCollector::OnFrameEventReceived( const FrameCoordinationUnitImpl* frame_cu, - const mojom::Event event) { - if (event == mojom::Event::kNonPersistentNotificationCreated) { + const resource_coordinator::mojom::Event event) { + if (event == + resource_coordinator::mojom::Event::kNonPersistentNotificationCreated) { auto* page_cu = frame_cu->GetPageCoordinationUnit(); // Only record metrics while it is backgrounded. if (!page_cu || page_cu->IsVisible() || !ShouldReportMetrics(page_cu)) { @@ -131,8 +140,8 @@ void MetricsCollector::OnPageEventReceived( const PageCoordinationUnitImpl* page_cu, - const mojom::Event event) { - if (event == mojom::Event::kTitleUpdated) { + const resource_coordinator::mojom::Event event) { + if (event == resource_coordinator::mojom::Event::kTitleUpdated) { // Only record metrics while it is backgrounded. if (page_cu->IsVisible() || !ShouldReportMetrics(page_cu)) return; @@ -141,7 +150,7 @@ record.first_title_updated.OnSignalReceived( true, page_cu->TimeSinceLastVisibilityChange(), coordination_unit_graph().ukm_recorder()); - } else if (event == mojom::Event::kFaviconUpdated) { + } else if (event == resource_coordinator::mojom::Event::kFaviconUpdated) { // Only record metrics while it is backgrounded. if (page_cu->IsVisible() || !ShouldReportMetrics(page_cu)) return; @@ -159,14 +168,14 @@ } bool MetricsCollector::IsCollectingExpectedQueueingTimeForUkm( - const CoordinationUnitID& page_cu_id) { + const resource_coordinator::CoordinationUnitID& page_cu_id) { UkmCollectionState& state = ukm_collection_state_map_[page_cu_id]; return state.ukm_source_id != ukm::kInvalidSourceId && ++state.num_unreported_eqt_measurements >= frequency_ukm_eqt_reported_; } void MetricsCollector::RecordExpectedQueueingTimeForUkm( - const CoordinationUnitID& page_cu_id, + const resource_coordinator::CoordinationUnitID& page_cu_id, int64_t expected_queueing_time) { UkmCollectionState& state = ukm_collection_state_map_[page_cu_id]; state.num_unreported_eqt_measurements = 0u; @@ -176,7 +185,7 @@ } void MetricsCollector::UpdateUkmSourceIdForPage( - const CoordinationUnitID& page_cu_id, + const resource_coordinator::CoordinationUnitID& page_cu_id, ukm::SourceId ukm_source_id) { UkmCollectionState& state = ukm_collection_state_map_[page_cu_id]; @@ -191,7 +200,8 @@ kDefaultFrequencyUkmEQTReported); } -void MetricsCollector::ResetMetricsReportRecord(CoordinationUnitID cu_id) { +void MetricsCollector::ResetMetricsReportRecord( + resource_coordinator::CoordinationUnitID cu_id) { DCHECK(metrics_report_record_map_.find(cu_id) != metrics_report_record_map_.end()); metrics_report_record_map_.find(cu_id)->second.Reset(); @@ -215,4 +225,4 @@ first_title_updated.Reset(); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/observers/metrics_collector.h b/chrome/browser/performance_manager/observers/metrics_collector.h similarity index 63% rename from services/resource_coordinator/observers/metrics_collector.h rename to chrome/browser/performance_manager/observers/metrics_collector.h index 7b5e03a..d66c956b 100644 --- a/services/resource_coordinator/observers/metrics_collector.h +++ b/chrome/browser/performance_manager/observers/metrics_collector.h
@@ -2,18 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_METRICS_COLLECTOR_H_ -#define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_METRICS_COLLECTOR_H_ +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_OBSERVERS_METRICS_COLLECTOR_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_OBSERVERS_METRICS_COLLECTOR_H_ + +#include <map> #include "base/macros.h" #include "base/metrics/histogram_macros.h" #include "base/time/time.h" +#include "chrome/browser/performance_manager/observers/background_metrics_reporter.h" +#include "chrome/browser/performance_manager/observers/coordination_unit_graph_observer.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_source_id.h" -#include "services/resource_coordinator/observers/background_metrics_reporter.h" -#include "services/resource_coordinator/observers/coordination_unit_graph_observer.h" -namespace resource_coordinator { +namespace performance_manager { class CoordinationUnitBase; class FrameCoordinationUnitImpl; @@ -39,16 +41,20 @@ const CoordinationUnitBase* coordination_unit) override; void OnBeforeCoordinationUnitDestroyed( const CoordinationUnitBase* coordination_unit) override; - void OnPagePropertyChanged(const PageCoordinationUnitImpl* page_cu, - const mojom::PropertyType property_type, - int64_t value) override; - void OnProcessPropertyChanged(const ProcessCoordinationUnitImpl* process_cu, - const mojom::PropertyType property_type, - int64_t value) override; - void OnFrameEventReceived(const FrameCoordinationUnitImpl* frame_cu, - const mojom::Event event) override; - void OnPageEventReceived(const PageCoordinationUnitImpl* page_cu, - const mojom::Event event) override; + void OnPagePropertyChanged( + const PageCoordinationUnitImpl* page_cu, + const resource_coordinator::mojom::PropertyType property_type, + int64_t value) override; + void OnProcessPropertyChanged( + const ProcessCoordinationUnitImpl* process_cu, + const resource_coordinator::mojom::PropertyType property_type, + int64_t value) override; + void OnFrameEventReceived( + const FrameCoordinationUnitImpl* frame_cu, + const resource_coordinator::mojom::Event event) override; + void OnPageEventReceived( + const PageCoordinationUnitImpl* page_cu, + const resource_coordinator::mojom::Event event) override; private: struct MetricsReportRecord { @@ -81,18 +87,22 @@ bool ShouldReportMetrics(const PageCoordinationUnitImpl* page_cu); bool IsCollectingExpectedQueueingTimeForUkm( - const CoordinationUnitID& page_cu_id); - void RecordExpectedQueueingTimeForUkm(const CoordinationUnitID& page_cu_id, - int64_t expected_queueing_time); - void UpdateUkmSourceIdForPage(const CoordinationUnitID& page_cu_id, - ukm::SourceId ukm_source_id); + const resource_coordinator::CoordinationUnitID& page_cu_id); + void RecordExpectedQueueingTimeForUkm( + const resource_coordinator::CoordinationUnitID& page_cu_id, + int64_t expected_queueing_time); + void UpdateUkmSourceIdForPage( + const resource_coordinator::CoordinationUnitID& page_cu_id, + ukm::SourceId ukm_source_id); void UpdateWithFieldTrialParams(); - void ResetMetricsReportRecord(CoordinationUnitID cu_id); + void ResetMetricsReportRecord(resource_coordinator::CoordinationUnitID cu_id); // The metrics_report_record_map_ is used to record whether a metric was // already reported to avoid reporting multiple metrics. - std::map<CoordinationUnitID, MetricsReportRecord> metrics_report_record_map_; - std::map<CoordinationUnitID, UkmCollectionState> ukm_collection_state_map_; + std::map<resource_coordinator::CoordinationUnitID, MetricsReportRecord> + metrics_report_record_map_; + std::map<resource_coordinator::CoordinationUnitID, UkmCollectionState> + ukm_collection_state_map_; // The number of reports to wait before reporting ExpectedQueueingTime. For // example, if |frequency_ukm_eqt_reported_| is 2, then the first value is not // reported, the second one is, the third one isn't, etc. @@ -100,6 +110,6 @@ DISALLOW_COPY_AND_ASSIGN(MetricsCollector); }; -} // namespace resource_coordinator +} // namespace performance_manager -#endif // SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_METRICS_COLLECTOR_H_ +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_OBSERVERS_METRICS_COLLECTOR_H_
diff --git a/services/resource_coordinator/observers/metrics_collector_unittest.cc b/chrome/browser/performance_manager/observers/metrics_collector_unittest.cc similarity index 93% rename from services/resource_coordinator/observers/metrics_collector_unittest.cc rename to chrome/browser/performance_manager/observers/metrics_collector_unittest.cc index d976b64..858eb75 100644 --- a/services/resource_coordinator/observers/metrics_collector_unittest.cc +++ b/chrome/browser/performance_manager/observers/metrics_collector_unittest.cc
@@ -2,19 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/observers/metrics_collector.h" +#include "chrome/browser/performance_manager/observers/metrics_collector.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/simple_test_tick_clock.h" #include "build/build_config.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/resource_coordinator_clock.h" #include "components/ukm/test_ukm_recorder.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_test_harness.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" -#include "services/resource_coordinator/resource_coordinator_clock.h" -namespace resource_coordinator { +namespace performance_manager { const char kResponsivenessMeasurement[] = "ResponsivenessMeasurement"; const char kExpectedQueueingTime[] = "ExpectedTaskQueueingDuration"; @@ -41,9 +41,7 @@ base::WrapUnique(metrics_collector)); } - void TearDown() override { - ResourceCoordinatorClock::ResetClockForTesting(); - } + void TearDown() override { ResourceCoordinatorClock::ResetClockForTesting(); } protected: static constexpr char kDummyUrl[] = "http://www.example.org"; @@ -265,4 +263,4 @@ } } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/observers/page_signal_generator_impl.cc b/chrome/browser/performance_manager/observers/page_signal_generator_impl.cc similarity index 75% rename from services/resource_coordinator/observers/page_signal_generator_impl.cc rename to chrome/browser/performance_manager/observers/page_signal_generator_impl.cc index 876d195..1e1fa820 100644 --- a/services/resource_coordinator/observers/page_signal_generator_impl.cc +++ b/chrome/browser/performance_manager/observers/page_signal_generator_impl.cc
@@ -2,21 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/observers/page_signal_generator_impl.h" +#include "chrome/browser/performance_manager/observers/page_signal_generator_impl.h" #include <utility> #include "base/bind.h" #include "base/metrics/histogram_macros.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/system_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/system_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/resource_coordinator_clock.h" #include "services/resource_coordinator/public/cpp/resource_coordinator_features.h" -#include "services/resource_coordinator/resource_coordinator_clock.h" #include "services/service_manager/public/cpp/bind_source_info.h" -namespace resource_coordinator { +namespace performance_manager { namespace { @@ -58,7 +58,7 @@ PageSignalGeneratorImpl::~PageSignalGeneratorImpl() = default; void PageSignalGeneratorImpl::AddReceiver( - mojom::PageSignalReceiverPtr receiver) { + resource_coordinator::mojom::PageSignalReceiverPtr receiver) { receivers_.AddPtr(std::move(receiver)); } @@ -77,12 +77,12 @@ const CoordinationUnitBase* coordination_unit) { auto cu_type = coordination_unit->id().type; switch (cu_type) { - case CoordinationUnitType::kPage: - case CoordinationUnitType::kProcess: - case CoordinationUnitType::kSystem: + case resource_coordinator::CoordinationUnitType::kPage: + case resource_coordinator::CoordinationUnitType::kProcess: + case resource_coordinator::CoordinationUnitType::kSystem: return true; - case CoordinationUnitType::kFrame: + case resource_coordinator::CoordinationUnitType::kFrame: return resource_coordinator::IsPageAlmostIdleSignalEnabled(); default: @@ -94,7 +94,7 @@ void PageSignalGeneratorImpl::OnCoordinationUnitCreated( const CoordinationUnitBase* cu) { auto cu_type = cu->id().type; - if (cu_type != CoordinationUnitType::kPage) + if (cu_type != resource_coordinator::CoordinationUnitType::kPage) return; if (!resource_coordinator::IsPageAlmostIdleSignalEnabled()) @@ -110,7 +110,7 @@ void PageSignalGeneratorImpl::OnBeforeCoordinationUnitDestroyed( const CoordinationUnitBase* cu) { auto cu_type = cu->id().type; - if (cu_type != CoordinationUnitType::kPage) + if (cu_type != resource_coordinator::CoordinationUnitType::kPage) return; if (!resource_coordinator::IsPageAlmostIdleSignalEnabled()) @@ -123,33 +123,38 @@ void PageSignalGeneratorImpl::OnFramePropertyChanged( const FrameCoordinationUnitImpl* frame_cu, - const mojom::PropertyType property_type, + const resource_coordinator::mojom::PropertyType property_type, int64_t value) { DCHECK(resource_coordinator::IsPageAlmostIdleSignalEnabled()); // Only the network idle state of a frame is of interest. - if (property_type != mojom::PropertyType::kNetworkAlmostIdle) + if (property_type != + resource_coordinator::mojom::PropertyType::kNetworkAlmostIdle) return; UpdateLoadIdleStateFrame(frame_cu); } void PageSignalGeneratorImpl::OnPagePropertyChanged( const PageCoordinationUnitImpl* page_cu, - const mojom::PropertyType property_type, + const resource_coordinator::mojom::PropertyType property_type, int64_t value) { if (resource_coordinator::IsPageAlmostIdleSignalEnabled() && - property_type == mojom::PropertyType::kIsLoading) { + property_type == resource_coordinator::mojom::PropertyType::kIsLoading) { UpdateLoadIdleStatePage(page_cu); - } else if (property_type == mojom::PropertyType::kLifecycleState) { - UpdateLifecycleState(page_cu, static_cast<mojom::LifecycleState>(value)); + } else if (property_type == + resource_coordinator::mojom::PropertyType::kLifecycleState) { + UpdateLifecycleState( + page_cu, + static_cast<resource_coordinator::mojom::LifecycleState>(value)); } } void PageSignalGeneratorImpl::OnProcessPropertyChanged( const ProcessCoordinationUnitImpl* process_cu, - const mojom::PropertyType property_type, + const resource_coordinator::mojom::PropertyType property_type, int64_t value) { - if (property_type == mojom::PropertyType::kExpectedTaskQueueingDuration) { + if (property_type == resource_coordinator::mojom::PropertyType:: + kExpectedTaskQueueingDuration) { for (auto* frame_cu : process_cu->GetFrameCoordinationUnits()) { if (!frame_cu->IsMainFrame()) continue; @@ -157,13 +162,15 @@ int64_t duration; if (!page_cu || !page_cu->GetExpectedTaskQueueingDuration(&duration)) continue; - DispatchPageSignal( - page_cu, &mojom::PageSignalReceiver::SetExpectedTaskQueueingDuration, - base::TimeDelta::FromMilliseconds(duration)); + DispatchPageSignal(page_cu, + &resource_coordinator::mojom::PageSignalReceiver:: + SetExpectedTaskQueueingDuration, + base::TimeDelta::FromMilliseconds(duration)); } } else { if (resource_coordinator::IsPageAlmostIdleSignalEnabled() && - property_type == mojom::PropertyType::kMainThreadTaskLoadIsLow) { + property_type == resource_coordinator::mojom::PropertyType:: + kMainThreadTaskLoadIsLow) { UpdateLoadIdleStateProcess(process_cu); } } @@ -171,28 +178,28 @@ void PageSignalGeneratorImpl::OnFrameEventReceived( const FrameCoordinationUnitImpl* frame_cu, - const mojom::Event event) { - if (event != mojom::Event::kNonPersistentNotificationCreated) + const resource_coordinator::mojom::Event event) { + if (event != + resource_coordinator::mojom::Event::kNonPersistentNotificationCreated) return; auto* page_cu = frame_cu->GetPageCoordinationUnit(); if (!page_cu) return; - DispatchPageSignal( - page_cu, - &mojom::PageSignalReceiver::NotifyNonPersistentNotificationCreated); + DispatchPageSignal(page_cu, &resource_coordinator::mojom::PageSignalReceiver:: + NotifyNonPersistentNotificationCreated); } void PageSignalGeneratorImpl::OnPageEventReceived( const PageCoordinationUnitImpl* page_cu, - const mojom::Event event) { + const resource_coordinator::mojom::Event event) { // We only care about the events if network idle signal is enabled. if (!resource_coordinator::IsPageAlmostIdleSignalEnabled()) return; // Only the navigation committed event is of interest. - if (event != mojom::Event::kNavigationCommitted) + if (event != resource_coordinator::mojom::Event::kNavigationCommitted) return; // Reset the load-idle state associated with this page as a new navigation has @@ -204,15 +211,16 @@ void PageSignalGeneratorImpl::OnProcessEventReceived( const ProcessCoordinationUnitImpl* process_cu, - const mojom::Event event) { - if (event == mojom::Event::kRendererIsBloated) { + const resource_coordinator::mojom::Event event) { + if (event == resource_coordinator::mojom::Event::kRendererIsBloated) { std::set<PageCoordinationUnitImpl*> page_cus = process_cu->GetAssociatedPageCoordinationUnits(); // Currently bloated renderer handling supports only a single page. if (page_cus.size() == 1u) { auto* page_cu = *page_cus.begin(); DispatchPageSignal(page_cu, - &mojom::PageSignalReceiver::NotifyRendererIsBloated); + &resource_coordinator::mojom::PageSignalReceiver:: + NotifyRendererIsBloated); RecordBloatedRendererHandling( BloatedRendererHandlingInResourceCoordinator::kForwardedToBrowser); } else { @@ -225,8 +233,8 @@ void PageSignalGeneratorImpl::OnSystemEventReceived( const SystemCoordinationUnitImpl* system_cu, - const mojom::Event event) { - if (event == mojom::Event::kProcessCPUUsageReady) { + const resource_coordinator::mojom::Event event) { + if (event == resource_coordinator::mojom::Event::kProcessCPUUsageReady) { base::TimeTicks measurement_start = system_cu->last_measurement_start_time(); @@ -241,11 +249,12 @@ if (data->GetLoadIdleState() == kLoadedAndIdle && !data->performance_estimate_issued && data->last_state_change < measurement_start) { - DispatchPageSignal( - page, &mojom::PageSignalReceiver::OnLoadTimePerformanceEstimate, - page->TimeSinceLastNavigation(), - page->cumulative_cpu_usage_estimate(), - page->private_footprint_kb_estimate()); + DispatchPageSignal(page, + &resource_coordinator::mojom::PageSignalReceiver:: + OnLoadTimePerformanceEstimate, + page->TimeSinceLastNavigation(), + page->cumulative_cpu_usage_estimate(), + page->private_footprint_kb_estimate()); data->performance_estimate_issued = true; } } @@ -357,8 +366,8 @@ } page_data->idling_timer.Start( FROM_HERE, timeout, - base::Bind(&PageSignalGeneratorImpl::UpdateLoadIdleStatePage, - base::Unretained(this), page_cu)); + base::BindRepeating(&PageSignalGeneratorImpl::UpdateLoadIdleStatePage, + base::Unretained(this), page_cu)); } void PageSignalGeneratorImpl::UpdateLoadIdleStateProcess( @@ -370,9 +379,11 @@ void PageSignalGeneratorImpl::UpdateLifecycleState( const PageCoordinationUnitImpl* page_cu, - const mojom::LifecycleState state) { - DispatchPageSignal(page_cu, &mojom::PageSignalReceiver::SetLifecycleState, - state); + const resource_coordinator::mojom::LifecycleState state) { + DispatchPageSignal( + page_cu, + &resource_coordinator::mojom::PageSignalReceiver::SetLifecycleState, + state); } void PageSignalGeneratorImpl::TransitionToLoadedAndIdle( @@ -382,7 +393,9 @@ auto* page_data = GetPageData(page_cu); page_data->SetLoadIdleState(kLoadedAndIdle, now); // Notify observers that the page is loaded and idle. - DispatchPageSignal(page_cu, &mojom::PageSignalReceiver::NotifyPageAlmostIdle); + DispatchPageSignal( + page_cu, + &resource_coordinator::mojom::PageSignalReceiver::NotifyPageAlmostIdle); } PageSignalGeneratorImpl::PageData* PageSignalGeneratorImpl::GetPageData( @@ -402,7 +415,8 @@ const PageCoordinationUnitImpl* page_cu) { DCHECK(resource_coordinator::IsPageAlmostIdleSignalEnabled()); int64_t is_loading = 0; - if (!page_cu->GetProperty(mojom::PropertyType::kIsLoading, &is_loading)) + if (!page_cu->GetProperty( + resource_coordinator::mojom::PropertyType::kIsLoading, &is_loading)) return false; return is_loading; } @@ -428,9 +442,12 @@ // of session restore this is mitigated by having a timeout while waiting for // this signal. return main_frame_cu->GetPropertyOrDefault( - mojom::PropertyType::kNetworkAlmostIdle, 0u) && + resource_coordinator::mojom::PropertyType::kNetworkAlmostIdle, + 0u) && process_cu->GetPropertyOrDefault( - mojom::PropertyType::kMainThreadTaskLoadIsLow, 0u); + resource_coordinator::mojom::PropertyType:: + kMainThreadTaskLoadIsLow, + 0u); } void PageSignalGeneratorImpl::PageData::SetLoadIdleState( @@ -446,12 +463,14 @@ const PageCoordinationUnitImpl* page_cu, Method m, Params... params) { - receivers_.ForAllPtrs([&](mojom::PageSignalReceiver* receiver) { - (receiver->*m)( - PageNavigationIdentity{page_cu->id(), page_cu->navigation_id(), - page_cu->main_frame_url()}, - std::forward<Params>(params)...); - }); + receivers_.ForAllPtrs( + [&](resource_coordinator::mojom::PageSignalReceiver* receiver) { + (receiver->*m)( + resource_coordinator::PageNavigationIdentity{ + page_cu->id(), page_cu->navigation_id(), + page_cu->main_frame_url()}, + std::forward<Params>(params)...); + }); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/observers/page_signal_generator_impl.h b/chrome/browser/performance_manager/observers/page_signal_generator_impl.h similarity index 76% rename from services/resource_coordinator/observers/page_signal_generator_impl.h rename to chrome/browser/performance_manager/observers/page_signal_generator_impl.h index cbfe1ce..4980a1c 100644 --- a/services/resource_coordinator/observers/page_signal_generator_impl.h +++ b/chrome/browser/performance_manager/observers/page_signal_generator_impl.h
@@ -2,60 +2,69 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_PAGE_SIGNAL_GENERATOR_IMPL_H_ -#define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_PAGE_SIGNAL_GENERATOR_IMPL_H_ +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_OBSERVERS_PAGE_SIGNAL_GENERATOR_IMPL_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_OBSERVERS_PAGE_SIGNAL_GENERATOR_IMPL_H_ #include <map> #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/timer/timer.h" +#include "chrome/browser/performance_manager/observers/coordination_unit_graph_observer.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "mojo/public/cpp/bindings/interface_ptr_set.h" -#include "services/resource_coordinator/observers/coordination_unit_graph_observer.h" #include "services/resource_coordinator/public/mojom/page_signal.mojom.h" namespace service_manager { struct BindSourceInfo; } // namespace service_manager -namespace resource_coordinator { +namespace performance_manager { // The PageSignalGenerator is a dedicated |CoordinationUnitGraphObserver| for // calculating and emitting page-scoped signals. This observer observes // PageCoordinationUnits, ProcessCoordinationUnits and FrameCoordinationUnits, // combining information from the graph to generate page level signals. -class PageSignalGeneratorImpl : public CoordinationUnitGraphObserver, - public mojom::PageSignalGenerator { +class PageSignalGeneratorImpl + : public CoordinationUnitGraphObserver, + public resource_coordinator::mojom::PageSignalGenerator { public: PageSignalGeneratorImpl(); ~PageSignalGeneratorImpl() override; - // mojom::PageSignalGenerator implementation. - void AddReceiver(mojom::PageSignalReceiverPtr receiver) override; + // resource_coordinator::mojom::PageSignalGenerator implementation. + void AddReceiver( + resource_coordinator::mojom::PageSignalReceiverPtr receiver) override; // CoordinationUnitGraphObserver implementation. bool ShouldObserve(const CoordinationUnitBase* coordination_unit) override; void OnCoordinationUnitCreated(const CoordinationUnitBase* cu) override; void OnBeforeCoordinationUnitDestroyed( const CoordinationUnitBase* cu) override; - void OnFramePropertyChanged(const FrameCoordinationUnitImpl* frame_cu, - const mojom::PropertyType property_type, - int64_t value) override; - void OnPagePropertyChanged(const PageCoordinationUnitImpl* page_cu, - const mojom::PropertyType property_type, - int64_t value) override; - void OnProcessPropertyChanged(const ProcessCoordinationUnitImpl* process_cu, - const mojom::PropertyType property_type, - int64_t value) override; - void OnFrameEventReceived(const FrameCoordinationUnitImpl* frame_cu, - const mojom::Event event) override; - void OnPageEventReceived(const PageCoordinationUnitImpl* page_cu, - const mojom::Event event) override; - void OnProcessEventReceived(const ProcessCoordinationUnitImpl* page_cu, - const mojom::Event event) override; - void OnSystemEventReceived(const SystemCoordinationUnitImpl* system_cu, - const mojom::Event event) override; + void OnFramePropertyChanged( + const FrameCoordinationUnitImpl* frame_cu, + const resource_coordinator::mojom::PropertyType property_type, + int64_t value) override; + void OnPagePropertyChanged( + const PageCoordinationUnitImpl* page_cu, + const resource_coordinator::mojom::PropertyType property_type, + int64_t value) override; + void OnProcessPropertyChanged( + const ProcessCoordinationUnitImpl* process_cu, + const resource_coordinator::mojom::PropertyType property_type, + int64_t value) override; + void OnFrameEventReceived( + const FrameCoordinationUnitImpl* frame_cu, + const resource_coordinator::mojom::Event event) override; + void OnPageEventReceived( + const PageCoordinationUnitImpl* page_cu, + const resource_coordinator::mojom::Event event) override; + void OnProcessEventReceived( + const ProcessCoordinationUnitImpl* page_cu, + const resource_coordinator::mojom::Event event) override; + void OnSystemEventReceived( + const SystemCoordinationUnitImpl* system_cu, + const resource_coordinator::mojom::Event event) override; void BindToInterface( resource_coordinator::mojom::PageSignalGeneratorRequest request, @@ -150,7 +159,7 @@ // This method is called when a property affecting the lifecycle state is // observed. void UpdateLifecycleState(const PageCoordinationUnitImpl* page_cu, - mojom::LifecycleState state); + resource_coordinator::mojom::LifecycleState state); // Helper function for transitioning to the final state. void TransitionToLoadedAndIdle(const PageCoordinationUnitImpl* page_cu, @@ -166,8 +175,9 @@ Method m, Params... params); - mojo::BindingSet<mojom::PageSignalGenerator> bindings_; - mojo::InterfacePtrSet<mojom::PageSignalReceiver> receivers_; + mojo::BindingSet<resource_coordinator::mojom::PageSignalGenerator> bindings_; + mojo::InterfacePtrSet<resource_coordinator::mojom::PageSignalReceiver> + receivers_; // Stores per Page CU data. This set is maintained by // OnCoordinationUnitCreated and OnBeforeCoordinationUnitDestroyed. @@ -176,6 +186,6 @@ DISALLOW_COPY_AND_ASSIGN(PageSignalGeneratorImpl); }; -} // namespace resource_coordinator +} // namespace performance_manager -#endif // SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_PAGE_SIGNAL_GENERATOR_IMPL_H_ +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_OBSERVERS_PAGE_SIGNAL_GENERATOR_IMPL_H_
diff --git a/services/resource_coordinator/observers/page_signal_generator_impl_unittest.cc b/chrome/browser/performance_manager/observers/page_signal_generator_impl_unittest.cc similarity index 84% rename from services/resource_coordinator/observers/page_signal_generator_impl_unittest.cc rename to chrome/browser/performance_manager/observers/page_signal_generator_impl_unittest.cc index 1ba999f..b15393c 100644 --- a/services/resource_coordinator/observers/page_signal_generator_impl_unittest.cc +++ b/chrome/browser/performance_manager/observers/page_signal_generator_impl_unittest.cc
@@ -2,27 +2,27 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/observers/page_signal_generator_impl.h" +#include "chrome/browser/performance_manager/observers/page_signal_generator_impl.h" #include "base/run_loop.h" #include "base/test/scoped_feature_list.h" #include "base/test/simple_test_tick_clock.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/resource_coordinator_clock.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/public/cpp/bindings/strong_binding.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_test_harness.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/mock_coordination_unit_graphs.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" #include "services/resource_coordinator/public/cpp/resource_coordinator_features.h" -#include "services/resource_coordinator/resource_coordinator_clock.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::_; -namespace resource_coordinator { +namespace performance_manager { MATCHER_P3(IdentityMatches, cu_id, navigation_id, url, "") { return arg.page_cu_id == cu_id && arg.navigation_id == navigation_id && @@ -32,10 +32,12 @@ class MockPageSignalGeneratorImpl : public PageSignalGeneratorImpl { public: // Overridden from PageSignalGeneratorImpl. - void OnProcessPropertyChanged(const ProcessCoordinationUnitImpl* process_cu, - const mojom::PropertyType property_type, - int64_t value) override { - if (property_type == mojom::PropertyType::kExpectedTaskQueueingDuration) + void OnProcessPropertyChanged( + const ProcessCoordinationUnitImpl* process_cu, + const resource_coordinator::mojom::PropertyType property_type, + int64_t value) override { + if (property_type == resource_coordinator::mojom::PropertyType:: + kExpectedTaskQueueingDuration) ++eqt_change_count_; } @@ -45,32 +47,38 @@ size_t eqt_change_count_ = 0; }; -class MockPageSignalReceiverImpl : public mojom::PageSignalReceiver { +class MockPageSignalReceiverImpl + : public resource_coordinator::mojom::PageSignalReceiver { public: - MockPageSignalReceiverImpl(mojom::PageSignalReceiverRequest request) + explicit MockPageSignalReceiverImpl( + resource_coordinator::mojom::PageSignalReceiverRequest request) : binding_(this, std::move(request)) {} ~MockPageSignalReceiverImpl() override = default; - // mojom::PageSignalReceiver implementation. - void NotifyPageAlmostIdle( - const PageNavigationIdentity& page_navigation_id) override {} + // resource_coordinator::mojom::PageSignalReceiver implementation. + void NotifyPageAlmostIdle(const resource_coordinator::PageNavigationIdentity& + page_navigation_id) override {} void SetExpectedTaskQueueingDuration( - const PageNavigationIdentity& page_navigation_id, + const resource_coordinator::PageNavigationIdentity& page_navigation_id, base::TimeDelta duration) override {} - void SetLifecycleState(const PageNavigationIdentity& page_navigation_id, - mojom::LifecycleState) override {} + void SetLifecycleState( + const resource_coordinator::PageNavigationIdentity& page_navigation_id, + resource_coordinator::mojom::LifecycleState) override {} MOCK_METHOD1(NotifyNonPersistentNotificationCreated, - void(const PageNavigationIdentity& page_navigation_id)); + void(const resource_coordinator::PageNavigationIdentity& + page_navigation_id)); MOCK_METHOD1(NotifyRendererIsBloated, - void(const PageNavigationIdentity& page_navigation_id)); + void(const resource_coordinator::PageNavigationIdentity& + page_navigation_id)); MOCK_METHOD4(OnLoadTimePerformanceEstimate, - void(const PageNavigationIdentity& page_navigation_id, + void(const resource_coordinator::PageNavigationIdentity& + page_navigation_id, base::TimeDelta load_duration, base::TimeDelta cpu_usage_estimate, uint64_t private_footprint_kb_estimate)); private: - mojo::Binding<mojom::PageSignalReceiver> binding_; + mojo::Binding<resource_coordinator::mojom::PageSignalReceiver> binding_; DISALLOW_COPY_AND_ASSIGN(MockPageSignalReceiverImpl); }; @@ -329,7 +337,7 @@ auto* frame_cu = cu_graph.frame.get(); // Create a mock receiver and register it against the psg. - mojom::PageSignalReceiverPtr mock_receiver_ptr; + resource_coordinator::mojom::PageSignalReceiverPtr mock_receiver_ptr; MockPageSignalReceiver mock_receiver(mojo::MakeRequest(&mock_receiver_ptr)); page_signal_generator()->AddReceiver(std::move(mock_receiver_ptr)); @@ -338,10 +346,12 @@ IdentityMatches(cu_graph.page->id(), 0u, ""))) .WillOnce(::testing::InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit)); - // Send a mojom::Event::kNonPersistentNotificationCreated event and wait for - // the receiver to get it. + // Send a + // resource_coordinator::mojom::Event::kNonPersistentNotificationCreated event + // and wait for the receiver to get it. page_signal_generator()->OnFrameEventReceived( - frame_cu, mojom::Event::kNonPersistentNotificationCreated); + frame_cu, + resource_coordinator::mojom::Event::kNonPersistentNotificationCreated); run_loop.Run(); ::testing::Mock::VerifyAndClear(&mock_receiver); @@ -354,7 +364,7 @@ auto* psg = page_signal_generator(); // Create a mock receiver and register it against the psg. - mojom::PageSignalReceiverPtr mock_receiver_ptr; + resource_coordinator::mojom::PageSignalReceiverPtr mock_receiver_ptr; MockPageSignalReceiver mock_receiver(mojo::MakeRequest(&mock_receiver_ptr)); psg->AddReceiver(std::move(mock_receiver_ptr)); @@ -372,7 +382,7 @@ auto* psg = page_signal_generator(); // Create a mock receiver and register it against the psg. - mojom::PageSignalReceiverPtr mock_receiver_ptr; + resource_coordinator::mojom::PageSignalReceiverPtr mock_receiver_ptr; MockPageSignalReceiver mock_receiver(mojo::MakeRequest(&mock_receiver_ptr)); psg->AddReceiver(std::move(mock_receiver_ptr)); @@ -385,17 +395,17 @@ namespace { -mojom::ProcessResourceMeasurementBatchPtr CreateMeasurementBatch( - base::TimeTicks start_time, - size_t cpu_time_us, - size_t private_fp_kb) { - mojom::ProcessResourceMeasurementBatchPtr batch = - mojom::ProcessResourceMeasurementBatch::New(); +resource_coordinator::mojom::ProcessResourceMeasurementBatchPtr +CreateMeasurementBatch(base::TimeTicks start_time, + size_t cpu_time_us, + size_t private_fp_kb) { + resource_coordinator::mojom::ProcessResourceMeasurementBatchPtr batch = + resource_coordinator::mojom::ProcessResourceMeasurementBatch::New(); batch->batch_started_time = start_time; batch->batch_ended_time = start_time + base::TimeDelta::FromMicroseconds(10); - mojom::ProcessResourceMeasurementPtr measurement = - mojom::ProcessResourceMeasurement::New(); + resource_coordinator::mojom::ProcessResourceMeasurementPtr measurement = + resource_coordinator::mojom::ProcessResourceMeasurement::New(); measurement->pid = 1; measurement->cpu_usage = base::TimeDelta::FromMicroseconds(cpu_time_us); measurement->private_footprint_kb = static_cast<uint32_t>(private_fp_kb); @@ -413,7 +423,7 @@ coordination_unit_graph()); // Create a mock receiver and register it against the psg. - mojom::PageSignalReceiverPtr mock_receiver_ptr; + resource_coordinator::mojom::PageSignalReceiverPtr mock_receiver_ptr; MockPageSignalReceiver mock_receiver(mojo::MakeRequest(&mock_receiver_ptr)); page_signal_generator()->AddReceiver(std::move(mock_receiver_ptr)); @@ -496,4 +506,4 @@ ::testing::Mock::VerifyAndClear(&mock_receiver); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/observers/working_set_trimmer_win.cc b/chrome/browser/performance_manager/observers/working_set_trimmer_win.cc similarity index 81% rename from services/resource_coordinator/observers/working_set_trimmer_win.cc rename to chrome/browser/performance_manager/observers/working_set_trimmer_win.cc index 3ec3494..b5e5f0df 100644 --- a/services/resource_coordinator/observers/working_set_trimmer_win.cc +++ b/chrome/browser/performance_manager/observers/working_set_trimmer_win.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 "services/resource_coordinator/observers/working_set_trimmer_win.h" +#include "chrome/browser/performance_manager/observers/working_set_trimmer_win.h" #include <windows.h> // Must be in front of other Windows header files. @@ -11,10 +11,10 @@ #include "base/logging.h" #include "base/process/process.h" #include "base/time/time.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_base.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_base.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" -namespace resource_coordinator { +namespace performance_manager { namespace { @@ -53,7 +53,8 @@ bool WorkingSetTrimmer::ShouldObserve( const CoordinationUnitBase* coordination_unit) { - return coordination_unit->id().type == CoordinationUnitType::kProcess; + return coordination_unit->id().type == + resource_coordinator::CoordinationUnitType::kProcess; } void WorkingSetTrimmer::OnAllFramesInProcessFrozen( @@ -64,4 +65,4 @@ } } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/observers/working_set_trimmer_win.h b/chrome/browser/performance_manager/observers/working_set_trimmer_win.h similarity index 78% rename from services/resource_coordinator/observers/working_set_trimmer_win.h rename to chrome/browser/performance_manager/observers/working_set_trimmer_win.h index 64f45ce..f1db57b 100644 --- a/services/resource_coordinator/observers/working_set_trimmer_win.h +++ b/chrome/browser/performance_manager/observers/working_set_trimmer_win.h
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_RESOURCE_COORDINATOR_OBSERVERS_WORKING_SET_TRIMMER_WIN_H_ -#define SERVICES_RESOURCE_COORDINATOR_OBSERVERS_WORKING_SET_TRIMMER_WIN_H_ +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_OBSERVERS_WORKING_SET_TRIMMER_WIN_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_OBSERVERS_WORKING_SET_TRIMMER_WIN_H_ #include "base/macros.h" -#include "services/resource_coordinator/observers/coordination_unit_graph_observer.h" +#include "chrome/browser/performance_manager/observers/coordination_unit_graph_observer.h" -namespace resource_coordinator { +namespace performance_manager { // Empties the working set of processes in which all frames are frozen. // @@ -40,6 +40,6 @@ DISALLOW_COPY_AND_ASSIGN(WorkingSetTrimmer); }; -} // namespace resource_coordinator +} // namespace performance_manager -#endif // SERVICES_RESOURCE_COORDINATOR_OBSERVERS_WORKING_SET_TRIMMER_WIN_H_ +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_OBSERVERS_WORKING_SET_TRIMMER_WIN_H_
diff --git a/services/resource_coordinator/observers/working_set_trimmer_win_unittest.cc b/chrome/browser/performance_manager/observers/working_set_trimmer_win_unittest.cc similarity index 87% rename from services/resource_coordinator/observers/working_set_trimmer_win_unittest.cc rename to chrome/browser/performance_manager/observers/working_set_trimmer_win_unittest.cc index 52ae4efa..eb6d976 100644 --- a/services/resource_coordinator/observers/working_set_trimmer_win_unittest.cc +++ b/chrome/browser/performance_manager/observers/working_set_trimmer_win_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/observers/working_set_trimmer_win.h" +#include "chrome/browser/performance_manager/observers/working_set_trimmer_win.h" #include <windows.h> // Must be in front of other Windows header files. @@ -17,12 +17,12 @@ #include "base/strings/string_number_conversions.h" #include "base/synchronization/waitable_event.h" #include "base/test/multiprocess_test.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_test_harness.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/multiprocess_func_list.h" -namespace resource_coordinator { +namespace performance_manager { namespace { @@ -40,7 +40,7 @@ return event; } -SIZE_T GetWorkingSetSizeMb(base::ProcessHandle handle) { +size_t GetWorkingSetSizeMb(base::ProcessHandle handle) { PROCESS_MEMORY_COUNTERS_EX pmc; if (::GetProcessMemoryInfo(handle, reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmc), @@ -120,8 +120,11 @@ // When all frames in the Process CU are frozen, the working set of // |child_process_| should be emptied. + size_t working_set_before = GetWorkingSetSizeMb(child_process_.Handle()); working_set_trimmer_.OnAllFramesInProcessFrozen(process_cu_.get()); - EXPECT_EQ(GetWorkingSetSizeMb(child_process_.Handle()), 0U); + // Make sure the working set has shrunk by at least the 10mb allocation. + EXPECT_GE(working_set_before - 10U, + GetWorkingSetSizeMb(child_process_.Handle())); } TEST_F(WorkingSetTrimmerTest, EmptyWorkingSetInconsistentLaunchTime) { @@ -135,4 +138,4 @@ EXPECT_GE(GetWorkingSetSizeMb(child_process_.Handle()), 10U); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/public/cpp/page_resource_coordinator.cc b/chrome/browser/performance_manager/page_resource_coordinator.cc similarity index 74% rename from services/resource_coordinator/public/cpp/page_resource_coordinator.cc rename to chrome/browser/performance_manager/page_resource_coordinator.cc index c487fd9..ed014e39 100644 --- a/services/resource_coordinator/public/cpp/page_resource_coordinator.cc +++ b/chrome/browser/performance_manager/page_resource_coordinator.cc
@@ -2,17 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/public/cpp/page_resource_coordinator.h" +#include "chrome/browser/performance_manager/page_resource_coordinator.h" #include "base/bind.h" -namespace resource_coordinator { +namespace performance_manager { PageResourceCoordinator::PageResourceCoordinator( - service_manager::Connector* connector) + PerformanceManager* performance_manager) : ResourceCoordinatorInterface(), weak_ptr_factory_(this) { - CoordinationUnitID new_cu_id(CoordinationUnitType::kPage, - CoordinationUnitID::RANDOM_ID); - ResourceCoordinatorInterface::ConnectToService(connector, new_cu_id); + resource_coordinator::CoordinationUnitID new_cu_id( + resource_coordinator::CoordinationUnitType::kPage, + resource_coordinator::CoordinationUnitID::RANDOM_ID); + ResourceCoordinatorInterface::ConnectToService(performance_manager, + new_cu_id); } PageResourceCoordinator::~PageResourceCoordinator() = default; @@ -78,19 +80,21 @@ } void PageResourceCoordinator::ConnectToService( - mojom::CoordinationUnitProviderPtr& provider, - const CoordinationUnitID& cu_id) { + resource_coordinator::mojom::CoordinationUnitProviderPtr& provider, + const resource_coordinator::CoordinationUnitID& cu_id) { provider->CreatePageCoordinationUnit(mojo::MakeRequest(&service_), cu_id); } -void PageResourceCoordinator::AddFrameByID(const CoordinationUnitID& cu_id) { +void PageResourceCoordinator::AddFrameByID( + const resource_coordinator::CoordinationUnitID& cu_id) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); service_->AddFrame(cu_id); } -void PageResourceCoordinator::RemoveFrameByID(const CoordinationUnitID& cu_id) { +void PageResourceCoordinator::RemoveFrameByID( + const resource_coordinator::CoordinationUnitID& cu_id) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); service_->RemoveFrame(cu_id); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/chrome/browser/performance_manager/page_resource_coordinator.h b/chrome/browser/performance_manager/page_resource_coordinator.h new file mode 100644 index 0000000..fd82255 --- /dev/null +++ b/chrome/browser/performance_manager/page_resource_coordinator.h
@@ -0,0 +1,56 @@ +// Copyright 2017 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_PERFORMANCE_MANAGER_PAGE_RESOURCE_COORDINATOR_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_PAGE_RESOURCE_COORDINATOR_H_ + +#include "base/memory/weak_ptr.h" +#include "base/threading/thread_checker.h" +#include "base/time/time.h" +#include "chrome/browser/performance_manager/frame_resource_coordinator.h" +#include "chrome/browser/performance_manager/resource_coordinator_interface.h" +#include "services/resource_coordinator/public/mojom/coordination_unit.mojom.h" + +namespace performance_manager { + +class PageResourceCoordinator + : public ResourceCoordinatorInterface< + resource_coordinator::mojom::PageCoordinationUnitPtr, + resource_coordinator::mojom::PageCoordinationUnitRequest> { + public: + explicit PageResourceCoordinator(PerformanceManager* performance_manager); + ~PageResourceCoordinator() override; + + void SetIsLoading(bool is_loading); + void SetVisibility(bool visible); + void SetUKMSourceId(int64_t ukm_source_id); + void OnFaviconUpdated(); + void OnTitleUpdated(); + void OnMainFrameNavigationCommitted(base::TimeTicks navigation_committed_time, + uint64_t navigation_id, + const std::string& url); + + void AddFrame(const FrameResourceCoordinator& frame); + void RemoveFrame(const FrameResourceCoordinator& frame); + + private: + void ConnectToService( + resource_coordinator::mojom::CoordinationUnitProviderPtr& provider, + const resource_coordinator::CoordinationUnitID& cu_id) override; + + void AddFrameByID(const resource_coordinator::CoordinationUnitID& cu_id); + void RemoveFrameByID(const resource_coordinator::CoordinationUnitID& cu_id); + + THREAD_CHECKER(thread_checker_); + + // The WeakPtrFactory should come last so the weak ptrs are invalidated + // before the rest of the member variables. + base::WeakPtrFactory<PageResourceCoordinator> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(PageResourceCoordinator); +}; + +} // namespace performance_manager + +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_PAGE_RESOURCE_COORDINATOR_H_
diff --git a/chrome/browser/performance_manager/performance_manager.cc b/chrome/browser/performance_manager/performance_manager.cc new file mode 100644 index 0000000..d657931 --- /dev/null +++ b/chrome/browser/performance_manager/performance_manager.cc
@@ -0,0 +1,159 @@ +// 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. + +#include "chrome/browser/performance_manager/performance_manager.h" + +#include <memory> +#include <utility> + +#include "base/feature_list.h" +#include "base/macros.h" +#include "base/memory/ptr_util.h" +#include "base/task/post_task.h" +#include "base/task/task_traits.h" +#include "build/build_config.h" +#include "chrome/browser/performance_manager/observers/metrics_collector.h" +#include "chrome/browser/performance_manager/observers/page_signal_generator_impl.h" +#include "chrome/browser/performance_manager/observers/working_set_trimmer_win.h" +#include "content/public/common/service_manager_connection.h" +#include "services/resource_coordinator/public/cpp/resource_coordinator_features.h" + +namespace performance_manager { + +namespace { +PerformanceManager* g_performance_manager = nullptr; + +scoped_refptr<base::SequencedTaskRunner> CreateTaskRunner() { + return base::CreateSequencedTaskRunnerWithTraits( + {base::TaskPriority::USER_VISIBLE, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, base::MayBlock()}); +} + +} // namespace + +PerformanceManager* PerformanceManager::GetInstance() { + return g_performance_manager; +} + +PerformanceManager::PerformanceManager() + : service_keepalive_(static_cast<service_manager::ServiceBinding*>(nullptr), + base::nullopt), + task_runner_(CreateTaskRunner()), + introspector_(&graph_) { + DETACH_FROM_SEQUENCE(sequence_checker_); +} + +PerformanceManager::~PerformanceManager() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); +} + +// static +std::unique_ptr<PerformanceManager> PerformanceManager::Create() { + DCHECK_EQ(nullptr, g_performance_manager); + std::unique_ptr<PerformanceManager> instance = + base::WrapUnique(new PerformanceManager()); + + instance->OnStart(); + g_performance_manager = instance.get(); + + return instance; +} + +// static +void PerformanceManager::Destroy(std::unique_ptr<PerformanceManager> instance) { + DCHECK_EQ(instance.get(), g_performance_manager); + g_performance_manager = nullptr; + + instance->task_runner_->DeleteSoon(FROM_HERE, instance.release()); +} + +void PerformanceManager::BindInterface( + const std::string& interface_name, + mojo::ScopedMessagePipeHandle message_pipe) { + task_runner_->PostTask(FROM_HERE, + base::BindOnce(&PerformanceManager::BindInterfaceImpl, + base::Unretained(this), interface_name, + std::move(message_pipe))); +} + +void PerformanceManager::OnStart() { + // Some tests don't initialize the service manager connection, so this class + // tolerates its absence for tests. + auto* connection = content::ServiceManagerConnection::GetForProcess(); + task_runner_->PostTask( + FROM_HERE, + base::BindOnce( + &PerformanceManager::OnStartImpl, base::Unretained(this), + connection ? connection->GetConnector()->Clone() : nullptr)); +} + +void PerformanceManager::OnStartImpl( + std::unique_ptr<service_manager::Connector> connector) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + interface_registry_.AddInterface( + base::BindRepeating(&CoordinationUnitIntrospectorImpl::BindToInterface, + base::Unretained(&introspector_))); + + // Register new |CoordinationUnitGraphObserver| implementations here. + auto page_signal_generator_impl = std::make_unique<PageSignalGeneratorImpl>(); + interface_registry_.AddInterface( + base::BindRepeating(&PageSignalGeneratorImpl::BindToInterface, + base::Unretained(page_signal_generator_impl.get()))); + graph_.RegisterObserver(std::move(page_signal_generator_impl)); + + graph_.RegisterObserver(std::make_unique<MetricsCollector>()); + +#if defined(OS_WIN) + if (base::FeatureList::IsEnabled(features::kEmptyWorkingSet)) + graph_.RegisterObserver(std::make_unique<WorkingSetTrimmer>()); +#endif + + interface_registry_.AddInterface(base::BindRepeating( + &PerformanceManager::BindWebUIGraphDump, base::Unretained(this))); + + if (connector) { + ukm_recorder_ = ukm::MojoUkmRecorder::Create(connector.get()); + graph_.set_ukm_recorder(ukm_recorder_.get()); + } + + graph_.OnStart(&interface_registry_, &service_keepalive_); +} + +void PerformanceManager::BindInterfaceImpl( + const std::string& interface_name, + mojo::ScopedMessagePipeHandle message_pipe) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + interface_registry_.BindInterface(interface_name, std::move(message_pipe), + service_manager::BindSourceInfo()); +} + +void PerformanceManager::BindWebUIGraphDump( + resource_coordinator::mojom::WebUIGraphDumpRequest request, + const service_manager::BindSourceInfo& source_info) { + std::unique_ptr<WebUIGraphDumpImpl> graph_dump = + std::make_unique<WebUIGraphDumpImpl>(&graph_); + + auto error_callback = + base::BindOnce(&PerformanceManager::OnGraphDumpConnectionError, + base::Unretained(this), graph_dump.get()); + graph_dump->Bind(std::move(request), std::move(error_callback)); + + graph_dumps_.push_back(std::move(graph_dump)); +} + +void PerformanceManager::OnGraphDumpConnectionError( + WebUIGraphDumpImpl* graph_dump) { + const auto it = std::find_if( + graph_dumps_.begin(), graph_dumps_.end(), + [graph_dump](const std::unique_ptr<WebUIGraphDumpImpl>& graph_dump_ptr) { + return graph_dump_ptr.get() == graph_dump; + }); + + DCHECK(it != graph_dumps_.end()); + + graph_dumps_.erase(it); +} + +} // namespace performance_manager
diff --git a/chrome/browser/performance_manager/performance_manager.h b/chrome/browser/performance_manager/performance_manager.h new file mode 100644 index 0000000..b15d7a9 --- /dev/null +++ b/chrome/browser/performance_manager/performance_manager.h
@@ -0,0 +1,104 @@ +// 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. + +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_PERFORMANCE_MANAGER_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_PERFORMANCE_MANAGER_H_ + +#include <memory> +#include <string> +#include <vector> + +#include "base/sequence_checker.h" +#include "base/sequenced_task_runner.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_introspector_impl.h" +#include "chrome/browser/performance_manager/performance_manager.h" +#include "chrome/browser/performance_manager/webui_graph_dump_impl.h" +#include "services/resource_coordinator/public/mojom/coordination_unit_provider.mojom.h" +#include "services/service_manager/public/cpp/bind_source_info.h" +#include "services/service_manager/public/cpp/binder_registry.h" +#include "services/service_manager/public/cpp/connector.h" +#include "services/service_manager/public/cpp/service_keepalive.h" + +namespace ukm { +class MojoUkmRecorder; +} // namespace ukm + +namespace performance_manager { + +// The performance manager is a rendezvous point for binding to performance +// manager interfaces. +// TODO(https://crbug.com/910288): Refactor this along with the +// {Frame|Page|Process|System}ResourceCoordinator classes. +class PerformanceManager { + public: + ~PerformanceManager(); + + // Retrieves the currently registered instance. + // The caller needs to ensure that the lifetime of the registered instance + // exceeds the use of this function and the retrieved pointer. + // This function can be called from any sequence with those caveats. + static PerformanceManager* GetInstance(); + + // Creates, initializes and registers an instance. + static std::unique_ptr<PerformanceManager> Create(); + + // Unregisters |instance| if it's currently registered and arranges for its + // deletion on its sequence. + static void Destroy(std::unique_ptr<PerformanceManager> instance); + + // Forwards the binding request to the implementation class. + template <typename Interface> + void BindInterface(mojo::InterfaceRequest<Interface> request); + + private: + using InterfaceRegistry = service_manager::BinderRegistryWithArgs< + const service_manager::BindSourceInfo&>; + + PerformanceManager(); + + void BindInterface(const std::string& interface_name, + mojo::ScopedMessagePipeHandle message_pipe); + + void OnStart(); + void OnStartImpl(std::unique_ptr<service_manager::Connector> connector); + void BindInterfaceImpl(const std::string& interface_name, + mojo::ScopedMessagePipeHandle message_pipe); + + void BindWebUIGraphDump( + resource_coordinator::mojom::WebUIGraphDumpRequest request, + const service_manager::BindSourceInfo& source_info); + void OnGraphDumpConnectionError(WebUIGraphDumpImpl* graph_dump); + + // TODO(siggi): Remove this as it's only here to maintain compatibility + // with the current interface of the CoordinationUnits. + service_manager::ServiceKeepalive service_keepalive_; + InterfaceRegistry interface_registry_; + + // The performance task runner. + const scoped_refptr<base::SequencedTaskRunner> task_runner_; + CoordinationUnitGraph graph_; + CoordinationUnitIntrospectorImpl introspector_; + + // Provided to |graph_|. + // TODO(siggi): This no longer needs to go through mojo. + std::unique_ptr<ukm::MojoUkmRecorder> ukm_recorder_; + + // Current graph dump instances. + std::vector<std::unique_ptr<WebUIGraphDumpImpl>> graph_dumps_; + + SEQUENCE_CHECKER(sequence_checker_); + + DISALLOW_COPY_AND_ASSIGN(PerformanceManager); +}; + +template <typename Interface> +void PerformanceManager::BindInterface( + mojo::InterfaceRequest<Interface> request) { + BindInterface(Interface::Name_, request.PassMessagePipe()); +} + +} // namespace performance_manager + +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_PERFORMANCE_MANAGER_H_
diff --git a/chrome/browser/performance_manager/performance_manager_unittest.cc b/chrome/browser/performance_manager/performance_manager_unittest.cc new file mode 100644 index 0000000..adca71e --- /dev/null +++ b/chrome/browser/performance_manager/performance_manager_unittest.cc
@@ -0,0 +1,128 @@ +// 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. + +#include "chrome/browser/performance_manager/performance_manager.h" + +#include <utility> + +#include "base/test/bind_test_util.h" +#include "base/test/scoped_task_environment.h" +#include "chrome/browser/performance_manager/frame_resource_coordinator.h" +#include "chrome/browser/performance_manager/page_resource_coordinator.h" +#include "chrome/browser/performance_manager/process_resource_coordinator.h" +#include "chrome/browser/performance_manager/system_resource_coordinator.h" +#include "services/resource_coordinator/public/cpp/coordination_unit_id.h" +#include "services/resource_coordinator/public/mojom/coordination_unit.mojom.h" +#include "services/resource_coordinator/public/mojom/coordination_unit_provider.mojom.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace performance_manager { + +class PerformanceManagerTest : public testing::Test { + public: + PerformanceManagerTest() {} + + ~PerformanceManagerTest() override {} + + void SetUp() override { + EXPECT_EQ(nullptr, PerformanceManager::GetInstance()); + performance_manager_ = PerformanceManager::Create(); + // Make sure creation registers the created instance. + EXPECT_EQ(performance_manager_.get(), PerformanceManager::GetInstance()); + } + + void TearDown() override { + if (performance_manager_) { + PerformanceManager::Destroy(std::move(performance_manager_)); + // Make sure destruction unregisters the instance. + EXPECT_EQ(nullptr, PerformanceManager::GetInstance()); + } + + task_environment_.RunUntilIdle(); + } + + // Given a CU, tests that it works by invoking GetID and waiting for the + // response. This test will hang (and eventually fail) if the response does + // not come back from the remote endpoint. + template <typename CoordinationUnitPtrType> + void TestCUImpl(CoordinationUnitPtrType cu) { + base::RunLoop loop; + cu->GetID(base::BindLambdaForTesting( + [&loop](const resource_coordinator::CoordinationUnitID& cu_id) { + loop.Quit(); + })); + loop.Run(); + } + + // Variant that works with mojo interface pointers. + template <typename CoordinationUnitPtrType> + void TestCU(CoordinationUnitPtrType& cu) { + TestCUImpl<CoordinationUnitPtrType&>(cu); + } + + // Variant that works with pointers to FooResourceCoordinator wrappers. + template <typename CoordinationUnitPtrType> + void TestCU(CoordinationUnitPtrType* cu) { + TestCUImpl<CoordinationUnitPtrType*>(cu); + } + + protected: + PerformanceManager* performance_manager() { + return performance_manager_.get(); + } + + private: + std::unique_ptr<PerformanceManager> performance_manager_; + base::test::ScopedTaskEnvironment task_environment_; + + DISALLOW_COPY_AND_ASSIGN(PerformanceManagerTest); +}; + +TEST_F(PerformanceManagerTest, ResourceCoordinatorInstantiate) { + // Get the CU provider interface. + resource_coordinator::mojom::CoordinationUnitProviderPtr provider; + performance_manager()->BindInterface(mojo::MakeRequest(&provider)); + + // Create and test a dummy FrameCU. + resource_coordinator::CoordinationUnitID frame_id( + resource_coordinator::CoordinationUnitType::kFrame, + resource_coordinator::CoordinationUnitID::RANDOM_ID); + resource_coordinator::mojom::FrameCoordinationUnitPtr frame_cu; + provider->CreateFrameCoordinationUnit(mojo::MakeRequest(&frame_cu), frame_id); + TestCU(frame_cu); + + // Create and test a dummy PageCU. + resource_coordinator::CoordinationUnitID page_id( + resource_coordinator::CoordinationUnitType::kPage, + resource_coordinator::CoordinationUnitID::RANDOM_ID); + resource_coordinator::mojom::PageCoordinationUnitPtr page_cu; + provider->CreatePageCoordinationUnit(mojo::MakeRequest(&page_cu), page_id); + TestCU(page_cu); + + // Create and test a dummy SystemCU. + resource_coordinator::mojom::SystemCoordinationUnitPtr system_cu; + provider->GetSystemCoordinationUnit(mojo::MakeRequest(&system_cu)); + TestCU(system_cu); + + // Create and test a dummy ProcessCU. + resource_coordinator::CoordinationUnitID process_id( + resource_coordinator::CoordinationUnitType::kProcess, + resource_coordinator::CoordinationUnitID::RANDOM_ID); + resource_coordinator::mojom::ProcessCoordinationUnitPtr process_cu; + provider->CreateProcessCoordinationUnit(mojo::MakeRequest(&process_cu), + process_id); + TestCU(process_cu); + + // Also test the convenience headers for creating and communicating with CUs. + FrameResourceCoordinator frame_rc(performance_manager()); + TestCU(&frame_rc); + PageResourceCoordinator page_rc(performance_manager()); + TestCU(&page_rc); + ProcessResourceCoordinator process_rc(performance_manager()); + TestCU(&process_rc); + SystemResourceCoordinator system_rc(performance_manager()); + TestCU(&system_rc); +} + +} // namespace performance_manager
diff --git a/services/resource_coordinator/public/cpp/process_resource_coordinator.cc b/chrome/browser/performance_manager/process_resource_coordinator.cc similarity index 68% rename from services/resource_coordinator/public/cpp/process_resource_coordinator.cc rename to chrome/browser/performance_manager/process_resource_coordinator.cc index b45a93c8..f213837 100644 --- a/services/resource_coordinator/public/cpp/process_resource_coordinator.cc +++ b/chrome/browser/performance_manager/process_resource_coordinator.cc
@@ -2,19 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/public/cpp/process_resource_coordinator.h" +#include "chrome/browser/performance_manager/process_resource_coordinator.h" #include "base/time/time.h" #include "build/build_config.h" -namespace resource_coordinator { +namespace performance_manager { ProcessResourceCoordinator::ProcessResourceCoordinator( - service_manager::Connector* connector) + PerformanceManager* performance_manager) : ResourceCoordinatorInterface(), weak_ptr_factory_(this) { - CoordinationUnitID new_cu_id(CoordinationUnitType::kProcess, - CoordinationUnitID::RANDOM_ID); - ResourceCoordinatorInterface::ConnectToService(connector, new_cu_id); + resource_coordinator::CoordinationUnitID new_cu_id( + resource_coordinator::CoordinationUnitType::kProcess, + resource_coordinator::CoordinationUnitID::RANDOM_ID); + ResourceCoordinatorInterface::ConnectToService(performance_manager, + new_cu_id); } ProcessResourceCoordinator::~ProcessResourceCoordinator() = default; @@ -35,7 +37,7 @@ #else process.CreationTime() #endif - ); + ); } void ProcessResourceCoordinator::SetCPUUsage(double cpu_usage) { @@ -53,9 +55,9 @@ } void ProcessResourceCoordinator::ConnectToService( - mojom::CoordinationUnitProviderPtr& provider, - const CoordinationUnitID& cu_id) { + resource_coordinator::mojom::CoordinationUnitProviderPtr& provider, + const resource_coordinator::CoordinationUnitID& cu_id) { provider->CreateProcessCoordinationUnit(mojo::MakeRequest(&service_), cu_id); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/chrome/browser/performance_manager/process_resource_coordinator.h b/chrome/browser/performance_manager/process_resource_coordinator.h new file mode 100644 index 0000000..fe5475c --- /dev/null +++ b/chrome/browser/performance_manager/process_resource_coordinator.h
@@ -0,0 +1,47 @@ +// Copyright 2017 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_PERFORMANCE_MANAGER_PROCESS_RESOURCE_COORDINATOR_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_PROCESS_RESOURCE_COORDINATOR_H_ + +#include "base/memory/weak_ptr.h" +#include "base/process/process.h" +#include "base/threading/thread_checker.h" +#include "chrome/browser/performance_manager/frame_resource_coordinator.h" +#include "chrome/browser/performance_manager/resource_coordinator_interface.h" +#include "services/resource_coordinator/public/mojom/coordination_unit.mojom.h" + +namespace performance_manager { + +class ProcessResourceCoordinator + : public ResourceCoordinatorInterface< + resource_coordinator::mojom::ProcessCoordinationUnitPtr, + resource_coordinator::mojom::ProcessCoordinationUnitRequest> { + public: + explicit ProcessResourceCoordinator(PerformanceManager* performance_manager); + ~ProcessResourceCoordinator() override; + + // Must be called immediately after the process is launched. + void OnProcessLaunched(const base::Process& process); + + void SetCPUUsage(double usage); + void SetProcessExitStatus(int32_t exit_status); + + private: + void ConnectToService( + resource_coordinator::mojom::CoordinationUnitProviderPtr& provider, + const resource_coordinator::CoordinationUnitID& cu_id) override; + + THREAD_CHECKER(thread_checker_); + + // The WeakPtrFactory should come last so the weak ptrs are invalidated + // before the rest of the member variables. + base::WeakPtrFactory<ProcessResourceCoordinator> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(ProcessResourceCoordinator); +}; + +} // namespace performance_manager + +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_PROCESS_RESOURCE_COORDINATOR_H_
diff --git a/services/resource_coordinator/resource_coordinator_clock.cc b/chrome/browser/performance_manager/resource_coordinator_clock.cc similarity index 86% rename from services/resource_coordinator/resource_coordinator_clock.cc rename to chrome/browser/performance_manager/resource_coordinator_clock.cc index 7856f26f..a68a0d51 100644 --- a/services/resource_coordinator/resource_coordinator_clock.cc +++ b/chrome/browser/performance_manager/resource_coordinator_clock.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 "services/resource_coordinator/resource_coordinator_clock.h" +#include "chrome/browser/performance_manager/resource_coordinator_clock.h" #include "base/time/tick_clock.h" -namespace resource_coordinator { +namespace performance_manager { namespace { @@ -36,4 +36,4 @@ g_tick_clock_for_testing() = tick_clock; } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/services/resource_coordinator/resource_coordinator_clock.h b/chrome/browser/performance_manager/resource_coordinator_clock.h similarity index 75% rename from services/resource_coordinator/resource_coordinator_clock.h rename to chrome/browser/performance_manager/resource_coordinator_clock.h index 622dae72..df1c22c 100644 --- a/services/resource_coordinator/resource_coordinator_clock.h +++ b/chrome/browser/performance_manager/resource_coordinator_clock.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 SERVICES_RESOURCE_COORDINATOR_RESOURCE_COORDINATOR_CLOCK_H_ -#define SERVICES_RESOURCE_COORDINATOR_RESOURCE_COORDINATOR_CLOCK_H_ +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_RESOURCE_COORDINATOR_CLOCK_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_RESOURCE_COORDINATOR_CLOCK_H_ #include <memory> @@ -14,7 +14,7 @@ class TickClock; } -namespace resource_coordinator { +namespace performance_manager { // ResourceCoordinatorClock provides timing methods that resource_coordinator/ // needs at a central place, and facilitates testing across components when @@ -36,6 +36,6 @@ DISALLOW_COPY_AND_ASSIGN(ResourceCoordinatorClock); }; -} // namespace resource_coordinator +} // namespace performance_manager -#endif // SERVICES_RESOURCE_COORDINATOR_RESOURCE_COORDINATOR_CLOCK_H_ +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_RESOURCE_COORDINATOR_CLOCK_H_
diff --git a/services/resource_coordinator/public/cpp/resource_coordinator_interface.h b/chrome/browser/performance_manager/resource_coordinator_interface.h similarity index 61% rename from services/resource_coordinator/public/cpp/resource_coordinator_interface.h rename to chrome/browser/performance_manager/resource_coordinator_interface.h index c949abe..0a182bb 100644 --- a/services/resource_coordinator/public/cpp/resource_coordinator_interface.h +++ b/chrome/browser/performance_manager/resource_coordinator_interface.h
@@ -2,19 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_RESOURCE_COORDINATOR_INTERFACE_H_ -#define SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_RESOURCE_COORDINATOR_INTERFACE_H_ +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_RESOURCE_COORDINATOR_INTERFACE_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_RESOURCE_COORDINATOR_INTERFACE_H_ #include <stdint.h> #include "base/component_export.h" #include "base/macros.h" +#include "chrome/browser/performance_manager/performance_manager.h" #include "services/resource_coordinator/public/cpp/coordination_unit_id.h" #include "services/resource_coordinator/public/mojom/coordination_unit_provider.mojom.h" #include "services/resource_coordinator/public/mojom/service_constants.mojom.h" -#include "services/service_manager/public/cpp/connector.h" -namespace resource_coordinator { +namespace performance_manager { template <class CoordinationUnitMojoPtr, class CoordinationUnitMojoRequest> class ResourceCoordinatorInterface { @@ -29,7 +29,7 @@ } // Returns the ID. Note that this is meaningless for a singleton CU. - CoordinationUnitID id() const { return cu_id_; } + resource_coordinator::CoordinationUnitID id() const { return cu_id_; } // Returns the remote endpoint interface. const CoordinationUnitMojoPtr& service() const { return service_; } @@ -44,26 +44,27 @@ } protected: - virtual void ConnectToService(mojom::CoordinationUnitProviderPtr& provider, - const CoordinationUnitID& cu_id) = 0; + virtual void ConnectToService( + resource_coordinator::mojom::CoordinationUnitProviderPtr& provider, + const resource_coordinator::CoordinationUnitID& cu_id) = 0; - void ConnectToService(service_manager::Connector* connector, - const CoordinationUnitID& cu_id) { - if (!connector) + void ConnectToService(PerformanceManager* performance_manager, + const resource_coordinator::CoordinationUnitID& cu_id) { + if (!performance_manager) return; cu_id_ = cu_id; - mojom::CoordinationUnitProviderPtr provider; - connector->BindInterface(mojom::kServiceName, mojo::MakeRequest(&provider)); + resource_coordinator::mojom::CoordinationUnitProviderPtr provider; + performance_manager->BindInterface(mojo::MakeRequest(&provider)); ConnectToService(provider, cu_id); } CoordinationUnitMojoPtr service_; - CoordinationUnitID cu_id_; + resource_coordinator::CoordinationUnitID cu_id_; private: DISALLOW_COPY_AND_ASSIGN(ResourceCoordinatorInterface); }; -} // namespace resource_coordinator +} // namespace performance_manager -#endif // SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_RESOURCE_COORDINATOR_INTERFACE_H_ +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_RESOURCE_COORDINATOR_INTERFACE_H_
diff --git a/chrome/browser/performance_manager/system_resource_coordinator.cc b/chrome/browser/performance_manager/system_resource_coordinator.cc new file mode 100644 index 0000000..eb92375 --- /dev/null +++ b/chrome/browser/performance_manager/system_resource_coordinator.cc
@@ -0,0 +1,34 @@ +// 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. + +#include "chrome/browser/performance_manager/system_resource_coordinator.h" + +namespace performance_manager { + +SystemResourceCoordinator::SystemResourceCoordinator( + PerformanceManager* performance_manager) + : ResourceCoordinatorInterface() { + resource_coordinator::CoordinationUnitID new_cu_id( + resource_coordinator::CoordinationUnitType::kSystem, + resource_coordinator::CoordinationUnitID::RANDOM_ID); + ResourceCoordinatorInterface::ConnectToService(performance_manager, + new_cu_id); +} + +SystemResourceCoordinator::~SystemResourceCoordinator() = default; + +void SystemResourceCoordinator::DistributeMeasurementBatch( + resource_coordinator::mojom::ProcessResourceMeasurementBatchPtr batch) { + if (!service_) + return; + service_->DistributeMeasurementBatch(std::move(batch)); +} + +void SystemResourceCoordinator::ConnectToService( + resource_coordinator::mojom::CoordinationUnitProviderPtr& provider, + const resource_coordinator::CoordinationUnitID& cu_id) { + provider->GetSystemCoordinationUnit(mojo::MakeRequest(&service_)); +} + +} // namespace performance_manager
diff --git a/chrome/browser/performance_manager/system_resource_coordinator.h b/chrome/browser/performance_manager/system_resource_coordinator.h new file mode 100644 index 0000000..672ce8b --- /dev/null +++ b/chrome/browser/performance_manager/system_resource_coordinator.h
@@ -0,0 +1,34 @@ +// 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. + +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_SYSTEM_RESOURCE_COORDINATOR_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_SYSTEM_RESOURCE_COORDINATOR_H_ + +#include "chrome/browser/performance_manager/resource_coordinator_interface.h" +#include "services/resource_coordinator/public/mojom/coordination_unit.mojom.h" + +namespace performance_manager { + +class SystemResourceCoordinator + : public ResourceCoordinatorInterface< + resource_coordinator::mojom::SystemCoordinationUnitPtr, + resource_coordinator::mojom::SystemCoordinationUnitRequest> { + public: + explicit SystemResourceCoordinator(PerformanceManager* performance_manager); + ~SystemResourceCoordinator() override; + + void DistributeMeasurementBatch( + resource_coordinator::mojom::ProcessResourceMeasurementBatchPtr batch); + + private: + void ConnectToService( + resource_coordinator::mojom::CoordinationUnitProviderPtr& provider, + const resource_coordinator::CoordinationUnitID& cu_id) override; + + DISALLOW_COPY_AND_ASSIGN(SystemResourceCoordinator); +}; + +} // namespace performance_manager + +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_SYSTEM_RESOURCE_COORDINATOR_H_
diff --git a/services/resource_coordinator/webui_graph_dump_impl.cc b/chrome/browser/performance_manager/webui_graph_dump_impl.cc similarity index 63% rename from services/resource_coordinator/webui_graph_dump_impl.cc rename to chrome/browser/performance_manager/webui_graph_dump_impl.cc index 42ef9c9..e76118a 100644 --- a/services/resource_coordinator/webui_graph_dump_impl.cc +++ b/chrome/browser/performance_manager/webui_graph_dump_impl.cc
@@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/webui_graph_dump_impl.h" +#include "chrome/browser/performance_manager/webui_graph_dump_impl.h" #include "base/macros.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_graph.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_graph.h" +#include "chrome/browser/performance_manager/coordination_unit/frame_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/coordination_unit/process_coordination_unit_impl.h" -namespace resource_coordinator { +namespace performance_manager { WebUIGraphDumpImpl::WebUIGraphDumpImpl(CoordinationUnitGraph* graph) : graph_(graph), binding_(this) { @@ -19,20 +19,23 @@ WebUIGraphDumpImpl::~WebUIGraphDumpImpl() {} -void WebUIGraphDumpImpl::Bind(mojom::WebUIGraphDumpRequest request, - base::OnceClosure error_handler) { +void WebUIGraphDumpImpl::Bind( + resource_coordinator::mojom::WebUIGraphDumpRequest request, + base::OnceClosure error_handler) { binding_.Bind(std::move(request)); binding_.set_connection_error_handler(std::move(error_handler)); } void WebUIGraphDumpImpl::GetCurrentGraph(GetCurrentGraphCallback callback) { - mojom::WebUIGraphPtr graph = mojom::WebUIGraph::New(); + resource_coordinator::mojom::WebUIGraphPtr graph = + resource_coordinator::mojom::WebUIGraph::New(); { auto processes = graph_->GetAllProcessCoordinationUnits(); graph->processes.reserve(processes.size()); for (auto* process : processes) { - mojom::WebUIProcessInfoPtr process_info = mojom::WebUIProcessInfo::New(); + resource_coordinator::mojom::WebUIProcessInfoPtr process_info = + resource_coordinator::mojom::WebUIProcessInfo::New(); process_info->id = process->id().id; process_info->pid = process->process_id(); @@ -47,7 +50,8 @@ auto frames = graph_->GetAllFrameCoordinationUnits(); graph->frames.reserve(frames.size()); for (auto* frame : frames) { - mojom::WebUIFrameInfoPtr frame_info = mojom::WebUIFrameInfo::New(); + resource_coordinator::mojom::WebUIFrameInfoPtr frame_info = + resource_coordinator::mojom::WebUIFrameInfo::New(); frame_info->id = frame->id().id; @@ -65,7 +69,8 @@ auto pages = graph_->GetAllPageCoordinationUnits(); graph->pages.reserve(pages.size()); for (auto* page : pages) { - mojom::WebUIPageInfoPtr page_info = mojom::WebUIPageInfo::New(); + resource_coordinator::mojom::WebUIPageInfoPtr page_info = + resource_coordinator::mojom::WebUIPageInfo::New(); page_info->id = page->id().id; page_info->main_frame_url = page->main_frame_url(); @@ -79,4 +84,4 @@ std::move(callback).Run(std::move(graph)); } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/chrome/browser/performance_manager/webui_graph_dump_impl.h b/chrome/browser/performance_manager/webui_graph_dump_impl.h new file mode 100644 index 0000000..10f972f --- /dev/null +++ b/chrome/browser/performance_manager/webui_graph_dump_impl.h
@@ -0,0 +1,36 @@ +// Copyright 2017 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_PERFORMANCE_MANAGER_WEBUI_GRAPH_DUMP_IMPL_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_WEBUI_GRAPH_DUMP_IMPL_H_ + +#include "mojo/public/cpp/bindings/binding.h" +#include "services/resource_coordinator/public/mojom/webui_graph_dump.mojom.h" + +namespace performance_manager { + +class CoordinationUnitGraph; + +class WebUIGraphDumpImpl : public resource_coordinator::mojom::WebUIGraphDump { + public: + explicit WebUIGraphDumpImpl(CoordinationUnitGraph* graph); + ~WebUIGraphDumpImpl() override; + + // WebUIGraphDump implementation. + void GetCurrentGraph(GetCurrentGraphCallback callback) override; + + // Bind this instance to |request| with the |error_handler|. + void Bind(resource_coordinator::mojom::WebUIGraphDumpRequest request, + base::OnceClosure error_handler); + + private: + CoordinationUnitGraph* graph_; + mojo::Binding<resource_coordinator::mojom::WebUIGraphDump> binding_; + + DISALLOW_COPY_AND_ASSIGN(WebUIGraphDumpImpl); +}; + +} // namespace performance_manager + +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_WEBUI_GRAPH_DUMP_IMPL_H_
diff --git a/services/resource_coordinator/webui_graph_dump_impl_unittest.cc b/chrome/browser/performance_manager/webui_graph_dump_impl_unittest.cc similarity index 70% rename from services/resource_coordinator/webui_graph_dump_impl_unittest.cc rename to chrome/browser/performance_manager/webui_graph_dump_impl_unittest.cc index be205936..bdcb1e68 100644 --- a/services/resource_coordinator/webui_graph_dump_impl_unittest.cc +++ b/chrome/browser/performance_manager/webui_graph_dump_impl_unittest.cc
@@ -2,17 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/resource_coordinator/webui_graph_dump_impl.h" +#include "chrome/browser/performance_manager/webui_graph_dump_impl.h" #include "base/test/bind_test_util.h" #include "base/time/time.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_test_harness.h" -#include "services/resource_coordinator/coordination_unit/mock_coordination_unit_graphs.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" -#include "services/resource_coordinator/resource_coordinator_clock.h" +#include "chrome/browser/performance_manager/coordination_unit/coordination_unit_test_harness.h" +#include "chrome/browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.h" +#include "chrome/browser/performance_manager/coordination_unit/page_coordination_unit_impl.h" +#include "chrome/browser/performance_manager/resource_coordinator_clock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace resource_coordinator { +namespace performance_manager { class WebUIGraphDumpImplTest : public CoordinationUnitTestHarness {}; @@ -28,11 +28,12 @@ WebUIGraphDumpImpl impl(&graph); - mojom::WebUIGraphPtr returned_graph; + resource_coordinator::mojom::WebUIGraphPtr returned_graph; WebUIGraphDumpImpl::GetCurrentGraphCallback callback = - base::BindLambdaForTesting([&returned_graph](mojom::WebUIGraphPtr graph) { - returned_graph = std::move(graph); - }); + base::BindLambdaForTesting( + [&returned_graph](resource_coordinator::mojom::WebUIGraphPtr graph) { + returned_graph = std::move(graph); + }); impl.GetCurrentGraph(std::move(callback)); task_env().RunUntilIdle(); @@ -64,4 +65,4 @@ } } -} // namespace resource_coordinator +} // namespace performance_manager
diff --git a/chrome/browser/plugins/pdf_iframe_navigation_throttle.cc b/chrome/browser/plugins/pdf_iframe_navigation_throttle.cc index c22ac01..f555d21 100644 --- a/chrome/browser/plugins/pdf_iframe_navigation_throttle.cc +++ b/chrome/browser/plugins/pdf_iframe_navigation_throttle.cc
@@ -33,13 +33,13 @@ namespace { // Used to scope the posted navigation task to the lifetime of |web_contents|. -class WebContentsLifetimeHelper - : public content::WebContentsUserData<WebContentsLifetimeHelper> { +class PdfWebContentsLifetimeHelper + : public content::WebContentsUserData<PdfWebContentsLifetimeHelper> { public: - explicit WebContentsLifetimeHelper(content::WebContents* web_contents) + explicit PdfWebContentsLifetimeHelper(content::WebContents* web_contents) : web_contents_(web_contents) {} - base::WeakPtr<WebContentsLifetimeHelper> GetWeakPtr() { + base::WeakPtr<PdfWebContentsLifetimeHelper> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } @@ -48,15 +48,15 @@ } private: - friend class content::WebContentsUserData<WebContentsLifetimeHelper>; + friend class content::WebContentsUserData<PdfWebContentsLifetimeHelper>; content::WebContents* const web_contents_; - base::WeakPtrFactory<WebContentsLifetimeHelper> weak_factory_{this}; + base::WeakPtrFactory<PdfWebContentsLifetimeHelper> weak_factory_{this}; WEB_CONTENTS_USER_DATA_KEY_DECL(); }; -WEB_CONTENTS_USER_DATA_KEY_IMPL(WebContentsLifetimeHelper) +WEB_CONTENTS_USER_DATA_KEY_IMPL(PdfWebContentsLifetimeHelper) } // namespace @@ -141,12 +141,12 @@ // an antipattern. Use a helper object scoped to the WebContents lifetime to // scope the navigation task to the WebContents lifetime. content::WebContents* web_contents = navigation_handle()->GetWebContents(); - WebContentsLifetimeHelper::CreateForWebContents(web_contents); - WebContentsLifetimeHelper* helper = - WebContentsLifetimeHelper::FromWebContents(web_contents); + PdfWebContentsLifetimeHelper::CreateForWebContents(web_contents); + PdfWebContentsLifetimeHelper* helper = + PdfWebContentsLifetimeHelper::FromWebContents(web_contents); base::PostTaskWithTraits( FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&WebContentsLifetimeHelper::NavigateIFrameToPlaceholder, + base::BindOnce(&PdfWebContentsLifetimeHelper::NavigateIFrameToPlaceholder, helper->GetWeakPtr(), params)); return content::NavigationThrottle::CANCEL_AND_IGNORE;
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index 4c78b9ba..6f3bfca 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -962,6 +962,9 @@ { key::kBrowserSwitcherEnabled, browser_switcher::prefs::kEnabled, base::Value::Type::BOOLEAN }, + { key::kBrowserSwitcherKeepLastChromeTab, + browser_switcher::prefs::kKeepLastTab, + base::Value::Type::BOOLEAN }, #endif #if defined(OS_WIN) { key::kBrowserSwitcherUseIeSitelist,
diff --git a/chrome/browser/previews/previews_lite_page_browsertest.cc b/chrome/browser/previews/previews_lite_page_browsertest.cc index f180d92..87ddea2e 100644 --- a/chrome/browser/previews/previews_lite_page_browsertest.cc +++ b/chrome/browser/previews/previews_lite_page_browsertest.cc
@@ -72,6 +72,7 @@ namespace { const int kTimeoutMs = 250; +const int kRedirectLoopCount = 3; } class PreviewsLitePageServerBrowserTest : public InProcessBrowserTest { @@ -108,6 +109,9 @@ // Previews server will respond with HTTP 307 to a preview page. kRedirectPreview = 7, + + // Previews server will put Chrome into a redirect loop. + kRedirectLoop = 8, }; void SetUpCommandLine(base::CommandLine* cmd) override { @@ -150,6 +154,10 @@ https_server_->GetURL("/previews/to_https_redirect.html"); ASSERT_TRUE(https_to_https_redirect_url_.SchemeIs(url::kHttpsScheme)); + https_redirect_loop_url_ = + https_server_->GetURL("/previews/redirect_loop.html"); + ASSERT_TRUE(https_redirect_loop_url_.SchemeIs(url::kHttpsScheme)); + base_https_lite_page_url_ = https_server_->GetURL("/previews/lite_page_test.html"); ASSERT_TRUE(base_https_lite_page_url_.SchemeIs(url::kHttpsScheme)); @@ -180,6 +188,10 @@ http_server_->GetURL("/previews/to_https_redirect.html"); ASSERT_TRUE(http_to_https_redirect_url_.SchemeIs(url::kHttpScheme)); + http_redirect_loop_url_ = + http_server_->GetURL("/previews/redirect_loop.html"); + ASSERT_TRUE(http_redirect_loop_url_.SchemeIs(url::kHttpScheme)); + client_redirect_url_ = http_server_->GetURL("/previews/client_redirect.html"); ASSERT_TRUE(client_redirect_url_.SchemeIs(url::kHttpScheme)); @@ -204,8 +216,9 @@ {"previews_host", previews_server().spec()}, {"blacklisted_path_suffixes", ".mp4,.jpg"}, {"trigger_on_localhost", "true"}, + {"max_navigation_restart", base::NumberToString(kRedirectLoopCount)}, {"navigation_timeout_milliseconds", - use_timeout ? base::NumberToString(kTimeoutMs) : "0"}, + use_timeout ? base::NumberToString(kTimeoutMs) : "60000"}, {"control_group", is_control ? "true" : "false"}}; scoped_parameterized_feature_list_.InitAndEnableFeatureWithParameters( @@ -475,6 +488,10 @@ const GURL& https_to_https_redirect_url() const { return https_to_https_redirect_url_; } + const GURL& http_redirect_loop_url() const { return http_redirect_loop_url_; } + const GURL& https_redirect_loop_url() const { + return https_redirect_loop_url_; + } const GURL& client_redirect_url() const { return client_redirect_url_; } const GURL& subframe_url() const { return subframe_url_; } int subresources_requested() const { return subresources_requested_; } @@ -501,6 +518,29 @@ "\";</script></body></html>"); return std::move(response); } + + if (request.GetURL().spec().find("redirect_loop") != std::string::npos) { + std::unique_ptr<net::test_server::BasicHttpResponse> response = + std::make_unique<net::test_server::BasicHttpResponse>(); + response->set_code(net::HTTP_TEMPORARY_REDIRECT); + + if (request.GetURL().SchemeIsCryptographic()) { + response->AddCustomHeader("Location", http_redirect_loop_url().spec()); + } else { + // Provide a way out. If this request wasn't forward by the previews + // server, end the loop. + if (request.GetURL().spec().find("from_previews_server") != + std::string::npos) { + response->AddCustomHeader("Location", + https_redirect_loop_url().spec()); + } else { + response->set_code(net::HttpStatusCode::HTTP_OK); + } + } + + return std::move(response); + } + return nullptr; } @@ -556,6 +596,13 @@ return response; } + if (request.GetURL().spec().find("redirect_loop") != std::string::npos) { + response->set_code(net::HTTP_TEMPORARY_REDIRECT); + response->AddCustomHeader("Location", http_redirect_loop_url().spec() + + "?from_previews_server=true"); + return std::move(response); + } + std::string delay_query_param; int delay_ms = 0; @@ -600,6 +647,10 @@ response->AddCustomHeader("Location", HttpsLitePageURL(kSuccess).spec()); break; + case kRedirectLoop: + response->set_code(net::HTTP_TEMPORARY_REDIRECT); + response->AddCustomHeader("Location", https_redirect_loop_url().spec()); + break; case kBypass: response->set_code(net::HTTP_TEMPORARY_REDIRECT); // This will not cause a redirect loop because on following this @@ -655,6 +706,8 @@ GURL http_url_; GURL base_http_lite_page_url_; GURL http_to_https_redirect_url_; + GURL http_redirect_loop_url_; + GURL https_redirect_loop_url_; GURL https_to_https_redirect_url_; GURL client_redirect_url_; GURL subframe_url_; @@ -852,6 +905,30 @@ CookieSettingsFactory::GetForProfile(browser()->profile()) ->SetDefaultCookieSetting(CONTENT_SETTING_ALLOW); } + + { + // Verify a preview is not shown for a redirect loop. + base::HistogramTester histogram_tester; + ui_test_utils::NavigateToURL(browser(), HttpsLitePageURL(kRedirectLoop)); + + // Make sure we're done with all the navigation restarts before running + // checks. + for (int i = 0; i < kRedirectLoopCount + 1; i++) { + base::RunLoop().RunUntilIdle(); + content::WaitForLoadStop(GetWebContents()); + } + + VerifyPreviewNotLoaded(); + ClearDeciderState(); + + // It takes a few redirects to reach the end case. Just make sure at least + // one sample has been recorded in the correct bucket. + histogram_tester.ExpectBucketCount( + "Previews.ServerLitePage.IneligibleReasons", + static_cast<int>(PreviewsLitePageNavigationThrottle::IneligibleReason:: + kExceededMaxNavigationRestarts), + 1); + } } IN_PROC_BROWSER_TEST_F(PreviewsLitePageServerBrowserTest,
diff --git a/chrome/browser/previews/previews_lite_page_navigation_throttle.cc b/chrome/browser/previews/previews_lite_page_navigation_throttle.cc index e970572e..cf606337 100644 --- a/chrome/browser/previews/previews_lite_page_navigation_throttle.cc +++ b/chrome/browser/previews/previews_lite_page_navigation_throttle.cc
@@ -109,11 +109,11 @@ } // namespace -class WebContentsLifetimeHelper +class PreviewsWebContentsLifetimeHelper : public content::WebContentsObserver, - public content::WebContentsUserData<WebContentsLifetimeHelper> { + public content::WebContentsUserData<PreviewsWebContentsLifetimeHelper> { public: - explicit WebContentsLifetimeHelper(content::WebContents* web_contents) + explicit PreviewsWebContentsLifetimeHelper(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), web_contents_(web_contents), weak_factory_(this) {} @@ -220,7 +220,7 @@ std::move(fallback_callback).Run(); } - base::WeakPtr<WebContentsLifetimeHelper> GetWeakPtr() { + base::WeakPtr<PreviewsWebContentsLifetimeHelper> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } @@ -234,12 +234,13 @@ // synchronous. restarted_navigation_url_ = url_params.url; info_ = std::move(info); + info_->restart_count++; web_contents_->OpenURL(url_params); } private: - friend class content::WebContentsUserData<WebContentsLifetimeHelper>; + friend class content::WebContentsUserData<PreviewsWebContentsLifetimeHelper>; // The url to monitor for. When it is seen, |info_| will be attached to that // navigation. GURL restarted_navigation_url_; @@ -250,11 +251,11 @@ content::WebContents* web_contents_; std::unordered_set<content::NavigationHandle*> navigations_; - base::WeakPtrFactory<WebContentsLifetimeHelper> weak_factory_; + base::WeakPtrFactory<PreviewsWebContentsLifetimeHelper> weak_factory_; WEB_CONTENTS_USER_DATA_KEY_DECL(); }; -WEB_CONTENTS_USER_DATA_KEY_IMPL(WebContentsLifetimeHelper) +WEB_CONTENTS_USER_DATA_KEY_IMPL(PreviewsWebContentsLifetimeHelper) bool HandlePreviewsLitePageURLRewrite( GURL* url, @@ -334,6 +335,15 @@ ineligible_reasons.push_back(IneligibleReason::kCookiesBlocked); } + if (data_reduction_proxy::HasURLRedirectCycle( + navigation_handle()->GetRedirectChain()) || + (GetServerLitePageInfo() && + GetServerLitePageInfo()->restart_count >= + previews::params::LitePageRedirectPreviewMaxNavigationRestarts())) { + ineligible_reasons.push_back( + IneligibleReason::kExceededMaxNavigationRestarts); + } + // Record UMA. for (IneligibleReason reason : ineligible_reasons) { UMA_HISTOGRAM_ENUMERATION("Previews.ServerLitePage.IneligibleReasons", @@ -438,9 +448,9 @@ manager->AddSingleBypass(params.url.spec()); - WebContentsLifetimeHelper::CreateForWebContents(web_contents); - WebContentsLifetimeHelper* helper = - WebContentsLifetimeHelper::FromWebContents(web_contents); + PreviewsWebContentsLifetimeHelper::CreateForWebContents(web_contents); + PreviewsWebContentsLifetimeHelper* helper = + PreviewsWebContentsLifetimeHelper::FromWebContents(web_contents); if (!use_post_task) { helper->PostNewNavigation(params, std::move(info)); @@ -449,7 +459,7 @@ base::PostTaskWithTraits( FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&WebContentsLifetimeHelper::PostNewNavigation, + base::BindOnce(&PreviewsWebContentsLifetimeHelper::PostNewNavigation, helper->GetWeakPtr(), params, std::move(info))); } @@ -489,9 +499,9 @@ } content::WebContents* web_contents = navigation_handle()->GetWebContents(); - WebContentsLifetimeHelper::CreateForWebContents(web_contents); - WebContentsLifetimeHelper* helper = - WebContentsLifetimeHelper::FromWebContents(web_contents); + PreviewsWebContentsLifetimeHelper::CreateForWebContents(web_contents); + PreviewsWebContentsLifetimeHelper* helper = + PreviewsWebContentsLifetimeHelper::FromWebContents(web_contents); // Post a delayed task to the WebContents helper. This task will check after a // timeout whether the previews navigation has finished (either in success or @@ -506,7 +516,7 @@ base::PostDelayedTaskWithTraits( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( - &WebContentsLifetimeHelper::CheckForHungNavigation, + &PreviewsWebContentsLifetimeHelper::CheckForHungNavigation, helper->GetWeakPtr(), GetPreviewsURL(), base::BindOnce( &PreviewsLitePageNavigationThrottle::LoadAndBypass, @@ -523,7 +533,7 @@ // destroyed when the WebContents is and the task will not be executed. base::PostTaskWithTraits( FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&WebContentsLifetimeHelper::PostNewNavigation, + base::BindOnce(&PreviewsWebContentsLifetimeHelper::PostNewNavigation, helper->GetWeakPtr(), MakeOpenURLParams(navigation_handle(), GetPreviewsURL(), request_headers.ToString()), @@ -555,15 +565,15 @@ navigation_handle()->GetReloadType() != content::ReloadType::NONE && !GetServerLitePageInfo()) { // Don't use |LoadAndBypass| because we might not want to bypass. - WebContentsLifetimeHelper::CreateForWebContents( + PreviewsWebContentsLifetimeHelper::CreateForWebContents( navigation_handle()->GetWebContents()); - WebContentsLifetimeHelper* helper = - WebContentsLifetimeHelper::FromWebContents( + PreviewsWebContentsLifetimeHelper* helper = + PreviewsWebContentsLifetimeHelper::FromWebContents( navigation_handle()->GetWebContents()); base::PostTaskWithTraits( FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&WebContentsLifetimeHelper::PostNewNavigation, + base::BindOnce(&PreviewsWebContentsLifetimeHelper::PostNewNavigation, helper->GetWeakPtr(), MakeOpenURLParams(navigation_handle(), GURL(original_url), std::string()),
diff --git a/chrome/browser/previews/previews_lite_page_navigation_throttle.h b/chrome/browser/previews/previews_lite_page_navigation_throttle.h index f6229dc..d9285e0e 100644 --- a/chrome/browser/previews/previews_lite_page_navigation_throttle.h +++ b/chrome/browser/previews/previews_lite_page_navigation_throttle.h
@@ -50,7 +50,7 @@ // Reasons that a navigation is not eligible for this preview. This enum must // remain synchronized with the enum |PreviewsServerLitePageIneligibleReason| - // in metrics/histograms/enums.xml. + // in tools/metrics/histograms/enums.xml. enum class IneligibleReason { kNonHttpsScheme = 0, kHttpPost = 1, @@ -61,7 +61,8 @@ kLoadOriginalReload = 6, kCookiesBlocked = 7, kECTUnknown = 8, - kMaxValue = kECTUnknown, + kExceededMaxNavigationRestarts = 9, + kMaxValue = kExceededMaxNavigationRestarts, }; // The response type from the previews server. This enum must
diff --git a/chrome/browser/resource_coordinator/browser_child_process_watcher.cc b/chrome/browser/resource_coordinator/browser_child_process_watcher.cc index 00cf81d09a..0f31969a 100644 --- a/chrome/browser/resource_coordinator/browser_child_process_watcher.cc +++ b/chrome/browser/resource_coordinator/browser_child_process_watcher.cc
@@ -4,11 +4,13 @@ #include "chrome/browser/resource_coordinator/browser_child_process_watcher.h" +#include <memory> + #include "base/process/process.h" +#include "chrome/browser/performance_manager/performance_manager.h" +#include "chrome/browser/performance_manager/process_resource_coordinator.h" #include "content/public/browser/child_process_data.h" #include "content/public/common/process_type.h" -#include "content/public/common/service_manager_connection.h" -#include "services/resource_coordinator/public/cpp/process_resource_coordinator.h" namespace resource_coordinator { @@ -24,8 +26,8 @@ const content::ChildProcessData& data) { if (data.process_type == content::PROCESS_TYPE_GPU) { gpu_process_resource_coordinator_ = - std::make_unique<resource_coordinator::ProcessResourceCoordinator>( - content::ServiceManagerConnection::GetForProcess()->GetConnector()); + std::make_unique<performance_manager::ProcessResourceCoordinator>( + performance_manager::PerformanceManager::GetInstance()); gpu_process_resource_coordinator_->OnProcessLaunched(data.GetProcess()); } }
diff --git a/chrome/browser/resource_coordinator/browser_child_process_watcher.h b/chrome/browser/resource_coordinator/browser_child_process_watcher.h index c472e04c..0bb217a 100644 --- a/chrome/browser/resource_coordinator/browser_child_process_watcher.h +++ b/chrome/browser/resource_coordinator/browser_child_process_watcher.h
@@ -5,14 +5,18 @@ #ifndef CHROME_BROWSER_RESOURCE_COORDINATOR_BROWSER_CHILD_PROCESS_WATCHER_H_ #define CHROME_BROWSER_RESOURCE_COORDINATOR_BROWSER_CHILD_PROCESS_WATCHER_H_ +#include <memory> + #include "base/compiler_specific.h" #include "base/macros.h" #include "content/public/browser/browser_child_process_observer.h" #include "content/public/common/service_manager_connection.h" -namespace resource_coordinator { - +namespace performance_manager { class ProcessResourceCoordinator; +} // namespace performance_manager + +namespace resource_coordinator { class BrowserChildProcessWatcher : public content::BrowserChildProcessObserver { public: @@ -34,7 +38,7 @@ void GPUProcessStopped(); - std::unique_ptr<resource_coordinator::ProcessResourceCoordinator> + std::unique_ptr<performance_manager::ProcessResourceCoordinator> gpu_process_resource_coordinator_; DISALLOW_COPY_AND_ASSIGN(BrowserChildProcessWatcher);
diff --git a/chrome/browser/resource_coordinator/chrome_browser_main_extra_parts_resource_coordinator.cc b/chrome/browser/resource_coordinator/chrome_browser_main_extra_parts_resource_coordinator.cc index 764f537a..0572664 100644 --- a/chrome/browser/resource_coordinator/chrome_browser_main_extra_parts_resource_coordinator.cc +++ b/chrome/browser/resource_coordinator/chrome_browser_main_extra_parts_resource_coordinator.cc
@@ -4,13 +4,15 @@ #include "chrome/browser/resource_coordinator/chrome_browser_main_extra_parts_resource_coordinator.h" +#include <utility> + #include "base/process/process.h" +#include "chrome/browser/performance_manager/performance_manager.h" +#include "chrome/browser/performance_manager/process_resource_coordinator.h" #include "chrome/browser/resource_coordinator/browser_child_process_watcher.h" #include "chrome/browser/resource_coordinator/page_signal_receiver.h" #include "chrome/browser/resource_coordinator/render_process_probe.h" #include "chrome/browser/resource_coordinator/utils.h" -#include "content/public/common/service_manager_connection.h" -#include "services/resource_coordinator/public/cpp/process_resource_coordinator.h" #include "services/resource_coordinator/public/cpp/resource_coordinator_features.h" ChromeBrowserMainExtraPartsResourceCoordinator:: @@ -21,9 +23,11 @@ void ChromeBrowserMainExtraPartsResourceCoordinator:: ServiceManagerConnectionStarted( content::ServiceManagerConnection* connection) { + performance_manager_ = performance_manager::PerformanceManager::Create(); + process_resource_coordinator_ = - std::make_unique<resource_coordinator::ProcessResourceCoordinator>( - connection->GetConnector()); + std::make_unique<performance_manager::ProcessResourceCoordinator>( + performance_manager_.get()); process_resource_coordinator_->OnProcessLaunched(base::Process::Current()); @@ -37,7 +41,7 @@ resource_coordinator::PageSignalReceiver* page_signal_receiver = resource_coordinator::GetPageSignalReceiver(); - DCHECK(resource_coordinator::PageSignalReceiver::IsEnabled()); + DCHECK_NE(nullptr, performance_manager_.get()); resource_coordinator::RenderProcessProbe* render_process_probe = resource_coordinator::RenderProcessProbe::GetInstance(); @@ -46,3 +50,8 @@ page_signal_receiver, render_process_probe); } } + +void ChromeBrowserMainExtraPartsResourceCoordinator::PostMainMessageLoopRun() { + performance_manager::PerformanceManager::Destroy( + std::move(performance_manager_)); +}
diff --git a/chrome/browser/resource_coordinator/chrome_browser_main_extra_parts_resource_coordinator.h b/chrome/browser/resource_coordinator/chrome_browser_main_extra_parts_resource_coordinator.h index 2e5e8f5..8ad06f2b2 100644 --- a/chrome/browser/resource_coordinator/chrome_browser_main_extra_parts_resource_coordinator.h +++ b/chrome/browser/resource_coordinator/chrome_browser_main_extra_parts_resource_coordinator.h
@@ -11,11 +11,10 @@ #include "chrome/browser/resource_coordinator/browser_child_process_watcher.h" #include "chrome/browser/resource_coordinator/performance_measurement_manager.h" -namespace resource_coordinator { - +namespace performance_manager { +class PerformanceManager; class ProcessResourceCoordinator; - -} // namespace resource_coordinator +} // namespace performance_manager class ChromeBrowserMainExtraPartsResourceCoordinator : public ChromeBrowserMainExtraParts { @@ -28,8 +27,10 @@ void ServiceManagerConnectionStarted( content::ServiceManagerConnection* connection) override; void PreBrowserStart() override; + void PostMainMessageLoopRun() override; - std::unique_ptr<resource_coordinator::ProcessResourceCoordinator> + std::unique_ptr<performance_manager::PerformanceManager> performance_manager_; + std::unique_ptr<performance_manager::ProcessResourceCoordinator> process_resource_coordinator_; std::unique_ptr<resource_coordinator::BrowserChildProcessWatcher>
diff --git a/chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.cc b/chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.cc index 47ebc2d..c7791902 100644 --- a/chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.cc +++ b/chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.cc
@@ -4,7 +4,10 @@ #include "chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.h" +#include <utility> + #include "base/task/post_task.h" +#include "chrome/browser/performance_manager/performance_manager.h" #include "chrome/browser/resource_coordinator/local_site_characteristics_data_store_factory.h" #include "chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.h" #include "chrome/browser/resource_coordinator/tab_helper.h" @@ -94,9 +97,6 @@ ChromeTestHarnessWithLocalDB::ChromeTestHarnessWithLocalDB() { scoped_feature_list_.InitAndEnableFeature( features::kSiteCharacteristicsDatabase); - - LocalSiteCharacteristicsWebContentsObserver:: - SkipObserverRegistrationForTesting(); } ChromeTestHarnessWithLocalDB::~ChromeTestHarnessWithLocalDB() = default; @@ -106,7 +106,11 @@ // ChromeRenderViewHostTestHarness::SetUp(), this will prevent the creation // of a non-mock version of a data store when browser_context() gets // initialized. + performance_manager_ = performance_manager::PerformanceManager::Create(); + LocalSiteCharacteristicsDataStoreFactory::EnableForTesting(); + + // TODO(siggi): Can this die now? content::ServiceManagerConnection::SetForProcess( content::ServiceManagerConnection::Create( mojo::MakeRequest(&service_), @@ -117,6 +121,9 @@ } void ChromeTestHarnessWithLocalDB::TearDown() { + performance_manager::PerformanceManager::Destroy( + std::move(performance_manager_)); + content::ServiceManagerConnection::DestroyForProcess(); ChromeRenderViewHostTestHarness::TearDown(); }
diff --git a/chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.h b/chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.h index 74cabd81..911565f 100644 --- a/chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.h +++ b/chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.h
@@ -5,6 +5,8 @@ #ifndef CHROME_BROWSER_RESOURCE_COORDINATOR_LOCAL_SITE_CHARACTERISTICS_DATA_UNITTEST_UTILS_H_ #define CHROME_BROWSER_RESOURCE_COORDINATOR_LOCAL_SITE_CHARACTERISTICS_DATA_UNITTEST_UTILS_H_ +#include <memory> + #include "base/callback_forward.h" #include "base/macros.h" #include "base/test/scoped_feature_list.h" @@ -20,7 +22,13 @@ class WebContents; } +namespace performance_manager { +class PerformanceManager; +} // namespace performance_manager + namespace resource_coordinator { + + namespace testing { // Return the LocalSiteCharacteristicsDataImpl instance backing a WebContents, @@ -94,6 +102,7 @@ private: base::test::ScopedFeatureList scoped_feature_list_; service_manager::mojom::ServicePtr service_; + std::unique_ptr<performance_manager::PerformanceManager> performance_manager_; }; } // namespace testing
diff --git a/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.cc b/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.cc index 1e49f8fc..29156d3 100644 --- a/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.cc +++ b/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.h" #include "base/metrics/histogram_macros.h" +#include "chrome/browser/performance_manager/performance_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/resource_coordinator/local_site_characteristics_data_store_factory.h" #include "chrome/browser/resource_coordinator/time.h" @@ -24,25 +25,16 @@ return TabVisibility::kBackground; } -bool g_skip_observer_registration_for_testing = false; - } // namespace -// static -void LocalSiteCharacteristicsWebContentsObserver:: - SkipObserverRegistrationForTesting() { - g_skip_observer_registration_for_testing = true; -} - LocalSiteCharacteristicsWebContentsObserver:: LocalSiteCharacteristicsWebContentsObserver( content::WebContents* web_contents) : content::WebContentsObserver(web_contents) { - if (!g_skip_observer_registration_for_testing) { + // May not be present in some tests. + if (performance_manager::PerformanceManager::GetInstance()) { // The PageSignalReceiver has to be enabled in order to properly track the // non-persistent notification events. - DCHECK(PageSignalReceiver::IsEnabled()); - TabLoadTracker::Get()->AddObserver(this); page_signal_receiver_ = GetPageSignalReceiver(); DCHECK(page_signal_receiver_); @@ -68,7 +60,7 @@ void LocalSiteCharacteristicsWebContentsObserver::WebContentsDestroyed() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!g_skip_observer_registration_for_testing) { + if (page_signal_receiver_) { TabLoadTracker::Get()->RemoveObserver(this); page_signal_receiver_->RemoveObserver(this); }
diff --git a/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.h b/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.h index 48336ada..dfb40fa 100644 --- a/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.h +++ b/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.h
@@ -28,12 +28,6 @@ public TabLoadTracker::Observer, public PageSignalObserver { public: - // Allows skipping the observer registration in the constructor for the - // unittests that don't have all the services enabled - // (e.g. PageSignalReceiver), these features should be tested in integration - // tests instead. - static void SkipObserverRegistrationForTesting(); - explicit LocalSiteCharacteristicsWebContentsObserver( content::WebContents* contents); ~LocalSiteCharacteristicsWebContentsObserver() override;
diff --git a/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer_unittest.cc b/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer_unittest.cc index a8897f6..fcc00241 100644 --- a/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer_unittest.cc +++ b/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer_unittest.cc
@@ -95,8 +95,6 @@ browser_context(), base::BindRepeating(&BuildMockDataStoreForContext)); TabLoadTracker::Get()->StartTracking(web_contents()); - LocalSiteCharacteristicsWebContentsObserver:: - SkipObserverRegistrationForTesting(); observer_ = std::make_unique<LocalSiteCharacteristicsWebContentsObserver>( web_contents()); observer()->SetPageSignalReceiverForTesting(&receiver_); @@ -190,6 +188,7 @@ observer()->DidUpdateFaviconURL({}); observer()->TitleWasSet(nullptr); + EXPECT_CALL(*mock_writer, NotifySiteLoaded()); TabLoadTracker::Get()->TransitionStateForTesting(web_contents(), LoadingState::LOADED); EXPECT_CALL(*mock_writer, @@ -361,6 +360,7 @@ TEST_F(LocalSiteCharacteristicsWebContentsObserverTest, LateNotificationUsageSignalIsIgnored) { MockDataWriter* mock_writer = NavigateAndReturnMockWriter(kTestUrl1); + EXPECT_CALL(*mock_writer, NotifySiteLoaded()); TabLoadTracker::Get()->TransitionStateForTesting(web_contents(), LoadingState::LOADED); @@ -394,6 +394,7 @@ TEST_F(LocalSiteCharacteristicsWebContentsObserverTest, OnLoadTimePerformanceMeasurement) { MockDataWriter* mock_writer = NavigateAndReturnMockWriter(kTestUrl1); + EXPECT_CALL(*mock_writer, NotifySiteLoaded()); TabLoadTracker::Get()->TransitionStateForTesting(web_contents(), LoadingState::LOADED);
diff --git a/chrome/browser/resource_coordinator/page_signal_receiver.cc b/chrome/browser/resource_coordinator/page_signal_receiver.cc index 59ebe61f..256139a 100644 --- a/chrome/browser/resource_coordinator/page_signal_receiver.cc +++ b/chrome/browser/resource_coordinator/page_signal_receiver.cc
@@ -6,20 +6,13 @@ #include "base/no_destructor.h" #include "base/time/time.h" -#include "content/public/common/service_manager_connection.h" +#include "chrome/browser/performance_manager/performance_manager.h" #include "services/resource_coordinator/public/cpp/coordination_unit_id.h" #include "services/resource_coordinator/public/cpp/resource_coordinator_features.h" #include "services/resource_coordinator/public/mojom/service_constants.mojom.h" -#include "services/service_manager/public/cpp/connector.h" namespace resource_coordinator { -// static -bool PageSignalReceiver::IsEnabled() { - // Check that service_manager is active and Resource Coordinator is enabled. - return content::ServiceManagerConnection::GetForProcess() != nullptr; -} - PageSignalReceiver::PageSignalReceiver() : binding_(this) {} PageSignalReceiver::~PageSignalReceiver() = default; @@ -73,15 +66,12 @@ // When PageSignalReceiver starts to have observer, construct the mojo // channel. if (!binding_.is_bound()) { - content::ServiceManagerConnection* service_manager_connection = - content::ServiceManagerConnection::GetForProcess(); - // Ensure service_manager is active before trying to connect to it. - if (service_manager_connection) { - service_manager::Connector* connector = - service_manager_connection->GetConnector(); + performance_manager::PerformanceManager* performance_manager = + performance_manager::PerformanceManager::GetInstance(); + if (performance_manager) { mojom::PageSignalGeneratorPtr page_signal_generator_ptr; - connector->BindInterface(mojom::kServiceName, - mojo::MakeRequest(&page_signal_generator_ptr)); + performance_manager->BindInterface( + mojo::MakeRequest(&page_signal_generator_ptr)); mojom::PageSignalReceiverPtr page_signal_receiver_ptr; binding_.Bind(mojo::MakeRequest(&page_signal_receiver_ptr)); page_signal_generator_ptr->AddReceiver(
diff --git a/chrome/browser/resource_coordinator/page_signal_receiver.h b/chrome/browser/resource_coordinator/page_signal_receiver.h index 7a446d0..10cd522 100644 --- a/chrome/browser/resource_coordinator/page_signal_receiver.h +++ b/chrome/browser/resource_coordinator/page_signal_receiver.h
@@ -69,8 +69,6 @@ PageSignalReceiver(); ~PageSignalReceiver() override; - static bool IsEnabled(); - // mojom::PageSignalReceiver implementation. void NotifyPageAlmostIdle( const PageNavigationIdentity& page_navigation_id) override;
diff --git a/chrome/browser/resource_coordinator/render_process_probe.cc b/chrome/browser/resource_coordinator/render_process_probe.cc index f6e7ac2..19e5c35c 100644 --- a/chrome/browser/resource_coordinator/render_process_probe.cc +++ b/chrome/browser/resource_coordinator/render_process_probe.cc
@@ -10,10 +10,10 @@ #include "base/metrics/histogram_macros.h" #include "base/task/post_task.h" #include "build/build_config.h" +#include "chrome/browser/performance_manager/performance_manager.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" -#include "content/public/common/service_manager_connection.h" #if defined(OS_MACOSX) #include "content/public/browser/browser_child_process_host.h" @@ -32,7 +32,7 @@ // static bool RenderProcessProbe::IsEnabled() { // Check that service_manager is active and GRC is enabled. - return content::ServiceManagerConnection::GetForProcess() != nullptr; + return performance_manager::PerformanceManager::GetInstance() != nullptr; } RenderProcessProbeImpl::RenderProcessInfo::RenderProcessInfo() = default; @@ -254,15 +254,12 @@ return info.process.Pid(); } -SystemResourceCoordinator* +performance_manager::SystemResourceCoordinator* RenderProcessProbeImpl::EnsureSystemResourceCoordinator() { if (!system_resource_coordinator_) { - content::ServiceManagerConnection* connection = - content::ServiceManagerConnection::GetForProcess(); - if (connection) - system_resource_coordinator_ = - std::make_unique<SystemResourceCoordinator>( - connection->GetConnector()); + system_resource_coordinator_ = + std::make_unique<performance_manager::SystemResourceCoordinator>( + performance_manager::PerformanceManager::GetInstance()); } return system_resource_coordinator_.get(); @@ -271,7 +268,7 @@ void RenderProcessProbeImpl::DispatchMetricsOnUIThread( mojom::ProcessResourceMeasurementBatchPtr batch) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - SystemResourceCoordinator* system_resource_coordinator = + performance_manager::SystemResourceCoordinator* system_resource_coordinator = EnsureSystemResourceCoordinator(); if (system_resource_coordinator && !batch->measurements.empty())
diff --git a/chrome/browser/resource_coordinator/render_process_probe.h b/chrome/browser/resource_coordinator/render_process_probe.h index 5e5478f6..a0f6299 100644 --- a/chrome/browser/resource_coordinator/render_process_probe.h +++ b/chrome/browser/resource_coordinator/render_process_probe.h
@@ -14,8 +14,8 @@ #include "base/process/process.h" #include "base/process/process_metrics.h" #include "base/timer/timer.h" +#include "chrome/browser/performance_manager/system_resource_coordinator.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" -#include "services/resource_coordinator/public/cpp/system_resource_coordinator.h" namespace resource_coordinator { @@ -94,7 +94,8 @@ virtual base::ProcessId GetProcessId(int host_id, const RenderProcessInfo& info); - SystemResourceCoordinator* EnsureSystemResourceCoordinator(); + performance_manager::SystemResourceCoordinator* + EnsureSystemResourceCoordinator(); // Dispatch the collected metrics. // Virtual for testing. @@ -113,7 +114,8 @@ bool is_gathering_ = false; // Used to signal the end of a CPU measurement cycle to the RC. - std::unique_ptr<SystemResourceCoordinator> system_resource_coordinator_; + std::unique_ptr<performance_manager::SystemResourceCoordinator> + system_resource_coordinator_; DISALLOW_COPY_AND_ASSIGN(RenderProcessProbeImpl); };
diff --git a/chrome/browser/resource_coordinator/render_process_user_data.cc b/chrome/browser/resource_coordinator/render_process_user_data.cc index 4c954df..9f877e99 100644 --- a/chrome/browser/resource_coordinator/render_process_user_data.cc +++ b/chrome/browser/resource_coordinator/render_process_user_data.cc
@@ -9,11 +9,11 @@ #include "base/command_line.h" #include "base/memory/ptr_util.h" +#include "chrome/browser/performance_manager/performance_manager.h" #include "content/public/browser/child_process_termination_info.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_process_host_observer.h" #include "content/public/common/content_switches.h" -#include "content/public/common/service_manager_connection.h" #include "services/service_manager/public/cpp/connector.h" namespace resource_coordinator { @@ -49,17 +49,12 @@ } }; -service_manager::Connector* MaybeGetConnectionForProcess() { - if (!content::ServiceManagerConnection::GetForProcess()) - return nullptr; - return content::ServiceManagerConnection::GetForProcess()->GetConnector(); -} - } // namespace RenderProcessUserData::RenderProcessUserData( content::RenderProcessHost* render_process_host) - : process_resource_coordinator_(MaybeGetConnectionForProcess()) { + : process_resource_coordinator_( + performance_manager::PerformanceManager::GetInstance()) { // The process itself shouldn't have been created at this point. DCHECK(!render_process_host->GetProcess().IsValid() || base::CommandLine::ForCurrentProcess()->HasSwitch(
diff --git a/chrome/browser/resource_coordinator/render_process_user_data.h b/chrome/browser/resource_coordinator/render_process_user_data.h index de14f2b..a89e96e 100644 --- a/chrome/browser/resource_coordinator/render_process_user_data.h +++ b/chrome/browser/resource_coordinator/render_process_user_data.h
@@ -7,7 +7,7 @@ #include "base/macros.h" #include "base/supports_user_data.h" -#include "services/resource_coordinator/public/cpp/process_resource_coordinator.h" +#include "chrome/browser/performance_manager/process_resource_coordinator.h" namespace content { @@ -25,7 +25,8 @@ static RenderProcessUserData* GetForRenderProcessHost( content::RenderProcessHost* host); - ProcessResourceCoordinator* process_resource_coordinator() { + performance_manager::ProcessResourceCoordinator* + process_resource_coordinator() { return &process_resource_coordinator_; } @@ -33,7 +34,7 @@ explicit RenderProcessUserData( content::RenderProcessHost* render_process_host); - ProcessResourceCoordinator process_resource_coordinator_; + performance_manager::ProcessResourceCoordinator process_resource_coordinator_; DISALLOW_COPY_AND_ASSIGN(RenderProcessUserData); };
diff --git a/chrome/browser/resource_coordinator/resource_coordinator_parts.cc b/chrome/browser/resource_coordinator/resource_coordinator_parts.cc index 785b1c42..62583b3 100644 --- a/chrome/browser/resource_coordinator/resource_coordinator_parts.cc +++ b/chrome/browser/resource_coordinator/resource_coordinator_parts.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/resource_coordinator/resource_coordinator_parts.h" +#include "chrome/browser/performance_manager/performance_manager.h" #include "chrome/browser/resource_coordinator/page_signal_receiver.h" #include "services/resource_coordinator/public/cpp/resource_coordinator_features.h" @@ -11,7 +12,7 @@ ResourceCoordinatorParts::ResourceCoordinatorParts() : page_signal_receiver_( - resource_coordinator::PageSignalReceiver::IsEnabled() + performance_manager::PerformanceManager::GetInstance() ? std::make_unique<resource_coordinator::PageSignalReceiver>() : nullptr) #if !defined(OS_ANDROID)
diff --git a/chrome/browser/resource_coordinator/session_restore_policy.cc b/chrome/browser/resource_coordinator/session_restore_policy.cc index 0c3ca59..649f2d8 100644 --- a/chrome/browser/resource_coordinator/session_restore_policy.cc +++ b/chrome/browser/resource_coordinator/session_restore_policy.cc
@@ -91,12 +91,9 @@ } // namespace SessionRestorePolicy::SessionRestorePolicy() - : policy_enabled_( - base::FeatureList::IsEnabled(features::kInfiniteSessionRestore)), + : policy_enabled_(true), delegate_(SysInfoDelegate::Get()), - parsed_params_(GetInfiniteSessionRestoreParams()), - params_(&parsed_params_), - simultaneous_tab_loads_(CalculateSimultaneousTabLoadsFromParams()), + simultaneous_tab_loads_(CalculateSimultaneousTabLoads()), weak_factory_(this) {} SessionRestorePolicy::~SessionRestorePolicy() = default; @@ -198,18 +195,17 @@ if (!policy_enabled_) return true; - if (tab_loads_started_ < params_->min_tabs_to_restore) + if (tab_loads_started_ < min_tabs_to_restore_) return true; - if (params_->max_tabs_to_restore != 0 && - tab_loads_started_ >= params_->max_tabs_to_restore) { + if (max_tabs_to_restore_ != 0 && tab_loads_started_ >= max_tabs_to_restore_) { return false; } // If there is a free memory constraint then enforce it. - if (params_->mb_free_memory_per_tab_to_restore != 0) { + if (mb_free_memory_per_tab_to_restore_ != 0) { size_t free_mem_mb = delegate_->GetFreeMemoryMiB(); - if (free_mem_mb < params_->mb_free_memory_per_tab_to_restore) + if (free_mem_mb < mb_free_memory_per_tab_to_restore_) return false; } @@ -218,15 +214,15 @@ const TabData& tab_data = it->second; // Enforce a max time since use if one is specified. - if (!params_->max_time_since_last_use_to_restore.is_zero()) { + if (!max_time_since_last_use_to_restore_.is_zero()) { base::TimeDelta time_since_active = delegate_->NowTicks() - contents->GetLastActiveTime(); - if (time_since_active > params_->max_time_since_last_use_to_restore) + if (time_since_active > max_time_since_last_use_to_restore_) return false; } // Enforce a minimum site engagement score. - if (tab_data.site_engagement < params_->min_site_engagement_to_restore) + if (tab_data.site_engagement < min_site_engagement_to_restore_) return false; return true; @@ -236,14 +232,11 @@ ++tab_loads_started_; } -SessionRestorePolicy::SessionRestorePolicy( - bool policy_enabled, - const Delegate* delegate, - const InfiniteSessionRestoreParams* params) +SessionRestorePolicy::SessionRestorePolicy(bool policy_enabled, + const Delegate* delegate) : policy_enabled_(policy_enabled), delegate_(delegate), - params_(params), - simultaneous_tab_loads_(CalculateSimultaneousTabLoadsFromParams()), + simultaneous_tab_loads_(CalculateSimultaneousTabLoads()), weak_factory_(this) {} // static @@ -273,14 +266,14 @@ return loads; } -size_t SessionRestorePolicy::CalculateSimultaneousTabLoadsFromParams() const { +size_t SessionRestorePolicy::CalculateSimultaneousTabLoads() const { // If the policy is disabled then there are no limits on the simultaneous tab // loads. if (!policy_enabled_) return std::numeric_limits<size_t>::max(); return CalculateSimultaneousTabLoads( - params_->min_simultaneous_tab_loads, params_->max_simultaneous_tab_loads, - params_->cores_per_simultaneous_tab_load, delegate_->GetNumberOfCores()); + min_simultaneous_tab_loads_, max_simultaneous_tab_loads_, + cores_per_simultaneous_tab_load_, delegate_->GetNumberOfCores()); } // static
diff --git a/chrome/browser/resource_coordinator/session_restore_policy.h b/chrome/browser/resource_coordinator/session_restore_policy.h index 71c297b..aab1037 100644 --- a/chrome/browser/resource_coordinator/session_restore_policy.h +++ b/chrome/browser/resource_coordinator/session_restore_policy.h
@@ -84,13 +84,37 @@ // Returns the status of the policy logic. bool policy_enabled() const { return policy_enabled_; } + // Direct access to parameters for testing. + uint32_t& MinSimultaneousTabLoadsForTesting() { + return min_simultaneous_tab_loads_; + } + uint32_t& MaxSimultaneousTabLoadsForTesting() { + return max_simultaneous_tab_loads_; + } + uint32_t& CoresPerSimultaneousTabLoadForTesting() { + return cores_per_simultaneous_tab_load_; + } + uint32_t& MinTabsToRestoreForTesting() { return min_tabs_to_restore_; } + uint32_t& MaxTabsToRestoreForTesting() { return max_tabs_to_restore_; } + uint32_t& MbFreeMemoryPerTabToRestoreForTesting() { + return mb_free_memory_per_tab_to_restore_; + } + base::TimeDelta& MaxTimeSinceLastUseToRestoreForTesting() { + return max_time_since_last_use_to_restore_; + } + uint32_t& MinSiteEngagementToRestoreForTesting() { + return min_site_engagement_to_restore_; + } + size_t& SimultaneousTabLoadsForTesting() { return simultaneous_tab_loads_; } + void CalculateSimultaneousTabLoadsForTesting() { + simultaneous_tab_loads_ = CalculateSimultaneousTabLoads(); + } + protected: // Protected so can be exposed for unittesting. // Full constructor for testing. - SessionRestorePolicy(bool policy_enabled, - const Delegate* delegate, - const InfiniteSessionRestoreParams* params); + SessionRestorePolicy(bool policy_enabled, const Delegate* delegate); // Helper function for computing the number of loading slots to use. All // parameters are exposed for testing. @@ -157,9 +181,9 @@ float score = 0.0f; }; - // This is safe to call from the constructor if |delegate_| and |params_| are - // already initialized. - size_t CalculateSimultaneousTabLoadsFromParams() const; + // This is safe to call from the constructor if |delegate_| is already + // initialized. + size_t CalculateSimultaneousTabLoads() const; // Initializes |used_in_bg| using the data from the |reader|. The reader must // be initialized at the time this is called. @@ -193,25 +217,50 @@ // Returns true if given tab has had a final score calculated for it. static bool HasFinalScore(const TabData* tab_data); - // Initialized from the InfiniteSessionRestore policy. + // Only used in testing to disable the policy. const bool policy_enabled_; // Delegate for interface with the system. This allows easy testing of only // the logic in this class. const Delegate* const delegate_; - // A container for storing parsed parameters. Unless parameters are injected - // externally this will be populated with parsed parameters. - const InfiniteSessionRestoreParams parsed_params_; + // The minimum number of tabs to ever load simultaneously. This can be + // exceeded by user actions or load timeouts. See TabLoader for details. + uint32_t min_simultaneous_tab_loads_ = 1; - // The parameters being used by this policy engine. By default this is simply - // a pointer to |parsed_params_|, but it can also point to externally - // injected parameters for testing. - const InfiniteSessionRestoreParams* const params_; + // The maximum number of simultaneous tab loads that should be permitted. + // Setting to zero means no maximum is applied. + uint32_t max_simultaneous_tab_loads_ = 4; + + // The number of CPU cores required before per permitted simultaneous tab + // load. Setting to zero means no CPU core limit applies. + uint32_t cores_per_simultaneous_tab_load_ = 2; + + // The minimum total number of tabs to restore (if there are even that many). + uint32_t min_tabs_to_restore_ = 4; + + // The maximum total number of tabs to restore in a session restore. Setting + // to zero means no maximum is applied. + uint32_t max_tabs_to_restore_ = 20; + + // The required amount of system free memory per tab to restore. Setting to + // zero means no memory limit will be applied. + uint32_t mb_free_memory_per_tab_to_restore_ = 150; + + // The maximum time since last use of a tab in order for it to be restored. + // Setting to zero means this logic does not apply. + base::TimeDelta max_time_since_last_use_to_restore_ = + base::TimeDelta::FromDays(30); + + // The minimum site engagement score in order for a tab to be restored. + // Setting this to zero means all tabs will be restored regardless of the + // site engagement score. + uint32_t min_site_engagement_to_restore_ = 15; // The number of simultaneous tab loads that are permitted by policy. This - // is computed via InfiniteSessionRestore feature variations. - const size_t simultaneous_tab_loads_; + // is computed based on the number of cores on the machine, except for in + // tests. + size_t simultaneous_tab_loads_; // The number of tab loads that have started. Every call to ShouldLoad // returning to true is assumed to correspond to a tab that starts loading,
diff --git a/chrome/browser/resource_coordinator/session_restore_policy_unittest.cc b/chrome/browser/resource_coordinator/session_restore_policy_unittest.cc index 0ebc2394..4ab53c1 100644 --- a/chrome/browser/resource_coordinator/session_restore_policy_unittest.cc +++ b/chrome/browser/resource_coordinator/session_restore_policy_unittest.cc
@@ -79,10 +79,19 @@ using SessionRestorePolicy::TabData; using SessionRestorePolicy::UpdateSiteEngagementScoreForTesting; - TestSessionRestorePolicy(bool policy_enabled, - const Delegate* delegate, - const InfiniteSessionRestoreParams* params) - : SessionRestorePolicy(policy_enabled, delegate, params) {} + // Expose parameters. + using SessionRestorePolicy::cores_per_simultaneous_tab_load_; + using SessionRestorePolicy::max_simultaneous_tab_loads_; + using SessionRestorePolicy::max_tabs_to_restore_; + using SessionRestorePolicy::max_time_since_last_use_to_restore_; + using SessionRestorePolicy::mb_free_memory_per_tab_to_restore_; + using SessionRestorePolicy::min_simultaneous_tab_loads_; + using SessionRestorePolicy::min_site_engagement_to_restore_; + using SessionRestorePolicy::min_tabs_to_restore_; + using SessionRestorePolicy::simultaneous_tab_loads_; + + TestSessionRestorePolicy(bool policy_enabled, const Delegate* delegate) + : SessionRestorePolicy(policy_enabled, delegate) {} ~TestSessionRestorePolicy() override {} @@ -124,17 +133,7 @@ void SetUp() override { testing::ChromeTestHarnessWithLocalDB::SetUp(); - // Set some reasonable initial parameters. Tests often override these. - params_.min_simultaneous_tab_loads = 1; - params_.max_simultaneous_tab_loads = 4; - params_.cores_per_simultaneous_tab_load = 2; - params_.min_tabs_to_restore = 2; - params_.max_tabs_to_restore = 30; - params_.mb_free_memory_per_tab_to_restore = 150; - params_.max_time_since_last_use_to_restore = base::TimeDelta::FromHours(6); - params_.min_site_engagement_to_restore = 15; - - // Ditto for delegate constants. + // Set some reasonable delegate constants. delegate_.SetNumberOfCores(4); delegate_.SetFreeMemoryMiB(1024); delegate_.SetSiteEngagementScore(30); @@ -165,8 +164,24 @@ } void CreatePolicy(bool policy_enabled) { - policy_ = std::make_unique<TestSessionRestorePolicy>(policy_enabled, - &delegate_, ¶ms_); + policy_ = + std::make_unique<TestSessionRestorePolicy>(policy_enabled, &delegate_); + + // Set some reasonable initial parameters. + policy_->min_simultaneous_tab_loads_ = 1; + policy_->max_simultaneous_tab_loads_ = 4; + policy_->cores_per_simultaneous_tab_load_ = 2; + policy_->min_tabs_to_restore_ = 2; + policy_->max_tabs_to_restore_ = 30; + policy_->mb_free_memory_per_tab_to_restore_ = 150; + policy_->max_time_since_last_use_to_restore_ = + base::TimeDelta::FromHours(6); + policy_->min_site_engagement_to_restore_ = 15; + + // Ensure the simultaneous tab loads is properly calculated wrt the above + // parameters. + policy_->CalculateSimultaneousTabLoadsForTesting(); + policy_->SetTabScoreChangedCallback(base::BindRepeating( &TabScoreChangeMock::NotifyTabScoreChanged, base::Unretained(&mock_))); policy_->AddTabForScoring(contents1_.get()); @@ -185,7 +200,6 @@ protected: base::SimpleTestTickClock clock_; TestDelegate delegate_; - InfiniteSessionRestoreParams params_; TabScoreChangeMock mock_; std::unique_ptr<TestSessionRestorePolicy> policy_; @@ -248,7 +262,7 @@ // Reset and set a maximum number of tabs to load policy. policy_->SetTabLoadsStartedForTesting(0); - params_.max_tabs_to_restore = 2; + policy_->max_tabs_to_restore_ = 2; EXPECT_TRUE(policy_->ShouldLoad(contents1_.get())); policy_->NotifyTabLoadStarted(); EXPECT_TRUE(policy_->ShouldLoad(contents2_.get())); @@ -256,13 +270,13 @@ EXPECT_FALSE(policy_->ShouldLoad(contents3_.get())); // Disable the number of tab load limits entirely. - params_.min_tabs_to_restore = 0; - params_.max_tabs_to_restore = 0; + policy_->min_tabs_to_restore_ = 0; + policy_->max_tabs_to_restore_ = 0; // Reset and impose a memory policy. policy_->SetTabLoadsStartedForTesting(0); constexpr size_t kFreeMemoryLimit = 150; - params_.mb_free_memory_per_tab_to_restore = kFreeMemoryLimit; + policy_->mb_free_memory_per_tab_to_restore_ = kFreeMemoryLimit; delegate_.SetFreeMemoryMiB(kFreeMemoryLimit); EXPECT_TRUE(policy_->ShouldLoad(contents1_.get())); policy_->NotifyTabLoadStarted(); @@ -273,24 +287,25 @@ policy_->NotifyTabLoadStarted(); // Disable memory limits to not interfere with later tests. - params_.mb_free_memory_per_tab_to_restore = 0; + policy_->mb_free_memory_per_tab_to_restore_ = 0; // Reset and impose a max time since use policy. The contents have ages of 1, // 2 and 3 hours respectively. policy_->SetTabLoadsStartedForTesting(0); - params_.max_time_since_last_use_to_restore = base::TimeDelta::FromMinutes(90); + policy_->max_time_since_last_use_to_restore_ = + base::TimeDelta::FromMinutes(90); EXPECT_TRUE(policy_->ShouldLoad(contents1_.get())); policy_->NotifyTabLoadStarted(); EXPECT_FALSE(policy_->ShouldLoad(contents2_.get())); EXPECT_FALSE(policy_->ShouldLoad(contents3_.get())); // Disable the age limits entirely. - params_.max_time_since_last_use_to_restore = base::TimeDelta(); + policy_->max_time_since_last_use_to_restore_ = base::TimeDelta(); // Reset and impose a site engagement policy. policy_->SetTabLoadsStartedForTesting(0); constexpr size_t kEngagementLimit = 15; - params_.min_site_engagement_to_restore = kEngagementLimit; + policy_->min_site_engagement_to_restore_ = kEngagementLimit; policy_->UpdateSiteEngagementScoreForTesting(contents1_.get(), kEngagementLimit + 1); EXPECT_TRUE(policy_->ShouldLoad(contents1_.get())); @@ -312,11 +327,12 @@ // Set everything aggressive so it would return false if the feature was // enabled. - params_.min_tabs_to_restore = 0; - params_.max_tabs_to_restore = 1; - params_.mb_free_memory_per_tab_to_restore = 1024; - params_.max_time_since_last_use_to_restore = base::TimeDelta::FromMinutes(1); - params_.min_site_engagement_to_restore = 100; + policy_->min_tabs_to_restore_ = 0; + policy_->max_tabs_to_restore_ = 1; + policy_->mb_free_memory_per_tab_to_restore_ = 1024; + policy_->max_time_since_last_use_to_restore_ = + base::TimeDelta::FromMinutes(1); + policy_->min_site_engagement_to_restore_ = 100; // Make the system look like its effectively out of memory as well. delegate_.SetFreeMemoryMiB(1);
diff --git a/chrome/browser/resource_coordinator/tab_helper.cc b/chrome/browser/resource_coordinator/tab_helper.cc index c81116d..e300a6d 100644 --- a/chrome/browser/resource_coordinator/tab_helper.cc +++ b/chrome/browser/resource_coordinator/tab_helper.cc
@@ -13,6 +13,8 @@ #include "base/strings/string_number_conversions.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/performance_manager/page_resource_coordinator.h" +#include "chrome/browser/performance_manager/performance_manager.h" #include "chrome/browser/resource_coordinator/page_signal_receiver.h" #include "chrome/browser/resource_coordinator/render_process_user_data.h" #include "chrome/browser/resource_coordinator/resource_coordinator_parts.h" @@ -22,10 +24,7 @@ #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" -#include "content/public/common/service_manager_connection.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" -#include "services/resource_coordinator/public/cpp/page_resource_coordinator.h" -#include "services/service_manager/public/cpp/connector.h" #if !defined(OS_ANDROID) #include "chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.h" @@ -36,15 +35,14 @@ ResourceCoordinatorTabHelper::ResourceCoordinatorTabHelper( content::WebContents* web_contents) - : content::WebContentsObserver(web_contents) { + : content::WebContentsObserver(web_contents), + performance_manager_( + performance_manager::PerformanceManager::GetInstance()) { TabLoadTracker::Get()->StartTracking(web_contents); - - if (content::ServiceManagerConnection::GetForProcess()) { - connector_ = - content::ServiceManagerConnection::GetForProcess()->GetConnector(); + if (performance_manager_) { page_resource_coordinator_ = - std::make_unique<resource_coordinator::PageResourceCoordinator>( - connector_); + std::make_unique<performance_manager::PageResourceCoordinator>( + performance_manager_); // Make sure to set the visibility property when we create // |page_resource_coordinator_|. @@ -100,11 +98,12 @@ // This must not exist in the map yet. DCHECK(!base::ContainsKey(frames_, render_frame_host)); - if (!connector_) + if (!performance_manager_) return; - std::unique_ptr<FrameResourceCoordinator> frame = - std::make_unique<FrameResourceCoordinator>(connector_); + std::unique_ptr<performance_manager::FrameResourceCoordinator> frame = + std::make_unique<performance_manager::FrameResourceCoordinator>( + performance_manager_); content::RenderFrameHost* parent = render_frame_host->GetParent(); if (parent) { DCHECK(base::ContainsKey(frames_, parent)); @@ -127,7 +126,7 @@ void ResourceCoordinatorTabHelper::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { - if (!connector_) + if (!performance_manager_) return; // TODO(siggi): Ideally this would DCHECK that the deleted render frame host
diff --git a/chrome/browser/resource_coordinator/tab_helper.h b/chrome/browser/resource_coordinator/tab_helper.h index 527d676..4188649 100644 --- a/chrome/browser/resource_coordinator/tab_helper.h +++ b/chrome/browser/resource_coordinator/tab_helper.h
@@ -13,19 +13,19 @@ #include "base/process/kill.h" #include "base/time/time.h" #include "build/build_config.h" +#include "chrome/browser/performance_manager/frame_resource_coordinator.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" #include "services/metrics/public/cpp/ukm_source_id.h" -#include "services/resource_coordinator/public/cpp/frame_resource_coordinator.h" #include "url/gurl.h" -namespace service_manager { -class Connector; -} // namespace service_manager +namespace performance_manager { +class PageResourceCoordinator; +class PerformanceManager; +} // namespace performance_manager namespace resource_coordinator { -class PageResourceCoordinator; class LocalSiteCharacteristicsWebContentsObserver; class ResourceCoordinatorTabHelper @@ -36,7 +36,7 @@ static bool ukm_recorder_initialized; - resource_coordinator::PageResourceCoordinator* page_resource_coordinator() { + performance_manager::PageResourceCoordinator* page_resource_coordinator() { return page_resource_coordinator_.get(); } @@ -84,10 +84,10 @@ friend class content::WebContentsUserData<ResourceCoordinatorTabHelper>; - // The service manager connector for this process, if any. - service_manager::Connector* connector_ = nullptr; + // The performance manager for this process, if any. + performance_manager::PerformanceManager* performance_manager_ = nullptr; - std::unique_ptr<resource_coordinator::PageResourceCoordinator> + std::unique_ptr<performance_manager::PageResourceCoordinator> page_resource_coordinator_; ukm::SourceId ukm_source_id_ = ukm::kInvalidSourceId; @@ -104,7 +104,8 @@ bool first_time_title_set_ = false; // Maps from RenderFrameHost to the associated RC node. - std::map<content::RenderFrameHost*, std::unique_ptr<FrameResourceCoordinator>> + std::map<content::RenderFrameHost*, + std::unique_ptr<performance_manager::FrameResourceCoordinator>> frames_; WEB_CONTENTS_USER_DATA_KEY_DECL();
diff --git a/chrome/browser/resource_coordinator/tab_lifecycle_unit_unittest.cc b/chrome/browser/resource_coordinator/tab_lifecycle_unit_unittest.cc index f56def02..841d3ac 100644 --- a/chrome/browser/resource_coordinator/tab_lifecycle_unit_unittest.cc +++ b/chrome/browser/resource_coordinator/tab_lifecycle_unit_unittest.cc
@@ -11,6 +11,7 @@ #include "base/macros.h" #include "base/observer_list.h" #include "base/test/simple_test_tick_clock.h" +#include "base/time/time.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h" @@ -90,6 +91,8 @@ class ScopedEnterpriseOptOut; TabLifecycleUnitTest() : scoped_set_tick_clock_for_testing_(&test_clock_) { + // Advance the clock so that it doesn't yield null time ticks. + test_clock_.Advance(base::TimeDelta::FromSeconds(1)); observers_.AddObserver(&observer_); }
diff --git a/chrome/browser/resource_coordinator/tab_manager.cc b/chrome/browser/resource_coordinator/tab_manager.cc index 602629d7..14b8d34 100644 --- a/chrome/browser/resource_coordinator/tab_manager.cc +++ b/chrome/browser/resource_coordinator/tab_manager.cc
@@ -30,6 +30,7 @@ #include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h" #include "chrome/browser/media/webrtc/media_stream_capture_indicator.h" #include "chrome/browser/memory/oom_memory_details.h" +#include "chrome/browser/performance_manager/performance_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/resource_coordinator/background_tab_navigation_throttle.h" #include "chrome/browser/resource_coordinator/tab_activity_watcher.h" @@ -185,7 +186,7 @@ #endif browser_tab_strip_tracker_.Init(); session_restore_observer_.reset(new TabManagerSessionRestoreObserver(this)); - if (PageSignalReceiver::IsEnabled()) { + if (performance_manager::PerformanceManager::GetInstance()) { resource_coordinator_signal_observer_.reset( new ResourceCoordinatorSignalObserver(page_signal_receiver)); }
diff --git a/chrome/browser/resource_coordinator/tab_manager_features.cc b/chrome/browser/resource_coordinator/tab_manager_features.cc index ccfd1c4..ef44b2a 100644 --- a/chrome/browser/resource_coordinator/tab_manager_features.cc +++ b/chrome/browser/resource_coordinator/tab_manager_features.cc
@@ -23,11 +23,6 @@ const base::Feature kCustomizedTabLoadTimeout{ "CustomizedTabLoadTimeout", base::FEATURE_DISABLED_BY_DEFAULT}; -// Enables TabLoader improvements for reducing the overhead of session restores -// involving many many tabs. -const base::Feature kInfiniteSessionRestore{"InfiniteSessionRestore", - base::FEATURE_ENABLED_BY_DEFAULT}; - // Enables proactive tab freezing and discarding. const base::Feature kProactiveTabFreezeAndDiscard{ resource_coordinator::kProactiveTabFreezeAndDiscardFeatureName, @@ -135,24 +130,6 @@ constexpr base::FeatureParam<int> SiteCharacteristicsDatabaseParams::kAudioUsageGracePeriod; -// Instantiate the feature parameters for infinite session restore. -constexpr base::FeatureParam<int> - InfiniteSessionRestoreParams::kMinSimultaneousTabLoads; -constexpr base::FeatureParam<int> - InfiniteSessionRestoreParams::kMaxSimultaneousTabLoads; -constexpr base::FeatureParam<int> - InfiniteSessionRestoreParams::kCoresPerSimultaneousTabLoad; -constexpr base::FeatureParam<int> - InfiniteSessionRestoreParams::kMinTabsToRestore; -constexpr base::FeatureParam<int> - InfiniteSessionRestoreParams::kMaxTabsToRestore; -constexpr base::FeatureParam<int> - InfiniteSessionRestoreParams::kMbFreeMemoryPerTabToRestore; -constexpr base::FeatureParam<int> - InfiniteSessionRestoreParams::kMaxTimeSinceLastUseToRestore; -constexpr base::FeatureParam<int> - InfiniteSessionRestoreParams::kMinSiteEngagementToRestore; - ProactiveTabFreezeAndDiscardParams::ProactiveTabFreezeAndDiscardParams() = default; ProactiveTabFreezeAndDiscardParams::ProactiveTabFreezeAndDiscardParams( @@ -163,10 +140,6 @@ SiteCharacteristicsDatabaseParams::SiteCharacteristicsDatabaseParams( const SiteCharacteristicsDatabaseParams& rhs) = default; -InfiniteSessionRestoreParams::InfiniteSessionRestoreParams() = default; -InfiniteSessionRestoreParams::InfiniteSessionRestoreParams( - const InfiniteSessionRestoreParams& rhs) = default; - ProactiveTabFreezeAndDiscardParams GetProactiveTabFreezeAndDiscardParams( int memory_in_gb) { // TimeDelta::Max() should be used to express infinite timeouts. A large @@ -284,29 +257,6 @@ return *params; } -InfiniteSessionRestoreParams GetInfiniteSessionRestoreParams() { - InfiniteSessionRestoreParams params = {}; - - params.min_simultaneous_tab_loads = - InfiniteSessionRestoreParams::kMinSimultaneousTabLoads.Get(); - params.max_simultaneous_tab_loads = - InfiniteSessionRestoreParams::kMaxSimultaneousTabLoads.Get(); - params.cores_per_simultaneous_tab_load = - InfiniteSessionRestoreParams::kCoresPerSimultaneousTabLoad.Get(); - params.min_tabs_to_restore = - InfiniteSessionRestoreParams::kMinTabsToRestore.Get(); - params.max_tabs_to_restore = - InfiniteSessionRestoreParams::kMaxTabsToRestore.Get(); - params.mb_free_memory_per_tab_to_restore = - InfiniteSessionRestoreParams::kMbFreeMemoryPerTabToRestore.Get(); - params.max_time_since_last_use_to_restore = base::TimeDelta::FromSeconds( - InfiniteSessionRestoreParams::kMaxTimeSinceLastUseToRestore.Get()); - params.min_site_engagement_to_restore = - InfiniteSessionRestoreParams::kMinSiteEngagementToRestore.Get(); - - return params; -} - int GetNumOldestTabsToScoreWithTabRanker() { return base::GetFieldTrialParamByFeatureAsInt( features::kTabRanker, "number_of_oldest_tabs_to_score_with_TabRanker",
diff --git a/chrome/browser/resource_coordinator/tab_manager_features.h b/chrome/browser/resource_coordinator/tab_manager_features.h index 3d9c045..dddc8547 100644 --- a/chrome/browser/resource_coordinator/tab_manager_features.h +++ b/chrome/browser/resource_coordinator/tab_manager_features.h
@@ -14,7 +14,6 @@ namespace features { extern const base::Feature kCustomizedTabLoadTimeout; -extern const base::Feature kInfiniteSessionRestore; extern const base::Feature kProactiveTabFreezeAndDiscard; extern const base::Feature kSiteCharacteristicsDatabase; extern const base::Feature kStaggeredBackgroundTabOpening; @@ -241,66 +240,6 @@ base::TimeDelta audio_usage_grace_period; }; -// Parameters used by the infinite session restore feature. -struct InfiniteSessionRestoreParams { - InfiniteSessionRestoreParams(); - InfiniteSessionRestoreParams(const InfiniteSessionRestoreParams& rhs); - - // Static definition of the different parameters that can be used by this - // feature. - - static constexpr base::FeatureParam<int> kMinSimultaneousTabLoads{ - &features::kInfiniteSessionRestore, "MinSimultaneousTabLoads", 1}; - static constexpr base::FeatureParam<int> kMaxSimultaneousTabLoads{ - &features::kInfiniteSessionRestore, "MaxSimultaneousTabLoads", 4}; - static constexpr base::FeatureParam<int> kCoresPerSimultaneousTabLoad{ - &features::kInfiniteSessionRestore, "CoresPerSimultaneousTabLoad", 2}; - static constexpr base::FeatureParam<int> kMinTabsToRestore{ - &features::kInfiniteSessionRestore, "MinTabsToRestore", 4}; - static constexpr base::FeatureParam<int> kMaxTabsToRestore{ - &features::kInfiniteSessionRestore, "MaxTabsToRestore", 20}; - // This is the 75th percentile of Memory.Renderer.PrivateMemoryFootprint. - static constexpr base::FeatureParam<int> kMbFreeMemoryPerTabToRestore{ - &features::kInfiniteSessionRestore, "MbFreeMemoryPerTabToRestore", 150}; - // This value has been determined by a Finch experiment, it reduces user pain - // without impacting the gains from this feature. - static constexpr base::FeatureParam<int> kMaxTimeSinceLastUseToRestore{ - &features::kInfiniteSessionRestore, "MaxTimeSinceLastUseToRestore", - 30 * base::Time::kHoursPerDay* base::Time::kSecondsPerHour}; - // Taken from an informal survey of Googlers on min engagement of things they - // think *must* load. Note that about 25% of session-restore tabs fall above - // this threshold (see SessionRestore.RestoredTab.SiteEngagementScore). - static constexpr base::FeatureParam<int> kMinSiteEngagementToRestore{ - &features::kInfiniteSessionRestore, "MinSiteEngagementToRestore", 15}; - - // Parameters directly retrieved from the experiment configuration. - - // The minimum number of tabs to ever load simultaneously. This can be - // exceeded by user actions or load timeouts. See TabLoader for details. - uint32_t min_simultaneous_tab_loads; - // The maximum number of simultaneous tab loads that should be permitted. - // Setting to zero means no maximum is applied. - uint32_t max_simultaneous_tab_loads; - // The number of CPU cores required before per permitted simultaneous tab - // load. Setting to zero means no CPU core limit applies. - uint32_t cores_per_simultaneous_tab_load; - // The minimum total number of tabs to restore (if there are even that many). - uint32_t min_tabs_to_restore; - // The maximum total number of tabs to restore in a session restore. Setting - // to zero means no maximum is applied. - uint32_t max_tabs_to_restore; - // The required amount of system free memory per tab to restore. Setting to - // zero means no memory limit will be applied. - uint32_t mb_free_memory_per_tab_to_restore; - // The maximum time since last use of a tab in order for it to be restored. - // Setting to zero means this logic does not apply. - base::TimeDelta max_time_since_last_use_to_restore; - // The minimum site engagement score in order for a tab to be restored. - // Setting this to zero means all tabs will be restored regardless of the - // site engagement score. - uint32_t min_site_engagement_to_restore; -}; - // Gets parameters for the proactive tab discarding feature. This does no // parameter validation, and sets the default values if the feature is not // enabled. @@ -327,9 +266,6 @@ const SiteCharacteristicsDatabaseParams& GetStaticSiteCharacteristicsDatabaseParams(); -// Gets parameters for the infinite session restore feature. -InfiniteSessionRestoreParams GetInfiniteSessionRestoreParams(); - // Gets number of oldest tab that should be scored by TabRanker. int GetNumOldestTabsToScoreWithTabRanker();
diff --git a/chrome/browser/resource_coordinator/tab_manager_features_unittest.cc b/chrome/browser/resource_coordinator/tab_manager_features_unittest.cc index 7590377..582bab8 100644 --- a/chrome/browser/resource_coordinator/tab_manager_features_unittest.cc +++ b/chrome/browser/resource_coordinator/tab_manager_features_unittest.cc
@@ -34,15 +34,6 @@ "DummyTrial", params_, features); } - // Enables the site characteristics database feature, and sets up the - // associated variations parameter values. - void EnableInfiniteSessionRestore() { - std::set<std::string> features; - features.insert(features::kInfiniteSessionRestore.name); - variations_manager_.SetVariationParamsWithFeatureAssociations( - "DummyTrial", params_, features); - } - void SetParam(base::StringPiece key, base::StringPiece value) { params_[key.as_string()] = value.as_string(); } @@ -114,30 +105,6 @@ EXPECT_EQ(audio_usage_grace_period, params.audio_usage_grace_period); } - void ExpectInfiniteSessionRestoreParams( - uint32_t min_simultaneous_tab_loads, - uint32_t max_simultaneous_tab_loads, - uint32_t cores_per_simultaneous_tab_load, - uint32_t min_tabs_to_restore, - uint32_t max_tabs_to_restore, - uint32_t mb_free_memory_per_tab_to_restore, - base::TimeDelta max_time_since_last_use_to_restore, - uint32_t min_site_engagement_to_restore) { - InfiniteSessionRestoreParams params = GetInfiniteSessionRestoreParams(); - EXPECT_EQ(min_simultaneous_tab_loads, params.min_simultaneous_tab_loads); - EXPECT_EQ(max_simultaneous_tab_loads, params.max_simultaneous_tab_loads); - EXPECT_EQ(cores_per_simultaneous_tab_load, - params.cores_per_simultaneous_tab_load); - EXPECT_EQ(min_tabs_to_restore, params.min_tabs_to_restore); - EXPECT_EQ(max_tabs_to_restore, params.max_tabs_to_restore); - EXPECT_EQ(mb_free_memory_per_tab_to_restore, - params.mb_free_memory_per_tab_to_restore); - EXPECT_EQ(max_time_since_last_use_to_restore, - params.max_time_since_last_use_to_restore); - EXPECT_EQ(min_site_engagement_to_restore, - params.min_site_engagement_to_restore); - } - void ExpectDefaultProactiveTabFreezeAndDiscardParams() { int memory_in_gb = 4; ExpectProactiveTabFreezeAndDiscardParams( @@ -194,23 +161,6 @@ .default_value)); } - void ExpectDefaultInfiniteSessionRestoreParams() { - ExpectInfiniteSessionRestoreParams( - InfiniteSessionRestoreParams::kMinSimultaneousTabLoads.default_value, - InfiniteSessionRestoreParams::kMaxSimultaneousTabLoads.default_value, - InfiniteSessionRestoreParams::kCoresPerSimultaneousTabLoad - .default_value, - InfiniteSessionRestoreParams::kMinTabsToRestore.default_value, - InfiniteSessionRestoreParams::kMaxTabsToRestore.default_value, - InfiniteSessionRestoreParams::kMbFreeMemoryPerTabToRestore - .default_value, - base::TimeDelta::FromSeconds( - InfiniteSessionRestoreParams::kMaxTimeSinceLastUseToRestore - .default_value), - InfiniteSessionRestoreParams::kMinSiteEngagementToRestore - .default_value); - } - private: std::map<std::string, std::string> params_; variations::testing::VariationParamsManager variations_manager_; @@ -375,39 +325,4 @@ base::TimeDelta::FromSeconds(43)); } -TEST_F(TabManagerFeaturesTest, - GetInfiniteSessionRestoreParamsInvalidGoesToDefault) { - SetParam(InfiniteSessionRestoreParams::kMinSimultaneousTabLoads.name, " "); - SetParam(InfiniteSessionRestoreParams::kMaxSimultaneousTabLoads.name, "a.b"); - SetParam(InfiniteSessionRestoreParams::kCoresPerSimultaneousTabLoad.name, - "-- "); - SetParam(InfiniteSessionRestoreParams::kMinTabsToRestore.name, "hey"); - SetParam(InfiniteSessionRestoreParams::kMaxTabsToRestore.name, "."); - SetParam(InfiniteSessionRestoreParams::kMbFreeMemoryPerTabToRestore.name, - "0x0"); - SetParam(InfiniteSessionRestoreParams::kMaxTimeSinceLastUseToRestore.name, - "foo"); - SetParam(InfiniteSessionRestoreParams::kMinSiteEngagementToRestore.name, - "bar"); - EnableInfiniteSessionRestore(); - ExpectDefaultInfiniteSessionRestoreParams(); -} - -TEST_F(TabManagerFeaturesTest, GetInfiniteSessionRestoreParams) { - SetParam(InfiniteSessionRestoreParams::kMinSimultaneousTabLoads.name, "10"); - SetParam(InfiniteSessionRestoreParams::kMaxSimultaneousTabLoads.name, "20"); - SetParam(InfiniteSessionRestoreParams::kCoresPerSimultaneousTabLoad.name, - "2"); - SetParam(InfiniteSessionRestoreParams::kMinTabsToRestore.name, "13"); - SetParam(InfiniteSessionRestoreParams::kMaxTabsToRestore.name, "27"); - SetParam(InfiniteSessionRestoreParams::kMbFreeMemoryPerTabToRestore.name, - "1337"); - SetParam(InfiniteSessionRestoreParams::kMaxTimeSinceLastUseToRestore.name, - "60"); - SetParam(InfiniteSessionRestoreParams::kMinSiteEngagementToRestore.name, "9"); - EnableInfiniteSessionRestore(); - ExpectInfiniteSessionRestoreParams(10, 20, 2, 13, 27, 1337, - base::TimeDelta::FromMinutes(1), 9); -} - } // namespace resource_coordinator
diff --git a/chrome/browser/resources/chromeos/chromevox/BUILD.gn b/chrome/browser/resources/chromeos/chromevox/BUILD.gn index c35b938..df605581 100644 --- a/chrome/browser/resources/chromeos/chromevox/BUILD.gn +++ b/chrome/browser/resources/chromeos/chromevox/BUILD.gn
@@ -140,6 +140,7 @@ "cvox2/background/gesture_command_handler.js", "cvox2/background/i_search.js", "cvox2/background/keyboard_handler.js", + "cvox2/background/language_switching.js", "cvox2/background/live_regions.js", "cvox2/background/log.js", "cvox2/background/log_store.js", @@ -620,6 +621,7 @@ "cvox2/background/cursors_test.extjs", "cvox2/background/editing_test.extjs", "cvox2/background/i_search_test.extjs", + "cvox2/background/language_switching_test.extjs", "cvox2/background/live_regions_test.extjs", "cvox2/background/log_store_test.extjs", "cvox2/background/output_test.extjs",
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/background_test.extjs b/chrome/browser/resources/chromeos/chromevox/cvox2/background/background_test.extjs index 4276ed5..e575798 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/background_test.extjs +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/background_test.extjs
@@ -129,14 +129,6 @@ <p>After</p> </div> */}, - - languageSwitchingDoc: function() {/*! - <p id="breakfast">In the morning, I sometimes eat breakfast.</p> - <p id="lunch" lang="fr">Dans l'apres-midi, je dejeune.</p> - <p id="greeting"> - Hello it's a pleasure to meet you. <span lang="fr">Comment ca va?</span> - </p> - */}, }; /** Tests that ChromeVox classic is in this context. */ @@ -1870,26 +1862,6 @@ }); }); -TEST_F('ChromeVoxBackgroundTest', 'DetectLanguage', function() { - var mockFeedback = this.createMockFeedback(); - this.runWithLoadedTree(this.languageSwitchingDoc, function() { - - mockFeedback.call(doCmd('jumpToTop')) - .expectSpeech("In the morning, I sometimes eat breakfast."); - mockFeedback.call(doCmd('nextLine')) - .expectSpeech("Dans l'apres-midi, je dejeune."); - mockFeedback.call(doCmd('nextLine')) - .expectSpeech("Hello it's a pleasure to meet you. "); - mockFeedback.call(doCmd('nextLine')) - .expectSpeech("Comment ca va?"); - - // TODO(akihiroota): Implement expectSpeechWithLanguage() to assert correct - // output language. - - mockFeedback.replay(); - }); -}); - TEST_F('ChromeVoxBackgroundTest', 'AriaSliderWithValueNow', function() { var mockFeedback = this.createMockFeedback(); this.runWithLoadedTree(function(root) {/*
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/language_switching.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/language_switching.js new file mode 100644 index 0000000..717d41c --- /dev/null +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/language_switching.js
@@ -0,0 +1,90 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview Provides language switching services for ChromeVox. + */ + +goog.provide('LanguageSwitching'); + +/** + * The current output language. + * @private {string} + */ +LanguageSwitching.currentLanguage = ''; + +/** + * Maps languages to array of country codes that are considered equivalent. + * @private {!Object<string, !Array<string>>} + */ +LanguageSwitching.equivalentDialects = { + 'en': ['au', 'ca', 'gb', 'ie', 'nz', 'us', ''] + // TODO(akihiroota): Populate this object. +}; + +/** + * Updates current language and returns the output language for node. + * @param {AutomationNode} node + * @return {string} + */ +LanguageSwitching.updateCurrentLanguageForNode = function(node) { + if (!node) + return LanguageSwitching.currentLanguage; + // Use detected language. If unavailable, fallback on author-provided + // language. + var targetLanguage = node.detectedLanguage || node.language; + // If targetLanguage is still empty, then do not switch languages. + if (!targetLanguage) + return LanguageSwitching.currentLanguage; + + targetLanguage = targetLanguage.toLowerCase(); + // Validate targetLanguage. + // Each language code should be of length 2 or 5 AND each component should + // be of length 2. + // Ex: en or en-us + if (!(targetLanguage.length === 2 || targetLanguage.length === 5)) + return LanguageSwitching.currentLanguage; + var arr = targetLanguage.split('-'); + for (var i = 0; i < arr.length; ++i) { + if (!(arr[i].length === 2)) + return LanguageSwitching.currentLanguage; + } + + // Only switch languages if targetLanguage is different than currentLanguage. + if (!LanguageSwitching.isEquivalentToCurrentLanguage(targetLanguage)) + LanguageSwitching.currentLanguage = targetLanguage; + return LanguageSwitching.currentLanguage; +}; + +/** + * Returns true if targetLanguage is equivalent to current language. + * @param {!string} targetLanguage + * @return {boolean} + */ +LanguageSwitching.isEquivalentToCurrentLanguage = function(targetLanguage) { + // Language codes are composed of two components: language and country. + // Ex: en-us represents American English. + // Note: language codes sometimes come without the country component. + + // Compare the language codes of current and target language. + if (LanguageSwitching.currentLanguage.substring(0, 2) !== + targetLanguage.substring(0, 2)) { + return false; + } + + // Lookup the equivalent country codes for language. + var countryCodes = + LanguageSwitching.equivalentDialects[LanguageSwitching.currentLanguage + .substring(0, 2)]; + + // If language not in object, return false. + if (countryCodes === undefined) + return false; + + var currentCountryCode = LanguageSwitching.currentLanguage.substring(3); + var targetCountryCode = targetLanguage.substring(3); + + return countryCodes.includes(currentCountryCode) && + countryCodes.includes(targetCountryCode); +};
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/language_switching_test.extjs b/chrome/browser/resources/chromeos/chromevox/cvox2/background/language_switching_test.extjs new file mode 100644 index 0000000..3419880 --- /dev/null +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/language_switching_test.extjs
@@ -0,0 +1,121 @@ +// 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. + +// Include test fixture. +GEN_INCLUDE(['../../testing/chromevox_next_e2e_test_base.js']); + +GEN_INCLUDE(['../../testing/mock_feedback.js']); + +/** + * Test fixture for LanguageSwitching. + * @constructor + * @extends {ChromeVoxE2ETest} + */ +function ChromeVoxLanguageSwitchingTest() { + ChromeVoxNextE2ETest.call(this); +} + +ChromeVoxLanguageSwitchingTest.prototype = { + __proto__: ChromeVoxNextE2ETest.prototype, + + /** @override */ + setUp: function() { + window.doCmd = this.doCmd; + }, + + /** + * @return {!MockFeedback} + */ + createMockFeedback: function() { + var mockFeedback = new MockFeedback(this.newCallback(), + this.newCallback.bind(this)); + + mockFeedback.install(); + return mockFeedback; + }, + + /** + * Create a function which performs the command |cmd|. + * @param {string} cmd + * @return {function(): void} + */ + doCmd: function(cmd) { + return function() { + CommandHandler.onCommand(cmd); + } + }, + + multipleLanguagesDoc: function() {/*! + <p lang="en">Hello.</p> + <p lang="es">Hola.</p> + <p lang="fr">Salut.</p> + <span lang="it">Ciao.</span> + */}, + + nestedLanguagesDoc: function() {/*! + <p id="breakfast" lang="en">In the morning, I sometimes eat breakfast.</p> + <p id="lunch" lang="fr">Dans l'apres-midi, je dejeune.</p> + <p id="greeting" lang="en"> + Hello it's a pleasure to meet you. + <span lang="fr">Comment ca va?</span>Switching back to English.<span lang="es">Hola.</span>Goodbye. +</p> + */}, + + dialectsDoc: function() {/*! + <p lang="en-gb">Spoken in GB English.</p> + <p lang="en-us">This text should also be in GB English.</p> + <p lang="en-us">So should this text.</p> +*/}, +}; + +TEST_F('ChromeVoxLanguageSwitchingTest', 'MultipleLanguagesTest', function() { + var mockFeedback = this.createMockFeedback(); + this.runWithLoadedTree(this.multipleLanguagesDoc, function() { + // Turn on language switching. + localStorage['languageSwitching'] = 'true'; + + mockFeedback.call(doCmd('jumpToTop')).expectSpeechWithLanguage('en', 'Hello.'); + mockFeedback.call(doCmd('nextLine')).expectSpeechWithLanguage('es', 'Hola.'); + mockFeedback.call(doCmd('nextLine')).expectSpeechWithLanguage('fr', 'Salut.'); + mockFeedback.call(doCmd('nextLine')).expectSpeechWithLanguage('it', 'Ciao.'); + mockFeedback.replay(); + }); +}); + +TEST_F('ChromeVoxLanguageSwitchingTest', 'NestedLanguagesTest', function() { + var mockFeedback = this.createMockFeedback(); + this.runWithLoadedTree(this.nestedLanguagesDoc, function() { + localStorage['languageSwitching'] = 'true'; + + mockFeedback.call(doCmd('jumpToTop')) + .expectSpeechWithLanguage('en', 'In the morning, I sometimes eat breakfast.'); + mockFeedback.call(doCmd('nextLine')) + .expectSpeechWithLanguage('fr', "Dans l'apres-midi, je dejeune."); + mockFeedback.call(doCmd('nextLine')) + .expectSpeechWithLanguage('en', "Hello it's a pleasure to meet you. "); + mockFeedback.call(doCmd('nextLine')) + .expectSpeechWithLanguage('fr', 'Comment ca va?'); + mockFeedback.call(doCmd('nextLine')) + .expectSpeechWithLanguage('en', 'Switching back to English.'); + mockFeedback.call(doCmd('nextLine')) + .expectSpeechWithLanguage('es', 'Hola.'); + mockFeedback.call(doCmd('nextLine')) + .expectSpeechWithLanguage('en', 'Goodbye.'); + mockFeedback.replay(); + }); +}); + +TEST_F('ChromeVoxLanguageSwitchingTest', 'DialectTest', function() { + var mockFeedback = this.createMockFeedback(); + this.runWithLoadedTree(this.dialectsDoc, function(root) { + localStorage['languageSwitching'] = 'true'; + + mockFeedback.call(doCmd('jumpToTop')) + .call(doCmd('nextLine')) + .call(doCmd('nextLine')) + .expectSpeechWithLanguage('en-gb', 'Spoken in GB English.', + 'This text should also be in GB English.', 'So should this text.'); + mockFeedback.replay(); + }); +});
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/live_regions.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/live_regions.js index 5e283ddc..50d8ac59 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/live_regions.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/live_regions.js
@@ -77,7 +77,7 @@ * @type {boolean} * @private */ -LiveRegions.announceLiveRegionsFromBackgroundTabs_ = true; +LiveRegions.announceLiveRegionsFromBackgroundTabs_ = false; LiveRegions.prototype = { /**
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js index 43238805..b2bb04ee 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js
@@ -27,6 +27,7 @@ goog.require('cvox.ValueSelectionSpan'); goog.require('cvox.ValueSpan'); goog.require('goog.i18n.MessageFormat'); +goog.require('LanguageSwitching'); goog.scope(function() { var AutomationNode = chrome.automation.AutomationNode; @@ -1245,6 +1246,12 @@ this.append_(buff, node.name || '', options); ruleStr.writeTokenWithValue(token, node.name); + // Language Switching. Only execute if feature is enabled. + if (localStorage['languageSwitching'] === 'true') { + speechProps = new Output.SpeechProperties(); + speechProps['lang'] = + LanguageSwitching.updateCurrentLanguageForNode(node); + } } else if (token == 'description') { if (node.name == node.description) return;
diff --git a/chrome/browser/resources/chromeos/login/oobe_supervision_transition.html b/chrome/browser/resources/chromeos/login/oobe_supervision_transition.html index b21e969..1e5341f 100644 --- a/chrome/browser/resources/chromeos/login/oobe_supervision_transition.html +++ b/chrome/browser/resources/chromeos/login/oobe_supervision_transition.html
@@ -7,7 +7,8 @@ <link rel="stylesheet" href="oobe_flex_layout.css"> <link rel="stylesheet" href="oobe_supervision_transition.css"> <oobe-dialog id="supervisionTransitionDialog"> - <iron-icon src="chrome://oobe/supervision_icon.png" slot="oobe-icon"> + <iron-icon src="chrome://oobe/supervision_icon.png" slot="oobe-icon" + aria-hidden="true"> </iron-icon> <h1 slot="title" id="supervisionTitle"> <div hidden="[[isRemovingSupervision_]]"> @@ -19,12 +20,13 @@ </h1> <div slot="subtitle">$i18n{supervisionTransitionIntroMessage}</div> <div slot="footer"> - <paper-progress class="slow" indeterminate> + <paper-progress class="slow" aria-hidden="true" indeterminate> </paper-progress> </div> </oobe-dialog> <oobe-dialog id="supervisionTransitionErrorDialog" has-buttons hidden> - <iron-icon src="chrome://oobe/supervision_icon.png" slot="oobe-icon"> + <iron-icon src="chrome://oobe/supervision_icon.png" slot="oobe-icon" + aria-hidden="true"> </iron-icon> <h1 slot="title">$i18n{supervisionTransitionErrorTitle}</h1> <div slot="subtitle">$i18n{supervisionTransitionErrorMessage}</div>
diff --git a/chrome/browser/resources/md_extensions/host_permissions_toggle_list.html b/chrome/browser/resources/md_extensions/host_permissions_toggle_list.html index 56126ec..0e8b619 100644 --- a/chrome/browser/resources/md_extensions/host_permissions_toggle_list.html +++ b/chrome/browser/resources/md_extensions/host_permissions_toggle_list.html
@@ -20,10 +20,6 @@ margin-top: 12px; } - extensions-toggle-row { - color: black; - } - .toggle-section { display: flex; flex-direction: column;
diff --git a/chrome/browser/resources/print_preview/cloud_print_interface_js.js b/chrome/browser/resources/print_preview/cloud_print_interface_js.js index 713309b..4bed3cf 100644 --- a/chrome/browser/resources/print_preview/cloud_print_interface_js.js +++ b/chrome/browser/resources/print_preview/cloud_print_interface_js.js
@@ -332,7 +332,6 @@ for (let i = 0; i < users.length; i++) { this.userSessionIndex_[users[i]] = i; } - this.dispatchUserUpdateEvent_(request.result['request']['user'], users); } } @@ -433,6 +432,8 @@ }); // Extract and store users. this.setUsers_(request); + this.dispatchUserUpdateEvent_( + activeUser, request.result['request']['users']); // Dispatch SEARCH_DONE event. this.eventTarget_.dispatchEvent( new CustomEvent(CloudPrintInterfaceEventType.SEARCH_DONE, { @@ -555,11 +556,12 @@ request.result && request.result['request']['user'] && request.result['request']['users'] && request.account != request.result['request']['user']) { + const users = request.result['request']['users']; this.setUsers_(request); // In case the user account is known, but not the primary one, // activate it. - if (request.account && this.userSessionIndex_[request.account] > 0) { - this.dispatchUserUpdateEvent_(request.result['request']['user']); + if (this.userSessionIndex_[request.account] > 0 && request.account) { + this.dispatchUserUpdateEvent_(request.account, users); // Repeat the request for the newly activated account. this.printer( request.result['request']['params']['printerid'], request.origin, @@ -567,6 +569,7 @@ // Stop processing this request, wait for the new response. return; } + this.dispatchUserUpdateEvent_(request.result['request']['user'], users); } // Process response. if (request.xhr.status == 200 && request.result['success']) {
diff --git a/chrome/browser/resources/print_preview/data/destination_store.js b/chrome/browser/resources/print_preview/data/destination_store.js index 66c3e9e..3922b57 100644 --- a/chrome/browser/resources/print_preview/data/destination_store.js +++ b/chrome/browser/resources/print_preview/data/destination_store.js
@@ -374,6 +374,7 @@ let startedAutoSelect = false; let selected = false; + let account = ''; // Run through the destinations forward. As soon as we find a // destination, don't select any future destinations, just fetch their // capabilities in case the user switches to them later. @@ -382,19 +383,29 @@ print_preview.createRecentDestinationKey(destination)); const shouldSelectDestination = !this.useSystemDefaultAsDefault_ && !selected && !startedAutoSelect; + if (destination.account && account && destination.account !== account) { + // If we have already selected a destination with a specific account, + // don't request destinations from a different account, as doing so + // will cause the cloud print interface to reset the UI to have a + // different active user from the user that owns the selected printer. + continue; + } if (candidate != undefined) { // Destination is already in the store. Select it, if we haven't // started selecting a destination already. if (shouldSelectDestination) { this.selectDestination(candidate); selected = true; + account = destination.account; } } else { // Pre-fetch the destination and start auto select if needed. const startedFetch = this.fetchPreselectedDestination_( destination, shouldSelectDestination); - startedAutoSelect = - startedAutoSelect || (startedFetch && shouldSelectDestination); + if (startedFetch && shouldSelectDestination) { + startedAutoSelect = true; + account = destination.account; + } } } @@ -1147,7 +1158,6 @@ this.destinations_ = []; this.destinationMap_.clear(); this.inFlightCloudPrintRequests_.clear(); - this.selectDestination(null); this.loadedCloudOrigins_.clear(); this.destinationSearchStatus_.forEach((status, type) => { this.destinationSearchStatus_.set(
diff --git a/chrome/browser/resources/print_preview/new/destination_dialog.js b/chrome/browser/resources/print_preview/new/destination_dialog.js index 4325214..9cceebda 100644 --- a/chrome/browser/resources/print_preview/new/destination_dialog.js +++ b/chrome/browser/resources/print_preview/new/destination_dialog.js
@@ -22,6 +22,8 @@ activeUser: String, + currentDestinationAccount: String, + /** @type {!Array<string>} */ users: Array, @@ -169,12 +171,15 @@ if (this.searchQuery_) { this.$.searchBox.setValue(''); } - if (this.$.dialog.getNative().returnValue == 'success') { - this.metrics_.record(print_preview.Metrics.DestinationSearchBucket - .DESTINATION_CLOSED_CHANGED); - } else { - this.metrics_.record(print_preview.Metrics.DestinationSearchBucket - .DESTINATION_CLOSED_UNCHANGED); + const cancelled = this.$.dialog.getNative().returnValue !== 'success'; + this.metrics_.record( + cancelled ? print_preview.Metrics.DestinationSearchBucket + .DESTINATION_CLOSED_UNCHANGED : + print_preview.Metrics.DestinationSearchBucket + .DESTINATION_CLOSED_CHANGED); + if (cancelled && this.currentDestinationAccount && + this.currentDestinationAccount !== this.activeUser) { + this.fire('account-change', this.currentDestinationAccount); } }, @@ -364,6 +369,7 @@ const account = select.value; if (account) { this.showCloudPrintPromo = false; + this.loadingDestinations_ = true; this.destinations_ = []; this.fire('account-change', account); this.metrics_.record(
diff --git a/chrome/browser/resources/print_preview/new/destination_settings.html b/chrome/browser/resources/print_preview/new/destination_settings.html index ab8d9464..d2e86d7b 100644 --- a/chrome/browser/resources/print_preview/new/destination_settings.html +++ b/chrome/browser/resources/print_preview/new/destination_settings.html
@@ -81,6 +81,7 @@ invitation-store="[[invitationStore]]" recent-destination-list="[[recentDestinationList_]]" active-user="[[activeUser]]" users="[[users]]" + current-destination-account="[[destination.account]]" on-close="onDialogClose_"> </print-preview-destination-dialog> </template>
diff --git a/chrome/browser/resources/print_preview/new/destination_settings.js b/chrome/browser/resources/print_preview/new/destination_settings.js index fb76d0f..1ba7c43 100644 --- a/chrome/browser/resources/print_preview/new/destination_settings.js +++ b/chrome/browser/resources/print_preview/new/destination_settings.js
@@ -21,7 +21,7 @@ /** @type {!print_preview.Destination} */ destination: { type: Object, - observer: 'updateShouldShowSpinner_', + observer: 'onDestinationSet_', }, /** @type {?print_preview.DestinationStore} */ @@ -145,45 +145,42 @@ /** @private */ onCloudPrintStateChanged_: function() { - switch (this.cloudPrintState) { - case print_preview.CloudPrintState.ENABLED: - // Try to fetch all the destinations/invitations if the dialog is open. - const destinationDialog = this.$$('print-preview-destination-dialog'); - if (destinationDialog && destinationDialog.isOpen()) { - this.destinationStore.startLoadCloudDestinations(); - if (this.activeUser) { - this.invitationStore.startLoadingInvitations(this.activeUser); - } - } else { - // Only try to load the docs destination for now. If this request - // succeeds, it will trigger a transition to SIGNED_IN, and we can - // load the remaining destinations. - this.destinationStore.startLoadCookieDestination( - print_preview.Destination.GooglePromotedId.DOCS); - } - break; - case print_preview.CloudPrintState.SIGNED_IN: - // Load docs, in case sign in was triggered by something else. - this.destinationStore.startLoadCookieDestination( - print_preview.Destination.GooglePromotedId.DOCS); - // Load any recent cloud destinations for the dropdown. - this.recentDestinations.forEach(destination => { - if (destination.origin === print_preview.DestinationOrigin.COOKIES && - (destination.account === this.activeUser || - destination.account === '')) { - this.destinationStore.startLoadCookieDestination(destination.id); - } - }); - break; - default: - break; + if (this.cloudPrintState !== print_preview.CloudPrintState.SIGNED_IN) { + return; + } + + if (this.destination && this.destination.account !== '') { + this.updateDestination_(); + } + + // Load docs, in case the user was not signed in previously and signed in + // from the destinations dialog. + this.destinationStore.startLoadCookieDestination( + print_preview.Destination.GooglePromotedId.DOCS); + + // Load any recent cloud destinations for the dropdown. + this.recentDestinations.forEach(destination => { + if (destination.origin === print_preview.DestinationOrigin.COOKIES && + (destination.account === this.activeUser || + destination.account === '')) { + this.destinationStore.startLoadCookieDestination(destination.id); + } + }); + }, + + /** @private */ + onDestinationSet_: function() { + this.updateShouldShowSpinner_(); + if (this.cloudPrintState === print_preview.CloudPrintState.ENABLED) { + // Only try to load the docs destination for now. If this request + // succeeds, it will trigger a transition to SIGNED_IN, and we can + // load the remaining destinations. Otherwise, it will transition to + // NOT_SIGNED_IN, so we will not do this more than once. + this.destinationStore.startLoadCookieDestination( + print_preview.Destination.GooglePromotedId.DOCS); } }, - // TODO (rbpotter): Clean up the updateShouldShowSpinner_ observer so that it - // is a multiple property observer instead of registered twice once Polymer 1 - // support in Print Preview is dropped. It is currently registered twice to - // allow it to be called when |destination| is undefined. /** @private */ updateShouldShowSpinner_: function() { this.shouldShowSpinner_ = !this.destination && !this.noDestinationsFound; @@ -223,20 +220,16 @@ /** @private */ onDialogClose_: function() { - // Reset the select value in case the user dismissed the dialog without + // Reset the select value if the user dismissed the dialog without // selecting a new destination. if (this.destination) { - this.$.destinationSelect.updateDestination(); + this.updateDestination_(); } this.$.destinationSelect.focus(); }, /** @private */ - onShouldShowSpinnerChange_: function() { - if (this.shouldShowSpinner_ || this.noDestinationsFound) { - return; - } - + updateDestination_: function() { // TODO (rbpotter): Remove this conditional when the Polymer 2 migration // is completed. if (Polymer.DomIf) { @@ -249,4 +242,14 @@ }); } }, + + /** @private */ + onShouldShowSpinnerChange_: function() { + if (this.shouldShowSpinner_ || this.noDestinationsFound || + (this.cloudPrintState !== print_preview.CloudPrintState.SIGNED_IN && + this.destination.account !== '')) { + return; + } + this.updateDestination_(); + }, });
diff --git a/chrome/browser/resources/safe_browsing/download_file_types.asciipb b/chrome/browser/resources/safe_browsing/download_file_types.asciipb index d082d229..d3164c4 100644 --- a/chrome/browser/resources/safe_browsing/download_file_types.asciipb +++ b/chrome/browser/resources/safe_browsing/download_file_types.asciipb
@@ -1377,7 +1377,7 @@ file_types { extension: "pdf" uma_value: 14 - ping_setting: FULL_PING + ping_setting: SAMPLED_PING } file_types { extension: "pot"
diff --git a/chrome/browser/resources/settings/languages_page/languages_page.html b/chrome/browser/resources/settings/languages_page/languages_page.html index 803dccb2..de0b4b2 100644 --- a/chrome/browser/resources/settings/languages_page/languages_page.html +++ b/chrome/browser/resources/settings/languages_page/languages_page.html
@@ -147,6 +147,10 @@ <div title="[[item.language.nativeDisplayName]]"> [[item.language.displayName]] </div> + <div class="secondary" + hidden="[[!isTranslationTarget_(item.language.code)]]"> + $i18n{translateTargetLabel} + </div> <if expr="chromeos or is_win"> <div class="explain-selected" hidden="[[!isProspectiveUILanguage_(
diff --git a/chrome/browser/resources/settings/languages_page/languages_page.js b/chrome/browser/resources/settings/languages_page/languages_page.js index 7b8a6e25..01b5114 100644 --- a/chrome/browser/resources/settings/languages_page/languages_page.js +++ b/chrome/browser/resources/settings/languages_page/languages_page.js
@@ -217,6 +217,15 @@ return this.languages != undefined && this.languages.enabled.length <= 1; }, + /** + * @param {string} languageCode The language code identifying a language. + * @return {boolean} True iff this language is the one used when translating + * pages. + */ + isTranslationTarget_: function(languageCode) { + return languageCode == this.languages.translateTarget; + }, + // <if expr="chromeos"> /** * Applies Chrome OS session tweaks to the menu.
diff --git a/chrome/browser/resources/signin/dice_sync_confirmation/icons.html b/chrome/browser/resources/signin/dice_sync_confirmation/icons.html deleted file mode 100644 index d773635..0000000 --- a/chrome/browser/resources/signin/dice_sync_confirmation/icons.html +++ /dev/null
@@ -1,11 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/iron-iconset-svg/iron-iconset-svg.html"> - -<iron-iconset-svg name="sync-confirmation" size="24"> -<svg> -<defs> -<g id="lock"><path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z"></path></g> -<g id="spellcheck"><path d="M12.45 16h2.09L9.43 3H7.57L2.46 16h2.09l1.12-3h5.64l1.14 3zm-6.02-5L8.5 5.48 10.57 11H6.43zm15.16.59l-8.09 8.09L9.83 16l-1.41 1.41 5.09 5.09L23 13l-1.41-1.41z"></path></g> -</defs> -</svg> -</iron-iconset-svg>
diff --git a/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_app.html b/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_app.html index 03981ef..b2dcd13c 100644 --- a/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_app.html +++ b/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_app.html
@@ -1,14 +1,11 @@ <link rel="import" href="chrome://resources/html/polymer.html"> -<link rel="import" href="chrome://resources/cr_elements/icons.html"> <link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html"> <link rel="import" href="chrome://resources/html/cr.html"> <link rel="import" href="chrome://resources/html/load_time_data.html"> <link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html"> -<link rel="import" href="icons.html"> <link rel="import" href="signin_shared_css.html"> <link rel="import" href="sync_confirmation_browser_proxy.html"> @@ -89,7 +86,6 @@ } .message-container { - display: flex; line-height: 20px; margin-bottom: 16px; padding: 0 24px; @@ -99,28 +95,6 @@ color: var(--paper-grey-600); } - .logo { - background-size: cover; - flex-shrink: 0; - height: 16px; - margin-inline-end: 16px; - margin-top: 2px; - position: relative; - width: 16px; - } - - #sync-logo { - fill: var(--google-green-700); - } - - #spellcheck-logo { - fill: var(--google-blue-700); - } - - #lock-logo { - fill: var(--google-yellow-700); - } - #grey-banner { background: var(--paper-grey-50); height: 128px; @@ -161,37 +135,9 @@ $i18n{syncConfirmationTitle} </h1> <div class="message-container"> - <iron-icon icon="cr:sync" id="sync-logo" class="logo"></iron-icon> - <div> - <div consent-description>$i18n{syncConfirmationSyncInfoTitle}</div> - <div class="secondary" consent-description> - $i18n{syncConfirmationSyncInfoDesc} - </div> - </div> - </div> - <div class="message-container"> - <iron-icon icon="sync-confirmation:spellcheck" id="spellcheck-logo" - class="logo"> - </iron-icon> - <div> - <div consent-description> - $i18n{syncConfirmationSpellcheckInfoTitle} - </div> - <div class="secondary" consent-description> - $i18n{syncConfirmationSpellcheckInfoDesc} - </div> - </div> - </div> - <div class="message-container"> - <iron-icon icon="sync-confirmation:lock" id="lock-logo" class="logo"> - </iron-icon> - <div> - <div consent-description> - $i18n{syncConfirmationImproveChromeInfoTitle} - </div> - <div class="secondary" consent-description> - $i18n{syncConfirmationImproveChromeInfoDesc} - </div> + <div consent-description>$i18n{syncConfirmationSyncInfoTitle}</div> + <div class="secondary" consent-description> + $i18n{syncConfirmationSyncInfoDesc} </div> </div> <div id="footer" class="message-container secondary">
diff --git a/chrome/browser/search/ntp_icon_source.cc b/chrome/browser/search/ntp_icon_source.cc index 2f54984..3cf49f75 100644 --- a/chrome/browser/search/ntp_icon_source.cc +++ b/chrome/browser/search/ntp_icon_source.cc
@@ -7,6 +7,7 @@ #include <stddef.h> #include <algorithm> #include <cmath> +#include <utility> #include "base/bind.h" #include "base/callback.h" @@ -276,10 +277,7 @@ std::make_unique<suggestions::ImageDecoderImpl>(), content::BrowserContext::GetDefaultStoragePartition(profile) ->GetURLLoaderFactoryForBrowserProcess())), - weak_ptr_factory_(this) { - image_fetcher_->SetDataUseServiceName( - data_use_measurement::DataUseUserData::NTP_TILES); -} + weak_ptr_factory_(this) {} NtpIconSource::~NtpIconSource() = default; @@ -432,18 +430,18 @@ "default." policy_exception_justification: "Not implemented." })"); - image_fetcher_->SetDesiredImageFrameSize( + image_fetcher::ImageFetcherParams params(traffic_annotation); + params.set_frame_size( gfx::Size(request.icon_size_in_pixels, request.icon_size_in_pixels)); image_fetcher_->FetchImage( - /*id=*/std::string(), server_favicon_url, + server_favicon_url, base::Bind(&NtpIconSource::OnServerFaviconAvailable, weak_ptr_factory_.GetWeakPtr(), request), - traffic_annotation); + std::move(params)); } void NtpIconSource::OnServerFaviconAvailable( const NtpIconRequest& request, - const std::string& id, const gfx::Image& fetched_image, const image_fetcher::RequestMetadata& metadata) { // If a server icon was not found, |fetched_bitmap| will be empty and a
diff --git a/chrome/browser/search/ntp_icon_source.h b/chrome/browser/search/ntp_icon_source.h index fce0016..df56900 100644 --- a/chrome/browser/search/ntp_icon_source.h +++ b/chrome/browser/search/ntp_icon_source.h
@@ -54,7 +54,6 @@ bool IsRequestedUrlInServerSuggestions(const GURL& url); void RequestServerFavicon(const NtpIconRequest& request); void OnServerFaviconAvailable(const NtpIconRequest& request, - const std::string& id, const gfx::Image& fetched_image, const image_fetcher::RequestMetadata& metadata);
diff --git a/chrome/browser/search/suggestions/image_fetcher_impl_browsertest.cc b/chrome/browser/search/suggestions/image_fetcher_impl_browsertest.cc index 763856b2..1eb9ca9f 100644 --- a/chrome/browser/search/suggestions/image_fetcher_impl_browsertest.cc +++ b/chrome/browser/search/suggestions/image_fetcher_impl_browsertest.cc
@@ -28,7 +28,6 @@ namespace { -const char kTestUrl[] = "http://go.com/"; const char kTestImagePath[] = "/image_decoding/droids.png"; const char kInvalidImagePath[] = "/DOESNOTEXIST"; @@ -50,8 +49,8 @@ ASSERT_TRUE(test_server_.Start()); } - ImageFetcherImpl* CreateImageFetcher() { - ImageFetcherImpl* fetcher = new ImageFetcherImpl( + ImageFetcher* CreateImageFetcher() { + ImageFetcher* fetcher = new ImageFetcherImpl( std::make_unique<suggestions::ImageDecoderImpl>(), content::BrowserContext::GetDefaultStoragePartition( browser()->profile()) @@ -60,7 +59,6 @@ } void OnImageAvailable(base::RunLoop* loop, - const std::string& id, const gfx::Image& image, const image_fetcher::RequestMetadata& metadata) { if (!image.IsEmpty()) { @@ -81,11 +79,11 @@ } void FetchImageAndDataHelper(const GURL& image_url) { - std::unique_ptr<ImageFetcherImpl> image_fetcher_(CreateImageFetcher()); + std::unique_ptr<ImageFetcher> image_fetcher_(CreateImageFetcher()); base::RunLoop run_loop; image_fetcher_->FetchImageAndData( - kTestUrl, image_url, + image_url, base::BindOnce(&ImageFetcherImplBrowserTest::OnImageDataAvailable, base::Unretained(this)), base::Bind(&ImageFetcherImplBrowserTest::OnImageAvailable,
diff --git a/chrome/browser/sessions/tab_loader.cc b/chrome/browser/sessions/tab_loader.cc index ed8ea1f6..cf8b4eb8 100644 --- a/chrome/browser/sessions/tab_loader.cc +++ b/chrome/browser/sessions/tab_loader.cc
@@ -130,7 +130,7 @@ void TabLoader::SetMaxSimultaneousLoadsForTesting(size_t loading_slots) { DCHECK_EQ(0u, reentry_depth_); // Should never be called reentrantly. - max_simultaneous_loads_ = loading_slots; + max_simultaneous_loads_for_testing_ = loading_slots; } void TabLoader::SetTickClockForTesting(base::TickClock* tick_clock) { @@ -279,8 +279,6 @@ bool delegate_existed = true; if (!delegate_) { delegate_ = TabLoaderDelegate::Create(this); - if (max_simultaneous_loads_ == 0) - max_simultaneous_loads_ = delegate_->GetMaxSimultaneousTabLoads(); delegate_existed = false; } @@ -404,8 +402,8 @@ // Determine the number of free loading slots available. size_t tabs_to_load = 0; - if (loading_tab_count < max_simultaneous_loads_) - tabs_to_load = max_simultaneous_loads_ - loading_tab_count; + if (loading_tab_count < MaxSimultaneousLoads()) + tabs_to_load = MaxSimultaneousLoads() - loading_tab_count; // Cap the number of loads by the actual number of tabs remaining. tabs_to_load = std::min(tabs_to_load, tabs_to_load_.size()); @@ -758,3 +756,9 @@ } } } + +size_t TabLoader::MaxSimultaneousLoads() const { + if (max_simultaneous_loads_for_testing_ != 0) + return max_simultaneous_loads_for_testing_; + return delegate_->GetMaxSimultaneousTabLoads(); +}
diff --git a/chrome/browser/sessions/tab_loader.h b/chrome/browser/sessions/tab_loader.h index a0f5408..b5c2a0cc 100644 --- a/chrome/browser/sessions/tab_loader.h +++ b/chrome/browser/sessions/tab_loader.h
@@ -216,6 +216,12 @@ // sorted. void MoveToSortedPosition(TabVector::iterator it); + // The number of tabs to load simultaneously. This is a soft cap in that it + // can be exceeded by tabs that timeout, visible tabs, and user interactions + // forcing a tab load. However, normal session restore tab loads will not kick + // off a new load unless there is room below this cap. + size_t MaxSimultaneousLoads() const; + // The OS specific delegate of the TabLoader. std::unique_ptr<TabLoaderDelegate> delegate_; @@ -227,12 +233,9 @@ // non-active tabs from being scheduled to load initially. bool did_one_tab_load_ = false; - // The number of tabs to load simultaneously. This is a soft cap in that it - // can be exceeded by tabs that timeout, visible tabs, and user interactions - // forcing a tab load. However, normal session restore tab loads will not kick - // off a new load unless there is room below this cap. This is initialized via - // the delegate. The initial value of 0 is used to indicate "uninitialized". - size_t max_simultaneous_loads_ = 0; + // Overrides the value of max simultaneous loads that is normally provided by + // the policy engine. + size_t max_simultaneous_loads_for_testing_ = 0; // The delay timer multiplier. See class description for details. size_t force_load_delay_multiplier_ = 1;
diff --git a/chrome/browser/sessions/tab_loader_delegate.cc b/chrome/browser/sessions/tab_loader_delegate.cc index f42d5c5..f685120d 100644 --- a/chrome/browser/sessions/tab_loader_delegate.cc +++ b/chrome/browser/sessions/tab_loader_delegate.cc
@@ -71,6 +71,11 @@ // TabLoaderDelegate: void NotifyTabLoadStarted() override { policy_->NotifyTabLoadStarted(); } + // TabLoaderDelegate: + resource_coordinator::SessionRestorePolicy* GetPolicyForTesting() override { + return policy_; + } + // network::NetworkConnectionTracker::NetworkConnectionObserver: void OnConnectionChanged(network::mojom::ConnectionType type) override;
diff --git a/chrome/browser/sessions/tab_loader_delegate.h b/chrome/browser/sessions/tab_loader_delegate.h index 42f8f72..88123c9 100644 --- a/chrome/browser/sessions/tab_loader_delegate.h +++ b/chrome/browser/sessions/tab_loader_delegate.h
@@ -71,6 +71,9 @@ // Notifies the delegate that a tab load has been initiated. virtual void NotifyTabLoadStarted() = 0; + // Returns the policy engine that is in use. + virtual resource_coordinator::SessionRestorePolicy* GetPolicyForTesting() = 0; + // Testing seam to inject a custom SessionRestorePolicy. static void SetSessionRestorePolicyForTesting( resource_coordinator::SessionRestorePolicy* policy);
diff --git a/chrome/browser/sessions/tab_loader_tester.cc b/chrome/browser/sessions/tab_loader_tester.cc index b3f3f905..c1d1a64 100644 --- a/chrome/browser/sessions/tab_loader_tester.cc +++ b/chrome/browser/sessions/tab_loader_tester.cc
@@ -83,6 +83,10 @@ return TabLoader::shared_tab_loader_; } +resource_coordinator::SessionRestorePolicy* TabLoaderTester::GetPolicy() { + return tab_loader_->delegate_->GetPolicyForTesting(); +} + bool TabLoaderTester::IsSharedTabLoader() const { return tab_loader_ == TabLoader::shared_tab_loader_; }
diff --git a/chrome/browser/sessions/tab_loader_tester.h b/chrome/browser/sessions/tab_loader_tester.h index e515d2a..30cc099 100644 --- a/chrome/browser/sessions/tab_loader_tester.h +++ b/chrome/browser/sessions/tab_loader_tester.h
@@ -6,6 +6,7 @@ #define CHROME_BROWSER_SESSIONS_TAB_LOADER_TESTER_H_ #include "base/timer/timer.h" +#include "chrome/browser/resource_coordinator/session_restore_policy.h" #include "chrome/browser/sessions/tab_loader.h" // Wraps a TabLoader and exposes helper functions for testing. See tab_loader.h @@ -44,6 +45,9 @@ size_t scheduled_to_load_count() const; static TabLoader* shared_tab_loader(); + // Returns the session restore policy engine that is currently being used. + resource_coordinator::SessionRestorePolicy* GetPolicy(); + // Additional helper functions. bool IsSharedTabLoader() const; bool HasTimedOutLoads() const;
diff --git a/chrome/browser/sessions/tab_loader_unittest.cc b/chrome/browser/sessions/tab_loader_unittest.cc index 4c6a06b0..8d4c561e 100644 --- a/chrome/browser/sessions/tab_loader_unittest.cc +++ b/chrome/browser/sessions/tab_loader_unittest.cc
@@ -334,32 +334,6 @@ test_policy_.reset(); - std::set<std::string> features; - features.insert(features::kInfiniteSessionRestore.name); - - // Configure the policy engine via its experimental feature. This configures - // it such that there are 2 max simultaneous tab loads, and 3 maximum tabs to - // restore. - std::map<std::string, std::string> params; - params[rc::InfiniteSessionRestoreParams::kMinSimultaneousTabLoads.name] = "2"; - params[rc::InfiniteSessionRestoreParams::kMaxSimultaneousTabLoads.name] = "2"; - params[rc::InfiniteSessionRestoreParams::kCoresPerSimultaneousTabLoad.name] = - "0"; - params[rc::InfiniteSessionRestoreParams::kMinTabsToRestore.name] = "1"; - params[rc::InfiniteSessionRestoreParams::kMaxTabsToRestore.name] = "3"; - - // Disable these policy features. - params[rc::InfiniteSessionRestoreParams::kMbFreeMemoryPerTabToRestore.name] = - "0"; - params[rc::InfiniteSessionRestoreParams::kMaxTimeSinceLastUseToRestore.name] = - "0"; - params[rc::InfiniteSessionRestoreParams::kMinSiteEngagementToRestore.name] = - "0"; - - variations::testing::VariationParamsManager variations_manager; - variations_manager.SetVariationParamsWithFeatureAssociations( - "DummyTrial", params, features); - // Don't directly configure the max simultaneous loads, but rather let it be // configured via the policy engine. max_simultaneous_loads_ = 0; @@ -373,6 +347,19 @@ EXPECT_EQ(4u, tab_loader_.tabs_to_load().size()); EXPECT_EQ(1u, tab_loader_.scheduled_to_load_count()); + // Configure the policy engine explicitly. Values of zero disable those + // particular aspects of the policy engine. + auto* policy = tab_loader_.GetPolicy(); + policy->MinSimultaneousTabLoadsForTesting() = 2; + policy->MaxSimultaneousTabLoadsForTesting() = 2; + policy->CoresPerSimultaneousTabLoadForTesting() = 0; + policy->MinTabsToRestoreForTesting() = 1; + policy->MaxTabsToRestoreForTesting() = 3; + policy->MbFreeMemoryPerTabToRestoreForTesting() = 0; + policy->MaxTimeSinceLastUseToRestoreForTesting() = base::TimeDelta(); + policy->MinSiteEngagementToRestoreForTesting() = 0; + policy->CalculateSimultaneousTabLoadsForTesting(); + // Simulate the first tab as having loaded. Another 2 should start loading. SimulateLoaded(0); EXPECT_EQ(2u, tab_loader_.tabs_to_load().size());
diff --git a/chrome/browser/signin/signin_util_win.cc b/chrome/browser/signin/signin_util_win.cc index 7770ee33..5593c3e 100644 --- a/chrome/browser/signin/signin_util_win.cc +++ b/chrome/browser/signin/signin_util_win.cc
@@ -20,8 +20,6 @@ #include "chrome/browser/profiles/profile_window.h" #include "chrome/browser/signin/about_signin_internals_factory.h" #include "chrome/browser/signin/identity_manager_factory.h" -#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" -#include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h" @@ -29,7 +27,6 @@ #include "components/os_crypt/os_crypt.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/about_signin_internals.h" -#include "components/signin/core/browser/signin_manager.h" #include "components/signin/core/browser/signin_metrics.h" #include "components/signin/core/browser/signin_pref_names.h" #include "services/identity/public/cpp/accounts_mutator.h" @@ -207,7 +204,7 @@ if (!(first_run::IsChromeFirstRun() && g_browser_process->profile_manager()->GetInitialProfileDir() == profile->GetPath().BaseName() && - !SigninManagerFactory::GetForProfile(profile)->IsAuthenticated())) { + !IdentityManagerFactory::GetForProfile(profile)->HasPrimaryAccount())) { return; } @@ -220,19 +217,17 @@ // - The profile is marked as having been signed in with a system credential. // - The profile is already signed in. // - The profile is in an auth error state. - SigninManager* manager = SigninManagerFactory::GetForProfile(profile); - ProfileOAuth2TokenService* token_service = - ProfileOAuth2TokenServiceFactory::GetForProfile(profile); + auto* identity_manager = IdentityManagerFactory::GetForProfile(profile); if (!(profile->GetPrefs()->GetBoolean( prefs::kSignedInWithCredentialProvider) && - manager->IsAuthenticated() && - token_service->RefreshTokenHasError( - manager->GetAuthenticatedAccountId()))) { + identity_manager->HasPrimaryAccount() && + identity_manager->HasAccountWithRefreshTokenInPersistentErrorState( + identity_manager->GetPrimaryAccountId()))) { return false; } base::string16 gaia_id = - base::UTF8ToUTF16(manager->GetAuthenticatedAccountInfo().gaia.c_str()); + base::UTF8ToUTF16(identity_manager->GetPrimaryAccountInfo().gaia.c_str()); return TrySigninWithCredentialProvider(profile, gaia_id, false); }
diff --git a/chrome/browser/supervised_user/child_accounts/child_account_service.cc b/chrome/browser/supervised_user/child_accounts/child_account_service.cc index 69d4a17..0e64f16 100644 --- a/chrome/browser/supervised_user/child_accounts/child_account_service.cc +++ b/chrome/browser/supervised_user/child_accounts/child_account_service.cc
@@ -77,11 +77,9 @@ gaia_cookie_manager_( GaiaCookieManagerServiceFactory::GetForProfile(profile)), weak_ptr_factory_(this) { - gaia_cookie_manager_->AddObserver(this); } ChildAccountService::~ChildAccountService() { - gaia_cookie_manager_->RemoveObserver(this); } // static @@ -102,6 +100,7 @@ void ChildAccountService::Init() { SupervisedUserServiceFactory::GetForProfile(profile_)->SetDelegate(this); + gaia_cookie_manager_->AddObserver(this); IdentityManagerFactory::GetForProfile(profile_)->AddObserver(this); PropagateChildStatusToUser(profile_->IsChild()); @@ -121,6 +120,7 @@ void ChildAccountService::Shutdown() { family_fetcher_.reset(); IdentityManagerFactory::GetForProfile(profile_)->RemoveObserver(this); + gaia_cookie_manager_->RemoveObserver(this); SupervisedUserServiceFactory::GetForProfile(profile_)->SetDelegate(nullptr); DCHECK(!active_); }
diff --git a/chrome/browser/sync/sync_ui_util.cc b/chrome/browser/sync/sync_ui_util.cc index 9b0af47..871c01b 100644 --- a/chrome/browser/sync/sync_ui_util.cc +++ b/chrome/browser/sync/sync_ui_util.cc
@@ -4,27 +4,24 @@ #include "chrome/browser/sync/sync_ui_util.h" -#include "base/strings/utf_string_conversions.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/signin_error_controller_factory.h" +#include "chrome/browser/signin/signin_util.h" #include "chrome/browser/sync/profile_sync_service_factory.h" -#include "chrome/common/url_constants.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" -#include "components/browser_sync/profile_sync_service.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/signin_error_controller.h" #include "components/strings/grit/components_strings.h" +#include "components/sync/driver/sync_service.h" +#include "components/sync/driver/sync_user_settings.h" +#include "components/sync/engine/sync_status.h" #include "components/sync/protocol/sync_protocol_error.h" #include "google_apis/gaia/google_service_auth_error.h" #include "services/identity/public/cpp/identity_manager.h" #include "services/identity/public/cpp/primary_account_mutator.h" #include "ui/base/l10n/l10n_util.h" -#if !defined(OS_CHROMEOS) -#include "chrome/browser/signin/signin_util.h" -#endif // defined(OS_CHROMEOS) - namespace sync_ui_util { namespace { @@ -32,10 +29,10 @@ // Returns the message that should be displayed when the user is authenticated // and can connect to the sync server. If the user hasn't yet authenticated, an // empty string is returned. -base::string16 GetSyncedStateStatusLabel(const syncer::SyncService* service, - bool sync_everything) { - if (!service || service->HasDisableReason( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY)) { +base::string16 GetSyncedStateStatusLabel(const syncer::SyncService* service) { + DCHECK(service); + if (service->HasDisableReason( + syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY)) { // User is signed in, but sync is disabled. return l10n_util::GetStringUTF16(IDS_SIGNED_IN_WITH_SYNC_DISABLED); } @@ -50,8 +47,9 @@ } return l10n_util::GetStringUTF16( - sync_everything ? IDS_SYNC_ACCOUNT_SYNCING - : IDS_SYNC_ACCOUNT_SYNCING_CUSTOM_DATA_TYPES); + service->GetUserSettings()->IsSyncEverythingEnabled() + ? IDS_SYNC_ACCOUNT_SYNCING + : IDS_SYNC_ACCOUNT_SYNCING_CUSTOM_DATA_TYPES); } void GetStatusForActionableError(syncer::ClientAction action, @@ -77,18 +75,15 @@ } } -void GetStatusForUnrecoverableError(Profile* profile, - const syncer::SyncService* service, +void GetStatusForUnrecoverableError(bool is_user_signout_allowed, + syncer::ClientAction action, base::string16* status_label, base::string16* link_label, ActionType* action_type) { // Unrecoverable error is sometimes accompanied by actionable error. // If status message is set display that message, otherwise show generic // unrecoverable error message. - syncer::SyncStatus status; - service->QueryDetailedSyncStatus(&status); - GetStatusForActionableError(status.sync_protocol_error.action, status_label, - link_label, action_type); + GetStatusForActionableError(action, status_label, link_label, action_type); if (status_label->empty()) { *action_type = REAUTHENTICATE; *link_label = l10n_util::GetStringUTF16(IDS_SYNC_RELOGIN_LINK_LABEL); @@ -97,7 +92,7 @@ *status_label = l10n_util::GetStringUTF16(IDS_SYNC_STATUS_UNRECOVERABLE_ERROR); // The message for managed accounts is the same as that of the cros. - if (!signin_util::IsUserSignoutAllowedForProfile(profile)) { + if (!is_user_signout_allowed) { *status_label = l10n_util::GetStringUTF16( IDS_SYNC_STATUS_UNRECOVERABLE_ERROR_NEEDS_SIGNOUT); } @@ -142,12 +137,13 @@ } // status_label and link_label must either be both null or both non-null. -MessageType GetStatusInfo(Profile* profile, - const syncer::SyncService* service, - identity::IdentityManager* identity_manager, - base::string16* status_label, - base::string16* link_label, - ActionType* action_type) { +MessageType GetStatusLabelsImpl(const syncer::SyncService* service, + identity::IdentityManager* identity_manager, + const bool is_user_signout_allowed, + const GoogleServiceAuthError& auth_error, + base::string16* status_label, + base::string16* link_label, + ActionType* action_type) { DCHECK(service); DCHECK_EQ(status_label == nullptr, link_label == nullptr); @@ -159,6 +155,9 @@ const auto* primary_account_mutator = identity_manager->GetPrimaryAccountMutator(); + syncer::SyncStatus status; + service->QueryDetailedSyncStatus(&status); + if (service->GetUserSettings()->IsFirstSetupComplete() || service->HasDisableReason( syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY) || @@ -169,8 +168,9 @@ if (service->HasUnrecoverableError()) { if (status_label && link_label) { - GetStatusForUnrecoverableError(profile, service, status_label, - link_label, action_type); + GetStatusForUnrecoverableError(is_user_signout_allowed, + status.sync_protocol_error.action, + status_label, link_label, action_type); } return SYNC_ERROR; } @@ -186,8 +186,6 @@ } // Since there is no auth in progress, check for an auth error first. - GoogleServiceAuthError auth_error = - SigninErrorControllerFactory::GetForProfile(profile)->auth_error(); if (auth_error.state() != GoogleServiceAuthError::NONE) { if (status_label && link_label) { GetStatusForAuthError(auth_error, status_label, link_label, @@ -197,8 +195,6 @@ } // We don't have an auth error. Check for an actionable error. - syncer::SyncStatus status; - service->QueryDetailedSyncStatus(&status); if (status_label && link_label) { GetStatusForActionableError(status.sync_protocol_error.action, status_label, link_label, action_type); @@ -219,24 +215,19 @@ return SYNC_ERROR; } - const bool sync_everything = - service->GetUserSettings()->IsSyncEverythingEnabled(); + if (status_label) { + *status_label = GetSyncedStateStatusLabel(service); + } // Check to see if sync has been disabled via the dasboard and needs to be // set up once again. if (service->HasDisableReason( syncer::SyncService::DISABLE_REASON_USER_CHOICE) && status.sync_protocol_error.error_type == syncer::NOT_MY_BIRTHDAY) { - if (status_label) { - *status_label = GetSyncedStateStatusLabel(service, sync_everything); - } return PRE_SYNCED; } // There is no error. Display "Last synced..." message. - if (status_label) { - *status_label = GetSyncedStateStatusLabel(service, sync_everything); - } return SYNCED; } @@ -249,8 +240,6 @@ *status_label = l10n_util::GetStringUTF16(IDS_SYNC_NTP_SETUP_IN_PROGRESS); } - GoogleServiceAuthError auth_error = - SigninErrorControllerFactory::GetForProfile(profile)->auth_error(); if (primary_account_mutator && primary_account_mutator->LegacyIsPrimaryAccountAuthInProgress()) { if (status_label) { @@ -268,8 +257,9 @@ } else if (service->HasUnrecoverableError()) { result_type = SYNC_ERROR; if (status_label && link_label) { - GetStatusForUnrecoverableError(profile, service, status_label, link_label, - action_type); + GetStatusForUnrecoverableError(is_user_signout_allowed, + status.sync_protocol_error.action, + status_label, link_label, action_type); } } else { if (ShouldRequestSyncConfirmation(service)) { @@ -302,10 +292,13 @@ base::string16* link_label, ActionType* action_type) { DCHECK(service); - DCHECK(status_label); - DCHECK(link_label); - return GetStatusInfo(profile, service, identity_manager, status_label, - link_label, action_type); + + const bool is_user_signout_allowed = + signin_util::IsUserSignoutAllowedForProfile(profile); + GoogleServiceAuthError auth_error = + SigninErrorControllerFactory::GetForProfile(profile)->auth_error(); + return GetStatusLabelsImpl(service, identity_manager, is_user_signout_allowed, + auth_error, status_label, link_label, action_type); } #if !defined(OS_CHROMEOS) @@ -387,8 +380,9 @@ identity::IdentityManager* identity_manager) { DCHECK(service); ActionType action_type = NO_ACTION; - return GetStatusInfo(profile, service, identity_manager, nullptr, nullptr, - &action_type); + return GetStatusLabels(profile, service, identity_manager, + /*status_label=*/nullptr, /*link_label=*/nullptr, + &action_type); } bool ShouldRequestSyncConfirmation(const syncer::SyncService* service) {
diff --git a/chrome/browser/sync/sync_ui_util.h b/chrome/browser/sync/sync_ui_util.h index f6e225d..56493c1 100644 --- a/chrome/browser/sync/sync_ui_util.h +++ b/chrome/browser/sync/sync_ui_util.h
@@ -52,6 +52,7 @@ // Create status and link labels for the current status labels and link text // by querying |service|. +// |status_label| and |link_label| must either be both null or both non-null. MessageType GetStatusLabels(Profile* profile, const syncer::SyncService* service, identity::IdentityManager* identity_manager,
diff --git a/base/trace_event/trace_event_system_stats_monitor.cc b/chrome/browser/tracing/trace_event_system_stats_monitor.cc similarity index 70% rename from base/trace_event/trace_event_system_stats_monitor.cc rename to chrome/browser/tracing/trace_event_system_stats_monitor.cc index 599be19..c43b6a2 100644 --- a/base/trace_event/trace_event_system_stats_monitor.cc +++ b/chrome/browser/tracing/trace_event_system_stats_monitor.cc
@@ -2,29 +2,33 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/trace_event/trace_event_system_stats_monitor.h" +#include "chrome/browser/tracing/trace_event_system_stats_monitor.h" #include <memory> #include "base/bind.h" -#include "base/debug/leak_annotations.h" #include "base/json/json_writer.h" -#include "base/lazy_instance.h" -#include "base/logging.h" -#include "base/macros.h" #include "base/process/process_metrics.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_util.h" #include "base/task/post_task.h" -#include "base/threading/thread_local_storage.h" #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" -namespace base { -namespace trace_event { +namespace tracing { namespace { +// Length of time interval between stat profiles. +static const int kSamplingIntervalMilliseconds = 2000; + +// Converts system memory profiling stats in |input| to trace event compatible +// JSON and appends to |output|. +void AppendSystemProfileAsTraceFormat(const base::SystemMetrics& system_metrics, + std::string* output) { + std::string tmp; + base::JSONWriter::Write(*system_metrics.ToValue(), &tmp); + *output += tmp; +} + ///////////////////////////////////////////////////////////////////////////// // Holds profiled system stats until the tracing system needs to serialize it. class SystemStatsHolder : public base::trace_event::ConvertableToTraceFormat { @@ -42,13 +46,13 @@ } private: - SystemMetrics system_stats_; + base::SystemMetrics system_stats_; DISALLOW_COPY_AND_ASSIGN(SystemStatsHolder); }; void SystemStatsHolder::GetSystemProfilingStats() { - system_stats_ = SystemMetrics::Sample(); + system_stats_ = base::SystemMetrics::Sample(); } void DumpSystemStatsImpl(TraceEventSystemStatsMonitor* stats_monitor) { @@ -66,29 +70,28 @@ ////////////////////////////////////////////////////////////////////////////// -TraceEventSystemStatsMonitor::TraceEventSystemStatsMonitor( - scoped_refptr<SingleThreadTaskRunner> task_runner) - : task_runner_(task_runner), - weak_factory_(this) { +TraceEventSystemStatsMonitor::TraceEventSystemStatsMonitor() + : task_runner_(base::ThreadTaskRunnerHandle::Get()), weak_factory_(this) { // Force the "system_stats" category to show up in the trace viewer. - TraceLog::GetCategoryGroupEnabled(TRACE_DISABLED_BY_DEFAULT("system_stats")); + base::trace_event::TraceLog::GetCategoryGroupEnabled( + TRACE_DISABLED_BY_DEFAULT("system_stats")); // Allow this to be instantiated on unsupported platforms, but don't run. - TraceLog::GetInstance()->AddEnabledStateObserver(this); + base::trace_event::TraceLog::GetInstance()->AddEnabledStateObserver(this); } TraceEventSystemStatsMonitor::~TraceEventSystemStatsMonitor() { if (dump_timer_.IsRunning()) StopProfiling(); - TraceLog::GetInstance()->RemoveEnabledStateObserver(this); + base::trace_event::TraceLog::GetInstance()->RemoveEnabledStateObserver(this); } void TraceEventSystemStatsMonitor::OnTraceLogEnabled() { // Check to see if system tracing is enabled. bool enabled; - TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT( - "system_stats"), &enabled); + TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("system_stats"), + &enabled); if (!enabled) return; task_runner_->PostTask( @@ -107,12 +110,11 @@ if (dump_timer_.IsRunning()) return; - dump_timer_.Start(FROM_HERE, - TimeDelta::FromMilliseconds(TraceEventSystemStatsMonitor:: - kSamplingIntervalMilliseconds), - base::Bind(&TraceEventSystemStatsMonitor:: - DumpSystemStats, - weak_factory_.GetWeakPtr())); + dump_timer_.Start( + FROM_HERE, + base::TimeDelta::FromMilliseconds(kSamplingIntervalMilliseconds), + base::BindRepeating(&TraceEventSystemStatsMonitor::DumpSystemStats, + weak_factory_.GetWeakPtr())); } void TraceEventSystemStatsMonitor::DumpSystemStats() { @@ -132,16 +134,8 @@ dump_timer_.Stop(); } -bool TraceEventSystemStatsMonitor::IsTimerRunningForTest() const { +bool TraceEventSystemStatsMonitor::IsTimerRunningForTesting() const { return dump_timer_.IsRunning(); } -void AppendSystemProfileAsTraceFormat(const SystemMetrics& system_metrics, - std::string* output) { - std::string tmp; - base::JSONWriter::Write(*system_metrics.ToValue(), &tmp); - *output += tmp; -} - -} // namespace trace_event -} // namespace base +} // namespace tracing
diff --git a/chrome/browser/tracing/trace_event_system_stats_monitor.h b/chrome/browser/tracing/trace_event_system_stats_monitor.h new file mode 100644 index 0000000..0c1dd52 --- /dev/null +++ b/chrome/browser/tracing/trace_event_system_stats_monitor.h
@@ -0,0 +1,60 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_TRACING_TRACE_EVENT_SYSTEM_STATS_MONITOR_H_ +#define CHROME_BROWSER_TRACING_TRACE_EVENT_SYSTEM_STATS_MONITOR_H_ + +#include <string> + +#include <memory> + +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "base/process/process_metrics.h" +#include "base/timer/timer.h" +#include "base/trace_event/trace_log.h" + +namespace tracing { + +// Watches for chrome://tracing to be enabled or disabled. When tracing is +// enabled, also enables system events profiling. This class is the preferred +// way to turn system tracing on and off. +class TraceEventSystemStatsMonitor + : public base::trace_event::TraceLog::EnabledStateObserver { + public: + TraceEventSystemStatsMonitor(); + ~TraceEventSystemStatsMonitor() override; + + // base::trace_event::TraceLog::EnabledStateChangedObserver overrides: + void OnTraceLogEnabled() override; + void OnTraceLogDisabled() override; + + // Retrieves system profiling at the current time. + void DumpSystemStats(); + + bool IsTimerRunningForTesting() const; + + void StartProfilingForTesting() { StartProfiling(); } + void StopProfilingForTesting() { StopProfiling(); } + + private: + void StartProfiling(); + + void StopProfiling(); + + // Ensures the observer starts and stops tracing on the primary thread. + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; + + // Timer to schedule system profile dumps. + base::RepeatingTimer dump_timer_; + + base::WeakPtrFactory<TraceEventSystemStatsMonitor> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(TraceEventSystemStatsMonitor); +}; + +} // namespace tracing + +#endif // CHROME_BROWSER_TRACING_TRACE_EVENT_SYSTEM_STATS_MONITOR_H_
diff --git a/chrome/browser/tracing/trace_event_system_stats_monitor_unittest.cc b/chrome/browser/tracing/trace_event_system_stats_monitor_unittest.cc new file mode 100644 index 0000000..c1d38bb --- /dev/null +++ b/chrome/browser/tracing/trace_event_system_stats_monitor_unittest.cc
@@ -0,0 +1,38 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/tracing/trace_event_system_stats_monitor.h" + +#include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace tracing { + +using TraceSystemStatsMonitorTest = testing::Test; + +TEST_F(TraceSystemStatsMonitorTest, TraceEventSystemStatsMonitor) { + base::test::ScopedTaskEnvironment scoped_task_environment; + + TraceEventSystemStatsMonitor system_stats_monitor; + + EXPECT_TRUE( + base::trace_event::TraceLog::GetInstance()->HasEnabledStateObserver( + &system_stats_monitor)); + + // By default the observer isn't dumping memory profiles. + EXPECT_FALSE(system_stats_monitor.IsTimerRunningForTesting()); + + // Simulate enabling tracing. + system_stats_monitor.StartProfilingForTesting(); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(system_stats_monitor.IsTimerRunningForTesting()); + + // Simulate disabling tracing. + system_stats_monitor.StopProfilingForTesting(); + base::RunLoop().RunUntilIdle(); + EXPECT_FALSE(system_stats_monitor.IsTimerRunningForTesting()); +} + +} // namespace tracing
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index fb2d0dcc..9553724 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -511,7 +511,6 @@ "//services/identity/public/cpp", "//services/metrics/public/cpp:ukm_builders", "//services/network/public/mojom", - "//services/service_manager/runner/common", "//skia", "//storage/browser", "//storage/common", @@ -2504,6 +2503,7 @@ "views/folder_upload_confirmation_view.h", "views/frame/app_menu_button.cc", "views/frame/app_menu_button.h", + "views/frame/app_menu_button_observer.h", "views/frame/browser_frame.cc", "views/frame/browser_frame.h", "views/frame/browser_non_client_frame_view.cc", @@ -2824,7 +2824,6 @@ "views/theme_copying_widget.h", "views/toolbar/app_menu.cc", "views/toolbar/app_menu.h", - "views/toolbar/app_menu_observer.h", "views/toolbar/browser_actions_container.cc", "views/toolbar/browser_actions_container.h", "views/toolbar/browser_app_menu_button.cc",
diff --git a/chrome/browser/ui/cocoa/media_picker/desktop_media_picker_controller.mm b/chrome/browser/ui/cocoa/media_picker/desktop_media_picker_controller.mm index cd8053c..b4864da0 100644 --- a/chrome/browser/ui/cocoa/media_picker/desktop_media_picker_controller.mm +++ b/chrome/browser/ui/cocoa/media_picker/desktop_media_picker_controller.mm
@@ -617,6 +617,9 @@ indexes = [NSIndexSet indexSetWithIndex:index]; [tabBrowser_ selectRowIndexes:indexes byExtendingSelection:NO]; + + // Enable or disable the OK button based on whether we have a selection. + [shareButton_ setEnabled:(index >= 0)]; } #pragma mark NSWindowDelegate
diff --git a/chrome/browser/ui/signin_view_controller.cc b/chrome/browser/ui/signin_view_controller.cc index 841ebae..d38a50c 100644 --- a/chrome/browser/ui/signin_view_controller.cc +++ b/chrome/browser/ui/signin_view_controller.cc
@@ -274,5 +274,5 @@ content::WebContents* SigninViewController::GetModalDialogWebContentsForTesting() { DCHECK(delegate_); - return delegate_->web_contents(); + return delegate_->GetWebContents(); }
diff --git a/chrome/browser/ui/signin_view_controller_delegate.cc b/chrome/browser/ui/signin_view_controller_delegate.cc index 9312b16..ff5e2f60 100644 --- a/chrome/browser/ui/signin_view_controller_delegate.cc +++ b/chrome/browser/ui/signin_view_controller_delegate.cc
@@ -15,95 +15,6 @@ #include "components/web_modal/web_contents_modal_dialog_manager.h" #include "content/public/browser/web_contents.h" -namespace { - -content::WebContents* GetAuthFrameWebContents( - content::WebContents* web_ui_web_contents) { - return signin::GetAuthFrameWebContents(web_ui_web_contents, "signin-frame"); -} - -} // namespace - -SigninViewControllerDelegate::SigninViewControllerDelegate( - SigninViewController* signin_view_controller, - content::WebContents* web_contents, - Browser* browser) - : signin_view_controller_(signin_view_controller), - web_contents_(web_contents), - browser_(browser) { - DCHECK(web_contents_); - DCHECK(browser_); - DCHECK(browser_->tab_strip_model()->GetActiveWebContents()) - << "A tab must be active to present the sign-in modal dialog."; - web_contents_->SetDelegate(this); -} +SigninViewControllerDelegate::SigninViewControllerDelegate() {} SigninViewControllerDelegate::~SigninViewControllerDelegate() {} - -void SigninViewControllerDelegate::AttachDialogManager() { - web_modal::WebContentsModalDialogManager::CreateForWebContents(web_contents_); - web_modal::WebContentsModalDialogManager* manager = - web_modal::WebContentsModalDialogManager::FromWebContents(web_contents_); - manager->SetDelegate(this); -} - -void SigninViewControllerDelegate::CloseModalSignin() { - ResetSigninViewControllerDelegate(); - PerformClose(); -} - -void SigninViewControllerDelegate::PerformNavigation() { - if (CanGoBack(web_contents_)) - GetAuthFrameWebContents(web_contents_)->GetController().GoBack(); - else - CloseModalSignin(); -} - -bool SigninViewControllerDelegate::HandleContextMenu( - const content::ContextMenuParams& params) { - // Discard the context menu - return true; -} - -web_modal::WebContentsModalDialogHost* -SigninViewControllerDelegate::GetWebContentsModalDialogHost() { - return browser()->window()->GetWebContentsModalDialogHost(); -} - -void SigninViewControllerDelegate::ResetSigninViewControllerDelegate() { - if (signin_view_controller_) { - signin_view_controller_->ResetModalSigninDelegate(); - signin_view_controller_ = nullptr; - } -} - -// content::WebContentsDelegate -void SigninViewControllerDelegate::LoadingStateChanged( - content::WebContents* source, - bool to_different_document) { - // The WebUI object can be missing for an error page, per - // https://crbug.com/860409. - if (!source->GetWebUI()) - return; - - if (CanGoBack(source)) { - source->GetWebUI()->CallJavascriptFunctionUnsafe( - "inline.login.showBackButton"); - } else { - source->GetWebUI()->CallJavascriptFunctionUnsafe( - "inline.login.showCloseButton"); - } -} - -bool SigninViewControllerDelegate::HandleKeyboardEvent( - content::WebContents* source, - const content::NativeWebKeyboardEvent& event) { - NOTREACHED(); - return false; -} - -bool SigninViewControllerDelegate::CanGoBack( - content::WebContents* web_ui_web_contents) const { - auto* auth_web_contents = GetAuthFrameWebContents(web_ui_web_contents); - return auth_web_contents && auth_web_contents->GetController().CanGoBack(); -}
diff --git a/chrome/browser/ui/signin_view_controller_delegate.h b/chrome/browser/ui/signin_view_controller_delegate.h index 5bdf013..6df28e9 100644 --- a/chrome/browser/ui/signin_view_controller_delegate.h +++ b/chrome/browser/ui/signin_view_controller_delegate.h
@@ -5,10 +5,7 @@ #ifndef CHROME_BROWSER_UI_SIGNIN_VIEW_CONTROLLER_DELEGATE_H_ #define CHROME_BROWSER_UI_SIGNIN_VIEW_CONTROLLER_DELEGATE_H_ -#include "build/build_config.h" -#include "chrome/browser/ui/chrome_web_modal_dialog_manager_delegate.h" -#include "chrome/browser/ui/profile_chooser_constants.h" -#include "content/public/browser/web_contents_delegate.h" +#include "base/macros.h" class Browser; class SigninViewController; @@ -17,26 +14,19 @@ enum class AccessPoint; } -// Abstract base class to the platform-specific managers of the Signin and Sync +namespace content { +class WebContents; +} + +// Interface to the platform-specific managers of the Signin and Sync // confirmation tab-modal dialogs. This and its platform-specific // implementations are responsible for actually creating and owning the dialogs, // as well as managing the navigation inside them. // Subclasses are responsible for deleting themselves when the window they're // managing closes. -class SigninViewControllerDelegate - : public content::WebContentsDelegate, - public ChromeWebModalDialogManagerDelegate { +class SigninViewControllerDelegate { public: // Returns a platform-specific SigninViewControllerDelegate instance that - // displays the sign in flow. The returned object should delete itself when - // the window it's managing is closed. - static SigninViewControllerDelegate* CreateModalSigninDelegate( - SigninViewController* signin_view_controller, - profiles::BubbleViewMode mode, - Browser* browser, - signin_metrics::AccessPoint access_point); - - // Returns a platform-specific SigninViewControllerDelegate instance that // displays the sync confirmation dialog. The returned object should delete // itself when the window it's managing is closed. static SigninViewControllerDelegate* CreateSyncConfirmationDelegate( @@ -50,71 +40,29 @@ SigninViewController* signin_view_controller, Browser* browser); - // Attaches a dialog manager to this sign-in view controller dialog. - // Should be called by subclasses when a different dialog may need to be - // presented on top of the sign-in dialog. - void AttachDialogManager(); - // Closes the sign-in dialog. Note that this method may destroy this object, // so the caller should no longer use this object after calling this method. - void CloseModalSignin(); + virtual void CloseModalSignin() = 0; // Either navigates back in the signin flow if the history state allows it or // closes the flow otherwise. Note that if view is closed, this method may // destroy this object, so the caller should no longer use this object after // calling this method. - void PerformNavigation(); + virtual void PerformNavigation() = 0; // This will be called by the base class to request a resize of the native // view hosting the content to |height|. |height| is the total height of the // content, in pixels. virtual void ResizeNativeView(int height) = 0; - // content::WebContentsDelegate: - bool HandleContextMenu(const content::ContextMenuParams& params) override; - - // ChromeWebModalDialogManagerDelegate: - web_modal::WebContentsModalDialogHost* GetWebContentsModalDialogHost() - override; - - // WebContents is used for executing javascript in the context of a modal sync - // confirmation dialog. - content::WebContents* web_contents() { return web_contents_; } + // Returns the web contents of the modal dialog. + virtual content::WebContents* GetWebContents() = 0; protected: - SigninViewControllerDelegate(SigninViewController* signin_view_controller, - content::WebContents* web_contents, - Browser* browser); - ~SigninViewControllerDelegate() override; - - Browser* browser() { return browser_; } - - // Notifies the SigninViewController that this instance is being deleted. - void ResetSigninViewControllerDelegate(); - - // content::WebContentsDelegate - void LoadingStateChanged(content::WebContents* source, - bool to_different_document) override; - - // Subclasses must override this method to correctly handle accelerators. - bool HandleKeyboardEvent( - content::WebContents* source, - const content::NativeWebKeyboardEvent& event) override; - - // This will be called by this base class when the tab-modal window must be - // closed. This should close the platform-specific window that is currently - // showing the sign in flow or the sync confirmation dialog. Note that this - // method may destroy this object, so the caller should no longer use this - // object after calling this method. - virtual void PerformClose() = 0; + SigninViewControllerDelegate(); + virtual ~SigninViewControllerDelegate(); private: - bool CanGoBack(content::WebContents* web_ui_web_contents) const; - - SigninViewController* signin_view_controller_; // Not owned. - content::WebContents* const web_contents_; // Not owned. - Browser* const browser_; // Not owned. - DISALLOW_COPY_AND_ASSIGN(SigninViewControllerDelegate); };
diff --git a/chrome/browser/ui/views/chrome_browser_main_extra_parts_views.cc b/chrome/browser/ui/views/chrome_browser_main_extra_parts_views.cc index a9f3496a..743ac2f 100644 --- a/chrome/browser/ui/views/chrome_browser_main_extra_parts_views.cc +++ b/chrome/browser/ui/views/chrome_browser_main_extra_parts_views.cc
@@ -26,7 +26,6 @@ #include "content/public/browser/browser_thread.h" #include "content/public/common/service_manager_connection.h" #include "services/service_manager/public/cpp/connector.h" -#include "services/service_manager/runner/common/client_util.h" #include "services/ws/public/cpp/gpu/gpu.h" // nogncheck #include "services/ws/public/mojom/constants.mojom.h" #include "ui/display/screen.h"
diff --git a/chrome/browser/ui/views/feature_promos/reopen_tab_promo_controller.cc b/chrome/browser/ui/views/feature_promos/reopen_tab_promo_controller.cc index 693b40f..12f81403 100644 --- a/chrome/browser/ui/views/feature_promos/reopen_tab_promo_controller.cc +++ b/chrome/browser/ui/views/feature_promos/reopen_tab_promo_controller.cc
@@ -21,26 +21,7 @@ namespace { -// Last step of the flow completed by the user before dismissal (whether by -// successful completion of the flow, timing out, or clicking away.). This is -// used for an UMA histogram. -// -// These values are persisted to logs. Entries should not be renumbered and -// numeric values should never be reused. -enum class ReopenTabPromoStepAtDismissal { - // The promo bubble was shown, but the menu was not opened; i.e. the bubble - // timed out. - kBubbleShown = 0, - // The menu was opened, but the user clicked away without opening the last - // closed tab. - kMenuOpened = 1, - // The last closed tab item was clicked. The promo was successful. - kTabReopened = 2, - - kMaxValue = kTabReopened, -}; - -const char kReopenTabPromoDismissedAtHistogram[] = +constexpr char kReopenTabPromoDismissedAtHistogram[] = "InProductHelp.Promos.IPH_ReopenTab.DismissedAt"; } // namespace @@ -53,13 +34,12 @@ void ReopenTabPromoController::ShowPromo() { // This shouldn't be called more than once. Check that state is fresh. - DCHECK(!tab_reopened_before_app_menu_closed_); + DCHECK_EQ(StepAtDismissal::kBubbleShown, promo_step_); // Here, we start the promo display. We highlight the app menu button and open // the promo bubble. - BrowserAppMenuButton* app_menu_button = - browser_view_->toolbar()->app_menu_button(); - app_menu_button->AddMenuListener(this); + auto* app_menu_button = browser_view_->toolbar()->app_menu_button(); + app_menu_button->AddObserver(this); app_menu_button->SetPromoFeature(InProductHelpFeature::kReopenTab); promo_bubble_ = FeaturePromoBubbleView::CreateOwned( @@ -73,54 +53,39 @@ iph_service_->TabReopened(); if (command_id == AppMenuModel::kMinRecentTabsCommandId) { - DCHECK(!tab_reopened_before_app_menu_closed_); - UMA_HISTOGRAM_ENUMERATION(kReopenTabPromoDismissedAtHistogram, - ReopenTabPromoStepAtDismissal::kTabReopened); - tab_reopened_before_app_menu_closed_ = true; + DCHECK_EQ(StepAtDismissal::kBubbleShown, promo_step_); + promo_step_ = StepAtDismissal::kTabReopened; } } -void ReopenTabPromoController::OnMenuOpened() { - // The user followed the promo and opened the menu. First, we close the promo - // bubble since it doesn't automatically close on click. Then, we highlight - // the history item and observe for the history submenu opening. - promo_bubble_->GetWidget()->Close(); - - auto* app_menu_button = browser_view_->toolbar()->app_menu_button(); - app_menu_button->RemoveMenuListener(this); - - app_menu_button->app_menu()->AddObserver(this); -} - void ReopenTabPromoController::OnWidgetDestroying(views::Widget* widget) { DCHECK(promo_bubble_); promo_bubble_ = nullptr; - // If the menu isn't showing, that means the promo bubble timed out. We should - // notify our IPH service that help was dismissed. - auto* app_menu_button = browser_view_->toolbar()->app_menu_button(); - if (!app_menu_button->IsMenuShowing()) { - UMA_HISTOGRAM_ENUMERATION(kReopenTabPromoDismissedAtHistogram, - ReopenTabPromoStepAtDismissal::kBubbleShown); + // If the menu isn't showing, that means the promo bubble timed out. + if (!browser_view_->toolbar()->app_menu_button()->IsMenuShowing()) + PromoEnded(); +} - app_menu_button->RemoveMenuListener(this); - app_menu_button->SetPromoFeature(base::nullopt); - iph_service_->HelpDismissed(); - } +void ReopenTabPromoController::AppMenuShown() { + // Close the promo bubble since it doesn't automatically close on click. + promo_bubble_->GetWidget()->Close(); + + promo_step_ = StepAtDismissal::kMenuOpened; } void ReopenTabPromoController::AppMenuClosed() { - // The menu was opened then closed, whether by clicking away or by clicking a - // menu item. We notify the service regardless of whether IPH succeeded. - // Success is determined by whether the reopen tab event was sent. - if (!tab_reopened_before_app_menu_closed_) { - UMA_HISTOGRAM_ENUMERATION(kReopenTabPromoDismissedAtHistogram, - ReopenTabPromoStepAtDismissal::kMenuOpened); - } + PromoEnded(); +} +void ReopenTabPromoController::PromoEnded() { + UMA_HISTOGRAM_ENUMERATION(kReopenTabPromoDismissedAtHistogram, promo_step_); + + // We notify the service regardless of whether IPH succeeded. Success is + // determined by whether the reopen tab event was sent. iph_service_->HelpDismissed(); auto* app_menu_button = browser_view_->toolbar()->app_menu_button(); app_menu_button->SetPromoFeature(base::nullopt); - app_menu_button->app_menu()->RemoveObserver(this); + app_menu_button->RemoveObserver(this); }
diff --git a/chrome/browser/ui/views/feature_promos/reopen_tab_promo_controller.h b/chrome/browser/ui/views/feature_promos/reopen_tab_promo_controller.h index 170a6a3..f445e94 100644 --- a/chrome/browser/ui/views/feature_promos/reopen_tab_promo_controller.h +++ b/chrome/browser/ui/views/feature_promos/reopen_tab_promo_controller.h
@@ -5,8 +5,7 @@ #ifndef CHROME_BROWSER_UI_VIEWS_FEATURE_PROMOS_REOPEN_TAB_PROMO_CONTROLLER_H_ #define CHROME_BROWSER_UI_VIEWS_FEATURE_PROMOS_REOPEN_TAB_PROMO_CONTROLLER_H_ -#include "chrome/browser/ui/views/toolbar/app_menu_observer.h" -#include "ui/views/controls/menu/menu_listener.h" +#include "chrome/browser/ui/views/frame/app_menu_button_observer.h" #include "ui/views/widget/widget_observer.h" class BrowserView; @@ -16,8 +15,7 @@ // Handles display of the reopen tab in-product help promo, including showing // the promo bubble and highlighting the appropriate app menu items. Notifies // the |ReopenTabInProductHelp| service when the promo is finished. -class ReopenTabPromoController : public AppMenuObserver, - public views::MenuListener, +class ReopenTabPromoController : public AppMenuButtonObserver, public views::WidgetObserver { public: explicit ReopenTabPromoController(BrowserView* browser_view); @@ -31,23 +29,43 @@ void OnTabReopened(int command_id); private: - // views::MenuListener: - void OnMenuOpened() override; + // Last step of the flow completed by the user before dismissal (whether by + // successful completion of the flow, timing out, or clicking away.). This is + // used for an UMA histogram. + // + // These values are persisted to logs. Entries should not be renumbered and + // numeric values should never be reused. + enum class StepAtDismissal { + // The promo bubble was shown, but the menu was not opened; i.e. the bubble + // timed out. + kBubbleShown = 0, + // The menu was opened, but the user clicked away without opening the last + // closed tab. + kMenuOpened = 1, + // The last closed tab item was clicked. The promo was successful. + kTabReopened = 2, + + kMaxValue = kTabReopened, + }; // views::WidgetObserver: void OnWidgetDestroying(views::Widget* widget) override; - // AppMenuObserver: + // AppMenuButtonObserver: + void AppMenuShown() override; void AppMenuClosed() override; + // Called when the promo flow ends, either because the bubble timed out, or + // because the user did something to close the menu. + void PromoEnded(); + ReopenTabInProductHelp* const iph_service_; BrowserView* const browser_view_; FeaturePromoBubbleView* promo_bubble_ = nullptr; - // Flag used to determine whether the promo completed successfully or not upon - // the app menu closing. This is set to true if the user reopened the most - // recently closed tab. - bool tab_reopened_before_app_menu_closed_ = false; + // The promo stage that has been reached, logged to a histogram when the promo + // flow ends. + StepAtDismissal promo_step_ = StepAtDismissal::kBubbleShown; DISALLOW_COPY_AND_ASSIGN(ReopenTabPromoController); };
diff --git a/chrome/browser/ui/views/frame/app_menu_button.cc b/chrome/browser/ui/views/frame/app_menu_button.cc index a302144..b7baf66 100644 --- a/chrome/browser/ui/views/frame/app_menu_button.cc +++ b/chrome/browser/ui/views/frame/app_menu_button.cc
@@ -7,9 +7,9 @@ #include <utility> #include "chrome/browser/ui/toolbar/app_menu_model.h" +#include "chrome/browser/ui/views/frame/app_menu_button_observer.h" #include "chrome/browser/ui/views/toolbar/app_menu.h" #include "chrome/browser/ui/views/toolbar/toolbar_ink_drop_util.h" -#include "ui/views/controls/menu/menu_listener.h" AppMenuButton::AppMenuButton(views::MenuButtonListener* menu_button_listener) : views::MenuButton(base::string16(), menu_button_listener) {} @@ -20,28 +20,33 @@ return GetToolbarInkDropBaseColor(this); } +void AppMenuButton::AddObserver(AppMenuButtonObserver* observer) { + observer_list_.AddObserver(observer); +} + +void AppMenuButton::RemoveObserver(AppMenuButtonObserver* observer) { + observer_list_.RemoveObserver(observer); +} + void AppMenuButton::CloseMenu() { if (menu_) menu_->CloseMenu(); menu_.reset(); } +void AppMenuButton::OnMenuClosed() { + for (AppMenuButtonObserver& observer : observer_list_) + observer.AppMenuClosed(); +} + bool AppMenuButton::IsMenuShowing() const { return menu_ && menu_->IsShowing(); } -void AppMenuButton::AddMenuListener(views::MenuListener* listener) { - menu_listeners_.AddObserver(listener); -} - -void AppMenuButton::RemoveMenuListener(views::MenuListener* listener) { - menu_listeners_.RemoveObserver(listener); -} - -void AppMenuButton::InitMenu(std::unique_ptr<AppMenuModel> menu_model, - Browser* browser, - int run_flags, - bool alert_reopen_tab_items) { +void AppMenuButton::RunMenu(std::unique_ptr<AppMenuModel> menu_model, + Browser* browser, + int run_flags, + bool alert_reopen_tab_items) { // |menu_| must be reset before |menu_model_| is destroyed, as per the comment // in the class declaration. menu_.reset(); @@ -50,6 +55,8 @@ menu_ = std::make_unique<AppMenu>(browser, run_flags, alert_reopen_tab_items); menu_->Init(menu_model_.get()); - for (views::MenuListener& observer : menu_listeners_) - observer.OnMenuOpened(); + menu_->RunMenu(this); + + for (AppMenuButtonObserver& observer : observer_list_) + observer.AppMenuShown(); }
diff --git a/chrome/browser/ui/views/frame/app_menu_button.h b/chrome/browser/ui/views/frame/app_menu_button.h index ba51fac..dde1c17 100644 --- a/chrome/browser/ui/views/frame/app_menu_button.h +++ b/chrome/browser/ui/views/frame/app_menu_button.h
@@ -7,15 +7,16 @@ #include <memory> +#include "base/observer_list.h" #include "ui/views/controls/button/menu_button.h" class AppMenu; +class AppMenuButtonObserver; class AppMenuModel; class Browser; namespace views { class MenuButtonListener; -class MenuListener; } // namespace views // The app menu button lives in the top right of browser windows. It shows three @@ -31,30 +32,27 @@ // views::MenuButton: SkColor GetInkDropBaseColor() const override; + void AddObserver(AppMenuButtonObserver* observer); + void RemoveObserver(AppMenuButtonObserver* observer); + // Closes the app menu, if it's open. void CloseMenu(); + // Called by the app menu when it closes. + void OnMenuClosed(); + // Whether the app menu is currently showing. bool IsMenuShowing() const; - // Adds a listener to receive a callback when the menu opens. - void AddMenuListener(views::MenuListener* listener); - - // Removes a menu listener. - void RemoveMenuListener(views::MenuListener* listener); - AppMenu* app_menu() { return menu_.get(); } protected: - // Create (but don't show) the menu. |menu_model| should be a newly created - // AppMenuModel. The other params are forwarded to the created AppMenu. - void InitMenu(std::unique_ptr<AppMenuModel> menu_model, - Browser* browser, - int run_flags, - bool alert_reopen_tab_items); - - AppMenu* menu() { return menu_.get(); } - const AppMenu* menu() const { return menu_.get(); } + // Show the menu. |menu_model| should be a newly created AppMenuModel. The + // other params are forwarded to the created AppMenu. + void RunMenu(std::unique_ptr<AppMenuModel> menu_model, + Browser* browser, + int run_flags, + bool alert_reopen_tab_items); private: // App model and menu. @@ -65,8 +63,7 @@ std::unique_ptr<AppMenuModel> menu_model_; std::unique_ptr<AppMenu> menu_; - // Listeners to call when the menu opens. - base::ObserverList<views::MenuListener>::Unchecked menu_listeners_; + base::ObserverList<AppMenuButtonObserver>::Unchecked observer_list_; DISALLOW_COPY_AND_ASSIGN(AppMenuButton); };
diff --git a/chrome/browser/ui/views/frame/app_menu_button_observer.h b/chrome/browser/ui/views/frame/app_menu_button_observer.h new file mode 100644 index 0000000..e8dfa19 --- /dev/null +++ b/chrome/browser/ui/views/frame/app_menu_button_observer.h
@@ -0,0 +1,20 @@ +// 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. + +#ifndef CHROME_BROWSER_UI_VIEWS_FRAME_APP_MENU_BUTTON_OBSERVER_H_ +#define CHROME_BROWSER_UI_VIEWS_FRAME_APP_MENU_BUTTON_OBSERVER_H_ + +class AppMenuButtonObserver { + public: + // Called after AppMenu::RunMenu(). + virtual void AppMenuShown() {} + + // Called during AppMenu::OnMenuClosed(). + virtual void AppMenuClosed() {} + + protected: + virtual ~AppMenuButtonObserver() = default; +}; + +#endif // CHROME_BROWSER_UI_VIEWS_FRAME_APP_MENU_BUTTON_OBSERVER_H_
diff --git a/chrome/browser/ui/views/frame/hosted_app_menu_button.cc b/chrome/browser/ui/views/frame/hosted_app_menu_button.cc index 9f45c9eb..8290fe9 100644 --- a/chrome/browser/ui/views/frame/hosted_app_menu_button.cc +++ b/chrome/browser/ui/views/frame/hosted_app_menu_button.cc
@@ -70,10 +70,8 @@ const gfx::Point& point, const ui::Event* event) { Browser* browser = browser_view_->browser(); - InitMenu(std::make_unique<HostedAppMenuModel>(browser_view_, browser), - browser, AppMenu::NO_FLAGS, false); - - menu()->RunMenu(this); + RunMenu(std::make_unique<HostedAppMenuModel>(browser_view_, browser), browser, + AppMenu::NO_FLAGS, false); // Add UMA for how many times the hosted app menu button are clicked. base::RecordAction(
diff --git a/chrome/browser/ui/views/keyboard_access_browsertest.cc b/chrome/browser/ui/views/keyboard_access_browsertest.cc index d6bf791..2a64915 100644 --- a/chrome/browser/ui/views/keyboard_access_browsertest.cc +++ b/chrome/browser/ui/views/keyboard_access_browsertest.cc
@@ -20,7 +20,9 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/browser/ui/views/frame/app_menu_button_observer.h" #include "chrome/browser/ui/views/frame/browser_view.h" +#include "chrome/browser/ui/views/toolbar/app_menu.h" #include "chrome/browser/ui/views/toolbar/browser_app_menu_button.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" #include "chrome/test/base/in_process_browser_test.h" @@ -29,7 +31,6 @@ #include "ui/base/test/ui_controls.h" #include "ui/events/event_constants.h" #include "ui/events/keycodes/keyboard_codes.h" -#include "ui/views/controls/menu/menu_listener.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" @@ -67,7 +68,7 @@ } private: - // Inherited from FocusChangeListener + // views::FocusChangeListener: void OnWillChangeFocus(views::View* focused_before, views::View* focused_now) override {} @@ -86,45 +87,38 @@ DISALLOW_COPY_AND_ASSIGN(ViewFocusChangeWaiter); }; -class SendKeysMenuListener : public views::MenuListener { +class SendKeysMenuListener : public AppMenuButtonObserver { public: SendKeysMenuListener(AppMenuButton* app_menu_button, Browser* browser, bool test_dismiss_menu) - : app_menu_button_(app_menu_button), - browser_(browser), + : browser_(browser), menu_open_count_(0), test_dismiss_menu_(test_dismiss_menu) { - app_menu_button_->AddMenuListener(this); + observer_.Add(app_menu_button); } - ~SendKeysMenuListener() override { - if (test_dismiss_menu_) - app_menu_button_->RemoveMenuListener(this); - } + ~SendKeysMenuListener() override = default; - int menu_open_count() const { - return menu_open_count_; - } - - private: - // Overridden from views::MenuListener: - void OnMenuOpened() override { + // AppMenuButtonObserver: + void AppMenuShown() override { menu_open_count_++; - if (!test_dismiss_menu_) { - app_menu_button_->RemoveMenuListener(this); - // Press DOWN to select the first item, then RETURN to select it. - SendKeyPress(browser_, ui::VKEY_DOWN); - SendKeyPress(browser_, ui::VKEY_RETURN); - } else { + if (test_dismiss_menu_) { SendKeyPress(browser_, ui::VKEY_ESCAPE); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated(), base::TimeDelta::FromMilliseconds(200)); + } else { + observer_.RemoveAll(); + // Press DOWN to select the first item, then RETURN to select it. + SendKeyPress(browser_, ui::VKEY_DOWN); + SendKeyPress(browser_, ui::VKEY_RETURN); } } - AppMenuButton* app_menu_button_; + int menu_open_count() const { return menu_open_count_; } + + private: Browser* browser_; // Keeps track of the number of times the menu was opened. int menu_open_count_; @@ -132,6 +126,8 @@ // we dismiss it by sending the ESC key. bool test_dismiss_menu_; + ScopedObserver<AppMenuButton, AppMenuButtonObserver> observer_{this}; + DISALLOW_COPY_AND_ASSIGN(SendKeysMenuListener); };
diff --git a/chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.cc b/chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.cc index a05c4d04..cd4002b 100644 --- a/chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.cc +++ b/chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.cc
@@ -23,6 +23,17 @@ #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/widget.h" +#include "chrome/browser/ui/webui/signin/signin_utils.h" + +namespace { + +content::WebContents* GetAuthFrameWebContents( + content::WebContents* web_ui_web_contents) { + return signin::GetAuthFrameWebContents(web_ui_web_contents, "signin-frame"); +} + +} // namespace + namespace { const int kModalDialogWidth = 448; @@ -54,12 +65,18 @@ Browser* browser, ui::ModalType dialog_modal_type, bool wait_for_size) - : SigninViewControllerDelegate(signin_view_controller, - content_view->GetWebContents(), - browser), + : signin_view_controller_(signin_view_controller), + web_contents_(content_view->GetWebContents()), + browser_(browser), content_view_(content_view.release()), modal_signin_widget_(nullptr), dialog_modal_type_(dialog_modal_type) { + DCHECK(web_contents_); + DCHECK(browser_); + DCHECK(browser_->tab_strip_model()->GetActiveWebContents()) + << "A tab must be active to present the sign-in modal dialog."; + web_contents_->SetDelegate(this); + DCHECK(dialog_modal_type == ui::MODAL_TYPE_CHILD || dialog_modal_type == ui::MODAL_TYPE_WINDOW) << "Unsupported dialog modal type " << dialog_modal_type; @@ -120,16 +137,20 @@ } } -bool SigninViewControllerDelegateViews::HandleKeyboardEvent( - content::WebContents* source, - const content::NativeWebKeyboardEvent& event) { - // If this is a MODAL_TYPE_CHILD, then GetFocusManager() will return the focus - // manager of the parent window, which has registered accelerators, and the - // accelerators will fire. If this is a MODAL_TYPE_WINDOW, then this will have - // no effect, since no accelerators have been registered for this standalone - // window. - return unhandled_keyboard_event_handler_.HandleKeyboardEvent( - event, GetFocusManager()); +content::WebContents* SigninViewControllerDelegateViews::GetWebContents() { + return web_contents_; +} + +void SigninViewControllerDelegateViews::PerformNavigation() { + if (CanGoBack(web_contents_)) + GetAuthFrameWebContents(web_contents_)->GetController().GoBack(); + else + CloseModalSignin(); +} + +void SigninViewControllerDelegateViews::CloseModalSignin() { + ResetSigninViewControllerDelegate(); + PerformClose(); } void SigninViewControllerDelegateViews::DisplayModal() { @@ -161,40 +182,40 @@ content_view_->RequestFocus(); } -#if defined(OS_CHROMEOS) -// static -std::unique_ptr<views::WebView> -SigninViewControllerDelegateViews::CreateGaiaWebView( - content::WebContentsDelegate* delegate, - profiles::BubbleViewMode mode, - Browser* browser, - signin_metrics::AccessPoint access_point) { - GURL url = signin::GetEmbeddedSigninURLFromBubbleViewMode(browser->profile(), - mode, access_point); - - constexpr int kFixedGaiaViewHeight = 612; - int max_height = browser - ->window() - ->GetWebContentsModalDialogHost() - ->GetMaximumDialogSize().height(); - // Adds Gaia signin webview. - const gfx::Size pref_size(kModalDialogWidth, - std::min(kFixedGaiaViewHeight, max_height)); - views::WebView* web_view = new views::WebView(browser->profile()); - web_view->LoadInitialURL(url); - - if (delegate) - web_view->GetWebContents()->SetDelegate(delegate); - - web_view->SetPreferredSize(pref_size); - content::RenderWidgetHostView* rwhv = - web_view->GetWebContents()->GetRenderWidgetHostView(); - if (rwhv) - rwhv->SetBackgroundColor(profiles::kAvatarBubbleGaiaBackgroundColor); - - return std::unique_ptr<views::WebView>(web_view); +bool SigninViewControllerDelegateViews::HandleKeyboardEvent( + content::WebContents* source, + const content::NativeWebKeyboardEvent& event) { + // If this is a MODAL_TYPE_CHILD, then GetFocusManager() will return the focus + // manager of the parent window, which has registered accelerators, and the + // accelerators will fire. If this is a MODAL_TYPE_WINDOW, then this will have + // no effect, since no accelerators have been registered for this standalone + // window. + return unhandled_keyboard_event_handler_.HandleKeyboardEvent( + event, GetFocusManager()); } -#endif + +bool SigninViewControllerDelegateViews::HandleContextMenu( + const content::ContextMenuParams& params) { + // Discard the context menu + return true; +} + +void SigninViewControllerDelegateViews::LoadingStateChanged( + content::WebContents* source, + bool to_different_document) { + // The WebUI object can be missing for an error page, per + // https://crbug.com/860409. + if (!source->GetWebUI()) + return; + + if (CanGoBack(source)) { + source->GetWebUI()->CallJavascriptFunctionUnsafe( + "inline.login.showBackButton"); + } else { + source->GetWebUI()->CallJavascriptFunctionUnsafe( + "inline.login.showCloseButton"); + } +} std::unique_ptr<views::WebView> SigninViewControllerDelegateViews::CreateSyncConfirmationWebView( @@ -238,20 +259,27 @@ return std::unique_ptr<views::WebView>(web_view); } -#if defined(OS_CHROMEOS) -SigninViewControllerDelegate* -SigninViewControllerDelegate::CreateModalSigninDelegate( - SigninViewController* signin_view_controller, - profiles::BubbleViewMode mode, - Browser* browser, - signin_metrics::AccessPoint access_point) { - return new SigninViewControllerDelegateViews( - signin_view_controller, - SigninViewControllerDelegateViews::CreateGaiaWebView( - nullptr, mode, browser, access_point), - browser, ui::MODAL_TYPE_CHILD, false); +web_modal::WebContentsModalDialogHost* +SigninViewControllerDelegateViews::GetWebContentsModalDialogHost() { + return browser()->window()->GetWebContentsModalDialogHost(); } -#endif + +void SigninViewControllerDelegateViews::ResetSigninViewControllerDelegate() { + if (signin_view_controller_) { + signin_view_controller_->ResetModalSigninDelegate(); + signin_view_controller_ = nullptr; + } +} + +bool SigninViewControllerDelegateViews::CanGoBack( + content::WebContents* web_ui_web_contents) const { + auto* auth_web_contents = GetAuthFrameWebContents(web_ui_web_contents); + return auth_web_contents && auth_web_contents->GetController().CanGoBack(); +} + +// -------------------------------------------------------------------- +// SigninViewControllerDelegate static methods +// -------------------------------------------------------------------- SigninViewControllerDelegate* SigninViewControllerDelegate::CreateSyncConfirmationDelegate(
diff --git a/chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.h b/chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.h index ffa6ab6..d2e43be 100644 --- a/chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.h +++ b/chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.h
@@ -6,21 +6,17 @@ #define CHROME_BROWSER_UI_VIEWS_PROFILES_SIGNIN_VIEW_CONTROLLER_DELEGATE_VIEWS_H_ #include "base/macros.h" +#include "chrome/browser/ui/chrome_web_modal_dialog_manager_delegate.h" #include "chrome/browser/ui/profile_chooser_constants.h" #include "chrome/browser/ui/signin_view_controller_delegate.h" +#include "content/public/browser/web_contents_delegate.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/window/dialog_delegate.h" -class Browser; - namespace content { class WebContentsDelegate; } -namespace signin_metrics { -enum class AccessPoint; -} - namespace views { class WebView; } @@ -29,8 +25,11 @@ // managing the Signin and Sync Confirmation tab-modal dialogs. // Instances of this class delete themselves when the window they're managing // closes (in the DeleteDelegate callback). -class SigninViewControllerDelegateViews : public views::DialogDelegateView, - public SigninViewControllerDelegate { +class SigninViewControllerDelegateViews + : public views::DialogDelegateView, + public SigninViewControllerDelegate, + public content::WebContentsDelegate, + public ChromeWebModalDialogManagerDelegate { public: static std::unique_ptr<views::WebView> CreateSyncConfirmationWebView( @@ -48,20 +47,27 @@ bool ShouldShowCloseButton() const override; int GetDialogButtons() const override; + // SigninViewControllerDelegate: + void CloseModalSignin() override; + void PerformNavigation() override; + void ResizeNativeView(int height) override; + content::WebContents* GetWebContents() override; + + // content::WebContentsDelegate: + void LoadingStateChanged(content::WebContents* source, + bool to_different_document) override; + bool HandleContextMenu(const content::ContextMenuParams& params) override; + bool HandleKeyboardEvent( + content::WebContents* source, + const content::NativeWebKeyboardEvent& event) override; + + // ChromeWebModalDialogManagerDelegate: + web_modal::WebContentsModalDialogHost* GetWebContentsModalDialogHost() + override; + private: friend SigninViewControllerDelegate; -#if defined(OS_CHROMEOS) - // Creates the web view that contains the signin flow in |mode| using - // |profile| as the web content's profile, then sets |delegate| as the created - // web content's delegate. - static std::unique_ptr<views::WebView> CreateGaiaWebView( - content::WebContentsDelegate* delegate, - profiles::BubbleViewMode mode, - Browser* browser, - signin_metrics::AccessPoint access_point); -#endif - // Creates and displays a constrained window containing |web_contents|. If // |wait_for_size| is true, the delegate will wait for ResizeNativeView() to // be called by the base class before displaying the constrained window. @@ -73,16 +79,6 @@ bool wait_for_size); ~SigninViewControllerDelegateViews() override; - void PerformClose() override; - void ResizeNativeView(int height) override; - - // content::WebContentsDelegate: - bool HandleKeyboardEvent( - content::WebContents* source, - const content::NativeWebKeyboardEvent& event) override; - - void DisplayModal(); - // Creates a WebView for a dialog with the specified URL. static std::unique_ptr<views::WebView> CreateDialogWebView( Browser* browser, @@ -90,6 +86,25 @@ int dialog_height, base::Optional<int> dialog_width); + // Notifies the SigninViewController that this instance is being deleted. + void ResetSigninViewControllerDelegate(); + + // Displays the modal dialog. + void DisplayModal(); + + // Returns true if |web_ui_web_contents| can go back. + bool CanGoBack(content::WebContents* web_ui_web_contents) const; + + // Close the platform-specific dialog window. Note that this + // method may destroy this object, so the caller should no longer use this + // object after calling this method. + void PerformClose(); + + Browser* browser() { return browser_; } + + SigninViewController* signin_view_controller_; // Not owned. + content::WebContents* const web_contents_; // Not owned. + Browser* const browser_; // Not owned. views::WebView* content_view_; views::Widget* modal_signin_widget_; // Not owned. ui::ModalType dialog_modal_type_;
diff --git a/chrome/browser/ui/views/toolbar/app_menu.cc b/chrome/browser/ui/views/toolbar/app_menu.cc index 19c480c..abdd422 100644 --- a/chrome/browser/ui/views/toolbar/app_menu.cc +++ b/chrome/browser/ui/views/toolbar/app_menu.cc
@@ -29,7 +29,9 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/toolbar/app_menu_model.h" #include "chrome/browser/ui/views/bookmarks/bookmark_menu_delegate.h" -#include "chrome/browser/ui/views/toolbar/app_menu_observer.h" +#include "chrome/browser/ui/views/frame/app_menu_button.h" +#include "chrome/browser/ui/views/frame/browser_view.h" +#include "chrome/browser/ui/views/frame/toolbar_button_provider.h" #include "chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.h" #include "chrome/grit/generated_resources.h" #include "chrome/grit/theme_resources.h" @@ -813,9 +815,6 @@ menu_runner_->RunMenuAt(host->GetWidget(), host, host->GetAnchorBoundsInScreen(), views::MENU_ANCHOR_TOPRIGHT, ui::MENU_SOURCE_NONE); - - for (AppMenuObserver& observer : observer_list_) - observer.AppMenuShown(); } void AppMenu::CloseMenu() { @@ -827,14 +826,6 @@ return menu_runner_.get() && menu_runner_->IsRunning(); } -void AppMenu::AddObserver(AppMenuObserver* observer) { - observer_list_.AddObserver(observer); -} - -void AppMenu::RemoveObserver(AppMenuObserver* observer) { - observer_list_.RemoveObserver(observer); -} - void AppMenu::GetLabelStyle(int command_id, LabelStyle* style) const { if (IsRecentTabsCommand(command_id)) { const gfx::FontList* font_list = @@ -1036,8 +1027,8 @@ } void AppMenu::OnMenuClosed(views::MenuItemView* menu) { - for (AppMenuObserver& observer : observer_list_) - observer.AppMenuClosed(); + auto* browser_view = BrowserView::GetBrowserViewForBrowser(browser_); + browser_view->toolbar_button_provider()->GetAppMenuButton()->OnMenuClosed(); if (bookmark_menu_delegate_.get()) { BookmarkModel* model = @@ -1045,6 +1036,7 @@ if (model) model->RemoveObserver(this); } + if (selected_menu_model_) selected_menu_model_->ActivatedAt(selected_index_); } @@ -1105,8 +1097,8 @@ switch (model->GetCommandIdAt(i)) { case IDC_EXTENSIONS_OVERFLOW_MENU: { - std::unique_ptr<ExtensionToolbarMenuView> extension_toolbar( - new ExtensionToolbarMenuView(browser_, this, item)); + auto extension_toolbar = + std::make_unique<ExtensionToolbarMenuView>(browser_, item); for (int i = 0; i < extension_toolbar->contents()->child_count(); ++i) { View* action_view = extension_toolbar->contents()->child_at(i); action_view->SetBackground(std::make_unique<InMenuButtonBackground>(
diff --git a/chrome/browser/ui/views/toolbar/app_menu.h b/chrome/browser/ui/views/toolbar/app_menu.h index 08545ad..91c883c 100644 --- a/chrome/browser/ui/views/toolbar/app_menu.h +++ b/chrome/browser/ui/views/toolbar/app_menu.h
@@ -11,7 +11,6 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "base/observer_list.h" #include "base/time/time.h" #include "base/timer/elapsed_timer.h" #include "components/bookmarks/browser/base_bookmark_model_observer.h" @@ -20,7 +19,6 @@ #include "ui/base/models/menu_model.h" #include "ui/views/controls/menu/menu_delegate.h" -class AppMenuObserver; class BookmarkMenuDelegate; class Browser; class ExtensionToolbarMenuView; @@ -61,9 +59,6 @@ views::MenuItemView* root_menu_item() { return root_; } - void AddObserver(AppMenuObserver* observer); - void RemoveObserver(AppMenuObserver* observer); - // MenuDelegate overrides: void GetLabelStyle(int command_id, LabelStyle* style) const override; base::string16 GetTooltipText(int command_id, @@ -199,8 +194,6 @@ // Whether to show items relating to reopening the last-closed tab as alerted. const bool alert_reopen_tab_items_; - base::ObserverList<AppMenuObserver>::Unchecked observer_list_; - // Records the time from when menu opens to when the user selects a menu item. base::ElapsedTimer menu_opened_timer_;
diff --git a/chrome/browser/ui/views/toolbar/app_menu_observer.h b/chrome/browser/ui/views/toolbar/app_menu_observer.h deleted file mode 100644 index 32d1a75..0000000 --- a/chrome/browser/ui/views/toolbar/app_menu_observer.h +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_VIEWS_TOOLBAR_APP_MENU_OBSERVER_H_ -#define CHROME_BROWSER_UI_VIEWS_TOOLBAR_APP_MENU_OBSERVER_H_ - -class AppMenuObserver { - public: - virtual void AppMenuClosed() {} - - // Called after AppMenu::RunMenu(). - virtual void AppMenuShown() {} - - protected: - virtual ~AppMenuObserver() {} -}; - -#endif // CHROME_BROWSER_UI_VIEWS_TOOLBAR_APP_MENU_OBSERVER_H_
diff --git a/chrome/browser/ui/views/toolbar/browser_app_menu_button.cc b/chrome/browser/ui/views/toolbar/browser_app_menu_button.cc index b68f632b..af922e1 100644 --- a/chrome/browser/ui/views/toolbar/browser_app_menu_button.cc +++ b/chrome/browser/ui/views/toolbar/browser_app_menu_button.cc
@@ -132,15 +132,13 @@ #if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) alert_reopen_tab_items = promo_feature_ == InProductHelpFeature::kReopenTab; #endif - InitMenu( + base::TimeTicks menu_open_time = base::TimeTicks::Now(); + RunMenu( std::make_unique<AppMenuModel>(toolbar_view_, browser, toolbar_view_->app_menu_icon_controller()), browser, for_drop ? AppMenu::FOR_DROP : AppMenu::NO_FLAGS, alert_reopen_tab_items); - base::TimeTicks menu_open_time = base::TimeTicks::Now(); - menu()->RunMenu(this); - if (!for_drop) { // Record the time-to-action for the menu. We don't record in the case of a // drag-and-drop command because menus opened for drag-and-drop don't block
diff --git a/chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.cc b/chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.cc index d0ebf139..7419243 100644 --- a/chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.cc +++ b/chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.cc
@@ -10,6 +10,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "chrome/browser/ui/toolbar/toolbar_actions_bar.h" +#include "chrome/browser/ui/views/frame/app_menu_button.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/toolbar/app_menu.h" #include "chrome/browser/ui/views/toolbar/browser_actions_container.h" @@ -27,21 +28,18 @@ ExtensionToolbarMenuView::ExtensionToolbarMenuView( Browser* browser, - AppMenu* app_menu, views::MenuItemView* menu_item) - : browser_(browser), - app_menu_(app_menu), - menu_item_(menu_item), - toolbar_actions_bar_observer_(this), - app_menu_observer_(this), - weak_factory_(this) { + : browser_(browser), menu_item_(menu_item) { + auto* browser_view = BrowserView::GetBrowserViewForBrowser(browser_); + auto* toolbar_button_provider = browser_view->toolbar_button_provider(); + auto* app_menu_button = toolbar_button_provider->GetAppMenuButton(); + app_menu_ = app_menu_button->app_menu(); + // Use a transparent background so that the menu's background shows through. // None of the children use layers, so this should be ok. SetBackgroundColor(SK_ColorTRANSPARENT); BrowserActionsContainer* main = - BrowserView::GetBrowserViewForBrowser(browser_) - ->toolbar_button_provider() - ->GetBrowserActionsContainer(); + toolbar_button_provider->GetBrowserActionsContainer(); container_ = new BrowserActionsContainer(browser_, main, main->delegate()); SetContents(container_); @@ -49,7 +47,7 @@ toolbar_actions_bar_observer_.Add(main->toolbar_actions_bar()); // Observe app menu so we know when RunMenu() is called. - app_menu_observer_.Add(app_menu_); + app_menu_button_observer_.Add(app_menu_button); // In *very* extreme cases, it's possible that there are so many overflowed // actions, we won't be able to show them all. Cap the height so that the
diff --git a/chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.h b/chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.h index d98145942..2a3ea8e 100644 --- a/chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.h +++ b/chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.h
@@ -9,10 +9,11 @@ #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" #include "chrome/browser/ui/toolbar/toolbar_actions_bar_observer.h" -#include "chrome/browser/ui/views/toolbar/app_menu_observer.h" +#include "chrome/browser/ui/views/frame/app_menu_button_observer.h" #include "ui/views/controls/scroll_view.h" class AppMenu; +class AppMenuButton; class Browser; class BrowserActionsContainer; class ToolbarActionsBar; @@ -26,13 +27,11 @@ // the app menu. // In the event that the app menu was opened for an Extension Action drag-and- // drop, this will also close the menu upon completion. -class ExtensionToolbarMenuView : public AppMenuObserver, +class ExtensionToolbarMenuView : public AppMenuButtonObserver, public views::ScrollView, public ToolbarActionsBarObserver { public: - ExtensionToolbarMenuView(Browser* browser, - AppMenu* app_menu, - views::MenuItemView* menu_item); + ExtensionToolbarMenuView(Browser* browser, views::MenuItemView* menu_item); ~ExtensionToolbarMenuView() override; BrowserActionsContainer* container_for_testing() { @@ -54,7 +53,7 @@ void OnToolbarActionsBarDestroyed() override; void OnToolbarActionDragDone() override; - // AppMenuObserver: + // AppMenuButtonObserver: void AppMenuShown() override; // Closes the |app_menu_|. @@ -70,7 +69,7 @@ Browser* const browser_; // The app menu, which may need to be closed after a drag-and-drop. - AppMenu* app_menu_; + AppMenu* app_menu_ = nullptr; // The MenuItemView this view is contained within. views::MenuItemView* menu_item_; @@ -82,15 +81,11 @@ int max_height_ = 0; ScopedObserver<ToolbarActionsBar, ToolbarActionsBarObserver> - toolbar_actions_bar_observer_; + toolbar_actions_bar_observer_{this}; + ScopedObserver<AppMenuButton, AppMenuButtonObserver> + app_menu_button_observer_{this}; - // Instances of this class are always indirectly owned by |AppMenu|, as part - // of the |MenuItemView| tree owned by the |MenuRunner|. Therefore, this is - // safe and we don't have to worry about the |AppMenu| being destroyed before - // us. - ScopedObserver<AppMenu, AppMenuObserver> app_menu_observer_; - - base::WeakPtrFactory<ExtensionToolbarMenuView> weak_factory_; + base::WeakPtrFactory<ExtensionToolbarMenuView> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ExtensionToolbarMenuView); };
diff --git a/chrome/browser/ui/views/toolbar/toolbar_action_view_interactive_uitest.cc b/chrome/browser/ui/views/toolbar/toolbar_action_view_interactive_uitest.cc index c2c31b5..86cbfd63 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_action_view_interactive_uitest.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_action_view_interactive_uitest.cc
@@ -15,6 +15,7 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/toolbar/toolbar_action_view_controller.h" #include "chrome/browser/ui/toolbar/toolbar_actions_bar.h" +#include "chrome/browser/ui/views/frame/app_menu_button_observer.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.h" #include "chrome/browser/ui/views/toolbar/app_menu.h" @@ -29,7 +30,6 @@ #include "extensions/test/extension_test_message_listener.h" #include "ui/views/controls/menu/menu_controller.h" #include "ui/views/controls/menu/menu_item_view.h" -#include "ui/views/controls/menu/menu_listener.h" #include "ui/views/controls/menu/submenu_view.h" #include "ui/views/test/menu_test_utils.h" @@ -41,35 +41,30 @@ ->GetAppMenuButton(); } -class AppMenuShowingWaiter : public views::MenuListener { +class AppMenuShowingWaiter : public AppMenuButtonObserver { public: explicit AppMenuShowingWaiter(AppMenuButton* button); - ~AppMenuShowingWaiter() override; + ~AppMenuShowingWaiter() override = default; - // views::MenuListener: - void OnMenuOpened() override; + // AppMenuButtonObserver: + void AppMenuShown() override; void Wait(); private: bool observed_ = false; - AppMenuButton* button_; base::RunLoop run_loop_; + ScopedObserver<AppMenuButton, AppMenuButtonObserver> observer_{this}; }; -AppMenuShowingWaiter::AppMenuShowingWaiter(AppMenuButton* button) - : button_(button) { - DCHECK(button_); - if (button_->IsMenuShowing()) +AppMenuShowingWaiter::AppMenuShowingWaiter(AppMenuButton* button) { + DCHECK(button); + if (button->IsMenuShowing()) observed_ = true; - button_->AddMenuListener(this); + observer_.Add(button); } -AppMenuShowingWaiter::~AppMenuShowingWaiter() { - button_->RemoveMenuListener(this); -} - -void AppMenuShowingWaiter::OnMenuOpened() { +void AppMenuShowingWaiter::AppMenuShown() { observed_ = true; if (run_loop_.running()) run_loop_.Quit();
diff --git a/chrome/browser/ui/views/toolbar/toolbar_view_interactive_uitest.cc b/chrome/browser/ui/views/toolbar/toolbar_view_interactive_uitest.cc index 550ed19..77a29cf8 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_view_interactive_uitest.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_view_interactive_uitest.cc
@@ -22,8 +22,10 @@ #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/toolbar/toolbar_actions_bar.h" #include "chrome/browser/ui/view_ids.h" +#include "chrome/browser/ui/views/frame/app_menu_button_observer.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/test_with_browser_view.h" +#include "chrome/browser/ui/views/toolbar/app_menu.h" #include "chrome/browser/ui/views/toolbar/browser_actions_container.h" #include "chrome/browser/ui/views/toolbar/browser_app_menu_button.h" #include "chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.h" @@ -32,7 +34,6 @@ #include "chrome/test/base/interactive_test_utils.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/browser/bookmark_utils.h" -#include "ui/views/controls/menu/menu_listener.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/test/widget_test.h" #include "ui/views/view.h" @@ -40,14 +41,14 @@ using bookmarks::BookmarkModel; -class ToolbarViewInteractiveUITest : public extensions::ExtensionBrowserTest, - public views::MenuListener { +class ToolbarViewInteractiveUITest : public AppMenuButtonObserver, + public extensions::ExtensionBrowserTest { public: ToolbarViewInteractiveUITest() = default; ~ToolbarViewInteractiveUITest() override = default; - // views::MenuListener: - void OnMenuOpened() override; + // AppMenuButtonObserver: + void AppMenuShown() override; protected: AppMenuButton* app_menu_button() { return app_menu_button_; } @@ -65,12 +66,12 @@ AppMenuButton* app_menu_button_ = nullptr; BrowserActionsContainer* browser_actions_ = nullptr; - bool menu_opened_ = false; + bool menu_shown_ = false; base::OnceClosure quit_closure_; }; -void ToolbarViewInteractiveUITest::OnMenuOpened() { - menu_opened_ = true; +void ToolbarViewInteractiveUITest::AppMenuShown() { + menu_shown_ = true; ui_controls::SendMouseEventsNotifyWhenDone(ui_controls::LEFT, ui_controls::UP, std::move(quit_closure_)); } @@ -83,7 +84,8 @@ // TODO(devlin): In a perfect world, this would be factored better. // Begin listening for the app menu to open. - app_menu_button()->AddMenuListener(this); + ScopedObserver<AppMenuButton, AppMenuButtonObserver> observer(this); + observer.Add(app_menu_button()); // Send the mouse to |start|, and click. The event queue must be flushed // after processing the click, or the next mouse move sent may get processed @@ -111,12 +113,10 @@ base::RunLoop run_loop; quit_closure_ = run_loop.QuitWhenIdleClosure(); run_loop.Run(); - EXPECT_TRUE(menu_opened_); + EXPECT_TRUE(menu_shown_); // The app menu should have closed once the drag-and-drop completed. EXPECT_FALSE(app_menu_button()->IsMenuShowing()); - - app_menu_button()->RemoveMenuListener(this); } void ToolbarViewInteractiveUITest::SetUpCommandLine(
diff --git a/chrome/browser/ui/views/webauthn/authenticator_dialog_view_browsertest.cc b/chrome/browser/ui/views/webauthn/authenticator_dialog_view_browsertest.cc index 9f3c6d0..d0a3dff 100644 --- a/chrome/browser/ui/views/webauthn/authenticator_dialog_view_browsertest.cc +++ b/chrome/browser/ui/views/webauthn/authenticator_dialog_view_browsertest.cc
@@ -104,7 +104,7 @@ auto dialog_model = std::make_unique<AuthenticatorRequestDialogModel>(); dialog_model->SetCurrentStep( - AuthenticatorRequestDialogModel::Step::kPostMortemTimedOut); + AuthenticatorRequestDialogModel::Step::kTimedOut); auto dialog = std::make_unique<AuthenticatorRequestDialogView>( web_contents, std::move(dialog_model));
diff --git a/chrome/browser/ui/views/webauthn/sheet_view_factory.cc b/chrome/browser/ui/views/webauthn/sheet_view_factory.cc index 9f4ac8b..03053d1 100644 --- a/chrome/browser/ui/views/webauthn/sheet_view_factory.cc +++ b/chrome/browser/ui/views/webauthn/sheet_view_factory.cc
@@ -55,15 +55,15 @@ std::make_unique<AuthenticatorNoAvailableTransportsErrorModel>( dialog_model)); break; - case Step::kPostMortemTimedOut: + case Step::kTimedOut: sheet_view = std::make_unique<AuthenticatorRequestSheetView>( std::make_unique<AuthenticatorTimeoutErrorModel>(dialog_model)); break; - case Step::kPostMortemKeyNotRegistered: + case Step::kKeyNotRegistered: sheet_view = std::make_unique<AuthenticatorRequestSheetView>( std::make_unique<AuthenticatorNotRegisteredErrorModel>(dialog_model)); break; - case Step::kPostMortemKeyAlreadyRegistered: + case Step::kKeyAlreadyRegistered: sheet_view = std::make_unique<AuthenticatorRequestSheetView>( std::make_unique<AuthenticatorAlreadyRegisteredErrorModel>( dialog_model));
diff --git a/chrome/browser/ui/webauthn/authenticator_dialog_browsertest.cc b/chrome/browser/ui/webauthn/authenticator_dialog_browsertest.cc index 2a22a9e..3b7a017 100644 --- a/chrome/browser/ui/webauthn/authenticator_dialog_browsertest.cc +++ b/chrome/browser/ui/webauthn/authenticator_dialog_browsertest.cc
@@ -45,17 +45,16 @@ model->SetCurrentStep( AuthenticatorRequestDialogModel::Step::kUsbInsertAndActivate); } else if (name == "timeout") { - model->SetCurrentStep( - AuthenticatorRequestDialogModel::Step::kPostMortemTimedOut); + model->SetCurrentStep(AuthenticatorRequestDialogModel::Step::kTimedOut); } else if (name == "no_available_transports") { model->SetCurrentStep( AuthenticatorRequestDialogModel::Step::kErrorNoAvailableTransports); } else if (name == "key_not_registered") { model->SetCurrentStep( - AuthenticatorRequestDialogModel::Step::kPostMortemKeyNotRegistered); + AuthenticatorRequestDialogModel::Step::kKeyNotRegistered); } else if (name == "key_already_registered") { - model->SetCurrentStep(AuthenticatorRequestDialogModel::Step:: - kPostMortemKeyAlreadyRegistered); + model->SetCurrentStep( + AuthenticatorRequestDialogModel::Step::kKeyAlreadyRegistered); } else if (name == "ble_power_on_manual") { model->SetCurrentStep( AuthenticatorRequestDialogModel::Step::kBlePowerOnManual);
diff --git a/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc b/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc index 62bd92ce..c9c5669 100644 --- a/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc +++ b/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc
@@ -263,10 +263,18 @@ // ConstrainedWebDialogBrowserTest.ContentResizeInAutoResizingDialog but // has the surface synchronization flag turned on. Once surface synchronization // is on by default, this test can be deleted. -// TODO(fsamuel): Fix tis for Mac too. +// TODO(fsamuel): Fix this for Mac too. #if defined(USE_AURA) +// Flaky on CrOS: http://crbug.com/928924 +#if defined(OS_CHROMEOS) +#define MAYBE_ContentResizeInAutoResizingDialog \ + DISABLED_ContentResizeInAutoResizingDialog +#else +#define MAYBE_ContentResizeInAutoResizingDialog \ + ContentResizeInAutoResizingDialog +#endif IN_PROC_BROWSER_TEST_F(ConstrainedWebDialogSurfaceSynchronizationBrowserTest, - ContentResizeInAutoResizingDialog) { + MAYBE_ContentResizeInAutoResizingDialog) { // During auto-resizing, dialogs size to (WebContents size) + 16. const int dialog_border_space = 16;
diff --git a/chrome/browser/ui/webui/discards/discards_ui.cc b/chrome/browser/ui/webui/discards/discards_ui.cc index 8ccd4b3..4ddf19be 100644 --- a/chrome/browser/ui/webui/discards/discards_ui.cc +++ b/chrome/browser/ui/webui/discards/discards_ui.cc
@@ -14,6 +14,7 @@ #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/engagement/site_engagement_service.h" +#include "chrome/browser/performance_manager/performance_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/resource_coordinator/lifecycle_unit.h" #include "chrome/browser/resource_coordinator/lifecycle_unit_state.mojom.h" @@ -33,10 +34,8 @@ #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "content/public/browser/web_ui_message_handler.h" -#include "content/public/common/service_manager_connection.h" #include "mojo/public/cpp/bindings/binding.h" #include "services/resource_coordinator/public/mojom/service_constants.mojom.h" -#include "services/service_manager/public/cpp/connector.h" #include "ui/resources/grit/ui_resources.h" #include "url/gurl.h" #include "url/origin.h" @@ -451,12 +450,10 @@ void DiscardsUI::BindWebUIGraphDumpProvider( resource_coordinator::mojom::WebUIGraphDumpRequest request) { - service_manager::Connector* connector = - content::ServiceManagerConnection::GetForProcess()->GetConnector(); - - if (connector) { + performance_manager::PerformanceManager* performance_manager = + performance_manager::PerformanceManager::GetInstance(); + if (performance_manager) { // Forward the interface request directly to the service. - connector->BindInterface(resource_coordinator::mojom::kServiceName, - std::move(request)); + performance_manager->BindInterface(std::move(request)); } }
diff --git a/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc index f67cd02..a745350b 100644 --- a/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc
@@ -1323,6 +1323,7 @@ IDS_SETTINGS_LANGUAGES_OFFER_TO_TRANSLATE_IN_THIS_LANGUAGE}, {"offerToEnableTranslate", IDS_SETTINGS_LANGUAGES_OFFER_TO_ENABLE_TRANSLATE}, + {"translateTargetLabel", IDS_SETTINGS_LANGUAGES_TRANSLATE_TARGET}, #if !defined(OS_MACOSX) {"spellCheckListTitle", IDS_SETTINGS_LANGUAGES_SPELL_CHECK_LIST_TITLE}, {"spellCheckExpandA11yLabel",
diff --git a/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc b/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc index 6f405021..880f787 100644 --- a/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc +++ b/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc
@@ -12,12 +12,13 @@ #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/signin/account_tracker_service_factory.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/ui/webui/signin/inline_login_handler.h" #include "chromeos/account_manager/account_manager.h" #include "chromeos/account_manager/account_manager_factory.h" -#include "components/signin/core/browser/account_tracker_service.h" +#include "components/signin/core/browser/account_info.h" #include "google_apis/gaia/gaia_urls.h" +#include "services/identity/public/cpp/identity_manager.h" #include "services/network/public/cpp/shared_url_loader_factory.h" namespace chromeos { @@ -57,14 +58,19 @@ // GaiaAuthConsumer overrides. void OnClientOAuthSuccess(const ClientOAuthResult& result) override { // TODO(sinhak): Do not depend on Profile unnecessarily. A Profile should - // call |AccountTrackerServiceFactory| for the list of accounts it wants to + // call |IdentityManagerFactory| for the list of accounts it wants to // pull from |AccountManager|, not the other way round. Remove this when we // release multi Profile on Chrome OS and have the infra in place to do // this. // Account info needs to be seeded before the OAuth2TokenService chain can // use it. Do this before anything else. - AccountTrackerServiceFactory::GetForProfile(profile_)->SeedAccountInfo( - account_key_.id, email_); + AccountInfo account_info; + account_info.gaia = account_key_.id; + account_info.email = email_; + // TODO(crbug.com/922026): SigninHelper and InlineLoginHandlerChromeOS + // must be refactored to remove this use of LegacySeedAccountInfo. + IdentityManagerFactory::GetForProfile(profile_)->LegacySeedAccountInfo( + account_info); account_manager_->UpsertToken(account_key_, result.refresh_token);
diff --git a/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc b/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc index 1488264..572e5cf4 100644 --- a/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc +++ b/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc
@@ -43,8 +43,6 @@ int undo_button_ids = -1; if (is_unified_consent_enabled && is_sync_allowed) { source->SetDefaultResource(IDR_DICE_SYNC_CONFIRMATION_HTML); - source->AddResourcePath("icons.html", - IDR_DICE_SYNC_CONFIRMATION_ICONS_HTML); source->AddResourcePath("sync_confirmation_browser_proxy.html", IDR_DICE_SYNC_CONFIRMATION_BROWSER_PROXY_HTML); source->AddResourcePath("sync_confirmation_browser_proxy.js", @@ -60,14 +58,6 @@ IDS_SYNC_CONFIRMATION_UNITY_SYNC_INFO_TITLE); AddStringResource(source, "syncConfirmationSyncInfoDesc", IDS_SYNC_CONFIRMATION_UNITY_SYNC_INFO_DESC); - AddStringResource(source, "syncConfirmationSpellcheckInfoTitle", - IDS_SYNC_CONFIRMATION_UNITY_SPELLCHECK_INFO_TITLE); - AddStringResource(source, "syncConfirmationSpellcheckInfoDesc", - IDS_SYNC_CONFIRMATION_UNITY_SPELLCHECK_INFO_DESC); - AddStringResource(source, "syncConfirmationImproveChromeInfoTitle", - IDS_SYNC_CONFIRMATION_UNITY_IMPROVE_CHROME_INFO_TITLE); - AddStringResource(source, "syncConfirmationImproveChromeInfoDesc", - IDS_SYNC_CONFIRMATION_UNITY_IMPROVE_CHROME_INFO_DESC); AddStringResource(source, "syncConfirmationSettingsInfo", IDS_SYNC_CONFIRMATION_UNITY_SETTINGS_INFO); @@ -87,7 +77,7 @@ } source->AddString("accountPictureUrl", custom_picture_url); - title_ids = IDS_SYNC_CONFIRMATION_UNITY_TITLE; + title_ids = IDS_SYNC_CONFIRMATION_DICE_TITLE; confirm_button_ids = IDS_SYNC_CONFIRMATION_DICE_CONFIRM_BUTTON_LABEL; undo_button_ids = IDS_CANCEL; consent_feature_ = consent_auditor::Feature::CHROME_UNIFIED_CONSENT;
diff --git a/chrome/browser/ui/webui/sync_internals_message_handler.cc b/chrome/browser/ui/webui/sync_internals_message_handler.cc index d60afffa3..d738d8c 100644 --- a/chrome/browser/ui/webui/sync_internals_message_handler.cc +++ b/chrome/browser/ui/webui/sync_internals_message_handler.cc
@@ -362,8 +362,7 @@ void SyncInternalsMessageHandler::OnProtocolEvent( const syncer::ProtocolEvent& event) { - std::unique_ptr<DictionaryValue> value( - syncer::ProtocolEvent::ToValue(event, include_specifics_)); + std::unique_ptr<DictionaryValue> value(event.ToValue(include_specifics_)); DispatchEvent(syncer::sync_ui_util::kOnProtocolEvent, *value); }
diff --git a/chrome/browser/upgrade_detector/upgrade_detector_chromeos.cc b/chrome/browser/upgrade_detector/upgrade_detector_chromeos.cc index 8ad270e..11b0059 100644 --- a/chrome/browser/upgrade_detector/upgrade_detector_chromeos.cc +++ b/chrome/browser/upgrade_detector/upgrade_detector_chromeos.cc
@@ -156,7 +156,8 @@ void UpgradeDetectorChromeos::UpdateStatusChanged( const UpdateEngineClient::Status& status) { if (status.status == UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT) { - set_upgrade_detected_time(clock()->Now()); + if (upgrade_detected_time().is_null()) + set_upgrade_detected_time(clock()->Now()); if (status.is_rollback) { // Powerwash will be required, determine what kind of notification to show
diff --git a/chrome/browser/upgrade_detector/upgrade_detector_chromeos.h b/chrome/browser/upgrade_detector/upgrade_detector_chromeos.h index 6d1931d..9febc95d 100644 --- a/chrome/browser/upgrade_detector/upgrade_detector_chromeos.h +++ b/chrome/browser/upgrade_detector/upgrade_detector_chromeos.h
@@ -40,12 +40,13 @@ base::TimeDelta GetHighAnnoyanceLevelDelta() override; base::Time GetHighAnnoyanceDeadline() override; - private: - friend class base::NoDestructor<UpgradeDetectorChromeos>; - + protected: UpgradeDetectorChromeos(const base::Clock* clock, const base::TickClock* tick_clock); + private: + friend class base::NoDestructor<UpgradeDetectorChromeos>; + // Returns the threshold to reach high annoyance level. static base::TimeDelta DetermineHighThreshold();
diff --git a/chrome/browser/upgrade_detector/upgrade_detector_chromeos_unittest.cc b/chrome/browser/upgrade_detector/upgrade_detector_chromeos_unittest.cc new file mode 100644 index 0000000..c2665401 --- /dev/null +++ b/chrome/browser/upgrade_detector/upgrade_detector_chromeos_unittest.cc
@@ -0,0 +1,138 @@ +// 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. + +#include "chrome/browser/upgrade_detector/upgrade_detector_chromeos.h" + +#include <memory> +#include <utility> + +#include "base/macros.h" +#include "base/test/scoped_task_environment.h" +#include "base/time/clock.h" +#include "base/time/tick_clock.h" +#include "base/values.h" +#include "build/build_config.h" +#include "chrome/browser/upgrade_detector/upgrade_observer.h" +#include "chrome/common/pref_names.h" +#include "chrome/test/base/scoped_testing_local_state.h" +#include "chrome/test/base/testing_browser_process.h" +#include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/dbus/fake_update_engine_client.h" +#include "components/prefs/testing_pref_service.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +class TestUpgradeDetectorChromeos : public UpgradeDetectorChromeos { + public: + explicit TestUpgradeDetectorChromeos(const base::Clock* clock, + const base::TickClock* tick_clock) + : UpgradeDetectorChromeos(clock, tick_clock) {} + ~TestUpgradeDetectorChromeos() override = default; + + // Exposed for testing. + using UpgradeDetectorChromeos::UPGRADE_AVAILABLE_REGULAR; + + DISALLOW_COPY_AND_ASSIGN(TestUpgradeDetectorChromeos); +}; + +class MockUpgradeObserver : public UpgradeObserver { + public: + explicit MockUpgradeObserver(UpgradeDetector* upgrade_detector) + : upgrade_detector_(upgrade_detector) { + upgrade_detector_->AddObserver(this); + } + ~MockUpgradeObserver() override { upgrade_detector_->RemoveObserver(this); } + MOCK_METHOD0(OnUpdateOverCellularAvailable, void()); + MOCK_METHOD0(OnUpdateOverCellularOneTimePermissionGranted, void()); + MOCK_METHOD0(OnUpgradeRecommended, void()); + MOCK_METHOD0(OnCriticalUpgradeInstalled, void()); + MOCK_METHOD0(OnOutdatedInstall, void()); + MOCK_METHOD0(OnOutdatedInstallNoAutoUpdate, void()); + + private: + UpgradeDetector* const upgrade_detector_; + DISALLOW_COPY_AND_ASSIGN(MockUpgradeObserver); +}; + +} // namespace + +class UpgradeDetectorChromeosTest : public ::testing::Test { + protected: + UpgradeDetectorChromeosTest() + : scoped_task_environment_( + base::test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME), + scoped_local_state_(TestingBrowserProcess::GetGlobal()) { + // Disable the detector's check to see if autoupdates are inabled. + // Without this, tests put the detector into an invalid state by detecting + // upgrades before the detection task completes. + scoped_local_state_.Get()->SetUserPref(prefs::kAttemptedToEnableAutoupdate, + std::make_unique<base::Value>(true)); + + fake_update_engine_client_ = new chromeos::FakeUpdateEngineClient(); + std::unique_ptr<chromeos::DBusThreadManagerSetter> dbus_setter = + chromeos::DBusThreadManager::GetSetterForTesting(); + dbus_setter->SetUpdateEngineClient( + std::unique_ptr<chromeos::UpdateEngineClient>( + fake_update_engine_client_)); + } + + const base::Clock* GetMockClock() { + return scoped_task_environment_.GetMockClock(); + } + + const base::TickClock* GetMockTickClock() { + return scoped_task_environment_.GetMockTickClock(); + } + + void RunUntilIdle() { scoped_task_environment_.RunUntilIdle(); } + + void NotifyUpdateReadyToInstall() { + chromeos::UpdateEngineClient::Status status; + status.status = + chromeos::UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT; + fake_update_engine_client_->set_default_status(status); + fake_update_engine_client_->NotifyObserversThatStatusChanged(status); + } + + // Fast-forwards virtual time by |delta|. + void FastForwardBy(base::TimeDelta delta) { + scoped_task_environment_.FastForwardBy(delta); + } + + private: + base::test::ScopedTaskEnvironment scoped_task_environment_; + ScopedTestingLocalState scoped_local_state_; + + chromeos::FakeUpdateEngineClient* fake_update_engine_client_; // Not owned. + + DISALLOW_COPY_AND_ASSIGN(UpgradeDetectorChromeosTest); +}; + +TEST_F(UpgradeDetectorChromeosTest, TestHighAnnoyanceDeadline) { + TestUpgradeDetectorChromeos upgrade_detector(GetMockClock(), + GetMockTickClock()); + upgrade_detector.Init(); + ::testing::StrictMock<MockUpgradeObserver> mock_observer(&upgrade_detector); + + // Observer should get some notifications about new version. + EXPECT_CALL(mock_observer, OnUpgradeRecommended()).Times(testing::AtLeast(1)); + NotifyUpdateReadyToInstall(); + + const auto deadline = upgrade_detector.GetHighAnnoyanceDeadline(); + + // Another new version of ChromeOS is ready to install after a day. + FastForwardBy(base::TimeDelta::FromDays(1)); + ::testing::Mock::VerifyAndClear(&mock_observer); + // New notification could be sent or not. + EXPECT_CALL(mock_observer, OnUpgradeRecommended()) + .Times(testing::AnyNumber()); + NotifyUpdateReadyToInstall(); + + // Deadline wasn't changed because of new upgrade detected. + EXPECT_EQ(upgrade_detector.GetHighAnnoyanceDeadline(), deadline); + upgrade_detector.Shutdown(); + RunUntilIdle(); +}
diff --git a/chrome/browser/webauthn/authenticator_request_dialog_model.cc b/chrome/browser/webauthn/authenticator_request_dialog_model.cc index 81fce024..0d1476e 100644 --- a/chrome/browser/webauthn/authenticator_request_dialog_model.cc +++ b/chrome/browser/webauthn/authenticator_request_dialog_model.cc
@@ -306,7 +306,6 @@ void AuthenticatorRequestDialogModel::Cancel() { if (is_request_complete()) { SetCurrentStep(Step::kClosed); - return; } for (auto& observer : observers_) @@ -331,25 +330,22 @@ } void AuthenticatorRequestDialogModel::OnRequestComplete() { - DCHECK_NE(current_step(), Step::kClosed); - if (is_showing_post_mortem()) - return; SetCurrentStep(Step::kClosed); } void AuthenticatorRequestDialogModel::OnRequestTimeout() { DCHECK(!is_request_complete()); - SetCurrentStep(Step::kPostMortemTimedOut); + SetCurrentStep(Step::kTimedOut); } void AuthenticatorRequestDialogModel::OnActivatedKeyNotRegistered() { DCHECK(!is_request_complete()); - SetCurrentStep(Step::kPostMortemKeyNotRegistered); + SetCurrentStep(Step::kKeyNotRegistered); } void AuthenticatorRequestDialogModel::OnActivatedKeyAlreadyRegistered() { DCHECK(!is_request_complete()); - SetCurrentStep(Step::kPostMortemKeyAlreadyRegistered); + SetCurrentStep(Step::kKeyAlreadyRegistered); } void AuthenticatorRequestDialogModel::OnBluetoothPoweredStateChanged(
diff --git a/chrome/browser/webauthn/authenticator_request_dialog_model.h b/chrome/browser/webauthn/authenticator_request_dialog_model.h index 46b5226..a082a0c0 100644 --- a/chrome/browser/webauthn/authenticator_request_dialog_model.h +++ b/chrome/browser/webauthn/authenticator_request_dialog_model.h
@@ -44,15 +44,16 @@ kWelcomeScreen, kTransportSelection, - // The request is not yet complete, and will only be after user interaction. + // The request errored out before completing. Error will only be sent + // after user interaction. kErrorNoAvailableTransports, kErrorInternalUnrecognized, - // The request is already complete, but the dialog should remain open with - // an explaining of what went wrong. - kPostMortemTimedOut, - kPostMortemKeyNotRegistered, - kPostMortemKeyAlreadyRegistered, + // The request is already complete, but the error dialog should wait + // until user acknowledgement. + kTimedOut, + kKeyNotRegistered, + kKeyAlreadyRegistered, // The request is completed, and the dialog should be closed. kClosed, @@ -108,14 +109,14 @@ void SetCurrentStep(Step step); Step current_step() const { return current_step_; } - bool is_showing_post_mortem() const { - return current_step() == Step::kPostMortemTimedOut || - current_step() == Step::kPostMortemKeyNotRegistered || - current_step() == Step::kPostMortemKeyAlreadyRegistered; - } - + // Returns whether the UI is in a state at which the |request_| member of + // AuthenticatorImpl has completed processing. Note that the request callback + // is only resolved after the UI is dismissed. bool is_request_complete() const { - return is_showing_post_mortem() || current_step() == Step::kClosed; + return current_step() == Step::kTimedOut || + current_step() == Step::kKeyNotRegistered || + current_step() == Step::kKeyAlreadyRegistered || + current_step() == Step::kClosed; } bool should_dialog_be_closed() const {
diff --git a/chrome/browser/webauthn/authenticator_request_dialog_model_unittest.cc b/chrome/browser/webauthn/authenticator_request_dialog_model_unittest.cc index 72333df3..dee5af1 100644 --- a/chrome/browser/webauthn/authenticator_request_dialog_model_unittest.cc +++ b/chrome/browser/webauthn/authenticator_request_dialog_model_unittest.cc
@@ -322,17 +322,16 @@ EXPECT_CALL(mock_observer, OnModelDestroyed()); } -TEST_F(AuthenticatorRequestDialogModelTest, PostMortems) { +TEST_F(AuthenticatorRequestDialogModelTest, AwaitingAcknowledgement) { const struct { void (AuthenticatorRequestDialogModel::*event)(); - Step expected_post_mortem_sheet; + Step expected_sheet; } kTestCases[] = { - {&AuthenticatorRequestDialogModel::OnRequestTimeout, - Step::kPostMortemTimedOut}, + {&AuthenticatorRequestDialogModel::OnRequestTimeout, Step::kTimedOut}, {&AuthenticatorRequestDialogModel::OnActivatedKeyNotRegistered, - Step::kPostMortemKeyNotRegistered}, + Step::kKeyNotRegistered}, {&AuthenticatorRequestDialogModel::OnActivatedKeyAlreadyRegistered, - Step::kPostMortemKeyAlreadyRegistered}, + Step::kKeyAlreadyRegistered}, }; for (const auto& test_case : kTestCases) { @@ -351,11 +350,11 @@ EXPECT_CALL(mock_observer, OnStepTransition()); (model.*test_case.event)(); - model.OnRequestComplete(); - EXPECT_EQ(test_case.expected_post_mortem_sheet, model.current_step()); + EXPECT_EQ(test_case.expected_sheet, model.current_step()); testing::Mock::VerifyAndClearExpectations(&mock_observer); EXPECT_CALL(mock_observer, OnStepTransition()); + EXPECT_CALL(mock_observer, OnCancelRequest()); model.Cancel(); EXPECT_EQ(Step::kClosed, model.current_step()); testing::Mock::VerifyAndClearExpectations(&mock_observer);
diff --git a/chrome/browser/webauthn/chrome_authenticator_request_delegate.cc b/chrome/browser/webauthn/chrome_authenticator_request_delegate.cc index e309391..719495d6 100644 --- a/chrome/browser/webauthn/chrome_authenticator_request_delegate.cc +++ b/chrome/browser/webauthn/chrome_authenticator_request_delegate.cc
@@ -117,10 +117,12 @@ ->GetBrowserContext(); } -void ChromeAuthenticatorRequestDelegate::DidFailWithInterestingReason( +bool ChromeAuthenticatorRequestDelegate::DoesBlockRequestOnFailure( InterestingFailureReason reason) { + if (!IsWebAuthnUIEnabled()) + return false; if (!weak_dialog_model_) - return; + return false; switch (reason) { case InterestingFailureReason::kTimeout: @@ -133,6 +135,7 @@ weak_dialog_model_->OnActivatedKeyAlreadyRegistered(); break; } + return true; } void ChromeAuthenticatorRequestDelegate::RegisterActionCallbacks( @@ -284,6 +287,17 @@ } } +void ChromeAuthenticatorRequestDelegate::DisableUI() { + disable_ui_ = true; +} + +bool ChromeAuthenticatorRequestDelegate::IsWebAuthnUIEnabled() { + // UI can be disabled via flag or by the request handler for certain + // requests (e.g. on Windows, where the native API renders its own UI). + return base::FeatureList::IsEnabled(features::kWebAuthenticationUI) && + !disable_ui_; +} + void ChromeAuthenticatorRequestDelegate::OnTransportAvailabilityEnumerated( device::FidoRequestHandlerBase::TransportAvailabilityInfo data) { #if !defined(OS_ANDROID) @@ -292,7 +306,7 @@ return; } - if (!IsWebAuthnUiEnabled()) + if (!IsWebAuthnUIEnabled()) return; DCHECK(weak_dialog_model_); @@ -308,7 +322,7 @@ bool ChromeAuthenticatorRequestDelegate::EmbedderControlsAuthenticatorDispatch( const device::FidoAuthenticator& authenticator) { - if (!IsWebAuthnUiEnabled()) + if (!IsWebAuthnUIEnabled()) return false; // On macOS, a native dialog is shown for the Touch ID authenticator // immediately after dispatch to that authenticator. This dialog must not @@ -324,7 +338,7 @@ void ChromeAuthenticatorRequestDelegate::FidoAuthenticatorAdded( const device::FidoAuthenticator& authenticator) { - if (!IsWebAuthnUiEnabled()) + if (!IsWebAuthnUIEnabled()) return; if (!weak_dialog_model_) @@ -335,7 +349,7 @@ void ChromeAuthenticatorRequestDelegate::FidoAuthenticatorRemoved( base::StringPiece authenticator_id) { - if (!IsWebAuthnUiEnabled()) + if (!IsWebAuthnUIEnabled()) return; if (!weak_dialog_model_) @@ -416,10 +430,3 @@ Profile::FromBrowserContext(browser_context())->GetPrefs(); return prefs->GetList(kWebAuthnBlePairedMacAddressesPrefName); } - -bool ChromeAuthenticatorRequestDelegate::IsWebAuthnUiEnabled() const { - // UI can be disabled via flag or by the request handler for certain - // requests (e.g. on Windows, where the native API renders its own UI). - return base::FeatureList::IsEnabled(features::kWebAuthenticationUI) && - !disable_ui_; -}
diff --git a/chrome/browser/webauthn/chrome_authenticator_request_delegate.h b/chrome/browser/webauthn/chrome_authenticator_request_delegate.h index 10cce970..b5fd753 100644 --- a/chrome/browser/webauthn/chrome_authenticator_request_delegate.h +++ b/chrome/browser/webauthn/chrome_authenticator_request_delegate.h
@@ -69,7 +69,7 @@ content::BrowserContext* browser_context() const; // content::AuthenticatorRequestClientDelegate: - void DidFailWithInterestingReason(InterestingFailureReason reason) override; + bool DoesBlockRequestOnFailure(InterestingFailureReason reason) override; void RegisterActionCallbacks( base::OnceClosure cancel_callback, device::FidoRequestHandlerBase::RequestCallback request_callback, @@ -84,6 +84,8 @@ bool IsFocused() override; void UpdateLastTransportUsed( device::FidoTransportProtocol transport) override; + void DisableUI() override; + bool IsWebAuthnUIEnabled() override; // device::FidoRequestHandlerBase::TransportAvailabilityObserver: void OnTransportAvailabilityEnumerated( @@ -106,7 +108,6 @@ void AddFidoBleDeviceToPairedList(std::string ble_authenticator_id); base::Optional<device::FidoTransportProtocol> GetLastTransportUsed() const; const base::ListValue* GetPreviouslyPairedFidoBleDeviceIds() const; - bool IsWebAuthnUiEnabled() const; content::RenderFrameHost* const render_frame_host_; AuthenticatorRequestDialogModel* weak_dialog_model_ = nullptr;
diff --git a/chrome/common/extensions/docs/templates/articles/getstarted.html b/chrome/common/extensions/docs/templates/articles/getstarted.html index 4c9f8077..6183144 100644 --- a/chrome/common/extensions/docs/templates/articles/getstarted.html +++ b/chrome/common/extensions/docs/templates/articles/getstarted.html
@@ -213,7 +213,7 @@ "persistent": false }, <b>"page_action": {</b> - <b>"default_popup": "popup.html",</b> + <b>"default_popup": "popup.html"</b> <b>},</b> "manifest_version": 2 } @@ -240,8 +240,8 @@ "persistent": false }, "page_action": { - "default_popup": "popup.html", - <b>"default_icon": {</b> + "default_popup": "popup.html"<b>, + "default_icon": {</b> <b>"16": "images/get_started16.png",</b> <b>"32": "images/get_started32.png",</b> <b>"48": "images/get_started48.png",</b>
diff --git a/chrome/common/extensions/docs/templates/intros/storage.html b/chrome/common/extensions/docs/templates/intros/storage.html index a34496aa..4db8b0c 100644 --- a/chrome/common/extensions/docs/templates/intros/storage.html +++ b/chrome/common/extensions/docs/templates/intros/storage.html
@@ -159,7 +159,7 @@ <pre> chrome.storage.onChanged.addListener(function(changes, namespace) { - for (key in changes) { + for (var key in changes) { var storageChange = changes[key]; console.log('Storage key "%s" in namespace "%s" changed. ' + 'Old value was "%s", new value is "%s".',
diff --git a/chrome/installer/setup/archive_patch_helper.cc b/chrome/installer/setup/archive_patch_helper.cc index 4d4f86e..dc9bc19 100644 --- a/chrome/installer/setup/archive_patch_helper.cc +++ b/chrome/installer/setup/archive_patch_helper.cc
@@ -63,15 +63,11 @@ } bool ArchivePatchHelper::ApplyPatch() { - // TODO(ckitagawa): Swap ordering back to Zucchini first once we ship - // Zucchini based patches by default. - if (CourgetteEnsemblePatch() || BinaryPatch()) - return true; #if BUILDFLAG(ZUCCHINI) if (ZucchiniEnsemblePatch()) return true; #endif // BUILDFLAG(ZUCCHINI) - return false; + return CourgetteEnsemblePatch() || BinaryPatch(); } bool ArchivePatchHelper::CourgetteEnsemblePatch() {
diff --git a/chrome/renderer/resources/extensions/automation/automation_node.js b/chrome/renderer/resources/extensions/automation/automation_node.js index 52794fb2..9190320 100644 --- a/chrome/renderer/resources/extensions/automation/automation_node.js +++ b/chrome/renderer/resources/extensions/automation/automation_node.js
@@ -1014,6 +1014,7 @@ 'containerLiveStatus', 'description', 'display', + 'fontFamily', 'htmlTag', 'imageDataUrl', 'innerHtml', @@ -1088,9 +1089,10 @@ ['labelledbyIds', 'labelledBy', 'labelFor']]; var floatAttributes = [ - 'valueForRange', + 'fontSize', + 'maxValueForRange', 'minValueForRange', - 'maxValueForRange']; + 'valueForRange']; var htmlAttributes = [ ['type', 'inputType']];
diff --git a/chrome/renderer/safe_browsing/phishing_term_feature_extractor_unittest.cc b/chrome/renderer/safe_browsing/phishing_term_feature_extractor_unittest.cc index 0c7febc1..39d5ce1 100644 --- a/chrome/renderer/safe_browsing/phishing_term_feature_extractor_unittest.cc +++ b/chrome/renderer/safe_browsing/phishing_term_feature_extractor_unittest.cc
@@ -14,12 +14,13 @@ #include "base/bind.h" #include "base/callback.h" #include "base/location.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/string16.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/scoped_task_environment.h" +#include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "build/build_config.h" #include "chrome/renderer/safe_browsing/features.h" @@ -115,7 +116,7 @@ shingle_hashes, base::Bind(&PhishingTermFeatureExtractorTest::ExtractionDone, base::Unretained(this))); - msg_loop_.task_runner()->PostTask( + base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&PhishingTermFeatureExtractorTest::QuitExtraction, base::Unretained(this))); @@ -134,7 +135,7 @@ active_run_loop_->QuitWhenIdle(); } - base::MessageLoop msg_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; std::unique_ptr<base::RunLoop> active_run_loop_; MockFeatureExtractorClock clock_; std::unique_ptr<PhishingTermFeatureExtractor> extractor_;
diff --git a/chrome/service/service_process.cc b/chrome/service/service_process.cc index 88d7c4d..494138da 100644 --- a/chrome/service/service_process.cc +++ b/chrome/service/service_process.cc
@@ -154,15 +154,19 @@ service_process_state_ = std::move(state); // Initialize TaskScheduler. - constexpr int kMaxBackgroundThreads = 2; - constexpr int kMaxForegroundThreads = 6; + constexpr int kMaxBackgroundThreads = 1; + constexpr int kMaxBackgroundBlockingThreads = 1; + constexpr int kMaxForegroundThreads = 3; + constexpr int kMaxForegroundBlockingThreads = 3; constexpr base::TimeDelta kSuggestedReclaimTime = base::TimeDelta::FromSeconds(30); base::TaskScheduler::Create("CloudPrintServiceProcess"); base::TaskScheduler::GetInstance()->Start( {{kMaxBackgroundThreads, kSuggestedReclaimTime}, - {kMaxForegroundThreads, kSuggestedReclaimTime, + {kMaxBackgroundBlockingThreads, kSuggestedReclaimTime}, + {kMaxForegroundThreads, kSuggestedReclaimTime}, + {kMaxForegroundBlockingThreads, kSuggestedReclaimTime, base::SchedulerBackwardCompatibility::INIT_COM_STA}}); // The NetworkChangeNotifier must be created after TaskScheduler because it
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 1db74678..5c01854 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -2715,6 +2715,22 @@ "../browser/password_manager/password_store_mac_unittest.cc", "../browser/password_manager/password_store_x_unittest.cc", "../browser/payments/payment_handler_permission_context_unittest.cc", + "../browser/performance_manager/coordination_unit/coordination_unit_base_unittest.cc", + "../browser/performance_manager/coordination_unit/coordination_unit_graph_unittest.cc", + "../browser/performance_manager/coordination_unit/coordination_unit_test_harness.cc", + "../browser/performance_manager/coordination_unit/coordination_unit_test_harness.h", + "../browser/performance_manager/coordination_unit/frame_coordination_unit_impl_unittest.cc", + "../browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.cc", + "../browser/performance_manager/coordination_unit/mock_coordination_unit_graphs.h", + "../browser/performance_manager/coordination_unit/page_coordination_unit_impl_unittest.cc", + "../browser/performance_manager/coordination_unit/process_coordination_unit_impl_unittest.cc", + "../browser/performance_manager/coordination_unit/system_coordination_unit_impl_unittest.cc", + "../browser/performance_manager/observers/coordination_unit_graph_observer_unittest.cc", + "../browser/performance_manager/observers/metrics_collector_unittest.cc", + "../browser/performance_manager/observers/page_signal_generator_impl_unittest.cc", + "../browser/performance_manager/observers/working_set_trimmer_win_unittest.cc", + "../browser/performance_manager/performance_manager_unittest.cc", + "../browser/performance_manager/webui_graph_dump_impl_unittest.cc", "../browser/performance_monitor/system_monitor_helper_win_unittest.cc", "../browser/performance_monitor/system_monitor_unittest.cc", "../browser/permissions/chooser_context_base_mock_permission_observer.cc", @@ -2844,6 +2860,7 @@ "../browser/sync/sync_startup_tracker_unittest.cc", "../browser/thumbnails/thumbnail_utils_unittest.cc", "../browser/tracing/background_tracing_field_trial_unittest.cc", + "../browser/tracing/trace_event_system_stats_monitor_unittest.cc", "../browser/translate/chrome_translate_client_unittest.cc", "../browser/translate/translate_fake_page.cc", "../browser/translate/translate_service_unittest.cc", @@ -3163,6 +3180,7 @@ "../browser/password_manager/account_chooser_dialog_android_unittest.cc", "../browser/password_manager/auto_signin_first_run_dialog_android_unittest.cc", "../browser/password_manager/password_accessory_controller_impl_unittest.cc", + "../browser/password_manager/password_generation_controller_impl_unittest.cc", "../browser/password_manager/save_password_infobar_delegate_android_unittest.cc", "../browser/password_manager/update_password_infobar_delegate_android_unittest.cc", "../browser/translate/translate_manager_render_view_host_android_unittest.cc", @@ -4445,6 +4463,10 @@ "../browser/upgrade_detector/upgrade_detector_impl_unittest.cc", ] } + if (is_chromeos) { + sources += + [ "../browser/upgrade_detector/upgrade_detector_chromeos_unittest.cc" ] + } if (toolkit_views) { deps += [ "//components/web_modal:test_support",
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/compositor/layouts/DisableChromeAnimations.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/compositor/layouts/DisableChromeAnimations.java index 78b7356..4b71a11 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/compositor/layouts/DisableChromeAnimations.java +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/compositor/layouts/DisableChromeAnimations.java
@@ -6,22 +6,31 @@ import org.junit.rules.ExternalResource; +import org.chromium.chrome.browser.compositor.animation.CompositorAnimationHandler; import org.chromium.chrome.browser.compositor.layouts.ChromeAnimation; /** - * JUnit 4 rule that disables animations in ChromeAnimation for tests. + * JUnit 4 rule that disables animations in ChromeAnimation / CompositorAnimationHandler for tests. */ public class DisableChromeAnimations extends ExternalResource { + private boolean mOldTestingMode; private float mOldAnimationMultiplier; @Override protected void before() { + // old API (ChromeAnimation) mOldAnimationMultiplier = ChromeAnimation.Animation.getAnimationMultiplier(); ChromeAnimation.Animation.setAnimationMultiplierForTesting(0f); + // new API + mOldTestingMode = CompositorAnimationHandler.isInTestingMode(); + CompositorAnimationHandler.setTestingMode(true); } @Override protected void after() { + // old API (ChromeAnimation) ChromeAnimation.Animation.setAnimationMultiplierForTesting(mOldAnimationMultiplier); + // new API + CompositorAnimationHandler.setTestingMode(mOldTestingMode); } }
diff --git a/chrome/test/base/chrome_test_launcher.cc b/chrome/test/base/chrome_test_launcher.cc index 8da3ff5..0b2d3685 100644 --- a/chrome/test/base/chrome_test_launcher.cc +++ b/chrome/test/base/chrome_test_launcher.cc
@@ -33,7 +33,6 @@ #include "content/public/test/network_service_test_helper.h" #include "content/public/test/test_launcher.h" #include "content/public/test/test_utils.h" -#include "services/service_manager/runner/common/switches.h" #include "ui/base/test/ui_controls.h" #if defined(OS_MACOSX)
diff --git a/chrome/test/chromedriver/BUILD.gn b/chrome/test/chromedriver/BUILD.gn index eb127a4..fa0b843d 100644 --- a/chrome/test/chromedriver/BUILD.gn +++ b/chrome/test/chromedriver/BUILD.gn
@@ -413,10 +413,17 @@ "chrome_launcher_unittest.cc", "command_listener_proxy_unittest.cc", "commands_unittest.cc", + "key_converter_unittest.cc", + "keycode_text_conversion_unittest.cc", "log_replay/devtools_log_reader_unittest.cc", "logging_unittest.cc", "net/adb_client_socket_unittest.cc", + "net/net_util_unittest.cc", + "net/sync_websocket_impl_unittest.cc", + "net/test_http_server.cc", + "net/test_http_server.h", "net/timeout_unittest.cc", + "net/websocket_unittest.cc", "performance_logger_unittest.cc", "server/http_handler_unittest.cc", "session_commands_unittest.cc", @@ -437,15 +444,19 @@ ":lib", "//base", "//base/test:run_all_unittests", + "//mojo/core/embedder", "//net", "//net:test_support", "//net/server:http_server", + "//services/network/public/cpp", "//services/network/public/mojom", "//testing/gmock", "//testing/gtest", "//ui/base", + "//ui/events:test_support", "//ui/gfx", "//ui/gfx/geometry", + "//url", ] }
diff --git a/chrome/test/chromedriver/keycode_text_conversion_unittest.cc b/chrome/test/chromedriver/keycode_text_conversion_unittest.cc index f45cc7b6..bc78143 100644 --- a/chrome/test/chromedriver/keycode_text_conversion_unittest.cc +++ b/chrome/test/chromedriver/keycode_text_conversion_unittest.cc
@@ -136,7 +136,7 @@ #endif } -#if (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || defined(OS_MACOSX) +#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_MACOSX) // Not implemented on Linux. // Fails if tested layouts are not installed on Mac. #define MAYBE_NonEnglish DISABLED_NonEnglish
diff --git a/chrome/test/chromedriver/logging.cc b/chrome/test/chromedriver/logging.cc index 94061785..ed04f8276b 100644 --- a/chrome/test/chromedriver/logging.cc +++ b/chrome/test/chromedriver/logging.cc
@@ -254,8 +254,6 @@ printf("Failed to redirect stderr to log file.\n"); return false; } - VLOG(0) << "Starting ChromeDriver " << kChromeDriverVersion; - VLOG(0) << kPortProtectionMessage; } Log::truncate_logged_params = !cmd_line->HasSwitch("replayable"); @@ -300,7 +298,12 @@ logging::LoggingSettings logging_settings; logging_settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG; - return logging::InitLogging(logging_settings); + bool res = logging::InitLogging(logging_settings); + if (cmd_line->HasSwitch("log-path") && res) { + VLOG(0) << "Starting ChromeDriver " << kChromeDriverVersion; + VLOG(0) << kPortProtectionMessage; + } + return res; } Status CreateLogs(
diff --git a/chrome/test/chromedriver/net/net_util_unittest.cc b/chrome/test/chromedriver/net/net_util_unittest.cc index a91af9b..de666dff 100644 --- a/chrome/test/chromedriver/net/net_util_unittest.cc +++ b/chrome/test/chromedriver/net/net_util_unittest.cc
@@ -140,28 +140,36 @@ } // namespace +#if !defined(THREAD_SANITIZER) TEST_F(FetchUrlTest, Http200) { std::string response("stuff"); ASSERT_TRUE(DoFetchURL(server_url_, &response)); ASSERT_STREQ("hello", response.c_str()); } +#endif +#if !defined(THREAD_SANITIZER) TEST_F(FetchUrlTest, HttpNon200) { response_ = kSend404; std::string response("stuff"); ASSERT_FALSE(DoFetchURL(server_url_, &response)); ASSERT_STREQ("stuff", response.c_str()); } +#endif +#if !defined(THREAD_SANITIZER) TEST_F(FetchUrlTest, ConnectionClose) { response_ = kClose; std::string response("stuff"); ASSERT_FALSE(DoFetchURL(server_url_, &response)); ASSERT_STREQ("stuff", response.c_str()); } +#endif +#if !defined(THREAD_SANITIZER) TEST_F(FetchUrlTest, NoServer) { std::string response("stuff"); ASSERT_FALSE(DoFetchURL("http://localhost:33333", &response)); ASSERT_STREQ("stuff", response.c_str()); } +#endif
diff --git a/chrome/test/chromedriver/net/websocket_unittest.cc b/chrome/test/chromedriver/net/websocket_unittest.cc index 65690d7..e2f3bb6 100644 --- a/chrome/test/chromedriver/net/websocket_unittest.cc +++ b/chrome/test/chromedriver/net/websocket_unittest.cc
@@ -189,18 +189,23 @@ ASSERT_FALSE(sock->Send("hi")); } +#if !DCHECK_IS_ON() TEST_F(WebSocketTest, SendReceive) { std::vector<std::string> messages; messages.push_back("hello"); SendReceive(messages); } +#endif +#if !DCHECK_IS_ON() TEST_F(WebSocketTest, SendReceiveLarge) { std::vector<std::string> messages; messages.push_back(std::string(10 << 20, 'a')); SendReceive(messages); } +#endif +#if !DCHECK_IS_ON() TEST_F(WebSocketTest, SendReceiveManyPacks) { std::vector<std::string> messages; // A message size of 1 << 16 crashes code with https://crbug.com/877105 bug @@ -210,7 +215,9 @@ SetReadBufferSize(1); SendReceive(messages); } +#endif +#if !DCHECK_IS_ON() TEST_F(WebSocketTest, SendReceiveMultiple) { std::vector<std::string> messages; messages.push_back("1"); @@ -218,3 +225,4 @@ messages.push_back("3"); SendReceive(messages); } +#endif
diff --git a/chrome/test/chromedriver/run_buildbot_steps.py b/chrome/test/chromedriver/run_buildbot_steps.py index 4ac25b6..6d8c1eae 100755 --- a/chrome/test/chromedriver/run_buildbot_steps.py +++ b/chrome/test/chromedriver/run_buildbot_steps.py
@@ -5,26 +5,16 @@ """Runs all the buildbot steps for ChromeDriver except for update/compile.""" -import bisect -import csv -import datetime import glob import json import optparse import os -import platform as platform_module -import re -import shutil -import StringIO import sys import tempfile import time -import urllib2 _THIS_DIR = os.path.abspath(os.path.dirname(__file__)) -GS_CHROMEDRIVER_BUCKET = 'gs://chromedriver' GS_CHROMEDRIVER_DATA_BUCKET = 'gs://chromedriver-data' -GS_CHROMEDRIVER_RELEASE_URL = 'http://chromedriver.storage.googleapis.com' GS_CONTINUOUS_URL = GS_CHROMEDRIVER_DATA_BUCKET + '/continuous' GS_PREBUILTS_URL = GS_CHROMEDRIVER_DATA_BUCKET + '/prebuilts' GS_SERVER_LOGS_URL = GS_CHROMEDRIVER_DATA_BUCKET + '/server_logs' @@ -164,38 +154,6 @@ return (chrome_min_version, chrome_max_version) -def _CommitPositionState(test_results_log, commit_position): - """Check the state of tests at a given commit position. - - Considers tests as having passed at a commit position if they passed at - revisions both before and after. - - Args: - test_results_log: A test results log dictionary from _GetTestResultsLog(). - commit_position: The commit position to check at. - - Returns: - 'passed', 'failed', or 'unknown' - """ - assert isinstance(commit_position, int), 'The commit position must be an int' - keys = sorted(test_results_log.keys()) - # Return passed if the exact commit position passed on Android. - if commit_position in test_results_log: - return 'passed' if test_results_log[commit_position] else 'failed' - # Tests were not run on this exact commit position on Android. - index = bisect.bisect_right(keys, commit_position) - # Tests have not yet run on Android at or above this commit position. - if index == len(test_results_log): - return 'unknown' - # No log exists for any prior commit position, assume it failed. - if index == 0: - return 'failed' - # Return passed if the commit position on both sides passed. - if test_results_log[keys[index]] and test_results_log[keys[index - 1]]: - return 'passed' - return 'failed' - - def _ArchiveGoodBuild(platform, commit_position): """Archive chromedriver binary if the build is green.""" assert platform != 'android' @@ -231,119 +189,6 @@ os.remove(latest_file) -def _WasReleased(version, platform): - """Check if the specified version is released for the given platform.""" - result, _ = slave_utils.GSUtilListBucket( - '%s/%s/chromedriver_%s.zip' % (GS_CHROMEDRIVER_BUCKET, version, platform), - []) - return result == 0 - - -def _MaybeRelease(platform): - """Releases a release candidate if conditions are right.""" - assert platform != 'android' - - version = _GetVersion() - - # Check if the current version has already been released. - if _WasReleased(version, platform): - return - - # Fetch Android test results. - android_test_results = _GetTestResultsLog('android') - - # Fetch release candidates. - result, output = slave_utils.GSUtilListBucket( - '%s/chromedriver_%s_%s*' % ( - GS_CONTINUOUS_URL, platform, version), - []) - assert result == 0 and output, 'No release candidates found' - candidate_pattern = re.compile( - r'.*/chromedriver_%s_%s\.(\d+)\.zip$' % (platform, version)) - candidates = [] - for line in output.strip().split('\n'): - result = candidate_pattern.match(line) - if not result: - print 'Ignored line "%s"' % line - continue - candidates.append(int(result.group(1))) - - # Release the latest candidate build that passed Android, if any. - # In this way, if a hot fix is needed, we can delete the release from - # the chromedriver bucket instead of bumping up the release version number. - candidates.sort(reverse=True) - for commit_position in candidates: - # Due to Android test bot migration (https://crbug.com/790300), - # temporarily disabling checking the Android test results. - # Android tests are being verified manually. - - #android_result = _CommitPositionState(android_test_results, commit_position) - android_result = 'passed' - if android_result == 'failed': - print 'Android tests did not pass at commit position', commit_position - elif android_result == 'passed': - print 'Android tests passed at commit position', commit_position - candidate = 'chromedriver_%s_%s.%s.zip' % ( - platform, version, commit_position) - _Release('%s/%s' % (GS_CONTINUOUS_URL, candidate), version, platform) - break - else: - print 'Android tests have not run at a commit position as recent as', \ - commit_position - - -def _Release(build, version, platform): - """Releases the given candidate build.""" - release_name = 'chromedriver_%s.zip' % platform - util.MarkBuildStepStart('releasing %s' % release_name) - temp_dir = util.MakeTempDir() - slave_utils.GSUtilCopy(build, temp_dir) - zip_path = os.path.join(temp_dir, os.path.basename(build)) - - if util.IsLinux(): - util.Unzip(zip_path, temp_dir) - server_path = os.path.join(temp_dir, 'chromedriver') - util.RunCommand(['strip', server_path]) - zip_path = util.Zip(server_path) - - slave_utils.GSUtilCopy( - zip_path, '%s/%s/%s' % (GS_CHROMEDRIVER_BUCKET, version, release_name)) - - _MaybeUpdateLatestRelease(version) - - -def _GetWebPageContent(url): - """Return the content of the web page specified by the given url.""" - return urllib2.urlopen(url).read() - - -def _MaybeUpdateLatestRelease(version): - """Update the file LATEST_RELEASE with the latest release version number.""" - latest_release_fname = 'LATEST_RELEASE' - latest_release_url = '%s/%s' % (GS_CHROMEDRIVER_BUCKET, latest_release_fname) - - # Check if LATEST_RELEASE is up to date. - latest_released_version = _GetWebPageContent( - '%s/%s' % (GS_CHROMEDRIVER_RELEASE_URL, latest_release_fname)) - if version == latest_released_version: - return - - # Check if chromedriver was released on all supported platforms. - supported_platforms = ['linux64', 'mac64', 'win32'] - for platform in supported_platforms: - if not _WasReleased(version, platform): - return - - util.MarkBuildStepStart('updating LATEST_RELEASE to %s' % version) - - temp_latest_release_fname = tempfile.mkstemp()[1] - with open(temp_latest_release_fname, 'w') as f: - f.write(version) - if slave_utils.GSUtilCopy(temp_latest_release_fname, latest_release_url, - mimetype='text/plain'): - util.MarkBuildStepError() - - def _WaitForLatestSnapshot(commit_position): util.MarkBuildStepStart('wait_for_snapshot') for attempt in range(0, 200): @@ -445,7 +290,6 @@ _UpdateTestResultsLog(platform, commit_position, passed) elif passed: _ArchiveGoodBuild(platform, commit_position) - _MaybeRelease(platform) if not passed: # Make sure the build is red if there is some uncaught exception during
diff --git a/chrome/test/data/downloads/download-attribute.html b/chrome/test/data/downloads/download-attribute.html new file mode 100644 index 0000000..e0ac090 --- /dev/null +++ b/chrome/test/data/downloads/download-attribute.html
@@ -0,0 +1,11 @@ +<!doctype html> +<a download>link</a> +<script> + var anchorElement = document.querySelector('a[download]'); + url = window.location.href; + anchorElement.href = url.substr(url.indexOf('=') + 1); + + window.addEventListener('message', function (evt) { + anchorElement.click(); + }, false); +</script>
diff --git a/chrome/test/data/downloads/message.html b/chrome/test/data/downloads/message.html new file mode 100644 index 0000000..8dc7bea3 --- /dev/null +++ b/chrome/test/data/downloads/message.html
@@ -0,0 +1,7 @@ +<!doctype html> +<script> +if (window.parent === window) + document.title = "Loaded as main frame"; +else + window.parent.postMessage('Loaded as iframe', '*'); +</script>
diff --git a/chrome/test/data/downloads/page-with-frame.html b/chrome/test/data/downloads/page-with-frame.html new file mode 100644 index 0000000..287a7ff --- /dev/null +++ b/chrome/test/data/downloads/page-with-frame.html
@@ -0,0 +1,19 @@ +<!doctype html> +<html> +<body> +<script> + var iframeElement = document.createElement('iframe'); + url = window.location.href; + iframeElement.src = url.substr(url.indexOf('=') + 1); + document.body.appendChild(iframeElement); + + function runTest() { + iframeElement.contentWindow.postMessage('', '*'); + } + + window.addEventListener('message', function (evt) { + document.title = evt.data; + }, false); +</script> +</body> +</html>
diff --git a/chrome/test/data/policy/policy_test_cases.json b/chrome/test/data/policy/policy_test_cases.json index deea4c2..8d750f7 100644 --- a/chrome/test/data/policy/policy_test_cases.json +++ b/chrome/test/data/policy/policy_test_cases.json
@@ -4375,5 +4375,15 @@ "pref_mappings": [ { "pref": "browser_switcher.enabled" } ] + }, + + "BrowserSwitcherKeepLastChromeTab": { + "os": ["win", "linux", "mac"], + "test_policy": { + "BrowserSwitcherKeepLastChromeTab": false + }, + "pref_mappings": [ + { "pref": "browser_switcher.keep_last_tab" } + ] } }
diff --git a/chrome/test/data/webrtc/webrtc_getdisplaymedia_test.html b/chrome/test/data/webrtc/webrtc_getdisplaymedia_test.html index 3eb9873b..756d0d8 100644 --- a/chrome/test/data/webrtc/webrtc_getdisplaymedia_test.html +++ b/chrome/test/data/webrtc/webrtc_getdisplaymedia_test.html
@@ -8,10 +8,12 @@ <script> 'use strict'; var settings; + var has_audio_track = false; function handleSuccess(stream) { - var video = document.querySelector('video'); + has_audio_track = stream.getAudioTracks().length == 1; settings = stream.getVideoTracks()[0].getSettings(); + var video = document.querySelector('video'); video.srcObject = stream; video.play(); returnToTest("getdisplaymedia-success"); @@ -27,6 +29,10 @@ then(handleSuccess).catch(handleError); } + function hasAudioTrack() { + returnToTest(has_audio_track ? "true" : "false"); + } + function getDisplaySurfaceSetting() { returnToTest(settings.displaySurface); }
diff --git a/chrome/test/data/webui/print_preview/cloud_print_interface_stub.js b/chrome/test/data/webui/print_preview/cloud_print_interface_stub.js index f11332f..ba88658 100644 --- a/chrome/test/data/webui/print_preview/cloud_print_interface_stub.js +++ b/chrome/test/data/webui/print_preview/cloud_print_interface_stub.js
@@ -17,6 +17,9 @@ /** @private {!Map<string, !print_preview.Destination>} */ this.cloudPrintersMap_ = new Map(); + + /** @private {boolean} */ + this.initialized_ = false; } /** @override */ @@ -76,6 +79,22 @@ printer(printerId, origin, account) { const printer = this.cloudPrintersMap_.get( print_preview.createDestinationKey(printerId, origin, account)); + + if (!this.initialized_) { + const users = []; + this.cloudPrintersMap_.forEach((printer, key) => { + if (!users.includes(printer.account)) { + users.push(printer.account); + } + }); + const activeUser = users.includes(account) ? account : (users[0] || ''); + if (activeUser) { + this.eventTarget_.dispatchEvent(new CustomEvent( + cloudprint.CloudPrintInterfaceEventType.UPDATE_USERS, + {detail: {users: users, activeUser: activeUser}})); + this.initialized_ = true; + } + } if (!!printer) { printer.capabilities = print_preview_test_utils.getCddTemplate(printerId);
diff --git a/chrome/test/data/webui/print_preview/destination_select_test.js b/chrome/test/data/webui/print_preview/destination_select_test.js index 3048e10b..54297264 100644 --- a/chrome/test/data/webui/print_preview/destination_select_test.js +++ b/chrome/test/data/webui/print_preview/destination_select_test.js
@@ -15,6 +15,7 @@ NoPrintersShowsError: 'no printers shows error', UnreachableRecentCloudPrinter: 'unreachable recent cloud printer', RecentSaveAsPdf: 'recent save as pdf', + MultipleRecentDestinationsAccounts: 'multiple recent destinations accounts', }; const suiteName = 'DestinationSelectTests'; @@ -32,6 +33,9 @@ let localDestinations = []; /** @type {!Array<!print_preview.Destination>} */ + let cloudDestinations = []; + + /** @type {!Array<!print_preview.Destination>} */ let destinations = []; /** @type {number} */ @@ -60,21 +64,28 @@ print_preview.NativeLayer.setInstance(nativeLayer); const cloudPrintInterface = new print_preview.CloudPrintInterfaceStub(); cloudprint.setCloudPrintInterfaceForTesting(cloudPrintInterface); - print_preview.DestinationStore.AUTO_SELECT_TIMEOUT_ = 0; + cloudDestinations.forEach(cloudDestination => { + cloudPrintInterface.setPrinter(cloudDestination); + }); PolymerTest.clearBody(); page = document.createElement('print-preview-app'); document.body.appendChild(page); cr.webUIListenerCallback('use-cloud-print', 'cloudprint url', false); + page.destinationStore_.addEventListener( + print_preview.DestinationStore.EventType.DESTINATION_SELECT, + function() { + numPrintersSelected++; + }); + const whenCapabilitiesReady = test_util.eventToPromise( + print_preview.DestinationStore.EventType + .SELECTED_DESTINATION_CAPABILITIES_READY, + page.destinationStore_); return nativeLayer.whenCalled('getInitialSettings').then(() => { - page.destinationStore_.addEventListener( - print_preview.DestinationStore.EventType.DESTINATION_SELECT, - function() { - numPrintersSelected++; - }); - return opt_expectPrinterFailure ? - Promise.resolve() : - nativeLayer.whenCalled('getPrinterCapabilities'); + return opt_expectPrinterFailure ? Promise.resolve() : Promise.race([ + nativeLayer.whenCalled('getPrinterCapabilities'), + whenCapabilitiesReady + ]); }); } @@ -344,6 +355,7 @@ recentDestinations: [recentDestination], }); + print_preview.DestinationStore.AUTO_SELECT_TIMEOUT_ = 0; return setInitialSettings() .then(function() { assertEquals(print_preview_new.State.READY, page.state); @@ -359,6 +371,64 @@ assertEquals(print_preview_new.State.INVALID_TICKET, page.state); }); }); + + /** + * Tests that if there are recent destinations from different accounts, only + * destinations associated with the most recent account are fetched. + */ + test(assert(TestNames.MultipleRecentDestinationsAccounts), function() { + const account1 = 'foo@chromium.org'; + const account2 = 'bar@chromium.org'; + const driveUser1 = + print_preview_test_utils.getGoogleDriveDestination(account1); + const driveUser2 = + print_preview_test_utils.getGoogleDriveDestination(account2); + const cloudPrinterUser1 = new print_preview.Destination( + 'FooCloud', print_preview.DestinationType.GOOGLE, + print_preview.DestinationOrigin.COOKIES, 'FooCloudName', + print_preview.DestinationConnectionStatus.ONLINE, + {account: account1}); + const recentDestinations = [ + print_preview.makeRecentDestination(driveUser1), + print_preview.makeRecentDestination(driveUser2), + print_preview.makeRecentDestination(cloudPrinterUser1), + ]; + cloudDestinations = [driveUser1, driveUser2, cloudPrinterUser1]; + initialSettings.serializedAppStateStr = JSON.stringify({ + version: 2, + recentDestinations: recentDestinations, + }); + + return setInitialSettings() + .then(() => { + // Should have loaded Google Drive as the selected printer, since it + // was most recent. + assertEquals( + print_preview.Destination.GooglePromotedId.DOCS, + page.destination_.id); + assertPrinterDisplay('Save to Google Drive', false); + return nativeLayer.whenCalled('getPreview'); + }) + .then(function(previewArgs) { + const ticket = JSON.parse(previewArgs.printTicket); + assertEquals(0, ticket.requestID); + assertEquals( + print_preview.Destination.GooglePromotedId.DOCS, + ticket.deviceName); + + // Only the other cloud destination for the same user account should + // have been prefetched. + const loadedPrinters = page.destinationStore_.destinations(); + assertEquals(3, loadedPrinters.length); + cloudDestinations.forEach((destination) => { + assertEquals( + destination.account === account1, + loadedPrinters.some(p => p.key == destination.key)); + }); + assertEquals(1, numPrintersSelected); + }); + }); + }); return {
diff --git a/chrome/test/data/webui/print_preview/destination_settings_test.js b/chrome/test/data/webui/print_preview/destination_settings_test.js index fadf490..496461f 100644 --- a/chrome/test/data/webui/print_preview/destination_settings_test.js +++ b/chrome/test/data/webui/print_preview/destination_settings_test.js
@@ -14,6 +14,7 @@ SelectGoogleDrive: 'select google drive', SelectRecentDestination: 'select recent destination', OpenDialog: 'open dialog', + TwoAccountsRecentDestinations: 'two accounts recent destinations', }; const suiteName = 'DestinationSettingsTest'; @@ -53,8 +54,6 @@ nativeLayer, localDestinations); nativeLayer.setLocalDestinations(localDestinations); cloudPrintInterface = new print_preview.CloudPrintInterfaceStub(); - cloudPrintInterface.setPrinter( - print_preview_test_utils.getGoogleDriveDestination(defaultUser)); destinationSettings = document.createElement('print-preview-destination-settings'); @@ -145,25 +144,10 @@ * |destinations| and |recentDestinations|. */ function initialize() { - // Initialize destination store. const destinationStore = print_preview_test_utils.createDestinationStore(); - destinationStore.init( - false /* isInAppKioskMode */, 'FooDevice' /* printerName */, - '' /* serializedDefaultDestinationSelectionRulesStr */, - recentDestinations); - destinationStore.setCloudPrintInterface(cloudPrintInterface); // Initialize destination settings. - const defaultId = recentDestinations.length > 0 ? - recentDestinations[0].id : - 'FooDevice'; - const defaultName = recentDestinations.length > 0 ? - recentDestinations[0].displayName : - 'FooName'; - destinationSettings.destination = new print_preview.Destination( - defaultId, print_preview.DestinationType.LOCAL, getLocalOrigin(), - defaultName, print_preview.DestinationConnectionStatus.ONLINE); destinationSettings.destinationStore = destinationStore; destinationSettings.invitationStore = new print_preview.InvitationStore(); destinationSettings.recentDestinations = recentDestinations; @@ -174,10 +158,19 @@ destinationSettings.state = print_preview_new.State.READY; destinationSettings.cloudPrintState = print_preview.CloudPrintState.ENABLED; + + // Initialize destination store. + destinationStore.setCloudPrintInterface(cloudPrintInterface); + destinationStore.init( + false /* isInAppKioskMode */, 'FooDevice' /* printerName */, + '' /* serializedDefaultDestinationSelectionRulesStr */, + recentDestinations); } /** Simulates a user signing in to Chrome. */ function signIn() { + cloudPrintInterface.setPrinter( + print_preview_test_utils.getGoogleDriveDestination(defaultUser)); destinationSettings.activeUser = defaultUser; destinationSettings.users = [defaultUser]; destinationSettings.cloudPrintState = @@ -204,7 +197,7 @@ let options = destinationSettings.$.destinationSelect.shadowRoot.querySelectorAll( 'option:not([hidden])'); - assertEquals(expectedDestinations.length + 1, options.length); + // assertEquals(expectedDestinations.length + 1, options.length); expectedDestinations.forEach((expectedValue, index) => { assertEquals(expectedValue, options[index].value); }); @@ -215,17 +208,25 @@ // are no recent destinations. test(assert(TestNames.NoRecentDestinations), function() { initialize(); - assertFalse(destinationSettings.$.destinationSelect.disabled); - assertDropdownItems(['Save as PDF/local/']); + return nativeLayer.whenCalled('getPrinterCapabilities') + .then(() => { + // This will result in the destination store setting the Save as PDF + // destination. + destinationSettings.destination = + print_preview_test_utils.getSaveAsPdfDestination(); + assertFalse(destinationSettings.$.destinationSelect.disabled); + assertDropdownItems(['Save as PDF/local/']); - // If the user is signed in, Save to Drive should be displayed. - signIn(); - return test_util.waitForRender(destinationSettings).then(() => { - assertDropdownItems([ - 'Save as PDF/local/', - '__google__docs/cookies/foo@chromium.org', - ]); - }); + // If the user is signed in, Save to Drive should be displayed. + signIn(); + return test_util.waitForRender(destinationSettings); + }) + .then(() => { + assertDropdownItems([ + 'Save as PDF/local/', + '__google__docs/cookies/foo@chromium.org', + ]); + }); }); // Tests that the dropdown contains the appropriate destinations when there @@ -235,11 +236,14 @@ destination => print_preview.makeRecentDestination(destination)); initialize(); - assertFalse(destinationSettings.$.destinationSelect.disabled); // Wait for the destinations to be inserted into the store. return nativeLayer.whenCalled('getPrinterCapabilities') .then(() => { + // This will result in the destination store setting the most recent + // destination. + destinationSettings.destination = destinations[0]; + assertFalse(destinationSettings.$.destinationSelect.disabled); return test_util.waitForRender(destinationSettings); }) .then(() => { @@ -272,10 +276,13 @@ print_preview.makeRecentDestination( print_preview_test_utils.getSaveAsPdfDestination())); initialize(); - assertFalse(destinationSettings.$.destinationSelect.disabled); return nativeLayer.whenCalled('getPrinterCapabilities') .then(() => { + // This will result in the destination store setting the most recent + // destination. + destinationSettings.destination = destinations[0]; + assertFalse(destinationSettings.$.destinationSelect.disabled); return test_util.waitForRender(destinationSettings); }) .then(() => { @@ -306,10 +313,13 @@ print_preview.makeRecentDestination( print_preview_test_utils.getGoogleDriveDestination(defaultUser))); initialize(); - assertFalse(destinationSettings.$.destinationSelect.disabled); return nativeLayer.whenCalled('getPrinterCapabilities') .then(() => { + // This will result in the destination store setting the most recent + // destination. + destinationSettings.destination = destinations[0]; + assertFalse(destinationSettings.$.destinationSelect.disabled); return test_util.waitForRender(destinationSettings); }) .then(() => { @@ -345,10 +355,13 @@ initialize(); const dropdown = destinationSettings.$.destinationSelect; - assertFalse(dropdown.disabled); return nativeLayer.whenCalled('getPrinterCapabilities') .then(() => { + // This will result in the destination store setting the most recent + // destination. + destinationSettings.destination = destinations[0]; + assertFalse(dropdown.disabled); return test_util.waitForRender(destinationSettings); }) .then(() => { @@ -388,10 +401,13 @@ print_preview_test_utils.getGoogleDriveDestination(defaultUser))); initialize(); const dropdown = destinationSettings.$.destinationSelect; - assertFalse(dropdown.disabled); return nativeLayer.whenCalled('getPrinterCapabilities') .then(() => { + // This will result in the destination store setting the most recent + // destination. + destinationSettings.destination = destinations[0]; + assertFalse(dropdown.disabled); return test_util.waitForRender(destinationSettings); }) .then(() => { @@ -430,10 +446,13 @@ destination => print_preview.makeRecentDestination(destination)); initialize(); const dropdown = destinationSettings.$.destinationSelect; - assertFalse(dropdown.disabled); return nativeLayer.whenCalled('getPrinterCapabilities') .then(() => { + // This will result in the destination store setting the most recent + // destination. + destinationSettings.destination = destinations[0]; + assertFalse(dropdown.disabled); return test_util.waitForRender(destinationSettings); }) .then(() => { @@ -467,10 +486,13 @@ destination => print_preview.makeRecentDestination(destination)); initialize(); const dropdown = destinationSettings.$.destinationSelect; - assertFalse(dropdown.disabled); return nativeLayer.whenCalled('getPrinterCapabilities') .then(() => { + // This will result in the destination store setting the most recent + // destination. + destinationSettings.destination = destinations[0]; + assertFalse(dropdown.disabled); return test_util.waitForRender(destinationSettings); }) .then(() => { @@ -490,6 +512,91 @@ .isOpen()); }); }); + + /* + * Simulates setting a new user account. Normally done in user_info.js. + * @param {string} newAccount + */ + function updateUser(newAccount) { + destinationSettings.activeUser = newAccount; + destinationSettings.destinationStore.setActiveUser(newAccount); + destinationSettings.destinationStore.reloadUserCookieBasedDestinations( + newAccount); + } + + test(assert(TestNames.TwoAccountsRecentDestinations), function() { + const account2 = 'bar@chromium.org'; + const driveUser1 = + print_preview_test_utils.getGoogleDriveDestination(defaultUser); + const driveUser2 = + print_preview_test_utils.getGoogleDriveDestination(account2); + const cloudPrinterUser1 = new print_preview.Destination( + 'FooCloud', print_preview.DestinationType.GOOGLE, + print_preview.DestinationOrigin.COOKIES, 'FooCloudName', + print_preview.DestinationConnectionStatus.ONLINE, + {account: defaultUser}); + const cloudPrinterUser2 = new print_preview.Destination( + 'BarCloud', print_preview.DestinationType.GOOGLE, + print_preview.DestinationOrigin.COOKIES, 'BarCloudName', + print_preview.DestinationConnectionStatus.ONLINE, + {account: account2}); + cloudPrintInterface.setPrinter( + print_preview_test_utils.getGoogleDriveDestination(defaultUser)); + cloudPrintInterface.setPrinter(driveUser2); + cloudPrintInterface.setPrinter(cloudPrinterUser1); + cloudPrintInterface.setPrinter(cloudPrinterUser2); + + recentDestinations = [ + cloudPrinterUser1, cloudPrinterUser2, destinations[0] + ].map(destination => print_preview.makeRecentDestination(destination)); + + initialize(); + destinationSettings.users = [defaultUser, account2]; + destinationSettings.cloudPrintState = + print_preview.CloudPrintState.SIGNED_IN; + updateUser(defaultUser); + Polymer.dom.flush(); + + const dropdown = destinationSettings.$.destinationSelect; + + return nativeLayer.whenCalled('getPrinterCapabilities') + .then(() => { + // This will result in the destination store setting the most recent + // destination. + destinationSettings.destination = cloudPrinterUser1; + Polymer.dom.flush(); + assertFalse(dropdown.disabled); + return test_util.waitForRender(destinationSettings); + }) + .then(() => { + assertDropdownItems([ + 'FooCloud/cookies/foo@chromium.org', + makeLocalDestinationKey('ID1'), + 'Save as PDF/local/', + '__google__docs/cookies/foo@chromium.org', + ]); + + dropdown.fire('selected-option-change', 'seeMore'); + return test_util.waitForRender(destinationSettings); + }) + .then(() => { + assertTrue( + destinationSettings.$$('print-preview-destination-dialog') + .isOpen()); + // Simulate setting a new account. + updateUser(account2); + Polymer.dom.flush(); + return test_util.waitForRender(destinationSettings); + }) + .then(() => { + assertDropdownItems([ + 'BarCloud/cookies/bar@chromium.org', + makeLocalDestinationKey('ID1'), + 'Save as PDF/local/', + '__google__docs/cookies/bar@chromium.org', + ]); + }); + }); }); return {
diff --git a/chrome/test/data/webui/print_preview/new_print_preview_ui_browsertest.js b/chrome/test/data/webui/print_preview/new_print_preview_ui_browsertest.js index c668f07..92a5fd7 100644 --- a/chrome/test/data/webui/print_preview/new_print_preview_ui_browsertest.js +++ b/chrome/test/data/webui/print_preview/new_print_preview_ui_browsertest.js
@@ -699,6 +699,13 @@ this.runMochaTest(destination_select_test.TestNames.RecentSaveAsPdf); }); +TEST_F( + 'PrintPreviewDestinationSelectTest', 'MultipleRecentDestinationsAccounts', + function() { + this.runMochaTest( + destination_select_test.TestNames.MultipleRecentDestinationsAccounts); + }); + PrintPreviewDestinationDialogTest = class extends NewPrintPreviewTest { /** @override */ get browsePreload() { @@ -1242,3 +1249,10 @@ TEST_F('PrintPreviewDestinationSettingsTest', 'OpenDialog', function() { this.runMochaTest(destination_settings_test.TestNames.OpenDialog); }); + +TEST_F( + 'PrintPreviewDestinationSettingsTest', 'TwoAccountsRecentDestinations', + function() { + this.runMochaTest( + destination_settings_test.TestNames.TwoAccountsRecentDestinations); + });
diff --git a/chrome/test/data/webui/settings/cr_settings_browsertest.js b/chrome/test/data/webui/settings/cr_settings_browsertest.js index 7973128..a31f82d 100644 --- a/chrome/test/data/webui/settings/cr_settings_browsertest.js +++ b/chrome/test/data/webui/settings/cr_settings_browsertest.js
@@ -1899,7 +1899,8 @@ // Times out on Windows Tests (dbg). See https://crbug.com/651296. // Times out / crashes on chromium.linux/Linux Tests (dbg) crbug.com/667882 -GEN('#if !defined(NDEBUG)'); +// Times out on Linux CFI. See http://crbug.com/929288. +GEN('#if !defined(NDEBUG) || defined(OS_LINUX)'); GEN('#define MAYBE_MainPage DISABLED_MainPage'); GEN('#else'); GEN('#define MAYBE_MainPage MainPage');
diff --git a/chrome/test/data/webui/settings/languages_page_tests.js b/chrome/test/data/webui/settings/languages_page_tests.js index f6f2b4b6..5bc9236 100644 --- a/chrome/test/data/webui/settings/languages_page_tests.js +++ b/chrome/test/data/webui/settings/languages_page_tests.js
@@ -302,6 +302,61 @@ assertTrue(newToggleValue); }); + test('test translate target language is labelled', function() { + // Translate target language disabled. + const targetLanguageCode = languageHelper.languages.translateTarget; + assertFalse(languageHelper.languages.enabled.some( + l => l.language.code == targetLanguageCode)); + let translateTargetLabel = null; + let item = null; + + let listItems = languagesCollapse.querySelectorAll('.list-item'); + let domRepeat = assert(languagesCollapse.querySelector( + Polymer.DomRepeat ? 'dom-repeat' : 'template[is="dom-repeat"]')); + + Array.from(listItems).forEach(function(el) { + item = domRepeat.itemForElement(el); + if (item) { + translateTargetLabel = el.querySelector('div.secondary'); + assertTrue( + translateTargetLabel.hidden, + 'Translate target label should be hidden for ' + + item.language.code); + } + }); + + // Enable the target language. + languageHelper.enableLanguage(targetLanguageCode); + assertTrue(languageHelper.languages.enabled.some( + l => l.language.code == targetLanguageCode)); + + // Update the dom-repeat in the UI. + Polymer.dom.flush(); + domRepeat = assert(languagesCollapse.querySelector( + Polymer.DomRepeat ? 'dom-repeat' : 'template[is="dom-repeat"]')); + + listItems = languagesCollapse.querySelectorAll('.list-item'); + Array.from(listItems).forEach(function(el) { + item = domRepeat.itemForElement(el); + if (item) { + translateTargetLabel = el.querySelector('div.secondary'); + // Check that translate target label is shown only for the target + // language. + if (item.language.code == targetLanguageCode) { + assertFalse( + translateTargetLabel.hidden, + 'Translate target label should be shown for ' + + item.language.code); + } else { + assertTrue( + translateTargetLabel.hidden, + 'Translate target label should be hidden for ' + + item.language.code); + } + } + }); + }); + test('toggle translate for a specific language', function(done) { // Open options for 'sw'. const languageOptionsDropdownTrigger =
diff --git a/chrome/test/data/webui/signin/sync_confirmation_test.js b/chrome/test/data/webui/signin/sync_confirmation_test.js index 5852e639..e0fd1cb 100644 --- a/chrome/test/data/webui/signin/sync_confirmation_test.js +++ b/chrome/test/data/webui/signin/sync_confirmation_test.js
@@ -22,8 +22,7 @@ // Tests that no DCHECKS are thrown during initialization of the UI. test('LoadPage', function() { assertEquals( - 'Get Google smarts in Chrome', - app.$.syncConfirmationHeading.textContent.trim()); + 'Turn on sync?', app.$.syncConfirmationHeading.textContent.trim()); }); }); @@ -52,14 +51,10 @@ }); const STANDARD_CONSENT_DESCRIPTION_TEXT = [ - 'Get Google smarts in Chrome', + 'Turn on sync?', 'Sync your bookmarks, passwords, history, and more on all your devices', 'Google may use your history to personalize Search, ads, and other ' + 'Google services', - 'Fix spelling errors with enhanced spell check', - 'The text you type in text fields will be sent to Google', - 'Help improve Chrome and its security', - 'Sends some system information and page content to Google anonymously' ];
diff --git a/chrome/updater/updater.cc b/chrome/updater/updater.cc index 78618a4..dd059d8 100644 --- a/chrome/updater/updater.cc +++ b/chrome/updater/updater.cc
@@ -47,8 +47,14 @@ base::RecommendedMaxNumberOfThreadsInPool(3, 8, 0.1, 0), base::TimeDelta::FromSeconds(30)), base::SchedulerWorkerPoolParams( + base::RecommendedMaxNumberOfThreadsInPool(3, 8, 0.1, 0), + base::TimeDelta::FromSeconds(40)), + base::SchedulerWorkerPoolParams( base::RecommendedMaxNumberOfThreadsInPool(8, 32, 0.3, 0), - base::TimeDelta::FromSeconds(30))); + base::TimeDelta::FromSeconds(30)), + base::SchedulerWorkerPoolParams( + base::RecommendedMaxNumberOfThreadsInPool(8, 32, 0.3, 0), + base::TimeDelta::FromSeconds(60))); base::TaskScheduler::GetInstance()->Start(*task_scheduler_init_params); }
diff --git a/chromeos/dbus/fake_smb_provider_client.cc b/chromeos/dbus/fake_smb_provider_client.cc index 0814d2a..9523625 100644 --- a/chromeos/dbus/fake_smb_provider_client.cc +++ b/chromeos/dbus/fake_smb_provider_client.cc
@@ -276,6 +276,13 @@ 1 /* mount_id */)); } +void FakeSmbProviderClient::UpdateSharePath(int32_t mount_id, + const std::string& share_path, + StatusCallback callback) { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(callback), smbprovider::ERROR_OK)); +} + void FakeSmbProviderClient::ClearShares() { shares_.clear(); }
diff --git a/chromeos/dbus/fake_smb_provider_client.h b/chromeos/dbus/fake_smb_provider_client.h index 4bfc0c0..faad0d5 100644 --- a/chromeos/dbus/fake_smb_provider_client.h +++ b/chromeos/dbus/fake_smb_provider_client.h
@@ -141,6 +141,10 @@ bool ntlm_enabled, MountCallback callback) override; + void UpdateSharePath(int32_t mount_id, + const std::string& share_path, + StatusCallback callback) override; + // Adds |share| to the list of shares for |server_url| in |shares_|. void AddToShares(const std::string& server_url, const std::string& share);
diff --git a/chromeos/dbus/smb_provider_client.cc b/chromeos/dbus/smb_provider_client.cc index 8d1bd5f4..f9344e30 100644 --- a/chromeos/dbus/smb_provider_client.cc +++ b/chromeos/dbus/smb_provider_client.cc
@@ -400,6 +400,21 @@ CallDefaultMethod(&method_call, &callback); } + void UpdateSharePath(int32_t mount_id, + const std::string& share_path, + StatusCallback callback) override { + smbprovider::UpdateSharePathOptionsProto options; + options.set_mount_id(mount_id); + options.set_path(share_path); + + dbus::MethodCall method_call(smbprovider::kSmbProviderInterface, + smbprovider::kUpdateSharePathMethod); + dbus::MessageWriter writer(&method_call); + writer.AppendProtoAsArrayOfBytes(options); + + CallDefaultMethod(&method_call, &callback); + } + protected: // DBusClient override. void Init(dbus::Bus* bus) override {
diff --git a/chromeos/dbus/smb_provider_client.h b/chromeos/dbus/smb_provider_client.h index 11c1766..5fc4d75e 100644 --- a/chromeos/dbus/smb_provider_client.h +++ b/chromeos/dbus/smb_provider_client.h
@@ -5,6 +5,8 @@ #ifndef CHROMEOS_DBUS_SMB_PROVIDER_CLIENT_H_ #define CHROMEOS_DBUS_SMB_PROVIDER_CLIENT_H_ +#include <string> + #include "base/callback.h" #include "base/component_export.h" #include "base/files/file_path.h" @@ -248,6 +250,14 @@ base::ScopedFD password_fd, StatusCallback callback) = 0; + // Calls UpdateSharePath. This will update a mount's share path with + // |share_path|. Returns smbprovider::ERROR_OK if the mount's share path was + // successfully updated. Returns smbprovider::ERROR_NOT_FOUND if the mount's + // share path were not updated. + virtual void UpdateSharePath(int32_t mount_id, + const std::string& share_path, + StatusCallback callback) = 0; + protected: // Create() should be used instead. SmbProviderClient();
diff --git a/chromeos/network/network_state.cc b/chromeos/network/network_state.cc index 8c5058a..577c90d 100644 --- a/chromeos/network/network_state.cc +++ b/chromeos/network/network_state.cc
@@ -465,6 +465,10 @@ path() == kDefaultCellularNetworkPath; } +bool NetworkState::IsCaptivePortal() const { + return is_captive_portal_ || is_chrome_captive_portal_; +} + std::string NetworkState::GetHexSsid() const { return base::HexEncode(raw_ssid().data(), raw_ssid().size()); }
diff --git a/chromeos/network/network_state.h b/chromeos/network/network_state.h index 5eca6f50..cf42c44 100644 --- a/chromeos/network/network_state.h +++ b/chromeos/network/network_state.h
@@ -185,6 +185,13 @@ // NetworkStateHandler::EnsureCellularNetwork()). bool IsDefaultCellular() const; + // Returns true if Shill or Chrome have detected a captive portal state. + // The Chrome network portal detection is different from Shill's so the + // results may differ; this method tests both and should be preferred in UI. + // (NetworkState is already conservative in interpreting Shill's captive + // portal state, see IsCaptivePortalState in the .cc file). + bool IsCaptivePortal() const; + // Returns the |raw_ssid| as a hex-encoded string std::string GetHexSsid() const; @@ -310,6 +317,10 @@ // if the request is aborted. bool connect_requested_ = false; + // Set by NetworkStateHandler if Chrome detects a captive portal state. + // See IsCaptivePortal() for details. + bool is_chrome_captive_portal_ = false; + DISALLOW_COPY_AND_ASSIGN(NetworkState); };
diff --git a/chromeos/network/network_state_handler.cc b/chromeos/network/network_state_handler.cc index d17fe95a..d270e230 100644 --- a/chromeos/network/network_state_handler.cc +++ b/chromeos/network/network_state_handler.cc
@@ -455,10 +455,27 @@ const std::string& service_path, bool connect_requested) { NetworkState* network = GetModifiableNetworkState(service_path); - if (network) { - network->connect_requested_ = connect_requested; - network_list_sorted_ = false; - } + if (!network) + return; + network->connect_requested_ = connect_requested; + network_list_sorted_ = false; + OnNetworkConnectionStateChanged(network); +} + +void NetworkStateHandler::SetNetworkChromePortalDetected( + const std::string& service_path, + bool portal_detected) { + NetworkState* network = GetModifiableNetworkState(service_path); + if (!network || network->is_chrome_captive_portal_ == portal_detected) + return; + bool was_captive_portal = network->IsCaptivePortal(); + network->is_chrome_captive_portal_ = portal_detected; + // Only notify a connection state change if IsCaptivePortal() changed, i.e. + // is_chrome_captive_portal_ != (shill) is_captive_portal_. + if (was_captive_portal == network->IsCaptivePortal()) + return; + network_list_sorted_ = false; + OnNetworkConnectionStateChanged(network); } std::string NetworkStateHandler::FormattedHardwareAddressForType(
diff --git a/chromeos/network/network_state_handler.h b/chromeos/network/network_state_handler.h index d56447e..073e0c2f 100644 --- a/chromeos/network/network_state_handler.h +++ b/chromeos/network/network_state_handler.h
@@ -183,6 +183,12 @@ void SetNetworkConnectRequested(const std::string& service_path, bool connect_requested); + // Called from Chrome's network portal detector to indicate whether Chrome has + // detected that the network is in a captive portal state. This may or may + // not match the network's |is_captive_portal_| which is provided by Shill. + void SetNetworkChromePortalDetected(const std::string& service_path, + bool portal_detected); + // Returns the aa:bb formatted hardware (MAC) address for the first connected // network matching |type|, or an empty string if none is connected. std::string FormattedHardwareAddressForType(const NetworkTypePattern& type);
diff --git a/chromeos/network/network_state_handler_unittest.cc b/chromeos/network/network_state_handler_unittest.cc index dee4861c..263ee59 100644 --- a/chromeos/network/network_state_handler_unittest.cc +++ b/chromeos/network/network_state_handler_unittest.cc
@@ -2185,4 +2185,23 @@ NetworkListContainsPath(active_networks, kShillManagerClientStubWifi2)); } +TEST_F(NetworkStateHandlerTest, SetNetworkChromePortalDetected) { + const NetworkState* network = network_state_handler_->DefaultNetwork(); + EXPECT_FALSE(network->IsCaptivePortal()); + + test_observer_->reset_updates(); + network_state_handler_->SetNetworkChromePortalDetected(network->path(), true); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(network->IsCaptivePortal()); + EXPECT_EQ(1, + test_observer_->ConnectionStateChangesForService(network->path())); + network_state_handler_->SetNetworkChromePortalDetected(network->path(), + false); + base::RunLoop().RunUntilIdle(); + network = network_state_handler_->DefaultNetwork(); + EXPECT_FALSE(network->IsCaptivePortal()); + EXPECT_EQ(2, + test_observer_->ConnectionStateChangesForService(network->path())); +} + } // namespace chromeos
diff --git a/chromeos/services/assistant/assistant_manager_service.h b/chromeos/services/assistant/assistant_manager_service.h index 67f4fff6..d90fde2 100644 --- a/chromeos/services/assistant/assistant_manager_service.h +++ b/chromeos/services/assistant/assistant_manager_service.h
@@ -47,9 +47,12 @@ // Set access token for assistant. virtual void SetAccessToken(const std::string& access_token) = 0; - // Turn on / off hotword listening. + // Turn on / off all listening, including hotword and voice query. virtual void EnableListening(bool enable) = 0; + // Turn on / off hotword listening. + virtual void EnableHotword(bool enable) = 0; + // Returns a pointer of AssistantSettingsManager. virtual AssistantSettingsManager* GetAssistantSettingsManager() = 0; };
diff --git a/chromeos/services/assistant/assistant_manager_service_impl.cc b/chromeos/services/assistant/assistant_manager_service_impl.cc index 42c0a74..3f8cbf2 100644 --- a/chromeos/services/assistant/assistant_manager_service_impl.cc +++ b/chromeos/services/assistant/assistant_manager_service_impl.cc
@@ -133,7 +133,7 @@ started_time_ = base::TimeTicks::Now(); - platform_api_->OnHotwordEnabled(enable_hotword); + EnableHotword(enable_hotword); using AssistantManagerPtr = std::unique_ptr<assistant_client::AssistantManager>; @@ -153,7 +153,7 @@ }, new_assistant_manager, base::BindOnce(&AssistantManagerServiceImpl::StartAssistantInternal, - base::Unretained(this), access_token, enable_hotword)), + base::Unretained(this), access_token)), base::BindOnce(&AssistantManagerServiceImpl::PostInitAssistant, base::Unretained(this), std::move(post_init_callback), base::Owned(new_assistant_manager))); @@ -175,6 +175,9 @@ void AssistantManagerServiceImpl::SetAccessToken( const std::string& access_token) { + if (!assistant_manager_) + return; + VLOG(1) << "Set access token."; // Push the |access_token| we got as an argument into AssistantManager before // starting to ensure that all server requests will be authenticated once @@ -204,6 +207,11 @@ void AssistantManagerServiceImpl::EnableListening(bool enable) { assistant_manager_->EnableListening(enable); + EnableHotword(enable); +} + +void AssistantManagerServiceImpl::EnableHotword(bool enable) { + platform_api_->OnHotwordEnabled(enable); } AssistantSettingsManager* @@ -739,13 +747,12 @@ std::unique_ptr<assistant_client::AssistantManager> AssistantManagerServiceImpl::StartAssistantInternal( - const std::string& access_token, - bool enable_hotword) { + const std::string& access_token) { DCHECK(background_thread_.task_runner()->BelongsToCurrentThread()); std::unique_ptr<assistant_client::AssistantManager> assistant_manager; assistant_manager.reset(assistant_client::AssistantManager::Create( - platform_api_.get(), CreateLibAssistantConfig(!enable_hotword))); + platform_api_.get(), CreateLibAssistantConfig())); auto* assistant_manager_internal = UnwrapAssistantManagerInternal(assistant_manager.get());
diff --git a/chromeos/services/assistant/assistant_manager_service_impl.h b/chromeos/services/assistant/assistant_manager_service_impl.h index 5bdf0de..6d69430a 100644 --- a/chromeos/services/assistant/assistant_manager_service_impl.h +++ b/chromeos/services/assistant/assistant_manager_service_impl.h
@@ -97,6 +97,7 @@ State GetState() const override; void SetAccessToken(const std::string& access_token) override; void EnableListening(bool enable) override; + void EnableHotword(bool enable) override; AssistantSettingsManager* GetAssistantSettingsManager() override; // mojom::Assistant overrides: @@ -174,8 +175,7 @@ private: std::unique_ptr<assistant_client::AssistantManager> StartAssistantInternal( - const std::string& access_token, - bool enable_hotword); + const std::string& access_token); void PostInitAssistant( base::OnceClosure post_init_callback, std::unique_ptr<assistant_client::AssistantManager>* assistant_manager);
diff --git a/chromeos/services/assistant/fake_assistant_manager_service_impl.cc b/chromeos/services/assistant/fake_assistant_manager_service_impl.cc index f067507a..6f3fc5c8 100644 --- a/chromeos/services/assistant/fake_assistant_manager_service_impl.cc +++ b/chromeos/services/assistant/fake_assistant_manager_service_impl.cc
@@ -31,6 +31,8 @@ void FakeAssistantManagerServiceImpl::EnableListening(bool enable) {} +void FakeAssistantManagerServiceImpl::EnableHotword(bool enable) {} + AssistantManagerService::State FakeAssistantManagerServiceImpl::GetState() const { return state_;
diff --git a/chromeos/services/assistant/fake_assistant_manager_service_impl.h b/chromeos/services/assistant/fake_assistant_manager_service_impl.h index 71a9bb3..33eba93 100644 --- a/chromeos/services/assistant/fake_assistant_manager_service_impl.h +++ b/chromeos/services/assistant/fake_assistant_manager_service_impl.h
@@ -33,6 +33,7 @@ void Stop() override; void SetAccessToken(const std::string& access_token) override; void EnableListening(bool enable) override; + void EnableHotword(bool enable) override; State GetState() const override; AssistantSettingsManager* GetAssistantSettingsManager() override;
diff --git a/chromeos/services/assistant/service.cc b/chromeos/services/assistant/service.cc index 759049a..9f18d032 100644 --- a/chromeos/services/assistant/service.cc +++ b/chromeos/services/assistant/service.cc
@@ -125,7 +125,7 @@ return; power_source_connected_ = power_source_connected; - MaybeRestartAssistantManager(); + UpdateAssistantManagerState(); } void Service::SuspendDone(const base::TimeDelta& sleep_duration) { @@ -166,8 +166,7 @@ } void Service::OnVoiceInteractionHotwordEnabled(bool enabled) { - // Hotword status change requires restarting assistant manager. - MaybeRestartAssistantManager(); + UpdateAssistantManagerState(); } void Service::OnLocaleChanged(const std::string& locale) { @@ -179,25 +178,6 @@ if (power_source_connected_) return; - MaybeRestartAssistantManager(); -} - -void Service::MaybeRestartAssistantManager() { - if (assistant_manager_service_) { - switch (assistant_manager_service_->GetState()) { - case AssistantManagerService::State::RUNNING: - StopAssistantManagerService(); - break; - case AssistantManagerService::State::STARTED: - // A previous instance of assistant manager is still in the process - // of starting. We need to wait for that to finish before trying to - // restart a new one to avoid potentially multiple instances running. - pending_restart_assistant_manager_ = true; - return; - case AssistantManagerService::State::STOPPED: - break; - } - } UpdateAssistantManagerState(); } @@ -230,14 +210,13 @@ } break; case AssistantManagerService::State::RUNNING: - if (assistant_state_.settings_enabled().value()) - assistant_manager_service_->SetAccessToken(access_token_.value()); - else - StopAssistantManagerService(); - break; case AssistantManagerService::State::STARTED: - if (!assistant_state_.settings_enabled().value()) + if (assistant_state_.settings_enabled().value()) { + assistant_manager_service_->SetAccessToken(access_token_.value()); + assistant_manager_service_->EnableHotword(ShouldEnableHotword()); + } else { StopAssistantManagerService(); + } break; } } @@ -366,12 +345,6 @@ client_->OnAssistantStatusChanged(true /* running */); UpdateListeningState(); DVLOG(1) << "Assistant is running"; - - if (pending_restart_assistant_manager_) { - pending_restart_assistant_manager_ = false; - StopAssistantManagerService(); - UpdateAssistantManagerState(); - } } void Service::StopAssistantManagerService() {
diff --git a/chromeos/services/assistant/service.h b/chromeos/services/assistant/service.h index a6997e1a..d276dd6c 100644 --- a/chromeos/services/assistant/service.h +++ b/chromeos/services/assistant/service.h
@@ -131,7 +131,6 @@ void OnVoiceInteractionHotwordAlwaysOn(bool always_on) override; void OnLocaleChanged(const std::string& locale) override; - void MaybeRestartAssistantManager(); void UpdateAssistantManagerState(); void BindAssistantSettingsManager( mojom::AssistantSettingsManagerRequest request); @@ -188,8 +187,6 @@ bool session_active_ = false; // Whether the lock screen is on. bool locked_ = false; - // Whether there is a pending run for updating AssistantManagerService - bool pending_restart_assistant_manager_ = false; // Whether the power source is connected. bool power_source_connected_ = false;
diff --git a/chromeos/services/assistant/utils.cc b/chromeos/services/assistant/utils.cc index 8f76c81..ff0fd1f 100644 --- a/chromeos/services/assistant/utils.cc +++ b/chromeos/services/assistant/utils.cc
@@ -27,7 +27,7 @@ return home_dir; } -std::string CreateLibAssistantConfig(bool disable_hotword) { +std::string CreateLibAssistantConfig() { using Value = base::Value; using Type = base::Value::Type;
diff --git a/chromeos/services/assistant/utils.h b/chromeos/services/assistant/utils.h index c33d76e..162edc6 100644 --- a/chromeos/services/assistant/utils.h +++ b/chromeos/services/assistant/utils.h
@@ -18,7 +18,7 @@ base::FilePath GetRootPath(); -std::string CreateLibAssistantConfig(bool disable_hotword); +std::string CreateLibAssistantConfig(); } // namespace assistant } // namespace chromeos
diff --git a/components/assist_ranker/example_preprocessing.cc b/components/assist_ranker/example_preprocessing.cc index 8b9dde8..b5929e6 100644 --- a/components/assist_ranker/example_preprocessing.cc +++ b/components/assist_ranker/example_preprocessing.cc
@@ -95,7 +95,7 @@ break; } // Set one hot feature as features[feature_name] = "index"; - feature_map[feature_name].set_string_value(base::IntToString(index)); + feature_map[feature_name].set_string_value(base::NumberToString(index)); } return error_code; } @@ -135,10 +135,10 @@ switch (feature.feature_type_case()) { case Feature::kBoolValue: feature.set_string_value( - base::IntToString(static_cast<int>(feature.bool_value()))); + base::NumberToString(static_cast<int>(feature.bool_value()))); break; case Feature::kInt32Value: - feature.set_string_value(base::IntToString(feature.int32_value())); + feature.set_string_value(base::NumberToString(feature.int32_value())); break; case Feature::kStringValue: break;
diff --git a/components/assist_ranker/example_preprocessing_unittest.cc b/components/assist_ranker/example_preprocessing_unittest.cc index aac69e18..79c1e76 100644 --- a/components/assist_ranker/example_preprocessing_unittest.cc +++ b/components/assist_ranker/example_preprocessing_unittest.cc
@@ -193,9 +193,9 @@ ExamplePreprocessor::kSuccess); (*expected.mutable_features())[bool_name_].set_string_value( - base::IntToString(static_cast<int>(bool_value_))); + base::NumberToString(static_cast<int>(bool_value_))); (*expected.mutable_features())[int32_name_].set_string_value( - base::IntToString(int32_value_)); + base::NumberToString(int32_value_)); EXPECT_EQUALS_EXAMPLE(example_, expected); }
diff --git a/components/autofill/android/BUILD.gn b/components/autofill/android/BUILD.gn index c952a263..3dae3f5 100644 --- a/components/autofill/android/BUILD.gn +++ b/components/autofill/android/BUILD.gn
@@ -7,22 +7,24 @@ java_strings_grd("autofill_strings_grd") { grd_file = "java/strings/autofill_strings.grd" outputs = [ + "values/autofill_strings.xml", "values-am/autofill_strings.xml", "values-ar/autofill_strings.xml", "values-bg/autofill_strings.xml", + "values-bn/autofill_strings.xml", "values-ca/autofill_strings.xml", "values-cs/autofill_strings.xml", "values-da/autofill_strings.xml", "values-de/autofill_strings.xml", "values-el/autofill_strings.xml", - "values/autofill_strings.xml", "values-en-rGB/autofill_strings.xml", "values-es/autofill_strings.xml", "values-es-rUS/autofill_strings.xml", + "values-et/autofill_strings.xml", "values-fa/autofill_strings.xml", "values-fi/autofill_strings.xml", - "values-tl/autofill_strings.xml", "values-fr/autofill_strings.xml", + "values-gu/autofill_strings.xml", "values-hi/autofill_strings.xml", "values-hr/autofill_strings.xml", "values-hu/autofill_strings.xml", @@ -30,11 +32,15 @@ "values-it/autofill_strings.xml", "values-iw/autofill_strings.xml", "values-ja/autofill_strings.xml", + "values-kn/autofill_strings.xml", "values-ko/autofill_strings.xml", "values-lt/autofill_strings.xml", "values-lv/autofill_strings.xml", - "values-nl/autofill_strings.xml", + "values-ml/autofill_strings.xml", + "values-mr/autofill_strings.xml", + "values-ms/autofill_strings.xml", "values-nb/autofill_strings.xml", + "values-nl/autofill_strings.xml", "values-pl/autofill_strings.xml", "values-pt-rBR/autofill_strings.xml", "values-pt-rPT/autofill_strings.xml", @@ -45,7 +51,10 @@ "values-sr/autofill_strings.xml", "values-sv/autofill_strings.xml", "values-sw/autofill_strings.xml", + "values-ta/autofill_strings.xml", + "values-te/autofill_strings.xml", "values-th/autofill_strings.xml", + "values-tl/autofill_strings.xml", "values-tr/autofill_strings.xml", "values-uk/autofill_strings.xml", "values-vi/autofill_strings.xml",
diff --git a/components/autofill/android/java/strings/autofill_strings.grd b/components/autofill/android/java/strings/autofill_strings.grd index cd32dec..e4e1b59 100644 --- a/components/autofill/android/java/strings/autofill_strings.grd +++ b/components/autofill/android/java/strings/autofill_strings.grd
@@ -6,6 +6,7 @@ <output filename="values-am/autofill_strings.xml" lang="am" type="android" /> <output filename="values-ar/autofill_strings.xml" lang="ar" type="android" /> <output filename="values-bg/autofill_strings.xml" lang="bg" type="android" /> + <output filename="values-bn/autofill_strings.xml" lang="bn" type="android" /> <output filename="values-ca/autofill_strings.xml" lang="ca" type="android" /> <output filename="values-cs/autofill_strings.xml" lang="cs" type="android" /> <output filename="values-da/autofill_strings.xml" lang="da" type="android" /> @@ -15,20 +16,26 @@ <output filename="values-en-rGB/autofill_strings.xml" lang="en-GB" type="android" /> <output filename="values-es/autofill_strings.xml" lang="es" type="android" /> <output filename="values-es-rUS/autofill_strings.xml" lang="es-419" type="android" /> + <output filename="values-et/autofill_strings.xml" lang="et" type="android" /> <output filename="values-fa/autofill_strings.xml" lang="fa" type="android" /> <output filename="values-fi/autofill_strings.xml" lang="fi" type="android" /> <output filename="values-tl/autofill_strings.xml" lang="fil" type="android" /> <output filename="values-fr/autofill_strings.xml" lang="fr" type="android" /> + <output filename="values-gu/autofill_strings.xml" lang="gu" type="android" /> + <output filename="values-iw/autofill_strings.xml" lang="he" type="android" /> <output filename="values-hi/autofill_strings.xml" lang="hi" type="android" /> <output filename="values-hr/autofill_strings.xml" lang="hr" type="android" /> <output filename="values-hu/autofill_strings.xml" lang="hu" type="android" /> <output filename="values-in/autofill_strings.xml" lang="id" type="android" /> <output filename="values-it/autofill_strings.xml" lang="it" type="android" /> - <output filename="values-iw/autofill_strings.xml" lang="he" type="android" /> <output filename="values-ja/autofill_strings.xml" lang="ja" type="android" /> + <output filename="values-kn/autofill_strings.xml" lang="kn" type="android" /> <output filename="values-ko/autofill_strings.xml" lang="ko" type="android" /> <output filename="values-lt/autofill_strings.xml" lang="lt" type="android" /> <output filename="values-lv/autofill_strings.xml" lang="lv" type="android" /> + <output filename="values-ml/autofill_strings.xml" lang="ml" type="android" /> + <output filename="values-mr/autofill_strings.xml" lang="mr" type="android" /> + <output filename="values-ms/autofill_strings.xml" lang="ms" type="android" /> <output filename="values-nl/autofill_strings.xml" lang="nl" type="android" /> <output filename="values-nb/autofill_strings.xml" lang="no" type="android" /> <output filename="values-pl/autofill_strings.xml" lang="pl" type="android" /> @@ -41,6 +48,8 @@ <output filename="values-sr/autofill_strings.xml" lang="sr" type="android" /> <output filename="values-sv/autofill_strings.xml" lang="sv" type="android" /> <output filename="values-sw/autofill_strings.xml" lang="sw" type="android" /> + <output filename="values-ta/autofill_strings.xml" lang="ta" type="android" /> + <output filename="values-te/autofill_strings.xml" lang="te" type="android" /> <output filename="values-th/autofill_strings.xml" lang="th" type="android" /> <output filename="values-tr/autofill_strings.xml" lang="tr" type="android" /> <output filename="values-uk/autofill_strings.xml" lang="uk" type="android" />
diff --git a/components/autofill/content/renderer/form_autofill_util_browsertest.cc b/components/autofill/content/renderer/form_autofill_util_browsertest.cc index 48ce8bb5..f9b4f4e2 100644 --- a/components/autofill/content/renderer/form_autofill_util_browsertest.cc +++ b/components/autofill/content/renderer/form_autofill_util_browsertest.cc
@@ -316,7 +316,7 @@ std::string kFormHtml = "<form id='target'>"; for (int i = 0; i < 10; i++) { std::string kFieldHtml = - "<input type='button' value='" + base::IntToString(i) + title + "'>"; + "<input type='button' value='" + base::NumberToString(i) + title + "'>"; kFormHtml += kFieldHtml; } kFormHtml += "</form>";
diff --git a/components/autofill/content/renderer/renderer_save_password_progress_logger.cc b/components/autofill/content/renderer/renderer_save_password_progress_logger.cc index 46aae75..9001bcd8 100644 --- a/components/autofill/content/renderer/renderer_save_password_progress_logger.cc +++ b/components/autofill/content/renderer/renderer_save_password_progress_logger.cc
@@ -9,8 +9,6 @@ #include "base/values.h" #include "third_party/blink/public/web/web_form_control_element.h" -using base::UintToString; - namespace autofill { RendererSavePasswordProgressLogger::RendererSavePasswordProgressLogger( @@ -30,7 +28,8 @@ const blink::WebFormControlElement& element) { std::string text = "name = " + ScrubElementID(element.NameForAutofill().Utf8()) + - ", renderer_id = " + UintToString(element.UniqueRendererFormControlId()); + ", renderer_id = " + + base::NumberToString(element.UniqueRendererFormControlId()); LogValue(label, base::Value(text)); }
diff --git a/components/autofill/core/browser/autofill_download_manager_unittest.cc b/components/autofill/core/browser/autofill_download_manager_unittest.cc index 13d7f760d..c6ae22d 100644 --- a/components/autofill/core/browser/autofill_download_manager_unittest.cc +++ b/components/autofill/core/browser/autofill_download_manager_unittest.cc
@@ -773,8 +773,8 @@ for (auto& form : forms) { for (size_t i = 0; i < 5; ++i) { FormFieldData field; - field.label = base::IntToString16(i); - field.name = base::IntToString16(i); + field.label = base::NumberToString16(i); + field.name = base::NumberToString16(i); field.form_control_type = "text"; form.fields.push_back(field); } @@ -794,8 +794,8 @@ for (auto& form : forms) { for (size_t i = 0; i < 4; ++i) { FormFieldData field; - field.label = base::IntToString16(i); - field.name = base::IntToString16(i); + field.label = base::NumberToString16(i); + field.name = base::NumberToString16(i); field.form_control_type = "text"; form.fields.push_back(field); }
diff --git a/components/autofill/core/browser/autofill_field.cc b/components/autofill/core/browser/autofill_field.cc index afc5e7c..e60544c 100644 --- a/components/autofill/core/browser/autofill_field.cc +++ b/components/autofill/core/browser/autofill_field.cc
@@ -169,7 +169,7 @@ } std::string AutofillField::FieldSignatureAsStr() const { - return base::UintToString(GetFieldSignature()); + return base::NumberToString(GetFieldSignature()); } bool AutofillField::IsFieldFillable() const {
diff --git a/components/autofill/core/browser/credit_card.cc b/components/autofill/core/browser/credit_card.cc index 139dca4..b0d490af 100644 --- a/components/autofill/core/browser/credit_card.cc +++ b/components/autofill/core/browser/credit_card.cc
@@ -869,7 +869,7 @@ if (expiration_month_ == 0) return base::string16(); - base::string16 month = base::IntToString16(expiration_month_); + base::string16 month = base::NumberToString16(expiration_month_); if (expiration_month_ >= 10) return month; @@ -882,7 +882,7 @@ if (expiration_year_ == 0) return base::string16(); - return base::IntToString16(Expiration4DigitYear()); + return base::NumberToString16(Expiration4DigitYear()); } bool CreditCard::HasFirstAndLastName() const { @@ -898,7 +898,7 @@ if (expiration_year_ == 0) return base::string16(); - return base::IntToString16(Expiration2DigitYear()); + return base::NumberToString16(Expiration2DigitYear()); } void CreditCard::GetSupportedTypes(ServerFieldTypeSet* supported_types) const {
diff --git a/components/autofill/core/browser/credit_card_field.cc b/components/autofill/core/browser/credit_card_field.cc index fb1f8bf9..cbf5de6 100644 --- a/components/autofill/core/browser/credit_card_field.cc +++ b/components/autofill/core/browser/credit_card_field.cc
@@ -322,7 +322,7 @@ for (int year = time_exploded.year; year < time_exploded.year + kYearsToMatch; ++year) { - years_to_check.push_back(base::IntToString16(year)); + years_to_check.push_back(base::NumberToString16(year)); } return (FindConsecutiveStrings(years_to_check, field->option_values) || FindConsecutiveStrings(years_to_check, field->option_contents));
diff --git a/components/autofill/core/browser/credit_card_unittest.cc b/components/autofill/core/browser/credit_card_unittest.cc index 9552cae..69d4e1b4 100644 --- a/components/autofill/core/browser/credit_card_unittest.cc +++ b/components/autofill/core/browser/credit_card_unittest.cc
@@ -931,9 +931,9 @@ base::Time::Exploded now_exploded; now.LocalExplode(&now_exploded); card.SetRawInfo(CREDIT_CARD_EXP_MONTH, - base::IntToString16(now_exploded.month)); + base::NumberToString16(now_exploded.month)); card.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, - base::IntToString16(now_exploded.year - 1)); + base::NumberToString16(now_exploded.year - 1)); card.SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16("4111111111111111")); EXPECT_FALSE(card.IsValid()); EXPECT_FALSE(card.HasValidExpirationDate());
diff --git a/components/autofill/core/browser/phone_number_i18n.cc b/components/autofill/core/browser/phone_number_i18n.cc index f4e7e3b..85cf047 100644 --- a/components/autofill/core/browser/phone_number_i18n.cc +++ b/components/autofill/core/browser/phone_number_i18n.cc
@@ -214,7 +214,7 @@ i18n_number->country_code_source() != ::i18n::phonenumbers::PhoneNumber::FROM_DEFAULT_COUNTRY) { *country_code = - base::UTF8ToUTF16(base::IntToString(i18n_number->country_code())); + base::UTF8ToUTF16(base::NumberToString(i18n_number->country_code())); } // The region might be different from what we started with.
diff --git a/components/autofill/core/common/save_password_progress_logger.cc b/components/autofill/core/common/save_password_progress_logger.cc index de25481..266a830 100644 --- a/components/autofill/core/common/save_password_progress_logger.cc +++ b/components/autofill/core/common/save_password_progress_logger.cc
@@ -18,7 +18,7 @@ using base::checked_cast; using base::DictionaryValue; -using base::UintToString; +using base::NumberToString; using base::Value; namespace autofill { @@ -72,19 +72,19 @@ ScrubElementID(form.username_element)); if (form.has_renderer_ids) { log.SetString(GetStringFromID(STRING_USERNAME_ELEMENT_RENDERER_ID), - UintToString(form.username_element_renderer_id)); + NumberToString(form.username_element_renderer_id)); } log.SetString(GetStringFromID(STRING_PASSWORD_ELEMENT), ScrubElementID(form.password_element)); if (form.has_renderer_ids) { log.SetString(GetStringFromID(STRING_PASSWORD_ELEMENT_RENDERER_ID), - UintToString(form.password_element_renderer_id)); + NumberToString(form.password_element_renderer_id)); } log.SetString(GetStringFromID(STRING_NEW_PASSWORD_ELEMENT), ScrubElementID(form.new_password_element)); if (form.has_renderer_ids) { log.SetString(GetStringFromID(STRING_NEW_PASSWORD_ELEMENT_RENDERER_ID), - UintToString(form.new_password_element_renderer_id)); + NumberToString(form.new_password_element_renderer_id)); } if (!form.confirmation_password_element.empty()) { log.SetString(GetStringFromID(STRING_CONFIRMATION_PASSWORD_ELEMENT), @@ -92,7 +92,7 @@ if (form.has_renderer_ids) { log.SetString( GetStringFromID(STRING_CONFIRMATION_PASSWORD_ELEMENT_RENDERER_ID), - UintToString(form.confirmation_password_element_renderer_id)); + NumberToString(form.confirmation_password_element_renderer_id)); } } log.SetBoolean(GetStringFromID(STRING_PASSWORD_GENERATED),
diff --git a/components/bookmarks/browser/bookmark_codec.cc b/components/bookmarks/browser/bookmark_codec.cc index 36d60c0..5474355 100644 --- a/components/bookmarks/browser/bookmark_codec.cc +++ b/components/bookmarks/browser/bookmark_codec.cc
@@ -86,7 +86,7 @@ if (sync_transaction_version != BookmarkNode::kInvalidSyncTransactionVersion) { roots->SetString(kSyncTransactionVersion, - base::Int64ToString(sync_transaction_version)); + base::NumberToString(sync_transaction_version)); } auto main = std::make_unique<base::DictionaryValue>(); main->SetInteger(kVersionKey, kCurrentVersion); @@ -130,12 +130,12 @@ std::unique_ptr<base::Value> BookmarkCodec::EncodeNode( const BookmarkNode* node) { std::unique_ptr<base::DictionaryValue> value(new base::DictionaryValue()); - std::string id = base::Int64ToString(node->id()); + std::string id = base::NumberToString(node->id()); value->SetString(kIdKey, id); const base::string16& title = node->GetTitle(); value->SetString(kNameKey, title); value->SetString(kDateAddedKey, - base::Int64ToString(node->date_added().ToInternalValue())); + base::NumberToString(node->date_added().ToInternalValue())); if (node->is_url()) { value->SetString(kTypeKey, kTypeURL); std::string url = node->url().possibly_invalid_spec(); @@ -145,7 +145,7 @@ value->SetString(kTypeKey, kTypeFolder); value->SetString( kDateModifiedKey, - base::Int64ToString(node->date_folder_modified().ToInternalValue())); + base::NumberToString(node->date_folder_modified().ToInternalValue())); UpdateChecksumWithFolderNode(id, title); auto child_values = std::make_unique<base::ListValue>(); @@ -159,7 +159,7 @@ if (node->sync_transaction_version() != BookmarkNode::kInvalidSyncTransactionVersion) { value->SetString(kSyncTransactionVersion, - base::Int64ToString(node->sync_transaction_version())); + base::NumberToString(node->sync_transaction_version())); } return std::move(value); } @@ -315,7 +315,7 @@ std::string date_added_string; if (!value.GetString(kDateAddedKey, &date_added_string)) - date_added_string = base::Int64ToString(Time::Now().ToInternalValue()); + date_added_string = base::NumberToString(Time::Now().ToInternalValue()); int64_t internal_time; base::StringToInt64(date_added_string, &internal_time); @@ -344,7 +344,7 @@ } else { std::string last_modified_date; if (!value.GetString(kDateModifiedKey, &last_modified_date)) - last_modified_date = base::Int64ToString(Time::Now().ToInternalValue()); + last_modified_date = base::NumberToString(Time::Now().ToInternalValue()); const base::Value* child_values; if (!value.Get(kChildrenKey, &child_values))
diff --git a/components/bookmarks/browser/bookmark_expanded_state_tracker.cc b/components/bookmarks/browser/bookmark_expanded_state_tracker.cc index 2799881..40cdbaa 100644 --- a/components/bookmarks/browser/bookmark_expanded_state_tracker.cc +++ b/components/bookmarks/browser/bookmark_expanded_state_tracker.cc
@@ -109,7 +109,7 @@ std::vector<base::Value> values; values.reserve(nodes.size()); for (const auto* node : nodes) { - values.emplace_back(base::Int64ToString(node->id())); + values.emplace_back(base::NumberToString(node->id())); } pref_service_->Set(prefs::kBookmarkEditorExpandedNodes,
diff --git a/components/bookmarks/browser/bookmark_expanded_state_tracker_unittest.cc b/components/bookmarks/browser/bookmark_expanded_state_tracker_unittest.cc index f59a18f1..9ab01a3 100644 --- a/components/bookmarks/browser/bookmark_expanded_state_tracker_unittest.cc +++ b/components/bookmarks/browser/bookmark_expanded_state_tracker_unittest.cc
@@ -44,8 +44,7 @@ BookmarkExpandedStateTrackerTest::~BookmarkExpandedStateTrackerTest() {} void BookmarkExpandedStateTrackerTest::SetUp() { - prefs_.registry()->RegisterListPref(prefs::kBookmarkEditorExpandedNodes, - std::make_unique<base::ListValue>()); + prefs_.registry()->RegisterListPref(prefs::kBookmarkEditorExpandedNodes); prefs_.registry()->RegisterListPref(prefs::kManagedBookmarks); model_.reset(new BookmarkModel(std::make_unique<TestBookmarkClient>())); model_->Load(&prefs_, base::FilePath(),
diff --git a/components/bookmarks/browser/bookmark_model_unittest.cc b/components/bookmarks/browser/bookmark_model_unittest.cc index 9e07e4d..1a09c01c 100644 --- a/components/bookmarks/browser/bookmark_model_unittest.cc +++ b/components/bookmarks/browser/bookmark_model_unittest.cc
@@ -139,7 +139,7 @@ // in debugging. static int next_folder_id = 1; TestNode* new_node = parent->Add( - std::make_unique<TestNode>(base::IntToString16(next_folder_id++), + std::make_unique<TestNode>(base::NumberToString16(next_folder_id++), BookmarkNode::FOLDER), parent->child_count()); PopulateNodeImpl(description, index, new_node);
diff --git a/components/bookmarks/browser/bookmark_utils.cc b/components/bookmarks/browser/bookmark_utils.cc index 759b049..0b1f89c 100644 --- a/components/bookmarks/browser/bookmark_utils.cc +++ b/components/bookmarks/browser/bookmark_utils.cc
@@ -459,8 +459,7 @@ // will cause a deadlock (see http://crbug.com/97955). If we truly // want to sync the expanded state of folders, it should be part of // bookmark sync itself (i.e., a property of the sync folder nodes). - registry->RegisterListPref(prefs::kBookmarkEditorExpandedNodes, - std::make_unique<base::ListValue>()); + registry->RegisterListPref(prefs::kBookmarkEditorExpandedNodes); registry->RegisterListPref(prefs::kManagedBookmarks); registry->RegisterStringPref( prefs::kManagedBookmarksFolderName, std::string());
diff --git a/components/browser_sync/profile_sync_service_bookmark_unittest.cc b/components/browser_sync/profile_sync_service_bookmark_unittest.cc index 5076b1b..457199d 100644 --- a/components/browser_sync/profile_sync_service_bookmark_unittest.cc +++ b/components/browser_sync/profile_sync_service_bookmark_unittest.cc
@@ -87,7 +87,7 @@ syncer::syncable::ChangeEntryIDAndUpdateChildren( trans->GetWrappedWriteTrans(), node->GetMutableEntryForTest(), syncer::syncable::Id::CreateFromServerId( - base::Int64ToString(node->GetId()))); + base::NumberToString(node->GetId()))); node->GetMutableEntryForTest()->PutBaseVersion(10); node->GetMutableEntryForTest()->PutIsUnappliedUpdate(true); } @@ -1440,7 +1440,7 @@ // position. for (int i = 0; i < kTimesToInsert; ++i) { base::string16 title = - base::ASCIIToUTF16("Pre-insertion ") + base::IntToString16(i); + base::ASCIIToUTF16("Pre-insertion ") + base::NumberToString16(i); model()->AddFolder(model()->other_node(), 1, title); count++; } @@ -1449,7 +1449,7 @@ // second-to-last position. for (int i = 0; i < kTimesToInsert; ++i) { base::string16 title = - base::ASCIIToUTF16("Post-insertion ") + base::IntToString16(i); + base::ASCIIToUTF16("Post-insertion ") + base::NumberToString16(i); model()->AddFolder(model()->other_node(), count - 1, title); count++; }
diff --git a/components/browser_watcher/window_hang_monitor_win_unittest.cc b/components/browser_watcher/window_hang_monitor_win_unittest.cc index efe06066..d0f7927b 100644 --- a/components/browser_watcher/window_hang_monitor_win_unittest.cc +++ b/components/browser_watcher/window_hang_monitor_win_unittest.cc
@@ -76,7 +76,7 @@ std::string switch_name, HANDLE handle) { command_line->AppendSwitchASCII( - switch_name, base::UintToString(base::win::HandleToUint32(handle))); + switch_name, base::NumberToString(base::win::HandleToUint32(handle))); } // Retrieves the |handle| associated to |switch_name| from the command line.
diff --git a/components/cast_channel/cast_auth_util.cc b/components/cast_channel/cast_auth_util.cc index 7840474..fb9df96 100644 --- a/components/cast_channel/cast_auth_util.cc +++ b/components/cast_channel/cast_auth_util.cc
@@ -89,7 +89,7 @@ if (auth_message->has_error()) { return AuthResult::CreateWithParseError( "Auth message error: " + - base::IntToString(auth_message->error().error_type()), + base::NumberToString(auth_message->error().error_type()), AuthResult::ERROR_MESSAGE_ERROR); } if (!auth_message->has_response()) {
diff --git a/components/cast_channel/cast_framer.cc b/components/cast_channel/cast_framer.cc index b2830b9..f6024ed 100644 --- a/components/cast_channel/cast_framer.cc +++ b/components/cast_channel/cast_framer.cc
@@ -68,8 +68,7 @@ } std::string MessageFramer::MessageHeader::ToString() { - return "{message_size: " + - base::UintToString(static_cast<uint32_t>(message_size)) + "}"; + return "{message_size: " + base::NumberToString(message_size) + "}"; } // static
diff --git a/components/cast_channel/cast_message_util.cc b/components/cast_channel/cast_message_util.cc index a025a7fd..5ebf3a9 100644 --- a/components/cast_channel/cast_message_util.cc +++ b/components/cast_channel/cast_message_util.cc
@@ -192,7 +192,7 @@ out += "namespace = " + message_proto.namespace_(); out += ", sourceId = " + message_proto.source_id(); out += ", destId = " + message_proto.destination_id(); - out += ", type = " + base::IntToString(message_proto.payload_type()); + out += ", type = " + base::NumberToString(message_proto.payload_type()); out += ", str = \"" + message_proto.payload_utf8() + "\"}"; return out; } @@ -212,7 +212,7 @@ } if (message.has_error()) { out += ", error: {"; - out += base::IntToString(message.error().error_type()); + out += base::NumberToString(message.error().error_type()); out += "}"; } out += "}";
diff --git a/components/components_locale_settings.grd b/components/components_locale_settings.grd index a9ffdfb3..fa2ed5b 100644 --- a/components/components_locale_settings.grd +++ b/components/components_locale_settings.grd
@@ -13,8 +13,8 @@ <output filename="components_locale_settings_da.pak" type="data_package" lang="da" /> <output filename="components_locale_settings_de.pak" type="data_package" lang="de" /> <output filename="components_locale_settings_el.pak" type="data_package" lang="el" /> - <output filename="components_locale_settings_en-GB.pak" type="data_package" lang="en-GB" /> <output filename="components_locale_settings_en-US.pak" type="data_package" lang="en" /> + <output filename="components_locale_settings_en-GB.pak" type="data_package" lang="en-GB" /> <output filename="components_locale_settings_es.pak" type="data_package" lang="es" /> <if expr="is_ios"> <!-- iOS uses es-MX for es-419 --> @@ -79,6 +79,7 @@ <output filename="java/res/values-am/components_locale_settings.xml" lang="am" type="android" context="android_java" /> <output filename="java/res/values-ar/components_locale_settings.xml" lang="ar" type="android" context="android_java" /> <output filename="java/res/values-bg/components_locale_settings.xml" lang="bg" type="android" context="android_java" /> + <output filename="java/res/values-bn/components_locale_settings.xml" lang="bn" type="android" context="android_java" /> <output filename="java/res/values-ca/components_locale_settings.xml" lang="ca" type="android" context="android_java" /> <output filename="java/res/values-cs/components_locale_settings.xml" lang="cs" type="android" context="android_java" /> <output filename="java/res/values-da/components_locale_settings.xml" lang="da" type="android" context="android_java" /> @@ -88,20 +89,26 @@ <output filename="java/res/values-en-rGB/components_locale_settings.xml" lang="en-GB" type="android" context="android_java" /> <output filename="java/res/values-es/components_locale_settings.xml" lang="es" type="android" context="android_java" /> <output filename="java/res/values-es-rUS/components_locale_settings.xml" lang="es-419" type="android" context="android_java" /> + <output filename="java/res/values-et/components_locale_settings.xml" lang="et" type="android" context="android_java" /> <output filename="java/res/values-fa/components_locale_settings.xml" lang="fa" type="android" context="android_java" /> <output filename="java/res/values-fi/components_locale_settings.xml" lang="fi" type="android" context="android_java" /> <output filename="java/res/values-tl/components_locale_settings.xml" lang="fil" type="android" context="android_java" /> <output filename="java/res/values-fr/components_locale_settings.xml" lang="fr" type="android" context="android_java" /> + <output filename="java/res/values-gu/components_locale_settings.xml" lang="gu" type="android" context="android_java" /> + <output filename="java/res/values-iw/components_locale_settings.xml" lang="he" type="android" context="android_java" /> <output filename="java/res/values-hi/components_locale_settings.xml" lang="hi" type="android" context="android_java" /> <output filename="java/res/values-hr/components_locale_settings.xml" lang="hr" type="android" context="android_java" /> <output filename="java/res/values-hu/components_locale_settings.xml" lang="hu" type="android" context="android_java" /> <output filename="java/res/values-in/components_locale_settings.xml" lang="id" type="android" context="android_java" /> <output filename="java/res/values-it/components_locale_settings.xml" lang="it" type="android" context="android_java" /> - <output filename="java/res/values-iw/components_locale_settings.xml" lang="he" type="android" context="android_java" /> <output filename="java/res/values-ja/components_locale_settings.xml" lang="ja" type="android" context="android_java" /> + <output filename="java/res/values-kn/components_locale_settings.xml" lang="kn" type="android" context="android_java" /> <output filename="java/res/values-ko/components_locale_settings.xml" lang="ko" type="android" context="android_java" /> <output filename="java/res/values-lt/components_locale_settings.xml" lang="lt" type="android" context="android_java" /> <output filename="java/res/values-lv/components_locale_settings.xml" lang="lv" type="android" context="android_java" /> + <output filename="java/res/values-ml/components_locale_settings.xml" lang="ml" type="android" context="android_java" /> + <output filename="java/res/values-mr/components_locale_settings.xml" lang="mr" type="android" context="android_java" /> + <output filename="java/res/values-ms/components_locale_settings.xml" lang="ms" type="android" context="android_java" /> <output filename="java/res/values-nl/components_locale_settings.xml" lang="nl" type="android" context="android_java" /> <output filename="java/res/values-nb/components_locale_settings.xml" lang="no" type="android" context="android_java" /> <output filename="java/res/values-pl/components_locale_settings.xml" lang="pl" type="android" context="android_java" /> @@ -114,6 +121,8 @@ <output filename="java/res/values-sr/components_locale_settings.xml" lang="sr" type="android" context="android_java" /> <output filename="java/res/values-sv/components_locale_settings.xml" lang="sv" type="android" context="android_java" /> <output filename="java/res/values-sw/components_locale_settings.xml" lang="sw" type="android" context="android_java" /> + <output filename="java/res/values-ta/components_locale_settings.xml" lang="ta" type="android" context="android_java" /> + <output filename="java/res/values-te/components_locale_settings.xml" lang="te" type="android" context="android_java" /> <output filename="java/res/values-th/components_locale_settings.xml" lang="th" type="android" context="android_java" /> <output filename="java/res/values-tr/components_locale_settings.xml" lang="tr" type="android" context="android_java" /> <output filename="java/res/values-uk/components_locale_settings.xml" lang="uk" type="android" context="android_java" />
diff --git a/components/components_strings.grd b/components/components_strings.grd index 045961b..8ad54e69 100644 --- a/components/components_strings.grd +++ b/components/components_strings.grd
@@ -15,8 +15,8 @@ <output filename="components_strings_da.pak" type="data_package" lang="da" /> <output filename="components_strings_de.pak" type="data_package" lang="de" /> <output filename="components_strings_el.pak" type="data_package" lang="el" /> - <output filename="components_strings_en-GB.pak" type="data_package" lang="en-GB" /> <output filename="components_strings_en-US.pak" type="data_package" lang="en" /> + <output filename="components_strings_en-GB.pak" type="data_package" lang="en-GB" /> <output filename="components_strings_es.pak" type="data_package" lang="es" /> <if expr="is_ios"> <!-- iOS uses es-MX for es-419 --> @@ -81,6 +81,7 @@ <output filename="java/res/values-am/components_strings.xml" lang="am" type="android" context="android_java" /> <output filename="java/res/values-ar/components_strings.xml" lang="ar" type="android" context="android_java" /> <output filename="java/res/values-bg/components_strings.xml" lang="bg" type="android" context="android_java" /> + <output filename="java/res/values-bn/components_strings.xml" lang="bn" type="android" context="android_java" /> <output filename="java/res/values-ca/components_strings.xml" lang="ca" type="android" context="android_java" /> <output filename="java/res/values-cs/components_strings.xml" lang="cs" type="android" context="android_java" /> <output filename="java/res/values-da/components_strings.xml" lang="da" type="android" context="android_java" /> @@ -90,20 +91,26 @@ <output filename="java/res/values-en-rGB/components_strings.xml" lang="en-GB" type="android" context="android_java" /> <output filename="java/res/values-es/components_strings.xml" lang="es" type="android" context="android_java" /> <output filename="java/res/values-es-rUS/components_strings.xml" lang="es-419" type="android" context="android_java" /> + <output filename="java/res/values-et/components_strings.xml" lang="et" type="android" context="android_java" /> <output filename="java/res/values-fa/components_strings.xml" lang="fa" type="android" context="android_java" /> <output filename="java/res/values-fi/components_strings.xml" lang="fi" type="android" context="android_java" /> <output filename="java/res/values-tl/components_strings.xml" lang="fil" type="android" context="android_java" /> <output filename="java/res/values-fr/components_strings.xml" lang="fr" type="android" context="android_java" /> + <output filename="java/res/values-gu/components_strings.xml" lang="gu" type="android" context="android_java" /> + <output filename="java/res/values-iw/components_strings.xml" lang="he" type="android" context="android_java" /> <output filename="java/res/values-hi/components_strings.xml" lang="hi" type="android" context="android_java" /> <output filename="java/res/values-hr/components_strings.xml" lang="hr" type="android" context="android_java" /> <output filename="java/res/values-hu/components_strings.xml" lang="hu" type="android" context="android_java" /> <output filename="java/res/values-in/components_strings.xml" lang="id" type="android" context="android_java" /> <output filename="java/res/values-it/components_strings.xml" lang="it" type="android" context="android_java" /> - <output filename="java/res/values-iw/components_strings.xml" lang="he" type="android" context="android_java" /> <output filename="java/res/values-ja/components_strings.xml" lang="ja" type="android" context="android_java" /> + <output filename="java/res/values-kn/components_strings.xml" lang="kn" type="android" context="android_java" /> <output filename="java/res/values-ko/components_strings.xml" lang="ko" type="android" context="android_java" /> <output filename="java/res/values-lt/components_strings.xml" lang="lt" type="android" context="android_java" /> <output filename="java/res/values-lv/components_strings.xml" lang="lv" type="android" context="android_java" /> + <output filename="java/res/values-ml/components_strings.xml" lang="ml" type="android" context="android_java" /> + <output filename="java/res/values-mr/components_strings.xml" lang="mr" type="android" context="android_java" /> + <output filename="java/res/values-ms/components_strings.xml" lang="ms" type="android" context="android_java" /> <output filename="java/res/values-nl/components_strings.xml" lang="nl" type="android" context="android_java" /> <output filename="java/res/values-nb/components_strings.xml" lang="no" type="android" context="android_java" /> <output filename="java/res/values-pl/components_strings.xml" lang="pl" type="android" context="android_java" /> @@ -116,6 +123,8 @@ <output filename="java/res/values-sr/components_strings.xml" lang="sr" type="android" context="android_java" /> <output filename="java/res/values-sv/components_strings.xml" lang="sv" type="android" context="android_java" /> <output filename="java/res/values-sw/components_strings.xml" lang="sw" type="android" context="android_java" /> + <output filename="java/res/values-ta/components_strings.xml" lang="ta" type="android" context="android_java" /> + <output filename="java/res/values-te/components_strings.xml" lang="te" type="android" context="android_java" /> <output filename="java/res/values-th/components_strings.xml" lang="th" type="android" context="android_java" /> <output filename="java/res/values-tr/components_strings.xml" lang="tr" type="android" context="android_java" /> <output filename="java/res/values-uk/components_strings.xml" lang="uk" type="android" context="android_java" />
diff --git a/components/consent_auditor/consent_sync_bridge_impl.cc b/components/consent_auditor/consent_sync_bridge_impl.cc index cb4ee3b..ec2eadb 100644 --- a/components/consent_auditor/consent_sync_bridge_impl.cc +++ b/components/consent_auditor/consent_sync_bridge_impl.cc
@@ -46,7 +46,7 @@ std::unique_ptr<UserConsentSpecifics> specifics) { auto entity_data = std::make_unique<EntityData>(); entity_data->non_unique_name = - base::Int64ToString(specifics->client_consent_time_usec()); + base::NumberToString(specifics->client_consent_time_usec()); entity_data->specifics.set_allocated_user_consent(specifics.release()); return entity_data; }
diff --git a/components/content_settings/core/browser/content_settings_pref.cc b/components/content_settings/core/browser/content_settings_pref.cc index 90facf5..4e8ef3a 100644 --- a/components/content_settings/core/browser/content_settings_pref.cc +++ b/components/content_settings/core/browser/content_settings_pref.cc
@@ -404,7 +404,7 @@ value->CreateDeepCopy()); // Update timestamp for whole resource dictionary. settings_dictionary->SetKey(kLastModifiedPath, - base::Value(base::Int64ToString( + base::Value(base::NumberToString( last_modified.ToInternalValue()))); } } else { @@ -418,7 +418,7 @@ settings_dictionary->SetWithoutPathExpansion(kSettingPath, value->CreateDeepCopy()); settings_dictionary->SetKey(kLastModifiedPath, - base::Value(base::Int64ToString( + base::Value(base::NumberToString( last_modified.ToInternalValue()))); } }
diff --git a/components/crash/content/app/BUILD.gn b/components/crash/content/app/BUILD.gn index 5a13a519..30ba4f95 100644 --- a/components/crash/content/app/BUILD.gn +++ b/components/crash/content/app/BUILD.gn
@@ -189,6 +189,41 @@ } } +if (is_mac) { + # We build a chromium-specific crashpad_handler executable so that we can + # define custom UserStreamDataSources. + executable("chrome_crashpad_handler") { + sources = [ + "chrome_crashpad_handler.cc", + ] + + deps = [ + "//third_party/crashpad/crashpad/handler:handler", + ] + + if (is_component_build) { + ldflags = [ + # The handler is in + # Chromium.app/Contents/Versions/X/Chromium Framework.framework/Versions/A/Helpers/ + # so set rpath up to the base. + "-rpath", + "@loader_path/../../../../../../../..", + + # The handler is also in + # Content Shell.app/Contents/Frameworks/Content Shell Framework.framework/Versions/C/Helpers/ + # so set the rpath for that too. + "-rpath", + "@loader_path/../../../../../../..", + + # The handler can also be executed in an unbundled framework at + # Chromium Framework.framework/Versions/A/Helpers/ + "-rpath", + "@loader_path/../../../..", + ] + } + } +} + # This source set provides the functionality required for tests, which on Windows # link the export thunks directly into the test binary. source_set("test_support") {
diff --git a/components/crash/content/app/breakpad_win.cc b/components/crash/content/app/breakpad_win.cc index dec9daf..8de4938 100644 --- a/components/crash/content/app/breakpad_win.cc +++ b/components/crash/content/app/breakpad_win.cc
@@ -130,7 +130,7 @@ custom_entries->push_back( google_breakpad::CustomInfoEntry(L"ptype", type.c_str())); custom_entries->push_back(google_breakpad::CustomInfoEntry( - L"pid", base::IntToString16(::GetCurrentProcessId()).c_str())); + L"pid", base::NumberToString16(::GetCurrentProcessId()).c_str())); custom_entries->push_back( google_breakpad::CustomInfoEntry(L"channel", channel_name.c_str())); custom_entries->push_back(
diff --git a/components/crash/content/app/chrome_crashpad_handler.cc b/components/crash/content/app/chrome_crashpad_handler.cc new file mode 100644 index 0000000..ac121e2 --- /dev/null +++ b/components/crash/content/app/chrome_crashpad_handler.cc
@@ -0,0 +1,9 @@ +// 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. + +#include "third_party/crashpad/crashpad/handler/handler_main.h" + +int main(int argc, char* argv[]) { + return crashpad::HandlerMain(argc, argv, nullptr); +}
diff --git a/components/crash/content/app/crashpad.cc b/components/crash/content/app/crashpad.cc index 04127557..72c9703 100644 --- a/components/crash/content/app/crashpad.cc +++ b/components/crash/content/app/crashpad.cc
@@ -165,9 +165,9 @@ static crashpad::StringAnnotation<12> pid_key("pid"); #if defined(OS_POSIX) - pid_key.Set(base::IntToString(getpid())); + pid_key.Set(base::NumberToString(getpid())); #elif defined(OS_WIN) - pid_key.Set(base::IntToString(::GetCurrentProcessId())); + pid_key.Set(base::NumberToString(::GetCurrentProcessId())); #endif logging::SetLogMessageHandler(LogMessageHandler);
diff --git a/components/crash/content/app/crashpad_mac.mm b/components/crash/content/app/crashpad_mac.mm index f079174..a76d264 100644 --- a/components/crash/content/app/crashpad_mac.mm +++ b/components/crash/content/app/crashpad_mac.mm
@@ -124,7 +124,8 @@ @autoreleasepool { base::FilePath framework_bundle_path = base::mac::FrameworkBundlePath(); base::FilePath handler_path = - framework_bundle_path.Append("Helpers").Append("crashpad_handler"); + framework_bundle_path.Append("Helpers").Append( + "chrome_crashpad_handler"); // Is there a way to recover if this fails? CrashReporterClient* crash_reporter_client = GetCrashReporterClient();
diff --git a/components/crash/content/app/fallback_crash_handler_launcher_win.cc b/components/crash/content/app/fallback_crash_handler_launcher_win.cc index 453ff60..947bb0c 100644 --- a/components/crash/content/app/fallback_crash_handler_launcher_win.cc +++ b/components/crash/content/app/fallback_crash_handler_launcher_win.cc
@@ -54,7 +54,7 @@ "exception-pointers", base::NumberToString(reinterpret_cast<uintptr_t>(&exception_pointers_))); cmd_line.AppendSwitchASCII( - "process", base::UintToString( + "process", base::NumberToString( base::win::HandleToUint32(self_process_handle_.Get()))); std::wstring str_cmd_line = cmd_line.GetCommandLineString();
diff --git a/components/crash/content/app/fallback_crash_handler_win.cc b/components/crash/content/app/fallback_crash_handler_win.cc index c04570dae..56677a2 100644 --- a/components/crash/content/app/fallback_crash_handler_win.cc +++ b/components/crash/content/app/fallback_crash_handler_win.cc
@@ -59,9 +59,9 @@ // of system pages. crash_keys->insert(std::make_pair( "SystemCommitRemaining", - base::UintToString(perf_info.CommitLimit - perf_info.CommitTotal))); + base::NumberToString(perf_info.CommitLimit - perf_info.CommitTotal))); crash_keys->insert(std::make_pair( - "SystemCommitLimit", base::UintToString(perf_info.CommitLimit))); + "SystemCommitLimit", base::NumberToString(perf_info.CommitLimit))); } }
diff --git a/components/crash/content/app/fallback_crash_handler_win_unittest.cc b/components/crash/content/app/fallback_crash_handler_win_unittest.cc index 28950a2..e21fecbe 100644 --- a/components/crash/content/app/fallback_crash_handler_win_unittest.cc +++ b/components/crash/content/app/fallback_crash_handler_win_unittest.cc
@@ -120,7 +120,7 @@ } std::string SelfHandleAsString() const { - return base::UintToString(base::win::HandleToUint32(self_handle_)); + return base::NumberToString(base::win::HandleToUint32(self_handle_)); } void CreateDatabase() { @@ -155,7 +155,7 @@ ASSERT_FALSE(handler.ParseCommandLine(cmd_line)); cmd_line.AppendSwitchASCII( - "thread", base::UintToString(base::PlatformThread::CurrentId())); + "thread", base::NumberToString(base::PlatformThread::CurrentId())); // Should succeed with a fully populated command line. // Because of how handle ownership is guarded, we have to "disown" it before
diff --git a/components/crash/content/browser/child_exit_observer_android.cc b/components/crash/content/browser/child_exit_observer_android.cc index cd62274d37..595a52744 100644 --- a/components/crash/content/browser/child_exit_observer_android.cc +++ b/components/crash/content/browser/child_exit_observer_android.cc
@@ -139,7 +139,8 @@ browser_child_process_info_.erase(it); } else { info.process_host_id = data.id; - info.pid = data.GetProcess().Pid(); + if (data.GetProcess().IsValid()) + info.pid = data.GetProcess().Pid(); info.process_type = static_cast<content::ProcessType>(data.process_type); info.app_state = base::android::ApplicationStatusListener::GetState(); info.normal_termination = true;
diff --git a/components/crash/content/browser/child_exit_observer_android.h b/components/crash/content/browser/child_exit_observer_android.h index 161d2e8..1059f0c4 100644 --- a/components/crash/content/browser/child_exit_observer_android.h +++ b/components/crash/content/browser/child_exit_observer_android.h
@@ -47,6 +47,8 @@ bool is_crashed() const { return crash_signo != kInvalidSigno; } int process_host_id = content::ChildProcessHost::kInvalidUniqueID; + // |pid| may not be valid if termination happens before the process has + // finished launching. base::ProcessHandle pid = base::kNullProcessHandle; content::ProcessType process_type = content::PROCESS_TYPE_UNKNOWN; base::android::ApplicationState app_state =
diff --git a/components/cronet/stale_host_resolver.cc b/components/cronet/stale_host_resolver.cc index ef09344..dfef531 100644 --- a/components/cronet/stale_host_resolver.cc +++ b/components/cronet/stale_host_resolver.cc
@@ -4,7 +4,9 @@ #include "components/cronet/stale_host_resolver.h" +#include <string> #include <utility> +#include <vector> #include "base/bind.h" #include "base/callback_helpers.h" @@ -17,6 +19,7 @@ #include "net/base/net_errors.h" #include "net/dns/dns_util.h" #include "net/dns/host_resolver_source.h" +#include "net/log/net_log_with_source.h" namespace cronet { @@ -74,125 +77,86 @@ } } -bool StaleEntryIsUsable(const StaleHostResolver::StaleOptions& options, - const net::HostCache::EntryStaleness& entry) { - if (options.max_expired_time != base::TimeDelta() && - entry.expired_by > options.max_expired_time) { - return false; - } - if (options.max_stale_uses > 0 && entry.stale_hits > options.max_stale_uses) - return false; - if (!options.allow_other_network && entry.network_changes > 0) - return false; - return true; -} - } // namespace // A request made by the StaleHostResolver. May return fresh cached data, // network data, or stale cached data. -class StaleHostResolver::RequestImpl { +class StaleHostResolver::RequestImpl + : public net::HostResolver::ResolveHostRequest { public: - // If |use_stale_on_name_not_resolved| and network resolution returns - // ERR_NAME_NOT_RESOLVED, use stale result if available. - explicit RequestImpl(const base::TickClock* tick_clock, - bool use_stale_on_name_not_resolved); - ~RequestImpl(); + // StaleOptions will be read directly from |resolver|. + RequestImpl(base::WeakPtr<StaleHostResolver> resolver, + const net::HostPortPair& host, + const net::NetLogWithSource& net_log, + const ResolveHostParameters& input_parameters, + const base::TickClock* tick_clock); + ~RequestImpl() override; - // A callback for the caller to decide whether a stale entry is usable or not. - typedef base::Callback<bool(const net::HostCache::EntryStaleness&)> - StaleEntryUsableCallback; + // net::HostResolver::ResolveHostRequest implementation: + int Start(net::CompletionOnceCallback result_callback) override; + const base::Optional<net::AddressList>& GetAddressResults() const override; + const base::Optional<std::vector<std::string>>& GetTextResults() + const override; + const base::Optional<std::vector<net::HostPortPair>>& GetHostnameResults() + const override; + const base::Optional<net::HostCache::EntryStaleness>& GetStaleInfo() + const override; + void ChangeRequestPriority(net::RequestPriority priority) override; - // Starts the request. May call |usable_callback| inline if |resolver| returns - // stale data to let the caller decide whether the data is usable. - // - // Returns the result if the request finishes synchronously. Returns - // ERR_IO_PENDING and calls |result_callback| with the result if it finishes - // asynchronously (unless destroyed first). - // - // |addresses| must remain valid until the Request completes (synchronously or - // via |result_callback|) or is canceled by destroying the Request. - int Start(net::HostResolverImpl* resolver, - const net::HostPortPair& host, - const net::HostResolver::ResolveHostParameters& parameters, - net::AddressList* addresses, - net::CompletionOnceCallback result_callback, - std::unique_ptr<net::HostResolver::Request>* out_req, - const net::NetLogWithSource& net_log, - const StaleEntryUsableCallback& usable_callback, - base::TimeDelta stale_delay); - - void ChangeRequestPriority(net::RequestPriority priority); + // Called on completion of an asynchronous (network) inner request. Expected + // to be called by StaleHostResolver::OnNetworkRequestComplete(). + void OnNetworkRequestComplete(int error); private: - class Handle : public net::HostResolver::Request { - public: - explicit Handle(RequestImpl* request) : request_(request) {} - ~Handle() override { request_->OnHandleDestroyed(); } - - void ChangeRequestPriority(net::RequestPriority priority) override { - request_->ChangeRequestPriority(priority); - } - - private: - RequestImpl* request_; - }; - bool have_network_request() const { return network_request_ != nullptr; } - bool have_stale_data() const { - return stale_error_ != net::ERR_DNS_CACHE_MISS; + bool have_cache_data() const { + return cache_error_ != net::ERR_DNS_CACHE_MISS; } bool have_returned() const { return result_callback_.is_null(); } - bool have_handle() const { return handle_ != nullptr; } + + // Determines if |cache_error_| and |cache_request_| represents a usable entry + // per the requirements of |resolver_->options_|. + bool CacheDataIsUsable() const; // Callback for |stale_timer_| that returns stale results. void OnStaleDelayElapsed(); - // Callback for network request that returns fresh results if the request - // hasn't already returned stale results, and completes the request. - void OnNetworkRequestComplete(int error); - void OnHandleDestroyed(); - // Fills |*result_addresses_| if rv is OK and returns rv. - int HandleResult(int rv, const net::AddressList& addresses); - // Fills |*result_addresses_| if rv is OK and calls |result_callback_| with - // rv. - void ReturnResult(int rv, const net::AddressList& addresses); - - void MaybeDeleteThis(); - + // Logging for when the underlying resolve completes synchronously. void RecordSynchronousRequest(); + // Logging for when the overall result is determined on completion of + // |network_request_|. void RecordNetworkRequest( int error, - bool returned_stale_data, bool returned_stale_data_instead_of_network_name_not_resolved); + // Logging for when |stale_timer_| fires and |stale_request_| is to be used as + // the overall result. + void RecordLateRequest(); + // Logging for when the request is cancelled after Start() is called and + // before a result is returned. void RecordCanceledRequest(); - // The address list passed into |Start()| to be filled in when the request - // returns. - net::AddressList* result_addresses_; + base::WeakPtr<StaleHostResolver> resolver_; + + const net::HostPortPair host_; + const net::NetLogWithSource net_log_; + const ResolveHostParameters input_parameters_; + // The callback passed into |Start()| to be called when the request returns. net::CompletionOnceCallback result_callback_; - // Set when |result_callback_| is being called so |OnHandleDestroyed()| - // doesn't delete the request. - bool returning_result_; // The error from the stale cache entry, if there was one. // If not, net::ERR_DNS_CACHE_MISS. - int stale_error_; - // The address list from the stale cache entry, if there was one. - net::AddressList stale_addresses_; + int cache_error_; + // Inner local-only/stale-allowed request. + std::unique_ptr<ResolveHostRequest> cache_request_; // A timer that fires when the |Request| should return stale results, if the // underlying network request has not finished yet. base::OneShotTimer stale_timer_; - // Shared instance of tick clock, overridden for testing. - const base::TickClock* tick_clock_; - // The address list the underlying network request will fill in. (Can't be the - // one passed to |Start()|, or else the network request would overwrite stale - // results after they are returned.) - net::AddressList network_addresses_; - // The underlying network request, so the priority can be changed. - std::unique_ptr<net::HostResolver::Request> network_request_; + // An inner request for network results. Only set if |cache_request_| gave a + // stale or unusable result, and unset if the stale result is to be used as + // the overall result. + std::unique_ptr<ResolveHostRequest> network_request_; // Statistics used in histograms: // Number of HostCache entries that were restored from prefs, recorded at the @@ -201,186 +165,206 @@ // Current HostCache size at the time the cache was checked. size_t current_size_; - // Handle that caller can use to cancel the request before it returns. - // Owned by the caller; cleared via |OnHandleDestroyed()| when destroyed. - Handle* handle_; - - // If |use_stale_on_name_not_resolved| and network resolution returns - // ERR_NAME_NOT_RESOLVED, use stale result if available. - const bool use_stale_on_name_not_resolved_; + base::WeakPtrFactory<RequestImpl> weak_ptr_factory_; }; -StaleHostResolver::RequestImpl::RequestImpl(const base::TickClock* tick_clock, - bool use_stale_on_name_not_resolved) - : result_addresses_(nullptr), - returning_result_(false), - stale_error_(net::ERR_DNS_CACHE_MISS), +StaleHostResolver::RequestImpl::RequestImpl( + base::WeakPtr<StaleHostResolver> resolver, + const net::HostPortPair& host, + const net::NetLogWithSource& net_log, + const ResolveHostParameters& input_parameters, + const base::TickClock* tick_clock) + : resolver_(std::move(resolver)), + host_(host), + net_log_(net_log), + input_parameters_(input_parameters), + cache_error_(net::ERR_DNS_CACHE_MISS), stale_timer_(tick_clock), - tick_clock_(tick_clock), restore_size_(0), current_size_(0), - handle_(nullptr), - use_stale_on_name_not_resolved_(use_stale_on_name_not_resolved) {} + weak_ptr_factory_(this) { + DCHECK(resolver_); +} -StaleHostResolver::RequestImpl::~RequestImpl() {} +StaleHostResolver::RequestImpl::~RequestImpl() { + if (!have_returned()) + RecordCanceledRequest(); +} int StaleHostResolver::RequestImpl::Start( - net::HostResolverImpl* resolver, - const net::HostPortPair& host, - const net::HostResolver::ResolveHostParameters& parameters, - net::AddressList* addresses, - net::CompletionOnceCallback result_callback, - std::unique_ptr<net::HostResolver::Request>* out_req, - const net::NetLogWithSource& net_log, - const StaleEntryUsableCallback& usable_callback, - base::TimeDelta stale_delay) { - DCHECK(resolver); - DCHECK(addresses); + net::CompletionOnceCallback result_callback) { + DCHECK(resolver_); DCHECK(!result_callback.is_null()); - DCHECK(out_req); - DCHECK(!usable_callback.is_null()); - result_addresses_ = addresses; - restore_size_ = resolver->LastRestoredCacheSize(); - current_size_ = resolver->CacheSize(); + restore_size_ = resolver_->inner_resolver_->LastRestoredCacheSize(); + current_size_ = resolver_->inner_resolver_->CacheSize(); - { - net::HostResolver::ResolveHostParameters cache_parameters = parameters; - cache_parameters.cache_usage = - net::HostResolver::ResolveHostParameters::CacheUsage::STALE_ALLOWED; - cache_parameters.source = net::HostResolverSource::LOCAL_ONLY; - std::unique_ptr<net::HostResolver::ResolveHostRequest> cache_request = - resolver->CreateRequest(host, net_log, cache_parameters); - int cache_rv = - cache_request->Start(base::BindOnce([](int error) { NOTREACHED(); })); - DCHECK_NE(net::ERR_IO_PENDING, cache_rv); - // If it's a fresh cache hit (or literal), return it synchronously. - if (cache_rv != net::ERR_DNS_CACHE_MISS && - (!cache_request->GetStaleInfo() || - !cache_request->GetStaleInfo().value().is_stale())) { - RecordSynchronousRequest(); - return HandleResult(cache_rv, cache_request->GetAddressResults().value_or( - net::AddressList())); - } + net::HostResolver::ResolveHostParameters cache_parameters = input_parameters_; + cache_parameters.cache_usage = + net::HostResolver::ResolveHostParameters::CacheUsage::STALE_ALLOWED; + cache_parameters.source = net::HostResolverSource::LOCAL_ONLY; + cache_request_ = resolver_->inner_resolver_->CreateRequest(host_, net_log_, + cache_parameters); + cache_error_ = + cache_request_->Start(base::BindOnce([](int error) { NOTREACHED(); })); + DCHECK_NE(net::ERR_IO_PENDING, cache_error_); + // If it's a fresh cache hit (or literal), return it synchronously. + if (cache_error_ != net::ERR_DNS_CACHE_MISS && + (!cache_request_->GetStaleInfo() || + !cache_request_->GetStaleInfo().value().is_stale())) { + RecordSynchronousRequest(); + return cache_error_; + } - result_callback_ = std::move(result_callback); - handle_ = new Handle(this); - *out_req = base::WrapUnique(handle_); + result_callback_ = std::move(result_callback); - if (cache_rv == net::OK && - usable_callback.Run(cache_request->GetStaleInfo().value())) { - stale_error_ = cache_rv; - stale_addresses_ = cache_request->GetAddressResults().value(); - // |stale_timer_| is deleted when the Request is deleted, so it's safe to - // use Unretained here. - base::Callback<void()> stale_callback = - base::Bind(&StaleHostResolver::RequestImpl::OnStaleDelayElapsed, - base::Unretained(this)); - stale_timer_.Start(FROM_HERE, stale_delay, stale_callback); - } + if (CacheDataIsUsable()) { + // |stale_timer_| is deleted when the Request is deleted, so it's safe to + // use Unretained here. + base::Callback<void()> stale_callback = + base::Bind(&StaleHostResolver::RequestImpl::OnStaleDelayElapsed, + base::Unretained(this)); + stale_timer_.Start(FROM_HERE, resolver_->options_.delay, stale_callback); + } else { + cache_error_ = net::ERR_DNS_CACHE_MISS; + cache_request_.reset(); } // Don't check the cache again. - net::HostResolver::ResolveHostParameters no_cache_parameters = parameters; + net::HostResolver::ResolveHostParameters no_cache_parameters = + input_parameters_; no_cache_parameters.cache_usage = net::HostResolver::ResolveHostParameters::CacheUsage::DISALLOWED; - std::unique_ptr<net::HostResolver::ResolveHostRequest> network_request = - resolver->CreateRequest(host, net_log, no_cache_parameters); - int network_rv = net::HostResolver::LegacyResolve( - std::move(network_request), no_cache_parameters.is_speculative, - &network_addresses_, - base::BindOnce(&StaleHostResolver::RequestImpl::OnNetworkRequestComplete, - base::Unretained(this)), - &network_request_); + network_request_ = resolver_->inner_resolver_->CreateRequest( + host_, net_log_, no_cache_parameters); + int network_rv = network_request_->Start( + base::BindOnce(&StaleHostResolver::OnNetworkRequestComplete, resolver_, + network_request_.get(), weak_ptr_factory_.GetWeakPtr())); + // Network resolver has returned synchronously (for example by resolving from // /etc/hosts). if (network_rv != net::ERR_IO_PENDING) { + stale_timer_.Stop(); RecordSynchronousRequest(); - return HandleResult(network_rv, network_addresses_); } return network_rv; } +const base::Optional<net::AddressList>& +StaleHostResolver::RequestImpl::GetAddressResults() const { + if (network_request_) + return network_request_->GetAddressResults(); + + DCHECK(cache_request_); + return cache_request_->GetAddressResults(); +} + +const base::Optional<std::vector<std::string>>& +StaleHostResolver::RequestImpl::GetTextResults() const { + if (network_request_) + return network_request_->GetTextResults(); + + DCHECK(cache_request_); + return cache_request_->GetTextResults(); +} + +const base::Optional<std::vector<net::HostPortPair>>& +StaleHostResolver::RequestImpl::GetHostnameResults() const { + if (network_request_) + return network_request_->GetHostnameResults(); + + DCHECK(cache_request_); + return cache_request_->GetHostnameResults(); +} + +const base::Optional<net::HostCache::EntryStaleness>& +StaleHostResolver::RequestImpl::GetStaleInfo() const { + if (network_request_) + return network_request_->GetStaleInfo(); + + DCHECK(cache_request_); + return cache_request_->GetStaleInfo(); +} + void StaleHostResolver::RequestImpl::ChangeRequestPriority( net::RequestPriority priority) { - DCHECK(have_network_request()); + if (network_request_) { + network_request_->ChangeRequestPriority(priority); + } else { + DCHECK(cache_request_); + cache_request_->ChangeRequestPriority(priority); + } +} - network_request_->ChangeRequestPriority(priority); +void StaleHostResolver::RequestImpl::OnNetworkRequestComplete(int error) { + DCHECK(resolver_); + DCHECK(have_network_request()); + DCHECK(!have_returned()); + + bool return_stale_data_instead_of_network_name_not_resolved = + resolver_->options_.use_stale_on_name_not_resolved && + error == net::ERR_NAME_NOT_RESOLVED && have_cache_data(); + + RecordNetworkRequest(error, + return_stale_data_instead_of_network_name_not_resolved); + + stale_timer_.Stop(); + + if (return_stale_data_instead_of_network_name_not_resolved) { + network_request_.reset(); + std::move(result_callback_).Run(cache_error_); + } else { + cache_request_.reset(); + std::move(result_callback_).Run(error); + } +} + +bool StaleHostResolver::RequestImpl::CacheDataIsUsable() const { + DCHECK(resolver_); + DCHECK(cache_request_); + + if (cache_error_ != net::OK) + return false; + + DCHECK(cache_request_->GetStaleInfo()); + const net::HostCache::EntryStaleness& staleness = + cache_request_->GetStaleInfo().value(); + + if (resolver_->options_.max_expired_time != base::TimeDelta() && + staleness.expired_by > resolver_->options_.max_expired_time) { + return false; + } + if (resolver_->options_.max_stale_uses > 0 && + staleness.stale_hits > resolver_->options_.max_stale_uses) { + return false; + } + if (!resolver_->options_.allow_other_network && + staleness.network_changes > 0) { + return false; + } + return true; } void StaleHostResolver::RequestImpl::OnStaleDelayElapsed() { DCHECK(!have_returned()); - DCHECK(have_stale_data()); - - ReturnResult(stale_error_, stale_addresses_); - - // The request needs to wait for both the network request to complete (to - // backfill the cache) and the caller to delete the handle before deleting - // itself. + DCHECK(have_cache_data()); DCHECK(have_network_request()); -} -void StaleHostResolver::RequestImpl::OnNetworkRequestComplete(int error) { - DCHECK(have_network_request()); - network_request_.reset(); - - bool return_stale_data_instead_of_network_name_not_resolved = - !have_returned() && use_stale_on_name_not_resolved_ && - error == net::ERR_NAME_NOT_RESOLVED && have_stale_data(); - - RecordNetworkRequest( - error, /* returned_stale_data = */ have_returned() || - return_stale_data_instead_of_network_name_not_resolved, - return_stale_data_instead_of_network_name_not_resolved); - - if (!have_returned()) { - if (have_stale_data()) - stale_timer_.Stop(); - if (return_stale_data_instead_of_network_name_not_resolved) { - ReturnResult(stale_error_, stale_addresses_); - } else { - ReturnResult(error, network_addresses_); - } - } - - if (!have_handle()) - delete this; -} - -void StaleHostResolver::RequestImpl::OnHandleDestroyed() { - DCHECK(have_handle()); - handle_ = nullptr; - - // If the caller deletes the handle *before* the request has returned, treat - // it as a cancel. - if (!have_returned()) { + // If resolver is destroyed after starting a request, the request is + // considered cancelled and callbacks must not be invoked. Logging the + // cancellation will happen on destruction of |this|. + if (!resolver_) { network_request_.reset(); - result_callback_ = net::CompletionOnceCallback(); - RecordCanceledRequest(); + return; } + DCHECK(CacheDataIsUsable()); - if (!returning_result_ && !have_handle() && !have_network_request()) - delete this; -} + // Detach |network_request_| to allow it to complete and backfill the cache + // even if |this| is destroyed. + resolver_->DetachRequest(std::move(network_request_)); -int StaleHostResolver::RequestImpl::HandleResult( - int rv, - const net::AddressList& addresses) { - DCHECK(result_addresses_); - - if (rv == net::OK) - *result_addresses_ = addresses; - result_addresses_ = nullptr; - return rv; -} - -void StaleHostResolver::RequestImpl::ReturnResult( - int rv, - const net::AddressList& addresses) { - DCHECK(result_callback_); - returning_result_ = true; - std::move(result_callback_).Run(HandleResult(rv, addresses)); - returning_result_ = false; + RecordLateRequest(); + std::move(result_callback_).Run(cache_error_); } void StaleHostResolver::RequestImpl::RecordSynchronousRequest() { @@ -389,32 +373,44 @@ void StaleHostResolver::RequestImpl::RecordNetworkRequest( int error, - bool returned_stale_data, bool returned_stale_data_instead_of_network_name_not_resolved) { - if (have_stale_data()) - RecordTimeDelta(tick_clock_->NowTicks(), stale_timer_.desired_run_time()); + DCHECK(resolver_); - if (returned_stale_data && stale_error_ == net::OK && error == net::OK) { - RecordAddressListDelta( - FindAddressListDeltaType(stale_addresses_, network_addresses_)); - } + if (have_cache_data()) { + RecordTimeDelta(resolver_->tick_clock_->NowTicks(), + stale_timer_.desired_run_time()); - if (returned_stale_data) { + if (cache_request_->GetAddressResults() && error == net::OK && + network_request_->GetAddressResults()) { + RecordAddressListDelta(FindAddressListDeltaType( + cache_request_->GetAddressResults().value(), + network_request_->GetAddressResults().value())); + } + if (returned_stale_data_instead_of_network_name_not_resolved) { RecordRequestOutcome(STALE_INSTEAD_OF_NETWORK_NAME_NOT_RESOLVED); } else { - RecordRequestOutcome(STALE_BEFORE_NETWORK); + RecordRequestOutcome(NETWORK_WITH_STALE); + RecordCacheSizes(restore_size_, current_size_); } - } else if (have_stale_data()) { - RecordRequestOutcome(NETWORK_WITH_STALE); - RecordCacheSizes(restore_size_, current_size_); } else { RecordRequestOutcome(NETWORK_WITHOUT_STALE); } } +void StaleHostResolver::RequestImpl::RecordLateRequest() { + DCHECK(resolver_); + DCHECK(have_cache_data()); + + RecordTimeDelta(resolver_->tick_clock_->NowTicks(), + stale_timer_.desired_run_time()); + RecordRequestOutcome(STALE_BEFORE_NETWORK); +} + void StaleHostResolver::RequestImpl::RecordCanceledRequest() { - if (have_stale_data()) + DCHECK(!have_returned()); + + if (have_cache_data()) RecordRequestOutcome(CANCELED_WITH_STALE); else RecordRequestOutcome(CANCELED_WITHOUT_STALE); @@ -428,7 +424,9 @@ StaleHostResolver::StaleHostResolver( std::unique_ptr<net::HostResolverImpl> inner_resolver, const StaleOptions& stale_options) - : inner_resolver_(std::move(inner_resolver)), options_(stale_options) { + : inner_resolver_(std::move(inner_resolver)), + options_(stale_options), + weak_ptr_factory_(this) { DCHECK_LE(0, stale_options.max_expired_time.InMicroseconds()); DCHECK_LE(0, stale_options.max_stale_uses); } @@ -440,9 +438,10 @@ const net::HostPortPair& host, const net::NetLogWithSource& net_log, const base::Optional<ResolveHostParameters>& optional_parameters) { - // TODO(crbug.com/821021): Implement. - NOTIMPLEMENTED(); - return nullptr; + DCHECK(tick_clock_); + return std::make_unique<RequestImpl>( + weak_ptr_factory_.GetWeakPtr(), host, net_log, + optional_parameters.value_or(ResolveHostParameters()), tick_clock_); } int StaleHostResolver::Resolve(const RequestInfo& info, @@ -451,20 +450,11 @@ net::CompletionOnceCallback callback, std::unique_ptr<Request>* out_req, const net::NetLogWithSource& net_log) { - DCHECK(tick_clock_); - StaleHostResolver::RequestImpl::StaleEntryUsableCallback usable_callback = - base::Bind(&StaleEntryIsUsable, options_); - RequestImpl* request = - new RequestImpl(tick_clock_, options_.use_stale_on_name_not_resolved); - net::HostResolver::ResolveHostParameters parameters = - net::HostResolver::RequestInfoToResolveHostParameters(info, priority); - int rv = request->Start(inner_resolver_.get(), info.host_port_pair(), - parameters, addresses, std::move(callback), out_req, - net_log, usable_callback, options_.delay); - if (rv != net::ERR_IO_PENDING) - delete request; - - return rv; + std::unique_ptr<ResolveHostRequest> inner_request = + CreateRequest(info.host_port_pair(), net_log, + RequestInfoToResolveHostParameters(info, priority)); + return LegacyResolve(std::move(inner_request), info.is_speculative(), + addresses, std::move(callback), out_req); } int StaleHostResolver::ResolveFromCache(const RequestInfo& info, @@ -501,6 +491,27 @@ return inner_resolver_->GetDnsConfigAsValue(); } +void StaleHostResolver::OnNetworkRequestComplete( + ResolveHostRequest* network_request, + base::WeakPtr<RequestImpl> stale_request, + int error) { + if (detached_requests_.erase(network_request)) + return; + + // If not a detached request, there should still be an owning RequestImpl. + // Otherwise the request should have been cancelled and this method never + // called. + DCHECK(stale_request); + + stale_request->OnNetworkRequestComplete(error); +} + +void StaleHostResolver::DetachRequest( + std::unique_ptr<ResolveHostRequest> request) { + DCHECK_EQ(0u, detached_requests_.count(request.get())); + detached_requests_[request.get()] = std::move(request); +} + void StaleHostResolver::SetTickClockForTesting( const base::TickClock* tick_clock) { tick_clock_ = tick_clock;
diff --git a/components/cronet/stale_host_resolver.h b/components/cronet/stale_host_resolver.h index 687019d4..60f6208e 100644 --- a/components/cronet/stale_host_resolver.h +++ b/components/cronet/stale_host_resolver.h
@@ -6,8 +6,9 @@ #define COMPONENTS_CRONET_STALE_HOST_RESOLVER_H_ #include <memory> -#include <unordered_set> +#include <unordered_map> +#include "base/memory/weak_ptr.h" #include "base/time/default_tick_clock.h" #include "net/base/completion_once_callback.h" #include "net/dns/host_resolver.h" @@ -106,8 +107,16 @@ class RequestImpl; friend class StaleHostResolverTest; - // Called from |Request| when a request is complete and can be destroyed. - void OnRequestComplete(Request* request); + // Called on completion of |network_request| when completed asynchronously (a + // "network" request). Determines if the request is owned by a RequestImpl or + // if it is a detached request and handles appropriately. + void OnNetworkRequestComplete(ResolveHostRequest* network_request, + base::WeakPtr<RequestImpl> stale_request, + int error); + + // Detach an inner request from a RequestImpl, letting it finish (and populate + // the host cache) as long as |this| is not destroyed. + void DetachRequest(std::unique_ptr<ResolveHostRequest> request); // Set |tick_clock_| for testing. Must be set before issuing any requests. void SetTickClockForTesting(const base::TickClock* tick_clock); @@ -120,7 +129,14 @@ const base::TickClock* tick_clock_ = base::DefaultTickClock::GetInstance(); // Options that govern when a stale response can or can't be returned. - StaleOptions options_; + const StaleOptions options_; + + // Requests not used for returned results but allowed to continue (unless + // |this| is destroyed) to backfill the cache. + std::unordered_map<ResolveHostRequest*, std::unique_ptr<ResolveHostRequest>> + detached_requests_; + + base::WeakPtrFactory<StaleHostResolver> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(StaleHostResolver); };
diff --git a/components/cronet/stale_host_resolver_unittest.cc b/components/cronet/stale_host_resolver_unittest.cc index 65c9356..f028661 100644 --- a/components/cronet/stale_host_resolver_unittest.cc +++ b/components/cronet/stale_host_resolver_unittest.cc
@@ -32,6 +32,7 @@ #include "net/dns/dns_test_util.h" #include "net/dns/host_resolver_impl.h" #include "net/dns/host_resolver_proc.h" +#include "net/dns/public/dns_protocol.h" #include "net/http/http_network_session.h" #include "net/log/net_log.h" #include "net/log/net_log_with_source.h" @@ -82,6 +83,25 @@ net::MockDnsClientRuleList()); } +// Create a net::DnsClient where address requests for |kHostname| will hang +// until unblocked via CompleteDelayedTransactions() and then fail. +std::unique_ptr<net::MockDnsClient> CreateHangingMockDnsClient() { + net::DnsConfig config; + config.nameservers.push_back(net::IPEndPoint()); + + net::MockDnsClientRuleList rules; + rules.emplace_back( + kHostname, net::dns_protocol::kTypeA, + net::MockDnsClientRule::Result(net::MockDnsClientRule::FAIL), + true /* delay */); + rules.emplace_back( + kHostname, net::dns_protocol::kTypeAAAA, + net::MockDnsClientRule::Result(net::MockDnsClientRule::FAIL), + true /* delay */); + + return std::make_unique<net::MockDnsClient>(config, std::move(rules)); +} + class MockHostResolverProc : public net::HostResolverProc { public: // |result| is the net error code to return from resolution attempts. @@ -397,6 +417,20 @@ EXPECT_EQ(kCacheAddress, resolve_addresses()[0].ToStringWithoutPort()); } +// If the resolver is destroyed before a stale cache entry is returned, the +// resolve should not complete. +TEST_F(StaleHostResolverTest, StaleCache_DestroyedResolver) { + SetStaleDelay(kNoStaleDelaySec); + CreateResolverWithDnsClient(CreateHangingMockDnsClient()); + CreateCacheEntry(kAgeExpiredSec, net::OK); + + Resolve(); + DestroyResolver(); + WaitForResolve(); + + EXPECT_FALSE(resolve_complete()); +} + // Ensure that |use_stale_on_name_not_resolved| causes stale results to be // returned when ERR_NAME_NOT_RESOLVED is returned from network resolution. TEST_F(StaleHostResolverTest, StaleCacheNameNotResolvedEnabled) {
diff --git a/components/cronet/test/test_server.cc b/components/cronet/test/test_server.cc index bba65bfa..ac4f367 100644 --- a/components/cronet/test/test_server.cc +++ b/components/cronet/test/test_server.cc
@@ -267,7 +267,7 @@ response_builder += std::string(data_size, 'c'); g_big_data_body.Get() = response_builder; return g_test_server - ->GetURL(kBigDataPath + base::Int64ToString(response_builder.size())) + ->GetURL(kBigDataPath + base::NumberToString(response_builder.size())) .spec(); }
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.cc b/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.cc index c186174..3279d3cf 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.cc +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.cc
@@ -71,7 +71,7 @@ // Newly added lists are empty. Add entries to back to fill the window, // each initialized to zero. while (list->GetSize() < length) - list->AppendString(base::Int64ToString(0)); + list->AppendString(base::NumberToString(0)); DCHECK_EQ(length, list->GetSize()); } @@ -83,7 +83,7 @@ base::ListValue* list_update) { int64_t value = GetInt64PrefValue(*list_update, index) + length; list_update->Set(index, - std::make_unique<base::Value>(base::Int64ToString(value))); + std::make_unique<base::Value>(base::NumberToString(value))); } // DailyContentLengthUpdate maintains a data saving pref. The pref is a list @@ -227,7 +227,7 @@ int value) { DictionaryPrefUpdate pref_update(pref_service, pref); base::DictionaryValue* pref_dict = pref_update.Get(); - const std::string key_str = base::IntToString(key); + const std::string key_str = base::NumberToString(key); base::Value* dict_value = pref_dict->FindKey(key_str); if (dict_value) value += dict_value->GetInt(); @@ -365,7 +365,7 @@ for (int i = 0; i < days_since_last_update && i < static_cast<int>(kNumDaysInHistory); ++i) { - update_->AppendString(base::Int64ToString(0)); + update_->AppendString(base::NumberToString(0)); } // Entries for new days may have been appended. Maintain the invariant that @@ -619,8 +619,8 @@ original_update->Clear(); received_update->Clear(); for (size_t i = 0; i < kNumDaysInHistory; ++i) { - original_update->AppendString(base::Int64ToString(0)); - received_update->AppendString(base::Int64ToString(0)); + original_update->AppendString(base::NumberToString(0)); + received_update->AppendString(base::NumberToString(0)); } }
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats_unittest.cc b/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats_unittest.cc index a957678c4..4d7ff43 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats_unittest.cc +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats_unittest.cc
@@ -176,7 +176,7 @@ base::ListValue* update = compression_stats_->GetList(pref); update->Clear(); for (size_t i = 0; i < kNumDaysInHistory; ++i) { - update->Insert(0, std::make_unique<base::Value>(base::Int64ToString(0))); + update->Insert(0, std::make_unique<base::Value>(base::NumberToString(0))); } } @@ -492,10 +492,10 @@ int expected_value) const { const base::DictionaryValue* dict = compression_stats_->pref_service_->GetDictionary(pref); - EXPECT_EQ(expected_value != 0, dict->HasKey(base::IntToString(key))); + EXPECT_EQ(expected_value != 0, dict->HasKey(base::NumberToString(key))); if (expected_value) { EXPECT_EQ(expected_value, - dict->FindKey(base::IntToString(key))->GetInt()); + dict->FindKey(base::NumberToString(key))->GetInt()); } } @@ -537,7 +537,7 @@ TEST_F(DataReductionProxyCompressionStatsTest, StatsRestoredOnOnRestart) { base::ListValue list_value; list_value.Insert(0, - std::make_unique<base::Value>(base::Int64ToString(1234))); + std::make_unique<base::Value>(base::NumberToString(1234))); pref_service()->Set(prefs::kDailyHttpOriginalContentLength, list_value); ResetCompressionStatsWithDelay(
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_config.cc b/components/data_reduction_proxy/core/browser/data_reduction_proxy_config.cc index 71af80b01..7e62475 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_config.cc +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_config.cc
@@ -172,7 +172,7 @@ // connection type. return "cell," + ssid_mccmnc; } - return base::IntToString(static_cast<int>(connection_type)) + "," + + return base::NumberToString(static_cast<int>(connection_type)) + "," + ssid_mccmnc; } }
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_delegate_unittest.cc b/components/data_reduction_proxy/core/browser/data_reduction_proxy_delegate_unittest.cc index 610e5832..3ddb9cc 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_delegate_unittest.cc +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_delegate_unittest.cc
@@ -873,10 +873,10 @@ {"HTTP/1.1 200 OK\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "Content-Length: " + - base::Int64ToString(static_cast<int64_t>(1) << 60) + + base::NumberToString(static_cast<int64_t>(1) << 60) + "\r\n" "Chrome-Proxy: ofcl=" + - base::Int64ToString((static_cast<int64_t>(1) << 60) * 3) + + base::NumberToString((static_cast<int64_t>(1) << 60) * 3) + "\r\n\r\n", 100, 300}, {"HTTP/1.1 206 Partial Content\r\n"
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_network_delegate_unittest.cc b/components/data_reduction_proxy/core/browser/data_reduction_proxy_network_delegate_unittest.cc index 9483aad..dc2a149 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_network_delegate_unittest.cc +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_network_delegate_unittest.cc
@@ -1066,7 +1066,7 @@ "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "Chrome-Proxy: ofcl=" + - base::Int64ToString(kOriginalContentLength) + "\r\n\r\n"; + base::NumberToString(kOriginalContentLength) + "\r\n\r\n"; std::unique_ptr<net::URLRequest> fake_request(FetchURLRequest( GURL(kTestURL), nullptr, response_headers, kResponseContentLength, 0)); @@ -1111,7 +1111,7 @@ "Content-Type: video/mp4\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "Chrome-Proxy: ofcl=" + - base::Int64ToString(kOriginalContentLength) + "\r\n\r\n"; + base::NumberToString(kOriginalContentLength) + "\r\n\r\n"; FetchURLRequest(GURL(kTestURL), nullptr, video_response_headers, kResponseContentLength, 0); @@ -1290,8 +1290,9 @@ if (test.proxy_config == USE_INSECURE_PROXY) { via_header = "Via: 1.1 Chrome-Compression-Proxy\r\n"; - ocl_header = "Chrome-Proxy: ofcl=" + - base::Int64ToString(kOriginalContentLength) + "\r\n"; + ocl_header = + "Chrome-Proxy: ofcl=" + base::NumberToString(kOriginalContentLength) + + "\r\n"; } if (test.is_video) { // Check video
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs_unittest.cc b/components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs_unittest.cc index 8d241701..52730fe 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs_unittest.cc +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs_unittest.cc
@@ -39,7 +39,7 @@ PrefService* pref_service) { ListPrefUpdate list(local_state_prefs(), pref_name); for (int64_t i = 0; i < 10L; ++i) { - list->AppendString(base::Int64ToString(i + starting_value)); + list->AppendString(base::NumberToString(i + starting_value)); } }
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_settings_test_utils.cc b/components/data_reduction_proxy/core/browser/data_reduction_proxy_settings_test_utils.cc index 0945cd2..42e379d 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_settings_test_utils.cc +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_settings_test_utils.cc
@@ -59,9 +59,9 @@ prefs::kDailyHttpReceivedContentLength); for (int64_t i = 0; i < kNumDaysInHistory; i++) { original_update->Insert( - 0, std::make_unique<base::Value>(base::Int64ToString(2 * i))); + 0, std::make_unique<base::Value>(base::NumberToString(2 * i))); received_update->Insert( - 0, std::make_unique<base::Value>(base::Int64ToString(i))); + 0, std::make_unique<base::Value>(base::NumberToString(i))); } last_update_time_ = base::Time::Now().LocalMidnight(); pref_service->SetInt64(prefs::kDailyHttpContentLengthLastUpdateDate,
diff --git a/components/data_reduction_proxy/core/browser/data_usage_store.cc b/components/data_reduction_proxy/core/browser/data_usage_store.cc index dc1d7fd1..2f3f3d3 100644 --- a/components/data_reduction_proxy/core/browser/data_usage_store.cc +++ b/components/data_reduction_proxy/core/browser/data_usage_store.cc
@@ -143,7 +143,7 @@ base::Time::FromInternalValue(current.last_updated_timestamp()); buckets_to_save.insert(std::pair<std::string, std::string>( - kCurrentBucketIndexKey, base::IntToString(current_bucket_index_))); + kCurrentBucketIndexKey, base::NumberToString(current_bucket_index_))); DataStore::Status status = db_->Put(buckets_to_save); if (status != DataStore::Status::OK) {
diff --git a/components/data_reduction_proxy/core/browser/network_properties_manager_unittest.cc b/components/data_reduction_proxy/core/browser/network_properties_manager_unittest.cc index 0910e87..1129033 100644 --- a/components/data_reduction_proxy/core/browser/network_properties_manager_unittest.cc +++ b/components/data_reduction_proxy/core/browser/network_properties_manager_unittest.cc
@@ -243,7 +243,7 @@ size_t num_network_ids = 100; for (size_t i = 0; i < num_network_ids; ++i) { - std::string network_id("test" + base::IntToString(i)); + std::string network_id("test" + base::NumberToString(i)); network_properties_manager.OnChangeInNetworkID(network_id); // State should be reset when there is a change in the network ID. @@ -271,14 +271,14 @@ // The last 10 network IDs are guaranteed to be present in the prefs. for (size_t i = num_network_ids - 10; i < num_network_ids; ++i) { EXPECT_TRUE(test_prefs.GetDictionary(prefs::kNetworkProperties) - ->HasKey("test" + base::IntToString(i))); + ->HasKey("test" + base::NumberToString(i))); } { TestNetworkPropertiesManager network_properties_manager_2( &test_prefs, base::ThreadTaskRunnerHandle::Get()); for (size_t i = 0; i < num_network_ids; ++i) { - std::string network_id("test" + base::IntToString(i)); + std::string network_id("test" + base::NumberToString(i)); network_properties_manager_2.OnChangeInNetworkID(network_id); EXPECT_EQ(test_prefs.GetDictionary(prefs::kNetworkProperties) @@ -466,7 +466,7 @@ &test_clock, &test_prefs, base::ThreadTaskRunnerHandle::Get()); for (size_t i = 0; i < 5; ++i) { - std::string network_id("test" + base::IntToString(i)); + std::string network_id("test" + base::NumberToString(i)); network_properties_manager.OnChangeInNetworkID(network_id); network_properties_manager.SetIsCaptivePortal(true); } @@ -474,7 +474,7 @@ test_clock.Advance(base::TimeDelta::FromDays(20)); for (size_t i = 5; i < 10; ++i) { - std::string network_id("test" + base::IntToString(i)); + std::string network_id("test" + base::NumberToString(i)); network_properties_manager.OnChangeInNetworkID(network_id); network_properties_manager.SetIsCaptivePortal(true); } @@ -484,7 +484,7 @@ // Verify the prefs. EXPECT_EQ(10u, test_prefs.GetDictionary(prefs::kNetworkProperties)->size()); for (size_t i = 0; i < 10; ++i) { - std::string network_id("test" + base::IntToString(i)); + std::string network_id("test" + base::NumberToString(i)); EXPECT_TRUE(test_prefs.GetDictionary(prefs::kNetworkProperties) ->HasKey(network_id)); } @@ -494,7 +494,7 @@ TestNetworkPropertiesManager network_properties_manager_2( &test_clock, &test_prefs, base::ThreadTaskRunnerHandle::Get()); for (size_t i = 0; i < 10; ++i) { - std::string network_id("test" + base::IntToString(i)); + std::string network_id("test" + base::NumberToString(i)); EXPECT_TRUE(test_prefs.GetDictionary(prefs::kNetworkProperties) ->HasKey(network_id)); @@ -507,7 +507,7 @@ TestNetworkPropertiesManager network_properties_manager_3( &test_clock, &test_prefs, base::ThreadTaskRunnerHandle::Get()); for (size_t i = 0; i < 10; ++i) { - std::string network_id("test" + base::IntToString(i)); + std::string network_id("test" + base::NumberToString(i)); EXPECT_EQ(i >= 5, test_prefs.GetDictionary(prefs::kNetworkProperties) ->HasKey(network_id)); }
diff --git a/components/data_reduction_proxy/core/browser/warmup_url_fetcher_unittest.cc b/components/data_reduction_proxy/core/browser/warmup_url_fetcher_unittest.cc index 86c4195..e219a28 100644 --- a/components/data_reduction_proxy/core/browser/warmup_url_fetcher_unittest.cc +++ b/components/data_reduction_proxy/core/browser/warmup_url_fetcher_unittest.cc
@@ -76,9 +76,9 @@ base::TimeDelta second_retry) { std::map<std::string, std::string> params; params["warmup_url_fetch_wait_timer_first_retry_seconds"] = - base::IntToString(first_retry.InSeconds()); + base::NumberToString(first_retry.InSeconds()); params["warmup_url_fetch_wait_timer_second_retry_seconds"] = - base::IntToString(second_retry.InSeconds()); + base::NumberToString(second_retry.InSeconds()); scoped_feature_list->InitAndEnableFeatureWithParameters( features::kDataReductionProxyRobustConnection, params); }
diff --git a/components/data_reduction_proxy/core/common/data_reduction_proxy_headers.cc b/components/data_reduction_proxy/core/common/data_reduction_proxy_headers.cc index fdac908..0e4394a 100644 --- a/components/data_reduction_proxy/core/common/data_reduction_proxy_headers.cc +++ b/components/data_reduction_proxy/core/common/data_reduction_proxy_headers.cc
@@ -9,7 +9,6 @@ #include <string> #include <utility> -#include <vector> #include "base/metrics/field_trial_params.h" #include "base/rand_util.h" @@ -103,17 +102,6 @@ IsPreviewTypeInHeaderValue(value, transform_type); } -// Returns true if there is a cycle in |url_chain|. -bool HasURLRedirectCycle(const std::vector<GURL>& url_chain) { - if (url_chain.size() <= 1) - return false; - - // If the last entry occurs earlier in the |url_chain|, then very likely there - // is a redirect cycle. - return std::find(url_chain.rbegin() + 1, url_chain.rend(), - url_chain.back()) != url_chain.rend(); -} - data_reduction_proxy::TransformDirective ParsePagePolicyDirective( const std::string chrome_proxy_header_value) { for (const auto& directive : base::SplitStringPiece( @@ -178,6 +166,16 @@ return kChromeProxyPagePoliciesDirective; } +bool HasURLRedirectCycle(const std::vector<GURL>& url_chain) { + if (url_chain.size() <= 1) + return false; + + // If the last entry occurs earlier in the |url_chain|, then very likely there + // is a redirect cycle. + return std::find(url_chain.rbegin() + 1, url_chain.rend(), + url_chain.back()) != url_chain.rend(); +} + TransformDirective ParseRequestTransform( const net::HttpRequestHeaders& headers) { std::string accept_transform_value;
diff --git a/components/data_reduction_proxy/core/common/data_reduction_proxy_headers.h b/components/data_reduction_proxy/core/common/data_reduction_proxy_headers.h index c97170e..45ace3b 100644 --- a/components/data_reduction_proxy/core/common/data_reduction_proxy_headers.h +++ b/components/data_reduction_proxy/core/common/data_reduction_proxy_headers.h
@@ -14,6 +14,7 @@ #include "net/http/http_request_headers.h" #include "net/http/http_response_headers.h" #include "net/proxy_resolution/proxy_resolution_service.h" +#include "url/gurl.h" class GURL; @@ -120,6 +121,9 @@ // that an empty image has been provided. bool IsEmptyImagePreview(const net::HttpResponseHeaders& headers); +// Returns true if there is a cycle in |url_chain|. +bool HasURLRedirectCycle(const std::vector<GURL>& url_chain); + // Retrieves the accepted transform type, if any, from |headers|. TransformDirective ParseRequestTransform( const net::HttpRequestHeaders& headers);
diff --git a/components/dom_distiller/core/distiller.cc b/components/dom_distiller/core/distiller.cc index 86cf468..fe4fbea 100644 --- a/components/dom_distiller/core/distiller.cc +++ b/components/dom_distiller/core/distiller.cc
@@ -285,8 +285,8 @@ for (int img_num = 0; img_num < distiller_result->content_images_size(); ++img_num) { - std::string image_id = - base::IntToString(page_num + 1) + "_" + base::IntToString(img_num); + std::string image_id = base::NumberToString(page_num + 1) + "_" + + base::NumberToString(img_num); MaybeFetchImage(page_num, image_id, distiller_result->content_images(img_num).url()); }
diff --git a/components/dom_distiller/core/distiller_unittest.cc b/components/dom_distiller/core/distiller_unittest.cc index 1de5eb92..48a1ee4 100644 --- a/components/dom_distiller/core/distiller_unittest.cc +++ b/components/dom_distiller/core/distiller_unittest.cc
@@ -60,7 +60,7 @@ const char kDebugLog[] = "Debug Log"; const string GetImageName(int page_num, int image_num) { - return base::IntToString(page_num) + "_" + base::IntToString(image_num); + return base::NumberToString(page_num) + "_" + base::NumberToString(image_num); } std::unique_ptr<base::Value> CreateDistilledValueReturnedFromJS(
diff --git a/components/dom_distiller/core/dom_distiller_service_unittest.cc b/components/dom_distiller/core/dom_distiller_service_unittest.cc index 10d5652c..5fe955c 100644 --- a/components/dom_distiller/core/dom_distiller_service_unittest.cc +++ b/components/dom_distiller/core/dom_distiller_service_unittest.cc
@@ -410,7 +410,7 @@ std::string base_url("http://www.example.com/p"); GURL pages_url[kPageCount]; for (int page_num = 0; page_num < kPageCount; ++page_num) { - pages_url[page_num] = GURL(base_url + base::IntToString(page_num)); + pages_url[page_num] = GURL(base_url + base::NumberToString(page_num)); } MockArticleAvailableCallback article_cb; @@ -529,7 +529,7 @@ std::string base_url("http://www.example.com/p"); GURL pages_url[kPageCount]; for (int page_num = 0; page_num < kPageCount; ++page_num) { - pages_url[page_num] = GURL(base_url + base::IntToString(page_num)); + pages_url[page_num] = GURL(base_url + base::NumberToString(page_num)); } MockArticleAvailableCallback article_cb;
diff --git a/components/dom_distiller/core/url_utils.cc b/components/dom_distiller/core/url_utils.cc index c34ec2932..cac08dd 100644 --- a/components/dom_distiller/core/url_utils.cc +++ b/components/dom_distiller/core/url_utils.cc
@@ -35,8 +35,8 @@ int64_t start_time_ms) { GURL url(scheme + "://" + base::GenerateGUID()); if (start_time_ms > 0) { - url = net::AppendOrReplaceQueryParameter(url, kTimeKey, - base::IntToString(start_time_ms)); + url = net::AppendOrReplaceQueryParameter( + url, kTimeKey, base::NumberToString(start_time_ms)); } return net::AppendOrReplaceQueryParameter(url, kUrlKey, view_url.spec()); }
diff --git a/components/domain_reliability/header.cc b/components/domain_reliability/header.cc index 81f19084..93cb220b 100644 --- a/components/domain_reliability/header.cc +++ b/components/domain_reliability/header.cc
@@ -291,7 +291,7 @@ string += "; "; } - string += "max-age=" + base::Int64ToString(max_age_s) + "; "; + string += "max-age=" + base::NumberToString(max_age_s) + "; "; if (config_->include_subdomains) string += "includeSubdomains; ";
diff --git a/components/download/internal/background_service/scheduler/scheduler_impl_unittest.cc b/components/download/internal/background_service/scheduler/scheduler_impl_unittest.cc index 35eb57b4..69247125 100644 --- a/components/download/internal/background_service/scheduler/scheduler_impl_unittest.cc +++ b/components/download/internal/background_service/scheduler/scheduler_impl_unittest.cc
@@ -49,7 +49,7 @@ void BuildDataEntries(size_t size) { entries_ = std::vector<Entry>(size, Entry()); for (size_t i = 0; i < size; ++i) { - entries_[i].guid = base::IntToString(i); + entries_[i].guid = base::NumberToString(i); entries_[i].scheduling_params.battery_requirements = SchedulingParams::BatteryRequirements::BATTERY_SENSITIVE; entries_[i].scheduling_params.network_requirements =
diff --git a/components/download/public/common/download_url_parameters.cc b/components/download/public/common/download_url_parameters.cc index 67787e54..c7c6897 100644 --- a/components/download/public/common/download_url_parameters.cc +++ b/components/download/public/common/download_url_parameters.cc
@@ -32,6 +32,7 @@ render_process_host_id_(render_process_host_id), render_view_host_routing_id_(render_view_host_routing_id), render_frame_host_routing_id_(render_frame_host_routing_id), + frame_tree_node_id_(-1), url_(url), do_not_prompt_for_login_(false), follow_cross_origin_redirects_(true),
diff --git a/components/download/public/common/download_url_parameters.h b/components/download/public/common/download_url_parameters.h index eaa1a48..214d419 100644 --- a/components/download/public/common/download_url_parameters.h +++ b/components/download/public/common/download_url_parameters.h
@@ -275,6 +275,9 @@ return render_frame_host_routing_id_; } + void set_frame_tree_node_id(int id) { frame_tree_node_id_ = id; } + int frame_tree_node_id() const { return frame_tree_node_id_; } + const RequestHeadersType& request_headers() const { return request_headers_; } const base::FilePath& file_path() const { return save_info_.file_path; } const base::string16& suggested_name() const { @@ -328,6 +331,7 @@ int render_process_host_id_; int render_view_host_routing_id_; int render_frame_host_routing_id_; + int frame_tree_node_id_; DownloadSaveInfo save_info_; GURL url_; bool do_not_prompt_for_login_;
diff --git a/components/drive/chromeos/change_list_loader.cc b/components/drive/chromeos/change_list_loader.cc index e7d495be..e2801b7 100644 --- a/components/drive/chromeos/change_list_loader.cc +++ b/components/drive/chromeos/change_list_loader.cc
@@ -497,7 +497,7 @@ logger_->Log(logging::LOG_INFO, "Change lists applied (%s) (elapsed time: %sms)", team_drive_msg_.c_str(), - base::Int64ToString(elapsed.InMilliseconds()).c_str()); + base::NumberToString(elapsed.InMilliseconds()).c_str()); if (should_notify_changed_directories) { for (auto& observer : observers_)
diff --git a/components/drive/drive_uploader.cc b/components/drive/drive_uploader.cc index 4030786..c10dcb8 100644 --- a/components/drive/drive_uploader.cc +++ b/components/drive/drive_uploader.cc
@@ -116,10 +116,9 @@ // Useful for printf debugging. std::string DebugString() const { - return "file_path=[" + file_path.AsUTF8Unsafe() + - "], content_type=[" + content_type + - "], content_length=[" + base::Int64ToString(content_length) + - "]"; + return "file_path=[" + file_path.AsUTF8Unsafe() + "], content_type=[" + + content_type + "], content_length=[" + + base::NumberToString(content_length) + "]"; } // Returns the callback to cancel the upload represented by this struct.
diff --git a/components/drive/job_list.cc b/components/drive/job_list.cc index bb03cdfa9..91aaf42 100644 --- a/components/drive/job_list.cc +++ b/components/drive/job_list.cc
@@ -93,10 +93,9 @@ if (job_type == TYPE_DOWNLOAD_FILE || job_type == TYPE_UPLOAD_NEW_FILE || job_type == TYPE_UPLOAD_EXISTING_FILE) { - base::StringAppendF(&output, - " bytes: %s/%s", - base::Int64ToString(num_completed_bytes).c_str(), - base::Int64ToString(num_total_bytes).c_str()); + base::StringAppendF(&output, " bytes: %s/%s", + base::NumberToString(num_completed_bytes).c_str(), + base::NumberToString(num_total_bytes).c_str()); } return output; }
diff --git a/components/drive/job_scheduler.cc b/components/drive/job_scheduler.cc index a562b80..327e6c0 100644 --- a/components/drive/job_scheduler.cc +++ b/components/drive/job_scheduler.cc
@@ -920,7 +920,7 @@ "Job done: %s => %s (elapsed time: %sms) - %s", job_info->ToString().c_str(), DriveApiErrorCodeToString(error).c_str(), - base::Int64ToString(elapsed.InMilliseconds()).c_str(), + base::NumberToString(elapsed.InMilliseconds()).c_str(), GetQueueInfo(queue_type).c_str()); // Retry, depending on the error. @@ -1188,7 +1188,7 @@ "Job aborted: %s => %s (elapsed time: %sms) - %s", job->job_info.ToString().c_str(), DriveApiErrorCodeToString(error).c_str(), - base::Int64ToString(elapsed.InMilliseconds()).c_str(), + base::NumberToString(elapsed.InMilliseconds()).c_str(), GetQueueInfo(queue_type).c_str()); base::Callback<void(google_apis::DriveApiErrorCode)> callback =
diff --git a/components/drive/service/fake_drive_service.cc b/components/drive/service/fake_drive_service.cc index f1c92e5..527856f51 100644 --- a/components/drive/service/fake_drive_service.cc +++ b/components/drive/service/fake_drive_service.cc
@@ -1888,7 +1888,7 @@ max_results)); if (start_changestamp > 0) { next_url = net::AppendOrReplaceQueryParameter( - next_url, "changestamp", base::Int64ToString(start_changestamp)); + next_url, "changestamp", base::NumberToString(start_changestamp)); } if (!search_query.empty()) { next_url = net::AppendOrReplaceQueryParameter( @@ -1916,7 +1916,7 @@ GURL FakeDriveService::GetNewUploadSessionUrl() { return GURL("https://upload_session_url/" + - base::Int64ToString(next_upload_sequence_number_++)); + base::NumberToString(next_upload_sequence_number_++)); } google_apis::CancelCallback FakeDriveService::AddPermission(
diff --git a/components/embedder_support/android/BUILD.gn b/components/embedder_support/android/BUILD.gn index ba53ed8..7eb08dc7 100644 --- a/components/embedder_support/android/BUILD.gn +++ b/components/embedder_support/android/BUILD.gn
@@ -58,22 +58,24 @@ java_strings_grd("web_contents_delegate_strings_grd") { grd_file = "java/strings/web_contents_delegate_android_strings.grd" outputs = [ + "values/web_contents_delegate_android_strings.xml", "values-am/web_contents_delegate_android_strings.xml", "values-ar/web_contents_delegate_android_strings.xml", "values-bg/web_contents_delegate_android_strings.xml", + "values-bn/web_contents_delegate_android_strings.xml", "values-ca/web_contents_delegate_android_strings.xml", "values-cs/web_contents_delegate_android_strings.xml", "values-da/web_contents_delegate_android_strings.xml", "values-de/web_contents_delegate_android_strings.xml", "values-el/web_contents_delegate_android_strings.xml", - "values/web_contents_delegate_android_strings.xml", "values-en-rGB/web_contents_delegate_android_strings.xml", "values-es/web_contents_delegate_android_strings.xml", "values-es-rUS/web_contents_delegate_android_strings.xml", + "values-et/web_contents_delegate_android_strings.xml", "values-fa/web_contents_delegate_android_strings.xml", "values-fi/web_contents_delegate_android_strings.xml", - "values-tl/web_contents_delegate_android_strings.xml", "values-fr/web_contents_delegate_android_strings.xml", + "values-gu/web_contents_delegate_android_strings.xml", "values-hi/web_contents_delegate_android_strings.xml", "values-hr/web_contents_delegate_android_strings.xml", "values-hu/web_contents_delegate_android_strings.xml", @@ -81,11 +83,15 @@ "values-it/web_contents_delegate_android_strings.xml", "values-iw/web_contents_delegate_android_strings.xml", "values-ja/web_contents_delegate_android_strings.xml", + "values-kn/web_contents_delegate_android_strings.xml", "values-ko/web_contents_delegate_android_strings.xml", "values-lt/web_contents_delegate_android_strings.xml", "values-lv/web_contents_delegate_android_strings.xml", - "values-nl/web_contents_delegate_android_strings.xml", + "values-ml/web_contents_delegate_android_strings.xml", + "values-mr/web_contents_delegate_android_strings.xml", + "values-ms/web_contents_delegate_android_strings.xml", "values-nb/web_contents_delegate_android_strings.xml", + "values-nl/web_contents_delegate_android_strings.xml", "values-pl/web_contents_delegate_android_strings.xml", "values-pt-rBR/web_contents_delegate_android_strings.xml", "values-pt-rPT/web_contents_delegate_android_strings.xml", @@ -96,7 +102,10 @@ "values-sr/web_contents_delegate_android_strings.xml", "values-sv/web_contents_delegate_android_strings.xml", "values-sw/web_contents_delegate_android_strings.xml", + "values-ta/web_contents_delegate_android_strings.xml", + "values-te/web_contents_delegate_android_strings.xml", "values-th/web_contents_delegate_android_strings.xml", + "values-tl/web_contents_delegate_android_strings.xml", "values-tr/web_contents_delegate_android_strings.xml", "values-uk/web_contents_delegate_android_strings.xml", "values-vi/web_contents_delegate_android_strings.xml",
diff --git a/components/embedder_support/android/java/strings/web_contents_delegate_android_strings.grd b/components/embedder_support/android/java/strings/web_contents_delegate_android_strings.grd index b5177f0..b438a13e 100644 --- a/components/embedder_support/android/java/strings/web_contents_delegate_android_strings.grd +++ b/components/embedder_support/android/java/strings/web_contents_delegate_android_strings.grd
@@ -6,6 +6,7 @@ <output filename="values-am/web_contents_delegate_android_strings.xml" lang="am" type="android" /> <output filename="values-ar/web_contents_delegate_android_strings.xml" lang="ar" type="android" /> <output filename="values-bg/web_contents_delegate_android_strings.xml" lang="bg" type="android" /> + <output filename="values-bn/web_contents_delegate_android_strings.xml" lang="bn" type="android" /> <output filename="values-ca/web_contents_delegate_android_strings.xml" lang="ca" type="android" /> <output filename="values-cs/web_contents_delegate_android_strings.xml" lang="cs" type="android" /> <output filename="values-da/web_contents_delegate_android_strings.xml" lang="da" type="android" /> @@ -15,20 +16,26 @@ <output filename="values-en-rGB/web_contents_delegate_android_strings.xml" lang="en-GB" type="android" /> <output filename="values-es/web_contents_delegate_android_strings.xml" lang="es" type="android" /> <output filename="values-es-rUS/web_contents_delegate_android_strings.xml" lang="es-419" type="android" /> + <output filename="values-et/web_contents_delegate_android_strings.xml" lang="et" type="android" /> <output filename="values-fa/web_contents_delegate_android_strings.xml" lang="fa" type="android" /> <output filename="values-fi/web_contents_delegate_android_strings.xml" lang="fi" type="android" /> <output filename="values-tl/web_contents_delegate_android_strings.xml" lang="fil" type="android" /> <output filename="values-fr/web_contents_delegate_android_strings.xml" lang="fr" type="android" /> + <output filename="values-gu/web_contents_delegate_android_strings.xml" lang="gu" type="android" /> + <output filename="values-iw/web_contents_delegate_android_strings.xml" lang="he" type="android" /> <output filename="values-hi/web_contents_delegate_android_strings.xml" lang="hi" type="android" /> <output filename="values-hr/web_contents_delegate_android_strings.xml" lang="hr" type="android" /> <output filename="values-hu/web_contents_delegate_android_strings.xml" lang="hu" type="android" /> <output filename="values-in/web_contents_delegate_android_strings.xml" lang="id" type="android" /> <output filename="values-it/web_contents_delegate_android_strings.xml" lang="it" type="android" /> - <output filename="values-iw/web_contents_delegate_android_strings.xml" lang="he" type="android" /> <output filename="values-ja/web_contents_delegate_android_strings.xml" lang="ja" type="android" /> + <output filename="values-kn/web_contents_delegate_android_strings.xml" lang="kn" type="android" /> <output filename="values-ko/web_contents_delegate_android_strings.xml" lang="ko" type="android" /> <output filename="values-lt/web_contents_delegate_android_strings.xml" lang="lt" type="android" /> <output filename="values-lv/web_contents_delegate_android_strings.xml" lang="lv" type="android" /> + <output filename="values-ml/web_contents_delegate_android_strings.xml" lang="ml" type="android" /> + <output filename="values-mr/web_contents_delegate_android_strings.xml" lang="mr" type="android" /> + <output filename="values-ms/web_contents_delegate_android_strings.xml" lang="ms" type="android" /> <output filename="values-nl/web_contents_delegate_android_strings.xml" lang="nl" type="android" /> <output filename="values-nb/web_contents_delegate_android_strings.xml" lang="no" type="android" /> <output filename="values-pl/web_contents_delegate_android_strings.xml" lang="pl" type="android" /> @@ -41,6 +48,8 @@ <output filename="values-sr/web_contents_delegate_android_strings.xml" lang="sr" type="android" /> <output filename="values-sv/web_contents_delegate_android_strings.xml" lang="sv" type="android" /> <output filename="values-sw/web_contents_delegate_android_strings.xml" lang="sw" type="android" /> + <output filename="values-ta/web_contents_delegate_android_strings.xml" lang="ta" type="android" /> + <output filename="values-te/web_contents_delegate_android_strings.xml" lang="te" type="android" /> <output filename="values-th/web_contents_delegate_android_strings.xml" lang="th" type="android" /> <output filename="values-tr/web_contents_delegate_android_strings.xml" lang="tr" type="android" /> <output filename="values-uk/web_contents_delegate_android_strings.xml" lang="uk" type="android" />
diff --git a/components/error_page/common/localized_error.cc b/components/error_page/common/localized_error.cc index 71ece78..0535931 100644 --- a/components/error_page/common/localized_error.cc +++ b/components/error_page/common/localized_error.cc
@@ -858,7 +858,7 @@ } std::string HttpErrorCodeToString(int error) { - return std::string("HTTP ERROR ") + base::IntToString(error); + return std::string("HTTP ERROR ") + base::NumberToString(error); } } // namespace
diff --git a/components/exo/wayland/clients/rects.cc b/components/exo/wayland/clients/rects.cc index cec28862..863b9ba5 100644 --- a/components/exo/wayland/clients/rects.cc +++ b/components/exo/wayland/clients/rects.cc
@@ -365,7 +365,7 @@ } // Set FPS counter text in case it's being shown. - fps_counter_text = base::UintToString( + fps_counter_text = base::NumberToString( std::round(benchmark_frames / benchmark_interval.InSecondsF())); benchmark_start_time = wall_time_start;
diff --git a/components/favicon/core/large_icon_service_impl.cc b/components/favicon/core/large_icon_service_impl.cc index c3ee156..1b88e824 100644 --- a/components/favicon/core/large_icon_service_impl.cc +++ b/components/favicon/core/large_icon_service_impl.cc
@@ -411,14 +411,15 @@ void OnFetchIconFromGoogleServerComplete( FaviconService* favicon_service, const GURL& page_url, + const GURL& server_request_url, favicon_base::IconType icon_type, const favicon_base::GoogleFaviconServerCallback& callback, - const std::string& server_request_url, const gfx::Image& image, const image_fetcher::RequestMetadata& metadata) { if (image.IsEmpty()) { - DLOG(WARNING) << "large icon server fetch empty " << server_request_url; - favicon_service->UnableToDownloadFavicon(GURL(server_request_url)); + DLOG(WARNING) << "large icon server fetch empty " + << server_request_url.spec(); + favicon_service->UnableToDownloadFavicon(server_request_url); callback.Run( metadata.http_response_code == image_fetcher::RequestMetadata::RESPONSE_CODE_INVALID @@ -434,7 +435,7 @@ // Otherwise, use the request URL as fallback. std::string original_icon_url = metadata.content_location_header; if (original_icon_url.empty()) { - original_icon_url = server_request_url; + original_icon_url = server_request_url.spec(); } // Write fetched icons to FaviconService's cache, but only if no icon was @@ -607,13 +608,12 @@ return; } - image_fetcher_->SetDataUseServiceName( - data_use_measurement::DataUseUserData::LARGE_ICON_SERVICE); + image_fetcher::ImageFetcherParams params(traffic_annotation); image_fetcher_->FetchImage( - server_request_url.spec(), server_request_url, + server_request_url, base::BindOnce(&OnFetchIconFromGoogleServerComplete, favicon_service_, - page_url, icon_type, callback), - traffic_annotation); + page_url, server_request_url, icon_type, callback), + std::move(params)); } } // namespace favicon
diff --git a/components/favicon/core/large_icon_service_impl_unittest.cc b/components/favicon/core/large_icon_service_impl_unittest.cc index b7917db7..397a5bd 100644 --- a/components/favicon/core/large_icon_service_impl_unittest.cc +++ b/components/favicon/core/large_icon_service_impl_unittest.cc
@@ -59,13 +59,13 @@ ACTION_P(PostFetchReply, p0) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(std::move(*arg3), arg0, p0, - image_fetcher::RequestMetadata())); + FROM_HERE, + base::BindOnce(std::move(*arg2), p0, image_fetcher::RequestMetadata())); } ACTION_P2(PostFetchReplyWithMetadata, p0, p1) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(std::move(*arg3), arg0, p0, p1)); + FROM_HERE, base::BindOnce(std::move(*arg2), p0, p1)); } ACTION_P(PostBoolReplyToArg4, p0) { @@ -161,7 +161,7 @@ base::MockCallback<favicon_base::GoogleFaviconServerCallback> callback; EXPECT_CALL(*mock_image_fetcher_, - FetchImageAndData_(_, kExpectedServerUrl, _, _, _)) + FetchImageAndData_(kExpectedServerUrl, _, _, _)) .WillOnce(PostFetchReply(gfx::Image::CreateFrom1xBitmap( CreateTestSkBitmap(64, 64, kTestColor)))); EXPECT_CALL(mock_favicon_service_, @@ -199,7 +199,7 @@ base::MockCallback<favicon_base::GoogleFaviconServerCallback> callback; EXPECT_CALL(*mock_image_fetcher_, - FetchImageAndData_(_, kExpectedServerUrl, _, _, _)) + FetchImageAndData_(kExpectedServerUrl, _, _, _)) .WillOnce(PostFetchReply(gfx::Image::CreateFrom1xBitmap( CreateTestSkBitmap(32, 32, kTestColor)))); EXPECT_CALL(mock_favicon_service_, @@ -242,7 +242,7 @@ base::MockCallback<favicon_base::GoogleFaviconServerCallback> callback; EXPECT_CALL(*mock_image_fetcher_, - FetchImageAndData_(_, kExpectedServerUrl, _, _, _)) + FetchImageAndData_(kExpectedServerUrl, _, _, _)) .WillOnce(PostFetchReply(gfx::Image::CreateFrom1xBitmap( CreateTestSkBitmap(64, 64, kTestColor)))); EXPECT_CALL(mock_favicon_service_, @@ -279,7 +279,7 @@ image_fetcher::RequestMetadata expected_metadata; expected_metadata.content_location_header = kExpectedOriginalUrl.spec(); EXPECT_CALL(*mock_image_fetcher_, - FetchImageAndData_(_, kExpectedServerUrl, _, _, _)) + FetchImageAndData_(kExpectedServerUrl, _, _, _)) .WillOnce(PostFetchReplyWithMetadata( gfx::Image::CreateFrom1xBitmap( CreateTestSkBitmap(64, 64, kTestColor)), @@ -317,7 +317,7 @@ .WillOnce(PostBoolReplyToArg2(true)); EXPECT_CALL(*mock_image_fetcher_, - FetchImageAndData_(_, kExpectedServerUrl, _, _, _)) + FetchImageAndData_(kExpectedServerUrl, _, _, _)) .WillOnce(PostFetchReply(gfx::Image::CreateFrom1xBitmap( CreateTestSkBitmap(64, 64, kTestColor)))); // Verify that the non-trimmed page URL is used when writing to the database. @@ -342,10 +342,10 @@ favicon_base::IconType::kTouchIcon, _)) .WillOnce(PostBoolReplyToArg2(true)); // The request has no "check_seen=true"; full URL is tested elsewhere. - EXPECT_CALL(*mock_image_fetcher_, - FetchImageAndData_( - _, Property(&GURL::query, Not(HasSubstr("check_seen=true"))), - _, _, _)) + EXPECT_CALL( + *mock_image_fetcher_, + FetchImageAndData_( + Property(&GURL::query, Not(HasSubstr("check_seen=true"))), _, _, _)) .WillOnce(PostFetchReply(gfx::Image())); base::MockCallback<favicon_base::GoogleFaviconServerCallback> callback; @@ -367,7 +367,7 @@ TEST_F(LargeIconServiceTest, ShouldNotQueryGoogleServerIfInvalidScheme) { const GURL kDummyFtpUrl("ftp://www.example.com"); - EXPECT_CALL(*mock_image_fetcher_, FetchImageAndData_(_, _, _, _, _)).Times(0); + EXPECT_CALL(*mock_image_fetcher_, FetchImageAndData_(_, _, _, _)).Times(0); base::MockCallback<favicon_base::GoogleFaviconServerCallback> callback; @@ -391,7 +391,7 @@ TEST_F(LargeIconServiceTest, ShouldNotQueryGoogleServerIfInvalidURL) { const GURL kDummyInvalidUrl("htt"); - EXPECT_CALL(*mock_image_fetcher_, FetchImageAndData_(_, _, _, _, _)).Times(0); + EXPECT_CALL(*mock_image_fetcher_, FetchImageAndData_(_, _, _, _)).Times(0); base::MockCallback<favicon_base::GoogleFaviconServerCallback> callback; @@ -427,7 +427,7 @@ base::MockCallback<favicon_base::GoogleFaviconServerCallback> callback; EXPECT_CALL(*mock_image_fetcher_, - FetchImageAndData_(_, kExpectedServerUrl, _, _, _)) + FetchImageAndData_(kExpectedServerUrl, _, _, _)) .WillOnce(PostFetchReply(gfx::Image())); EXPECT_CALL(mock_favicon_service_, UnableToDownloadFavicon(kExpectedServerUrl)); @@ -458,7 +458,7 @@ .WillByDefault(Return(true)); EXPECT_CALL(mock_favicon_service_, UnableToDownloadFavicon(_)).Times(0); - EXPECT_CALL(*mock_image_fetcher_, FetchImageAndData_(_, _, _, _, _)).Times(0); + EXPECT_CALL(*mock_image_fetcher_, FetchImageAndData_(_, _, _, _)).Times(0); EXPECT_CALL(mock_favicon_service_, SetOnDemandFavicons(_, _, _, _, _)) .Times(0); @@ -487,7 +487,7 @@ favicon_base::IconType::kTouchIcon, _)) .WillOnce(PostBoolReplyToArg2(false)); - EXPECT_CALL(*mock_image_fetcher_, FetchImageAndData_(_, _, _, _, _)).Times(0); + EXPECT_CALL(*mock_image_fetcher_, FetchImageAndData_(_, _, _, _)).Times(0); EXPECT_CALL(mock_favicon_service_, SetOnDemandFavicons(_, _, _, _, _)) .Times(0);
diff --git a/components/feed/core/feed_image_manager.cc b/components/feed/core/feed_image_manager.cc index c7776e4..226197c5 100644 --- a/components/feed/core/feed_image_manager.cc +++ b/components/feed/core/feed_image_manager.cc
@@ -187,7 +187,7 @@ } image_fetcher_->FetchImageData( - url.spec(), url, + url, base::BindOnce(&FeedImageManager::OnImageFetchedFromNetwork, weak_ptr_factory_.GetWeakPtr(), url_index, std::move(urls), width_px, height_px, std::move(callback)),
diff --git a/components/feedback/anonymizer_tool.cc b/components/feedback/anonymizer_tool.cc index 7fbf845..02fc89dd 100644 --- a/components/feedback/anonymizer_tool.cc +++ b/components/feedback/anonymizer_tool.cc
@@ -460,7 +460,7 @@ std::string matched_id_as_string = matched_id.as_string(); std::string replacement_id = (*identifier_space)[matched_id_as_string]; if (replacement_id.empty()) { - replacement_id = base::IntToString(identifier_space->size()); + replacement_id = base::NumberToString(identifier_space->size()); (*identifier_space)[matched_id_as_string] = replacement_id; }
diff --git a/components/flags_ui/feature_entry.cc b/components/flags_ui/feature_entry.cc index e1d703fc..ede9113 100644 --- a/components/flags_ui/feature_entry.cc +++ b/components/flags_ui/feature_entry.cc
@@ -55,7 +55,7 @@ type == FeatureEntry::FEATURE_WITH_PARAMS_VALUE); DCHECK_LT(index, num_options); return std::string(internal_name) + testing::kMultiSeparator + - base::IntToString(index); + base::NumberToString(index); } base::string16 FeatureEntry::DescriptionForOption(int index) const {
diff --git a/components/gcm_driver/gcm_client_impl_unittest.cc b/components/gcm_driver/gcm_client_impl_unittest.cc index 7e6ad0b..45ab3b9 100644 --- a/components/gcm_driver/gcm_client_impl_unittest.cc +++ b/components/gcm_driver/gcm_client_impl_unittest.cc
@@ -1202,7 +1202,7 @@ TEST_F(GCMClientImplCheckinTest, GServicesSettingsAfterInitialCheckin) { std::map<std::string, std::string> settings; - settings["checkin_interval"] = base::Int64ToString(kSettingsCheckinInterval); + settings["checkin_interval"] = base::NumberToString(kSettingsCheckinInterval); settings["checkin_url"] = "http://alternative.url/checkin"; settings["gcm_hostname"] = "alternative.gcm.host"; settings["gcm_secure_port"] = "7777"; @@ -1225,7 +1225,7 @@ // This test only checks that periodic checkin happens. TEST_F(GCMClientImplCheckinTest, PeriodicCheckin) { std::map<std::string, std::string> settings; - settings["checkin_interval"] = base::Int64ToString(kSettingsCheckinInterval); + settings["checkin_interval"] = base::NumberToString(kSettingsCheckinInterval); settings["checkin_url"] = "http://alternative.url/checkin"; settings["gcm_hostname"] = "alternative.gcm.host"; settings["gcm_secure_port"] = "7777"; @@ -1244,7 +1244,7 @@ TEST_F(GCMClientImplCheckinTest, LoadGSettingsFromStore) { std::map<std::string, std::string> settings; - settings["checkin_interval"] = base::Int64ToString(kSettingsCheckinInterval); + settings["checkin_interval"] = base::NumberToString(kSettingsCheckinInterval); settings["checkin_url"] = "http://alternative.url/checkin"; settings["gcm_hostname"] = "alternative.gcm.host"; settings["gcm_secure_port"] = "7777"; @@ -1272,7 +1272,7 @@ // This test only checks that periodic checkin happens. TEST_F(GCMClientImplCheckinTest, CheckinWithAccounts) { std::map<std::string, std::string> settings; - settings["checkin_interval"] = base::Int64ToString(kSettingsCheckinInterval); + settings["checkin_interval"] = base::NumberToString(kSettingsCheckinInterval); settings["checkin_url"] = "http://alternative.url/checkin"; settings["gcm_hostname"] = "alternative.gcm.host"; settings["gcm_secure_port"] = "7777"; @@ -1308,7 +1308,7 @@ // This test only checks that periodic checkin happens. TEST_F(GCMClientImplCheckinTest, CheckinWhenAccountRemoved) { std::map<std::string, std::string> settings; - settings["checkin_interval"] = base::Int64ToString(kSettingsCheckinInterval); + settings["checkin_interval"] = base::NumberToString(kSettingsCheckinInterval); settings["checkin_url"] = "http://alternative.url/checkin"; settings["gcm_hostname"] = "alternative.gcm.host"; settings["gcm_secure_port"] = "7777"; @@ -1350,7 +1350,7 @@ // This test only checks that periodic checkin happens. TEST_F(GCMClientImplCheckinTest, CheckinWhenAccountReplaced) { std::map<std::string, std::string> settings; - settings["checkin_interval"] = base::Int64ToString(kSettingsCheckinInterval); + settings["checkin_interval"] = base::NumberToString(kSettingsCheckinInterval); settings["checkin_url"] = "http://alternative.url/checkin"; settings["gcm_hostname"] = "alternative.gcm.host"; settings["gcm_secure_port"] = "7777";
diff --git a/components/gcm_driver/gcm_internals_helper.cc b/components/gcm_driver/gcm_internals_helper.cc index 0486680..90cc506 100644 --- a/components/gcm_driver/gcm_internals_helper.cc +++ b/components/gcm_driver/gcm_internals_helper.cc
@@ -65,7 +65,7 @@ row->AppendDouble(receive.time.ToJsTime()); row->AppendString(receive.app_id); row->AppendString(receive.from); - row->AppendString(base::IntToString(receive.message_byte_size)); + row->AppendString(base::NumberToString(receive.message_byte_size)); row->AppendString(receive.event); row->AppendString(receive.details); receive_info->Append(std::move(row));
diff --git a/components/gcm_driver/instance_id/instance_id_impl.cc b/components/gcm_driver/instance_id/instance_id_impl.cc index 3d7d542..3576f875 100644 --- a/components/gcm_driver/instance_id/instance_id_impl.cc +++ b/components/gcm_driver/instance_id/instance_id_impl.cc
@@ -256,7 +256,7 @@ // Save to the persistent store. Handler()->AddInstanceIDData( - app_id(), id_, base::Int64ToString(creation_time_.ToInternalValue())); + app_id(), id_, base::NumberToString(creation_time_.ToInternalValue())); } gcm::InstanceIDHandler* InstanceIDImpl::Handler() {
diff --git a/components/gcm_driver/registration_info.cc b/components/gcm_driver/registration_info.cc index f10e769..1d749ebb 100644 --- a/components/gcm_driver/registration_info.cc +++ b/components/gcm_driver/registration_info.cc
@@ -191,7 +191,7 @@ const std::string& registration_id) const { int64_t last_validated_ms = last_validated.since_origin().InMicroseconds(); return registration_id + kSerializedValidationTimeSeparator + - base::Int64ToString(last_validated_ms); + base::NumberToString(last_validated_ms); } bool InstanceIDTokenInfo::Deserialize(const std::string& serialized_key,
diff --git a/components/gwp_asan/BUILD.gn b/components/gwp_asan/BUILD.gn index 5176c8c..f1eb0732 100644 --- a/components/gwp_asan/BUILD.gn +++ b/components/gwp_asan/BUILD.gn
@@ -2,12 +2,14 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//components/gwp_asan/buildflags/buildflags.gni") + source_set("unit_tests") { testonly = true deps = [ "//components/gwp_asan/common:unit_tests", ] - if (is_win || is_mac) { + if (enable_gwp_asan || is_mac) { deps += [ "//components/gwp_asan/client:unit_tests", "//components/gwp_asan/crash_handler:unit_tests",
diff --git a/components/gwp_asan/buildflags/BUILD.gn b/components/gwp_asan/buildflags/BUILD.gn new file mode 100644 index 0000000..95e986c --- /dev/null +++ b/components/gwp_asan/buildflags/BUILD.gn
@@ -0,0 +1,11 @@ +# 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. + +import("//build/buildflag_header.gni") +import("//components/gwp_asan/buildflags/buildflags.gni") + +buildflag_header("buildflags") { + header = "buildflags.h" + flags = [ "ENABLE_GWP_ASAN=$enable_gwp_asan" ] +}
diff --git a/components/gwp_asan/buildflags/buildflags.gni b/components/gwp_asan/buildflags/buildflags.gni new file mode 100644 index 0000000..5554855 --- /dev/null +++ b/components/gwp_asan/buildflags/buildflags.gni
@@ -0,0 +1,8 @@ +# 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. + +declare_args() { + # Is the GWP-ASan client enabled for chrome/ on a given platform. + enable_gwp_asan = is_win +}
diff --git a/components/gwp_asan/crash_handler/crash_handler.cc b/components/gwp_asan/crash_handler/crash_handler.cc index 7734879..ad2216e 100644 --- a/components/gwp_asan/crash_handler/crash_handler.cc +++ b/components/gwp_asan/crash_handler/crash_handler.cc
@@ -7,7 +7,6 @@ #include <stddef.h> #include "base/compiler_specific.h" -#include "base/debug/stack_trace.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "components/gwp_asan/crash_handler/crash.pb.h" @@ -75,17 +74,6 @@ } } -#if !defined(NDEBUG) -void PrintStackTrace( - const ::google::protobuf::RepeatedField<::google::protobuf::uint64>& - trace_pb) { - void* trace_array[trace_pb.size()]; - for (int i = 0; i < trace_pb.size(); i++) - trace_array[i] = reinterpret_cast<void*>(trace_pb.Get(i)); - base::debug::StackTrace(trace_array, trace_pb.size()).Print(); -} -#endif - std::unique_ptr<crashpad::MinidumpUserExtensionStreamDataSource> HandleException(const crashpad::ProcessSnapshot& snapshot) { gwp_asan::Crash proto; @@ -103,17 +91,6 @@ << proto.free_invalid_address() << std::dec; } -#if !defined(NDEBUG) - if (proto.has_deallocation() && proto.deallocation().stack_trace_size() > 0) { - LOG(ERROR) << "Deallocation stack trace:"; - PrintStackTrace(proto.deallocation().stack_trace()); - } - if (proto.has_allocation() && proto.allocation().stack_trace_size() > 0) { - LOG(ERROR) << "Allocation stack trace:"; - PrintStackTrace(proto.allocation().stack_trace()); - } -#endif - return std::make_unique<BufferExtensionStreamDataSource>( kGwpAsanMinidumpStreamType, proto); }
diff --git a/components/history/core/browser/visit_database.cc b/components/history/core/browser/visit_database.cc index 8b4712c..81859a97 100644 --- a/components/history/core/browser/visit_database.cc +++ b/components/history/core/browser/visit_database.cc
@@ -605,7 +605,7 @@ for (size_t j = start_index; j < end_index; j++) { if (j != start_index) sql.push_back(','); - sql.append(base::Int64ToString(visits[j].visit_id)); + sql.append(base::NumberToString(visits[j].visit_id)); } sql.append(") ORDER BY id"); sql::Statement statement(GetDB().GetUniqueStatement(sql.c_str()));
diff --git a/components/history/core/browser/web_history_service.cc b/components/history/core/browser/web_history_service.cc index 21e8fa0..7e7b4e5 100644 --- a/components/history/core/browser/web_history_service.cc +++ b/components/history/core/browser/web_history_service.cc
@@ -281,8 +281,9 @@ // history server. std::string ServerTimeString(base::Time time) { if (time < base::Time::UnixEpoch()) - return base::Int64ToString(0); - return base::Int64ToString((time - base::Time::UnixEpoch()).InMicroseconds()); + return base::NumberToString(0); + return base::NumberToString( + (time - base::Time::UnixEpoch()).InMicroseconds()); } // Returns a URL for querying the history server for a query specified by @@ -313,8 +314,8 @@ } if (options.max_count) { - url = net::AppendQueryParameter( - url, "num", base::IntToString(options.max_count)); + url = net::AppendQueryParameter(url, "num", + base::NumberToString(options.max_count)); } if (!text_query.empty())
diff --git a/components/image_fetcher/core/BUILD.gn b/components/image_fetcher/core/BUILD.gn index 68ab5db..e13f0b7 100644 --- a/components/image_fetcher/core/BUILD.gn +++ b/components/image_fetcher/core/BUILD.gn
@@ -15,6 +15,7 @@ "image_data_fetcher.cc", "image_data_fetcher.h", "image_decoder.h", + "image_fetcher.cc", "image_fetcher.h", "image_fetcher_impl.cc", "image_fetcher_impl.h",
diff --git a/components/image_fetcher/core/cached_image_fetcher.cc b/components/image_fetcher/core/cached_image_fetcher.cc index b6a5ddf..18a45b8 100644 --- a/components/image_fetcher/core/cached_image_fetcher.cc +++ b/components/image_fetcher/core/cached_image_fetcher.cc
@@ -7,6 +7,7 @@ #include <utility> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/metrics/histogram_macros.h" #include "base/task/post_task.h" #include "base/threading/sequenced_task_runner_handle.h" @@ -25,17 +26,7 @@ // The url to be fetched. const GURL url; - // An identifier passed back to the caller. - const std::string id; - - // The desired frame size if there are multiple frames to choose from. - const gfx::Size desired_frame_size; - - // The service to track data usage for. - const DataUseServiceName data_use_service_name; - - // Limit the number of bytes to download for the image. - const base::Optional<int64_t> image_download_limit_bytes; + const ImageFetcherParams params; // Analytic events below. @@ -58,13 +49,12 @@ } void ImageCallbackIfPresent(ImageFetcherCallback image_callback, - const std::string& id, const gfx::Image& image, const image_fetcher::RequestMetadata& metadata) { if (image_callback.is_null()) { return; } - std::move(image_callback).Run(id, image, metadata); + std::move(image_callback).Run(image, metadata); } std::string EncodeSkBitmapToPNG(const SkBitmap& bitmap) { @@ -93,37 +83,20 @@ CachedImageFetcher::~CachedImageFetcher() = default; -void CachedImageFetcher::SetDataUseServiceName( - DataUseServiceName data_use_service_name) { - data_use_service_name_ = data_use_service_name; -} - -void CachedImageFetcher::SetDesiredImageFrameSize(const gfx::Size& size) { - desired_frame_size_ = size; -} - -void CachedImageFetcher::SetImageDownloadLimit( - base::Optional<int64_t> max_download_bytes) { - image_download_limit_bytes_ = max_download_bytes; -} - ImageDecoder* CachedImageFetcher::GetImageDecoder() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return image_fetcher_->GetImageDecoder(); } void CachedImageFetcher::FetchImageAndData( - const std::string& id, const GURL& image_url, ImageDataFetcherCallback image_data_callback, ImageFetcherCallback image_callback, - const net::NetworkTrafficAnnotationTag& traffic_annotation) { + ImageFetcherParams params) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // TODO(wylieb): Inject a clock for better testability. CachedImageFetcherRequest request = { - image_url, - id, - desired_frame_size_, - data_use_service_name_, - image_download_limit_bytes_, + image_url, std::move(params), /* cache_hit_before_network_request */ false, /* start_time */ base::Time::Now()}; @@ -132,7 +105,7 @@ read_only_, image_url.spec(), base::BindOnce(&CachedImageFetcher::OnImageFetchedFromCache, weak_ptr_factory_.GetWeakPtr(), std::move(request), - traffic_annotation, std::move(image_data_callback), + std::move(image_data_callback), std::move(image_callback))); CachedImageFetcherMetricsReporter::ReportEvent( @@ -141,13 +114,12 @@ void CachedImageFetcher::OnImageFetchedFromCache( CachedImageFetcherRequest request, - const net::NetworkTrafficAnnotationTag& traffic_annotation, ImageDataFetcherCallback image_data_callback, ImageFetcherCallback image_callback, std::string image_data) { if (image_data.empty()) { // Fetching from the DB failed, start a network fetch. - EnqueueFetchImageFromNetwork(std::move(request), traffic_annotation, + EnqueueFetchImageFromNetwork(std::move(request), std::move(image_data_callback), std::move(image_callback)); @@ -156,14 +128,19 @@ } else { DataCallbackIfPresent(std::move(image_data_callback), image_data, RequestMetadata()); - GetImageDecoder()->DecodeImage( - image_data, - /* The frame size had already been chosen during fetch. */ gfx::Size(), - base::BindRepeating( - &CachedImageFetcher::OnImageDecodedFromCache, - weak_ptr_factory_.GetWeakPtr(), std::move(request), - traffic_annotation, base::Passed(std::move(image_data_callback)), - base::Passed(std::move(image_callback)), image_data)); + + // Only continue with decoding if the user actually asked for an image. + if (!image_callback.is_null()) { + GetImageDecoder()->DecodeImage( + image_data, + /* The frame size had already been chosen during fetch. */ + gfx::Size(), + base::BindRepeating(&CachedImageFetcher::OnImageDecodedFromCache, + weak_ptr_factory_.GetWeakPtr(), + std::move(request), + base::Passed(std::move(image_data_callback)), + base::Passed(std::move(image_callback)))); + } CachedImageFetcherMetricsReporter::ReportEvent( CachedImageFetcherEvent::kCacheHit); } @@ -171,23 +148,20 @@ void CachedImageFetcher::OnImageDecodedFromCache( CachedImageFetcherRequest request, - const net::NetworkTrafficAnnotationTag& traffic_annotation, ImageDataFetcherCallback image_data_callback, ImageFetcherCallback image_callback, - const std::string& image_data, const gfx::Image& image) { if (image.IsEmpty()) { // Upon failure, fetch from the network. request.cache_hit_before_network_request = true; - EnqueueFetchImageFromNetwork(std::move(request), traffic_annotation, + EnqueueFetchImageFromNetwork(std::move(request), std::move(image_data_callback), std::move(image_callback)); CachedImageFetcherMetricsReporter::ReportEvent( CachedImageFetcherEvent::kCacheDecodingError); } else { - ImageCallbackIfPresent(std::move(image_callback), request.id, image, - RequestMetadata()); + ImageCallbackIfPresent(std::move(image_callback), image, RequestMetadata()); CachedImageFetcherMetricsReporter::ReportImageLoadFromCacheTime( request.start_time); } @@ -195,47 +169,39 @@ void CachedImageFetcher::EnqueueFetchImageFromNetwork( CachedImageFetcherRequest request, - const net::NetworkTrafficAnnotationTag& traffic_annotation, ImageDataFetcherCallback image_data_callback, ImageFetcherCallback image_callback) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&CachedImageFetcher::FetchImageFromNetwork, weak_ptr_factory_.GetWeakPtr(), std::move(request), - traffic_annotation, std::move(image_data_callback), + std::move(image_data_callback), std::move(image_callback))); } void CachedImageFetcher::FetchImageFromNetwork( CachedImageFetcherRequest request, - const net::NetworkTrafficAnnotationTag& traffic_annotation, ImageDataFetcherCallback image_data_callback, ImageFetcherCallback image_callback) { - std::string id = request.id; const GURL& url = request.url; - // Fetch image data and the image itself. The image data will be stored in - // the image cache, and the image will be returned to the caller. - image_fetcher_->SetDesiredImageFrameSize(request.desired_frame_size); - image_fetcher_->SetDataUseServiceName(request.data_use_service_name); - image_fetcher_->SetImageDownloadLimit(request.image_download_limit_bytes); + bool cache_hit = request.cache_hit_before_network_request; image_fetcher_->FetchImageAndData( - id, url, std::move(image_data_callback), + url, + cache_hit ? ImageDataFetcherCallback() : std::move(image_data_callback), base::BindOnce(&CachedImageFetcher::OnImageFetchedFromNetwork, weak_ptr_factory_.GetWeakPtr(), std::move(request), std::move(image_callback)), - traffic_annotation); + std::move(request.params)); } void CachedImageFetcher::OnImageFetchedFromNetwork( CachedImageFetcherRequest request, ImageFetcherCallback image_callback, - const std::string& id, const gfx::Image& image, const RequestMetadata& request_metadata) { // The image has been deocded by the fetcher already, return straight to the // caller. - ImageCallbackIfPresent(std::move(image_callback), request.id, image, - request_metadata); + ImageCallbackIfPresent(std::move(image_callback), image, request_metadata); // Copy the image data out and store it on disk. const SkBitmap* bitmap = image.IsEmpty() ? nullptr : image.ToSkBitmap();
diff --git a/components/image_fetcher/core/cached_image_fetcher.h b/components/image_fetcher/core/cached_image_fetcher.h index f40f574..a33be0b 100644 --- a/components/image_fetcher/core/cached_image_fetcher.h +++ b/components/image_fetcher/core/cached_image_fetcher.h
@@ -10,6 +10,7 @@ #include <vector> #include "base/memory/weak_ptr.h" +#include "base/sequence_checker.h" #include "components/image_fetcher/core/image_decoder.h" #include "components/image_fetcher/core/image_fetcher.h" #include "components/image_fetcher/core/image_fetcher_types.h" @@ -37,48 +38,36 @@ ~CachedImageFetcher() override; // ImageFetcher: - void SetDataUseServiceName(DataUseServiceName data_use_service_name) override; - void SetDesiredImageFrameSize(const gfx::Size& size) override; - void SetImageDownloadLimit( - base::Optional<int64_t> max_download_bytes) override; - void FetchImageAndData( - const std::string& id, - const GURL& image_url, - ImageDataFetcherCallback image_data_callback, - ImageFetcherCallback image_callback, - const net::NetworkTrafficAnnotationTag& traffic_annotation) override; + void FetchImageAndData(const GURL& image_url, + ImageDataFetcherCallback image_data_callback, + ImageFetcherCallback image_callback, + ImageFetcherParams params) override; ImageDecoder* GetImageDecoder() override; private: // Cache void OnImageFetchedFromCache( CachedImageFetcherRequest request, - const net::NetworkTrafficAnnotationTag& traffic_annotation, ImageDataFetcherCallback image_data_callback, ImageFetcherCallback image_callback, std::string image_data); void OnImageDecodedFromCache( CachedImageFetcherRequest request, - const net::NetworkTrafficAnnotationTag& traffic_annotation, ImageDataFetcherCallback image_data_callback, ImageFetcherCallback image_callback, - const std::string& image_data, const gfx::Image& image); // Network void EnqueueFetchImageFromNetwork( CachedImageFetcherRequest request, - const net::NetworkTrafficAnnotationTag& traffic_annotation, ImageDataFetcherCallback image_data_callback, ImageFetcherCallback image_callback); void FetchImageFromNetwork( CachedImageFetcherRequest request, - const net::NetworkTrafficAnnotationTag& traffic_annotation, ImageDataFetcherCallback image_data_callback, ImageFetcherCallback image_callback); void OnImageFetchedFromNetwork(CachedImageFetcherRequest request, ImageFetcherCallback image_callback, - const std::string& id, const gfx::Image& image, const RequestMetadata& request_metadata); void StoreEncodedData(const GURL& url, std::string image_data); @@ -95,10 +84,9 @@ // When true, operations won't affect the longeivity of valid cache items. bool read_only_; - // Capture parameters when ImageFetcher Set* methods are called. - gfx::Size desired_frame_size_; - DataUseServiceName data_use_service_name_; - base::Optional<int64_t> image_download_limit_bytes_; + // Used to ensure that operations are performed on the sequence that this + // object was created on. + SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory<CachedImageFetcher> weak_ptr_factory_;
diff --git a/components/image_fetcher/core/cached_image_fetcher_service.cc b/components/image_fetcher/core/cached_image_fetcher_service.cc index f6dc1e75..d6fd84f1 100644 --- a/components/image_fetcher/core/cached_image_fetcher_service.cc +++ b/components/image_fetcher/core/cached_image_fetcher_service.cc
@@ -10,30 +10,28 @@ #include "components/image_fetcher/core/cache/image_cache.h" #include "components/image_fetcher/core/cached_image_fetcher.h" #include "components/image_fetcher/core/image_decoder.h" +#include "components/image_fetcher/core/image_fetcher.h" #include "components/image_fetcher/core/image_fetcher_impl.h" #include "services/network/public/cpp/shared_url_loader_factory.h" namespace image_fetcher { CachedImageFetcherService::CachedImageFetcherService( - CreateImageDecoderCallback create_image_decoder_fn, + std::unique_ptr<ImageDecoder> image_decoder, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, scoped_refptr<ImageCache> image_cache, bool read_only) - : create_image_decoder_callback_(create_image_decoder_fn), - url_loader_factory_(url_loader_factory), - image_cache_(image_cache), - read_only_(read_only) {} + : cached_image_fetcher_(std::make_unique<CachedImageFetcher>( + std::make_unique<ImageFetcherImpl>(std::move(image_decoder), + url_loader_factory), + image_cache, + read_only)), + image_cache_(image_cache) {} CachedImageFetcherService::~CachedImageFetcherService() = default; -// TODO(wylieb): Store CachedImageFetcher once it's stateless. -std::unique_ptr<CachedImageFetcher> -CachedImageFetcherService::CreateCachedImageFetcher() { - return std::make_unique<CachedImageFetcher>( - std::make_unique<ImageFetcherImpl>(create_image_decoder_callback_.Run(), - url_loader_factory_), - image_cache_, read_only_); +ImageFetcher* CachedImageFetcherService::GetCachedImageFetcher() { + return cached_image_fetcher_.get(); } scoped_refptr<ImageCache> CachedImageFetcherService::ImageCacheForTesting()
diff --git a/components/image_fetcher/core/cached_image_fetcher_service.h b/components/image_fetcher/core/cached_image_fetcher_service.h index 059cef2..510d145 100644 --- a/components/image_fetcher/core/cached_image_fetcher_service.h +++ b/components/image_fetcher/core/cached_image_fetcher_service.h
@@ -18,38 +18,31 @@ namespace image_fetcher { -class CachedImageFetcher; +class ImageFetcher; class ImageCache; class ImageDecoder; -using CreateImageDecoderCallback = - base::RepeatingCallback<std::unique_ptr<ImageDecoder>()>; - // Keyed service responsible for managing the lifetime of CachedImageFetcher. // Persists the ImageCache, and uses it to create instances of the // CachedImageFethcer. class CachedImageFetcherService : public KeyedService { public: explicit CachedImageFetcherService( - CreateImageDecoderCallback create_image_decoder_callback, + std::unique_ptr<ImageDecoder> image_decoder, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, scoped_refptr<ImageCache> image_cache, bool read_only); ~CachedImageFetcherService() override; // Create an instance of CachedImageFetcher based on the ImageCache. - std::unique_ptr<CachedImageFetcher> CreateCachedImageFetcher(); + ImageFetcher* GetCachedImageFetcher(); scoped_refptr<ImageCache> ImageCacheForTesting() const; private: - CreateImageDecoderCallback create_image_decoder_callback_; - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; - scoped_refptr<ImageCache> image_cache_; + std::unique_ptr<ImageFetcher> cached_image_fetcher_; - // If true, the CachedImageFetcher will be started in read-only mode. Read- - // only mode doesn't perform write operations on the cache. - bool read_only_; + scoped_refptr<ImageCache> image_cache_; DISALLOW_COPY_AND_ASSIGN(CachedImageFetcherService); };
diff --git a/components/image_fetcher/core/cached_image_fetcher_unittest.cc b/components/image_fetcher/core/cached_image_fetcher_unittest.cc index fec79d6..e87aeba 100644 --- a/components/image_fetcher/core/cached_image_fetcher_unittest.cc +++ b/components/image_fetcher/core/cached_image_fetcher_unittest.cc
@@ -171,10 +171,10 @@ base::MockCallback<ImageFetcherCallback> image_callback; EXPECT_CALL(data_callback, Run(kImageData, _)); - EXPECT_CALL(image_callback, Run(kImageUrl.spec(), NonEmptyImage(), _)); + EXPECT_CALL(image_callback, Run(NonEmptyImage(), _)); cached_image_fetcher()->FetchImageAndData( - kImageUrl.spec(), kImageUrl, data_callback.Get(), image_callback.Get(), - TRAFFIC_ANNOTATION_FOR_TESTS); + kImageUrl, data_callback.Get(), image_callback.Get(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); RunUntilIdle(); @@ -198,10 +198,10 @@ image_decoder()->SetDecodingValid(false); base::MockCallback<ImageDataFetcherCallback> data_callback; base::MockCallback<ImageFetcherCallback> image_callback; - EXPECT_CALL(image_callback, Run(kImageUrl.spec(), EmptyImage(), _)); + EXPECT_CALL(image_callback, Run(EmptyImage(), _)); cached_image_fetcher()->FetchImageAndData( - kImageUrl.spec(), kImageUrl, data_callback.Get(), image_callback.Get(), - TRAFFIC_ANNOTATION_FOR_TESTS); + kImageUrl, data_callback.Get(), image_callback.Get(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); RunUntilIdle(); histogram_tester().ExpectBucketCount(kCachedImageFetcherEventHistogramName, @@ -218,10 +218,10 @@ image_decoder()->SetDecodingValid(true); base::MockCallback<ImageDataFetcherCallback> data_callback; base::MockCallback<ImageFetcherCallback> image_callback; - EXPECT_CALL(image_callback, Run(kImageUrl.spec(), NonEmptyImage(), _)); + EXPECT_CALL(image_callback, Run(NonEmptyImage(), _)); cached_image_fetcher()->FetchImageAndData( - kImageUrl.spec(), kImageUrl, data_callback.Get(), image_callback.Get(), - TRAFFIC_ANNOTATION_FOR_TESTS); + kImageUrl, data_callback.Get(), image_callback.Get(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); RunUntilIdle(); } } @@ -235,10 +235,10 @@ base::MockCallback<ImageFetcherCallback> image_callback; EXPECT_CALL(data_callback, Run(NonEmptyString(), _)); - EXPECT_CALL(image_callback, Run(kImageUrl.spec(), NonEmptyImage(), _)); + EXPECT_CALL(image_callback, Run(NonEmptyImage(), _)); cached_image_fetcher()->FetchImageAndData( - kImageUrl.spec(), kImageUrl, data_callback.Get(), image_callback.Get(), - TRAFFIC_ANNOTATION_FOR_TESTS); + kImageUrl, data_callback.Get(), image_callback.Get(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); RunUntilIdle(); @@ -267,10 +267,10 @@ base::MockCallback<ImageFetcherCallback> image_callback; EXPECT_CALL(data_callback, Run(NonEmptyString(), _)); - EXPECT_CALL(image_callback, Run(kImageUrl.spec(), NonEmptyImage(), _)); + EXPECT_CALL(image_callback, Run(NonEmptyImage(), _)); cached_image_fetcher()->FetchImageAndData( - kImageUrl.spec(), kImageUrl, data_callback.Get(), image_callback.Get(), - TRAFFIC_ANNOTATION_FOR_TESTS); + kImageUrl, data_callback.Get(), image_callback.Get(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); RunUntilIdle(); } @@ -286,10 +286,10 @@ base::MockCallback<ImageFetcherCallback> image_callback; EXPECT_CALL(data_callback, Run(NonEmptyString(), _)); - EXPECT_CALL(image_callback, Run(kImageUrl.spec(), NonEmptyImage(), _)); + EXPECT_CALL(image_callback, Run(NonEmptyImage(), _)); cached_image_fetcher()->FetchImageAndData( - kImageUrl.spec(), kImageUrl, data_callback.Get(), image_callback.Get(), - TRAFFIC_ANNOTATION_FOR_TESTS); + kImageUrl, data_callback.Get(), image_callback.Get(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); RunUntilIdle(); @@ -321,11 +321,11 @@ base::MockCallback<ImageDataFetcherCallback> data_callback; base::MockCallback<ImageFetcherCallback> image_callback; EXPECT_CALL(data_callback, Run(NonEmptyString(), _)); - EXPECT_CALL(image_callback, Run(kImageUrl.spec(), EmptyImage(), _)); + EXPECT_CALL(image_callback, Run(EmptyImage(), _)); test_url_loader_factory()->AddResponse(kImageUrl.spec(), kImageData); cached_image_fetcher()->FetchImageAndData( - kImageUrl.spec(), kImageUrl, data_callback.Get(), image_callback.Get(), - TRAFFIC_ANNOTATION_FOR_TESTS); + kImageUrl, data_callback.Get(), image_callback.Get(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); RunUntilIdle(); histogram_tester().ExpectTotalCount(kNetworkLoadAfterCacheHitHistogram, 1);
diff --git a/components/image_fetcher/core/image_data_fetcher.cc b/components/image_fetcher/core/image_data_fetcher.cc index f62bc05..90929f6 100644 --- a/components/image_fetcher/core/image_data_fetcher.cc +++ b/components/image_fetcher/core/image_data_fetcher.cc
@@ -16,8 +16,6 @@ #include "services/network/public/cpp/simple_url_loader.h" #include "url/gurl.h" -using data_use_measurement::DataUseUserData; - namespace { const char kContentLocationHeader[] = "Content-Location"; @@ -44,8 +42,7 @@ ImageDataFetcher::ImageDataFetcher( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) - : url_loader_factory_(url_loader_factory), - data_use_service_name_(DataUseUserData::IMAGE_FETCHER_UNTAGGED) { + : url_loader_factory_(url_loader_factory) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } @@ -53,12 +50,6 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } -void ImageDataFetcher::SetDataUseServiceName( - DataUseServiceName data_use_service_name) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - data_use_service_name_ = data_use_service_name; -} - void ImageDataFetcher::SetImageDownloadLimit( base::Optional<int64_t> max_download_bytes) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -94,10 +85,6 @@ net::LOAD_DO_NOT_SEND_AUTH_DATA; } - // TODO(https://crbug.com/808498) re-add data use measurement once - // SimpleURLLoader supports it. Parameter: - // data_use_service_name_ - std::unique_ptr<network::SimpleURLLoader> loader = network::SimpleURLLoader::Create(std::move(request), traffic_annotation);
diff --git a/components/image_fetcher/core/image_data_fetcher.h b/components/image_fetcher/core/image_data_fetcher.h index 0daca9f1..f95ef10 100644 --- a/components/image_fetcher/core/image_data_fetcher.h +++ b/components/image_fetcher/core/image_data_fetcher.h
@@ -36,9 +36,6 @@ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory); ~ImageDataFetcher(); - // Sets a service name against which to track data usage. - void SetDataUseServiceName(DataUseServiceName data_use_service_name); - // Sets an upper limit for image downloads. // Already running downloads are not affected. void SetImageDownloadLimit(base::Optional<int64_t> max_download_bytes); @@ -84,8 +81,6 @@ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; - DataUseServiceName data_use_service_name_; - // Upper limit for the number of bytes to download per image. base::Optional<int64_t> max_download_bytes_;
diff --git a/components/image_fetcher/core/image_fetcher.cc b/components/image_fetcher/core/image_fetcher.cc new file mode 100644 index 0000000..ef0d2f1 --- /dev/null +++ b/components/image_fetcher/core/image_fetcher.cc
@@ -0,0 +1,18 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/image_fetcher/core/image_fetcher.h" + +namespace image_fetcher { + +ImageFetcherParams::ImageFetcherParams( + const net::NetworkTrafficAnnotationTag network_traffic_annotation_tag) + : network_traffic_annotation_tag_(network_traffic_annotation_tag) {} + +ImageFetcherParams::ImageFetcherParams(const ImageFetcherParams& params) = + default; + +ImageFetcherParams::ImageFetcherParams(ImageFetcherParams&& params) = default; + +} // namespace image_fetcher \ No newline at end of file
diff --git a/components/image_fetcher/core/image_fetcher.h b/components/image_fetcher/core/image_fetcher.h index 33fa25d..13eae63 100644 --- a/components/image_fetcher/core/image_fetcher.h +++ b/components/image_fetcher/core/image_fetcher.h
@@ -6,22 +6,65 @@ #define COMPONENTS_IMAGE_FETCHER_CORE_IMAGE_FETCHER_H_ #include <string> +#include <utility> #include "base/callback.h" #include "base/macros.h" #include "base/optional.h" +#include "components/data_use_measurement/core/data_use_user_data.h" #include "components/image_fetcher/core/image_fetcher_types.h" #include "net/traffic_annotation/network_traffic_annotation.h" +#include "ui/gfx/geometry/size.h" #include "url/gurl.h" -namespace gfx { -class Size; -} // namespace gfx - namespace image_fetcher { class ImageDecoder; +// Encapsulates image fetching customization options. +// (required) +// traffic_annotation +// Documents what the network traffic is for, gives you free metrics. +// max_download_size +// Limits the size of the downloaded image. +// frame_size +// If multiple sizes of the image are available on the server, choose the one +// that's closest to the given size (only useful for .icos). Does NOT resize +// the downloaded image to the given dimensions. +class ImageFetcherParams { + public: + ImageFetcherParams( + net::NetworkTrafficAnnotationTag network_traffic_annotation_tag); + ImageFetcherParams(const ImageFetcherParams& params); + ImageFetcherParams(ImageFetcherParams&& params); + + ~ImageFetcherParams() = default; + + const net::NetworkTrafficAnnotationTag traffic_annotation() const { + return network_traffic_annotation_tag_; + } + + void set_max_download_size(base::Optional<int64_t> max_download_bytes) { + max_download_bytes_ = max_download_bytes; + } + + base::Optional<int64_t> max_download_size() const { + return max_download_bytes_; + } + + void set_frame_size(gfx::Size desired_frame_size) { + desired_frame_size_ = desired_frame_size; + } + + gfx::Size frame_size() const { return desired_frame_size_; } + + private: + const net::NetworkTrafficAnnotationTag network_traffic_annotation_tag_; + + base::Optional<int64_t> max_download_bytes_; + gfx::Size desired_frame_size_; +}; + // A class used to fetch server images. It can be called from any thread and the // callback will be called on the thread which initiated the fetch. class ImageFetcher { @@ -29,57 +72,34 @@ ImageFetcher() {} virtual ~ImageFetcher() {} - // Sets a service name against which to track data usage. - virtual void SetDataUseServiceName( - DataUseServiceName data_use_service_name) = 0; - - // Sets an upper limit for image downloads that is by default disabled. - // Setting |max_download_bytes| to a negative value will disable the limit. - // Already running downloads are not affected. - virtual void SetImageDownloadLimit( - base::Optional<int64_t> max_download_bytes) = 0; - - // Sets the desired size for images with multiple frames (like .ico files). - // By default, the image fetcher choses smaller images. Override to choose a - // frame with a size as close as possible to |size| (trying to take one in - // larger size if there's no precise match). Passing gfx::Size() as - // |size| is also supported and will result in chosing the smallest available - // size. - virtual void SetDesiredImageFrameSize(const gfx::Size& size) = 0; - // Fetch an image and optionally decode it. |image_data_callback| is called // when the image fetch completes, but |image_data_callback| may be empty. // |image_callback| is called when the image is finished decoding. // |image_callback| may be empty if image decoding is not required. If a // callback is provided, it will be called exactly once. On failure, an empty // string/gfx::Image is returned. - virtual void FetchImageAndData( - const std::string& id, - const GURL& image_url, - ImageDataFetcherCallback image_data_callback, - ImageFetcherCallback image_callback, - const net::NetworkTrafficAnnotationTag& traffic_annotation) = 0; + virtual void FetchImageAndData(const GURL& image_url, + ImageDataFetcherCallback image_data_callback, + ImageFetcherCallback image_callback, + ImageFetcherParams params) = 0; // Fetch an image and decode it. An empty gfx::Image will be returned to the // callback in case the image could not be fetched. This is the same as // calling FetchImageAndData without an |image_data_callback|. - void FetchImage(const std::string& id, - const GURL& image_url, + void FetchImage(const GURL& image_url, ImageFetcherCallback callback, - const net::NetworkTrafficAnnotationTag& traffic_annotation) { - FetchImageAndData(id, image_url, ImageDataFetcherCallback(), - std::move(callback), traffic_annotation); + ImageFetcherParams params) { + FetchImageAndData(image_url, ImageDataFetcherCallback(), + std::move(callback), params); } // Just fetch the image data, do not decode. This is the same as // calling FetchImageAndData without an |image_callback|. - void FetchImageData( - const std::string& id, - const GURL& image_url, - ImageDataFetcherCallback callback, - const net::NetworkTrafficAnnotationTag& traffic_annotation) { - FetchImageAndData(id, image_url, std::move(callback), - ImageFetcherCallback(), traffic_annotation); + void FetchImageData(const GURL& image_url, + ImageDataFetcherCallback callback, + ImageFetcherParams params) { + FetchImageAndData(image_url, std::move(callback), ImageFetcherCallback(), + params); } virtual ImageDecoder* GetImageDecoder() = 0;
diff --git a/components/image_fetcher/core/image_fetcher_impl.cc b/components/image_fetcher/core/image_fetcher_impl.cc index 4a845a3..dd54f64 100644 --- a/components/image_fetcher/core/image_fetcher_impl.cc +++ b/components/image_fetcher/core/image_fetcher_impl.cc
@@ -28,32 +28,17 @@ ImageFetcherImpl::ImageRequest::~ImageRequest() {} -void ImageFetcherImpl::SetDataUseServiceName( - DataUseServiceName data_use_service_name) { - image_data_fetcher_->SetDataUseServiceName(data_use_service_name); -} - -void ImageFetcherImpl::SetDesiredImageFrameSize(const gfx::Size& size) { - desired_image_frame_size_ = size; -} - -void ImageFetcherImpl::SetImageDownloadLimit( - base::Optional<int64_t> max_download_bytes) { - image_data_fetcher_->SetImageDownloadLimit(max_download_bytes); -} - void ImageFetcherImpl::FetchImageAndData( - const std::string& id, const GURL& image_url, ImageDataFetcherCallback image_data_callback, ImageFetcherCallback image_callback, - const net::NetworkTrafficAnnotationTag& traffic_annotation) { + ImageFetcherParams params) { // Before starting to fetch the image. Look for a request in progress for // |image_url|, and queue if appropriate. auto it = pending_net_requests_.find(image_url); if (it == pending_net_requests_.end()) { ImageRequest request; - request.id = id; + request.id = image_url.spec(); if (image_callback) { request.image_callbacks.push_back(std::move(image_callback)); } @@ -62,11 +47,12 @@ } pending_net_requests_.emplace(image_url, std::move(request)); + image_data_fetcher_->SetImageDownloadLimit(params.max_download_size()); image_data_fetcher_->FetchImageData( image_url, base::BindOnce(&ImageFetcherImpl::OnImageURLFetched, - base::Unretained(this), image_url), - traffic_annotation); + base::Unretained(this), image_url, std::move(params)), + params.traffic_annotation()); } else { ImageRequest* request = &it->second; // Request in progress. Register as an interested callback. @@ -91,6 +77,7 @@ } void ImageFetcherImpl::OnImageURLFetched(const GURL& image_url, + ImageFetcherParams params, const std::string& image_data, const RequestMetadata& metadata) { auto it = pending_net_requests_.find(image_url); @@ -106,7 +93,7 @@ if (image_data.empty() || request->image_callbacks.empty()) { for (auto& callback : request->image_callbacks) { - std::move(callback).Run(request->id, gfx::Image(), metadata); + std::move(callback).Run(gfx::Image(), metadata); } pending_net_requests_.erase(it); return; @@ -114,7 +101,7 @@ request->image_data = image_data; request->request_metadata = metadata; image_decoder_->DecodeImage( - image_data, desired_image_frame_size_, + image_data, params.frame_size(), base::BindRepeating(&ImageFetcherImpl::OnImageDecoded, base::Unretained(this), image_url, metadata)); } @@ -129,7 +116,7 @@ // Run all image callbacks. for (auto& callback : request->image_callbacks) { - std::move(callback).Run(request->id, image, metadata); + std::move(callback).Run(image, metadata); } // Erase the completed ImageRequest.
diff --git a/components/image_fetcher/core/image_fetcher_impl.h b/components/image_fetcher/core/image_fetcher_impl.h index 0b7a2eb..a63c15c 100644 --- a/components/image_fetcher/core/image_fetcher_impl.h +++ b/components/image_fetcher/core/image_fetcher_impl.h
@@ -38,20 +38,10 @@ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory); ~ImageFetcherImpl() override; - // Sets a service name against which to track data usage. - void SetDataUseServiceName(DataUseServiceName data_use_service_name) override; - - void SetDesiredImageFrameSize(const gfx::Size& size) override; - - void SetImageDownloadLimit( - base::Optional<int64_t> max_download_bytes) override; - - void FetchImageAndData( - const std::string& id, - const GURL& image_url, - ImageDataFetcherCallback image_data_callback, - ImageFetcherCallback image_callback, - const net::NetworkTrafficAnnotationTag& traffic_annotation) override; + void FetchImageAndData(const GURL& image_url, + ImageDataFetcherCallback image_data_callback, + ImageFetcherCallback image_callback, + ImageFetcherParams params) override; ImageDecoder* GetImageDecoder() override; @@ -79,6 +69,7 @@ // Processes image URL fetched events. This is the continuation method used // for creating callbacks that are passed to the ImageDataFetcher. void OnImageURLFetched(const GURL& image_url, + ImageFetcherParams params, const std::string& image_data, const RequestMetadata& metadata); @@ -88,8 +79,6 @@ const RequestMetadata& metadata, const gfx::Image& image); - gfx::Size desired_image_frame_size_; - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; std::unique_ptr<ImageDecoder> image_decoder_;
diff --git a/components/image_fetcher/core/image_fetcher_impl_unittest.cc b/components/image_fetcher/core/image_fetcher_impl_unittest.cc index 678ee135..fcbebf71 100644 --- a/components/image_fetcher/core/image_fetcher_impl_unittest.cc +++ b/components/image_fetcher/core/image_fetcher_impl_unittest.cc
@@ -31,8 +31,6 @@ namespace { -const char kFetchID[] = "fetch-1"; -const char kFetchID2[] = "fetch-2"; const char kImageData[] = "data"; const char kImageURL[] = "http://image.test/test.png"; @@ -77,11 +75,11 @@ base::MockCallback<ImageDataFetcherCallback> data_callback; base::MockCallback<ImageFetcherCallback> image_callback; EXPECT_CALL(data_callback, Run(kImageData, _)); - EXPECT_CALL(image_callback, Run(kFetchID, ValidImage(), _)); + EXPECT_CALL(image_callback, Run(ValidImage(), _)); - image_fetcher()->FetchImageAndData(kFetchID, GURL(kImageURL), - data_callback.Get(), image_callback.Get(), - TRAFFIC_ANNOTATION_FOR_TESTS); + image_fetcher()->FetchImageAndData( + GURL(kImageURL), data_callback.Get(), image_callback.Get(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); RunUntilIdle(); } @@ -91,34 +89,34 @@ base::MockCallback<ImageDataFetcherCallback> data_callback1; base::MockCallback<ImageFetcherCallback> image_callback1; EXPECT_CALL(data_callback1, Run(kImageData, _)); - EXPECT_CALL(image_callback1, Run(kFetchID, ValidImage(), _)); + EXPECT_CALL(image_callback1, Run(ValidImage(), _)); image_fetcher()->FetchImageAndData( - kFetchID, GURL(kImageURL), data_callback1.Get(), image_callback1.Get(), - TRAFFIC_ANNOTATION_FOR_TESTS); + GURL(kImageURL), data_callback1.Get(), image_callback1.Get(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); base::MockCallback<ImageDataFetcherCallback> data_callback2; base::MockCallback<ImageFetcherCallback> image_callback2; EXPECT_CALL(data_callback2, Run(kImageData, _)); - EXPECT_CALL(image_callback2, Run(kFetchID, ValidImage(), _)); + EXPECT_CALL(image_callback2, Run(ValidImage(), _)); // This call happens before the network request completes. image_fetcher()->FetchImageAndData( - kFetchID, GURL(kImageURL), data_callback2.Get(), image_callback2.Get(), - TRAFFIC_ANNOTATION_FOR_TESTS); + GURL(kImageURL), data_callback2.Get(), image_callback2.Get(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); base::MockCallback<ImageDataFetcherCallback> data_callback3; base::MockCallback<ImageFetcherCallback> image_callback3; EXPECT_CALL(data_callback3, Run(kImageData, _)); - EXPECT_CALL(image_callback3, Run(kFetchID, ValidImage(), _)); + EXPECT_CALL(image_callback3, Run(ValidImage(), _)); image_decoder()->SetBeforeImageDecoded(base::BindLambdaForTesting([&]() { // This happens after the network request completes. // Shouldn't need to fetch. test_url_loader_factory()->AddResponse(kImageURL, "", net::HTTP_NOT_FOUND); image_fetcher()->FetchImageAndData( - kFetchID2, GURL(kImageURL), data_callback3.Get(), image_callback3.Get(), - TRAFFIC_ANNOTATION_FOR_TESTS); + GURL(kImageURL), data_callback3.Get(), image_callback3.Get(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); })); RunUntilIdle(); @@ -131,20 +129,20 @@ base::MockCallback<ImageDataFetcherCallback> data_callback1; base::MockCallback<ImageFetcherCallback> image_callback1; EXPECT_CALL(data_callback1, Run("", _)); - EXPECT_CALL(image_callback1, Run(kFetchID, EmptyImage(), _)); + EXPECT_CALL(image_callback1, Run(EmptyImage(), _)); image_fetcher()->FetchImageAndData( - kFetchID, GURL(kImageURL), data_callback1.Get(), image_callback1.Get(), - TRAFFIC_ANNOTATION_FOR_TESTS); + GURL(kImageURL), data_callback1.Get(), image_callback1.Get(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); base::MockCallback<ImageDataFetcherCallback> data_callback2; base::MockCallback<ImageFetcherCallback> image_callback2; EXPECT_CALL(data_callback2, Run("", _)); - EXPECT_CALL(image_callback2, Run(kFetchID, EmptyImage(), _)); + EXPECT_CALL(image_callback2, Run(EmptyImage(), _)); image_fetcher()->FetchImageAndData( - kFetchID2, GURL(kImageURL), data_callback2.Get(), image_callback2.Get(), - TRAFFIC_ANNOTATION_FOR_TESTS); + GURL(kImageURL), data_callback2.Get(), image_callback2.Get(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); RunUntilIdle(); } @@ -156,8 +154,8 @@ EXPECT_CALL(data_callback, Run(kImageData, _)); image_fetcher()->FetchImageAndData( - kFetchID, GURL(kImageURL), data_callback.Get(), ImageFetcherCallback(), - TRAFFIC_ANNOTATION_FOR_TESTS); + GURL(kImageURL), data_callback.Get(), ImageFetcherCallback(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); RunUntilIdle(); } @@ -168,15 +166,15 @@ EXPECT_CALL(data_callback, Run(kImageData, _)); image_fetcher()->FetchImageAndData( - kFetchID, GURL(kImageURL), data_callback.Get(), ImageFetcherCallback(), - TRAFFIC_ANNOTATION_FOR_TESTS); + GURL(kImageURL), data_callback.Get(), ImageFetcherCallback(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); base::MockCallback<ImageFetcherCallback> image_callback; - EXPECT_CALL(image_callback, Run(kFetchID, ValidImage(), _)); + EXPECT_CALL(image_callback, Run(ValidImage(), _)); image_fetcher()->FetchImageAndData( - kFetchID2, GURL(kImageURL), ImageDataFetcherCallback(), - image_callback.Get(), TRAFFIC_ANNOTATION_FOR_TESTS); + GURL(kImageURL), ImageDataFetcherCallback(), image_callback.Get(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); RunUntilIdle(); } @@ -185,11 +183,11 @@ test_url_loader_factory()->AddResponse(kImageURL, kImageData); base::MockCallback<ImageFetcherCallback> image_callback; - EXPECT_CALL(image_callback, Run(kFetchID, ValidImage(), _)); + EXPECT_CALL(image_callback, Run(ValidImage(), _)); image_fetcher()->FetchImageAndData( - kFetchID, GURL(kImageURL), ImageDataFetcherCallback(), - image_callback.Get(), TRAFFIC_ANNOTATION_FOR_TESTS); + GURL(kImageURL), ImageDataFetcherCallback(), image_callback.Get(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); base::MockCallback<ImageDataFetcherCallback> data_callback; EXPECT_CALL(data_callback, Run(kImageData, _)); @@ -199,8 +197,8 @@ // Shouldn't need to fetch. test_url_loader_factory()->AddResponse(kImageURL, "", net::HTTP_NOT_FOUND); image_fetcher()->FetchImageAndData( - kFetchID2, GURL(kImageURL), data_callback.Get(), ImageFetcherCallback(), - TRAFFIC_ANNOTATION_FOR_TESTS); + GURL(kImageURL), data_callback.Get(), ImageFetcherCallback(), + ImageFetcherParams(TRAFFIC_ANNOTATION_FOR_TESTS)); })); RunUntilIdle();
diff --git a/components/image_fetcher/core/image_fetcher_types.h b/components/image_fetcher/core/image_fetcher_types.h index 84b4986..bc67e4cd 100644 --- a/components/image_fetcher/core/image_fetcher_types.h +++ b/components/image_fetcher/core/image_fetcher_types.h
@@ -8,7 +8,6 @@ #include <string> #include "base/callback.h" -#include "components/data_use_measurement/core/data_use_user_data.h" namespace gfx { class Image; @@ -22,16 +21,11 @@ struct RequestMetadata; -using DataUseServiceName = data_use_measurement::DataUseUserData::ServiceName; - using ImageFetcherCallback = - base::OnceCallback<void(const std::string& id, - const gfx::Image& image, - const RequestMetadata& metadata)>; + base::OnceCallback<void(const gfx::Image& image, + const RequestMetadata& request_metadata)>; -// Callback with the |image_data|. If an error prevented a http response, -// |request_metadata.response_code| will be RESPONSE_CODE_INVALID. -// TODO(treib): Use RefCountedBytes to avoid copying. +// TODO(wylieb): Use RefCountedBytes to avoid copying. using ImageDataFetcherCallback = base::OnceCallback<void(const std::string& image_data, const RequestMetadata& request_metadata)>;
diff --git a/components/image_fetcher/core/mock_image_fetcher.cc b/components/image_fetcher/core/mock_image_fetcher.cc index 644a4fa..46ce3a4 100644 --- a/components/image_fetcher/core/mock_image_fetcher.cc +++ b/components/image_fetcher/core/mock_image_fetcher.cc
@@ -4,6 +4,8 @@ #include "components/image_fetcher/core/mock_image_fetcher.h" +#include <utility> + #include "ui/gfx/geometry/size.h" namespace image_fetcher { @@ -12,13 +14,12 @@ MockImageFetcher::~MockImageFetcher() {} void MockImageFetcher::FetchImageAndData( - const std::string& id, const GURL& image_url, ImageDataFetcherCallback image_data_callback, ImageFetcherCallback image_callback, - const net::NetworkTrafficAnnotationTag& traffic_annotation) { - FetchImageAndData_(id, image_url, &image_data_callback, &image_callback, - traffic_annotation); + ImageFetcherParams params) { + FetchImageAndData_(image_url, &image_data_callback, &image_callback, + std::move(params)); } } // namespace image_fetcher
diff --git a/components/image_fetcher/core/mock_image_fetcher.h b/components/image_fetcher/core/mock_image_fetcher.h index b32deb8..021c5b74 100644 --- a/components/image_fetcher/core/mock_image_fetcher.h +++ b/components/image_fetcher/core/mock_image_fetcher.h
@@ -9,28 +9,29 @@ #include "testing/gmock/include/gmock/gmock.h" namespace image_fetcher { + class MockImageFetcher : public ImageFetcher { public: MockImageFetcher(); ~MockImageFetcher() override; - MOCK_METHOD1(SetDataUseServiceName, void(DataUseServiceName)); + + MOCK_METHOD1(SetDataUseServiceName, + void(data_use_measurement::DataUseUserData::ServiceName)); MOCK_METHOD1(SetImageDownloadLimit, void(base::Optional<int64_t> max_download_bytes)); MOCK_METHOD1(SetDesiredImageFrameSize, void(const gfx::Size&)); - MOCK_METHOD5(FetchImageAndData_, - void(const std::string&, - const GURL&, + MOCK_METHOD4(FetchImageAndData_, + void(const GURL&, ImageDataFetcherCallback*, ImageFetcherCallback*, - const net::NetworkTrafficAnnotationTag&)); - void FetchImageAndData( - const std::string& id, - const GURL& image_url, - ImageDataFetcherCallback image_data_callback, - ImageFetcherCallback image_callback, - const net::NetworkTrafficAnnotationTag& traffic_annotation) override; + ImageFetcherParams)); + void FetchImageAndData(const GURL& image_url, + ImageDataFetcherCallback image_data_callback, + ImageFetcherCallback image_callback, + ImageFetcherParams params) override; MOCK_METHOD0(GetImageDecoder, image_fetcher::ImageDecoder*()); }; + } // namespace image_fetcher #endif // COMPONENTS_IMAGE_FETCHER_CORE_MOCK_IMAGE_FETCHER_H_
diff --git a/components/image_fetcher/ios/ios_image_data_fetcher_wrapper.h b/components/image_fetcher/ios/ios_image_data_fetcher_wrapper.h index 5c302b1..133e3fb 100644 --- a/components/image_fetcher/ios/ios_image_data_fetcher_wrapper.h +++ b/components/image_fetcher/ios/ios_image_data_fetcher_wrapper.h
@@ -20,6 +20,8 @@ namespace image_fetcher { +using DataUseServiceName = data_use_measurement::DataUseUserData::ServiceName; + class IOSImageDataFetcherWrapper { public: // The TaskRunner is used to decode the image if it is WebP-encoded.
diff --git a/components/image_fetcher/ios/ios_image_data_fetcher_wrapper.mm b/components/image_fetcher/ios/ios_image_data_fetcher_wrapper.mm index ff24d00..627f680 100644 --- a/components/image_fetcher/ios/ios_image_data_fetcher_wrapper.mm +++ b/components/image_fetcher/ios/ios_image_data_fetcher_wrapper.mm
@@ -50,9 +50,7 @@ } void IOSImageDataFetcherWrapper::SetDataUseServiceName( - DataUseServiceName data_use_service_name) { - image_data_fetcher_.SetDataUseServiceName(data_use_service_name); -} + DataUseServiceName data_use_service_name) {} ImageDataFetcherCallback IOSImageDataFetcherWrapper::CallbackForImageDataFetcher(
diff --git a/components/invalidation/impl/unacked_invalidation_set.cc b/components/invalidation/impl/unacked_invalidation_set.cc index e7d1745..3cca59b 100644 --- a/components/invalidation/impl/unacked_invalidation_set.cc +++ b/components/invalidation/impl/unacked_invalidation_set.cc
@@ -159,7 +159,7 @@ std::unique_ptr<base::DictionaryValue> UnackedInvalidationSet::ToValue() const { std::unique_ptr<base::DictionaryValue> value(new base::DictionaryValue); - value->SetString(kSourceKey, base::IntToString(object_id_.source())); + value->SetString(kSourceKey, base::NumberToString(object_id_.source())); value->SetString(kNameKey, object_id_.name()); std::unique_ptr<base::ListValue> list_value(new base::ListValue);
diff --git a/components/invalidation/impl/unacked_invalidation_set_unittest.cc b/components/invalidation/impl/unacked_invalidation_set_unittest.cc index 23112ca4..fca8b2f 100644 --- a/components/invalidation/impl/unacked_invalidation_set_unittest.cc +++ b/components/invalidation/impl/unacked_invalidation_set_unittest.cc
@@ -248,7 +248,7 @@ EXPECT_FALSE(UnackedInvalidationSet::DeserializeSetIntoMap(dict, &map)); // Missing "name" should fail. - dict.SetString("source", base::IntToString(kObjectId_.source())); + dict.SetString("source", base::NumberToString(kObjectId_.source())); EXPECT_FALSE(UnackedInvalidationSet::DeserializeSetIntoMap(dict, &map)); // The "invalidation-list" is not required, so add "name" to make valid.
diff --git a/components/invalidation/public/ack_handle.cc b/components/invalidation/public/ack_handle.cc index 5fc44485..a6744e3 100644 --- a/components/invalidation/public/ack_handle.cc +++ b/components/invalidation/public/ack_handle.cc
@@ -38,7 +38,7 @@ std::unique_ptr<base::DictionaryValue> value(new base::DictionaryValue()); value->SetString("state", state_); value->SetString("timestamp", - base::Int64ToString(timestamp_.ToInternalValue())); + base::NumberToString(timestamp_.ToInternalValue())); return value; }
diff --git a/components/invalidation/public/invalidation.cc b/components/invalidation/public/invalidation.cc index 78a665d..834422c 100644 --- a/components/invalidation/public/invalidation.cc +++ b/components/invalidation/public/invalidation.cc
@@ -145,7 +145,7 @@ value->SetBoolean(kIsUnknownVersionKey, true); } else { value->SetBoolean(kIsUnknownVersionKey, false); - value->SetString(kVersionKey, base::Int64ToString(version_)); + value->SetString(kVersionKey, base::NumberToString(version_)); value->SetString(kPayloadKey, payload_); } return value;
diff --git a/components/metrics/metrics_service.h b/components/metrics/metrics_service.h index a14b538..b5c435a 100644 --- a/components/metrics/metrics_service.h +++ b/components/metrics/metrics_service.h
@@ -36,8 +36,6 @@ class PrefService; class PrefRegistrySimple; -FORWARD_DECLARE_TEST(ChromeMetricsServiceClientTest, - TestRegisterMetricsServiceProviders); namespace base { class HistogramSamples; @@ -386,8 +384,7 @@ static ShutdownCleanliness clean_shutdown_status_; FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, IsPluginProcess); - FRIEND_TEST_ALL_PREFIXES(::ChromeMetricsServiceClientTest, - TestRegisterMetricsServiceProviders); + SEQUENCE_CHECKER(sequence_checker_); // Weak pointers factory used to post task on different threads. All weak
diff --git a/components/metrics/metrics_state_manager.cc b/components/metrics/metrics_state_manager.cc index 1adb020..e2fa6c1 100644 --- a/components/metrics/metrics_state_manager.cc +++ b/components/metrics/metrics_state_manager.cc
@@ -341,7 +341,7 @@ if (low_entropy_source == kLowEntropySourceNotSet) low_entropy_source = GetLowEntropySource(); - return client_id_ + base::IntToString(low_entropy_source); + return client_id_ + base::NumberToString(low_entropy_source); } int MetricsStateManager::GetLowEntropySource() {
diff --git a/components/metrics/metrics_state_manager_unittest.cc b/components/metrics/metrics_state_manager_unittest.cc index d9edc8de..36e8cf5 100644 --- a/components/metrics/metrics_state_manager_unittest.cc +++ b/components/metrics/metrics_state_manager_unittest.cc
@@ -175,7 +175,7 @@ state_manager->GetOldLowEntropySource()); // ...and the high entropy source should include the *new* low entropy source. std::string high_source = state_manager->GetHighEntropySource(); - EXPECT_TRUE(base::EndsWith(high_source, base::IntToString(new_low_source), + EXPECT_TRUE(base::EndsWith(high_source, base::NumberToString(new_low_source), base::CompareCase::SENSITIVE)) << high_source; } @@ -193,7 +193,7 @@ state_manager->GetOldLowEntropySource()); // ...and the high entropy source should include the *new* low entropy source. std::string high_source = state_manager->GetHighEntropySource(); - EXPECT_TRUE(base::EndsWith(high_source, base::IntToString(new_low_source), + EXPECT_TRUE(base::EndsWith(high_source, base::NumberToString(new_low_source), base::CompareCase::SENSITIVE)) << high_source; } @@ -212,7 +212,7 @@ EXPECT_EQ(old_low_source, state_manager->GetOldLowEntropySource()); // ...and the high entropy source should include the *old* low entropy source. std::string high_source = state_manager->GetHighEntropySource(); - EXPECT_TRUE(base::EndsWith(high_source, base::IntToString(old_low_source), + EXPECT_TRUE(base::EndsWith(high_source, base::NumberToString(old_low_source), base::CompareCase::SENSITIVE)) << high_source; } @@ -230,7 +230,7 @@ EXPECT_EQ(old_low_source, state_manager->GetOldLowEntropySource()); // ...and the high entropy source should include the *old* low entropy source. std::string high_source = state_manager->GetHighEntropySource(); - EXPECT_TRUE(base::EndsWith(high_source, base::IntToString(old_low_source), + EXPECT_TRUE(base::EndsWith(high_source, base::NumberToString(old_low_source), base::CompareCase::SENSITIVE)) << high_source; }
diff --git a/components/metrics/persisted_logs.cc b/components/metrics/persisted_logs.cc index bbdb0474..6207769 100644 --- a/components/metrics/persisted_logs.cc +++ b/components/metrics/persisted_logs.cc
@@ -173,7 +173,7 @@ void PersistedLogs::StoreLog(const std::string& log_data) { list_.push_back(LogInfo()); list_.back().Init(metrics_.get(), log_data, - base::Int64ToString(base::Time::Now().ToTimeT()), + base::NumberToString(base::Time::Now().ToTimeT()), signing_key_); }
diff --git a/components/nacl/browser/pnacl_translation_cache.cc b/components/nacl/browser/pnacl_translation_cache.cc index bd58ad4..017040f 100644 --- a/components/nacl/browser/pnacl_translation_cache.cc +++ b/components/nacl/browser/pnacl_translation_cache.cc
@@ -23,7 +23,7 @@ #include "net/base/net_errors.h" #include "net/disk_cache/disk_cache.h" -using base::IntToString; +using base::NumberToString; using content::BrowserThread; namespace { @@ -398,8 +398,8 @@ info.extra_flags.size() > 512) return std::string(); std::string retval("ABI:"); - retval += IntToString(info.abi_version) + ";" + "opt:" + - IntToString(info.opt_level) + + retval += NumberToString(info.abi_version) + ";" + + "opt:" + NumberToString(info.opt_level) + (info.use_subzero ? "subzero;" : ";") + "URL:"; // Filter the username, password, and ref components from the URL GURL::Replacements replacements; @@ -416,12 +416,13 @@ if (info.last_modified.is_null() || !exploded.HasValidValues()) { memset(&exploded, 0, sizeof(exploded)); } - retval += "modified:" + IntToString(exploded.year) + ":" + - IntToString(exploded.month) + ":" + - IntToString(exploded.day_of_month) + ":" + - IntToString(exploded.hour) + ":" + IntToString(exploded.minute) + - ":" + IntToString(exploded.second) + ":" + - IntToString(exploded.millisecond) + ":UTC;"; + retval += "modified:" + NumberToString(exploded.year) + ":" + + NumberToString(exploded.month) + ":" + + NumberToString(exploded.day_of_month) + ":" + + NumberToString(exploded.hour) + ":" + + NumberToString(exploded.minute) + ":" + + NumberToString(exploded.second) + ":" + + NumberToString(exploded.millisecond) + ":UTC;"; retval += "etag:" + info.etag + ";"; retval += "sandbox:" + info.sandbox_isa + ";"; retval += "extra_flags:" + info.extra_flags + ";";
diff --git a/components/network_time/network_time_test_utils.cc b/components/network_time/network_time_test_utils.cc index d5016d2..984da34 100644 --- a/components/network_time/network_time_test_utils.cc +++ b/components/network_time/network_time_test_utils.cc
@@ -70,7 +70,7 @@ std::map<std::string, std::string> params; params["RandomQueryProbability"] = base::NumberToString(query_probability); - params["CheckTimeIntervalSeconds"] = base::Int64ToString(360); + params["CheckTimeIntervalSeconds"] = base::NumberToString(360); std::string fetch_behavior_param; switch (fetch_behavior) { case NetworkTimeTracker::FETCH_BEHAVIOR_UNKNOWN:
diff --git a/components/network_time/network_time_tracker.cc b/components/network_time/network_time_tracker.cc index 476e9d7..1d6d1e7 100644 --- a/components/network_time/network_time_tracker.cc +++ b/components/network_time/network_time_tracker.cc
@@ -174,8 +174,7 @@ // static void NetworkTimeTracker::RegisterPrefs(PrefRegistrySimple* registry) { - registry->RegisterDictionaryPref(prefs::kNetworkTimeMapping, - std::make_unique<base::DictionaryValue>()); + registry->RegisterDictionaryPref(prefs::kNetworkTimeMapping); registry->RegisterBooleanPref(prefs::kNetworkTimeQueriesEnabled, true); }
diff --git a/components/ntp_snippets/bookmarks/bookmark_last_visit_utils.cc b/components/ntp_snippets/bookmarks/bookmark_last_visit_utils.cc index 1efb413..1705e3c 100644 --- a/components/ntp_snippets/bookmarks/bookmark_last_visit_utils.cc +++ b/components/ntp_snippets/bookmarks/bookmark_last_visit_utils.cc
@@ -41,7 +41,7 @@ const char kBookmarkDismissedFromNTP[] = "dismissed_from_ntp"; std::string FormatLastVisitDate(const base::Time& date) { - return base::Int64ToString(SerializeTime(date)); + return base::NumberToString(SerializeTime(date)); } bool ExtractLastVisitDate(const BookmarkNode& node,
diff --git a/components/ntp_snippets/bookmarks/bookmark_last_visit_utils_unittest.cc b/components/ntp_snippets/bookmarks/bookmark_last_visit_utils_unittest.cc index 6e9dc1f..fe057023 100644 --- a/components/ntp_snippets/bookmarks/bookmark_last_visit_utils_unittest.cc +++ b/components/ntp_snippets/bookmarks/bookmark_last_visit_utils_unittest.cc
@@ -55,14 +55,14 @@ int num, const base::Time& visit_time) { AddBookmarks(model, num, kBookmarkLastVisitDateOnMobileKey, - base::Int64ToString(SerializeTime(visit_time))); + base::NumberToString(SerializeTime(visit_time))); } void AddBookmarksRecentOnDesktop(BookmarkModel* model, int num, const base::Time& visit_time) { AddBookmarks(model, num, kBookmarkLastVisitDateOnDesktopKey, - base::Int64ToString(SerializeTime(visit_time))); + base::NumberToString(SerializeTime(visit_time))); } void AddBookmarksNonVisited(BookmarkModel* model, int num) { @@ -78,7 +78,7 @@ const BookmarkNode* node = model->AddURL(model->bookmark_bar_node(), 0, title, GURL(url)); model->SetNodeMetaInfo(node, last_visit_key, - base::Int64ToString(SerializeTime(visit_time))); + base::NumberToString(SerializeTime(visit_time))); return node; } @@ -221,7 +221,7 @@ model.get(), "http://url-1.com", kBookmarkLastVisitDateOnMobileKey, delete_begin + base::TimeDelta::FromSeconds(1)); model->SetNodeMetaInfo(node, kBookmarkLastVisitDateOnDesktopKey, - base::Int64ToString(SerializeTime( + base::NumberToString(SerializeTime( delete_begin - base::TimeDelta::FromSeconds(1)))); ASSERT_THAT( GetRecentlyVisitedBookmarks(model.get(), 20, base::Time(),
diff --git a/components/ntp_snippets/category_rankers/click_based_category_ranker.cc b/components/ntp_snippets/category_rankers/click_based_category_ranker.cc index d6d5a79..f0ac042 100644 --- a/components/ntp_snippets/category_rankers/click_based_category_ranker.cc +++ b/components/ntp_snippets/category_rankers/click_based_category_ranker.cc
@@ -135,7 +135,7 @@ std::string GetOptionalCategoryAsString( const base::Optional<Category>& optional_category) { if (optional_category.has_value()) { - return base::IntToString(optional_category->id()); + return base::NumberToString(optional_category->id()); } return "None"; } @@ -293,8 +293,8 @@ for (const auto& ranked_category : ordered_categories_) { category_strings.push_back(base::ReplaceStringPlaceholders( "($1; $2)", - {base::IntToString(ranked_category.category.id()), - base::IntToString(ranked_category.clicks)}, + {base::NumberToString(ranked_category.category.id()), + base::NumberToString(ranked_category.clicks)}, /*offsets=*/nullptr)); } result.push_back( @@ -510,7 +510,7 @@ dictionary->SetInteger(kClicksKey, category.clicks); dictionary->SetString( kLastDismissedKey, - base::Int64ToString(SerializeTime(category.last_dismissed))); + base::NumberToString(SerializeTime(category.last_dismissed))); list.Append(std::move(dictionary)); } pref_service_->Set(prefs::kClickBasedCategoryRankerOrderWithClicks, list);
diff --git a/components/ntp_snippets/category_rankers/click_based_category_ranker_unittest.cc b/components/ntp_snippets/category_rankers/click_based_category_ranker_unittest.cc index 51fa506f..b7fd7c56 100644 --- a/components/ntp_snippets/category_rankers/click_based_category_ranker_unittest.cc +++ b/components/ntp_snippets/category_rankers/click_based_category_ranker_unittest.cc
@@ -86,7 +86,7 @@ variation_params_manager_.SetVariationParamsWithFeatureAssociations( kCategoryRanker.name, {{"click_based_category_ranker-dismissed_category_penalty", - base::IntToString(value)}}, + base::NumberToString(value)}}, {kCategoryRanker.name}); } @@ -94,7 +94,7 @@ variation_params_manager_.SetVariationParamsWithFeatureAssociations( kCategoryRanker.name, {{"click_based_category_ranker-promoted_category", - base::IntToString(value)}}, + base::NumberToString(value)}}, {kCategoryRanker.name}); }
diff --git a/components/ntp_snippets/category_rankers/constant_category_ranker.cc b/components/ntp_snippets/category_rankers/constant_category_ranker.cc index 6a0711a..60647cb 100644 --- a/components/ntp_snippets/category_rankers/constant_category_ranker.cc +++ b/components/ntp_snippets/category_rankers/constant_category_ranker.cc
@@ -96,7 +96,7 @@ std::vector<std::string> category_strings; for (Category category : ordered_categories_) { - category_strings.push_back(base::IntToString(category.id())); + category_strings.push_back(base::NumberToString(category.id())); } result.push_back(CategoryRanker::DebugDataItem( "Current order", base::JoinString(category_strings, ", ")));
diff --git a/components/ntp_snippets/content_suggestions_service_unittest.cc b/components/ntp_snippets/content_suggestions_service_unittest.cc index 67f9093..da8bf43 100644 --- a/components/ntp_snippets/content_suggestions_service_unittest.cc +++ b/components/ntp_snippets/content_suggestions_service_unittest.cc
@@ -175,8 +175,8 @@ // Returns a suggestion instance for testing. ContentSuggestion CreateSuggestion(Category category, int number) { return ContentSuggestion( - category, base::IntToString(number), - GURL("http://testsuggestion/" + base::IntToString(number))); + category, base::NumberToString(number), + GURL("http://testsuggestion/" + base::NumberToString(number))); } std::vector<ContentSuggestion> CreateSuggestions(
diff --git a/components/ntp_snippets/logger_unittest.cc b/components/ntp_snippets/logger_unittest.cc index 595415a..becf0383 100644 --- a/components/ntp_snippets/logger_unittest.cc +++ b/components/ntp_snippets/logger_unittest.cc
@@ -27,7 +27,7 @@ void EnableFeature() { params_manager_.SetVariationParamsWithFeatureAssociations( kContentSuggestionsDebugLog.name, - {{"max_items_count", base::IntToString(kMaxItemsCount)}}, + {{"max_items_count", base::NumberToString(kMaxItemsCount)}}, {kContentSuggestionsDebugLog.name}); }
diff --git a/components/ntp_snippets/offline_pages/offline_pages_test_utils.cc b/components/ntp_snippets/offline_pages/offline_pages_test_utils.cc index 0ee83c6..6bd01ec 100644 --- a/components/ntp_snippets/offline_pages/offline_pages_test_utils.cc +++ b/components/ntp_snippets/offline_pages/offline_pages_test_utils.cc
@@ -65,7 +65,7 @@ OfflinePageItem CreateDummyOfflinePageItem( int id, const offline_pages::ClientId& client_id) { - std::string id_string = base::IntToString(id); + std::string id_string = base::NumberToString(id); return OfflinePageItem( GURL("http://dummy.com/" + id_string), id, client_id, base::FilePath::FromUTF8Unsafe("some/folder/test" + id_string + ".mhtml"),
diff --git a/components/ntp_snippets/remote/cached_image_fetcher.cc b/components/ntp_snippets/remote/cached_image_fetcher.cc index afbdf6f6..41d84b2e 100644 --- a/components/ntp_snippets/remote/cached_image_fetcher.cc +++ b/components/ntp_snippets/remote/cached_image_fetcher.cc
@@ -50,11 +50,6 @@ thumbnail_requests_throttler_( pref_service, RequestThrottler::RequestType::CONTENT_SUGGESTION_THUMBNAIL) { - // |image_fetcher_| can be null in tests. - if (image_fetcher_) { - image_fetcher_->SetDataUseServiceName( - data_use_measurement::DataUseUserData::NTP_SNIPPETS_THUMBNAILS); - } } CachedImageFetcher::~CachedImageFetcher() {} @@ -79,6 +74,13 @@ std::move(callback).Run(image); } +void CachedImageFetcher::OnImageFetchingDone( + ImageFetchedCallback callback, + const gfx::Image& image, + const image_fetcher::RequestMetadata& metadata) { + std::move(callback).Run(image); +} + void CachedImageFetcher::OnImageFetchedFromDatabase( ImageDataFetchedCallback image_data_callback, ImageFetchedCallback image_callback, @@ -145,16 +147,17 @@ image_fetcher::ImageFetcherCallback decode_callback; if (image_callback) { decode_callback = - base::BindOnce(&CachedImageFetcher::OnImageDecodingDone, + base::BindOnce(&CachedImageFetcher::OnImageFetchingDone, base::Unretained(this), std::move(image_callback)); } + image_fetcher::ImageFetcherParams params(kTrafficAnnotation); image_fetcher_->FetchImageAndData( - suggestion_id.id_within_category(), url, + url, base::BindOnce(&CachedImageFetcher::SaveImageAndInvokeDataCallback, base::Unretained(this), suggestion_id.id_within_category(), std::move(image_data_callback)), - std::move(decode_callback), kTrafficAnnotation); + std::move(decode_callback), std::move(params)); } void CachedImageFetcher::SaveImageAndInvokeDataCallback(
diff --git a/components/ntp_snippets/remote/cached_image_fetcher.h b/components/ntp_snippets/remote/cached_image_fetcher.h index d1e1c6d5..3a2e8ae 100644 --- a/components/ntp_snippets/remote/cached_image_fetcher.h +++ b/components/ntp_snippets/remote/cached_image_fetcher.h
@@ -61,6 +61,10 @@ const gfx::Image& image, const image_fetcher::RequestMetadata& metadata); + void OnImageFetchingDone(ImageFetchedCallback callback, + const gfx::Image& image, + const image_fetcher::RequestMetadata& metadata); + void OnImageFetchedFromDatabase( ImageDataFetchedCallback image_data_callback, ImageFetchedCallback image_callback,
diff --git a/components/ntp_snippets/remote/prefetched_pages_tracker_impl_unittest.cc b/components/ntp_snippets/remote/prefetched_pages_tracker_impl_unittest.cc index 5563844..d76ea9d 100644 --- a/components/ntp_snippets/remote/prefetched_pages_tracker_impl_unittest.cc +++ b/components/ntp_snippets/remote/prefetched_pages_tracker_impl_unittest.cc
@@ -42,7 +42,7 @@ static int id = 0; ++id; return OfflinePageItem( - url, id, offline_pages::ClientId(name_space, base::IntToString(id)), + url, id, offline_pages::ClientId(name_space, base::NumberToString(id)), base::FilePath::FromUTF8Unsafe( base::StringPrintf("some/folder/%d.mhtml", id)), 0, base::Time::Now());
diff --git a/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc b/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc index bab05cb..4c5e4fc 100644 --- a/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc +++ b/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc
@@ -165,14 +165,13 @@ } void ServeOneByOneImage( - const std::string& id, image_fetcher::ImageDataFetcherCallback* image_data_callback, image_fetcher::ImageFetcherCallback* callback) { std::move(*image_data_callback) .Run("1-by-1-image-data", image_fetcher::RequestMetadata()); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(std::move(*callback), id, gfx::test::CreateImage(1, 1), + base::BindOnce(std::move(*callback), gfx::test::CreateImage(1, 1), image_fetcher::RequestMetadata())); } @@ -616,9 +615,9 @@ kKeepPrefetchedContentSuggestions.name, { {"max_additional_prefetched_suggestions", - base::IntToString(max_additional_prefetched_suggestions)}, + base::NumberToString(max_additional_prefetched_suggestions)}, {"max_age_for_additional_prefetched_suggestion_minutes", - base::IntToString( + base::NumberToString( max_age_for_additional_prefetched_suggestion.InMinutes())}, }, {kKeepPrefetchedContentSuggestions.name}); @@ -669,7 +668,7 @@ params_manager_.ClearAllVariationParams(); params_manager_.SetVariationParamsWithFeatureAssociations( /*trial_name=*/kArticleSuggestionsFeature.name, - {{"fetch_more_suggestions_count", base::IntToString(count)}}, + {{"fetch_more_suggestions_count", base::NumberToString(count)}}, {kArticleSuggestionsFeature.name}); } @@ -1326,8 +1325,8 @@ image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1)); auto serve_one_by_one_image_callback = base::BindRepeating(&ServeOneByOneImage); - EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _, _)) - .WillOnce(WithArgs<0, 2, 3>( + EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _)) + .WillOnce(WithArgs<1, 2>( Invoke(CreateFunctor(serve_one_by_one_image_callback)))); gfx::Image image = FetchImage(provider.get(), MakeArticleID("id")); @@ -1398,8 +1397,8 @@ image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1)); auto serve_one_by_one_image_callback = base::BindRepeating(&ServeOneByOneImage); - EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _, _)) - .WillOnce(WithArgs<0, 2, 3>( + EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _)) + .WillOnce(WithArgs<1, 2>( Invoke(CreateFunctor(serve_one_by_one_image_callback)))); gfx::Image image = FetchImage(provider.get(), MakeArticleID("id")); @@ -1566,9 +1565,9 @@ Status::Success(), std::move(fetched_categories)); // Make sure images of both batches are available. This is to sanity check our // assumptions for the test are right. - EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _, _)) + EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _)) .Times(2) - .WillRepeatedly(WithArgs<0, 2, 3>( + .WillRepeatedly(WithArgs<1, 2>( Invoke(CreateFunctor(base::BindRepeating(&ServeOneByOneImage))))); image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1)); gfx::Image image = FetchImage(provider.get(), MakeArticleID("http://id-1")); @@ -1731,8 +1730,8 @@ ASSERT_THAT(provider->GetSuggestionsForTesting(articles_category()), SizeIs(1)); // Load the image to store it in the database. - EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _, _)) - .WillOnce(WithArgs<0, 2, 3>( + EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _)) + .WillOnce(WithArgs<1, 2>( Invoke(CreateFunctor(base::BindRepeating(&ServeOneByOneImage))))); image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1)); gfx::Image image = @@ -1857,8 +1856,8 @@ // Load the image to store it in the database. // TODO(tschumann): Introduce some abstraction to nicely work with image // fetching expectations. - EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _, _)) - .WillOnce(WithArgs<0, 2, 3>( + EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _)) + .WillOnce(WithArgs<1, 2>( Invoke(CreateFunctor(base::BindRepeating(&ServeOneByOneImage))))); image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1)); gfx::Image image = FetchImage(provider.get(), MakeArticleID("http://first/")); @@ -2123,8 +2122,8 @@ MockFunction<void(const gfx::Image&)> image_fetched; { InSequence s; - EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _, _)) - .WillOnce(WithArgs<0, 2, 3>( + EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _)) + .WillOnce(WithArgs<1, 2>( Invoke(CreateFunctor(base::BindRepeating(&ServeOneByOneImage))))); EXPECT_CALL(image_fetched, Call(_)).WillOnce(SaveArg<0>(&image)); } @@ -2259,8 +2258,8 @@ FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, Status::Success(), std::move(fetched_categories)); - EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _, _)) - .WillOnce(WithArgs<0, 2, 3>( + EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _)) + .WillOnce(WithArgs<1, 2>( Invoke(CreateFunctor(base::BindRepeating(&ServeOneByOneImage))))); image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1)); @@ -2499,7 +2498,7 @@ std::set<std::string> known_ids; for (int i = 0; i < 200; ++i) { - known_ids.insert(base::IntToString(i)); + known_ids.insert(base::NumberToString(i)); } EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch()) @@ -3382,7 +3381,7 @@ FetchedCategoryBuilder category_builder = FetchedCategoryBuilder().SetCategory(articles_category()); for (int i = 0; i < 10; ++i) { - const std::string url = "http://other.com/" + base::IntToString(i); + const std::string url = "http://other.com/" + base::NumberToString(i); category_builder.AddSuggestionViaBuilder( RemoteSuggestionBuilder().AddId(url).SetUrl(url)); } @@ -3408,7 +3407,7 @@ for (int i = 0; i < 10; ++i) { expected.push_back( Property(&ContentSuggestion::id, - MakeArticleID("http://other.com/" + base::IntToString(i)))); + MakeArticleID("http://other.com/" + base::NumberToString(i)))); } EXPECT_THAT(observer().SuggestionsForCategory(articles_category()), @@ -3601,7 +3600,7 @@ FetchedCategoryBuilder category_builder = FetchedCategoryBuilder().SetCategory(articles_category()); for (int i = 0; i < 10; ++i) { - const std::string url = "http://other.com/" + base::IntToString(i); + const std::string url = "http://other.com/" + base::NumberToString(i); category_builder.AddSuggestionViaBuilder( RemoteSuggestionBuilder().AddId(url).SetUrl(url)); } @@ -3634,7 +3633,7 @@ for (int i = 0; i < 10; ++i) { expected.push_back( Property(&ContentSuggestion::id, - MakeArticleID("http://other.com/" + base::IntToString(i)))); + MakeArticleID("http://other.com/" + base::NumberToString(i)))); } EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
diff --git a/components/ntp_snippets/remote/remote_suggestions_scheduler_impl_unittest.cc b/components/ntp_snippets/remote/remote_suggestions_scheduler_impl_unittest.cc index 581c2ac2e..0225c52 100644 --- a/components/ntp_snippets/remote/remote_suggestions_scheduler_impl_unittest.cc +++ b/components/ntp_snippets/remote/remote_suggestions_scheduler_impl_unittest.cc
@@ -1201,7 +1201,7 @@ ShouldNotRefetchWhileDisplayingBeforeConfigurableDelay) { constexpr int kStaleHours = 18; SetVariationParameter("min_age_for_stale_fetch_hours", - base::IntToString(kStaleHours)); + base::NumberToString(kStaleHours)); // Activating the provider should schedule the persistent background fetches. EXPECT_CALL(*persistent_scheduler(), Schedule(_, _)).Times(2); // First enable the scheduler -- this will trigger the persistent scheduling. @@ -1230,7 +1230,7 @@ ShouldRefetchWhileDisplayingAfterConfigurableDelay) { constexpr int kStaleHours = 18; SetVariationParameter("min_age_for_stale_fetch_hours", - base::IntToString(kStaleHours)); + base::NumberToString(kStaleHours)); // Activating the provider should schedule the persistent background fetches. EXPECT_CALL(*persistent_scheduler(), Schedule(_, _)).Times(2); // First enable the scheduler -- this will trigger the persistent scheduling. @@ -1258,7 +1258,7 @@ ShouldNotRefetchWhileDisplayingBeforeFallbackConfigurableDelay) { constexpr int kStartupHours = 12; SetVariationParameter("startup_fetching_interval_hours-wifi-active_ntp_user", - base::IntToString(kStartupHours)); + base::NumberToString(kStartupHours)); // Activating the provider should schedule the persistent background fetches. EXPECT_CALL(*persistent_scheduler(), Schedule(_, _)).Times(2); // First enable the scheduler -- this will trigger the persistent scheduling. @@ -1287,7 +1287,7 @@ ShouldRefetchWhileDisplayingAfterFallbackConfigurableDelay) { constexpr int kStartupHours = 12; SetVariationParameter("startup_fetching_interval_hours-wifi-active_ntp_user", - base::IntToString(kStartupHours)); + base::NumberToString(kStartupHours)); // Activating the provider should schedule the persistent background fetches. EXPECT_CALL(*persistent_scheduler(), Schedule(_, _)).Times(2); // First enable the scheduler -- this will trigger the persistent scheduling.
diff --git a/components/ntp_tiles/icon_cacher_impl.cc b/components/ntp_tiles/icon_cacher_impl.cc index 855e70f..e6efa6a 100644 --- a/components/ntp_tiles/icon_cacher_impl.cc +++ b/components/ntp_tiles/icon_cacher_impl.cc
@@ -80,11 +80,6 @@ large_icon_service_(large_icon_service), image_fetcher_(std::move(image_fetcher)), weak_ptr_factory_(this) { - image_fetcher_->SetDataUseServiceName( - data_use_measurement::DataUseUserData::NTP_TILES); - // For images with multiple frames, prefer one of size 128x128px. - image_fetcher_->SetDesiredImageFrameSize( - gfx::Size(kDesiredFrameSize, kDesiredFrameSize)); } IconCacherImpl::~IconCacherImpl() = default; @@ -138,18 +133,20 @@ setting: "This feature cannot be disabled in settings." policy_exception_justification: "Not implemented." })"); + image_fetcher::ImageFetcherParams params(traffic_annotation); + // For images with multiple frames, prefer one of size 128x128px. + params.set_frame_size(gfx::Size(kDesiredFrameSize, kDesiredFrameSize)); image_fetcher_->FetchImage( - std::string(), IconURL(site), + IconURL(site), base::BindOnce(&IconCacherImpl::OnPopularSitesFaviconDownloaded, base::Unretained(this), site, std::move(preliminary_callback)), - traffic_annotation); + params); } void IconCacherImpl::OnPopularSitesFaviconDownloaded( PopularSites::Site site, std::unique_ptr<CancelableImageCallback> preliminary_callback, - const std::string& id, const gfx::Image& fetched_image, const image_fetcher::RequestMetadata& metadata) { if (fetched_image.IsEmpty()) {
diff --git a/components/ntp_tiles/icon_cacher_impl.h b/components/ntp_tiles/icon_cacher_impl.h index 671b020..25d2deb6 100644 --- a/components/ntp_tiles/icon_cacher_impl.h +++ b/components/ntp_tiles/icon_cacher_impl.h
@@ -69,7 +69,6 @@ void OnPopularSitesFaviconDownloaded( PopularSites::Site site, std::unique_ptr<CancelableImageCallback> preliminary_callback, - const std::string& id, const gfx::Image& fetched_image, const image_fetcher::RequestMetadata& metadata);
diff --git a/components/ntp_tiles/icon_cacher_impl_unittest.cc b/components/ntp_tiles/icon_cacher_impl_unittest.cc index 3c8e98c..c9fd3dbe 100644 --- a/components/ntp_tiles/icon_cacher_impl_unittest.cc +++ b/components/ntp_tiles/icon_cacher_impl_unittest.cc
@@ -37,12 +37,13 @@ #include "ui/gfx/image/image_unittest_util.h" using base::Bucket; +using image_fetcher::ImageFetcherParams; using ::image_fetcher::MockImageFetcher; using ::testing::_; using ::testing::ElementsAre; using ::testing::Eq; -using ::testing::Invoke; using ::testing::InSequence; +using ::testing::Invoke; using ::testing::IsEmpty; using ::testing::NiceMock; using ::testing::Return; @@ -84,7 +85,7 @@ ACTION(FailFetch) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(std::move(*arg3), arg0, gfx::Image(), + FROM_HERE, base::BindOnce(std::move(*arg2), gfx::Image(), image_fetcher::RequestMetadata())); } @@ -95,9 +96,9 @@ ACTION_P2(PassFetch, width, height) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(std::move(*arg3), arg0, - gfx::test::CreateImage(width, height), - image_fetcher::RequestMetadata())); + FROM_HERE, + base::BindOnce(std::move(*arg2), gfx::test::CreateImage(width, height), + image_fetcher::RequestMetadata())); } ACTION_P(Quit, run_loop) { @@ -221,14 +222,7 @@ base::HistogramTester histogram_tester; base::MockCallback<base::Closure> done; EXPECT_CALL(done, Run()).Times(0); - base::RunLoop loop; - { - InSequence s; - EXPECT_CALL(*image_fetcher_, - SetDataUseServiceName( - data_use_measurement::DataUseUserData::NTP_TILES)); - EXPECT_CALL(*image_fetcher_, SetDesiredImageFrameSize(gfx::Size(128, 128))); - } + PreloadIcon(site_.url, site_.large_icon_url, favicon_base::IconType::kTouchIcon, 128, 128); IconCacherImpl cacher(&favicon_service_, nullptr, std::move(image_fetcher_)); @@ -248,11 +242,7 @@ { InSequence s; EXPECT_CALL(*image_fetcher_, - SetDataUseServiceName( - data_use_measurement::DataUseUserData::NTP_TILES)); - EXPECT_CALL(*image_fetcher_, SetDesiredImageFrameSize(gfx::Size(128, 128))); - EXPECT_CALL(*image_fetcher_, - FetchImageAndData_(_, site_.large_icon_url, _, _, _)) + FetchImageAndData_(site_.large_icon_url, _, _, _)) .WillOnce(PassFetch(128, 128)); EXPECT_CALL(done, Run()).WillOnce(Quit(&loop)); } @@ -274,12 +264,7 @@ base::RunLoop loop; { InSequence s; - EXPECT_CALL(*image_fetcher_, - SetDataUseServiceName( - data_use_measurement::DataUseUserData::NTP_TILES)); - EXPECT_CALL(*image_fetcher_, SetDesiredImageFrameSize(gfx::Size(128, 128))); - EXPECT_CALL(*image_fetcher_, - FetchImageAndData_(_, site_.favicon_url, _, _, _)) + EXPECT_CALL(*image_fetcher_, FetchImageAndData_(site_.favicon_url, _, _, _)) .WillOnce(PassFetch(128, 128)); EXPECT_CALL(done, Run()).WillOnce(Quit(&loop)); } @@ -298,11 +283,7 @@ { InSequence s; EXPECT_CALL(*image_fetcher_, - SetDataUseServiceName( - data_use_measurement::DataUseUserData::NTP_TILES)); - EXPECT_CALL(*image_fetcher_, SetDesiredImageFrameSize(gfx::Size(128, 128))); - EXPECT_CALL(*image_fetcher_, - FetchImageAndData_(_, site_.large_icon_url, _, _, _)) + FetchImageAndData_(site_.large_icon_url, _, _, _)) .WillOnce(FailFetch()); } @@ -318,9 +299,7 @@ TEST_F(IconCacherTestPopularSites, HandlesEmptyCallbacksNicely) { base::HistogramTester histogram_tester; - EXPECT_CALL(*image_fetcher_, SetDataUseServiceName(_)); - EXPECT_CALL(*image_fetcher_, SetDesiredImageFrameSize(_)); - EXPECT_CALL(*image_fetcher_, FetchImageAndData_(_, _, _, _, _)) + EXPECT_CALL(*image_fetcher_, FetchImageAndData_(_, _, _, _)) .WillOnce(PassFetch(128, 128)); IconCacherImpl cacher(&favicon_service_, nullptr, std::move(image_fetcher_)); cacher.StartFetchPopularSites(site_, base::Closure(), base::Closure()); @@ -353,11 +332,7 @@ { InSequence s; EXPECT_CALL(*image_fetcher_, - SetDataUseServiceName( - data_use_measurement::DataUseUserData::NTP_TILES)); - EXPECT_CALL(*image_fetcher_, SetDesiredImageFrameSize(gfx::Size(128, 128))); - EXPECT_CALL(*image_fetcher_, - FetchImageAndData_(_, site_.large_icon_url, _, _, _)) + FetchImageAndData_(site_.large_icon_url, _, _, _)) .WillOnce(PassFetch(128, 128)); // Both callback are called async after the request but preliminary has to @@ -394,13 +369,8 @@ base::RunLoop loop; { InSequence s; - // Image fetcher is used only once. EXPECT_CALL(*image_fetcher_, - SetDataUseServiceName( - data_use_measurement::DataUseUserData::NTP_TILES)); - EXPECT_CALL(*image_fetcher_, SetDesiredImageFrameSize(gfx::Size(128, 128))); - EXPECT_CALL(*image_fetcher_, - FetchImageAndData_(_, site_.large_icon_url, _, _, _)) + FetchImageAndData_(site_.large_icon_url, _, _, _)) .WillOnce(PassFetch(128, 128)); // Success will be notified to both requests. EXPECT_CALL(done, Run()).WillOnce(Return()).WillOnce(Quit(&loop)); @@ -420,16 +390,7 @@ : fetcher_for_large_icon_service_( std::make_unique<::testing::StrictMock<MockImageFetcher>>()), fetcher_for_icon_cacher_( - std::make_unique<::testing::StrictMock<MockImageFetcher>>()) { - // Expect uninteresting calls here, |fetcher_for_icon_cacher_| is not - // related to these tests. Keep it strict to make sure we do not use it in - // any other way. - EXPECT_CALL(*fetcher_for_icon_cacher_, - SetDataUseServiceName( - data_use_measurement::DataUseUserData::NTP_TILES)); - EXPECT_CALL(*fetcher_for_icon_cacher_, - SetDesiredImageFrameSize(gfx::Size(128, 128))); - } + std::make_unique<::testing::StrictMock<MockImageFetcher>>()) {} std::unique_ptr<MockImageFetcher> fetcher_for_large_icon_service_; std::unique_ptr<MockImageFetcher> fetcher_for_icon_cacher_; @@ -467,11 +428,9 @@ base::RunLoop loop; { InSequence s; + EXPECT_CALL(*fetcher_for_large_icon_service_, - SetDataUseServiceName( - data_use_measurement::DataUseUserData::LARGE_ICON_SERVICE)); - EXPECT_CALL(*fetcher_for_large_icon_service_, - FetchImageAndData_(_, _, _, _, _)) + FetchImageAndData_(_, _, _, _)) .WillOnce(PassFetch(128, 128)); EXPECT_CALL(done, Run()).WillOnce(Quit(&loop)); } @@ -505,11 +464,9 @@ base::MockCallback<base::Closure> done; { InSequence s; + EXPECT_CALL(*fetcher_for_large_icon_service_, - SetDataUseServiceName( - data_use_measurement::DataUseUserData::LARGE_ICON_SERVICE)); - EXPECT_CALL(*fetcher_for_large_icon_service_, - FetchImageAndData_(_, _, _, _, _)) + FetchImageAndData_(_, _, _, _)) .WillOnce(FailFetch()); EXPECT_CALL(done, Run()).Times(0); } @@ -539,9 +496,7 @@ TEST_F(IconCacherTestMostLikely, HandlesEmptyCallbacksNicely) { GURL page_url("http://www.site.com"); - EXPECT_CALL(*fetcher_for_large_icon_service_, SetDataUseServiceName(_)); - EXPECT_CALL(*fetcher_for_large_icon_service_, - FetchImageAndData_(_, _, _, _, _)) + EXPECT_CALL(*fetcher_for_large_icon_service_, FetchImageAndData_(_, _, _, _)) .WillOnce(PassFetch(128, 128)); favicon::LargeIconServiceImpl large_icon_service( @@ -574,12 +529,9 @@ base::RunLoop loop; { InSequence s; - // Image fetcher is used only once. + EXPECT_CALL(*fetcher_for_large_icon_service_, - SetDataUseServiceName( - data_use_measurement::DataUseUserData::LARGE_ICON_SERVICE)); - EXPECT_CALL(*fetcher_for_large_icon_service_, - FetchImageAndData_(_, _, _, _, _)) + FetchImageAndData_(_, _, _, _)) .WillOnce(PassFetch(128, 128)); // Success will be notified to both requests. EXPECT_CALL(done, Run()).WillOnce(Return()).WillOnce(Quit(&loop));
diff --git a/components/offline_items_collection/core/offline_content_aggregator.cc b/components/offline_items_collection/core/offline_content_aggregator.cc index 8daa37a..67be1b54 100644 --- a/components/offline_items_collection/core/offline_content_aggregator.cc +++ b/components/offline_items_collection/core/offline_content_aggregator.cc
@@ -40,7 +40,7 @@ return prefix; static int num_registrations = 0; - return prefix + "_" + base::IntToString(++num_registrations); + return prefix + "_" + base::NumberToString(++num_registrations); } void OfflineContentAggregator::RegisterProvider(
diff --git a/components/offline_pages/core/downloads/download_ui_adapter.cc b/components/offline_pages/core/downloads/download_ui_adapter.cc index 1f87fa6..4ed1c08 100644 --- a/components/offline_pages/core/downloads/download_ui_adapter.cc +++ b/components/offline_pages/core/downloads/download_ui_adapter.cc
@@ -30,17 +30,22 @@ namespace { +bool RequestsMatchesGuid(const std::string& guid, + ClientPolicyController* policy_controller, + const SavePageRequest& request) { + return request.client_id().id == guid && + policy_controller->IsSupportedByDownload( + request.client_id().name_space); +} + std::vector<int64_t> FilterRequestsByGuid( std::vector<std::unique_ptr<SavePageRequest>> requests, const std::string& guid, ClientPolicyController* policy_controller) { std::vector<int64_t> request_ids; for (const auto& request : requests) { - if (request->client_id().id == guid && - policy_controller->IsSupportedByDownload( - request->client_id().name_space)) { + if (RequestsMatchesGuid(guid, policy_controller, *request)) request_ids.push_back(request->request_id()); - } } return request_ids; } @@ -389,19 +394,12 @@ } void DownloadUIAdapter::CancelDownload(const ContentId& id) { - // TODO(fgorski): Clean this up in a way where 2 round trips + GetAllRequests - // is not necessary. E.g. CancelByGuid(guid) might do the trick. - request_coordinator_->GetAllRequests( - base::BindOnce(&DownloadUIAdapter::CancelDownloadContinuation, - weak_ptr_factory_.GetWeakPtr(), id.id)); -} - -void DownloadUIAdapter::CancelDownloadContinuation( - const std::string& guid, - std::vector<std::unique_ptr<SavePageRequest>> requests) { - std::vector<int64_t> request_ids = FilterRequestsByGuid( - std::move(requests), guid, request_coordinator_->GetPolicyController()); - request_coordinator_->RemoveRequests(request_ids, base::DoNothing()); + auto predicate = + base::BindRepeating(&RequestsMatchesGuid, id.id, + // Since RequestCoordinator is calling us back, + // binding its policy controller is safe. + request_coordinator_->GetPolicyController()); + request_coordinator_->RemoveRequestsIf(predicate, base::DoNothing()); } void DownloadUIAdapter::PauseDownload(const ContentId& id) {
diff --git a/components/offline_pages/core/downloads/download_ui_adapter.h b/components/offline_pages/core/downloads/download_ui_adapter.h index c753419..c7984bd 100644 --- a/components/offline_pages/core/downloads/download_ui_adapter.h +++ b/components/offline_pages/core/downloads/download_ui_adapter.h
@@ -129,9 +129,6 @@ std::unique_ptr<offline_items_collection::OfflineItemVisuals>)>; // Task callbacks. - void CancelDownloadContinuation( - const std::string& guid, - std::vector<std::unique_ptr<SavePageRequest>> requests); void PauseDownloadContinuation( const std::string& guid, std::vector<std::unique_ptr<SavePageRequest>> requests);
diff --git a/components/offline_pages/core/model/offline_page_item_generator.cc b/components/offline_pages/core/model/offline_page_item_generator.cc index 3cf48e6..aee905b 100644 --- a/components/offline_pages/core/model/offline_page_item_generator.cc +++ b/components/offline_pages/core/model/offline_page_item_generator.cc
@@ -21,7 +21,7 @@ item.offline_id = store_utils::GenerateOfflineId(); item.client_id.name_space = namespace_; if (id_.empty()) - item.client_id.id = base::Int64ToString(item.offline_id); + item.client_id.id = base::NumberToString(item.offline_id); else item.client_id.id = id_; item.request_origin = request_origin_;
diff --git a/components/offline_pages/core/offline_page_thumbnail.cc b/components/offline_pages/core/offline_page_thumbnail.cc index 5b0fe99d..b9f14564 100644 --- a/components/offline_pages/core/offline_page_thumbnail.cc +++ b/components/offline_pages/core/offline_page_thumbnail.cc
@@ -37,8 +37,8 @@ base::Base64Encode(thumbnail, &thumb_data_base64); std::string s("OfflinePageThumbnail("); - s.append(base::Int64ToString(offline_id)).append(", "); - s.append(base::Int64ToString(store_utils::ToDatabaseTime(expiration))) + s.append(base::NumberToString(offline_id)).append(", "); + s.append(base::NumberToString(store_utils::ToDatabaseTime(expiration))) .append(", "); s.append(thumb_data_base64).append(")"); return s;
diff --git a/components/offline_pages/core/prefetch/mock_prefetch_item_generator.cc b/components/offline_pages/core/prefetch/mock_prefetch_item_generator.cc index 130f123..132a7ca 100644 --- a/components/offline_pages/core/prefetch/mock_prefetch_item_generator.cc +++ b/components/offline_pages/core/prefetch/mock_prefetch_item_generator.cc
@@ -47,13 +47,14 @@ // Values always set using prefixes. CHECK(client_namespace_.length()); - new_item.client_id = ClientId( - client_namespace_, client_id_prefix_ + base::IntToString(item_counter)); - new_item.url = GURL(url_prefix_ + base::IntToString(item_counter)); + new_item.client_id = + ClientId(client_namespace_, + client_id_prefix_ + base::NumberToString(item_counter)); + new_item.url = GURL(url_prefix_ + base::NumberToString(item_counter)); if (title_prefix_.length()) { new_item.title = - base::UTF8ToUTF16(title_prefix_ + base::IntToString(item_counter)); + base::UTF8ToUTF16(title_prefix_ + base::NumberToString(item_counter)); } if (state == PrefetchItemState::NEW_REQUEST || @@ -63,7 +64,7 @@ if (operation_name_prefix_.length()) { new_item.operation_name = - operation_name_prefix_ + base::IntToString(item_counter); + operation_name_prefix_ + base::NumberToString(item_counter); } if (state == PrefetchItemState::AWAITING_GCM || @@ -74,12 +75,12 @@ if (archive_body_name_prefix_.length()) { new_item.archive_body_name = - archive_body_name_prefix_ + base::IntToString(item_counter); + archive_body_name_prefix_ + base::NumberToString(item_counter); new_item.archive_body_length = item_counter * 100; } if (final_url_prefix_.length()) { new_item.final_archived_url = - GURL(final_url_prefix_ + base::IntToString(item_counter)); + GURL(final_url_prefix_ + base::NumberToString(item_counter)); } if (state == PrefetchItemState::RECEIVED_BUNDLE) @@ -88,7 +89,7 @@ new_item.guid = base::GenerateGUID(); if (file_path_prefix_.length()) { new_item.file_path = base::FilePath::FromUTF8Unsafe( - file_path_prefix_ + base::IntToString(item_counter)); + file_path_prefix_ + base::NumberToString(item_counter)); } if (state == PrefetchItemState::DOWNLOADING) {
diff --git a/components/offline_pages/core/prefetch/prefetch_dispatcher_impl_unittest.cc b/components/offline_pages/core/prefetch/prefetch_dispatcher_impl_unittest.cc index 79b82b3e..260dbcc 100644 --- a/components/offline_pages/core/prefetch/prefetch_dispatcher_impl_unittest.cc +++ b/components/offline_pages/core/prefetch/prefetch_dispatcher_impl_unittest.cc
@@ -364,11 +364,11 @@ const GURL& thumbnail_url) { ASSERT_TRUE(thumbnail_image_fetcher_) << "Not configured in kFeed mode"; EXPECT_CALL(*thumbnail_image_fetcher_, - FetchImageAndData_(std::string(), thumbnail_url, _, _, _)) - .WillOnce([=](const std::string& id, const GURL& image_url, + FetchImageAndData_(thumbnail_url, _, _, _)) + .WillOnce([=](const GURL& image_url, image_fetcher::ImageDataFetcherCallback* data_callback, image_fetcher::ImageFetcherCallback* image_callback, - const net::NetworkTrafficAnnotationTag&) { + image_fetcher::ImageFetcherParams params) { ASSERT_TRUE(image_callback->is_null()); std::move(*data_callback) .Run(thumbnail_data, image_fetcher::RequestMetadata());
diff --git a/components/offline_pages/core/prefetch/prefetch_service_impl.cc b/components/offline_pages/core/prefetch/prefetch_service_impl.cc index c15fba58..309c094 100644 --- a/components/offline_pages/core/prefetch/prefetch_service_impl.cc +++ b/components/offline_pages/core/prefetch/prefetch_service_impl.cc
@@ -38,7 +38,7 @@ std::unique_ptr<PrefetchBackgroundTaskHandler> prefetch_background_task_handler, std::unique_ptr<ThumbnailFetcher> thumbnail_fetcher, - std::unique_ptr<image_fetcher::ImageFetcher> thumbnail_image_fetcher) + image_fetcher::ImageFetcher* thumbnail_image_fetcher) : offline_metrics_collector_(std::move(offline_metrics_collector)), prefetch_dispatcher_(std::move(dispatcher)), prefetch_gcm_handler_(std::move(gcm_handler)), @@ -51,7 +51,7 @@ std::move(prefetch_background_task_handler)), suggested_articles_observer_(std::move(suggested_articles_observer)), thumbnail_fetcher_(std::move(thumbnail_fetcher)), - thumbnail_image_fetcher_(std::move(thumbnail_image_fetcher)) { + thumbnail_image_fetcher_(thumbnail_image_fetcher) { prefetch_dispatcher_->SetService(this); prefetch_downloader_->SetPrefetchService(this); prefetch_gcm_handler_->SetService(this); @@ -152,7 +152,7 @@ } image_fetcher::ImageFetcher* PrefetchServiceImpl::GetThumbnailImageFetcher() { - return thumbnail_image_fetcher_.get(); + return thumbnail_image_fetcher_; } void PrefetchServiceImpl::Shutdown() {
diff --git a/components/offline_pages/core/prefetch/prefetch_service_impl.h b/components/offline_pages/core/prefetch/prefetch_service_impl.h index 93fa2ef..40f3dfb 100644 --- a/components/offline_pages/core/prefetch/prefetch_service_impl.h +++ b/components/offline_pages/core/prefetch/prefetch_service_impl.h
@@ -31,7 +31,7 @@ std::unique_ptr<PrefetchImporter> prefetch_importer, std::unique_ptr<PrefetchBackgroundTaskHandler> background_task_handler, std::unique_ptr<ThumbnailFetcher> thumbnail_fetcher, - std::unique_ptr<image_fetcher::ImageFetcher> thumbnail_image_fetcher_); + image_fetcher::ImageFetcher* thumbnail_image_fetcher_); ~PrefetchServiceImpl() override; @@ -83,7 +83,8 @@ // Zine/Feed: only non-null when using Zine. std::unique_ptr<SuggestedArticlesObserver> suggested_articles_observer_; std::unique_ptr<ThumbnailFetcher> thumbnail_fetcher_; - std::unique_ptr<image_fetcher::ImageFetcher> thumbnail_image_fetcher_; + // Owned by CachedImageFetcherService. + image_fetcher::ImageFetcher* thumbnail_image_fetcher_; // Zine/Feed: only non-null when using Feed. SuggestionsProvider* suggestions_provider_ = nullptr;
diff --git a/components/offline_pages/core/prefetch/prefetch_service_test_taco.cc b/components/offline_pages/core/prefetch/prefetch_service_test_taco.cc index 80ed22e..02ed318 100644 --- a/components/offline_pages/core/prefetch/prefetch_service_test_taco.cc +++ b/components/offline_pages/core/prefetch/prefetch_service_test_taco.cc
@@ -201,7 +201,7 @@ std::move(suggested_articles_observer_), std::move(prefetch_downloader_), std::move(prefetch_importer_), std::move(prefetch_background_task_handler_), - std::move(thumbnail_fetcher_), std::move(thumbnail_image_fetcher_)); + std::move(thumbnail_fetcher_), thumbnail_image_fetcher_.get()); } std::unique_ptr<PrefetchService>
diff --git a/components/offline_pages/core/prefetch/thumbnail_fetch_by_url.cc b/components/offline_pages/core/prefetch/thumbnail_fetch_by_url.cc index 3874c27..db24254 100644 --- a/components/offline_pages/core/prefetch/thumbnail_fetch_by_url.cc +++ b/components/offline_pages/core/prefetch/thumbnail_fetch_by_url.cc
@@ -12,8 +12,9 @@ namespace offline_pages { namespace { -net::NetworkTrafficAnnotationTag TrafficAnnotation() { - return net::DefineNetworkTrafficAnnotation("prefetch_thumbnail", R"( + +constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation = + net::DefineNetworkTrafficAnnotation("prefetch_thumbnail", R"( semantics { sender: "Offline Pages Prefetch" description: @@ -38,7 +39,6 @@ } } })"); -} } // namespace @@ -52,9 +52,12 @@ const image_fetcher::RequestMetadata& request_metadata) { std::move(callback).Run(image_data); }; - fetcher->FetchImageData(/*id=*/std::string(), thumbnail_url, + + image_fetcher::ImageFetcherParams params(kTrafficAnnotation); + + fetcher->FetchImageData(thumbnail_url, base::BindOnce(forward_callback, std::move(callback)), - TrafficAnnotation()); + std::move(params)); } } // namespace offline_pages
diff --git a/components/omnibox/browser/autocomplete_match.cc b/components/omnibox/browser/autocomplete_match.cc index 226c160c..56be2da 100644 --- a/components/omnibox/browser/autocomplete_match.cc +++ b/components/omnibox/browser/autocomplete_match.cc
@@ -364,7 +364,7 @@ serialized_classifications += ','; serialized_classifications += base::NumberToString(classifications[i].offset) + ',' + - base::IntToString(classifications[i].style); + base::NumberToString(classifications[i].style); } return serialized_classifications; } @@ -684,7 +684,7 @@ void AutocompleteMatch::RecordAdditionalInfo(const std::string& property, int value) { - RecordAdditionalInfo(property, base::IntToString(value)); + RecordAdditionalInfo(property, base::NumberToString(value)); } void AutocompleteMatch::RecordAdditionalInfo(const std::string& property,
diff --git a/components/omnibox/browser/autocomplete_match_type.cc b/components/omnibox/browser/autocomplete_match_type.cc index 3dea006..05979020 100644 --- a/components/omnibox/browser/autocomplete_match_type.cc +++ b/components/omnibox/browser/autocomplete_match_type.cc
@@ -239,6 +239,6 @@ return result; // Don't add "n of m" positional info when button focused. return l10n_util::GetStringFUTF16(IDS_ACC_AUTOCOMPLETE_N_OF_M, result, - base::IntToString16(match_index + 1), - base::IntToString16(total_matches)); + base::NumberToString16(match_index + 1), + base::NumberToString16(total_matches)); }
diff --git a/components/omnibox/browser/autocomplete_provider_unittest.cc b/components/omnibox/browser/autocomplete_provider_unittest.cc index 67f22b4..4be9ef55 100644 --- a/components/omnibox/browser/autocomplete_provider_unittest.cc +++ b/components/omnibox/browser/autocomplete_provider_unittest.cc
@@ -177,7 +177,7 @@ for (int i = start_at; i < num; i++) { AutocompleteMatch match(this, relevance_ - i, false, type); - match.fill_into_edit = prefix_ + base::UTF8ToUTF16(base::IntToString(i)); + match.fill_into_edit = prefix_ + base::UTF8ToUTF16(base::NumberToString(i)); match.destination_url = GURL(base::UTF16ToUTF8(match.fill_into_edit)); match.allowed_to_be_default_match = true;
diff --git a/components/omnibox/browser/autocomplete_result_unittest.cc b/components/omnibox/browser/autocomplete_result_unittest.cc index 2c73f6c..a164f7c05 100644 --- a/components/omnibox/browser/autocomplete_result_unittest.cc +++ b/components/omnibox/browser/autocomplete_result_unittest.cc
@@ -166,7 +166,7 @@ const TestData& data, AutocompleteMatch* match) { match->provider = GetProvider(data.provider_id); - match->fill_into_edit = base::IntToString16(data.url_id); + match->fill_into_edit = base::NumberToString16(data.url_id); std::string url_id(1, data.url_id + 'a'); match->destination_url = GURL("http://" + url_id); match->relevance = data.relevance;
diff --git a/components/omnibox/browser/omnibox_field_trial.cc b/components/omnibox/browser/omnibox_field_trial.cc index 7a2f65a6..db2c4b8d 100644 --- a/components/omnibox/browser/omnibox_field_trial.cc +++ b/components/omnibox/browser/omnibox_field_trial.cc
@@ -749,7 +749,7 @@ std::string value_str(variations::GetVariationParamValue( kBundledExperimentFieldTrialName, std::string(kEmphasizeTitlesRule) + "_" + - base::IntToString(static_cast<int>(input.type())))); + base::NumberToString(static_cast<int>(input.type())))); if (value_str.empty()) { value_str = variations::GetVariationParamValue( kBundledExperimentFieldTrialName, @@ -945,7 +945,7 @@ return std::string(); } const std::string page_classification_str = - base::IntToString(static_cast<int>(page_classification)); + base::NumberToString(static_cast<int>(page_classification)); const std::string instant_extended = search::IsInstantExtendedAPIEnabled() ? "1" : "0"; // Look up rule in this exact context.
diff --git a/components/optimization_guide/test_hints_component_creator.cc b/components/optimization_guide/test_hints_component_creator.cc index b9641264..40c66b78 100644 --- a/components/optimization_guide/test_hints_component_creator.cc +++ b/components/optimization_guide/test_hints_component_creator.cc
@@ -156,7 +156,7 @@ optimization_guide::HintsComponentInfo TestHintsComponentCreator::WriteConfigToFileAndReturnHintsComponentInfo( const optimization_guide::proto::Configuration& config) { - std::string version_string = base::IntToString(next_component_version_++); + std::string version_string = base::NumberToString(next_component_version_++); base::FilePath file_path = GetFilePath(version_string); WriteConfigToFile(file_path, config); return optimization_guide::HintsComponentInfo(base::Version(version_string),
diff --git a/components/os_crypt/libsecret_util_linux.cc b/components/os_crypt/libsecret_util_linux.cc index 6288334..7587743 100644 --- a/components/os_crypt/libsecret_util_linux.cc +++ b/components/os_crypt/libsecret_util_linux.cc
@@ -191,5 +191,5 @@ void LibsecretAttributesBuilder::Append(const std::string& name, int64_t value) { - Append(name, base::Int64ToString(value)); + Append(name, base::NumberToString(value)); }
diff --git a/components/password_manager/core/browser/browser_save_password_progress_logger.cc b/components/password_manager/core/browser/browser_save_password_progress_logger.cc index 944a648..cc70f91f 100644 --- a/components/password_manager/core/browser/browser_save_password_progress_logger.cc +++ b/components/password_manager/core/browser/browser_save_password_progress_logger.cc
@@ -21,7 +21,6 @@ using autofill::AutofillUploadContents; using base::NumberToString; -using base::UintToString; namespace password_manager { @@ -154,7 +153,8 @@ ScrubNonDigit(field->FieldSignatureAsStr()) + ", type=" + ScrubElementID(field->form_control_type); - field_info += ", renderer_id = " + UintToString(field->unique_renderer_id); + field_info += + ", renderer_id = " + NumberToString(field->unique_renderer_id); if (!field->autocomplete_attribute.empty()) field_info += @@ -244,7 +244,7 @@ if (form.is_form_tag) { message += - "Form renderer id: " + UintToString(form.unique_renderer_id) + "\n"; + "Form renderer id: " + NumberToString(form.unique_renderer_id) + "\n"; } // Log fields. @@ -260,7 +260,7 @@ std::string field_info = ScrubElementID(field.name) + ": type=" + ScrubElementID(field.form_control_type) + - ", renderer_id = " + UintToString(field.unique_renderer_id) + ", " + + ", renderer_id = " + NumberToString(field.unique_renderer_id) + ", " + is_visible + ", " + is_empty + autocomplete + "\n"; message += field_info; }
diff --git a/components/password_manager/core/browser/form_parsing/form_parser_unittest.cc b/components/password_manager/core/browser/form_parsing/form_parser_unittest.cc index 7fcc6d6..1b0eaa1 100644 --- a/components/password_manager/core/browser/form_parsing/form_parser_unittest.cc +++ b/components/password_manager/core/browser/form_parsing/form_parser_unittest.cc
@@ -109,7 +109,7 @@ // Use to add a number suffix which is unique in the scope of the test. base::string16 StampUniqueSuffix(const char* base_str) { return ASCIIToUTF16(base_str) + ASCIIToUTF16("_") + - base::UintToString16(GetUniqueId()); + base::NumberToString16(GetUniqueId()); } // Describes which renderer IDs are expected for username/password fields
diff --git a/components/password_manager/core/browser/form_parsing/ios_form_parser_unittest.cc b/components/password_manager/core/browser/form_parsing/ios_form_parser_unittest.cc index 69c9001..f492f870 100644 --- a/components/password_manager/core/browser/form_parsing/ios_form_parser_unittest.cc +++ b/components/password_manager/core/browser/form_parsing/ios_form_parser_unittest.cc
@@ -19,7 +19,7 @@ using autofill::FormFieldData; using autofill::PasswordForm; using base::ASCIIToUTF16; -using base::UintToString16; +using base::NumberToString16; namespace password_manager { @@ -78,8 +78,8 @@ FormFieldData field; // An exact id is not important, set id such that different fields have // different id. - field.name_attribute = ASCIIToUTF16("field_name") + UintToString16(i); - field.id_attribute = ASCIIToUTF16("field_id") + UintToString16(i); + field.name_attribute = ASCIIToUTF16("field_name") + NumberToString16(i); + field.id_attribute = ASCIIToUTF16("field_id") + NumberToString16(i); // The fuzzing infrastructure doez not run on iOS, so the iOS specific parts of // PasswordForm are also built on fuzzer enabled platforms. @@ -98,7 +98,7 @@ } else if (!field_data.is_empty) { // An exact value is not important, set a value with simple pattern, such // that different fields have different values. - field.value = ASCIIToUTF16("field_value") + UintToString16(i); + field.value = ASCIIToUTF16("field_value") + NumberToString16(i); } if (field_data.autocomplete_attribute) field.autocomplete_attribute = field_data.autocomplete_attribute;
diff --git a/components/password_manager/core/browser/password_manager.cc b/components/password_manager/core/browser/password_manager.cc index 4b8562f..932d9a5 100644 --- a/components/password_manager/core/browser/password_manager.cc +++ b/components/password_manager/core/browser/password_manager.cc
@@ -479,7 +479,8 @@ return; } - bool should_block = ShouldBlockPasswordForSameOriginButDifferentScheme(form); + bool should_block = + ShouldBlockPasswordForSameOriginButDifferentScheme(form.origin); metrics_util::LogShouldBlockPasswordForSameOriginButDifferentScheme( should_block); if (should_block) { @@ -670,7 +671,8 @@ const PasswordForm& password_form) { if (!client_->GetPasswordStore()->IsAbleToSavePasswords() || !client_->IsSavingAndFillingEnabled(password_form.origin) || - ShouldBlockPasswordForSameOriginButDifferentScheme(password_form) || + ShouldBlockPasswordForSameOriginButDifferentScheme( + password_form.origin) || !client_->GetStoreResultFilter()->ShouldSave(password_form)) return; @@ -900,8 +902,17 @@ // PasswordToSave in NewPasswordFormManager DCHECKs that the password is never // empty. - // TODO(https://crbug.com/831123): Add the - // ShouldBlockPasswordForSameOriginButDifferentScheme check. + const GURL& origin = submitted_form.origin; + bool should_block = + ShouldBlockPasswordForSameOriginButDifferentScheme(origin); + metrics_util::LogShouldBlockPasswordForSameOriginButDifferentScheme( + should_block); + if (should_block) { + RecordProvisionalSaveFailure( + PasswordManagerMetricsRecorder::SAVING_ON_HTTP_AFTER_HTTPS, origin, + logger.get()); + return nullptr; + } NewPasswordFormManager* matched_manager = GetMatchedManager(driver, submitted_form); @@ -930,6 +941,11 @@ manager->set_not_submitted(); } + // Cache the user-visible URL (i.e., the one seen in the omnibox). Once the + // post-submit navigation concludes, we compare the landing URL against the + // cached and report the difference through UMA. + main_frame_url_ = client_->GetMainFrameURL(); + return matched_manager; } @@ -1006,12 +1022,10 @@ } bool PasswordManager::ShouldBlockPasswordForSameOriginButDifferentScheme( - const PasswordForm& form) const { + const GURL& origin) const { const GURL& old_origin = main_frame_url_.GetOrigin(); - const GURL& new_origin = form.origin.GetOrigin(); - return old_origin.host_piece() == new_origin.host_piece() && - old_origin.SchemeIsCryptographic() && - !new_origin.SchemeIsCryptographic(); + return old_origin.host_piece() == origin.host_piece() && + old_origin.SchemeIsCryptographic() && !origin.SchemeIsCryptographic(); } void PasswordManager::OnPasswordFormsRendered(
diff --git a/components/password_manager/core/browser/password_manager.h b/components/password_manager/core/browser/password_manager.h index e6a68ab..f04478a 100644 --- a/components/password_manager/core/browser/password_manager.h +++ b/components/password_manager/core/browser/password_manager.h
@@ -208,11 +208,11 @@ bool IsAutomaticSavePromptAvailable(); // Returns true if there already exists a provisionally saved password form - // from the same origin as |form|, but with a different and secure scheme. + // from the origin |origin|, but with a different and secure scheme. // This prevents a potential attack where users can be tricked into saving // unwanted credentials, see http://crbug.com/571580 for details. bool ShouldBlockPasswordForSameOriginButDifferentScheme( - const autofill::PasswordForm& form) const; + const GURL& origin) const; // Called when the login was deemed successful. It handles the special case // when the provisionally saved password is a sync credential, and otherwise
diff --git a/components/password_manager/core/browser/password_manager_unittest.cc b/components/password_manager/core/browser/password_manager_unittest.cc index bc1afc3..66061fe6 100644 --- a/components/password_manager/core/browser/password_manager_unittest.cc +++ b/components/password_manager/core/browser/password_manager_unittest.cc
@@ -1252,14 +1252,13 @@ false}, }; - PasswordForm form = MakeSimpleForm(); for (const auto& test_case : kTestData) { SCOPED_TRACE(testing::Message("#test_case = ") << (&test_case - kTestData)); manager()->main_frame_url_ = GURL(test_case.old_origin); - form.origin = GURL(test_case.new_origin); + GURL origin = GURL(test_case.new_origin); EXPECT_EQ( test_case.result, - manager()->ShouldBlockPasswordForSameOriginButDifferentScheme(form)); + manager()->ShouldBlockPasswordForSameOriginButDifferentScheme(origin)); } }
diff --git a/components/password_manager/core/browser/votes_uploader_unittest.cc b/components/password_manager/core/browser/votes_uploader_unittest.cc index e073296d..cbe12bf 100644 --- a/components/password_manager/core/browser/votes_uploader_unittest.cc +++ b/components/password_manager/core/browser/votes_uploader_unittest.cc
@@ -97,7 +97,7 @@ protected: base::string16 GetFieldNameByIndex(size_t index) { - return ASCIIToUTF16("field") + base::UintToString16(index); + return ASCIIToUTF16("field") + base::NumberToString16(index); } base::test::ScopedTaskEnvironment scoped_task_environment_;
diff --git a/components/password_manager/core/common/credential_manager_types.cc b/components/password_manager/core/common/credential_manager_types.cc index d9f9a74..f5fa75f 100644 --- a/components/password_manager/core/common/credential_manager_types.cc +++ b/components/password_manager/core/common/credential_manager_types.cc
@@ -20,7 +20,7 @@ return "CredentialType::CREDENTIAL_TYPE_FEDERATED"; } return "Unknown CredentialType value: " + - base::IntToString(static_cast<int>(value)); + base::NumberToString(static_cast<int>(value)); } std::ostream& operator<<(std::ostream& os, CredentialType value) {
diff --git a/components/policy/core/browser/configuration_policy_handler.cc b/components/policy/core/browser/configuration_policy_handler.cc index 1479a26..e0c3280 100644 --- a/components/policy/core/browser/configuration_policy_handler.cc +++ b/components/policy/core/browser/configuration_policy_handler.cc
@@ -178,9 +178,8 @@ if (value < min_ || value > max_) { if (errors) { - errors->AddError(policy_name(), - IDS_POLICY_OUT_OF_RANGE_ERROR, - base::IntToString(value)); + errors->AddError(policy_name(), IDS_POLICY_OUT_OF_RANGE_ERROR, + base::NumberToString(value)); } if (!clamp_)
diff --git a/components/policy/core/browser/policy_error_map.cc b/components/policy/core/browser/policy_error_map.cc index b0ea22d..9ab339c 100644 --- a/components/policy/core/browser/policy_error_map.cc +++ b/components/policy/core/browser/policy_error_map.cc
@@ -96,7 +96,7 @@ base::string16 GetMessage() const override { return l10n_util::GetStringFUTF16(IDS_POLICY_LIST_ENTRY_ERROR, - base::IntToString16(index_), + base::NumberToString16(index_), SimplePendingError::GetMessage()); }
diff --git a/components/policy/core/browser/proxy_policy_handler.cc b/components/policy/core/browser/proxy_policy_handler.cc index eab249ff..db4e18a 100644 --- a/components/policy/core/browser/proxy_policy_handler.cc +++ b/components/policy/core/browser/proxy_policy_handler.cc
@@ -319,10 +319,9 @@ *mode_value = ProxyPrefs::kSystemProxyModeName; break; default: - errors->AddError(key::kProxySettings, - key::kProxyServerMode, + errors->AddError(key::kProxySettings, key::kProxyServerMode, IDS_POLICY_OUT_OF_RANGE_ERROR, - base::IntToString(server_mode_value)); + base::NumberToString(server_mode_value)); return false; } }
diff --git a/components/policy/core/common/cloud/component_cloud_policy_updater.cc b/components/policy/core/common/cloud/component_cloud_policy_updater.cc index 8b0ee06..be51121a 100644 --- a/components/policy/core/common/cloud/component_cloud_policy_updater.cc +++ b/components/policy/core/common/cloud/component_cloud_policy_updater.cc
@@ -37,7 +37,7 @@ const int64_t kMaxParallelPolicyDataFetches = 2; std::string NamespaceToKey(const PolicyNamespace& ns) { - const std::string domain = base::IntToString(ns.domain); + const std::string domain = base::NumberToString(ns.domain); const std::string size = base::NumberToString(domain.size()); return size + ":" + domain + ":" + ns.component_id; }
diff --git a/components/policy/core/common/config_dir_policy_loader_unittest.cc b/components/policy/core/common/config_dir_policy_loader_unittest.cc index 1f3d434..d6b21a5 100644 --- a/components/policy/core/common/config_dir_policy_loader_unittest.cc +++ b/components/policy/core/common/config_dir_policy_loader_unittest.cc
@@ -155,7 +155,8 @@ std::string TestHarness::NextConfigFileName() { EXPECT_LE(next_policy_file_index_, 999); - return std::string("policy") + base::IntToString(next_policy_file_index_++); + return std::string("policy") + + base::NumberToString(next_policy_file_index_++); } // static @@ -224,12 +225,12 @@ const char kHomepageLocation[] = "HomepageLocation"; test_dict_bar.SetString(kHomepageLocation, "http://bar.com"); for (unsigned int i = 1; i <= 4; ++i) - harness_.WriteConfigFile(test_dict_bar, base::UintToString(i)); + harness_.WriteConfigFile(test_dict_bar, base::NumberToString(i)); base::DictionaryValue test_dict_foo; test_dict_foo.SetString(kHomepageLocation, "http://foo.com"); harness_.WriteConfigFile(test_dict_foo, "9"); for (unsigned int i = 5; i <= 8; ++i) - harness_.WriteConfigFile(test_dict_bar, base::UintToString(i)); + harness_.WriteConfigFile(test_dict_bar, base::NumberToString(i)); ConfigDirPolicyLoader loader( scoped_task_environment_.GetMainThreadTaskRunner(), harness_.test_dir(),
diff --git a/components/policy/core/common/plist_writer.cc b/components/policy/core/common/plist_writer.cc index 68c1db54..77b80026 100644 --- a/components/policy/core/common/plist_writer.cc +++ b/components/policy/core/common/plist_writer.cc
@@ -26,7 +26,7 @@ case base::Value::Type::INTEGER: { int value = node.GetInt(); - plist_writer.WriteElement("integer", base::IntToString(value)); + plist_writer.WriteElement("integer", base::NumberToString(value)); return true; }
diff --git a/components/policy/core/common/policy_loader_win_unittest.cc b/components/policy/core/common/policy_loader_win_unittest.cc index f2bbb23..41ae2526 100644 --- a/components/policy/core/common/policy_loader_win_unittest.cc +++ b/components/policy/core/common/policy_loader_win_unittest.cc
@@ -124,7 +124,7 @@ if (!list->Get(i, &item)) return false; if (!InstallValue(*item, hive, path + kPathSep + name, - base::UintToString16(i + 1))) { + base::NumberToString16(i + 1))) { return false; } } @@ -337,7 +337,7 @@ std::string element_value; if (!element->GetAsString(&element_value)) continue; - std::string name(base::IntToString(index++)); + std::string name(base::NumberToString(index++)); key.WriteValue(UTF8ToUTF16(name).c_str(), UTF8ToUTF16(element_value).c_str()); }
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index 52068e4..4aa3a19 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -14286,6 +14286,26 @@ This feature is a replacement for the <ph name="LEGACY_BROWSER_SUPPORT_EXTENSION_NAME">'Legacy Browser Support'</ph> extension. Configuration from the extension will carry over to this feature, but it is strongly advised to use the Chrome policies instead. This ensures better compatibility in the future.''', }, { + 'id': 519, + 'name': 'BrowserSwitcherKeepLastChromeTab', + 'future': True, + 'type': 'main', + 'schema': { 'type': 'boolean' }, + 'example_value': False, + 'features': { + 'dynamic_refresh': True, + 'per_profile': True, + }, + 'supported_on': ['chrome.*:74-'], + 'caption': '''Keep last tab open in Chrome.''', + 'tags': [], + 'desc': '''This policy controls whether to close Chrome completely when the last tab would switch to another browser. + + When this policy is left unset, or is set to true, Chrome will keep at least one tab open, after switching to an alternate browser. + + When this policy is set to false, Chrome will close the tab after switching to an alternate browser, even if it was the last tab. This will cause Chrome to exit completely.''', + }, + { 'name': 'DeviceDisplayResolution', 'type': 'dict', 'schema': { @@ -14688,5 +14708,5 @@ }, 'placeholders': [], 'deleted_policy_ids': [412], - 'highest_id_currently_used': 518 + 'highest_id_currently_used': 519 }
diff --git a/components/prefs/json_pref_store_unittest.cc b/components/prefs/json_pref_store_unittest.cc index d4e7870c..d3aa266 100644 --- a/components/prefs/json_pref_store_unittest.cc +++ b/components/prefs/json_pref_store_unittest.cc
@@ -285,7 +285,7 @@ pref_store->SetValue( kLongIntPref, - std::make_unique<Value>(base::Int64ToString(214748364842LL)), + std::make_unique<Value>(base::NumberToString(214748364842LL)), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); EXPECT_TRUE(pref_store->GetValue(kLongIntPref, &actual)); EXPECT_TRUE(actual->GetAsString(&string_value));
diff --git a/components/prefs/pref_registry_simple.cc b/components/prefs/pref_registry_simple.cc index 878f0ca..feb090f 100644 --- a/components/prefs/pref_registry_simple.cc +++ b/components/prefs/pref_registry_simple.cc
@@ -87,7 +87,7 @@ void PrefRegistrySimple::RegisterInt64Pref(const std::string& path, int64_t default_value, uint32_t flags) { - RegisterPreference(path, base::Value(base::Int64ToString(default_value)), + RegisterPreference(path, base::Value(base::NumberToString(default_value)), flags); }
diff --git a/components/prefs/pref_service.cc b/components/prefs/pref_service.cc index deb57106..f10814d 100644 --- a/components/prefs/pref_service.cc +++ b/components/prefs/pref_service.cc
@@ -491,7 +491,7 @@ void PrefService::SetInt64(const std::string& path, int64_t value) { SetUserPrefValue(path, - std::make_unique<base::Value>(base::Int64ToString(value))); + std::make_unique<base::Value>(base::NumberToString(value))); } int64_t PrefService::GetInt64(const std::string& path) const {
diff --git a/components/previews/content/previews_user_data.h b/components/previews/content/previews_user_data.h index decf74d1..0e6475a 100644 --- a/components/previews/content/previews_user_data.h +++ b/components/previews/content/previews_user_data.h
@@ -40,6 +40,9 @@ // The current state of the preview. ServerLitePageStatus status = ServerLitePageStatus::kUnknown; + + // The number of navigation restarts seen by this info instance. + size_t restart_count = 0; }; ~PreviewsUserData();
diff --git a/components/previews/core/previews_black_list_unittest.cc b/components/previews/core/previews_black_list_unittest.cc index 28265e4f..5db93c2a 100644 --- a/components/previews/core/previews_black_list_unittest.cc +++ b/components/previews/core/previews_black_list_unittest.cc
@@ -123,32 +123,32 @@ void SetHostThresholdParam(int per_host_threshold) { params_["per_host_opt_out_threshold"] = - base::IntToString(per_host_threshold); + base::NumberToString(per_host_threshold); } void SetHostIndifferentThresholdParam(int host_indifferent_threshold) { params_["host_indifferent_opt_out_threshold"] = - base::IntToString(host_indifferent_threshold); + base::NumberToString(host_indifferent_threshold); } void SetHostDurationParam(int duration_in_days) { params_["per_host_black_list_duration_in_days"] = - base::IntToString(duration_in_days); + base::NumberToString(duration_in_days); } void SetHostIndifferentDurationParam(int duration_in_days) { params_["host_indifferent_black_list_duration_in_days"] = - base::IntToString(duration_in_days); + base::NumberToString(duration_in_days); } void SetSingleOptOutDurationParam(int single_opt_out_duration) { params_["single_opt_out_duration_in_seconds"] = - base::IntToString(single_opt_out_duration); + base::NumberToString(single_opt_out_duration); } void SetMaxHostInBlackListParam(size_t max_hosts_in_blacklist) { params_["max_hosts_in_blacklist"] = - base::IntToString(max_hosts_in_blacklist); + base::NumberToString(max_hosts_in_blacklist); } protected:
diff --git a/components/previews/core/previews_experiments.cc b/components/previews/core/previews_experiments.cc index aa559ee..b31b9bf 100644 --- a/components/previews/core/previews_experiments.cc +++ b/components/previews/core/previews_experiments.cc
@@ -173,6 +173,11 @@ 250 * 1024 /* 250KB */); } +size_t LitePageRedirectPreviewMaxNavigationRestarts() { + return base::GetFieldTrialParamByFeatureAsInt( + features::kLitePageServerPreviews, "max_navigation_restart", 5); +} + int PreviewServerLoadshedMaxSeconds() { return base::GetFieldTrialParamByFeatureAsInt( features::kLitePageServerPreviews, "loadshed_max_seconds",
diff --git a/components/previews/core/previews_experiments.h b/components/previews/core/previews_experiments.h index aa0f675..406233b08 100644 --- a/components/previews/core/previews_experiments.h +++ b/components/previews/core/previews_experiments.h
@@ -116,6 +116,10 @@ // a blacklist. int LitePageRedirectPreviewMaxServerBlacklistByteSize(); +// The maximum number of times that a Lite Page Redirect preview should restart +// a navigation. +size_t LitePageRedirectPreviewMaxNavigationRestarts(); + // The maximum number of seconds to loadshed the Previews server for. int PreviewServerLoadshedMaxSeconds();
diff --git a/components/printing/common/cloud_print_cdd_conversion.cc b/components/printing/common/cloud_print_cdd_conversion.cc index 6c43195..2daeec3 100644 --- a/components/printing/common/cloud_print_cdd_conversion.cc +++ b/components/printing/common/cloud_print_cdd_conversion.cc
@@ -66,12 +66,13 @@ ColorCapability color; if (semantic_info.color_default || semantic_info.color_changeable) { Color standard_color(STANDARD_COLOR); - standard_color.vendor_id = base::IntToString(semantic_info.color_model); + standard_color.vendor_id = base::NumberToString(semantic_info.color_model); color.AddDefaultOption(standard_color, semantic_info.color_default); } if (!semantic_info.color_default || semantic_info.color_changeable) { Color standard_monochrome(STANDARD_MONOCHROME); - standard_monochrome.vendor_id = base::IntToString(semantic_info.bw_model); + standard_monochrome.vendor_id = + base::NumberToString(semantic_info.bw_model); color.AddDefaultOption(standard_monochrome, !semantic_info.color_default); } color.SaveTo(&description);
diff --git a/components/printing/renderer/BUILD.gn b/components/printing/renderer/BUILD.gn index abdfe5f..a3e925a1 100644 --- a/components/printing/renderer/BUILD.gn +++ b/components/printing/renderer/BUILD.gn
@@ -6,11 +6,17 @@ sources = [ "print_render_frame_helper.cc", "print_render_frame_helper.h", - "print_render_frame_helper_android.cc", "print_render_frame_helper_linux.cc", "print_render_frame_helper_mac.mm", ] + if (is_android) { + # Add back the Linux file which Android shares. + set_sources_assignment_filter([]) + sources += [ "print_render_frame_helper_linux.cc" ] + set_sources_assignment_filter(sources_assignment_filter) + } + deps = [ "//base", "//components/printing/common",
diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc index c25a685..56e2dd5 100644 --- a/components/printing/renderer/print_render_frame_helper.cc +++ b/components/printing/renderer/print_render_frame_helper.cc
@@ -37,7 +37,6 @@ #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "printing/buildflags/buildflags.h" #include "printing/metafile_skia.h" -#include "printing/metafile_skia_wrapper.h" #include "printing/units.h" #include "third_party/blink/public/common/frame/frame_owner_element_type.h" #include "third_party/blink/public/common/frame/sandbox_flags.h" @@ -1555,7 +1554,7 @@ metafile.GetVectorCanvasForNewPage(area_size, gfx::Rect(area_size), 1.0f); DCHECK(canvas); - MetafileSkiaWrapper::SetMetafileOnCanvas(canvas, &metafile); + canvas->SetPrintingMetafile(&metafile); // This subframe doesn't need to fit to the page size, thus we are not using // printing layout for it. It just prints with the specified size. @@ -2107,7 +2106,7 @@ if (!canvas) return; - MetafileSkiaWrapper::SetMetafileOnCanvas(canvas, metafile); + canvas->SetPrintingMetafile(metafile); if (params.display_header_footer) { #if defined(OS_WIN)
diff --git a/components/printing/renderer/print_render_frame_helper_android.cc b/components/printing/renderer/print_render_frame_helper_android.cc deleted file mode 100644 index 93c4382..0000000 --- a/components/printing/renderer/print_render_frame_helper_android.cc +++ /dev/null
@@ -1,7 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// All the necessary logic already lives in print_render_frame_helper_linux.cc. -// We need a separate file for Android due to build/filename_rules.gypi rules. -#include "components/printing/renderer/print_render_frame_helper_linux.cc"
diff --git a/components/printing/renderer/print_render_frame_helper_linux.cc b/components/printing/renderer/print_render_frame_helper_linux.cc index 9317bf9..e92009c 100644 --- a/components/printing/renderer/print_render_frame_helper_linux.cc +++ b/components/printing/renderer/print_render_frame_helper_linux.cc
@@ -12,7 +12,6 @@ #include "components/printing/common/print_messages.h" #include "printing/buildflags/buildflags.h" #include "printing/metafile_skia.h" -#include "printing/metafile_skia_wrapper.h" namespace printing {
diff --git a/components/printing/renderer/print_render_frame_helper_mac.mm b/components/printing/renderer/print_render_frame_helper_mac.mm index 6357237e..4471e2c 100644 --- a/components/printing/renderer/print_render_frame_helper_mac.mm +++ b/components/printing/renderer/print_render_frame_helper_mac.mm
@@ -15,7 +15,6 @@ #include "components/printing/common/print_messages.h" #include "printing/buildflags/buildflags.h" #include "printing/metafile_skia.h" -#include "printing/metafile_skia_wrapper.h" #include "printing/page_size_margins.h" #include "third_party/blink/public/web/web_local_frame.h" @@ -58,7 +57,7 @@ if (!canvas) return; - MetafileSkiaWrapper::SetMetafileOnCanvas(canvas, metafile); + canvas->SetPrintingMetafile(metafile); if (params.display_header_footer) { PrintHeaderAndFooter(canvas, page_number + 1, page_count, *frame, final_scale_factor, page_layout_in_points, params);
diff --git a/components/safe_browsing/triggers/ad_sampler_trigger_unittest.cc b/components/safe_browsing/triggers/ad_sampler_trigger_unittest.cc index ee718330..121c1c0 100644 --- a/components/safe_browsing/triggers/ad_sampler_trigger_unittest.cc +++ b/components/safe_browsing/triggers/ad_sampler_trigger_unittest.cc
@@ -238,7 +238,7 @@ std::map<std::string, std::string> feature_params; feature_params[std::string( safe_browsing::kAdSamplerFrequencyDenominatorParam)] = - base::IntToString(kDenominatorInt); + base::NumberToString(kDenominatorInt); base::AssociateFieldTrialParams(safe_browsing::kAdSamplerTriggerFeature.name, "Group", feature_params); std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);
diff --git a/components/safe_browsing/triggers/trigger_throttler.cc b/components/safe_browsing/triggers/trigger_throttler.cc index 49458e3..c80d3eab 100644 --- a/components/safe_browsing/triggers/trigger_throttler.cc +++ b/components/safe_browsing/triggers/trigger_throttler.cc
@@ -228,7 +228,7 @@ base::DictionaryValue trigger_dict; for (const auto& trigger_item : trigger_events_) { base::Value* pref_timestamps = trigger_dict.SetKey( - base::IntToString(static_cast<int>(trigger_item.first)), + base::NumberToString(static_cast<int>(trigger_item.first)), base::Value(base::Value::Type::LIST)); for (const base::Time timestamp : trigger_item.second) { pref_timestamps->GetList().push_back(base::Value(timestamp.ToDoubleT()));
diff --git a/components/search_engines/default_search_policy_handler.cc b/components/search_engines/default_search_policy_handler.cc index 9ff8e9e..e521899c 100644 --- a/components/search_engines/default_search_policy_handler.cc +++ b/components/search_engines/default_search_policy_handler.cc
@@ -173,7 +173,7 @@ // Set the fields which are not specified by the policy to default values. dict->SetString(DefaultSearchManager::kID, - base::Int64ToString(kInvalidTemplateURLID)); + base::NumberToString(kInvalidTemplateURLID)); dict->SetInteger(DefaultSearchManager::kPrepopulateID, 0); dict->SetString(DefaultSearchManager::kSyncGUID, std::string()); dict->SetString(DefaultSearchManager::kOriginatingURL, std::string());
diff --git a/components/search_engines/template_url.cc b/components/search_engines/template_url.cc index 159004b..0de7442 100644 --- a/components/search_engines/template_url.cc +++ b/components/search_engines/template_url.cc
@@ -1010,18 +1010,18 @@ case GOOGLE_INPUT_TYPE: DCHECK(!i->is_post_param); - HandleReplacement( - "oit", base::IntToString(search_terms_args.input_type), *i, &url); + HandleReplacement("oit", + base::NumberToString(search_terms_args.input_type), + *i, &url); break; case GOOGLE_CONTEXTUAL_SEARCH_VERSION: if (search_terms_args.contextual_search_params.version >= 0) { HandleReplacement( "ctxs", - base::IntToString( + base::NumberToString( search_terms_args.contextual_search_params.version), - *i, - &url); + *i, &url); } break; @@ -1034,17 +1034,17 @@ if (params.contextual_cards_version > 0) { args.push_back("ctxsl_coca=" + - base::IntToString(params.contextual_cards_version)); + base::NumberToString(params.contextual_cards_version)); } if (!params.home_country.empty()) args.push_back("ctxs_hc=" + params.home_country); if (params.previous_event_id != 0) { args.push_back("ctxsl_pid=" + - base::Int64ToString(params.previous_event_id)); + base::NumberToString(params.previous_event_id)); } if (params.previous_event_results != 0) { args.push_back("ctxsl_per=" + - base::IntToString(params.previous_event_results)); + base::NumberToString(params.previous_event_results)); } HandleReplacement(std::string(), base::JoinString(args, "&"), *i, &url); @@ -1064,8 +1064,9 @@ if (search_terms_args.page_classification != metrics::OmniboxEventProto::INVALID_SPEC) { HandleReplacement( - "pgcl", base::IntToString(search_terms_args.page_classification), - *i, &url); + "pgcl", + base::NumberToString(search_terms_args.page_classification), *i, + &url); } break; @@ -1165,19 +1166,19 @@ case GOOGLE_IMAGE_ORIGINAL_WIDTH: if (!search_terms_args.image_original_size.IsEmpty()) { - HandleReplacement( - std::string(), - base::IntToString(search_terms_args.image_original_size.width()), - *i, &url); + HandleReplacement(std::string(), + base::NumberToString( + search_terms_args.image_original_size.width()), + *i, &url); } break; case GOOGLE_IMAGE_ORIGINAL_HEIGHT: if (!search_terms_args.image_original_size.IsEmpty()) { - HandleReplacement( - std::string(), - base::IntToString(search_terms_args.image_original_size.height()), - *i, &url); + HandleReplacement(std::string(), + base::NumberToString( + search_terms_args.image_original_size.height()), + *i, &url); } break;
diff --git a/components/search_engines/template_url_data_util.cc b/components/search_engines/template_url_data_util.cc index 91bdafe7..b03157e 100644 --- a/components/search_engines/template_url_data_util.cc +++ b/components/search_engines/template_url_data_util.cc
@@ -114,7 +114,7 @@ std::unique_ptr<base::DictionaryValue> TemplateURLDataToDictionary( const TemplateURLData& data) { auto url_dict = std::make_unique<base::DictionaryValue>(); - url_dict->SetString(DefaultSearchManager::kID, base::Int64ToString(data.id)); + url_dict->SetString(DefaultSearchManager::kID, base::NumberToString(data.id)); url_dict->SetString(DefaultSearchManager::kShortName, data.short_name()); url_dict->SetString(DefaultSearchManager::kKeyword, data.keyword()); url_dict->SetInteger(DefaultSearchManager::kPrepopulateID, @@ -145,14 +145,15 @@ url_dict->SetBoolean(DefaultSearchManager::kSafeForAutoReplace, data.safe_for_autoreplace); - url_dict->SetString(DefaultSearchManager::kDateCreated, - base::Int64ToString(data.date_created.ToInternalValue())); + url_dict->SetString( + DefaultSearchManager::kDateCreated, + base::NumberToString(data.date_created.ToInternalValue())); url_dict->SetString( DefaultSearchManager::kLastModified, - base::Int64ToString(data.last_modified.ToInternalValue())); + base::NumberToString(data.last_modified.ToInternalValue())); url_dict->SetString( DefaultSearchManager::kLastVisited, - base::Int64ToString(data.last_visited.ToInternalValue())); + base::NumberToString(data.last_visited.ToInternalValue())); url_dict->SetInteger(DefaultSearchManager::kUsageCount, data.usage_count); auto alternate_urls = std::make_unique<base::ListValue>();
diff --git a/components/search_engines/template_url_unittest.cc b/components/search_engines/template_url_unittest.cc index 8a4efdf..4dc754e 100644 --- a/components/search_engines/template_url_unittest.cc +++ b/components/search_engines/template_url_unittest.cc
@@ -228,9 +228,9 @@ static_cast<size_t>(i - post_params.begin())) { switch (j->type) { case TemplateURLRef::GOOGLE_IMAGE_ORIGINAL_WIDTH: - ExpectPostParamIs(*i, "width", - base::IntToString( - search_args.image_original_size.width())); + ExpectPostParamIs( + *i, "width", + base::NumberToString(search_args.image_original_size.width())); break; case TemplateURLRef::GOOGLE_IMAGE_SEARCH_SOURCE: ExpectPostParamIs(*i, "sbisrc",
diff --git a/components/search_provider_logos/logo_cache.cc b/components/search_provider_logos/logo_cache.cc index f350805..4dbec533 100644 --- a/components/search_provider_logos/logo_cache.cc +++ b/components/search_provider_logos/logo_cache.cc
@@ -65,7 +65,7 @@ const std::string& key, const base::Time& time) { int64_t internal_time_value = time.ToInternalValue(); - dict.SetString(key, base::Int64ToString(internal_time_value)); + dict.SetString(key, base::NumberToString(internal_time_value)); } LogoType LogoTypeFromString(base::StringPiece type) {
diff --git a/components/services/heap_profiling/public/cpp/sampling_profiler_wrapper.cc b/components/services/heap_profiling/public/cpp/sampling_profiler_wrapper.cc index 05b88f1..fa9f376 100644 --- a/components/services/heap_profiling/public/cpp/sampling_profiler_wrapper.cc +++ b/components/services/heap_profiling/public/cpp/sampling_profiler_wrapper.cc
@@ -432,11 +432,13 @@ const void** CaptureStackTrace(const void** frames, size_t max_entries, size_t* count) { - // Skip 3 top frames related to the profiler itself, e.g.: - // base::debug::StackTrace::StackTrace + // Skip 5 top frames related to the profiler itself, e.g.: + // base::debug::CollectStackTrace + // heap_profiling::CaptureStackTrace // heap_profiling::RecordAndSendAlloc + // SamplingProfilerWrapper::SampleAdded // sampling_heap_profiler::PoissonAllocationSampler::DoRecordAlloc - size_t skip_frames = 3; + size_t skip_frames = 5; #if defined(OS_ANDROID) && BUILDFLAG(CAN_UNWIND_WITH_CFI_TABLE) && \ defined(OFFICIAL_BUILD) size_t frame_count = @@ -449,7 +451,6 @@ #else // Fall-back to capturing the stack with base::debug::CollectStackTrace, // which is likely slower, but more reliable. - // TODO(alph): Make CollectStackTrace accept const void** pointer. size_t frame_count = base::debug::CollectStackTrace(const_cast<void**>(frames), max_entries); #endif @@ -610,13 +611,8 @@ } // namespace -SamplingProfilerWrapper::SamplingProfilerWrapper() { - base::PoissonAllocationSampler::Get()->AddSamplesObserver(this); -} - -SamplingProfilerWrapper::~SamplingProfilerWrapper() { - base::PoissonAllocationSampler::Get()->RemoveSamplesObserver(this); -} +SamplingProfilerWrapper::SamplingProfilerWrapper() = default; +SamplingProfilerWrapper::~SamplingProfilerWrapper() = default; SamplingProfilerWrapper::Sample::Sample() = default; SamplingProfilerWrapper::Sample::Sample(Sample&&) = default; @@ -629,12 +625,12 @@ InitAllocationRecorder(sender_pipe, std::move(params)); auto* sampler = base::PoissonAllocationSampler::Get(); sampler->SetSamplingInterval(sampling_rate); - sampler->Start(); + sampler->AddSamplesObserver(this); AllocatorHooksHaveBeenInitialized(); } void SamplingProfilerWrapper::StopProfiling() { - base::PoissonAllocationSampler::Get()->Stop(); + base::PoissonAllocationSampler::Get()->RemoveSamplesObserver(this); } mojom::HeapProfilePtr SamplingProfilerWrapper::RetrieveHeapProfile() {
diff --git a/components/signin/core/browser/BUILD.gn b/components/signin/core/browser/BUILD.gn index 8bd17392..ac645cd1 100644 --- a/components/signin/core/browser/BUILD.gn +++ b/components/signin/core/browser/BUILD.gn
@@ -296,6 +296,7 @@ "//services/identity/public/cpp:test_support", "//testing/gmock", "//testing/gtest", + "//ui/gfx:test_support", ] if (is_chromeos) {
diff --git a/components/signin/core/browser/account_fetcher_service.cc b/components/signin/core/browser/account_fetcher_service.cc index 8028f9f6..f0ce7e3 100644 --- a/components/signin/core/browser/account_fetcher_service.cc +++ b/components/signin/core/browser/account_fetcher_service.cc
@@ -303,9 +303,9 @@ GURL image_url_with_size(signin::GetAvatarImageURLWithOptions( picture_url, kAccountImageDownloadSize, true /* no_silhouette */)); auto callback = base::BindRepeating(&AccountFetcherService::OnImageFetched, - base::Unretained(this)); - GetOrCreateImageFetcher()->FetchImage(account_id, image_url_with_size, - callback, traffic_annotation); + base::Unretained(this), account_id); + GetOrCreateImageFetcher()->FetchImage(image_url_with_size, callback, + traffic_annotation); } void AccountFetcherService::OnUserInfoFetchFailure(
diff --git a/components/signin/core/browser/account_info.h b/components/signin/core/browser/account_info.h index df99283..c98529c 100644 --- a/components/signin/core/browser/account_info.h +++ b/components/signin/core/browser/account_info.h
@@ -32,6 +32,8 @@ std::string account_id; std::string gaia; std::string email; + + bool is_under_advanced_protection = false; }; // Stores all the information known about an account. Part of the information @@ -53,7 +55,6 @@ std::string picture_url; gfx::Image account_image; bool is_child_account = false; - bool is_under_advanced_protection = false; // Returns true if all fields in the account info are empty. bool IsEmpty() const;
diff --git a/components/signin/core/browser/account_investigator.cc b/components/signin/core/browser/account_investigator.cc index 239b3723..f30d933 100644 --- a/components/signin/core/browser/account_investigator.cc +++ b/components/signin/core/browser/account_investigator.cc
@@ -84,21 +84,17 @@ void AccountInvestigator::OnAccountsInCookieUpdated( const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) { - OnGaiaAccountsInCookieUpdated(accounts_in_cookie_jar_info.signed_in_accounts, - accounts_in_cookie_jar_info.signed_out_accounts, - error); -} - -void AccountInvestigator::OnGaiaAccountsInCookieUpdated( - const std::vector<ListedAccount>& signed_in_accounts, - const std::vector<ListedAccount>& signed_out_accounts, - const GoogleServiceAuthError& error) { if (error != GoogleServiceAuthError::AuthErrorNone()) { // If we are pending periodic reporting, leave the flag set, and we will // continue next time the ListAccounts call succeeds. return; } + const std::vector<ListedAccount>& signed_in_accounts( + accounts_in_cookie_jar_info.signed_in_accounts); + const std::vector<ListedAccount>& signed_out_accounts( + accounts_in_cookie_jar_info.signed_out_accounts); + // Handling this is tricky. We could be here because there was a change. We // could be here because we tried to do periodic reporting but there wasn't // a valid cached ListAccounts response ready for us. Or even both of these
diff --git a/components/signin/core/browser/account_investigator.h b/components/signin/core/browser/account_investigator.h index dd6b666..ce7eabdb 100644 --- a/components/signin/core/browser/account_investigator.h +++ b/components/signin/core/browser/account_investigator.h
@@ -62,13 +62,6 @@ const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override; - // Internal implementation of OnAccountsInCookieUpdated. It is public given - // that it is called directly by unittests. - void OnGaiaAccountsInCookieUpdated( - const std::vector<gaia::ListedAccount>& signed_in_accounts, - const std::vector<gaia::ListedAccount>& signed_out_accounts, - const GoogleServiceAuthError& error); - private: friend class AccountInvestigatorTest;
diff --git a/components/signin/core/browser/account_investigator_unittest.cc b/components/signin/core/browser/account_investigator_unittest.cc index a08ba06..e64045d 100644 --- a/components/signin/core/browser/account_investigator_unittest.cc +++ b/components/signin/core/browser/account_investigator_unittest.cc
@@ -263,30 +263,37 @@ TEST_F(AccountInvestigatorTest, OnGaiaAccountsInCookieUpdatedError) { const HistogramTester histogram_tester; + identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = { + /*accounts_are_fresh=*/true, just_one, no_accounts}; GoogleServiceAuthError error(GoogleServiceAuthError::SERVICE_UNAVAILABLE); - investigator()->OnGaiaAccountsInCookieUpdated(just_one, no_accounts, error); + investigator()->OnAccountsInCookieUpdated(accounts_in_cookie_jar_info, error); EXPECT_EQ(0u, histogram_tester.GetTotalCountsForPrefix("Signin.").size()); } TEST_F(AccountInvestigatorTest, OnGaiaAccountsInCookieUpdatedOnChange) { const HistogramTester histogram_tester; - investigator()->OnGaiaAccountsInCookieUpdated( - just_one, no_accounts, GoogleServiceAuthError::AuthErrorNone()); + identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = { + /*accounts_are_fresh=*/true, just_one, no_accounts}; + investigator()->OnAccountsInCookieUpdated( + accounts_in_cookie_jar_info, GoogleServiceAuthError::AuthErrorNone()); ExpectSharedReportHistograms(ReportingType::ON_CHANGE, histogram_tester, nullptr, 1, 0, 1, nullptr, false); } TEST_F(AccountInvestigatorTest, OnGaiaAccountsInCookieUpdatedSigninOnly) { // Initial update to simulate the update on first-time-run. - investigator()->OnGaiaAccountsInCookieUpdated( - no_accounts, no_accounts, GoogleServiceAuthError::AuthErrorNone()); + investigator()->OnAccountsInCookieUpdated( + identity::AccountsInCookieJarInfo(), + GoogleServiceAuthError::AuthErrorNone()); const HistogramTester histogram_tester; identity_test_env()->SetPrimaryAccount("1@mail.com"); pref_service()->SetString(prefs::kGaiaCookieHash, Hash(just_one, no_accounts)); - investigator()->OnGaiaAccountsInCookieUpdated( - just_one, no_accounts, GoogleServiceAuthError::AuthErrorNone()); + identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = { + /*accounts_are_fresh=*/true, just_one, no_accounts}; + investigator()->OnAccountsInCookieUpdated( + accounts_in_cookie_jar_info, GoogleServiceAuthError::AuthErrorNone()); EXPECT_EQ(1u, histogram_tester.GetTotalCountsForPrefix("Signin.").size()); ExpectRelationReport(ReportingType::ON_CHANGE, histogram_tester, AccountRelation::SINGLE_SIGNED_IN_MATCH_NO_SIGNED_OUT); @@ -296,15 +303,19 @@ OnGaiaAccountsInCookieUpdatedSigninSignOutOfContent) { const HistogramTester histogram_tester; identity_test_env()->SetPrimaryAccount("1@mail.com"); - investigator()->OnGaiaAccountsInCookieUpdated( - just_one, no_accounts, GoogleServiceAuthError::AuthErrorNone()); + identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = { + /*accounts_are_fresh=*/true, just_one, no_accounts}; + investigator()->OnAccountsInCookieUpdated( + accounts_in_cookie_jar_info, GoogleServiceAuthError::AuthErrorNone()); ExpectRelationReport(ReportingType::ON_CHANGE, histogram_tester, AccountRelation::SINGLE_SIGNED_IN_MATCH_NO_SIGNED_OUT); // Simulate a sign out of the content area. const HistogramTester histogram_tester2; - investigator()->OnGaiaAccountsInCookieUpdated( - no_accounts, just_one, GoogleServiceAuthError::AuthErrorNone()); + accounts_in_cookie_jar_info = {/*accounts_are_fresh=*/true, no_accounts, + just_one}; + investigator()->OnAccountsInCookieUpdated( + accounts_in_cookie_jar_info, GoogleServiceAuthError::AuthErrorNone()); const AccountRelation expected_relation = AccountRelation::NO_SIGNED_IN_SINGLE_SIGNED_OUT_MATCH; ExpectSharedReportHistograms(ReportingType::ON_CHANGE, histogram_tester2,
diff --git a/components/signin/core/browser/account_reconcilor_unittest.cc b/components/signin/core/browser/account_reconcilor_unittest.cc index 2f8fc120..120c99b83 100644 --- a/components/signin/core/browser/account_reconcilor_unittest.cc +++ b/components/signin/core/browser/account_reconcilor_unittest.cc
@@ -263,9 +263,6 @@ } DiceTestSigninClient* test_signin_client() { return &test_signin_client_; } AccountTrackerService* account_tracker() { return &account_tracker_; } - GaiaCookieManagerService* cookie_manager_service() { - return &cookie_manager_service_; - } base::HistogramTester* histogram_tester() { return &histogram_tester_; } MockAccountReconcilor* GetMockReconcilor(); @@ -671,7 +668,7 @@ } signin::SetListAccountsResponseWithParams(cookie_params, &test_url_loader_factory_); - cookie_manager_service()->set_list_accounts_stale_for_testing(true); + identity_test_env()->SetFreshnessOfAccountsInGaiaCookie(true); } std::string GaiaIdForAccountKey(char account_key) { @@ -971,7 +968,7 @@ ConfigureCookieManagerService(cookies); // Call list accounts now so that the next call completes synchronously. - cookie_manager_service()->ListAccounts(nullptr, nullptr); + identity_test_env()->identity_manager()->GetAccountsInCookieJar(); base::RunLoop().RunUntilIdle(); // Setup expectations. @@ -1091,7 +1088,7 @@ std::vector<Cookie> cookies_after_reconcile = cookies; // Call list accounts now so that the next call completes synchronously. - cookie_manager_service()->ListAccounts(nullptr, nullptr); + identity_test_env()->identity_manager()->GetAccountsInCookieJar(); base::RunLoop().RunUntilIdle(); // Setup expectations. @@ -1332,7 +1329,7 @@ // Delete the cookies. signin::SetListAccountsResponseNoAccounts(&test_url_loader_factory_); - cookie_manager_service()->set_list_accounts_stale_for_testing(true); + identity_test_env()->SetFreshnessOfAccountsInGaiaCookie(true); if (!IsMultiloginEnabled()) { // Reconcile again and check that account_id_2 is added first. @@ -1791,7 +1788,7 @@ ConfigureCookieManagerService(cookies); // Call list accounts now so that the next call completes synchronously. - cookie_manager_service()->ListAccounts(nullptr, nullptr); + identity_test_env()->identity_manager()->GetAccountsInCookieJar(); base::RunLoop().RunUntilIdle(); // Setup expectations. @@ -1919,13 +1916,12 @@ base::RunLoop().RunUntilIdle(); ASSERT_EQ(signin_metrics::ACCOUNT_RECONCILOR_RUNNING, reconcilor->GetState()); - std::vector<gaia::ListedAccount> accounts; - std::vector<gaia::ListedAccount> signed_out_accounts; - ASSERT_TRUE( - cookie_manager_service()->ListAccounts(&accounts, &signed_out_accounts)); - ASSERT_EQ(1u, accounts.size()); - ASSERT_EQ(account_id, accounts[0].id); - ASSERT_EQ(0u, signed_out_accounts.size()); + identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = + identity_test_env()->identity_manager()->GetAccountsInCookieJar(); + ASSERT_TRUE(accounts_in_cookie_jar_info.accounts_are_fresh); + ASSERT_EQ(1u, accounts_in_cookie_jar_info.signed_in_accounts.size()); + ASSERT_EQ(account_id, accounts_in_cookie_jar_info.signed_in_accounts[0].id); + ASSERT_EQ(0u, accounts_in_cookie_jar_info.signed_out_accounts.size()); } TEST_P(AccountReconcilorMirrorEndpointParamTest, GetAccountsFromCookieFailure) { @@ -1940,12 +1936,11 @@ ASSERT_EQ(signin_metrics::ACCOUNT_RECONCILOR_RUNNING, reconcilor->GetState()); base::RunLoop().RunUntilIdle(); - std::vector<gaia::ListedAccount> accounts; - std::vector<gaia::ListedAccount> signed_out_accounts; - ASSERT_FALSE( - cookie_manager_service()->ListAccounts(&accounts, &signed_out_accounts)); - ASSERT_EQ(0u, accounts.size()); - ASSERT_EQ(0u, signed_out_accounts.size()); + identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = + identity_test_env()->identity_manager()->GetAccountsInCookieJar(); + ASSERT_FALSE(accounts_in_cookie_jar_info.accounts_are_fresh); + ASSERT_EQ(0u, accounts_in_cookie_jar_info.signed_in_accounts.size()); + ASSERT_EQ(0u, accounts_in_cookie_jar_info.signed_out_accounts.size()); base::RunLoop().RunUntilIdle(); ASSERT_EQ(signin_metrics::ACCOUNT_RECONCILOR_ERROR, reconcilor->GetState()); @@ -2041,7 +2036,9 @@ base::RunLoop().RunUntilIdle(); std::vector<gaia::ListedAccount> accounts; // This will be the first call to ListAccounts. - ASSERT_FALSE(cookie_manager_service()->ListAccounts(&accounts, nullptr)); + identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = + identity_test_env()->identity_manager()->GetAccountsInCookieJar(); + ASSERT_FALSE(accounts_in_cookie_jar_info.accounts_are_fresh); ASSERT_FALSE(reconcilor->is_reconcile_started_); } @@ -2440,7 +2437,7 @@ signin::SetListAccountsResponseTwoAccounts( account_info.email, account_info.gaia, account_info2.email, account_info2.gaia, &test_url_loader_factory_); - cookie_manager_service()->set_list_accounts_stale_for_testing(true); + identity_test_env()->SetFreshnessOfAccountsInGaiaCookie(true); // This will cause the reconcilor to fire. identity_test_env()->SetRefreshTokenForAccount(account_id3);
diff --git a/components/signin/core/browser/chrome_connected_header_helper.cc b/components/signin/core/browser/chrome_connected_header_helper.cc index d31cd38..d7b025d 100644 --- a/components/signin/core/browser/chrome_connected_header_helper.cc +++ b/components/signin/core/browser/chrome_connected_header_helper.cc
@@ -188,7 +188,7 @@ } parts.push_back( base::StringPrintf("%s=%s", kProfileModeAttrName, - base::IntToString(profile_mode_mask).c_str())); + base::NumberToString(profile_mode_mask).c_str())); bool is_mirror_enabled = account_consistency_ == AccountConsistencyMethod::kMirror; parts.push_back(base::StringPrintf("%s=%s", kEnableAccountConsistencyAttrName,
diff --git a/components/signin/core/browser/signin_manager_base.cc b/components/signin/core/browser/signin_manager_base.cc index 6012474..4eaecf6 100644 --- a/components/signin/core/browser/signin_manager_base.cc +++ b/components/signin/core/browser/signin_manager_base.cc
@@ -51,8 +51,7 @@ registry->RegisterStringPref(prefs::kGoogleServicesUserAccountId, std::string()); registry->RegisterBooleanPref(prefs::kAutologinEnabled, true); - registry->RegisterListPref(prefs::kReverseAutologinRejectedEmailList, - std::make_unique<base::ListValue>()); + registry->RegisterListPref(prefs::kReverseAutologinRejectedEmailList); registry->RegisterBooleanPref(prefs::kSigninAllowed, true); registry->RegisterInt64Pref(prefs::kSignedInTime, base::Time().ToInternalValue());
diff --git a/components/spellcheck/renderer/spellcheck_unittest.cc b/components/spellcheck/renderer/spellcheck_unittest.cc index 947ef73..12866ada 100644 --- a/components/spellcheck/renderer/spellcheck_unittest.cc +++ b/components/spellcheck/renderer/spellcheck_unittest.cc
@@ -1505,13 +1505,14 @@ suggestions_list.resize(1); for (int i = 0; i < spellcheck::kMaxSuggestions + 2; ++i) - suggestions_list[0].push_back(base::ASCIIToUTF16(base::IntToString(i))); + suggestions_list[0].push_back(base::ASCIIToUTF16(base::NumberToString(i))); FillSuggestions(suggestions_list, &suggestion_results); ASSERT_EQ(static_cast<size_t>(spellcheck::kMaxSuggestions), suggestion_results.size()); for (int i = 0; i < spellcheck::kMaxSuggestions; ++i) - EXPECT_EQ(base::ASCIIToUTF16(base::IntToString(i)), suggestion_results[i]); + EXPECT_EQ(base::ASCIIToUTF16(base::NumberToString(i)), + suggestion_results[i]); } TEST_F(SpellCheckTest, FillSuggestions_RemoveDuplicates) { @@ -1538,7 +1539,7 @@ suggestions_list.resize(2); for (size_t i = 0; i < 2; ++i) { - std::string prefix = base::IntToString(i); + std::string prefix = base::NumberToString(i); suggestions_list[i].push_back(base::ASCIIToUTF16(prefix + "foo")); suggestions_list[i].push_back(base::ASCIIToUTF16(prefix + "bar")); suggestions_list[i].push_back(base::ASCIIToUTF16(prefix + "baz")); @@ -1562,7 +1563,7 @@ suggestions_list.resize(3); for (size_t i = 0; i < 3; ++i) { - std::string prefix = base::IntToString(i); + std::string prefix = base::NumberToString(i); suggestions_list[i].push_back(base::ASCIIToUTF16(prefix + "foo")); suggestions_list[i].push_back(base::ASCIIToUTF16(prefix + "bar")); suggestions_list[i].push_back(base::ASCIIToUTF16(prefix + "baz"));
diff --git a/components/startup_metric_utils/browser/startup_metric_utils.cc b/components/startup_metric_utils/browser/startup_metric_utils.cc index 8125f38..1019e80 100644 --- a/components/startup_metric_utils/browser/startup_metric_utils.cc +++ b/components/startup_metric_utils/browser/startup_metric_utils.cc
@@ -293,7 +293,8 @@ DCHECK_GE(g_startups_with_current_version, 1); if (g_startups_with_current_version > kMaxSameVersionCountRecorded) return ".Over"; - return std::string(".") + base::IntToString(g_startups_with_current_version); + return std::string(".") + + base::NumberToString(g_startups_with_current_version); } // Returns the system uptime on process launch.
diff --git a/components/storage_monitor/storage_info_utils.cc b/components/storage_monitor/storage_info_utils.cc index 0f94ea5..601abe38 100644 --- a/components/storage_monitor/storage_info_utils.cc +++ b/components/storage_monitor/storage_info_utils.cc
@@ -58,8 +58,8 @@ // Some devices have multiple data stores. Therefore, include storage id as // part of unique id along with vendor, model and volume information. - const std::string vendor_id = base::UintToString(storage_info.vendor_id); - const std::string model_id = base::UintToString(storage_info.product_id); + const std::string vendor_id = base::NumberToString(storage_info.vendor_id); + const std::string model_id = base::NumberToString(storage_info.product_id); return StorageInfo::MakeDeviceId( StorageInfo::MTP_OR_PTP, kVendorModelVolumeStoragePrefix + vendor_id + ":" + model_id + ":" +
diff --git a/components/strings/BUILD.gn b/components/strings/BUILD.gn index ffdbb787..0317fd69 100644 --- a/components/strings/BUILD.gn +++ b/components/strings/BUILD.gn
@@ -13,17 +13,20 @@ "java/res/values-am/components_strings.xml", "java/res/values-ar/components_strings.xml", "java/res/values-bg/components_strings.xml", + "java/res/values-bn/components_strings.xml", "java/res/values-ca/components_strings.xml", "java/res/values-cs/components_strings.xml", "java/res/values-da/components_strings.xml", "java/res/values-de/components_strings.xml", "java/res/values-el/components_strings.xml", "java/res/values-en-rGB/components_strings.xml", - "java/res/values-es-rUS/components_strings.xml", "java/res/values-es/components_strings.xml", + "java/res/values-es-rUS/components_strings.xml", + "java/res/values-et/components_strings.xml", "java/res/values-fa/components_strings.xml", "java/res/values-fi/components_strings.xml", "java/res/values-fr/components_strings.xml", + "java/res/values-gu/components_strings.xml", "java/res/values-hi/components_strings.xml", "java/res/values-hr/components_strings.xml", "java/res/values-hu/components_strings.xml", @@ -31,9 +34,13 @@ "java/res/values-it/components_strings.xml", "java/res/values-iw/components_strings.xml", "java/res/values-ja/components_strings.xml", + "java/res/values-kn/components_strings.xml", "java/res/values-ko/components_strings.xml", "java/res/values-lt/components_strings.xml", "java/res/values-lv/components_strings.xml", + "java/res/values-ml/components_strings.xml", + "java/res/values-mr/components_strings.xml", + "java/res/values-ms/components_strings.xml", "java/res/values-nb/components_strings.xml", "java/res/values-nl/components_strings.xml", "java/res/values-pl/components_strings.xml", @@ -46,6 +53,8 @@ "java/res/values-sr/components_strings.xml", "java/res/values-sv/components_strings.xml", "java/res/values-sw/components_strings.xml", + "java/res/values-ta/components_strings.xml", + "java/res/values-te/components_strings.xml", "java/res/values-th/components_strings.xml", "java/res/values-tl/components_strings.xml", "java/res/values-tr/components_strings.xml", @@ -121,17 +130,20 @@ "java/res/values-am/components_locale_settings.xml", "java/res/values-ar/components_locale_settings.xml", "java/res/values-bg/components_locale_settings.xml", + "java/res/values-bn/components_locale_settings.xml", "java/res/values-ca/components_locale_settings.xml", "java/res/values-cs/components_locale_settings.xml", "java/res/values-da/components_locale_settings.xml", "java/res/values-de/components_locale_settings.xml", "java/res/values-el/components_locale_settings.xml", "java/res/values-en-rGB/components_locale_settings.xml", - "java/res/values-es-rUS/components_locale_settings.xml", "java/res/values-es/components_locale_settings.xml", + "java/res/values-es-rUS/components_locale_settings.xml", + "java/res/values-et/components_locale_settings.xml", "java/res/values-fa/components_locale_settings.xml", "java/res/values-fi/components_locale_settings.xml", "java/res/values-fr/components_locale_settings.xml", + "java/res/values-gu/components_locale_settings.xml", "java/res/values-hi/components_locale_settings.xml", "java/res/values-hr/components_locale_settings.xml", "java/res/values-hu/components_locale_settings.xml", @@ -139,9 +151,13 @@ "java/res/values-it/components_locale_settings.xml", "java/res/values-iw/components_locale_settings.xml", "java/res/values-ja/components_locale_settings.xml", + "java/res/values-kn/components_locale_settings.xml", "java/res/values-ko/components_locale_settings.xml", "java/res/values-lt/components_locale_settings.xml", "java/res/values-lv/components_locale_settings.xml", + "java/res/values-ml/components_locale_settings.xml", + "java/res/values-mr/components_locale_settings.xml", + "java/res/values-ms/components_locale_settings.xml", "java/res/values-nb/components_locale_settings.xml", "java/res/values-nl/components_locale_settings.xml", "java/res/values-pl/components_locale_settings.xml", @@ -154,6 +170,8 @@ "java/res/values-sr/components_locale_settings.xml", "java/res/values-sv/components_locale_settings.xml", "java/res/values-sw/components_locale_settings.xml", + "java/res/values-ta/components_locale_settings.xml", + "java/res/values-te/components_locale_settings.xml", "java/res/values-th/components_locale_settings.xml", "java/res/values-tl/components_locale_settings.xml", "java/res/values-tr/components_locale_settings.xml",
diff --git a/components/subresource_filter/content/browser/ruleset_service.cc b/components/subresource_filter/content/browser/ruleset_service.cc index 2be68ab..4e4e410e 100644 --- a/components/subresource_filter/content/browser/ruleset_service.cc +++ b/components/subresource_filter/content/browser/ruleset_service.cc
@@ -92,7 +92,7 @@ base::FilePath IndexedRulesetLocator::GetSubdirectoryPathForVersion( const base::FilePath& base_dir, const IndexedRulesetVersion& version) { - return base_dir.AppendASCII(base::IntToString(version.format_version)) + return base_dir.AppendASCII(base::NumberToString(version.format_version)) .AppendASCII(version.content_version); } @@ -119,7 +119,7 @@ const base::FilePath& indexed_ruleset_base_dir, const IndexedRulesetVersion& most_recent_version) { base::FilePath current_format_dir(indexed_ruleset_base_dir.AppendASCII( - base::IntToString(IndexedRulesetVersion::CurrentFormatVersion()))); + base::NumberToString(IndexedRulesetVersion::CurrentFormatVersion()))); // First delete all directories containing rulesets of obsolete formats. base::FileEnumerator format_dirs(indexed_ruleset_base_dir,
diff --git a/components/subresource_filter/content/browser/ruleset_service_unittest.cc b/components/subresource_filter/content/browser/ruleset_service_unittest.cc index 47a7bfe..1d4a284 100644 --- a/components/subresource_filter/content/browser/ruleset_service_unittest.cc +++ b/components/subresource_filter/content/browser/ruleset_service_unittest.cc
@@ -444,7 +444,7 @@ EXPECT_TRUE(base_dir().IsParent(version_dir)); EXPECT_PRED_FORMAT2(::testing::IsSubstring, - base::IntToString(indexed_version.format_version), + base::NumberToString(indexed_version.format_version), version_dir.MaybeAsASCII()); EXPECT_PRED_FORMAT2(::testing::IsSubstring, indexed_version.content_version, version_dir.MaybeAsASCII());
diff --git a/components/subresource_filter/core/common/first_party_origin_unittest.cc b/components/subresource_filter/core/common/first_party_origin_unittest.cc index 68e271e..9f4a591 100644 --- a/components/subresource_filter/core/common/first_party_origin_unittest.cc +++ b/components/subresource_filter/core/common/first_party_origin_unittest.cc
@@ -14,7 +14,7 @@ FirstPartyOrigin first_party(url::Origin::Create(GURL("https://" + kDomain))); for (int index = 0; index < 5; ++index) { - GURL url("https://" + kDomain + "/path?q=" + base::IntToString(index)); + GURL url("https://" + kDomain + "/path?q=" + base::NumberToString(index)); EXPECT_FALSE(FirstPartyOrigin::IsThirdParty(url, first_party.origin())); EXPECT_FALSE(first_party.IsThirdParty(url)); } @@ -25,7 +25,8 @@ FirstPartyOrigin first_party(url::Origin::Create(GURL("https://" + kDomain))); for (int index = 0; index < 5; ++index) { - GURL url("https://sub" + base::IntToString(index) + "." + kDomain + "/suf"); + GURL url("https://sub" + base::NumberToString(index) + "." + kDomain + + "/suf"); EXPECT_FALSE(FirstPartyOrigin::IsThirdParty(url, first_party.origin())); EXPECT_FALSE(first_party.IsThirdParty(url)); } @@ -36,7 +37,8 @@ FirstPartyOrigin first_party(url::Origin::Create(GURL("https://" + kDomain))); for (int index = 0; index < 5; ++index) { - GURL url("https://example" + base::IntToString(index) + ".co.uk/path?k=v"); + GURL url("https://example" + base::NumberToString(index) + + ".co.uk/path?k=v"); EXPECT_TRUE(FirstPartyOrigin::IsThirdParty(url, first_party.origin())); EXPECT_TRUE(first_party.IsThirdParty(url)); }
diff --git a/components/subresource_filter/core/common/test_ruleset_creator.cc b/components/subresource_filter/core/common/test_ruleset_creator.cc index 1785b8d..4d359de 100644 --- a/components/subresource_filter/core/common/test_ruleset_creator.cc +++ b/components/subresource_filter/core/common/test_ruleset_creator.cc
@@ -145,7 +145,7 @@ std::vector<proto::UrlRule> rules; for (int i = 0; i < num_of_suffixes; ++i) { std::string current_suffix = - suffix.as_string() + '_' + base::IntToString(i); + suffix.as_string() + '_' + base::NumberToString(i); rules.push_back(CreateSuffixRule(current_suffix)); } CreateRulesetWithRules(rules, test_ruleset_pair); @@ -176,7 +176,7 @@ ASSERT_TRUE(scoped_temp_dir_->IsValid() || scoped_temp_dir_->CreateUniqueTempDir()); *path = scoped_temp_dir_->GetPath().AppendASCII( - base::IntToString(next_unique_file_suffix++)); + base::NumberToString(next_unique_file_suffix++)); } void TestRulesetCreator::CreateTestRulesetFromContents(
diff --git a/components/subresource_filter/core/common/unindexed_ruleset_unittest.cc b/components/subresource_filter/core/common/unindexed_ruleset_unittest.cc index 2fefde29..6bc6f792 100644 --- a/components/subresource_filter/core/common/unindexed_ruleset_unittest.cc +++ b/components/subresource_filter/core/common/unindexed_ruleset_unittest.cc
@@ -65,7 +65,7 @@ bool AddUrlRules(int number_of_rules) { for (int i = 0; i < number_of_rules; ++i) { - std::string url_pattern = "example" + base::IntToString(i) + ".com"; + std::string url_pattern = "example" + base::NumberToString(i) + ".com"; if (!AddUrlRule(UrlPattern(url_pattern), testing::kAnyParty, i & 1)) return false; }
diff --git a/components/subresource_filter/tools/indexing_tool_unittest.cc b/components/subresource_filter/tools/indexing_tool_unittest.cc index 79434da..14f0a6c 100644 --- a/components/subresource_filter/tools/indexing_tool_unittest.cc +++ b/components/subresource_filter/tools/indexing_tool_unittest.cc
@@ -46,7 +46,7 @@ base::FilePath GetUniquePath() { base::FilePath path = scoped_temp_dir_.GetPath().AppendASCII( - base::IntToString(file_count_++)); + base::NumberToString(file_count_++)); return path; }
diff --git a/components/subresource_filter/tools/ruleset_converter/rule_stream_unittest.cc b/components/subresource_filter/tools/ruleset_converter/rule_stream_unittest.cc index e1050156..dfd1001b 100644 --- a/components/subresource_filter/tools/ruleset_converter/rule_stream_unittest.cc +++ b/components/subresource_filter/tools/ruleset_converter/rule_stream_unittest.cc
@@ -77,7 +77,7 @@ text_rule += "@@"; if (i & 1) text_rule += "sub."; - text_rule += "example" + base::IntToString(i) + ".com"; + text_rule += "example" + base::NumberToString(i) + ".com"; text_rule += '$'; text_rule += (i & 7) ? "script" : "image"; if (i & 1) @@ -90,7 +90,7 @@ if (i & 1) text_rule += ",~but_not.domain.com"; text_rule += (i & 3) ? "##" : "#@#"; - text_rule += "#id" + base::IntToString(i); + text_rule += "#id" + base::NumberToString(i); text_rules.push_back(text_rule); }
diff --git a/components/suggestions/webui/suggestions_source.cc b/components/suggestions/webui/suggestions_source.cc index 2cad79b..b6b56ab 100644 --- a/components/suggestions/webui/suggestions_source.cc +++ b/components/suggestions/webui/suggestions_source.cc
@@ -68,7 +68,7 @@ line += base::UTF16ToUTF8(remaining_time_formatted); std::vector<std::string> providers; for (int p = 0; p < suggestion.providers_size(); ++p) - providers.push_back(base::IntToString(suggestion.providers(p))); + providers.push_back(base::NumberToString(suggestion.providers(p))); line += ". Provider IDs: " + base::JoinString(providers, ", "); line += "</li>\n"; out.push_back(line);
diff --git a/components/supervised_user_error_page/supervised_user_error_page.cc b/components/supervised_user_error_page/supervised_user_error_page.cc index da5c980..1aaa3bc7 100644 --- a/components/supervised_user_error_page/supervised_user_error_page.cc +++ b/components/supervised_user_error_page/supervised_user_error_page.cc
@@ -30,8 +30,12 @@ std::string BuildAvatarImageUrl(const std::string& url, int size) { std::string result = url; size_t slash = result.rfind('/'); - if (slash != std::string::npos) - result.insert(slash, "/s" + base::IntToString(size) + "-c"); + if (slash != std::string::npos) { + // Check if the URL already contains the monogram (-mo) option. + // In that case, we must use the '-' separator, instead of '/'. + std::string separator = result.substr(slash - 3, 3) == "/mo" ? "-" : "/"; + result.insert(slash, separator + "s" + base::IntToString(size) + "-c"); + } return result; }
diff --git a/components/sync/base/sync_prefs.cc b/components/sync/base/sync_prefs.cc index 978b6575..0b4267b 100644 --- a/components/sync/base/sync_prefs.cc +++ b/components/sync/base/sync_prefs.cc
@@ -596,7 +596,7 @@ std::unique_ptr<base::DictionaryValue> invalidation_dictionary( new base::DictionaryValue()); for (const auto& map_iter : invalidation_versions) { - std::string version_str = base::Int64ToString(map_iter.second); + std::string version_str = base::NumberToString(map_iter.second); invalidation_dictionary->SetString(ModelTypeToString(map_iter.first), version_str); }
diff --git a/components/sync/base/unique_position_unittest.cc b/components/sync/base/unique_position_unittest.cc index 08a1f28..3c0782e 100644 --- a/components/sync/base/unique_position_unittest.cc +++ b/components/sync/base/unique_position_unittest.cc
@@ -392,7 +392,7 @@ // This is not entirely realistic, but that should be OK. The current // suffix format is a base64'ed SHA1 hash, which should be fairly close to // random anyway. - std::string input = cache_guid_ + base::Int64ToString(next_id_--); + std::string input = cache_guid_ + base::NumberToString(next_id_--); std::string output; base::Base64Encode(base::SHA1HashString(input), &output); return output;
diff --git a/components/sync/driver/generic_change_processor.cc b/components/sync/driver/generic_change_processor.cc index 6b8acbb..35eb85ae 100644 --- a/components/sync/driver/generic_change_processor.cc +++ b/components/sync/driver/generic_change_processor.cc
@@ -123,7 +123,7 @@ if (read_node.InitByIdLookup(it->id) != BaseNode::INIT_OK) { SyncError error(FROM_HERE, SyncError::DATATYPE_ERROR, "Failed to look up data for received change with id " + - base::Int64ToString(it->id), + base::NumberToString(it->id), GetModelTypeFromSpecifics(it->specifics)); error_handler()->OnUnrecoverableError(error); return;
diff --git a/components/sync/driver/sync_driver_switches.cc b/components/sync/driver/sync_driver_switches.cc index eb4d3801..b631435 100644 --- a/components/sync/driver/sync_driver_switches.cc +++ b/components/sync/driver/sync_driver_switches.cc
@@ -125,7 +125,7 @@ // Enable USS implementation of autofill wallet datatype. const base::Feature kSyncUSSAutofillWalletData{ - "SyncUSSAutofillWalletData", base::FEATURE_DISABLED_BY_DEFAULT}; + "SyncUSSAutofillWalletData", base::FEATURE_ENABLED_BY_DEFAULT}; // Enable USS implementation of autofill wallet metadata datatype. const base::Feature kSyncUSSAutofillWalletMetadata{
diff --git a/components/sync/engine/events/protocol_event.cc b/components/sync/engine/events/protocol_event.cc index b88912f..2d4fa22 100644 --- a/components/sync/engine/events/protocol_event.cc +++ b/components/sync/engine/events/protocol_event.cc
@@ -12,14 +12,17 @@ ProtocolEvent::~ProtocolEvent() {} std::unique_ptr<base::DictionaryValue> ProtocolEvent::ToValue( - const ProtocolEvent& event, - bool include_specifics) { + bool include_specifics) const { auto dict = std::make_unique<base::DictionaryValue>(); - dict->SetDouble("time", event.GetTimestamp().ToJsTime()); - dict->SetString("type", event.GetType()); - dict->SetString("details", event.GetDetails()); - dict->Set("proto", event.GetProtoMessage(include_specifics)); + dict->SetDouble("time", GetTimestamp().ToJsTime()); + dict->SetString("type", GetType()); + dict->SetString("details", GetDetails()); + dict->Set("proto", GetProtoMessage(include_specifics)); return dict; } +base::Time ProtocolEvent::GetTimestampForTesting() const { + return GetTimestamp(); +} + } // namespace syncer
diff --git a/components/sync/engine/events/protocol_event.h b/components/sync/engine/events/protocol_event.h index 0c20bef1f..28e32a63 100644 --- a/components/sync/engine/events/protocol_event.h +++ b/components/sync/engine/events/protocol_event.h
@@ -32,6 +32,17 @@ ProtocolEvent(); virtual ~ProtocolEvent(); + // Need a virtual copy constructor to copy this object across threads. + virtual std::unique_ptr<ProtocolEvent> Clone() const = 0; + + // Assembles the data exposed through the ProtocolEvent's interface into a + // single DictionaryValue. + std::unique_ptr<base::DictionaryValue> ToValue(bool include_specifics) const; + + // Returns the time when the request was sent or received. + base::Time GetTimestampForTesting() const; + + private: // Returns the time when the request was sent or received. virtual base::Time GetTimestamp() const = 0; @@ -46,15 +57,6 @@ // this event. virtual std::unique_ptr<base::DictionaryValue> GetProtoMessage( bool include_specifics) const = 0; - - // Need a virtual copy contructor to copy this object across threads. - virtual std::unique_ptr<ProtocolEvent> Clone() const = 0; - - // A static function that assembles the data exposed through the - // ProtocolEvent's interface into a single DictionaryValue. - static std::unique_ptr<base::DictionaryValue> ToValue( - const ProtocolEvent& event, - bool include_specifics); }; } // namespace syncer
diff --git a/components/sync/engine/net/http_bridge.cc b/components/sync/engine/net/http_bridge.cc index 86065d6..5369ecc3 100644 --- a/components/sync/engine/net/http_bridge.cc +++ b/components/sync/engine/net/http_bridge.cc
@@ -172,7 +172,7 @@ #endif GURL temp(url); GURL::Replacements replacements; - std::string port_str = base::IntToString(port); + std::string port_str = base::NumberToString(port); replacements.SetPort(port_str.c_str(), url::Component(0, port_str.length())); url_for_request_ = temp.ReplaceComponents(replacements); }
diff --git a/components/sync/engine_impl/events/clear_server_data_request_event.cc b/components/sync/engine_impl/events/clear_server_data_request_event.cc index c091b980..c0ab418e6 100644 --- a/components/sync/engine_impl/events/clear_server_data_request_event.cc +++ b/components/sync/engine_impl/events/clear_server_data_request_event.cc
@@ -16,6 +16,10 @@ ClearServerDataRequestEvent::~ClearServerDataRequestEvent() {} +std::unique_ptr<ProtocolEvent> ClearServerDataRequestEvent::Clone() const { + return std::make_unique<ClearServerDataRequestEvent>(timestamp_, request_); +} + base::Time ClearServerDataRequestEvent::GetTimestamp() const { return timestamp_; } @@ -30,13 +34,7 @@ std::unique_ptr<base::DictionaryValue> ClearServerDataRequestEvent::GetProtoMessage(bool include_specifics) const { - return std::unique_ptr<base::DictionaryValue>( - ClientToServerMessageToValue(request_, include_specifics)); -} - -std::unique_ptr<ProtocolEvent> ClearServerDataRequestEvent::Clone() const { - return std::unique_ptr<ProtocolEvent>( - new ClearServerDataRequestEvent(timestamp_, request_)); + return ClientToServerMessageToValue(request_, include_specifics); } } // namespace syncer
diff --git a/components/sync/engine_impl/events/clear_server_data_request_event.h b/components/sync/engine_impl/events/clear_server_data_request_event.h index 2715e313..634fe821 100644 --- a/components/sync/engine_impl/events/clear_server_data_request_event.h +++ b/components/sync/engine_impl/events/clear_server_data_request_event.h
@@ -22,18 +22,15 @@ ClearServerDataRequestEvent(base::Time timestamp, const sync_pb::ClientToServerMessage& request); ~ClearServerDataRequestEvent() override; + std::unique_ptr<ProtocolEvent> Clone() const override; + private: base::Time GetTimestamp() const override; std::string GetType() const override; std::string GetDetails() const override; std::unique_ptr<base::DictionaryValue> GetProtoMessage( bool include_specifics) const override; - std::unique_ptr<ProtocolEvent> Clone() const override; - static std::unique_ptr<base::DictionaryValue> ToValue( - const ProtocolEvent& event); - - private: const base::Time timestamp_; const sync_pb::ClientToServerMessage request_;
diff --git a/components/sync/engine_impl/events/clear_server_data_response_event.cc b/components/sync/engine_impl/events/clear_server_data_response_event.cc index 7ccce79..94602d1 100644 --- a/components/sync/engine_impl/events/clear_server_data_response_event.cc +++ b/components/sync/engine_impl/events/clear_server_data_response_event.cc
@@ -17,6 +17,11 @@ ClearServerDataResponseEvent::~ClearServerDataResponseEvent() {} +std::unique_ptr<ProtocolEvent> ClearServerDataResponseEvent::Clone() const { + return std::make_unique<ClearServerDataResponseEvent>(timestamp_, result_, + response_); +} + base::Time ClearServerDataResponseEvent::GetTimestamp() const { return timestamp_; } @@ -31,13 +36,7 @@ std::unique_ptr<base::DictionaryValue> ClearServerDataResponseEvent::GetProtoMessage(bool include_specifics) const { - return std::unique_ptr<base::DictionaryValue>( - ClientToServerResponseToValue(response_, include_specifics)); -} - -std::unique_ptr<ProtocolEvent> ClearServerDataResponseEvent::Clone() const { - return std::unique_ptr<ProtocolEvent>( - new ClearServerDataResponseEvent(timestamp_, result_, response_)); + return ClientToServerResponseToValue(response_, include_specifics); } } // namespace syncer
diff --git a/components/sync/engine_impl/events/clear_server_data_response_event.h b/components/sync/engine_impl/events/clear_server_data_response_event.h index 918b368..0810bdf5 100644 --- a/components/sync/engine_impl/events/clear_server_data_response_event.h +++ b/components/sync/engine_impl/events/clear_server_data_response_event.h
@@ -25,17 +25,15 @@ const sync_pb::ClientToServerResponse& response); ~ClearServerDataResponseEvent() override; + std::unique_ptr<ProtocolEvent> Clone() const override; + + private: base::Time GetTimestamp() const override; std::string GetType() const override; std::string GetDetails() const override; std::unique_ptr<base::DictionaryValue> GetProtoMessage( bool include_specifics) const override; - std::unique_ptr<ProtocolEvent> Clone() const override; - static std::unique_ptr<base::DictionaryValue> ToValue( - const ProtocolEvent& event); - - private: const base::Time timestamp_; const SyncerError result_; const sync_pb::ClientToServerResponse response_;
diff --git a/components/sync/engine_impl/events/commit_request_event.cc b/components/sync/engine_impl/events/commit_request_event.cc index f5b2fb1..8d0cce4bb 100644 --- a/components/sync/engine_impl/events/commit_request_event.cc +++ b/components/sync/engine_impl/events/commit_request_event.cc
@@ -24,6 +24,11 @@ CommitRequestEvent::~CommitRequestEvent() {} +std::unique_ptr<ProtocolEvent> CommitRequestEvent::Clone() const { + return std::make_unique<CommitRequestEvent>(timestamp_, num_items_, + contributing_types_, request_); +} + base::Time CommitRequestEvent::GetTimestamp() const { return timestamp_; } @@ -42,13 +47,7 @@ std::unique_ptr<base::DictionaryValue> CommitRequestEvent::GetProtoMessage( bool include_specifics) const { - return std::unique_ptr<base::DictionaryValue>( - ClientToServerMessageToValue(request_, include_specifics)); -} - -std::unique_ptr<ProtocolEvent> CommitRequestEvent::Clone() const { - return std::unique_ptr<ProtocolEvent>(new CommitRequestEvent( - timestamp_, num_items_, contributing_types_, request_)); + return ClientToServerMessageToValue(request_, include_specifics); } } // namespace syncer
diff --git a/components/sync/engine_impl/events/commit_request_event.h b/components/sync/engine_impl/events/commit_request_event.h index a188d94..369c543 100644 --- a/components/sync/engine_impl/events/commit_request_event.h +++ b/components/sync/engine_impl/events/commit_request_event.h
@@ -27,17 +27,15 @@ const sync_pb::ClientToServerMessage& request); ~CommitRequestEvent() override; + std::unique_ptr<ProtocolEvent> Clone() const override; + + private: base::Time GetTimestamp() const override; std::string GetType() const override; std::string GetDetails() const override; std::unique_ptr<base::DictionaryValue> GetProtoMessage( bool include_specifics) const override; - std::unique_ptr<ProtocolEvent> Clone() const override; - static std::unique_ptr<base::DictionaryValue> ToValue( - const ProtocolEvent& event); - - private: const base::Time timestamp_; const size_t num_items_; const ModelTypeSet contributing_types_;
diff --git a/components/sync/engine_impl/events/commit_response_event.cc b/components/sync/engine_impl/events/commit_response_event.cc index f00b2c6d..830802e4 100644 --- a/components/sync/engine_impl/events/commit_response_event.cc +++ b/components/sync/engine_impl/events/commit_response_event.cc
@@ -17,6 +17,10 @@ CommitResponseEvent::~CommitResponseEvent() {} +std::unique_ptr<ProtocolEvent> CommitResponseEvent::Clone() const { + return std::make_unique<CommitResponseEvent>(timestamp_, result_, response_); +} + base::Time CommitResponseEvent::GetTimestamp() const { return timestamp_; } @@ -31,13 +35,8 @@ std::unique_ptr<base::DictionaryValue> CommitResponseEvent::GetProtoMessage( bool include_specifics) const { - return std::unique_ptr<base::DictionaryValue>( - ClientToServerResponseToValue(response_, include_specifics)); + return ClientToServerResponseToValue(response_, include_specifics); } -std::unique_ptr<ProtocolEvent> CommitResponseEvent::Clone() const { - return std::unique_ptr<ProtocolEvent>( - new CommitResponseEvent(timestamp_, result_, response_)); -} } // namespace syncer
diff --git a/components/sync/engine_impl/events/commit_response_event.h b/components/sync/engine_impl/events/commit_response_event.h index dcb17b8..527e853 100644 --- a/components/sync/engine_impl/events/commit_response_event.h +++ b/components/sync/engine_impl/events/commit_response_event.h
@@ -25,18 +25,18 @@ SyncerError result, const sync_pb::ClientToServerResponse& response); ~CommitResponseEvent() override; + std::unique_ptr<ProtocolEvent> Clone() const override; + private: base::Time GetTimestamp() const override; std::string GetType() const override; std::string GetDetails() const override; std::unique_ptr<base::DictionaryValue> GetProtoMessage( bool include_specifics) const override; - std::unique_ptr<ProtocolEvent> Clone() const override; static std::unique_ptr<base::DictionaryValue> ToValue( const ProtocolEvent& event); - private: const base::Time timestamp_; const SyncerError result_; const sync_pb::ClientToServerResponse response_;
diff --git a/components/sync/engine_impl/events/configure_get_updates_request_event.cc b/components/sync/engine_impl/events/configure_get_updates_request_event.cc index 9679560..31bc46a 100644 --- a/components/sync/engine_impl/events/configure_get_updates_request_event.cc +++ b/components/sync/engine_impl/events/configure_get_updates_request_event.cc
@@ -18,6 +18,11 @@ ConfigureGetUpdatesRequestEvent::~ConfigureGetUpdatesRequestEvent() {} +std::unique_ptr<ProtocolEvent> ConfigureGetUpdatesRequestEvent::Clone() const { + return std::make_unique<ConfigureGetUpdatesRequestEvent>(timestamp_, origin_, + request_); +} + base::Time ConfigureGetUpdatesRequestEvent::GetTimestamp() const { return timestamp_; } @@ -32,13 +37,7 @@ std::unique_ptr<base::DictionaryValue> ConfigureGetUpdatesRequestEvent::GetProtoMessage(bool include_specifics) const { - return std::unique_ptr<base::DictionaryValue>( - ClientToServerMessageToValue(request_, include_specifics)); -} - -std::unique_ptr<ProtocolEvent> ConfigureGetUpdatesRequestEvent::Clone() const { - return std::unique_ptr<ProtocolEvent>( - new ConfigureGetUpdatesRequestEvent(timestamp_, origin_, request_)); + return ClientToServerMessageToValue(request_, include_specifics); } } // namespace syncer
diff --git a/components/sync/engine_impl/events/configure_get_updates_request_event.h b/components/sync/engine_impl/events/configure_get_updates_request_event.h index 8dd8854..2bd19fc 100644 --- a/components/sync/engine_impl/events/configure_get_updates_request_event.h +++ b/components/sync/engine_impl/events/configure_get_updates_request_event.h
@@ -24,15 +24,15 @@ sync_pb::SyncEnums::GetUpdatesOrigin origin, const sync_pb::ClientToServerMessage& request); ~ConfigureGetUpdatesRequestEvent() override; + std::unique_ptr<ProtocolEvent> Clone() const override; + private: base::Time GetTimestamp() const override; std::string GetType() const override; std::string GetDetails() const override; std::unique_ptr<base::DictionaryValue> GetProtoMessage( bool include_specifics) const override; - std::unique_ptr<ProtocolEvent> Clone() const override; - private: const base::Time timestamp_; const sync_pb::SyncEnums::GetUpdatesOrigin origin_; const sync_pb::ClientToServerMessage request_;
diff --git a/components/sync/engine_impl/events/get_updates_response_event.cc b/components/sync/engine_impl/events/get_updates_response_event.cc index 8beeb45..00f7d19 100644 --- a/components/sync/engine_impl/events/get_updates_response_event.cc +++ b/components/sync/engine_impl/events/get_updates_response_event.cc
@@ -17,6 +17,11 @@ GetUpdatesResponseEvent::~GetUpdatesResponseEvent() {} +std::unique_ptr<ProtocolEvent> GetUpdatesResponseEvent::Clone() const { + return std::make_unique<GetUpdatesResponseEvent>(timestamp_, response_, + error_); +} + base::Time GetUpdatesResponseEvent::GetTimestamp() const { return timestamp_; } @@ -40,13 +45,7 @@ std::unique_ptr<base::DictionaryValue> GetUpdatesResponseEvent::GetProtoMessage( bool include_specifics) const { - return std::unique_ptr<base::DictionaryValue>( - ClientToServerResponseToValue(response_, include_specifics)); -} - -std::unique_ptr<ProtocolEvent> GetUpdatesResponseEvent::Clone() const { - return std::unique_ptr<ProtocolEvent>( - new GetUpdatesResponseEvent(timestamp_, response_, error_)); + return ClientToServerResponseToValue(response_, include_specifics); } } // namespace syncer
diff --git a/components/sync/engine_impl/events/get_updates_response_event.h b/components/sync/engine_impl/events/get_updates_response_event.h index 6d553ea..f6bc71d 100644 --- a/components/sync/engine_impl/events/get_updates_response_event.h +++ b/components/sync/engine_impl/events/get_updates_response_event.h
@@ -28,15 +28,15 @@ SyncerError error); ~GetUpdatesResponseEvent() override; + std::unique_ptr<ProtocolEvent> Clone() const override; + private: base::Time GetTimestamp() const override; std::string GetType() const override; std::string GetDetails() const override; std::unique_ptr<base::DictionaryValue> GetProtoMessage( bool include_specifics) const override; - std::unique_ptr<ProtocolEvent> Clone() const override; - private: const base::Time timestamp_; const sync_pb::ClientToServerResponse response_; const SyncerError error_;
diff --git a/components/sync/engine_impl/events/normal_get_updates_request_event.cc b/components/sync/engine_impl/events/normal_get_updates_request_event.cc index 8156e67..36d7093 100644 --- a/components/sync/engine_impl/events/normal_get_updates_request_event.cc +++ b/components/sync/engine_impl/events/normal_get_updates_request_event.cc
@@ -14,13 +14,33 @@ base::Time timestamp, const NudgeTracker& nudge_tracker, const sync_pb::ClientToServerMessage& request) + : NormalGetUpdatesRequestEvent(timestamp, + nudge_tracker.GetNudgedTypes(), + nudge_tracker.GetNotifiedTypes(), + nudge_tracker.GetRefreshRequestedTypes(), + nudge_tracker.IsRetryRequired(), + request) {} + +NormalGetUpdatesRequestEvent::NormalGetUpdatesRequestEvent( + base::Time timestamp, + ModelTypeSet nudged_types, + ModelTypeSet notified_types, + ModelTypeSet refresh_requested_types, + bool is_retry, + sync_pb::ClientToServerMessage request) : timestamp_(timestamp), - nudged_types_(nudge_tracker.GetNudgedTypes()), - notified_types_(nudge_tracker.GetNotifiedTypes()), - refresh_requested_types_(nudge_tracker.GetRefreshRequestedTypes()), - is_retry_(nudge_tracker.IsRetryRequired()), + nudged_types_(nudged_types), + notified_types_(notified_types), + refresh_requested_types_(refresh_requested_types), + is_retry_(is_retry), request_(request) {} +std::unique_ptr<ProtocolEvent> NormalGetUpdatesRequestEvent::Clone() const { + return std::make_unique<NormalGetUpdatesRequestEvent>( + timestamp_, nudged_types_, notified_types_, refresh_requested_types_, + is_retry_, request_); +} + NormalGetUpdatesRequestEvent::~NormalGetUpdatesRequestEvent() {} base::Time NormalGetUpdatesRequestEvent::GetTimestamp() const { @@ -67,28 +87,7 @@ std::unique_ptr<base::DictionaryValue> NormalGetUpdatesRequestEvent::GetProtoMessage(bool include_specifics) const { - return std::unique_ptr<base::DictionaryValue>( - ClientToServerMessageToValue(request_, include_specifics)); + return ClientToServerMessageToValue(request_, include_specifics); } -std::unique_ptr<ProtocolEvent> NormalGetUpdatesRequestEvent::Clone() const { - return std::unique_ptr<ProtocolEvent>(new NormalGetUpdatesRequestEvent( - timestamp_, nudged_types_, notified_types_, refresh_requested_types_, - is_retry_, request_)); -} - -NormalGetUpdatesRequestEvent::NormalGetUpdatesRequestEvent( - base::Time timestamp, - ModelTypeSet nudged_types, - ModelTypeSet notified_types, - ModelTypeSet refresh_requested_types, - bool is_retry, - sync_pb::ClientToServerMessage request) - : timestamp_(timestamp), - nudged_types_(nudged_types), - notified_types_(notified_types), - refresh_requested_types_(refresh_requested_types), - is_retry_(is_retry), - request_(request) {} - } // namespace syncer
diff --git a/components/sync/engine_impl/events/normal_get_updates_request_event.h b/components/sync/engine_impl/events/normal_get_updates_request_event.h index dfa931b..1745898 100644 --- a/components/sync/engine_impl/events/normal_get_updates_request_event.h +++ b/components/sync/engine_impl/events/normal_get_updates_request_event.h
@@ -25,23 +25,21 @@ NormalGetUpdatesRequestEvent(base::Time timestamp, const NudgeTracker& nudge_tracker, const sync_pb::ClientToServerMessage& request); - - ~NormalGetUpdatesRequestEvent() override; - - base::Time GetTimestamp() const override; - std::string GetType() const override; - std::string GetDetails() const override; - std::unique_ptr<base::DictionaryValue> GetProtoMessage( - bool include_specifics) const override; - std::unique_ptr<ProtocolEvent> Clone() const override; - - private: NormalGetUpdatesRequestEvent(base::Time timestamp, ModelTypeSet nudged_types, ModelTypeSet notified_types, ModelTypeSet refresh_requested_types, bool is_retry, sync_pb::ClientToServerMessage request); + ~NormalGetUpdatesRequestEvent() override; + std::unique_ptr<ProtocolEvent> Clone() const override; + + private: + base::Time GetTimestamp() const override; + std::string GetType() const override; + std::string GetDetails() const override; + std::unique_ptr<base::DictionaryValue> GetProtoMessage( + bool include_specifics) const override; const base::Time timestamp_;
diff --git a/components/sync/engine_impl/events/poll_get_updates_request_event.cc b/components/sync/engine_impl/events/poll_get_updates_request_event.cc index 5651d378..e316b18 100644 --- a/components/sync/engine_impl/events/poll_get_updates_request_event.cc +++ b/components/sync/engine_impl/events/poll_get_updates_request_event.cc
@@ -15,6 +15,10 @@ PollGetUpdatesRequestEvent::~PollGetUpdatesRequestEvent() {} +std::unique_ptr<ProtocolEvent> PollGetUpdatesRequestEvent::Clone() const { + return std::make_unique<PollGetUpdatesRequestEvent>(timestamp_, request_); +} + base::Time PollGetUpdatesRequestEvent::GetTimestamp() const { return timestamp_; } @@ -29,13 +33,8 @@ std::unique_ptr<base::DictionaryValue> PollGetUpdatesRequestEvent::GetProtoMessage(bool include_specifics) const { - return std::unique_ptr<base::DictionaryValue>( - ClientToServerMessageToValue(request_, include_specifics)); + return ClientToServerMessageToValue(request_, include_specifics); } -std::unique_ptr<ProtocolEvent> PollGetUpdatesRequestEvent::Clone() const { - return std::unique_ptr<ProtocolEvent>( - new PollGetUpdatesRequestEvent(timestamp_, request_)); -} } // namespace syncer
diff --git a/components/sync/engine_impl/events/poll_get_updates_request_event.h b/components/sync/engine_impl/events/poll_get_updates_request_event.h index 7495aa72..0d011ae 100644 --- a/components/sync/engine_impl/events/poll_get_updates_request_event.h +++ b/components/sync/engine_impl/events/poll_get_updates_request_event.h
@@ -23,15 +23,15 @@ PollGetUpdatesRequestEvent(base::Time timestamp, const sync_pb::ClientToServerMessage& request); ~PollGetUpdatesRequestEvent() override; + std::unique_ptr<ProtocolEvent> Clone() const override; + private: base::Time GetTimestamp() const override; std::string GetType() const override; std::string GetDetails() const override; std::unique_ptr<base::DictionaryValue> GetProtoMessage( bool include_specifics) const override; - std::unique_ptr<ProtocolEvent> Clone() const override; - private: const base::Time timestamp_; const sync_pb::ClientToServerMessage request_;
diff --git a/components/sync/engine_impl/events/protocol_event_buffer_unittest.cc b/components/sync/engine_impl/events/protocol_event_buffer_unittest.cc index ffd7ea5..cf74558a6 100644 --- a/components/sync/engine_impl/events/protocol_event_buffer_unittest.cc +++ b/components/sync/engine_impl/events/protocol_event_buffer_unittest.cc
@@ -33,12 +33,16 @@ std::unique_ptr<ProtocolEvent> ProtocolEventBufferTest::MakeTestEvent( int64_t id) { sync_pb::ClientToServerMessage message; - return std::unique_ptr<ProtocolEvent>(new PollGetUpdatesRequestEvent( - base::Time::FromInternalValue(id), message)); + return std::make_unique<PollGetUpdatesRequestEvent>( + base::Time::FromDeltaSinceWindowsEpoch( + base::TimeDelta::FromMicroseconds(id)), + message); } bool ProtocolEventBufferTest::HasId(const ProtocolEvent& event, int64_t id) { - return event.GetTimestamp() == base::Time::FromInternalValue(id); + return event.GetTimestampForTesting() == + base::Time::FromDeltaSinceWindowsEpoch( + base::TimeDelta::FromMicroseconds(id)); } TEST_F(ProtocolEventBufferTest, AddThenReturnEvents) {
diff --git a/components/sync/engine_impl/js_mutation_event_observer.cc b/components/sync/engine_impl/js_mutation_event_observer.cc index 7fdaa2c..9c756ff 100644 --- a/components/sync/engine_impl/js_mutation_event_observer.cc +++ b/components/sync/engine_impl/js_mutation_event_observer.cc
@@ -55,7 +55,7 @@ base::DictionaryValue details; details.SetString("modelType", ModelTypeToString(model_type)); details.SetString("writeTransactionId", - base::Int64ToString(write_transaction_id)); + base::NumberToString(write_transaction_id)); std::unique_ptr<base::Value> changes_value; const size_t changes_size = changes.Get().size(); if (changes_size <= kChangeLimit) {
diff --git a/components/sync/engine_impl/loopback_server/loopback_server.cc b/components/sync/engine_impl/loopback_server/loopback_server.cc index adb7d225..009bdb8 100644 --- a/components/sync/engine_impl/loopback_server/loopback_server.cc +++ b/components/sync/engine_impl/loopback_server/loopback_server.cc
@@ -70,7 +70,7 @@ get_updates_response->add_new_progress_marker(); new_marker->set_data_type_id( GetSpecificsFieldNumberFromModelType(kv.first)); - new_marker->set_token(base::Int64ToString(kv.second)); + new_marker->set_token(base::NumberToString(kv.second)); } } @@ -540,7 +540,7 @@ std::string LoopbackServer::GetStoreBirthday() const { DCHECK(thread_checker_.CalledOnValidThread()); - return base::Int64ToString(store_birthday_); + return base::NumberToString(store_birthday_); } std::vector<sync_pb::SyncEntity> LoopbackServer::GetSyncEntitiesByModelType(
diff --git a/components/sync/engine_impl/syncer_unittest.cc b/components/sync/engine_impl/syncer_unittest.cc index 5e9ca93..9098a41cd 100644 --- a/components/sync/engine_impl/syncer_unittest.cc +++ b/components/sync/engine_impl/syncer_unittest.cc
@@ -3041,7 +3041,7 @@ { syncable::WriteTransaction trans(FROM_HERE, UNITTEST, directory()); for (uint32_t i = 0; i < items_to_commit; i++) { - string nameutf8 = base::UintToString(i); + string nameutf8 = base::NumberToString(i); string name(nameutf8.begin(), nameutf8.end()); MutableEntry e(&trans, CREATE, BOOKMARKS, trans.root_id(), name); e.PutIsUnsynced(true); @@ -3064,7 +3064,7 @@ { syncable::WriteTransaction trans(FROM_HERE, UNITTEST, directory()); for (uint32_t i = 0; i < items_to_commit; i++) { - string nameutf8 = base::UintToString(i); + string nameutf8 = base::NumberToString(i); string name(nameutf8.begin(), nameutf8.end()); MutableEntry e(&trans, CREATE, BOOKMARKS, trans.root_id(), name); e.PutIsUnsynced(true); @@ -3095,7 +3095,7 @@ { syncable::WriteTransaction trans(FROM_HERE, UNITTEST, directory()); for (uint32_t i = 0; i < items_to_commit; i++) { - string nameutf8 = base::UintToString(i); + string nameutf8 = base::NumberToString(i); string name(nameutf8.begin(), nameutf8.end()); MutableEntry e(&trans, CREATE, BOOKMARKS, trans.root_id(), name); e.PutIsUnsynced(true);
diff --git a/components/sync/model/sync_data.cc b/components/sync/model/sync_data.cc index 3dadfaf1..865f19d 100644 --- a/components/sync/model/sync_data.cc +++ b/components/sync/model/sync_data.cc
@@ -121,7 +121,7 @@ } SyncDataRemote sync_data_remote(*this); - std::string id = base::Int64ToString(sync_data_remote.id_); + std::string id = base::NumberToString(sync_data_remote.id_); return "{ isLocal: false, type: " + type + ", specifics: " + specifics + ", id: " + id + "}"; }
diff --git a/components/sync/protocol/proto_value_conversions.cc b/components/sync/protocol/proto_value_conversions.cc index 0c2ba2a..0edbf69 100644 --- a/components/sync/protocol/proto_value_conversions.cc +++ b/components/sync/protocol/proto_value_conversions.cc
@@ -252,16 +252,16 @@ } std::unique_ptr<base::Value> ToValue(int64_t value) const { - return std::make_unique<base::Value>(base::Int64ToString(value)); + return std::make_unique<base::Value>(base::NumberToString(value)); } std::unique_ptr<base::Value> ToValue(uint64_t value) const { - return std::make_unique<base::Value>(base::Int64ToString(value)); + return std::make_unique<base::Value>(base::NumberToString(value)); } std::unique_ptr<base::Value> ToValue(uint32_t value) const { - return std::make_unique<base::Value>(base::Int64ToString(value)); + return std::make_unique<base::Value>(base::NumberToString(value)); } std::unique_ptr<base::Value> ToValue(int32_t value) const { - return std::make_unique<base::Value>(base::Int64ToString(value)); + return std::make_unique<base::Value>(base::NumberToString(value)); } std::unique_ptr<base::Value> ToValue(bool value) const {
diff --git a/components/sync/protocol/proto_value_conversions_unittest.cc b/components/sync/protocol/proto_value_conversions_unittest.cc index 86465d5a8..0b70d097c 100644 --- a/components/sync/protocol/proto_value_conversions_unittest.cc +++ b/components/sync/protocol/proto_value_conversions_unittest.cc
@@ -188,7 +188,8 @@ EXPECT_FALSE(value->empty()); std::string encoded_time; EXPECT_TRUE(value->GetString("creation_time_us", &encoded_time)); - EXPECT_EQ(base::Int64ToString(creation_time.ToInternalValue()), encoded_time); + EXPECT_EQ(base::NumberToString(creation_time.ToInternalValue()), + encoded_time); std::string encoded_icon_url; EXPECT_TRUE(value->GetString("icon_url", &encoded_icon_url)); EXPECT_EQ(icon_url, encoded_icon_url);
diff --git a/components/sync/syncable/change_record.cc b/components/sync/syncable/change_record.cc index e16e0c8..846333d 100644 --- a/components/sync/syncable/change_record.cc +++ b/components/sync/syncable/change_record.cc
@@ -39,7 +39,7 @@ break; } value->SetString("action", action_str); - value->SetString("id", base::Int64ToString(id)); + value->SetString("id", base::NumberToString(id)); if (action == ACTION_DELETE) { if (extra.has_value()) { value->Set("extra", extra->ToValue());
diff --git a/components/sync/syncable/change_record_unittest.cc b/components/sync/syncable/change_record_unittest.cc index 61047a4..f98cf7a 100644 --- a/components/sync/syncable/change_record_unittest.cc +++ b/components/sync/syncable/change_record_unittest.cc
@@ -48,7 +48,7 @@ void CheckChangeRecordValue(const ChangeRecord& record, const base::DictionaryValue& value) { ExpectChangeRecordActionValue(record.action, value, "action"); - ExpectDictStringValue(base::Int64ToString(record.id), value, "id"); + ExpectDictStringValue(base::NumberToString(record.id), value, "id"); if (record.action == ChangeRecord::ACTION_DELETE) { std::unique_ptr<base::DictionaryValue> expected_extra_value; if (record.extra.has_value()) {
diff --git a/components/sync/syncable/directory_backing_store_unittest.cc b/components/sync/syncable/directory_backing_store_unittest.cc index 9daf959..44b6d2ef 100644 --- a/components/sync/syncable/directory_backing_store_unittest.cc +++ b/components/sync/syncable/directory_backing_store_unittest.cc
@@ -39,7 +39,7 @@ // Create a dirty EntryKernel with an ID derived from |id| + |id_suffix|. std::unique_ptr<EntryKernel> CreateEntry(int id, const std::string& id_suffix) { std::unique_ptr<EntryKernel> entry(new EntryKernel()); - std::string id_string = base::Int64ToString(id) + id_suffix; + std::string id_string = base::NumberToString(id) + id_suffix; entry->put(ID, Id::CreateFromClientString(id_string)); entry->put(META_HANDLE, id); entry->mark_dirty(nullptr);
diff --git a/components/sync/syncable/entry_kernel.cc b/components/sync/syncable/entry_kernel.cc index 67f09aa..05d73a2 100644 --- a/components/sync/syncable/entry_kernel.cc +++ b/components/sync/syncable/entry_kernel.cc
@@ -122,7 +122,7 @@ // Helper functions for SetFieldValues(). std::unique_ptr<base::Value> Int64ToValue(int64_t i) { - return std::make_unique<base::Value>(base::Int64ToString(i)); + return std::make_unique<base::Value>(base::NumberToString(i)); } std::unique_ptr<base::Value> TimeToValue(const base::Time& t) {
diff --git a/components/sync/syncable/parent_child_index_unittest.cc b/components/sync/syncable/parent_child_index_unittest.cc index d5da076..1e5b3bf 100644 --- a/components/sync/syncable/parent_child_index_unittest.cc +++ b/components/sync/syncable/parent_child_index_unittest.cc
@@ -33,11 +33,11 @@ } static syncable::Id GetBookmarkId(int n) { - return syncable::Id::CreateFromServerId("b" + base::IntToString(n)); + return syncable::Id::CreateFromServerId("b" + base::NumberToString(n)); } static syncable::Id GetClientUniqueId(int n) { - return syncable::Id::CreateFromServerId("c" + base::IntToString(n)); + return syncable::Id::CreateFromServerId("c" + base::NumberToString(n)); } EntryKernel* MakeRoot() { @@ -109,7 +109,7 @@ item->put(SERVER_VERSION, 10); item->put(IS_DIR, false); item->put(ID, GetClientUniqueId(n)); - item->put(UNIQUE_CLIENT_TAG, base::IntToString(n)); + item->put(UNIQUE_CLIENT_TAG, base::NumberToString(n)); if (!parent_id.IsNull()) { item->put(PARENT_ID, parent_id);
diff --git a/components/sync/syncable/write_transaction_info.cc b/components/sync/syncable/write_transaction_info.cc index e62a1e3..efbed0a 100644 --- a/components/sync/syncable/write_transaction_info.cc +++ b/components/sync/syncable/write_transaction_info.cc
@@ -29,7 +29,7 @@ std::unique_ptr<base::DictionaryValue> WriteTransactionInfo::ToValue( size_t max_mutations_size) const { auto dict = std::make_unique<base::DictionaryValue>(); - dict->SetString("id", base::Int64ToString(id)); + dict->SetString("id", base::NumberToString(id)); dict->SetString("location", location_.ToString()); dict->SetString("writer", WriterTagToString(writer)); std::unique_ptr<base::Value> mutations_value;
diff --git a/components/sync/test/engine/test_id_factory.h b/components/sync/test/engine/test_id_factory.h index ce0f1e7..f9a15a3f 100644 --- a/components/sync/test/engine/test_id_factory.h +++ b/components/sync/test/engine/test_id_factory.h
@@ -31,9 +31,9 @@ if (value == 0) return root(); else if (value < 0) - return syncable::Id::CreateFromClientString(base::Int64ToString(value)); + return syncable::Id::CreateFromClientString(base::NumberToString(value)); else - return syncable::Id::CreateFromServerId(base::Int64ToString(value)); + return syncable::Id::CreateFromServerId(base::NumberToString(value)); } // Create a local ID from a name. @@ -49,13 +49,13 @@ // Autogenerate a fresh local ID. syncable::Id NewLocalId() { return syncable::Id::CreateFromClientString( - std::string("_auto ") + base::IntToString(-next_value())); + std::string("_auto ") + base::NumberToString(-next_value())); } // Autogenerate a fresh server ID. syncable::Id NewServerId() { return syncable::Id::CreateFromServerId(std::string("_auto ") + - base::IntToString(next_value())); + base::NumberToString(next_value())); } private:
diff --git a/components/sync/test/fake_server/entity_builder_factory.cc b/components/sync/test/fake_server/entity_builder_factory.cc index ace0e38..9f23a90 100644 --- a/components/sync/test/fake_server/entity_builder_factory.cc +++ b/components/sync/test/fake_server/entity_builder_factory.cc
@@ -23,7 +23,7 @@ const string& title) { --latest_client_item_id_; BookmarkEntityBuilder builder(title, cache_guid_, - base::Int64ToString(latest_client_item_id_)); + base::NumberToString(latest_client_item_id_)); return builder; }
diff --git a/components/sync/test/fake_server/fake_server.cc b/components/sync/test/fake_server/fake_server.cc index 710012a..1f85d012 100644 --- a/components/sync/test/fake_server/fake_server.cc +++ b/components/sync/test/fake_server/fake_server.cc
@@ -94,8 +94,8 @@ } std::string GetTokenFromHashAndTime(int64_t hash, const base::Time& time) { - return base::Int64ToString(hash) + " " + - base::Int64ToString(time.ToDeltaSinceWindowsEpoch().InMicroseconds()); + return base::NumberToString(hash) + " " + + base::NumberToString(time.ToDeltaSinceWindowsEpoch().InMicroseconds()); } int64_t GetHashFromToken(const std::string& token, int64_t default_value) {
diff --git a/components/sync/test/local_sync_test_server.cc b/components/sync/test/local_sync_test_server.cc index 5319370..2ade27d 100644 --- a/components/sync/test/local_sync_test_server.cc +++ b/components/sync/test/local_sync_test_server.cc
@@ -40,7 +40,7 @@ if (!LocalTestServer::AddCommandLineArguments(command_line)) return false; if (xmpp_port_ != 0) { - std::string xmpp_port_str = base::UintToString(xmpp_port_); + std::string xmpp_port_str = base::NumberToString(xmpp_port_); command_line->AppendArg("--xmpp-port=" + xmpp_port_str); } return true;
diff --git a/components/sync/user_events/user_event_sync_bridge.cc b/components/sync/user_events/user_event_sync_bridge.cc index 924ab0c..ae12693 100644 --- a/components/sync/user_events/user_event_sync_bridge.cc +++ b/components/sync/user_events/user_event_sync_bridge.cc
@@ -54,7 +54,7 @@ std::unique_ptr<UserEventSpecifics> specifics) { auto entity_data = std::make_unique<EntityData>(); entity_data->non_unique_name = - base::Int64ToString(specifics->event_time_usec()); + base::NumberToString(specifics->event_time_usec()); entity_data->specifics.set_allocated_user_event(specifics.release()); return entity_data; }
diff --git a/components/sync_sessions/synced_session_unittest.cc b/components/sync_sessions/synced_session_unittest.cc index dc709c2..67c31047 100644 --- a/components/sync_sessions/synced_session_unittest.cc +++ b/components/sync_sessions/synced_session_unittest.cc
@@ -202,7 +202,7 @@ sync_data.set_extension_app_id("app_id"); for (int i = 0; i < 5; ++i) { sync_pb::TabNavigation* navigation = sync_data.add_navigation(); - navigation->set_virtual_url("http://foo/" + base::IntToString(i)); + navigation->set_virtual_url("http://foo/" + base::NumberToString(i)); navigation->set_referrer("referrer"); navigation->set_title("title"); navigation->set_page_transition(sync_pb::SyncEnums_PageTransition_TYPED); @@ -236,7 +236,7 @@ EXPECT_EQ(base::ASCIIToUTF16("title"), tab.navigations[i].title()); EXPECT_TRUE(ui::PageTransitionTypeIncludingQualifiersIs( tab.navigations[i].transition_type(), ui::PAGE_TRANSITION_TYPED)); - EXPECT_EQ(GURL("http://foo/" + base::IntToString(i)), + EXPECT_EQ(GURL("http://foo/" + base::NumberToString(i)), tab.navigations[i].virtual_url()); } EXPECT_TRUE(tab.session_storage_persistent_id.empty()); @@ -255,7 +255,7 @@ for (int i = 0; i < 5; ++i) { tab.navigations.push_back( SerializedNavigationEntryTestHelper::CreateNavigation( - "http://foo/" + base::IntToString(i), "title")); + "http://foo/" + base::NumberToString(i), "title")); } tab.session_storage_persistent_id = "fake";
diff --git a/components/task_scheduler_util/variations_util.cc b/components/task_scheduler_util/variations_util.cc index d7b3e7a..cff79ac 100644 --- a/components/task_scheduler_util/variations_util.cc +++ b/components/task_scheduler_util/variations_util.cc
@@ -98,14 +98,23 @@ const auto background_worker_pool_params = GetWorkerPoolParams("Background", variation_params); + const auto background_blocking_worker_pool_params = + GetWorkerPoolParams("BackgroundBlocking", variation_params); const auto foreground_worker_pool_params = GetWorkerPoolParams("Foreground", variation_params); + const auto foreground_blocking_worker_pool_params = + GetWorkerPoolParams("ForegroundBlocking", variation_params); - if (!background_worker_pool_params || !foreground_worker_pool_params) + if (!background_worker_pool_params || + !background_blocking_worker_pool_params || + !foreground_worker_pool_params || + !foreground_blocking_worker_pool_params) { return nullptr; + } return std::make_unique<base::TaskScheduler::InitParams>( - *background_worker_pool_params, *foreground_worker_pool_params); + *background_worker_pool_params, *background_blocking_worker_pool_params, + *foreground_worker_pool_params, *foreground_blocking_worker_pool_params); } std::unique_ptr<base::TaskScheduler::InitParams>
diff --git a/components/task_scheduler_util/variations_util_unittest.cc b/components/task_scheduler_util/variations_util_unittest.cc index d5aaffb..7193ca8 100644 --- a/components/task_scheduler_util/variations_util_unittest.cc +++ b/components/task_scheduler_util/variations_util_unittest.cc
@@ -41,7 +41,9 @@ TEST_F(TaskSchedulerUtilVariationsUtilTest, OrderingParams5) { std::map<std::string, std::string> variation_params; variation_params["Background"] = "1;1;1;0;42"; + variation_params["BackgroundBlocking"] = "2;2;1;0;52"; variation_params["Foreground"] = "4;4;1;0;62"; + variation_params["ForegroundBlocking"] = "8;8;1;0;72"; SetVariationParams(variation_params); auto init_params = GetTaskSchedulerInitParams(kRendererSchedulerInitParams); @@ -55,6 +57,14 @@ base::SchedulerBackwardCompatibility::DISABLED, init_params->background_worker_pool_params.backward_compatibility()); + EXPECT_EQ(2, init_params->background_blocking_worker_pool_params.max_tasks()); + EXPECT_EQ(base::TimeDelta::FromMilliseconds(52), + init_params->background_blocking_worker_pool_params + .suggested_reclaim_time()); + EXPECT_EQ(base::SchedulerBackwardCompatibility::DISABLED, + init_params->background_blocking_worker_pool_params + .backward_compatibility()); + EXPECT_EQ(4, init_params->foreground_worker_pool_params.max_tasks()); EXPECT_EQ( base::TimeDelta::FromMilliseconds(62), @@ -62,6 +72,14 @@ EXPECT_EQ( base::SchedulerBackwardCompatibility::DISABLED, init_params->foreground_worker_pool_params.backward_compatibility()); + + EXPECT_EQ(8, init_params->foreground_blocking_worker_pool_params.max_tasks()); + EXPECT_EQ(base::TimeDelta::FromMilliseconds(72), + init_params->foreground_blocking_worker_pool_params + .suggested_reclaim_time()); + EXPECT_EQ(base::SchedulerBackwardCompatibility::DISABLED, + init_params->foreground_blocking_worker_pool_params + .backward_compatibility()); } TEST_F(TaskSchedulerUtilVariationsUtilTest, NoData) { @@ -71,7 +89,9 @@ TEST_F(TaskSchedulerUtilVariationsUtilTest, IncompleteParameters) { std::map<std::string, std::string> variation_params; variation_params["Background"] = "1;1;1;0"; + variation_params["BackgroundBlocking"] = "2;2;1;0"; variation_params["Foreground"] = "4;4;1;0"; + variation_params["ForegroundBlocking"] = "8;8;1;0"; SetVariationParams(variation_params); EXPECT_FALSE(GetTaskSchedulerInitParams(kRendererSchedulerInitParams)); } @@ -79,7 +99,9 @@ TEST_F(TaskSchedulerUtilVariationsUtilTest, InvalidParametersFormat) { std::map<std::string, std::string> variation_params; variation_params["Background"] = "a;b;c;d;e"; + variation_params["BackgroundBlocking"] = "a;b;c;d;e"; variation_params["Foreground"] = "a;b;c;d;e"; + variation_params["ForegroundBlocking"] = "a;b;c;d;e"; SetVariationParams(variation_params); EXPECT_FALSE(GetTaskSchedulerInitParams(kRendererSchedulerInitParams)); } @@ -89,7 +111,9 @@ // invalid. std::map<std::string, std::string> variation_params; variation_params["Background"] = "0;0;0;0;0"; + variation_params["BackgroundBlocking"] = "2;2;1;0;52"; variation_params["Foreground"] = "4;4;1;0;62"; + variation_params["ForegroundBlocking"] = "8;8;1;0;72"; SetVariationParams(variation_params); EXPECT_FALSE(GetTaskSchedulerInitParams(kRendererSchedulerInitParams)); } @@ -99,7 +123,9 @@ // invalid. std::map<std::string, std::string> variation_params; variation_params["Background"] = "-5;-5;0;0;0"; + variation_params["BackgroundBlocking"] = "2;2;1;0;52"; variation_params["Foreground"] = "4;4;1;0;62"; + variation_params["ForegroundBlocking"] = "8;8;1;0;72"; SetVariationParams(variation_params); EXPECT_FALSE(GetTaskSchedulerInitParams(kRendererSchedulerInitParams)); } @@ -109,7 +135,9 @@ // invalid. std::map<std::string, std::string> variation_params; variation_params["Background"] = "1;1;1;0;-5"; + variation_params["BackgroundBlocking"] = "2;2;1;0;52"; variation_params["Foreground"] = "4;4;1;0;62"; + variation_params["ForegroundBlocking"] = "8;8;1;0;72"; SetVariationParams(variation_params); EXPECT_FALSE(GetTaskSchedulerInitParams(kRendererSchedulerInitParams)); }
diff --git a/components/translate/content/renderer/BUILD.gn b/components/translate/content/renderer/BUILD.gn index 8915865..d04d8d6 100644 --- a/components/translate/content/renderer/BUILD.gn +++ b/components/translate/content/renderer/BUILD.gn
@@ -22,6 +22,10 @@ "//url", "//v8", ] + + public_deps = [ + "//third_party/blink/public:blink_headers", + ] } source_set("unit_tests") {
diff --git a/components/ui_devtools/css_agent.cc b/components/ui_devtools/css_agent.cc index d4d9c57b..4fd7f68 100644 --- a/components/ui_devtools/css_agent.cc +++ b/components/ui_devtools/css_agent.cc
@@ -37,7 +37,7 @@ return CSS::CSSProperty::create() .setRange(BuildDefaultSourceRange()) .setName(name) - .setValue(base::IntToString(value)) + .setValue(base::NumberToString(value)) .build(); } @@ -78,7 +78,7 @@ return CSS::CSSStyle::create() .setRange(BuildDefaultSourceRange()) - .setStyleSheetId(base::IntToString(ui_element->node_id())) + .setStyleSheetId(base::NumberToString(ui_element->node_id())) .setCssProperties(std::move(css_properties)) .setShorthandEntries(Array<protocol::CSS::ShorthandEntry>::create()) .build(); @@ -191,7 +191,7 @@ void CSSAgent::InvalidateStyleSheet(UIElement* ui_element) { // The stylesheetId for each node is equivalent to its node_id (as a string). - frontend()->styleSheetChanged(base::IntToString(ui_element->node_id())); + frontend()->styleSheetChanged(base::NumberToString(ui_element->node_id())); } bool CSSAgent::GetPropertiesForUIElement(UIElement* ui_element,
diff --git a/components/ui_devtools/css_agent_unittest.cc b/components/ui_devtools/css_agent_unittest.cc index 320937d..675103f 100644 --- a/components/ui_devtools/css_agent_unittest.cc +++ b/components/ui_devtools/css_agent_unittest.cc
@@ -86,7 +86,7 @@ int node_id) { auto edits = protocol::Array<protocol::CSS::StyleDeclarationEdit>::create(); auto edit = protocol::CSS::StyleDeclarationEdit::create() - .setStyleSheetId(base::IntToString(node_id)) + .setStyleSheetId(base::NumberToString(node_id)) .setRange(protocol::CSS::SourceRange::create() .setStartLine(0) .setStartColumn(0) @@ -171,7 +171,7 @@ EXPECT_EQ(result.second->length(), 1U); protocol::CSS::CSSStyle* style = result.second->get(0); EXPECT_EQ(style->getStyleSheetId("default"), - base::IntToString(element()->node_id())); + base::NumberToString(element()->node_id())); EXPECT_EQ(GetValueForProperty(style, "visibility"), "1"); } @@ -184,7 +184,7 @@ EXPECT_EQ(result.second->length(), 1U); protocol::CSS::CSSStyle* style = result.second->get(0); EXPECT_EQ(style->getStyleSheetId("default"), - base::IntToString(element()->node_id())); + base::NumberToString(element()->node_id())); EXPECT_EQ(GetValueForProperty(style, "x"), "500"); } @@ -197,7 +197,7 @@ EXPECT_EQ(result.second->length(), 1U); protocol::CSS::CSSStyle* style = result.second->get(0); EXPECT_EQ(style->getStyleSheetId("default"), - base::IntToString(element()->node_id())); + base::NumberToString(element()->node_id())); EXPECT_EQ(GetValueForProperty(style, "y"), "100"); } TEST_F(CSSAgentTest, SettingWidth) { @@ -209,7 +209,7 @@ EXPECT_EQ(result.second->length(), 1U); protocol::CSS::CSSStyle* style = result.second->get(0); EXPECT_EQ(style->getStyleSheetId("default"), - base::IntToString(element()->node_id())); + base::NumberToString(element()->node_id())); EXPECT_EQ(GetValueForProperty(style, "width"), "20"); } TEST_F(CSSAgentTest, SettingHeight) { @@ -221,7 +221,7 @@ EXPECT_EQ(result.second->length(), 1U); protocol::CSS::CSSStyle* style = result.second->get(0); EXPECT_EQ(style->getStyleSheetId("default"), - base::IntToString(element()->node_id())); + base::NumberToString(element()->node_id())); EXPECT_EQ(GetValueForProperty(style, "height"), "30"); } @@ -239,7 +239,7 @@ EXPECT_EQ(result.second->length(), 1U); protocol::CSS::CSSStyle* style = result.second->get(0); EXPECT_EQ(style->getStyleSheetId("default"), - base::IntToString(element()->node_id())); + base::NumberToString(element()->node_id())); EXPECT_EQ(GetValueForProperty(style, "x"), "9000"); EXPECT_EQ(GetValueForProperty(style, "y"), "25"); EXPECT_EQ(GetValueForProperty(style, "width"), "50");
diff --git a/components/ui_devtools/string_util.h b/components/ui_devtools/string_util.h index 50995dc..1a79c0a 100644 --- a/components/ui_devtools/string_util.h +++ b/components/ui_devtools/string_util.h
@@ -38,7 +38,7 @@ static String substring(const String& s, unsigned pos, unsigned len) { return s.substr(pos, len); } - static String fromInteger(int number) { return base::IntToString(number); } + static String fromInteger(int number) { return base::NumberToString(number); } static String fromDouble(double number) { return base::NumberToString(number); }
diff --git a/components/ukm/ukm_recorder_impl.cc b/components/ukm/ukm_recorder_impl.cc index cf1fadb..629cfc9 100644 --- a/components/ukm/ukm_recorder_impl.cc +++ b/components/ukm/ukm_recorder_impl.cc
@@ -205,7 +205,7 @@ // Everybody (100%) should have a sampling configuration. std::map<std::string, std::string> params = { - {"_default_sampling", base::IntToString(default_sampling)}}; + {"_default_sampling", base::NumberToString(default_sampling)}}; variations::AssociateVariationParams(trial->trial_name(), sampled_group, params); trial->AppendGroup(sampled_group, 100);
diff --git a/components/ukm/ukm_service.h b/components/ukm/ukm_service.h index d28f540..ba8fe13 100644 --- a/components/ukm/ukm_service.h +++ b/components/ukm/ukm_service.h
@@ -9,7 +9,6 @@ #include <memory> #include <vector> -#include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/sequence_checker.h" @@ -22,7 +21,6 @@ class PrefRegistrySimple; class PrefService; -FORWARD_DECLARE_TEST(ChromeMetricsServiceClientTest, TestRegisterUKMProviders); namespace metrics { class MetricsServiceClient; @@ -82,7 +80,7 @@ // Registers the specified |provider| to provide additional metrics into the // UKM log. Should be called during MetricsService initialization only. - virtual void RegisterMetricsProvider( + void RegisterMetricsProvider( std::unique_ptr<metrics::MetricsProvider> provider); // Registers the names of all of the preferences used by UkmService in @@ -96,8 +94,7 @@ friend ::metrics::UkmEGTestHelper; friend ::ukm::debug::UkmDebugDataExtractor; friend ::ukm::UkmUtilsForTest; - FRIEND_TEST_ALL_PREFIXES(::ChromeMetricsServiceClientTest, - TestRegisterUKMProviders); + // Starts metrics client initialization. void StartInitTask();
diff --git a/components/update_client/updater_state.cc b/components/update_client/updater_state.cc index f8fd5fb..7178b54 100644 --- a/components/update_client/updater_state.cc +++ b/components/update_client/updater_state.cc
@@ -76,7 +76,7 @@ is_autoupdate_check_enabled_ ? "1" : "0"; DCHECK((update_policy_ >= 0 && update_policy_ <= 3) || update_policy_ == -1); - attributes["updatepolicy"] = base::IntToString(update_policy_); + attributes["updatepolicy"] = base::NumberToString(update_policy_); return attributes; }
diff --git a/components/upload_list/text_log_upload_list_unittest.cc b/components/upload_list/text_log_upload_list_unittest.cc index 9e011aa..91922ed 100644 --- a/components/upload_list/text_log_upload_list_unittest.cc +++ b/components/upload_list/text_log_upload_list_unittest.cc
@@ -248,7 +248,7 @@ test_entry += ","; test_entry.append(kTestCaptureTime); test_entry += ","; - test_entry.append(base::IntToString( + test_entry.append(base::NumberToString( static_cast<int>(UploadList::UploadInfo::State::Uploaded))); test_entry += "\n"; }
diff --git a/components/url_formatter/elide_url.cc b/components/url_formatter/elide_url.cc index 77cd4dd0..a629cc47 100644 --- a/components/url_formatter/elide_url.cc +++ b/components/url_formatter/elide_url.cc
@@ -432,7 +432,7 @@ const int default_port = url::DefaultPortForScheme( scheme.data(), static_cast<int>(scheme.length())); if (port != 0 && port != default_port) - result += colon + base::UintToString16(origin.port()); + result += colon + base::NumberToString16(origin.port()); return result; }
diff --git a/components/variations/android/java/src/org/chromium/components/variations/firstrun/VariationsSeedFetcher.java b/components/variations/android/java/src/org/chromium/components/variations/firstrun/VariationsSeedFetcher.java index 0808161..03d0cb4 100644 --- a/components/variations/android/java/src/org/chromium/components/variations/firstrun/VariationsSeedFetcher.java +++ b/components/variations/android/java/src/org/chromium/components/variations/firstrun/VariationsSeedFetcher.java
@@ -6,6 +6,7 @@ import android.content.SharedPreferences; import android.os.SystemClock; +import android.support.annotation.IntDef; import org.chromium.base.ContextUtils; import org.chromium.base.Log; @@ -17,6 +18,8 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.SocketTimeoutException; @@ -35,7 +38,12 @@ public class VariationsSeedFetcher { private static final String TAG = "VariationsSeedFetch"; - public enum VariationsPlatform { ANDROID, ANDROID_WEBVIEW } + @IntDef({VariationsPlatform.ANDROID, VariationsPlatform.ANDROID_WEBVIEW}) + @Retention(RetentionPolicy.SOURCE) + public @interface VariationsPlatform { + int ANDROID = 0; + int ANDROID_WEBVIEW = 1; + } private static final String VARIATIONS_SERVER_URL = "https://clientservices.googleapis.com/chrome-variations/seed?osname="; @@ -85,7 +93,7 @@ @VisibleForTesting protected HttpURLConnection getServerConnection( - VariationsPlatform platform, String restrictMode, String milestone, String channel) + @VariationsPlatform int platform, String restrictMode, String milestone, String channel) throws MalformedURLException, IOException { String urlString = getConnectionString(platform, restrictMode, milestone, channel); URL url = new URL(urlString); @@ -93,14 +101,14 @@ } @VisibleForTesting - protected String getConnectionString( - VariationsPlatform platform, String restrictMode, String milestone, String channel) { + protected String getConnectionString(@VariationsPlatform int platform, String restrictMode, + String milestone, String channel) { String urlString = VARIATIONS_SERVER_URL; switch (platform) { - case ANDROID: + case VariationsPlatform.ANDROID: urlString += "android"; break; - case ANDROID_WEBVIEW: + case VariationsPlatform.ANDROID_WEBVIEW: urlString += "android_webview"; break; default: @@ -217,7 +225,7 @@ * connection. */ public SeedInfo downloadContent( - VariationsPlatform platform, String restrictMode, String milestone, String channel) + @VariationsPlatform int platform, String restrictMode, String milestone, String channel) throws SocketTimeoutException, UnknownHostException, IOException { HttpURLConnection connection = null; try {
diff --git a/components/variations/entropy_provider.cc b/components/variations/entropy_provider.cc index 0c463682..d7eb868 100644 --- a/components/variations/entropy_provider.cc +++ b/components/variations/entropy_provider.cc
@@ -37,8 +37,9 @@ // distribution given the same |trial_name|. When using such a low entropy // source, NormalizedMurmurHashEntropyProvider should be used instead. std::string input(entropy_source_); - input.append(randomization_seed == 0 ? trial_name : base::UintToString( - randomization_seed)); + input.append(randomization_seed == 0 + ? trial_name + : base::NumberToString(randomization_seed)); unsigned char sha1_hash[base::kSHA1Length]; base::SHA1HashBytes(reinterpret_cast<const unsigned char*>(input.c_str()),
diff --git a/components/variations/entropy_provider_unittest.cc b/components/variations/entropy_provider_unittest.cc index de2ca10..79040f4 100644 --- a/components/variations/entropy_provider_unittest.cc +++ b/components/variations/entropy_provider_unittest.cc
@@ -91,7 +91,7 @@ const int low_entropy_source = static_cast<uint16_t>(base::RandInt(0, kMaxLowEntropySize - 1)); const std::string high_entropy_source = - base::GenerateGUID() + base::IntToString(low_entropy_source); + base::GenerateGUID() + base::NumberToString(low_entropy_source); return GenerateSHA1Entropy(high_entropy_source, trial_name_); }
diff --git a/components/variations/variations_http_header_provider.cc b/components/variations/variations_http_header_provider.cc index 67086009..d2a9746 100644 --- a/components/variations/variations_http_header_provider.cc +++ b/components/variations/variations_http_header_provider.cc
@@ -74,7 +74,7 @@ base::AutoLock scoped_lock(lock_); for (const VariationIDEntry& entry : GetAllVariationIds()) { if (entry.second == GOOGLE_WEB_PROPERTIES) { - ids_string.append(base::IntToString(entry.first)); + ids_string.append(base::NumberToString(entry.first)); ids_string.push_back(' '); } }
diff --git a/components/viz/common/features.cc b/components/viz/common/features.cc index 184c013..3ab8090 100644 --- a/components/viz/common/features.cc +++ b/components/viz/common/features.cc
@@ -42,6 +42,10 @@ const base::Feature kUseSkiaRenderer{"UseSkiaRenderer", base::FEATURE_DISABLED_BY_DEFAULT}; +// Use the SkiaRenderer without DDL. +const base::Feature kUseSkiaRendererNonDDL{"UseSkiaRendererNonDDL", + base::FEATURE_DISABLED_BY_DEFAULT}; + // Use the SkiaRenderer to record SkPicture. const base::Feature kRecordSkPicture{"RecordSkPicture", base::FEATURE_DISABLED_BY_DEFAULT}; @@ -81,6 +85,10 @@ return base::FeatureList::IsEnabled(kUseSkiaRenderer); } +bool IsUsingSkiaRendererNonDDL() { + return base::FeatureList::IsEnabled(kUseSkiaRendererNonDDL); +} + bool IsRecordingSkPicture() { return IsUsingSkiaRenderer() && base::FeatureList::IsEnabled(kRecordSkPicture);
diff --git a/components/viz/common/features.h b/components/viz/common/features.h index 69d8285..b5e1aac 100644 --- a/components/viz/common/features.h +++ b/components/viz/common/features.h
@@ -15,6 +15,7 @@ VIZ_COMMON_EXPORT extern const base::Feature kEnableVizHitTestDrawQuad; VIZ_COMMON_EXPORT extern const base::Feature kEnableVizHitTestSurfaceLayer; VIZ_COMMON_EXPORT extern const base::Feature kUseSkiaRenderer; +VIZ_COMMON_EXPORT extern const base::Feature kUseSkiaRendererNonDDL; VIZ_COMMON_EXPORT extern const base::Feature kRecordSkPicture; VIZ_COMMON_EXPORT extern const base::Feature kVizDisplayCompositor; @@ -24,6 +25,7 @@ VIZ_COMMON_EXPORT bool IsVizHitTestingEnabled(); VIZ_COMMON_EXPORT bool IsVizHitTestingSurfaceLayerEnabled(); VIZ_COMMON_EXPORT bool IsUsingSkiaRenderer(); +VIZ_COMMON_EXPORT bool IsUsingSkiaRendererNonDDL(); VIZ_COMMON_EXPORT bool IsRecordingSkPicture(); } // namespace features
diff --git a/components/viz/common/quads/frame_deadline.cc b/components/viz/common/quads/frame_deadline.cc index f5f5619b..6ab63d9a 100644 --- a/components/viz/common/quads/frame_deadline.cc +++ b/components/viz/common/quads/frame_deadline.cc
@@ -31,7 +31,7 @@ start_time_delta.InMilliseconds(), use_default_lower_bound_deadline_ ? "unresolved" - : base::UintToString(deadline_in_frames_).c_str(), + : base::NumberToString(deadline_in_frames_).c_str(), frame_interval_.InMilliseconds()); }
diff --git a/components/viz/service/BUILD.gn b/components/viz/service/BUILD.gn index ffd67e69..9ec0dfd0 100644 --- a/components/viz/service/BUILD.gn +++ b/components/viz/service/BUILD.gn
@@ -307,6 +307,8 @@ sources = [ "display_embedder/skia_output_surface_impl.cc", "display_embedder/skia_output_surface_impl.h", + "display_embedder/skia_output_surface_impl_non_ddl.cc", + "display_embedder/skia_output_surface_impl_non_ddl.h", "display_embedder/skia_output_surface_impl_on_gpu.cc", "display_embedder/skia_output_surface_impl_on_gpu.h", "gl/gpu_service_impl.cc",
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 815bb3a..2dafe84 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl.cc
@@ -533,9 +533,9 @@ std::vector<sk_sp<SkImage>> images) { if (images.empty()) return gpu::SyncToken(); - gpu::SyncToken sync_token(gpu::CommandBufferNamespace::VIZ_OUTPUT_SURFACE, - impl_on_gpu_->command_buffer_id(), - ++sync_fence_release_); + gpu::SyncToken sync_token( + gpu::CommandBufferNamespace::VIZ_SKIA_OUTPUT_SURFACE, + impl_on_gpu_->command_buffer_id(), ++sync_fence_release_); sync_token.SetVerifyFlush(); // impl_on_gpu_ is released on the GPU thread by a posted task from // SkiaOutputSurfaceImpl::dtor. So it is safe to use base::Unretained. @@ -585,9 +585,9 @@ // Otherwise we are painting a frame. bool painting_render_pass = current_render_pass_id_ != 0; - gpu::SyncToken sync_token(gpu::CommandBufferNamespace::VIZ_OUTPUT_SURFACE, - impl_on_gpu_->command_buffer_id(), - ++sync_fence_release_); + gpu::SyncToken sync_token( + gpu::CommandBufferNamespace::VIZ_SKIA_OUTPUT_SURFACE, + impl_on_gpu_->command_buffer_id(), ++sync_fence_release_); sync_token.SetVerifyFlush(); auto ddl = recorder_->detach();
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.cc b/components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.cc new file mode 100644 index 0000000..6407d8f --- /dev/null +++ b/components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.cc
@@ -0,0 +1,462 @@ +// 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. + +#include "components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.h" + +#include <utility> + +#include "base/atomic_sequence_num.h" +#include "base/bind.h" +#include "base/callback_helpers.h" +#include "base/synchronization/waitable_event.h" +#include "components/viz/common/frame_sinks/begin_frame_source.h" +#include "components/viz/common/frame_sinks/copy_output_request.h" +#include "components/viz/common/gpu/context_lost_observer.h" +#include "components/viz/common/resources/resource_format_utils.h" +#include "components/viz/service/display/output_surface_client.h" +#include "components/viz/service/display/output_surface_frame.h" +#include "components/viz/service/display/resource_metadata.h" +#include "gpu/command_buffer/common/swap_buffers_complete_params.h" +#include "gpu/command_buffer/service/mailbox_manager.h" +#include "gpu/command_buffer/service/skia_utils.h" +#include "gpu/command_buffer/service/sync_point_manager.h" +#include "gpu/command_buffer/service/texture_base.h" +#include "third_party/skia/include/core/SkYUVAIndex.h" +#include "ui/gfx/skia_util.h" +#include "ui/gl/gl_bindings.h" +#include "ui/gl/gl_context.h" +#include "ui/gl/gl_gl_api_implementation.h" +#include "ui/gl/gl_surface.h" +#include "ui/gl/gl_version_info.h" + +namespace viz { + +namespace { + +scoped_refptr<gpu::SyncPointClientState> CreateSyncPointClientState( + gpu::SyncPointManager* sync_point_manager, + gpu::SequenceId sequence_id) { + static uint64_t next_command_buffer_id = 0u; + auto command_buffer_id = + gpu::CommandBufferId::FromUnsafeValue(++next_command_buffer_id); + return sync_point_manager->CreateSyncPointClientState( + gpu::CommandBufferNamespace::VIZ_SKIA_OUTPUT_SURFACE_NON_DDL, + command_buffer_id, sequence_id); +} + +} // namespace + +SkiaOutputSurfaceImplNonDDL::SkiaOutputSurfaceImplNonDDL( + scoped_refptr<gl::GLSurface> gl_surface, + scoped_refptr<gpu::SharedContextState> shared_context_state, + gpu::MailboxManager* mailbox_manager, + gpu::SyncPointManager* sync_point_manager) + : gl_surface_(std::move(gl_surface)), + shared_context_state_(std::move(shared_context_state)), + mailbox_manager_(mailbox_manager), + sync_point_order_data_(sync_point_manager->CreateSyncPointOrderData()), + sync_point_client_state_( + CreateSyncPointClientState(sync_point_manager, + sync_point_order_data_->sequence_id())) {} + +SkiaOutputSurfaceImplNonDDL::~SkiaOutputSurfaceImplNonDDL() { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); +} + +void SkiaOutputSurfaceImplNonDDL::BindToClient(OutputSurfaceClient* client) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + DCHECK(client); + DCHECK(!client_); + client_ = client; +} + +void SkiaOutputSurfaceImplNonDDL::EnsureBackbuffer() { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + NOTIMPLEMENTED(); +} + +void SkiaOutputSurfaceImplNonDDL::DiscardBackbuffer() { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + NOTIMPLEMENTED(); +} + +void SkiaOutputSurfaceImplNonDDL::BindFramebuffer() { + // TODO(penghuang): remove this method when GLRenderer is removed. +} + +void SkiaOutputSurfaceImplNonDDL::SetDrawRectangle( + const gfx::Rect& draw_rectangle) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + NOTIMPLEMENTED(); +} + +void SkiaOutputSurfaceImplNonDDL::Reshape(const gfx::Size& size, + float device_scale_factor, + const gfx::ColorSpace& color_space, + bool has_alpha, + bool use_stencil) { + reshape_surface_size_ = size; + reshape_device_scale_factor_ = device_scale_factor; + reshape_color_space_ = color_space; + reshape_has_alpha_ = has_alpha; + reshape_use_stencil_ = use_stencil; + backing_framebuffer_object_ = gl_surface_->GetBackingFramebufferObject(); + + SkSurfaceProps surface_props = + SkSurfaceProps(0, SkSurfaceProps::kLegacyFontHost_InitType); + + GrGLFramebufferInfo framebuffer_info; + framebuffer_info.fFBOID = backing_framebuffer_object_; + framebuffer_info.fFormat = GL_RGBA8; + + GrBackendRenderTarget render_target(size.width(), size.height(), 0, 8, + framebuffer_info); + + sk_surface_ = SkSurface::MakeFromBackendRenderTarget( + gr_context(), render_target, kBottomLeft_GrSurfaceOrigin, + kRGBA_8888_SkColorType, color_space.ToSkColorSpace(), &surface_props); + DCHECK(sk_surface_); +} + +void SkiaOutputSurfaceImplNonDDL::SwapBuffers(OutputSurfaceFrame frame) { + NOTIMPLEMENTED(); +} + +uint32_t SkiaOutputSurfaceImplNonDDL::GetFramebufferCopyTextureFormat() { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + return GL_RGB; +} + +OverlayCandidateValidator* +SkiaOutputSurfaceImplNonDDL::GetOverlayCandidateValidator() const { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + return nullptr; +} + +bool SkiaOutputSurfaceImplNonDDL::IsDisplayedAsOverlayPlane() const { + return false; +} + +unsigned SkiaOutputSurfaceImplNonDDL::GetOverlayTextureId() const { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + return 0; +} + +gfx::BufferFormat SkiaOutputSurfaceImplNonDDL::GetOverlayBufferFormat() const { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + return gfx::BufferFormat::RGBX_8888; +} + +bool SkiaOutputSurfaceImplNonDDL::HasExternalStencilTest() const { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + return false; +} + +void SkiaOutputSurfaceImplNonDDL::ApplyExternalStencil() { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); +} + +#if BUILDFLAG(ENABLE_VULKAN) +gpu::VulkanSurface* SkiaOutputSurfaceImplNonDDL::GetVulkanSurface() { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + NOTIMPLEMENTED(); + return nullptr; +} +#endif + +unsigned SkiaOutputSurfaceImplNonDDL::UpdateGpuFence() { + return 0; +} + +void SkiaOutputSurfaceImplNonDDL::SetNeedsSwapSizeNotifications( + bool needs_swap_size_notifications) { + needs_swap_size_notifications_ = needs_swap_size_notifications; +} + +SkCanvas* SkiaOutputSurfaceImplNonDDL::BeginPaintCurrentFrame() { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + DCHECK(sk_surface_); + DCHECK_EQ(current_render_pass_id_, 0u); + DCHECK_EQ(order_num_, 0u); + order_num_ = sync_point_order_data_->GenerateUnprocessedOrderNumber(); + sync_point_order_data_->BeginProcessingOrderNumber(order_num_); + + // If FBO is changed, we need call Reshape() to recreate |sk_surface_|. + if (backing_framebuffer_object_ != + gl_surface_->GetBackingFramebufferObject()) { + Reshape(reshape_surface_size_, reshape_device_scale_factor_, + reshape_color_space_, reshape_has_alpha_, reshape_use_stencil_); + } + + return sk_surface_->getCanvas(); +} + +sk_sp<SkImage> SkiaOutputSurfaceImplNonDDL::MakePromiseSkImage( + ResourceMetadata metadata) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + + GrBackendTexture backend_texture; + if (!GetGrBackendTexture(metadata, &backend_texture)) { + DLOG(ERROR) << "Failed to GetGrBackendTexture from mailbox."; + return nullptr; + } + + auto sk_color_type = ResourceFormatToClosestSkColorType( + true /* gpu_compositing */, metadata.resource_format); + return SkImage::MakeFromTexture( + gr_context(), backend_texture, kTopLeft_GrSurfaceOrigin, sk_color_type, + metadata.alpha_type, metadata.color_space.ToSkColorSpace()); +} + +sk_sp<SkImage> SkiaOutputSurfaceImplNonDDL::MakePromiseSkImageFromYUV( + std::vector<ResourceMetadata> metadatas, + SkYUVColorSpace yuv_color_space, + bool has_alpha) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + DCHECK((has_alpha && (metadatas.size() == 3 || metadatas.size() == 4)) || + (!has_alpha && (metadatas.size() == 2 || metadatas.size() == 3))); + + bool is_i420 = has_alpha ? metadatas.size() == 4 : metadatas.size() == 3; + + GrBackendFormat formats[4]; + SkYUVAIndex indices[4] = { + {-1, SkColorChannel::kR}, + {-1, SkColorChannel::kR}, + {-1, SkColorChannel::kR}, + {-1, SkColorChannel::kR}, + }; + GrBackendTexture yuva_textures[4] = {}; + const auto process_planar = [&](size_t i, ResourceFormat resource_format) { + auto& metadata = metadatas[i]; + metadata.resource_format = resource_format; + if (!GetGrBackendTexture(metadata, &yuva_textures[i])) + DLOG(ERROR) << "Failed to GetGrBackendTexture from a mailbox."; + }; + + if (is_i420) { + process_planar(0, RED_8); + indices[SkYUVAIndex::kY_Index].fIndex = 0; + indices[SkYUVAIndex::kY_Index].fChannel = SkColorChannel::kR; + + process_planar(1, RED_8); + indices[SkYUVAIndex::kU_Index].fIndex = 1; + indices[SkYUVAIndex::kU_Index].fChannel = SkColorChannel::kR; + + process_planar(2, RED_8); + indices[SkYUVAIndex::kV_Index].fIndex = 2; + indices[SkYUVAIndex::kV_Index].fChannel = SkColorChannel::kR; + if (has_alpha) { + process_planar(3, RED_8); + indices[SkYUVAIndex::kA_Index].fIndex = 3; + indices[SkYUVAIndex::kA_Index].fChannel = SkColorChannel::kR; + } + } else { + process_planar(0, RED_8); + indices[SkYUVAIndex::kY_Index].fIndex = 0; + indices[SkYUVAIndex::kY_Index].fChannel = SkColorChannel::kR; + + process_planar(1, RG_88); + indices[SkYUVAIndex::kU_Index].fIndex = 1; + indices[SkYUVAIndex::kU_Index].fChannel = SkColorChannel::kR; + + indices[SkYUVAIndex::kV_Index].fIndex = 1; + indices[SkYUVAIndex::kV_Index].fChannel = SkColorChannel::kG; + if (has_alpha) { + process_planar(2, RED_8); + indices[SkYUVAIndex::kA_Index].fIndex = 2; + indices[SkYUVAIndex::kA_Index].fChannel = SkColorChannel::kR; + } + } + + return SkImage::MakeFromYUVATextures( + gr_context(), yuv_color_space, yuva_textures, indices, + SkISize::Make(yuva_textures[0].width(), yuva_textures[1].height()), + kTopLeft_GrSurfaceOrigin); +} + +gpu::SyncToken SkiaOutputSurfaceImplNonDDL::ReleasePromiseSkImages( + std::vector<sk_sp<SkImage>> images) { + if (images.empty()) + return gpu::SyncToken(); + DCHECK_EQ(order_num_, 0u); + order_num_ = sync_point_order_data_->GenerateUnprocessedOrderNumber(); + sync_point_order_data_->BeginProcessingOrderNumber(order_num_); + gpu::SyncToken sync_token( + gpu::CommandBufferNamespace::VIZ_SKIA_OUTPUT_SURFACE_NON_DDL, + sync_point_client_state_->command_buffer_id(), ++sync_fence_release_); + sync_token.SetVerifyFlush(); + sync_point_client_state_->ReleaseFenceSync(sync_fence_release_); + DCHECK(mailbox_manager_->UsesSync()); + mailbox_manager_->PushTextureUpdates(sync_token); + sync_point_order_data_->FinishProcessingOrderNumber(order_num_); + order_num_ = 0u; + return sync_token; +} + +void SkiaOutputSurfaceImplNonDDL::SkiaSwapBuffers(OutputSurfaceFrame frame) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + gpu::SwapBuffersCompleteParams params; + params.swap_response.swap_start = base::TimeTicks::Now(); + params.swap_response.result = gl_surface_->SwapBuffers(base::BindOnce( + &SkiaOutputSurfaceImplNonDDL::BufferPresented, base::Unretained(this))); + params.swap_response.swap_end = base::TimeTicks::Now(); + + DidSwapBuffersComplete(params, gfx::Size()); +} + +SkCanvas* SkiaOutputSurfaceImplNonDDL::BeginPaintRenderPass( + const RenderPassId& id, + const gfx::Size& surface_size, + ResourceFormat format, + bool mipmap, + sk_sp<SkColorSpace> color_space) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + // Make sure there is no unsubmitted PaintFrame or PaintRenderPass. + DCHECK_EQ(current_render_pass_id_, 0u); + DCHECK_EQ(order_num_, 0u); + order_num_ = sync_point_order_data_->GenerateUnprocessedOrderNumber(); + sync_point_order_data_->BeginProcessingOrderNumber(order_num_); + current_render_pass_id_ = id; + auto& sk_surface = offscreen_sk_surfaces_[id]; + + if (!sk_surface) { + SkColorType color_type = + ResourceFormatToClosestSkColorType(true /* gpu_compositing */, format); + SkImageInfo image_info = SkImageInfo::Make( + surface_size.width(), surface_size.height(), color_type, + kPremul_SkAlphaType, std::move(color_space)); + sk_surface = + SkSurface::MakeRenderTarget(gr_context(), SkBudgeted::kNo, image_info); + } + return sk_surface->getCanvas(); +} + +gpu::SyncToken SkiaOutputSurfaceImplNonDDL::SubmitPaint() { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + + if (current_render_pass_id_ == 0) { + sk_surface_->flush(); + } else { + offscreen_sk_surfaces_[current_render_pass_id_]->flush(); + } + gpu::SyncToken sync_token( + gpu::CommandBufferNamespace::VIZ_SKIA_OUTPUT_SURFACE_NON_DDL, + sync_point_client_state_->command_buffer_id(), ++sync_fence_release_); + sync_token.SetVerifyFlush(); + sync_point_client_state_->ReleaseFenceSync(sync_fence_release_); + DCHECK(mailbox_manager_->UsesSync()); + mailbox_manager_->PushTextureUpdates(sync_token); + DCHECK_NE(order_num_, 0u); + sync_point_order_data_->FinishProcessingOrderNumber(order_num_); + order_num_ = 0u; + current_render_pass_id_ = 0; + return sync_token; +} + +sk_sp<SkImage> SkiaOutputSurfaceImplNonDDL::MakePromiseSkImageFromRenderPass( + const RenderPassId& id, + const gfx::Size& size, + ResourceFormat format, + bool mipmap, + sk_sp<SkColorSpace> color_space) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + + auto it = offscreen_sk_surfaces_.find(id); + DCHECK(it != offscreen_sk_surfaces_.end()); + return it->second->makeImageSnapshot(); +} + +void SkiaOutputSurfaceImplNonDDL::RemoveRenderPassResource( + std::vector<RenderPassId> ids) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + DCHECK(!ids.empty()); + + for (const auto& id : ids) { + auto it = offscreen_sk_surfaces_.find(id); + DCHECK(it != offscreen_sk_surfaces_.end()); + offscreen_sk_surfaces_.erase(it); + } +} + +void SkiaOutputSurfaceImplNonDDL::CopyOutput( + RenderPassId id, + const gfx::Rect& copy_rect, + const gfx::ColorSpace& color_space, + const gfx::Rect& result_rect, + std::unique_ptr<CopyOutputRequest> request) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + NOTIMPLEMENTED(); +} + +void SkiaOutputSurfaceImplNonDDL::AddContextLostObserver( + ContextLostObserver* observer) { + observers_.AddObserver(observer); +} + +void SkiaOutputSurfaceImplNonDDL::RemoveContextLostObserver( + ContextLostObserver* observer) { + observers_.RemoveObserver(observer); +} + +bool SkiaOutputSurfaceImplNonDDL::GetGrBackendTexture( + const ResourceMetadata& metadata, + GrBackendTexture* backend_texture) { + DCHECK(!metadata.mailbox_holder.mailbox.IsZero()); + + base::WaitableEvent event; + if (sync_point_client_state_->Wait( + metadata.mailbox_holder.sync_token, + base::BindOnce(&base::WaitableEvent::Signal, + base::Unretained(&event)))) { + event.Wait(); + DCHECK(mailbox_manager_->UsesSync()); + mailbox_manager_->PullTextureUpdates(metadata.mailbox_holder.sync_token); + } + + if (metadata.mailbox_holder.mailbox.IsSharedImage()) { + // TODO(https://crbug.com/900973): support shared image. + } + + auto* texture_base = + mailbox_manager_->ConsumeTexture(metadata.mailbox_holder.mailbox); + if (!texture_base) { + DLOG(ERROR) << "Failed to make the SkImage"; + return false; + } + + auto* gl_version_info = + shared_context_state_->real_context()->GetVersionInfo(); + return gpu::GetGrBackendTexture(gl_version_info, texture_base->target(), + metadata.size, texture_base->service_id(), + metadata.resource_format, backend_texture); +} + +void SkiaOutputSurfaceImplNonDDL::DidSwapBuffersComplete( + const gpu::SwapBuffersCompleteParams& params, + const gfx::Size& pixel_size) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + DCHECK(client_); + + DCHECK(params.texture_in_use_responses.empty()); + DCHECK(params.ca_layer_params.is_empty); + + client_->DidReceiveSwapBuffersAck(); + if (needs_swap_size_notifications_) + client_->DidSwapWithSize(pixel_size); +} + +void SkiaOutputSurfaceImplNonDDL::BufferPresented( + const gfx::PresentationFeedback& feedback) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + DCHECK(client_); + client_->DidReceivePresentationFeedback(feedback); +} + +void SkiaOutputSurfaceImplNonDDL::ContextLost() { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + for (auto& observer : observers_) + observer.OnContextLost(); +} + +} // namespace viz
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.h b/components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.h new file mode 100644 index 0000000..ebfba74 --- /dev/null +++ b/components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.h
@@ -0,0 +1,162 @@ +// 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. + +#ifndef COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_SURFACE_IMPL_NON_DDL_H_ +#define COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_SURFACE_IMPL_NON_DDL_H_ + +#include <memory> +#include <vector> + +#include "base/containers/flat_map.h" +#include "base/macros.h" +#include "base/observer_list.h" +#include "base/threading/thread_checker.h" +#include "components/viz/service/display/skia_output_surface.h" +#include "components/viz/service/viz_service_export.h" +#include "gpu/command_buffer/common/sync_token.h" +#include "gpu/command_buffer/service/shared_context_state.h" + +namespace gl { +class GLSurface; +} + +namespace gfx { +struct PresentationFeedback; +} + +namespace gpu { +class MailboxManager; +struct SwapBuffersCompleteParams; +class SyncPointClientState; +class SyncPointManager; +class SyncPointOrderData; +} // namespace gpu + +namespace viz { + +// A SkiaOutputSurface implementation for running SkiaRenderer on GpuThread. +// Comparing to SkiaOutputSurfaceImpl, it will issue skia draw operations +// against OS graphics API (GL, Vulkan, etc) instead of recording deferred +// display list first. +class VIZ_SERVICE_EXPORT SkiaOutputSurfaceImplNonDDL + : public SkiaOutputSurface { + public: + SkiaOutputSurfaceImplNonDDL( + scoped_refptr<gl::GLSurface> gl_surface, + scoped_refptr<gpu::SharedContextState> shared_context_state, + gpu::MailboxManager* mailbox_manager, + gpu::SyncPointManager* sync_point_manager); + ~SkiaOutputSurfaceImplNonDDL() override; + + // OutputSurface implementation: + void BindToClient(OutputSurfaceClient* client) override; + void EnsureBackbuffer() override; + void DiscardBackbuffer() override; + void BindFramebuffer() override; + void SetDrawRectangle(const gfx::Rect& draw_rectangle) override; + void Reshape(const gfx::Size& size, + float device_scale_factor, + const gfx::ColorSpace& color_space, + bool has_alpha, + bool use_stencil) override; + void SwapBuffers(OutputSurfaceFrame frame) override; + uint32_t GetFramebufferCopyTextureFormat() override; + OverlayCandidateValidator* GetOverlayCandidateValidator() const override; + bool IsDisplayedAsOverlayPlane() const override; + unsigned GetOverlayTextureId() const override; + gfx::BufferFormat GetOverlayBufferFormat() const override; + bool HasExternalStencilTest() const override; + void ApplyExternalStencil() override; +#if BUILDFLAG(ENABLE_VULKAN) + gpu::VulkanSurface* GetVulkanSurface() override; +#endif + unsigned UpdateGpuFence() override; + void SetNeedsSwapSizeNotifications( + bool needs_swap_size_notifications) override; + + // SkiaOutputSurface implementation: + SkCanvas* BeginPaintCurrentFrame() override; + sk_sp<SkImage> MakePromiseSkImageFromYUV( + std::vector<ResourceMetadata> metadatas, + SkYUVColorSpace yuv_color_space, + bool has_alpha) override; + void SkiaSwapBuffers(OutputSurfaceFrame frame) override; + SkCanvas* BeginPaintRenderPass(const RenderPassId& id, + const gfx::Size& surface_size, + ResourceFormat format, + bool mipmap, + sk_sp<SkColorSpace> color_space) override; + gpu::SyncToken SubmitPaint() override; + sk_sp<SkImage> MakePromiseSkImage(ResourceMetadata metadata) override; + sk_sp<SkImage> MakePromiseSkImageFromRenderPass( + const RenderPassId& id, + const gfx::Size& size, + ResourceFormat format, + bool mipmap, + sk_sp<SkColorSpace> color_space) override; + gpu::SyncToken ReleasePromiseSkImages( + std::vector<sk_sp<SkImage>> images) override; + + void RemoveRenderPassResource(std::vector<RenderPassId> ids) override; + void CopyOutput(RenderPassId id, + const gfx::Rect& copy_rect, + const gfx::ColorSpace& color_space, + const gfx::Rect& result_rect, + std::unique_ptr<CopyOutputRequest> request) override; + void AddContextLostObserver(ContextLostObserver* observer) override; + void RemoveContextLostObserver(ContextLostObserver* observer) override; + + private: + GrContext* gr_context() { return shared_context_state_->gr_context(); } + + bool GetGrBackendTexture(const ResourceMetadata& metadata, + GrBackendTexture* backend_texture); + + void DidSwapBuffersComplete(const gpu::SwapBuffersCompleteParams& params, + const gfx::Size& pixel_size); + void BufferPresented(const gfx::PresentationFeedback& feedback); + void ContextLost(); + + uint64_t sync_fence_release_ = 0; + + // Stuffs for running with |task_executor_| instead of |gpu_service_|. + scoped_refptr<gl::GLSurface> gl_surface_; + scoped_refptr<gpu::SharedContextState> shared_context_state_; + gpu::MailboxManager* mailbox_manager_; + scoped_refptr<gpu::SyncPointOrderData> sync_point_order_data_; + scoped_refptr<gpu::SyncPointClientState> sync_point_client_state_; + uint32_t order_num_ = 0u; + + OutputSurfaceClient* client_ = nullptr; + + unsigned int backing_framebuffer_object_ = 0; + gfx::Size reshape_surface_size_; + float reshape_device_scale_factor_ = 0.f; + gfx::ColorSpace reshape_color_space_; + bool reshape_has_alpha_ = false; + bool reshape_use_stencil_ = false; + + // The current render pass id set by BeginPaintRenderPass. + RenderPassId current_render_pass_id_ = 0; + + // Whether to send OutputSurfaceClient::DidSwapWithSize notifications. + bool needs_swap_size_notifications_ = false; + + // Observers for context lost. + base::ObserverList<ContextLostObserver>::Unchecked observers_; + + // The SkSurface for the framebuffer. + sk_sp<SkSurface> sk_surface_; + + // Offscreen SkSurfaces for render passes. + base::flat_map<RenderPassId, sk_sp<SkSurface>> offscreen_sk_surfaces_; + + THREAD_CHECKER(thread_checker_); + + DISALLOW_COPY_AND_ASSIGN(SkiaOutputSurfaceImplNonDDL); +}; + +} // namespace viz + +#endif // COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_SURFACE_IMPL_NON_DDL_H_
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 716cf11..36cefca4 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
@@ -91,7 +91,7 @@ auto command_buffer_id = gpu::CommandBufferId::FromUnsafeValue( g_next_command_buffer_id.GetNext() + 1); return gpu_service->sync_point_manager()->CreateSyncPointClientState( - gpu::CommandBufferNamespace::VIZ_OUTPUT_SURFACE, command_buffer_id, + gpu::CommandBufferNamespace::VIZ_SKIA_OUTPUT_SURFACE, command_buffer_id, gpu_service->skia_output_surface_sequence_id()); } @@ -101,7 +101,7 @@ auto command_buffer_id = gpu::CommandBufferId::FromUnsafeValue( g_next_command_buffer_id.GetNext() + 1); return task_executor->sync_point_manager()->CreateSyncPointClientState( - gpu::CommandBufferNamespace::VIZ_OUTPUT_SURFACE, command_buffer_id, + gpu::CommandBufferNamespace::VIZ_SKIA_OUTPUT_SURFACE, command_buffer_id, sequence_id); } @@ -912,8 +912,9 @@ // context, PullTextureUpdates(token) will wait the GL fence associated with // the give token on the current GL context. // Reconstruct sync_token from sync_fence_release. - gpu::SyncToken sync_token(gpu::CommandBufferNamespace::VIZ_OUTPUT_SURFACE, - command_buffer_id(), sync_fence_release); + gpu::SyncToken sync_token( + gpu::CommandBufferNamespace::VIZ_SKIA_OUTPUT_SURFACE, + command_buffer_id(), sync_fence_release); mailbox_manager_->PushTextureUpdates(sync_token); } sync_point_client_state_->ReleaseFenceSync(sync_fence_release);
diff --git a/components/webdata/common/web_database_migration_unittest.cc b/components/webdata/common/web_database_migration_unittest.cc index 2f0dcc0..eb338ba 100644 --- a/components/webdata/common/web_database_migration_unittest.cc +++ b/components/webdata/common/web_database_migration_unittest.cc
@@ -156,7 +156,7 @@ connection.Raze(); const base::FilePath& file_name = base::FilePath::FromUTF8Unsafe( - "version_" + base::IntToString(i) + ".sql"); + "version_" + base::NumberToString(i) + ".sql"); ASSERT_NO_FATAL_FAILURE(LoadDatabase(file_name.value())) << "Failed to load " << file_name.MaybeAsASCII(); DoMigration();
diff --git a/components/zucchini/main_utils.cc b/components/zucchini/main_utils.cc index 6a09b32..3e6ff2d 100644 --- a/components/zucchini/main_utils.cc +++ b/components/zucchini/main_utils.cc
@@ -91,7 +91,7 @@ *resident_set_size_hwm = 0; auto status_path = base::FilePath("/proc") - .Append(base::IntToString(base::GetCurrentProcessHandle())) + .Append(base::NumberToString(base::GetCurrentProcessHandle())) .Append("status"); std::string contents_string; base::ReadFileToString(status_path, &contents_string);
diff --git a/content/app/BUILD.gn b/content/app/BUILD.gn index 14123c2..727f5f95 100644 --- a/content/app/BUILD.gn +++ b/content/app/BUILD.gn
@@ -30,7 +30,6 @@ "//crypto", "//services/service_manager/embedder", "//services/service_manager/public/mojom", - "//services/service_manager/runner/common", "//services/tracing/public/cpp", "//mojo/core/embedder", "//ppapi/buildflags",
diff --git a/content/app/DEPS b/content/app/DEPS index 5e3c905..dfe3826d 100644 --- a/content/app/DEPS +++ b/content/app/DEPS
@@ -11,6 +11,5 @@ "+services/network/public/cpp/features.h", "+services/tracing/public/cpp", "+services/service_manager/embedder", - "+services/service_manager/runner/common", "+services/service_manager/sandbox/sandbox_type.h", ]
diff --git a/content/app/content_service_manager_main_delegate.cc b/content/app/content_service_manager_main_delegate.cc index 3a6bc4e..c8a728e7 100644 --- a/content/app/content_service_manager_main_delegate.cc +++ b/content/app/content_service_manager_main_delegate.cc
@@ -10,7 +10,6 @@ #include "content/public/common/content_switches.h" #include "content/public/common/service_names.mojom.h" #include "services/service_manager/embedder/switches.h" -#include "services/service_manager/runner/common/client_util.h" namespace content { @@ -68,10 +67,10 @@ mojo::core::Configuration* config) { // If this is the browser process and there's no remote service manager, we // will serve as the global Mojo broker. - if (!service_manager::ServiceManagerIsRemote() && - !base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kProcessType)) + if (!base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kProcessType)) { config->is_broker_process = true; + } } std::vector<service_manager::Manifest>
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index fe1d609..551fc8c 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -158,7 +158,6 @@ "//services/service_manager/embedder:embedder_result_codes", "//services/service_manager/public/cpp", "//services/service_manager/public/mojom", - "//services/service_manager/runner/common", "//services/service_manager/zygote:zygote_buildflags", "//services/shape_detection:lib", "//services/shape_detection/public/mojom", @@ -1596,8 +1595,6 @@ "screenlock_monitor/screenlock_monitor_device_source_win.cc", "screenlock_monitor/screenlock_monitor_source.cc", "screenlock_monitor/screenlock_monitor_source.h", - "serial/serial_service.cc", - "serial/serial_service.h", "service_manager/common_browser_interfaces.cc", "service_manager/common_browser_interfaces.h", "service_manager/service_manager_context.cc", @@ -2084,6 +2081,8 @@ "plugin_content_origin_whitelist.h", "plugin_data_remover_impl.cc", "plugin_data_remover_impl.h", + "plugin_list.cc", + "plugin_list.h", "plugin_private_storage_helper.cc", "plugin_private_storage_helper.h", "plugin_service_impl.cc", @@ -2374,6 +2373,10 @@ "host_zoom_map_observer.cc", "host_zoom_map_observer.h", + # The Serial API is not implemented on Android. + "serial/serial_service.cc", + "serial/serial_service.h", + # Most speech code is non-Android. "speech/audio_buffer.cc", "speech/audio_buffer.h",
diff --git a/content/browser/appcache/appcache_fuzzer.cc b/content/browser/appcache/appcache_fuzzer.cc index e57ec16..5c2bc890 100644 --- a/content/browser/appcache/appcache_fuzzer.cc +++ b/content/browser/appcache/appcache_fuzzer.cc
@@ -48,7 +48,8 @@ scoped_refptr<URLLoaderFactoryGetter> loader_factory_getter = base::MakeRefCounted<URLLoaderFactoryGetter>(); - loader_factory_getter->SetNetworkFactoryForTesting(mock_url_loader_factory); + loader_factory_getter->SetNetworkFactoryForTesting( + mock_url_loader_factory, /* is_corb_enabled = */ true); appcache_service->set_url_loader_factory_getter( loader_factory_getter.get());
diff --git a/content/browser/appcache/appcache_storage_impl_unittest.cc b/content/browser/appcache/appcache_storage_impl_unittest.cc index 32e6017..f90061f6 100644 --- a/content/browser/appcache/appcache_storage_impl_unittest.cc +++ b/content/browser/appcache/appcache_storage_impl_unittest.cc
@@ -1657,7 +1657,7 @@ service_.reset(new AppCacheServiceImpl(nullptr)); auto loader_factory_getter = base::MakeRefCounted<URLLoaderFactoryGetter>(); loader_factory_getter->SetNetworkFactoryForTesting( - &mock_url_loader_factory_); + &mock_url_loader_factory_, /* is_corb_enabled = */ true); service_->set_url_loader_factory_getter(loader_factory_getter.get()); service_->Initialize(temp_directory_.GetPath());
diff --git a/content/browser/appcache/appcache_update_job_unittest.cc b/content/browser/appcache/appcache_update_job_unittest.cc index 87858a0..8d3ced60 100644 --- a/content/browser/appcache/appcache_update_job_unittest.cc +++ b/content/browser/appcache/appcache_update_job_unittest.cc
@@ -748,7 +748,7 @@ if (!loader_factory_getter_.get()) return; loader_factory_getter_->SetNetworkFactoryForTesting( - &mock_url_loader_factory_); + &mock_url_loader_factory_, /* is_corb_enabled = */ true); } void StartCacheAttemptTest() {
diff --git a/content/browser/appcache/appcache_update_url_loader_request.cc b/content/browser/appcache/appcache_update_url_loader_request.cc index c22cb619..d43a7cb 100644 --- a/content/browser/appcache/appcache_update_url_loader_request.cc +++ b/content/browser/appcache/appcache_update_url_loader_request.cc
@@ -54,10 +54,11 @@ network::mojom::URLLoaderClientPtr client; client_binding_.Bind(mojo::MakeRequest(&client)); - loader_factory_getter_->GetNetworkFactory()->CreateLoaderAndStart( - mojo::MakeRequest(&url_loader_), -1, -1, - network::mojom::kURLLoadOptionNone, request_, std::move(client), - net::MutableNetworkTrafficAnnotationTag(kAppCacheTrafficAnnotation)); + loader_factory_getter_->GetNetworkFactoryWithCORBEnabled() + ->CreateLoaderAndStart( + mojo::MakeRequest(&url_loader_), -1, -1, + network::mojom::kURLLoadOptionNone, request_, std::move(client), + net::MutableNetworkTrafficAnnotationTag(kAppCacheTrafficAnnotation)); } void AppCacheUpdateJob::UpdateURLLoaderRequest::SetExtraRequestHeaders(
diff --git a/content/browser/background_fetch/background_fetch_data_manager_unittest.cc b/content/browser/background_fetch/background_fetch_data_manager_unittest.cc index df338ce..99c2738 100644 --- a/content/browser/background_fetch/background_fetch_data_manager_unittest.cc +++ b/content/browser/background_fetch/background_fetch_data_manager_unittest.cc
@@ -394,7 +394,7 @@ // BackgroundFetchDataManager::MatchRequests(). void MatchRequests(const BackgroundFetchRegistrationId& registration_id, blink::mojom::FetchAPIRequestPtr request_to_match, - blink::mojom::QueryParamsPtr cache_query_params, + blink::mojom::CacheQueryOptionsPtr cache_query_options, bool match_all, blink::mojom::BackgroundFetchError* out_error, std::vector<blink::mojom::BackgroundFetchSettledFetchPtr>* @@ -404,7 +404,7 @@ base::RunLoop run_loop; auto match_params = std::make_unique<BackgroundFetchRequestMatchParams>( - std::move(request_to_match), std::move(cache_query_params), match_all); + std::move(request_to_match), std::move(cache_query_options), match_all); background_fetch_data_manager_->MatchRequests( registration_id, std::move(match_params), base::BindOnce(&BackgroundFetchDataManagerTest::DidMatchRequests, @@ -471,11 +471,11 @@ CacheStorageHandle cache_storage = background_fetch_data_manager_->cache_manager()->OpenCacheStorage( origin(), CacheStorageOwner::kBackgroundFetch); - auto match_params = blink::mojom::QueryParams::New(); - match_params->ignore_search = true; + auto match_options = blink::mojom::CacheQueryOptions::New(); + match_options->ignore_search = true; cache_storage.value()->MatchCache( kExampleUniqueId, BackgroundFetchSettledFetch::CloneRequest(request), - std::move(match_params), + std::move(match_options), base::BindOnce(&BackgroundFetchDataManagerTest::DidMatchCache, base::Unretained(this), run_loop.QuitClosure(), &result)); @@ -509,8 +509,9 @@ blink::mojom::OperationType::kDelete; operation_ptr_vec[0]->request = BackgroundFetchSettledFetch::CloneRequest(request); - operation_ptr_vec[0]->match_params = blink::mojom::QueryParams::New(); - operation_ptr_vec[0]->match_params->ignore_search = true; + operation_ptr_vec[0]->match_options = + blink::mojom::CacheQueryOptions::New(); + operation_ptr_vec[0]->match_options->ignore_search = true; handle.value()->BatchOperation( std::move(operation_ptr_vec), /* fail_on_duplicates= */ true, base::BindOnce(&BackgroundFetchDataManagerTest::DidDeleteFromCache, @@ -1810,7 +1811,7 @@ // Nothing is downloaded yet. std::vector<blink::mojom::BackgroundFetchSettledFetchPtr> settled_fetches; MatchRequests(registration_id, /* request_to_match= */ nullptr, - /* cache_query_params= */ nullptr, /* match_all= */ true, + /* cache_query_options= */ nullptr, /* match_all= */ true, &error, &settled_fetches); EXPECT_EQ(error, blink::mojom::BackgroundFetchError::NONE); EXPECT_EQ(settled_fetches.size(), num_requests); @@ -1833,7 +1834,7 @@ /* completed_requests= */ num_requests})); MatchRequests(registration_id, /* request_to_match= */ nullptr, - /* cache_query_params= */ nullptr, /* match_all= */ true, + /* cache_query_options= */ nullptr, /* match_all= */ true, &error, &settled_fetches); EXPECT_EQ(error, blink::mojom::BackgroundFetchError::NONE); @@ -1865,7 +1866,7 @@ std::vector<blink::mojom::BackgroundFetchSettledFetchPtr> settled_fetches; MatchRequests(registration_id, /* request_to_match= */ nullptr, - /* cache_query_params= */ nullptr, /* match_all= */ true, + /* cache_query_options= */ nullptr, /* match_all= */ true, &error, &settled_fetches); EXPECT_EQ(error, blink::mojom::BackgroundFetchError::NONE); ASSERT_EQ(settled_fetches.size(), 2u); @@ -1901,7 +1902,7 @@ std::vector<blink::mojom::BackgroundFetchSettledFetchPtr> settled_fetches; // Nothing is downloaded yet. MatchRequests(registration_id, /* request_to_match= */ nullptr, - /* cache_query_params= */ nullptr, /* match_all= */ true, + /* cache_query_options= */ nullptr, /* match_all= */ true, &error, &settled_fetches); EXPECT_EQ(error, blink::mojom::BackgroundFetchError::NONE); EXPECT_EQ(settled_fetches.size(), requests.size()); @@ -1920,7 +1921,7 @@ RestartDataManagerFromPersistentStorage(); MatchRequests(registration_id, /* request_to_match= */ nullptr, - /* cache_query_params= */ nullptr, /* match_all= */ true, + /* cache_query_options= */ nullptr, /* match_all= */ true, &error, &settled_fetches); EXPECT_EQ(error, blink::mojom::BackgroundFetchError::NONE); ASSERT_EQ(settled_fetches.size(), requests.size()); @@ -1976,7 +1977,7 @@ std::vector<blink::mojom::BackgroundFetchSettledFetchPtr> settled_fetches; MatchRequests(registration_id, /* request_to_match= */ std::move(requests[0]), - /* cache_query_params= */ nullptr, /* match_all= */ false, + /* cache_query_options= */ nullptr, /* match_all= */ false, &error, &settled_fetches); ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); // We are marking the responses as failed in Download Manager. @@ -1987,7 +1988,7 @@ non_existing_request->url = GURL("https://example.com/missing-file.txt"); MatchRequests(registration_id, /* request_to_match= */ std::move(non_existing_request), - /* cache_query_params= */ nullptr, /* match_all= */ false, + /* cache_query_options= */ nullptr, /* match_all= */ false, &error, &settled_fetches); EXPECT_TRUE(settled_fetches.empty()); } @@ -2028,7 +2029,7 @@ std::vector<blink::mojom::BackgroundFetchSettledFetchPtr> settled_fetches; MatchRequests(registration_id, /* request_to_match= */ std::move(requests[2]), - /* cache_query_params= */ nullptr, /* match_all= */ false, + /* cache_query_options= */ nullptr, /* match_all= */ false, &error, &settled_fetches); ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); ASSERT_EQ(settled_fetches.size(), 1u); @@ -2073,11 +2074,11 @@ /* completed_requests= */ requests.size()})); std::vector<blink::mojom::BackgroundFetchSettledFetchPtr> settled_fetches; - blink::mojom::QueryParamsPtr cache_query_params = - blink::mojom::QueryParams::New(); - cache_query_params->ignore_method = true; + blink::mojom::CacheQueryOptionsPtr cache_query_options = + blink::mojom::CacheQueryOptions::New(); + cache_query_options->ignore_method = true; MatchRequests(registration_id, /* request_to_match= */ std::move(requests[0]), - std::move(cache_query_params), /* match_all= */ true, &error, + std::move(cache_query_options), /* match_all= */ true, &error, &settled_fetches); ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); @@ -2139,29 +2140,29 @@ std::vector<blink::mojom::BackgroundFetchSettledFetchPtr> settled_fetches; auto request_to_match = BackgroundFetchSettledFetch::CloneRequest(requests[0]); - auto query_params = blink::mojom::QueryParams::New(); + auto query_options = blink::mojom::CacheQueryOptions::New(); MatchRequests(registration_id, BackgroundFetchSettledFetch::CloneRequest(request_to_match), - query_params->Clone(), /* match_all= */ true, &error, + query_options->Clone(), /* match_all= */ true, &error, &settled_fetches); EXPECT_EQ(error, blink::mojom::BackgroundFetchError::NONE); // Match only the GETs with the same url. EXPECT_EQ(settled_fetches.size(), 2u); - query_params->ignore_search = true; + query_options->ignore_search = true; MatchRequests(registration_id, BackgroundFetchSettledFetch::CloneRequest(request_to_match), - query_params->Clone(), /* match_all= */ true, &error, + query_options->Clone(), /* match_all= */ true, &error, &settled_fetches); EXPECT_EQ(error, blink::mojom::BackgroundFetchError::NONE); // Match only the GETs with the same url path. EXPECT_EQ(settled_fetches.size(), 5u); - query_params->ignore_method = true; + query_options->ignore_method = true; MatchRequests(registration_id, BackgroundFetchSettledFetch::CloneRequest(request_to_match), - query_params->Clone(), /* match_all= */ true, &error, + query_options->Clone(), /* match_all= */ true, &error, &settled_fetches); EXPECT_EQ(error, blink::mojom::BackgroundFetchError::NONE); // Match everything. @@ -2436,7 +2437,7 @@ { MatchRequests(registration_id, /* request_to_match= */ nullptr, - /* cache_query_params= */ nullptr, /* match_all= */ false, + /* cache_query_options= */ nullptr, /* match_all= */ false, &error, &settled_fetches); ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); @@ -2451,7 +2452,7 @@ { base::HistogramTester histogram_tester; MatchRequests(registration_id, /* request_to_match= */ nullptr, - /* cache_query_params= */ nullptr, /* match_all= */ true, + /* cache_query_options= */ nullptr, /* match_all= */ true, &error, &settled_fetches); ASSERT_EQ(error, blink::mojom::BackgroundFetchError::STORAGE_ERROR); @@ -2576,7 +2577,7 @@ std::vector<blink::mojom::BackgroundFetchSettledFetchPtr> settled_fetches; blink::mojom::BackgroundFetchError error; MatchRequests(registration_id, /* request_to_match= */ nullptr, - /* cache_query_params= */ nullptr, /* match_all= */ true, + /* cache_query_options= */ nullptr, /* match_all= */ true, &error, &settled_fetches); ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); ASSERT_EQ(settled_fetches.size(), requests.size());
diff --git a/content/browser/background_fetch/background_fetch_delegate_proxy.cc b/content/browser/background_fetch/background_fetch_delegate_proxy.cc index 30509f72..31686f8 100644 --- a/content/browser/background_fetch/background_fetch_delegate_proxy.cc +++ b/content/browser/background_fetch/background_fetch_delegate_proxy.cc
@@ -429,10 +429,11 @@ reason_to_abort == blink::mojom::BackgroundFetchFailureReason::DOWNLOAD_TOTAL_EXCEEDED); - DCHECK(controller_map_.count(job_unique_id)); - auto& controller = controller_map_[job_unique_id]; + auto it = controller_map_.find(job_unique_id); + if (it == controller_map_.end()) + return; - if (controller) + if (const auto& controller = it->second) controller->AbortFromDelegate(reason_to_abort); } @@ -442,10 +443,11 @@ std::unique_ptr<BackgroundFetchResponse> response) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - DCHECK(controller_map_.count(job_unique_id)); - auto& controller = controller_map_[job_unique_id]; + auto it = controller_map_.find(job_unique_id); + if (it == controller_map_.end()) + return; - if (controller) + if (const auto& controller = it->second) controller->DidStartRequest(guid, std::move(response)); } @@ -458,9 +460,10 @@ void BackgroundFetchDelegateProxy::DidUpdateUI( const std::string& job_unique_id) { auto it = update_ui_callback_map_.find(job_unique_id); - DCHECK(it != update_ui_callback_map_.end()); - DCHECK(it->second); + if (it == update_ui_callback_map_.end()) + return; + DCHECK(it->second); std::move(it->second).Run(blink::mojom::BackgroundFetchError::NONE); update_ui_callback_map_.erase(it); } @@ -472,12 +475,12 @@ uint64_t bytes_downloaded) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - DCHECK(controller_map_.count(job_unique_id)); - auto& controller = controller_map_[job_unique_id]; + auto it = controller_map_.find(job_unique_id); + if (it == controller_map_.end()) + return; - if (controller) { + if (const auto& controller = it->second) controller->DidUpdateRequest(guid, bytes_uploaded, bytes_downloaded); - } } void BackgroundFetchDelegateProxy::OnDownloadComplete( @@ -486,10 +489,11 @@ std::unique_ptr<BackgroundFetchResult> result) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - DCHECK(controller_map_.count(job_unique_id)); - auto& controller = controller_map_[job_unique_id]; + auto it = controller_map_.find(job_unique_id); + if (it == controller_map_.end()) + return; - if (controller) + if (const auto& controller = it->second) controller->DidCompleteRequest(guid, std::move(result)); } @@ -497,10 +501,13 @@ const std::string& job_unique_id, const std::string& download_guid, BackgroundFetchDelegate::GetUploadDataCallback callback) { - DCHECK(controller_map_.count(job_unique_id)); - auto& controller = controller_map_[job_unique_id]; + auto it = controller_map_.find(job_unique_id); + if (it == controller_map_.end()) { + std::move(callback).Run(nullptr); + return; + } - if (controller) + if (const auto& controller = it->second) controller->GetUploadData(download_guid, std::move(callback)); else std::move(callback).Run(nullptr);
diff --git a/content/browser/background_fetch/background_fetch_request_match_params.cc b/content/browser/background_fetch/background_fetch_request_match_params.cc index 88d99d9..effc4d3 100644 --- a/content/browser/background_fetch/background_fetch_request_match_params.cc +++ b/content/browser/background_fetch/background_fetch_request_match_params.cc
@@ -4,14 +4,16 @@ #include "content/browser/background_fetch/background_fetch_request_match_params.h" +#include <utility> + namespace content { BackgroundFetchRequestMatchParams::BackgroundFetchRequestMatchParams( blink::mojom::FetchAPIRequestPtr request_to_match, - blink::mojom::QueryParamsPtr cache_query_params, + blink::mojom::CacheQueryOptionsPtr cache_query_options, bool match_all) : request_to_match_(std::move(request_to_match)), - cache_query_params_(std::move(cache_query_params)), + cache_query_options_(std::move(cache_query_options)), match_all_(match_all) {} BackgroundFetchRequestMatchParams::BackgroundFetchRequestMatchParams() = @@ -19,4 +21,4 @@ BackgroundFetchRequestMatchParams::~BackgroundFetchRequestMatchParams() = default; -} // namespace content \ No newline at end of file +} // namespace content
diff --git a/content/browser/background_fetch/background_fetch_request_match_params.h b/content/browser/background_fetch/background_fetch_request_match_params.h index 8dab5fe..e1b0def 100644 --- a/content/browser/background_fetch/background_fetch_request_match_params.h +++ b/content/browser/background_fetch/background_fetch_request_match_params.h
@@ -16,7 +16,7 @@ BackgroundFetchRequestMatchParams(); BackgroundFetchRequestMatchParams( blink::mojom::FetchAPIRequestPtr request_to_match, - blink::mojom::QueryParamsPtr cache_query_params, + blink::mojom::CacheQueryOptionsPtr cache_query_options, bool match_all); ~BackgroundFetchRequestMatchParams(); @@ -28,14 +28,14 @@ return request_to_match_; } - const blink::mojom::QueryParamsPtr& cache_query_params() const { - return cache_query_params_; + const blink::mojom::CacheQueryOptionsPtr& cache_query_options() const { + return cache_query_options_; } - blink::mojom::QueryParamsPtr cloned_cache_query_params() const { - if (!cache_query_params_) + blink::mojom::CacheQueryOptionsPtr cloned_cache_query_options() const { + if (!cache_query_options_) return nullptr; - return cache_query_params_->Clone(); + return cache_query_options_->Clone(); } bool match_all() const { return match_all_; } @@ -47,7 +47,7 @@ blink::mojom::FetchAPIRequestPtr request_to_match_; // When nullptr, this has no effect on the response(s) returned. - blink::mojom::QueryParamsPtr cache_query_params_; + blink::mojom::CacheQueryOptionsPtr cache_query_options_; // Whether to return all matching responses from the cache storage. bool match_all_ = false;
diff --git a/content/browser/background_fetch/background_fetch_service_impl.cc b/content/browser/background_fetch/background_fetch_service_impl.cc index 718f19c..a19d291 100644 --- a/content/browser/background_fetch/background_fetch_service_impl.cc +++ b/content/browser/background_fetch/background_fetch_service_impl.cc
@@ -161,16 +161,16 @@ const std::string& developer_id, const std::string& unique_id, blink::mojom::FetchAPIRequestPtr request_to_match, - blink::mojom::QueryParamsPtr cache_query_params, + blink::mojom::CacheQueryOptionsPtr cache_query_options, bool match_all, MatchRequestsCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); BackgroundFetchRegistrationId registration_id( service_worker_registration_id, origin_, developer_id, unique_id); - // Create BackgroundFetchMatchRequestParams. + // Create BackgroundFetchMatchRequestMatchParams. auto match_params = std::make_unique<BackgroundFetchRequestMatchParams>( - std::move(request_to_match), std::move(cache_query_params), match_all); + std::move(request_to_match), std::move(cache_query_options), match_all); background_fetch_context_->MatchRequests( registration_id, std::move(match_params), std::move(callback));
diff --git a/content/browser/background_fetch/background_fetch_service_impl.h b/content/browser/background_fetch/background_fetch_service_impl.h index 4016d96..dd5bdade 100644 --- a/content/browser/background_fetch/background_fetch_service_impl.h +++ b/content/browser/background_fetch/background_fetch_service_impl.h
@@ -55,7 +55,7 @@ const std::string& developer_id, const std::string& unique_id, blink::mojom::FetchAPIRequestPtr request_to_match, - blink::mojom::QueryParamsPtr cache_query_params, + blink::mojom::CacheQueryOptionsPtr cache_query_options, bool match_all, MatchRequestsCallback callback) override; void UpdateUI(int64_t service_worker_registration_id,
diff --git a/content/browser/background_fetch/background_fetch_service_unittest.cc b/content/browser/background_fetch/background_fetch_service_unittest.cc index ac2e1b3..060344b 100644 --- a/content/browser/background_fetch/background_fetch_service_unittest.cc +++ b/content/browser/background_fetch/background_fetch_service_unittest.cc
@@ -202,7 +202,7 @@ service_->MatchRequests( service_worker_registration_id, developer_id, unique_id, /* request_to_match= */ nullptr, - /* cache_query_params= */ nullptr, /* match_all= */ true, + /* cache_query_options= */ nullptr, /* match_all= */ true, base::BindOnce(&BackgroundFetchServiceTest::DidMatchAllRequests, base::Unretained(this), run_loop.QuitClosure(), out_fetches));
diff --git a/content/browser/background_fetch/storage/get_initialization_data_task.cc b/content/browser/background_fetch/storage/get_initialization_data_task.cc index 7360a21..69beeeecd 100644 --- a/content/browser/background_fetch/storage/get_initialization_data_task.cc +++ b/content/browser/background_fetch/storage/get_initialization_data_task.cc
@@ -432,7 +432,7 @@ DCHECK(handle.value()); // Get all entries in the cache. handle.value()->GetAllMatchedEntries( - /* request= */ nullptr, /* query_params= */ nullptr, + /* request= */ nullptr, /* query_options= */ nullptr, base::BindOnce(&CacheStorageMigrationTask::DidGetAllMatchedEntries, weak_factory_.GetWeakPtr(), handle.Clone())); }
diff --git a/content/browser/background_fetch/storage/get_request_blob_task.cc b/content/browser/background_fetch/storage/get_request_blob_task.cc index 38efc71..9535a35f 100644 --- a/content/browser/background_fetch/storage/get_request_blob_task.cc +++ b/content/browser/background_fetch/storage/get_request_blob_task.cc
@@ -46,7 +46,7 @@ request_info_->request_index()); handle.value()->GetAllMatchedEntries( - std::move(request), /* match_params= */ nullptr, + std::move(request), /* match_options= */ nullptr, base::BindOnce(&GetRequestBlobTask::DidMatchRequest, weak_factory_.GetWeakPtr(), handle.Clone())); }
diff --git a/content/browser/background_fetch/storage/match_requests_task.cc b/content/browser/background_fetch/storage/match_requests_task.cc index 99c542ff..bcf786b7 100644 --- a/content/browser/background_fetch/storage/match_requests_task.cc +++ b/content/browser/background_fetch/storage/match_requests_task.cc
@@ -4,6 +4,8 @@ #include "content/browser/background_fetch/storage/match_requests_task.h" +#include <memory> + #include "base/barrier_closure.h" #include "base/bind.h" #include "content/browser/background_fetch/background_fetch_data_manager.h" @@ -57,20 +59,20 @@ request = blink::mojom::FetchAPIRequest::New(); } - auto query_params = match_params_->cloned_cache_query_params(); - if (!query_params) - query_params = blink::mojom::QueryParams::New(); + auto query_options = match_params_->cloned_cache_query_options(); + if (!query_options) + query_options = blink::mojom::CacheQueryOptions::New(); // Ignore the search params since we added query params to make the URL // unique. - query_params->ignore_search = true; + query_options->ignore_search = true; // Ignore the method since Cache Storage assumes the request being matched // against is a GET. - query_params->ignore_method = true; + query_options->ignore_method = true; handle_.value()->GetAllMatchedEntries( - std::move(request), std::move(query_params), + std::move(request), std::move(query_options), base::BindOnce(&MatchRequestsTask::DidGetAllMatchedEntries, weak_factory_.GetWeakPtr())); } @@ -124,15 +126,15 @@ return true; // Ignore the request if the methods don't match. - if ((!match_params_->cache_query_params() || - !match_params_->cache_query_params()->ignore_method) && + if ((!match_params_->cache_query_options() || + !match_params_->cache_query_options()->ignore_method) && request->method != match_params_->request_to_match()->method) { return false; } // Ignore the request if the queries don't match. - if ((!match_params_->cache_query_params() || - !match_params_->cache_query_params()->ignore_search) && + if ((!match_params_->cache_query_options() || + !match_params_->cache_query_options()->ignore_search) && request->url.query() != match_params_->request_to_match()->url.query()) { return false; }
diff --git a/content/browser/background_fetch/storage/match_requests_task.h b/content/browser/background_fetch/storage/match_requests_task.h index b1059fa..aa073833 100644 --- a/content/browser/background_fetch/storage/match_requests_task.h +++ b/content/browser/background_fetch/storage/match_requests_task.h
@@ -5,6 +5,8 @@ #ifndef CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_MATCH_REQUESTS_TASK_H_ #define CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_MATCH_REQUESTS_TASK_H_ +#include <memory> + #include "base/callback_forward.h" #include "base/memory/scoped_refptr.h" #include "content/browser/background_fetch/background_fetch.pb.h"
diff --git a/content/browser/browser_main_loop.cc b/content/browser/browser_main_loop.cc index 2fbd8546..6ed357c 100644 --- a/content/browser/browser_main_loop.cc +++ b/content/browser/browser_main_loop.cc
@@ -47,7 +47,6 @@ #include "base/timer/hi_res_timer_manager.h" #include "base/trace_event/memory_dump_manager.h" #include "base/trace_event/trace_event.h" -#include "base/trace_event/trace_event_system_stats_monitor.h" #include "build/build_config.h" #include "cc/base/histograms.h" #include "components/discardable_memory/service/discardable_shared_memory_manager.h" @@ -140,7 +139,6 @@ #include "services/resource_coordinator/public/cpp/memory_instrumentation/client_process_impl.h" #include "services/resource_coordinator/public/mojom/memory_instrumentation/memory_instrumentation.mojom.h" #include "services/resource_coordinator/public/mojom/service_constants.mojom.h" -#include "services/service_manager/runner/common/client_util.h" #include "services/service_manager/zygote/common/zygote_buildflags.h" #include "skia/ext/event_tracer_impl.h" #include "skia/ext/skia_memory_dump_provider.h" @@ -178,7 +176,6 @@ #if defined(OS_MACOSX) #include "base/memory/memory_pressure_monitor_mac.h" -#include "content/browser/cocoa/system_hotkey_helper_mac.h" #include "content/browser/mach_broker_mac.h" #include "content/browser/renderer_host/browser_compositor_view_mac.h" #include "content/browser/theme_helper_mac.h" @@ -734,12 +731,6 @@ } { - system_stats_monitor_.reset( - new base::trace_event::TraceEventSystemStatsMonitor( - base::ThreadTaskRunnerHandle::Get())); - } - - { base::SetRecordActionTaskRunner( base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI})); } @@ -1045,8 +1036,6 @@ parts_->PostMainMessageLoopRun(); } - system_stats_monitor_.reset(); - // Cancel pending requests and prevent new requests. if (resource_dispatcher_host_) { TRACE_EVENT0("shutdown", @@ -1461,7 +1450,6 @@ #if defined(OS_MACOSX) ThemeHelperMac::GetInstance(); - SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys(); #endif // defined(OS_MACOSX) responsiveness_watcher_ = new responsiveness::Watcher;
diff --git a/content/browser/browser_main_loop.h b/content/browser/browser_main_loop.h index 9561013..9a8f3e26 100644 --- a/content/browser/browser_main_loop.h +++ b/content/browser/browser_main_loop.h
@@ -40,9 +40,6 @@ class PowerMonitor; class SingleThreadTaskRunner; class SystemMonitor; -namespace trace_event { -class TraceEventSystemStatsMonitor; -} // namespace trace_event } // namespace base namespace discardable_memory { @@ -319,9 +316,6 @@ // Per-process listener for online state changes. std::unique_ptr<BrowserOnlineStateObserver> online_state_observer_; - std::unique_ptr<base::trace_event::TraceEventSystemStatsMonitor> - system_stats_monitor_; - #if defined(USE_AURA) std::unique_ptr<aura::Env> env_; #endif
diff --git a/content/browser/cache_storage/cache_storage.cc b/content/browser/cache_storage/cache_storage.cc index 6a9ff84..5b44e52 100644 --- a/content/browser/cache_storage/cache_storage.cc +++ b/content/browser/cache_storage/cache_storage.cc
@@ -702,7 +702,7 @@ void CacheStorage::MatchCache(const std::string& cache_name, blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, CacheStorageCache::ResponseCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); @@ -716,13 +716,13 @@ scheduler_->ScheduleOperation( CacheStorageSchedulerOp::kMatch, base::BindOnce(&CacheStorage::MatchCacheImpl, weak_factory_.GetWeakPtr(), - cache_name, std::move(request), std::move(match_params), + cache_name, std::move(request), std::move(match_options), scheduler_->WrapCallbackToRunNext(std::move(callback)))); } void CacheStorage::MatchAllCaches( blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, CacheStorageCache::ResponseCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); @@ -737,7 +737,7 @@ CacheStorageSchedulerOp::kMatchAll, base::BindOnce(&CacheStorage::MatchAllCachesImpl, weak_factory_.GetWeakPtr(), std::move(request), - std::move(match_params), + std::move(match_options), scheduler_->WrapCallbackToRunNext(std::move(callback)))); } @@ -1052,7 +1052,7 @@ void CacheStorage::MatchCacheImpl( const std::string& cache_name, blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, CacheStorageCache::ResponseCallback callback) { CacheStorageCacheHandle cache_handle = GetLoadedCache(cache_name); @@ -1066,7 +1066,7 @@ // match is done. CacheStorageCache* cache_ptr = cache_handle.value(); cache_ptr->Match( - std::move(request), std::move(match_params), + std::move(request), std::move(match_options), base::BindOnce(&CacheStorage::MatchCacheDidMatch, weak_factory_.GetWeakPtr(), std::move(cache_handle), std::move(callback))); @@ -1082,7 +1082,7 @@ void CacheStorage::MatchAllCachesImpl( blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, CacheStorageCache::ResponseCallback callback) { std::vector<CacheMatchResponse>* match_responses = new std::vector<CacheMatchResponse>(cache_index_->num_entries()); @@ -1101,7 +1101,7 @@ CacheStorageCache* cache_ptr = cache_handle.value(); cache_ptr->Match( BackgroundFetchSettledFetch::CloneRequest(request), - match_params ? match_params->Clone() : nullptr, + match_options ? match_options->Clone() : nullptr, base::BindOnce(&CacheStorage::MatchAllCachesDidMatch, weak_factory_.GetWeakPtr(), std::move(cache_handle), &match_responses->at(idx), barrier_closure));
diff --git a/content/browser/cache_storage/cache_storage.h b/content/browser/cache_storage/cache_storage.h index f8450029..2f4c7f5 100644 --- a/content/browser/cache_storage/cache_storage.h +++ b/content/browser/cache_storage/cache_storage.h
@@ -120,7 +120,7 @@ // Calls match on the cache with the given |cache_name|. void MatchCache(const std::string& cache_name, blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, CacheStorageCache::ResponseCallback callback); // Calls match on all of the caches in parallel, calling |callback| with the @@ -128,7 +128,7 @@ // entry. If no response is found then |callback| is called with // blink::mojom::CacheStorageError::kErrorNotFound. void MatchAllCaches(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, CacheStorageCache::ResponseCallback callback); // Puts the request/response pair in the cache. @@ -223,7 +223,7 @@ // The MatchCache callbacks are below. void MatchCacheImpl(const std::string& cache_name, blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, CacheStorageCache::ResponseCallback callback); void MatchCacheDidMatch(CacheStorageCacheHandle cache_handle, CacheStorageCache::ResponseCallback callback, @@ -232,7 +232,7 @@ // The MatchAllCaches callbacks are below. void MatchAllCachesImpl(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, CacheStorageCache::ResponseCallback callback); void MatchAllCachesDidMatch(CacheStorageCacheHandle cache_handle, CacheMatchResponse* out_match_response,
diff --git a/content/browser/cache_storage/cache_storage_cache.cc b/content/browser/cache_storage/cache_storage_cache.cc index 91f7df1..75d3e74 100644 --- a/content/browser/cache_storage/cache_storage_cache.cc +++ b/content/browser/cache_storage/cache_storage_cache.cc
@@ -220,7 +220,7 @@ // supports multiple operations is addAll() and it does not allow options // to be passed. Therefore we assume we do not need to take any options // into account here. - DCHECK(!outer_op->match_params); + DCHECK(!outer_op->match_options); // If this entry already matches a duplicate we found, then just skip // ahead to find any remaining duplicates. @@ -432,7 +432,7 @@ struct CacheStorageCache::QueryCacheContext { QueryCacheContext(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr options, + blink::mojom::CacheQueryOptionsPtr options, QueryCacheCallback callback, QueryTypes query_types) : request(std::move(request)), @@ -453,7 +453,7 @@ // Input to QueryCache blink::mojom::FetchAPIRequestPtr request; - blink::mojom::QueryParamsPtr options; + blink::mojom::CacheQueryOptionsPtr options; QueryCacheCallback callback; QueryTypes query_types = 0; size_t estimated_out_bytes = 0; @@ -545,7 +545,7 @@ } void CacheStorageCache::Match(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, ResponseCallback callback) { if (backend_state_ == BACKEND_CLOSED) { std::move(callback).Run( @@ -557,13 +557,14 @@ CacheStorageSchedulerOp::kMatch, base::BindOnce(&CacheStorageCache::MatchImpl, weak_ptr_factory_.GetWeakPtr(), std::move(request), - std::move(match_params), + std::move(match_options), scheduler_->WrapCallbackToRunNext(std::move(callback)))); } -void CacheStorageCache::MatchAll(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, - ResponsesCallback callback) { +void CacheStorageCache::MatchAll( + blink::mojom::FetchAPIRequestPtr request, + blink::mojom::CacheQueryOptionsPtr match_options, + ResponsesCallback callback) { if (backend_state_ == BACKEND_CLOSED) { std::move(callback).Run( MakeErrorStorage(ErrorStorageType::kMatchAllBackendClosed), @@ -575,7 +576,7 @@ CacheStorageSchedulerOp::kMatchAll, base::BindOnce(&CacheStorageCache::MatchAllImpl, weak_ptr_factory_.GetWeakPtr(), std::move(request), - std::move(match_params), + std::move(match_options), scheduler_->WrapCallbackToRunNext(std::move(callback)))); } @@ -820,7 +821,7 @@ } void CacheStorageCache::Keys(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr options, + blink::mojom::CacheQueryOptionsPtr options, RequestsCallback callback) { if (backend_state_ == BACKEND_CLOSED) { std::move(callback).Run( @@ -946,7 +947,7 @@ } void CacheStorageCache::QueryCache(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr options, + blink::mojom::CacheQueryOptionsPtr options, QueryTypes query_types, QueryCacheCallback callback) { DCHECK_NE( @@ -1233,11 +1234,12 @@ return kCachePaddingAlgorithmVersion; } -void CacheStorageCache::MatchImpl(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, - ResponseCallback callback) { +void CacheStorageCache::MatchImpl( + blink::mojom::FetchAPIRequestPtr request, + blink::mojom::CacheQueryOptionsPtr match_options, + ResponseCallback callback) { MatchAllImpl( - std::move(request), std::move(match_params), + std::move(request), std::move(match_options), base::BindOnce(&CacheStorageCache::MatchDidMatchAll, weak_ptr_factory_.GetWeakPtr(), std::move(callback))); } @@ -1261,7 +1263,7 @@ } void CacheStorageCache::MatchAllImpl(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr options, + blink::mojom::CacheQueryOptionsPtr options, ResponsesCallback callback) { DCHECK_NE(BACKEND_UNINITIALIZED, backend_state_); if (backend_state_ != BACKEND_OPEN) { @@ -1485,7 +1487,8 @@ delete_request->referrer = blink::mojom::Referrer::New(); delete_request->headers = {}; - blink::mojom::QueryParamsPtr query_options = blink::mojom::QueryParams::New(); + blink::mojom::CacheQueryOptionsPtr query_options = + blink::mojom::CacheQueryOptions::New(); query_options->ignore_method = true; query_options->ignore_vary = true; DeleteImpl( @@ -1711,7 +1714,8 @@ // necessary. DCHECK_EQ(backend_state_, BACKEND_UNINITIALIZED); auto request = blink::mojom::FetchAPIRequest::New(); - blink::mojom::QueryParamsPtr options = blink::mojom::QueryParams::New(); + blink::mojom::CacheQueryOptionsPtr options = + blink::mojom::CacheQueryOptions::New(); options->ignore_search = true; QueryCache(std::move(request), std::move(options), QUERY_CACHE_RESPONSES_NO_BODIES, @@ -1783,7 +1787,7 @@ void CacheStorageCache::GetAllMatchedEntries( blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr options, + blink::mojom::CacheQueryOptionsPtr options, CacheEntriesCallback callback) { if (backend_state_ == BACKEND_CLOSED) { std::move(callback).Run( @@ -1801,7 +1805,7 @@ void CacheStorageCache::GetAllMatchedEntriesImpl( blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr options, + blink::mojom::CacheQueryOptionsPtr options, CacheEntriesCallback callback) { DCHECK_NE(BACKEND_UNINITIALIZED, backend_state_); if (backend_state_ != BACKEND_OPEN) { @@ -1854,13 +1858,14 @@ CacheStorageSchedulerOp::kDelete, base::BindOnce(&CacheStorageCache::DeleteImpl, weak_ptr_factory_.GetWeakPtr(), std::move(request), - std::move(operation->match_params), + std::move(operation->match_options), scheduler_->WrapCallbackToRunNext(std::move(callback)))); } -void CacheStorageCache::DeleteImpl(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, - ErrorCallback callback) { +void CacheStorageCache::DeleteImpl( + blink::mojom::FetchAPIRequestPtr request, + blink::mojom::CacheQueryOptionsPtr match_options, + ErrorCallback callback) { DCHECK_NE(BACKEND_UNINITIALIZED, backend_state_); if (backend_state_ != BACKEND_OPEN) { std::move(callback).Run( @@ -1869,7 +1874,7 @@ } QueryCache( - std::move(request), std::move(match_params), + std::move(request), std::move(match_options), QUERY_CACHE_ENTRIES | QUERY_CACHE_RESPONSES_NO_BODIES, base::BindOnce(&CacheStorageCache::DeleteDidQueryCache, weak_ptr_factory_.GetWeakPtr(), std::move(callback))); @@ -1904,7 +1909,7 @@ } void CacheStorageCache::KeysImpl(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr options, + blink::mojom::CacheQueryOptionsPtr options, RequestsCallback callback) { DCHECK_NE(BACKEND_UNINITIALIZED, backend_state_); if (backend_state_ != BACKEND_OPEN) {
diff --git a/content/browser/cache_storage/cache_storage_cache.h b/content/browser/cache_storage/cache_storage_cache.h index 185c47c..9d5c76d 100644 --- a/content/browser/cache_storage/cache_storage_cache.h +++ b/content/browser/cache_storage/cache_storage_cache.h
@@ -115,14 +115,14 @@ // Returns ERROR_TYPE_NOT_FOUND if not found. void Match(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, ResponseCallback callback); // Returns blink::mojom::CacheStorageError::kSuccess and matched // responses in this cache. If there are no responses, returns // blink::mojom::CacheStorageError::kSuccess and an empty vector. void MatchAll(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, ResponsesCallback callback); // Writes the side data (ex: V8 code cache) for the specified cache entry. @@ -179,7 +179,7 @@ // Returns blink::mojom::CacheStorageError::kSuccess and a vector of // requests if there are no errors. void Keys(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr options, + blink::mojom::CacheQueryOptionsPtr options, RequestsCallback callback); // Closes the backend. Future operations that require the backend @@ -203,7 +203,7 @@ // Similar to MatchAll, but returns the associated requests as well. void GetAllMatchedEntries(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, CacheEntriesCallback callback); // Async operations in progress will cancel and not run their callbacks. @@ -294,7 +294,7 @@ // REQUESTS_AND_RESPONSES then only out_requests, out_responses, and // out_blob_data_handles are valid. void QueryCache(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr options, + blink::mojom::CacheQueryOptionsPtr options, QueryTypes query_types, QueryCacheCallback callback); void QueryCacheDidOpenFastPath( @@ -316,7 +316,7 @@ // Match callbacks void MatchImpl(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, ResponseCallback callback); void MatchDidMatchAll( ResponseCallback callback, @@ -325,7 +325,7 @@ // MatchAll callbacks void MatchAllImpl(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr options, + blink::mojom::CacheQueryOptionsPtr options, ResponsesCallback callback); void MatchAllDidQueryCache( ResponsesCallback callback, @@ -411,7 +411,7 @@ // GetAllMatchedEntries callbacks. void GetAllMatchedEntriesImpl(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr options, + blink::mojom::CacheQueryOptionsPtr options, CacheEntriesCallback callback); void GetAllMatchedEntriesDidQueryCache( CacheEntriesCallback callback, @@ -422,7 +422,7 @@ void Delete(blink::mojom::BatchOperationPtr operation, ErrorCallback callback); void DeleteImpl(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, ErrorCallback callback); void DeleteDidQueryCache( ErrorCallback callback, @@ -431,7 +431,7 @@ // Keys callbacks. void KeysImpl(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr options, + blink::mojom::CacheQueryOptionsPtr options, RequestsCallback callback); void KeysDidQueryCache( RequestsCallback callback,
diff --git a/content/browser/cache_storage/cache_storage_cache_unittest.cc b/content/browser/cache_storage/cache_storage_cache_unittest.cc index c7d0edc..0da10b1 100644 --- a/content/browser/cache_storage/cache_storage_cache_unittest.cc +++ b/content/browser/cache_storage/cache_storage_cache_unittest.cc
@@ -558,12 +558,12 @@ } bool Match(const blink::mojom::FetchAPIRequestPtr& request, - blink::mojom::QueryParamsPtr match_params = nullptr) { + blink::mojom::CacheQueryOptionsPtr match_options = nullptr) { base::HistogramTester histogram_tester; std::unique_ptr<base::RunLoop> loop(new base::RunLoop()); cache_->Match( - CopyFetchRequest(request), std::move(match_params), + CopyFetchRequest(request), std::move(match_options), base::BindOnce(&CacheStorageCacheTest::ResponseAndErrorCallback, base::Unretained(this), base::Unretained(loop.get()))); loop->Run(); @@ -573,12 +573,12 @@ } bool MatchAll(const blink::mojom::FetchAPIRequestPtr& request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, std::vector<blink::mojom::FetchAPIResponsePtr>* responses) { base::HistogramTester histogram_tester; base::RunLoop loop; cache_->MatchAll( - CopyFetchRequest(request), std::move(match_params), + CopyFetchRequest(request), std::move(match_options), base::BindOnce(&CacheStorageCacheTest::ResponsesAndErrorCallback, base::Unretained(this), loop.QuitClosure(), responses)); loop.Run(); @@ -604,13 +604,13 @@ } bool Delete(const blink::mojom::FetchAPIRequestPtr& request, - blink::mojom::QueryParamsPtr match_params = nullptr) { + blink::mojom::CacheQueryOptionsPtr match_options = nullptr) { base::HistogramTester histogram_tester; blink::mojom::BatchOperationPtr operation = blink::mojom::BatchOperation::New(); operation->operation_type = blink::mojom::OperationType::kDelete; operation->request = BackgroundFetchSettledFetch::CloneRequest(request); - operation->match_params = std::move(match_params); + operation->match_options = std::move(match_options); std::vector<blink::mojom::BatchOperationPtr> operations; operations.emplace_back(std::move(operation)); @@ -622,12 +622,12 @@ bool Keys(const blink::mojom::FetchAPIRequestPtr& request = blink::mojom::FetchAPIRequest::New(), - blink::mojom::QueryParamsPtr match_params = nullptr) { + blink::mojom::CacheQueryOptionsPtr match_options = nullptr) { base::HistogramTester histogram_tester; std::unique_ptr<base::RunLoop> loop(new base::RunLoop()); cache_->Keys( - CopyFetchRequest(request), std::move(match_params), + CopyFetchRequest(request), std::move(match_options), base::BindOnce(&CacheStorageCacheTest::RequestsCallback, base::Unretained(this), base::Unretained(loop.get()))); loop->Run(); @@ -913,25 +913,26 @@ EstimatedResponseSizeWithoutBlob(*callback_response_); std::vector<blink::mojom::FetchAPIResponsePtr> responses; - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); // There is enough room for both requests and responses SetMaxQuerySizeBytes(body_request_size + query_request_size); - EXPECT_TRUE(MatchAll(body_request_, match_params->Clone(), &responses)); + EXPECT_TRUE(MatchAll(body_request_, match_options->Clone(), &responses)); EXPECT_EQ(1u, responses.size()); - match_params->ignore_search = true; - EXPECT_TRUE(MatchAll(body_request_, match_params->Clone(), &responses)); + match_options->ignore_search = true; + EXPECT_TRUE(MatchAll(body_request_, match_options->Clone(), &responses)); EXPECT_EQ(2u, responses.size()); // There is not enough room for both requests and responses SetMaxQuerySizeBytes(body_request_size); - match_params->ignore_search = false; - EXPECT_TRUE(MatchAll(body_request_, match_params->Clone(), &responses)); + match_options->ignore_search = false; + EXPECT_TRUE(MatchAll(body_request_, match_options->Clone(), &responses)); EXPECT_EQ(1u, responses.size()); - match_params->ignore_search = true; - EXPECT_FALSE(MatchAll(body_request_, match_params->Clone(), &responses)); + match_options->ignore_search = true; + EXPECT_FALSE(MatchAll(body_request_, match_options->Clone(), &responses)); EXPECT_EQ(CacheStorageError::kErrorQueryTooLarge, callback_error_); } @@ -1009,13 +1010,13 @@ blink::mojom::BatchOperation::New( blink::mojom::OperationType::kPut, BackgroundFetchSettledFetch::CloneRequest(body_request_), - CreateBlobBodyResponse(), nullptr /* match_params */); + CreateBlobBodyResponse(), nullptr /* match_options */); operation1->response->blob->size = std::numeric_limits<uint64_t>::max(); blink::mojom::BatchOperationPtr operation2 = blink::mojom::BatchOperation::New( blink::mojom::OperationType::kPut, BackgroundFetchSettledFetch::CloneRequest(body_request_with_query_), - CreateBlobBodyResponse(), nullptr /* match_params */); + CreateBlobBodyResponse(), nullptr /* match_options */); operation2->response->blob->size = std::numeric_limits<uint64_t>::max(); std::vector<blink::mojom::BatchOperationPtr> operations; @@ -1193,9 +1194,10 @@ EXPECT_TRUE(Put(body_request_with_query_, CreateBlobBodyResponseWithQuery())); EXPECT_FALSE(Match(body_request_)); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_search = true; - EXPECT_TRUE(Match(body_request_, std::move(match_params))); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_search = true; + EXPECT_TRUE(Match(body_request_, std::move(match_options))); } TEST_P(CacheStorageCacheTestP, Match_IgnoreMethod) { @@ -1206,9 +1208,10 @@ post_request->method = "POST"; EXPECT_FALSE(Match(post_request)); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_method = true; - EXPECT_TRUE(Match(post_request, std::move(match_params))); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_method = true; + EXPECT_TRUE(Match(post_request, std::move(match_options))); } TEST_P(CacheStorageCacheTestP, Match_IgnoreVary) { @@ -1221,9 +1224,10 @@ body_request_->headers["vary_foo"] = "bar"; EXPECT_FALSE(Match(body_request_)); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_vary = true; - EXPECT_TRUE(Match(body_request_, std::move(match_params))); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_vary = true; + EXPECT_TRUE(Match(body_request_, std::move(match_options))); } TEST_P(CacheStorageCacheTestP, GetAllMatchedEntries_RequestsIncluded) { @@ -1251,9 +1255,10 @@ EXPECT_TRUE(Keys(body_request_)); EXPECT_EQ(0u, callback_strings_.size()); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_search = true; - EXPECT_TRUE(Keys(body_request_, std::move(match_params))); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_search = true; + EXPECT_TRUE(Keys(body_request_, std::move(match_options))); EXPECT_EQ(1u, callback_strings_.size()); } @@ -1266,9 +1271,10 @@ EXPECT_TRUE(Keys(post_request)); EXPECT_EQ(0u, callback_strings_.size()); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_method = true; - EXPECT_TRUE(Keys(post_request, std::move(match_params))); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_method = true; + EXPECT_TRUE(Keys(post_request, std::move(match_options))); EXPECT_EQ(1u, callback_strings_.size()); } @@ -1284,9 +1290,10 @@ EXPECT_TRUE(Keys(body_request_)); EXPECT_EQ(0u, callback_strings_.size()); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_vary = true; - EXPECT_TRUE(Keys(body_request_, std::move(match_params))); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_vary = true; + EXPECT_TRUE(Keys(body_request_, std::move(match_options))); EXPECT_EQ(1u, callback_strings_.size()); } @@ -1294,9 +1301,10 @@ EXPECT_TRUE(Put(body_request_with_query_, CreateBlobBodyResponseWithQuery())); EXPECT_FALSE(Delete(body_request_)); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_search = true; - EXPECT_TRUE(Delete(body_request_, std::move(match_params))); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_search = true; + EXPECT_TRUE(Delete(body_request_, std::move(match_options))); } TEST_P(CacheStorageCacheTestP, Delete_IgnoreMethod) { @@ -1307,9 +1315,10 @@ post_request->method = "POST"; EXPECT_FALSE(Delete(post_request)); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_method = true; - EXPECT_TRUE(Delete(post_request, std::move(match_params))); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_method = true; + EXPECT_TRUE(Delete(post_request, std::move(match_options))); } TEST_P(CacheStorageCacheTestP, Delete_IgnoreVary) { @@ -1321,9 +1330,10 @@ body_request_->headers["vary_foo"] = "bar"; EXPECT_FALSE(Delete(body_request_)); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_vary = true; - EXPECT_TRUE(Delete(body_request_, std::move(match_params))); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_vary = true; + EXPECT_TRUE(Delete(body_request_, std::move(match_options))); } TEST_P(CacheStorageCacheTestP, MatchAll_IgnoreMethod) { @@ -1337,9 +1347,10 @@ EXPECT_TRUE(MatchAll(post_request, nullptr, &responses)); EXPECT_EQ(0u, responses.size()); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_method = true; - EXPECT_TRUE(MatchAll(post_request, std::move(match_params), &responses)); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_method = true; + EXPECT_TRUE(MatchAll(post_request, std::move(match_options), &responses)); EXPECT_EQ(1u, responses.size()); } @@ -1357,9 +1368,10 @@ EXPECT_TRUE(MatchAll(body_request_, nullptr, &responses)); EXPECT_EQ(0u, responses.size()); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_vary = true; - EXPECT_TRUE(MatchAll(body_request_, std::move(match_params), &responses)); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_vary = true; + EXPECT_TRUE(MatchAll(body_request_, std::move(match_options), &responses)); EXPECT_EQ(1u, responses.size()); } @@ -1369,9 +1381,10 @@ EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse())); std::vector<blink::mojom::FetchAPIResponsePtr> responses; - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_search = true; - EXPECT_TRUE(MatchAll(body_request_, std::move(match_params), &responses)); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_search = true; + EXPECT_TRUE(MatchAll(body_request_, std::move(match_options), &responses)); ASSERT_EQ(2u, responses.size()); @@ -1396,13 +1409,14 @@ EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse())); std::vector<blink::mojom::FetchAPIResponsePtr> responses; - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_search = true; - EXPECT_TRUE(MatchAll(body_head_request_, match_params->Clone(), &responses)); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_search = true; + EXPECT_TRUE(MatchAll(body_head_request_, match_options->Clone(), &responses)); EXPECT_TRUE(responses.empty()); - match_params->ignore_method = true; - EXPECT_TRUE(MatchAll(body_head_request_, match_params->Clone(), &responses)); + match_options->ignore_method = true; + EXPECT_TRUE(MatchAll(body_head_request_, match_options->Clone(), &responses)); ASSERT_EQ(1u, responses.size()); EXPECT_TRUE(ResponseMetadataEqual(*SetCacheName(CreateBlobBodyResponse()), *responses[0])); @@ -1508,10 +1522,11 @@ EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse())); EXPECT_TRUE(Put(body_request_with_query_, CreateBlobBodyResponseWithQuery())); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_search = true; + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_search = true; - EXPECT_TRUE(Keys(body_request_with_query_, std::move(match_params))); + EXPECT_TRUE(Keys(body_request_with_query_, std::move(match_options))); std::vector<std::string> expected_keys = { body_request_->url.spec(), body_request_with_query_->url.spec()}; EXPECT_EQ(expected_keys, callback_strings_); @@ -1523,10 +1538,11 @@ EXPECT_TRUE(Put(body_request_with_query_, CreateBlobBodyResponseWithQuery())); // Default value of ignore_search is false. - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - EXPECT_EQ(match_params->ignore_search, false); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + EXPECT_EQ(match_options->ignore_search, false); - EXPECT_TRUE(Keys(body_request_with_query_, std::move(match_params))); + EXPECT_TRUE(Keys(body_request_with_query_, std::move(match_options))); std::vector<std::string> expected_keys = { body_request_with_query_->url.spec()}; EXPECT_EQ(expected_keys, callback_strings_); @@ -1567,9 +1583,10 @@ // The following delete operation will remove both of body_request_ and // body_request_with_query_ from cache storage. - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_search = true; - EXPECT_TRUE(Delete(body_request_with_query_, std::move(match_params))); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_search = true; + EXPECT_TRUE(Delete(body_request_with_query_, std::move(match_options))); EXPECT_TRUE(Keys()); expected_keys.clear(); @@ -1589,10 +1606,11 @@ EXPECT_EQ(expected_keys, callback_strings_); // Default value of ignore_search is false. - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - EXPECT_EQ(match_params->ignore_search, false); + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + EXPECT_EQ(match_options->ignore_search, false); - EXPECT_TRUE(Delete(body_request_with_query_, std::move(match_params))); + EXPECT_TRUE(Delete(body_request_with_query_, std::move(match_options))); EXPECT_TRUE(Keys()); std::vector<std::string> expected_keys2{no_body_request_->url.spec(),
diff --git a/content/browser/cache_storage/cache_storage_dispatcher_host.cc b/content/browser/cache_storage/cache_storage_dispatcher_host.cc index f52e203..08e24f2 100644 --- a/content/browser/cache_storage/cache_storage_dispatcher_host.cc +++ b/content/browser/cache_storage/cache_storage_dispatcher_host.cc
@@ -62,7 +62,7 @@ // blink::mojom::CacheStorageCache implementation: void Match(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, MatchCallback callback) override { content::CacheStorageCache* cache = cache_handle_.value(); if (!cache) { @@ -72,7 +72,7 @@ } cache->Match( - std::move(request), std::move(match_params), + std::move(request), std::move(match_options), base::BindOnce(&CacheImpl::OnCacheMatchCallback, weak_factory_.GetWeakPtr(), std::move(callback))); } @@ -91,7 +91,7 @@ } void MatchAll(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, MatchAllCallback callback) override { content::CacheStorageCache* cache = cache_handle_.value(); if (!cache) { @@ -101,7 +101,7 @@ } cache->MatchAll( - std::move(request), std::move(match_params), + std::move(request), std::move(match_options), base::BindOnce(&CacheImpl::OnCacheMatchAllCallback, weak_factory_.GetWeakPtr(), std::move(callback))); } @@ -121,7 +121,7 @@ } void Keys(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params, + blink::mojom::CacheQueryOptionsPtr match_options, KeysCallback callback) override { content::CacheStorageCache* cache = cache_handle_.value(); if (!cache) { @@ -131,7 +131,7 @@ } cache->Keys( - std::move(request), std::move(match_params), + std::move(request), std::move(match_options), base::BindOnce(&CacheImpl::OnCacheKeysCallback, weak_factory_.GetWeakPtr(), std::move(callback))); } @@ -270,7 +270,7 @@ } void Match(blink::mojom::FetchAPIRequestPtr request, - blink::mojom::MultiQueryParamsPtr match_params, + blink::mojom::MultiCacheQueryOptionsPtr match_options, blink::mojom::CacheStorage::MatchCallback callback) override { content::CacheStorage* cache_storage = GetOrCreateCacheStorage(); if (!cache_storage) { @@ -294,15 +294,15 @@ }, std::move(callback)); - if (!match_params->cache_name) { + if (!match_options->cache_name) { cache_storage->MatchAllCaches(std::move(request), - std::move(match_params->query_params), + std::move(match_options->query_options), std::move(on_match)); return; } - std::string cache_name = base::UTF16ToUTF8(*match_params->cache_name); + std::string cache_name = base::UTF16ToUTF8(*match_options->cache_name); cache_storage->MatchCache(std::move(cache_name), std::move(request), - std::move(match_params->query_params), + std::move(match_options->query_options), std::move(on_match)); }
diff --git a/content/browser/cache_storage/cache_storage_manager_unittest.cc b/content/browser/cache_storage/cache_storage_manager_unittest.cc index b6fdf89..3b760c7 100644 --- a/content/browser/cache_storage/cache_storage_manager_unittest.cc +++ b/content/browser/cache_storage/cache_storage_manager_unittest.cc
@@ -398,26 +398,26 @@ bool StorageMatch(const url::Origin& origin, const std::string& cache_name, const GURL& url, - blink::mojom::QueryParamsPtr match_params = nullptr, + blink::mojom::CacheQueryOptionsPtr match_options = nullptr, CacheStorageOwner owner = CacheStorageOwner::kCacheAPI) { auto request = blink::mojom::FetchAPIRequest::New(); request->url = url; return StorageMatchWithRequest(origin, cache_name, std::move(request), - std::move(match_params), owner); + std::move(match_options), owner); } bool StorageMatchWithRequest( const url::Origin& origin, const std::string& cache_name, blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params = nullptr, + blink::mojom::CacheQueryOptionsPtr match_options = nullptr, CacheStorageOwner owner = CacheStorageOwner::kCacheAPI) { base::HistogramTester histogram_tester; base::RunLoop loop; CacheStorageHandle cache_storage = cache_manager_->OpenCacheStorage(origin, owner); cache_storage.value()->MatchCache( - cache_name, std::move(request), std::move(match_params), + cache_name, std::move(request), std::move(match_options), base::BindOnce(&CacheStorageManagerTest::CacheMatchCallback, base::Unretained(this), base::Unretained(&loop))); loop.Run(); @@ -426,26 +426,27 @@ return callback_error_ == CacheStorageError::kSuccess; } - bool StorageMatchAll(const url::Origin& origin, - const GURL& url, - blink::mojom::QueryParamsPtr match_params = nullptr) { + bool StorageMatchAll( + const url::Origin& origin, + const GURL& url, + blink::mojom::CacheQueryOptionsPtr match_options = nullptr) { auto request = blink::mojom::FetchAPIRequest::New(); request->url = url; return StorageMatchAllWithRequest(origin, std::move(request), - std::move(match_params)); + std::move(match_options)); } bool StorageMatchAllWithRequest( const url::Origin& origin, blink::mojom::FetchAPIRequestPtr request, - blink::mojom::QueryParamsPtr match_params = nullptr, + blink::mojom::CacheQueryOptionsPtr match_options = nullptr, CacheStorageOwner owner = CacheStorageOwner::kCacheAPI) { base::HistogramTester histogram_tester; base::RunLoop loop; CacheStorageHandle cache_storage = cache_manager_->OpenCacheStorage(origin, owner); cache_storage.value()->MatchAllCaches( - std::move(request), std::move(match_params), + std::move(request), std::move(match_options), base::BindOnce(&CacheStorageManagerTest::CacheMatchCallback, base::Unretained(this), base::Unretained(&loop))); loop.Run(); @@ -1866,10 +1867,11 @@ EXPECT_FALSE(StorageMatch(origin1_, "foo", GURL("http://example.com/foo"))); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_search = true; + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_search = true; EXPECT_TRUE(StorageMatch(origin1_, "foo", GURL("http://example.com/foo"), - std::move(match_params))); + std::move(match_options))); } TEST_P(CacheStorageManagerTestP, StorageMatch_IgnoreMethod) { @@ -1884,10 +1886,11 @@ origin1_, "foo", BackgroundFetchSettledFetch::CloneRequest(post_request))); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_method = true; + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_method = true; EXPECT_TRUE(StorageMatchWithRequest(origin1_, "foo", std::move(post_request), - std::move(match_params))); + std::move(match_options))); } TEST_P(CacheStorageManagerTestP, StorageMatch_IgnoreVary) { @@ -1915,10 +1918,11 @@ auto request_4 = BackgroundFetchSettledFetch::CloneRequest(request); EXPECT_FALSE(StorageMatchWithRequest(origin1_, "foo", std::move(request_3))); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_vary = true; + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_vary = true; EXPECT_TRUE(StorageMatchWithRequest(origin1_, "foo", std::move(request_4), - std::move(match_params))); + std::move(match_options))); } TEST_P(CacheStorageManagerTestP, StorageMatchAll_IgnoreSearch) { @@ -1928,10 +1932,11 @@ EXPECT_FALSE(StorageMatchAll(origin1_, GURL("http://example.com/foo"))); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_search = true; + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_search = true; EXPECT_TRUE(StorageMatchAll(origin1_, GURL("http://example.com/foo"), - std::move(match_params))); + std::move(match_options))); } TEST_P(CacheStorageManagerTestP, StorageMatchAll_IgnoreMethod) { @@ -1945,10 +1950,11 @@ EXPECT_FALSE(StorageMatchAllWithRequest( origin1_, BackgroundFetchSettledFetch::CloneRequest(post_request))); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_method = true; + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_method = true; EXPECT_TRUE(StorageMatchAllWithRequest(origin1_, std::move(post_request), - std::move(match_params))); + std::move(match_options))); } TEST_P(CacheStorageManagerTestP, StorageMatchAll_IgnoreVary) { @@ -1975,10 +1981,11 @@ auto request_4 = BackgroundFetchSettledFetch::CloneRequest(request); EXPECT_FALSE(StorageMatchAllWithRequest(origin1_, std::move(request_3))); - blink::mojom::QueryParamsPtr match_params = blink::mojom::QueryParams::New(); - match_params->ignore_vary = true; + blink::mojom::CacheQueryOptionsPtr match_options = + blink::mojom::CacheQueryOptions::New(); + match_options->ignore_vary = true; EXPECT_TRUE(StorageMatchAllWithRequest(origin1_, std::move(request_4), - std::move(match_params))); + std::move(match_options))); } TEST_P(CacheStorageManagerTestP, StorageWriteToCache) {
diff --git a/content/browser/cocoa/system_hotkey_helper_mac.h b/content/browser/cocoa/system_hotkey_helper_mac.h index 19ecb888..b523430 100644 --- a/content/browser/cocoa/system_hotkey_helper_mac.h +++ b/content/browser/cocoa/system_hotkey_helper_mac.h
@@ -5,54 +5,12 @@ #ifndef CONTENT_BROWSER_COCOA_SYSTEM_HOTKEY_HELPER_MAC_H_ #define CONTENT_BROWSER_COCOA_SYSTEM_HOTKEY_HELPER_MAC_H_ -#include <memory> - -#include "base/macros.h" -#include "base/memory/singleton.h" -#include "base/memory/weak_ptr.h" - -#ifdef __OBJC__ -@class NSDictionary; -#else -class NSDictionary; -#endif - namespace content { class SystemHotkeyMap; -// This singleton holds a global mapping of hotkeys reserved by OSX. -class SystemHotkeyHelperMac { - public: - // Return pointer to the singleton instance for the current process. - static SystemHotkeyHelperMac* GetInstance(); - - // Loads the system hot keys after a brief delay, to reduce file system access - // immediately after launch. - void DeferredLoadSystemHotkeys(); - - // Guaranteed to not be NULL. - SystemHotkeyMap* map() { return map_.get(); } - - private: - friend struct base::DefaultSingletonTraits<SystemHotkeyHelperMac>; - - SystemHotkeyHelperMac(); - ~SystemHotkeyHelperMac(); - - // Must be called from the FILE thread. Loads the file containing the system - // hotkeys into a NSDictionary* object, and passes the result to FileDidLoad - // on the UI thread. - void LoadSystemHotkeys(); - - // Must be called from the UI thread. This takes ownership of |dictionary|. - // Parses the system hotkeys from the plist stored in |dictionary|. - void FileDidLoad(NSDictionary* dictionary); - - std::unique_ptr<SystemHotkeyMap> map_; - - DISALLOW_COPY_AND_ASSIGN(SystemHotkeyHelperMac); -}; +// Guaranteed to not be NULL. +SystemHotkeyMap* GetSystemHotkeyMap(); } // namespace content
diff --git a/content/browser/cocoa/system_hotkey_helper_mac.mm b/content/browser/cocoa/system_hotkey_helper_mac.mm index 27b8fae7..99a4d4d 100644 --- a/content/browser/cocoa/system_hotkey_helper_mac.mm +++ b/content/browser/cocoa/system_hotkey_helper_mac.mm
@@ -4,76 +4,37 @@ #include "content/browser/cocoa/system_hotkey_helper_mac.h" -#include "base/bind.h" #include "base/files/file_path.h" #include "base/mac/foundation_util.h" #include "base/metrics/histogram_macros.h" -#include "base/task/post_task.h" -#include "base/task/task_traits.h" -#include "base/threading/scoped_blocking_call.h" +#include "base/no_destructor.h" #include "content/browser/cocoa/system_hotkey_map.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" namespace { -NSString* kSystemHotkeyPlistExtension = - @"/Preferences/com.apple.symbolichotkeys.plist"; +constexpr auto* kSystemHotkeyPlistPath = + "Preferences/com.apple.symbolichotkeys.plist"; -// Amount of time to delay loading the hotkeys in seconds. -const int kLoadHotkeysDelaySeconds = 10; +content::SystemHotkeyMap LoadSystemHotkeyMap() { + auto* hotkey_plist_url = base::mac::FilePathToNSURL( + base::mac::GetUserLibraryPath().Append(kSystemHotkeyPlistPath)); + NSDictionary* dictionary = + [NSDictionary dictionaryWithContentsOfURL:hotkey_plist_url]; + + content::SystemHotkeyMap map; + bool success = map.ParseDictionary(dictionary); + UMA_HISTOGRAM_BOOLEAN("OSX.SystemHotkeyMap.LoadSuccess", success); + return map; +} } // namespace namespace content { // static -SystemHotkeyHelperMac* SystemHotkeyHelperMac::GetInstance() { - return base::Singleton<SystemHotkeyHelperMac>::get(); -} - -void SystemHotkeyHelperMac::DeferredLoadSystemHotkeys() { - base::PostDelayedTaskWithTraits( - FROM_HERE, - {base::TaskPriority::USER_VISIBLE, - base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN, base::MayBlock()}, - base::Bind(&SystemHotkeyHelperMac::LoadSystemHotkeys, - base::Unretained(this)), - base::TimeDelta::FromSeconds(kLoadHotkeysDelaySeconds)); -} - -SystemHotkeyHelperMac::SystemHotkeyHelperMac() : map_(new SystemHotkeyMap) { -} - -SystemHotkeyHelperMac::~SystemHotkeyHelperMac() { -} - -void SystemHotkeyHelperMac::LoadSystemHotkeys() { - base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK); - - std::string library_path(base::mac::GetUserLibraryPath().value()); - NSString* expanded_file_path = - [NSString stringWithFormat:@"%s%@", - library_path.c_str(), - kSystemHotkeyPlistExtension]; - - // Loads the file into memory. - NSData* data = [NSData dataWithContentsOfFile:expanded_file_path]; - // Intentionally create the object with +1 retain count, as FileDidLoad - // will destroy the object. - NSDictionary* dictionary = [SystemHotkeyMap::DictionaryFromData(data) retain]; - - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::Bind(&SystemHotkeyHelperMac::FileDidLoad, - base::Unretained(this), dictionary)); -} - -void SystemHotkeyHelperMac::FileDidLoad(NSDictionary* dictionary) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - bool success = map()->ParseDictionary(dictionary); - UMA_HISTOGRAM_BOOLEAN("OSX.SystemHotkeyMap.LoadSuccess", success); - [dictionary release]; +SystemHotkeyMap* GetSystemHotkeyMap() { + static base::NoDestructor<SystemHotkeyMap> instance(LoadSystemHotkeyMap()); + return instance.get(); } } // namespace content
diff --git a/content/browser/cocoa/system_hotkey_map.h b/content/browser/cocoa/system_hotkey_map.h index 1909aa53..e40c60ed 100644 --- a/content/browser/cocoa/system_hotkey_map.h +++ b/content/browser/cocoa/system_hotkey_map.h
@@ -22,12 +22,9 @@ class CONTENT_EXPORT SystemHotkeyMap { public: SystemHotkeyMap(); + SystemHotkeyMap(SystemHotkeyMap&&); ~SystemHotkeyMap(); - // Converts the plist stored in |data| into an NSDictionary. Returns nil on - // error. - static NSDictionary* DictionaryFromData(NSData* data); - // Parses the property list data commonly stored at // ~/Library/Preferences/com.apple.symbolichotkeys.plist // Returns false on encountering an irrecoverable error.
diff --git a/content/browser/cocoa/system_hotkey_map.mm b/content/browser/cocoa/system_hotkey_map.mm index 6ee40574..bf3484da 100644 --- a/content/browser/cocoa/system_hotkey_map.mm +++ b/content/browser/cocoa/system_hotkey_map.mm
@@ -50,28 +50,9 @@ #pragma mark - SystemHotkeyMap -SystemHotkeyMap::SystemHotkeyMap() { -} -SystemHotkeyMap::~SystemHotkeyMap() { -} - -NSDictionary* SystemHotkeyMap::DictionaryFromData(NSData* data) { - if (!data) - return nil; - - NSError* error = nil; - NSPropertyListFormat format; - NSDictionary* dictionary = - [NSPropertyListSerialization propertyListWithData:data - options:0 - format:&format - error:&error]; - - if (![dictionary isKindOfClass:[NSDictionary class]]) - return nil; - - return dictionary; -} +SystemHotkeyMap::SystemHotkeyMap() = default; +SystemHotkeyMap::SystemHotkeyMap(SystemHotkeyMap&&) = default; +SystemHotkeyMap::~SystemHotkeyMap() = default; bool SystemHotkeyMap::ParseDictionary(NSDictionary* dictionary) { system_hotkeys_.clear();
diff --git a/content/browser/cocoa/system_hotkey_map_unittest.mm b/content/browser/cocoa/system_hotkey_map_unittest.mm index d4b2a798..cbae4c3 100644 --- a/content/browser/cocoa/system_hotkey_map_unittest.mm +++ b/content/browser/cocoa/system_hotkey_map_unittest.mm
@@ -8,6 +8,7 @@ #import <Cocoa/Cocoa.h> #include "base/files/file_path.h" +#import "base/mac/foundation_util.h" #include "base/mac/scoped_nsobject.h" #include "base/path_service.h" #import "content/browser/cocoa/system_hotkey_map.h" @@ -19,17 +20,15 @@ protected: SystemHotkeyMapTest() {} - NSData* DataFromTestFile(const char* file) { + NSDictionary* DictionaryFromTestFile(const char* file) { base::FilePath test_data_dir; bool result = base::PathService::Get(DIR_TEST_DATA, &test_data_dir); if (!result) return nil; base::FilePath test_path = test_data_dir.AppendASCII(file); - std::string test_path_string = test_path.AsUTF8Unsafe(); - NSString* file_path = - [NSString stringWithUTF8String:test_path_string.c_str()]; - return [NSData dataWithContentsOfFile:file_path]; + return [NSDictionary + dictionaryWithContentsOfURL:base::mac::FilePathToNSURL(test_path)]; } void AddEntryToDictionary(BOOL enabled, @@ -84,10 +83,8 @@ TEST_F(SystemHotkeyMapTest, Parse) { // This plist was pulled from a real machine. It is extensively populated, // and has no missing or incomplete entries. - NSData* data = DataFromTestFile("mac/mac_system_hotkeys.plist"); - ASSERT_TRUE(data); - - NSDictionary* dictionary = SystemHotkeyMap::DictionaryFromData(data); + NSDictionary* dictionary = + DictionaryFromTestFile("mac/mac_system_hotkeys.plist"); ASSERT_TRUE(dictionary); SystemHotkeyMap map; @@ -124,10 +121,8 @@ TEST_F(SystemHotkeyMapTest, ParseMouse) { // This plist was pulled from a real machine. It has missing entries, // incomplete entries, and mouse hotkeys. - NSData* data = DataFromTestFile("mac/mac_system_hotkeys_sparse.plist"); - ASSERT_TRUE(data); - - NSDictionary* dictionary = SystemHotkeyMap::DictionaryFromData(data); + NSDictionary* dictionary = + DictionaryFromTestFile("mac/mac_system_hotkeys_sparse.plist"); ASSERT_TRUE(dictionary); SystemHotkeyMap map;
diff --git a/content/browser/compositor/gpu_process_transport_factory.cc b/content/browser/compositor/gpu_process_transport_factory.cc index 5aeda7b..e82686c 100644 --- a/content/browser/compositor/gpu_process_transport_factory.cc +++ b/content/browser/compositor/gpu_process_transport_factory.cc
@@ -62,7 +62,6 @@ #include "gpu/ipc/client/gpu_channel_host.h" #include "gpu/ipc/host/gpu_memory_buffer_support.h" #include "gpu/vulkan/buildflags.h" -#include "services/service_manager/runner/common/client_util.h" #include "services/ws/public/cpp/gpu/context_provider_command_buffer.h" #include "third_party/khronos/GLES2/gl2.h" #include "ui/base/ui_base_features.h"
diff --git a/content/browser/dom_storage/dom_storage_context_wrapper.cc b/content/browser/dom_storage/dom_storage_context_wrapper.cc index ff06e2d4..1dfcf25 100644 --- a/content/browser/dom_storage/dom_storage_context_wrapper.cc +++ b/content/browser/dom_storage/dom_storage_context_wrapper.cc
@@ -431,25 +431,36 @@ void DOMStorageContextWrapper::OpenLocalStorage( const url::Origin& origin, - blink::mojom::StorageAreaRequest request) { + blink::mojom::StorageAreaRequest request, + base::OnceClosure bind_done) { DCHECK(mojo_state_); + + base::OnceClosure wrapped_done_callback = base::BindOnce( + base::IgnoreResult(&base::SequencedTaskRunner::PostTask), + base::SequencedTaskRunnerHandle::Get(), FROM_HERE, std::move(bind_done)); + // base::Unretained is safe here, because the mojo_state_ won't be deleted // until a ShutdownAndDelete task has been ran on the mojo_task_runner_, and // as soon as that task is posted, mojo_state_ is set to null, preventing // further tasks from being queued. mojo_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&LocalStorageContextMojo::OpenLocalStorage, - base::Unretained(mojo_state_), origin, - std::move(request))); + FROM_HERE, + base::BindOnce(&LocalStorageContextMojo::OpenLocalStorage, + base::Unretained(mojo_state_), origin, std::move(request), + std::move(wrapped_done_callback))); } void DOMStorageContextWrapper::OpenSessionStorage( int process_id, const std::string& namespace_id, mojo::ReportBadMessageCallback bad_message_callback, - blink::mojom::SessionStorageNamespaceRequest request) { + blink::mojom::SessionStorageNamespaceRequest request, + base::OnceClosure bind_done) { if (!mojo_session_state_) return; + base::OnceClosure wrapped_done_callback = base::BindOnce( + base::IgnoreResult(&base::SequencedTaskRunner::PostTask), + base::SequencedTaskRunnerHandle::Get(), FROM_HERE, std::move(bind_done)); // The bad message callback must be called on the same sequenced task runner // as the binding set. It cannot be called from our own mojo task runner. auto wrapped_bad_message_callback = base::BindOnce( @@ -469,7 +480,7 @@ base::BindOnce(&SessionStorageContextMojo::OpenSessionStorage, base::Unretained(mojo_session_state_), process_id, namespace_id, std::move(wrapped_bad_message_callback), - std::move(request))); + std::move(request), std::move(wrapped_done_callback))); } void DOMStorageContextWrapper::SetLocalStorageDatabaseForTesting(
diff --git a/content/browser/dom_storage/dom_storage_context_wrapper.h b/content/browser/dom_storage/dom_storage_context_wrapper.h index ded7b75a..4e630f4 100644 --- a/content/browser/dom_storage/dom_storage_context_wrapper.h +++ b/content/browser/dom_storage/dom_storage_context_wrapper.h
@@ -88,11 +88,13 @@ // See mojom::StoragePartitionService interface. void OpenLocalStorage(const url::Origin& origin, - blink::mojom::StorageAreaRequest request); + blink::mojom::StorageAreaRequest request, + base::OnceClosure bind_done); void OpenSessionStorage(int process_id, const std::string& namespace_id, mojo::ReportBadMessageCallback bad_message_callback, - blink::mojom::SessionStorageNamespaceRequest request); + blink::mojom::SessionStorageNamespaceRequest request, + base::OnceClosure bind_done); void SetLocalStorageDatabaseForTesting( leveldb::mojom::LevelDBDatabaseAssociatedPtr database);
diff --git a/content/browser/dom_storage/dom_storage_context_wrapper_unittest.cc b/content/browser/dom_storage/dom_storage_context_wrapper_unittest.cc index 71b1cc8..18f1dc5 100644 --- a/content/browser/dom_storage/dom_storage_context_wrapper_unittest.cc +++ b/content/browser/dom_storage/dom_storage_context_wrapper_unittest.cc
@@ -63,13 +63,14 @@ blink::mojom::SessionStorageNamespacePtr ss_namespace_ptr; auto request = mojo::MakeRequest(&ss_namespace_ptr); bool called = false; + // This call is invalid because |CreateSessionNamespace| was never called on // the SessionStorage context. context_->OpenSessionStorage( 0, "nonexistant-namespace", base::BindLambdaForTesting( [&called](const std::string& message) { called = true; }), - std::move(request)); + std::move(request), base::DoNothing()); EXPECT_FALSE(called); fake_mojo_task_runner_->RunPendingTasks();
diff --git a/content/browser/dom_storage/local_storage_context_mojo.cc b/content/browser/dom_storage/local_storage_context_mojo.cc index 5067dec..6699f3f 100644 --- a/content/browser/dom_storage/local_storage_context_mojo.cc +++ b/content/browser/dom_storage/local_storage_context_mojo.cc
@@ -395,10 +395,11 @@ void LocalStorageContextMojo::OpenLocalStorage( const url::Origin& origin, - blink::mojom::StorageAreaRequest request) { + blink::mojom::StorageAreaRequest request, + base::OnceClosure bind_done) { RunWhenConnected(base::BindOnce(&LocalStorageContextMojo::BindLocalStorage, weak_ptr_factory_.GetWeakPtr(), origin, - std::move(request))); + std::move(request), std::move(bind_done))); } void LocalStorageContextMojo::GetStorageUsage( @@ -911,8 +912,10 @@ // directly from that function, or through |on_database_open_callbacks_|. void LocalStorageContextMojo::BindLocalStorage( const url::Origin& origin, - blink::mojom::StorageAreaRequest request) { + blink::mojom::StorageAreaRequest request, + base::OnceClosure bind_done) { GetOrCreateStorageArea(origin)->Bind(std::move(request)); + std::move(bind_done).Run(); } LocalStorageContextMojo::StorageAreaHolder*
diff --git a/content/browser/dom_storage/local_storage_context_mojo.h b/content/browser/dom_storage/local_storage_context_mojo.h index db50fab..5587e884 100644 --- a/content/browser/dom_storage/local_storage_context_mojo.h +++ b/content/browser/dom_storage/local_storage_context_mojo.h
@@ -57,7 +57,8 @@ scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy); void OpenLocalStorage(const url::Origin& origin, - blink::mojom::StorageAreaRequest request); + blink::mojom::StorageAreaRequest request, + base::OnceClosure bind_done); void GetStorageUsage(GetStorageUsageCallback callback); // |callback| is called when the deletion is sent to the database and // GetStorageUsage() will not return entries for |origin| anymore. @@ -123,7 +124,8 @@ // The (possibly delayed) implementation of OpenLocalStorage(). Can be called // directly from that function, or through |on_database_open_callbacks_|. void BindLocalStorage(const url::Origin& origin, - blink::mojom::StorageAreaRequest request); + blink::mojom::StorageAreaRequest request, + base::OnceClosure bind_done); StorageAreaHolder* GetOrCreateStorageArea(const url::Origin& origin); // The (possibly delayed) implementation of GetStorageUsage(). Can be called
diff --git a/content/browser/dom_storage/local_storage_context_mojo_unittest.cc b/content/browser/dom_storage/local_storage_context_mojo_unittest.cc index fee17f17..56b9ba4 100644 --- a/content/browser/dom_storage/local_storage_context_mojo_unittest.cc +++ b/content/browser/dom_storage/local_storage_context_mojo_unittest.cc
@@ -187,8 +187,9 @@ const url::Origin kOrigin = url::Origin::Create(GURL("http://foobar.com")); blink::mojom::StorageAreaPtr area; blink::mojom::StorageAreaPtr dummy_area; // To make sure values are cached. - context()->OpenLocalStorage(kOrigin, MakeRequest(&area)); - context()->OpenLocalStorage(kOrigin, MakeRequest(&dummy_area)); + context()->OpenLocalStorage(kOrigin, MakeRequest(&area), base::DoNothing()); + context()->OpenLocalStorage(kOrigin, MakeRequest(&dummy_area), + base::DoNothing()); std::vector<uint8_t> result; bool success = test::GetSync(area.get(), key, &result); return success ? base::Optional<std::vector<uint8_t>>(result) @@ -222,7 +223,7 @@ blink::mojom::StorageAreaPtr area; context()->OpenLocalStorage(url::Origin::Create(GURL("http://foobar.com")), - MakeRequest(&area)); + MakeRequest(&area), base::DoNothing()); area->Put(key, value, base::nullopt, "source", base::DoNothing()); area.reset(); @@ -241,11 +242,11 @@ auto value = StdStringToUint8Vector("value"); blink::mojom::StorageAreaPtr area; - context()->OpenLocalStorage(origin1, MakeRequest(&area)); + context()->OpenLocalStorage(origin1, MakeRequest(&area), base::DoNothing()); area->Put(key1, value, base::nullopt, "source", base::DoNothing()); area.reset(); - context()->OpenLocalStorage(origin2, MakeRequest(&area)); + context()->OpenLocalStorage(origin2, MakeRequest(&area), base::DoNothing()); area->Put(key2, value, base::nullopt, "source", base::DoNothing()); area.reset(); @@ -261,8 +262,9 @@ blink::mojom::StorageAreaPtr area; blink::mojom::StorageAreaPtr dummy_area; // To make sure values are cached. const url::Origin kOrigin(url::Origin::Create(GURL("http://foobar.com"))); - context()->OpenLocalStorage(kOrigin, MakeRequest(&area)); - context()->OpenLocalStorage(kOrigin, MakeRequest(&dummy_area)); + context()->OpenLocalStorage(kOrigin, MakeRequest(&area), base::DoNothing()); + context()->OpenLocalStorage(kOrigin, MakeRequest(&dummy_area), + base::DoNothing()); area->Put(key, value, base::nullopt, "source", base::DoNothing()); area.reset(); dummy_area.reset(); @@ -290,7 +292,7 @@ // Write some data to the DB. blink::mojom::StorageAreaPtr area; context()->OpenLocalStorage(url::Origin::Create(GURL("http://foobar.com")), - MakeRequest(&area)); + MakeRequest(&area), base::DoNothing()); area->Put(key, value, base::nullopt, "source", base::DoNothing()); area.reset(); base::RunLoop().RunUntilIdle(); @@ -303,7 +305,7 @@ for (int i = 1; i <= 100; ++i) { context()->OpenLocalStorage(url::Origin::Create(GURL(base::StringPrintf( "http://example.com:%d", i))), - MakeRequest(&area)); + MakeRequest(&area), base::DoNothing()); area.reset(); } @@ -348,12 +350,12 @@ base::Time before_write = base::Time::Now(); blink::mojom::StorageAreaPtr area; - context()->OpenLocalStorage(origin1, MakeRequest(&area)); + context()->OpenLocalStorage(origin1, MakeRequest(&area), base::DoNothing()); area->Put(key1, value, base::nullopt, "source", base::DoNothing()); area->Put(key2, value, base::nullopt, "source", base::DoNothing()); area.reset(); - context()->OpenLocalStorage(origin2, MakeRequest(&area)); + context()->OpenLocalStorage(origin2, MakeRequest(&area), base::DoNothing()); area->Put(key2, value, base::nullopt, "source", base::DoNothing()); area.reset(); @@ -395,13 +397,13 @@ auto value = StdStringToUint8Vector("value"); blink::mojom::StorageAreaPtr area; - context()->OpenLocalStorage(origin1, MakeRequest(&area)); + context()->OpenLocalStorage(origin1, MakeRequest(&area), base::DoNothing()); area->Put(key, value, base::nullopt, "source", base::DoNothing()); area.reset(); - context()->OpenLocalStorage(origin2, MakeRequest(&area)); + context()->OpenLocalStorage(origin2, MakeRequest(&area), base::DoNothing()); area->Put(key, value, base::nullopt, "source", base::DoNothing()); area.reset(); - context()->OpenLocalStorage(origin1, MakeRequest(&area)); + context()->OpenLocalStorage(origin1, MakeRequest(&area), base::DoNothing()); area->Delete(key, value, "source", base::DoNothing()); area.reset(); @@ -428,14 +430,14 @@ auto value = StdStringToUint8Vector("value"); blink::mojom::StorageAreaPtr area; - context()->OpenLocalStorage(origin1, MakeRequest(&area)); + context()->OpenLocalStorage(origin1, MakeRequest(&area), base::DoNothing()); area->Put(key, value, base::nullopt, "source", base::DoNothing()); area.reset(); - context()->OpenLocalStorage(origin2, MakeRequest(&area)); + context()->OpenLocalStorage(origin2, MakeRequest(&area), base::DoNothing()); area->Put(key, value, base::nullopt, "source", base::DoNothing()); area.reset(); - context()->OpenLocalStorage(origin1, MakeRequest(&area)); + context()->OpenLocalStorage(origin1, MakeRequest(&area), base::DoNothing()); area->DeleteAll("source", base::DoNothing()); area.reset(); @@ -462,7 +464,7 @@ { blink::mojom::StorageAreaPtr area; - context()->OpenLocalStorage(origin1, MakeRequest(&area)); + context()->OpenLocalStorage(origin1, MakeRequest(&area), base::DoNothing()); area->Put(key, value, base::nullopt, "source", base::DoNothing()); area.reset(); } @@ -478,7 +480,7 @@ // Check that local storage still works without a database. { blink::mojom::StorageAreaPtr area; - context()->OpenLocalStorage(origin1, MakeRequest(&area)); + context()->OpenLocalStorage(origin1, MakeRequest(&area), base::DoNothing()); area->Put(key, value, base::nullopt, "source", base::DoNothing()); area.reset(); } @@ -503,11 +505,11 @@ auto value = StdStringToUint8Vector("value"); blink::mojom::StorageAreaPtr area; - context()->OpenLocalStorage(origin1, MakeRequest(&area)); + context()->OpenLocalStorage(origin1, MakeRequest(&area), base::DoNothing()); area->Put(key, value, base::nullopt, "source", base::DoNothing()); area.reset(); - context()->OpenLocalStorage(origin2, MakeRequest(&area)); + context()->OpenLocalStorage(origin2, MakeRequest(&area), base::DoNothing()); area->Put(key, value, base::nullopt, "source", base::DoNothing()); area.reset(); @@ -538,11 +540,11 @@ auto value = StdStringToUint8Vector("value"); blink::mojom::StorageAreaPtr area; - context()->OpenLocalStorage(origin1, MakeRequest(&area)); + context()->OpenLocalStorage(origin1, MakeRequest(&area), base::DoNothing()); area->Put(key, value, base::nullopt, "source", base::DoNothing()); area.reset(); - context()->OpenLocalStorage(origin2, MakeRequest(&area)); + context()->OpenLocalStorage(origin2, MakeRequest(&area), base::DoNothing()); area->Put(key, value, base::nullopt, "source", base::DoNothing()); area.reset(); @@ -551,7 +553,7 @@ EXPECT_FALSE(mock_data().empty()); TestLevelDBObserver observer; - context()->OpenLocalStorage(origin1, MakeRequest(&area)); + context()->OpenLocalStorage(origin1, MakeRequest(&area), base::DoNothing()); area->AddObserver(observer.Bind()); base::RunLoop().RunUntilIdle(); @@ -582,11 +584,11 @@ auto value = StdStringToUint8Vector("value"); blink::mojom::StorageAreaPtr area; - context()->OpenLocalStorage(origin1, MakeRequest(&area)); + context()->OpenLocalStorage(origin1, MakeRequest(&area), base::DoNothing()); area->Put(key, value, base::nullopt, "source", base::DoNothing()); area.reset(); - context()->OpenLocalStorage(origin2, MakeRequest(&area)); + context()->OpenLocalStorage(origin2, MakeRequest(&area), base::DoNothing()); area->Put(key, value, base::nullopt, "source", base::DoNothing()); area.reset(); @@ -595,7 +597,7 @@ EXPECT_FALSE(mock_data().empty()); TestLevelDBObserver observer; - context()->OpenLocalStorage(origin1, MakeRequest(&area)); + context()->OpenLocalStorage(origin1, MakeRequest(&area), base::DoNothing()); area->AddObserver(observer.Bind()); area->Put(StdStringToUint8Vector("key2"), value, base::nullopt, "source", base::DoNothing()); @@ -645,9 +647,10 @@ // Opening origin2 and accessing its data should not migrate anything. blink::mojom::StorageAreaPtr area; - context()->OpenLocalStorage(origin2, MakeRequest(&area)); + context()->OpenLocalStorage(origin2, MakeRequest(&area), base::DoNothing()); blink::mojom::StorageAreaPtr dummy_area; // To make sure values are cached. - context()->OpenLocalStorage(origin2, MakeRequest(&dummy_area)); + context()->OpenLocalStorage(origin2, MakeRequest(&dummy_area), + base::DoNothing()); area->Get(std::vector<uint8_t>(), base::DoNothing()); area.reset(); dummy_area.reset(); @@ -655,8 +658,9 @@ EXPECT_TRUE(mock_data().empty()); // Opening origin1 and accessing its data should migrate its storage. - context()->OpenLocalStorage(origin1, MakeRequest(&area)); - context()->OpenLocalStorage(origin1, MakeRequest(&dummy_area)); + context()->OpenLocalStorage(origin1, MakeRequest(&area), base::DoNothing()); + context()->OpenLocalStorage(origin1, MakeRequest(&dummy_area), + base::DoNothing()); area->Get(std::vector<uint8_t>(), base::DoNothing()); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(mock_data().empty()); @@ -711,9 +715,9 @@ blink::mojom::StorageAreaPtr area; blink::mojom::StorageAreaPtr dummy_area; // To make sure values are cached. context()->OpenLocalStorage(url::Origin::Create(GURL("http://foobar.com")), - MakeRequest(&area)); + MakeRequest(&area), base::DoNothing()); context()->OpenLocalStorage(url::Origin::Create(GURL("http://foobar.com")), - MakeRequest(&dummy_area)); + MakeRequest(&dummy_area), base::DoNothing()); { std::vector<uint8_t> result; @@ -749,12 +753,12 @@ auto value = StdStringToUint8Vector("value"); blink::mojom::StorageAreaPtr area; - context()->OpenLocalStorage(origin1, MakeRequest(&area)); + context()->OpenLocalStorage(origin1, MakeRequest(&area), base::DoNothing()); area->Put(key1, value, base::nullopt, "source", base::DoNothing()); area->Put(key2, value, base::nullopt, "source", base::DoNothing()); area.reset(); - context()->OpenLocalStorage(origin2, MakeRequest(&area)); + context()->OpenLocalStorage(origin2, MakeRequest(&area), base::DoNothing()); area->Put(key2, value, base::nullopt, "source", base::DoNothing()); area.reset(); @@ -791,7 +795,7 @@ bool success = false; base::RunLoop run_loop; context->OpenLocalStorage(url::Origin::Create(GURL("http://foobar.com")), - MakeRequest(&area)); + MakeRequest(&area), base::DoNothing()); area->Put(key, value, base::nullopt, "source", test::MakeSuccessCallback(run_loop.QuitClosure(), &success)); run_loop.Run(); @@ -805,7 +809,7 @@ std::vector<uint8_t>* result) { blink::mojom::StorageAreaPtr area; context->OpenLocalStorage(url::Origin::Create(GURL("http://foobar.com")), - MakeRequest(&area)); + MakeRequest(&area), base::DoNothing()); base::RunLoop run_loop; std::vector<blink::mojom::KeyValuePtr> data; @@ -857,7 +861,7 @@ blink::mojom::StorageAreaPtr area; context->OpenLocalStorage(url::Origin::Create(GURL("http://foobar.com")), - MakeRequest(&area)); + MakeRequest(&area), base::DoNothing()); DoTestPut(context, key, value); std::vector<uint8_t> result; EXPECT_TRUE(DoTestGet(context, key, &result)); @@ -887,7 +891,7 @@ blink::mojom::StorageAreaPtr area; context->OpenLocalStorage(url::Origin::Create(GURL("http://foobar.com")), - MakeRequest(&area)); + MakeRequest(&area), base::DoNothing()); DoTestPut(context, key, value); std::vector<uint8_t> result; @@ -1061,11 +1065,11 @@ base::RunLoop loop; mock_leveldb_service.SetOnOpenCallback(loop.QuitClosure()); context->OpenLocalStorage(url::Origin::Create(GURL("http://foobar.com")), - MakeRequest(&area1)); + MakeRequest(&area1), base::DoNothing()); context->OpenLocalStorage(url::Origin::Create(GURL("http://foobar.com")), - MakeRequest(&area2)); + MakeRequest(&area2), base::DoNothing()); context->OpenLocalStorage(url::Origin::Create(GURL("http://example.com")), - MakeRequest(&area3)); + MakeRequest(&area3), base::DoNothing()); loop.Run(); } @@ -1135,7 +1139,7 @@ // Reconnect area1 to the database, and try to read a value. context->OpenLocalStorage(url::Origin::Create(GURL("http://foobar.com")), - MakeRequest(&area1)); + MakeRequest(&area1), base::DoNothing()); base::RunLoop delete_loop; bool success = true; TestLevelDBObserver observer3; @@ -1207,7 +1211,7 @@ base::RunLoop loop; mock_leveldb_service.SetOnOpenCallback(loop.QuitClosure()); context->OpenLocalStorage(url::Origin::Create(GURL("http://foobar.com")), - MakeRequest(&area)); + MakeRequest(&area), base::DoNothing()); loop.Run(); } @@ -1275,7 +1279,7 @@ // This time all should just keep getting written, and commit errors are // getting ignored. context->OpenLocalStorage(url::Origin::Create(GURL("http://foobar.com")), - MakeRequest(&area)); + MakeRequest(&area), base::DoNothing()); old_value = base::nullopt; for (int i = 0; i < 64; ++i) { base::RunLoop put_loop;
diff --git a/content/browser/dom_storage/session_storage_context_mojo.cc b/content/browser/dom_storage/session_storage_context_mojo.cc index 5439973..408b6138 100644 --- a/content/browser/dom_storage/session_storage_context_mojo.cc +++ b/content/browser/dom_storage/session_storage_context_mojo.cc
@@ -128,12 +128,14 @@ int process_id, const std::string& namespace_id, mojo::ReportBadMessageCallback bad_message_callback, - blink::mojom::SessionStorageNamespaceRequest request) { + blink::mojom::SessionStorageNamespaceRequest request, + base::OnceClosure bind_done) { if (connection_state_ != CONNECTION_FINISHED) { RunWhenConnected( base::BindOnce(&SessionStorageContextMojo::OpenSessionStorage, weak_ptr_factory_.GetWeakPtr(), process_id, namespace_id, - std::move(bad_message_callback), std::move(request))); + std::move(bad_message_callback), std::move(request), + std::move(bind_done))); return; } auto found = namespaces_.find(namespace_id); @@ -150,6 +152,7 @@ PurgeUnusedAreasIfNeeded(); found->second->Bind(std::move(request), process_id); + std::move(bind_done).Run(); size_t total_cache_size, unused_area_count; GetStatistics(&total_cache_size, &unused_area_count);
diff --git a/content/browser/dom_storage/session_storage_context_mojo.h b/content/browser/dom_storage/session_storage_context_mojo.h index e1ebd6bf..33ba435 100644 --- a/content/browser/dom_storage/session_storage_context_mojo.h +++ b/content/browser/dom_storage/session_storage_context_mojo.h
@@ -85,7 +85,8 @@ void OpenSessionStorage(int process_id, const std::string& namespace_id, mojo::ReportBadMessageCallback bad_message_callback, - blink::mojom::SessionStorageNamespaceRequest request); + blink::mojom::SessionStorageNamespaceRequest request, + base::OnceClosure bind_done); void CreateSessionNamespace(const std::string& namespace_id); void CloneSessionNamespace(const std::string& namespace_id_to_clone,
diff --git a/content/browser/dom_storage/session_storage_context_mojo_unittest.cc b/content/browser/dom_storage/session_storage_context_mojo_unittest.cc index f5a6325..7c1e0d6 100644 --- a/content/browser/dom_storage/session_storage_context_mojo_unittest.cc +++ b/content/browser/dom_storage/session_storage_context_mojo_unittest.cc
@@ -121,9 +121,9 @@ const std::string& source) { context()->CreateSessionNamespace(namespace_id); blink::mojom::SessionStorageNamespacePtr ss_namespace; - context()->OpenSessionStorage(kTestProcessId, namespace_id, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb; ss_namespace->OpenArea(origin, mojo::MakeRequest(&leveldb)); EXPECT_TRUE(test::PutSync( @@ -138,9 +138,9 @@ base::StringPiece key) { context()->CreateSessionNamespace(namespace_id); blink::mojom::SessionStorageNamespacePtr ss_namespace; - context()->OpenSessionStorage(kTestProcessId, namespace_id, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb; ss_namespace->OpenArea(origin, mojo::MakeRequest(&leveldb)); @@ -201,13 +201,13 @@ context()->CreateSessionNamespace(namespace_id2); blink::mojom::SessionStorageNamespacePtr ss_namespace1; - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); blink::mojom::SessionStorageNamespacePtr ss_namespace2; - context()->OpenSessionStorage(kTestProcessId, namespace_id2, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace2)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id2, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace2), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb_n2_o1; blink::mojom::StorageAreaAssociatedPtr leveldb_n2_o2; @@ -235,9 +235,9 @@ context()->CreateSessionNamespace(namespace_id1); blink::mojom::SessionStorageNamespacePtr ss_namespace1; - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb_n1_o1; ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb_n1_o1)); @@ -263,9 +263,9 @@ // This will re-open the context, and load the persisted namespace. context()->CreateSessionNamespace(namespace_id1); - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb_n1_o1)); // The data from before should be here. @@ -278,9 +278,9 @@ // This will re-open the context, and the namespace should be empty. context()->CreateSessionNamespace(namespace_id1); - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb_n1_o1)); // The data from before should not be here. @@ -294,9 +294,9 @@ url::Origin origin1 = url::Origin::Create(GURL("http://foobar.com")); context()->CreateSessionNamespace(namespace_id1); blink::mojom::SessionStorageNamespacePtr ss_namespace1; - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb_n1_o1; ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb_n1_o1)); @@ -315,9 +315,9 @@ // Open the second namespace. blink::mojom::SessionStorageNamespacePtr ss_namespace2; - context()->OpenSessionStorage(kTestProcessId, namespace_id2, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace2)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id2, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace2), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb_n2_o1; ss_namespace2->OpenArea(origin1, mojo::MakeRequest(&leveldb_n2_o1)); @@ -333,9 +333,9 @@ url::Origin origin1 = url::Origin::Create(GURL("http://foobar.com")); context()->CreateSessionNamespace(namespace_id1); blink::mojom::SessionStorageNamespacePtr ss_namespace1; - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb_n1_o1; ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb_n1_o1)); @@ -355,9 +355,9 @@ // Open the second namespace. blink::mojom::SessionStorageNamespacePtr ss_namespace2; - context()->OpenSessionStorage(kTestProcessId, namespace_id2, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace2)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id2, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace2), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb_n2_o1; ss_namespace2->OpenArea(origin1, mojo::MakeRequest(&leveldb_n2_o1)); @@ -380,9 +380,9 @@ // Re-open namespace 1, check that we don't have the extra data. context()->CreateSessionNamespace(namespace_id1); - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb_n1_o1)); // We should only have the first value. @@ -397,9 +397,9 @@ url::Origin origin1 = url::Origin::Create(GURL("http://foobar.com")); context()->CreateSessionNamespace(namespace_id1); blink::mojom::SessionStorageNamespacePtr ss_namespace1; - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb_n1_o1; ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb_n1_o1)); @@ -411,9 +411,9 @@ // Open the second namespace, ensure empty. { blink::mojom::SessionStorageNamespacePtr ss_namespace2; - context()->OpenSessionStorage(kTestProcessId, namespace_id2, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace2)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id2, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace2), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb_n2_o1; ss_namespace2->OpenArea(origin1, mojo::MakeRequest(&leveldb_n2_o1)); std::vector<blink::mojom::KeyValuePtr> data; @@ -436,9 +436,9 @@ // Open the second namespace, ensure populated { blink::mojom::SessionStorageNamespacePtr ss_namespace2; - context()->OpenSessionStorage(kTestProcessId, namespace_id2, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace2)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id2, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace2), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb_n2_o1; ss_namespace2->OpenArea(origin1, mojo::MakeRequest(&leveldb_n2_o1)); std::vector<blink::mojom::KeyValuePtr> data; @@ -483,9 +483,9 @@ context()->CreateSessionNamespace(namespace_id1); blink::mojom::SessionStorageNamespacePtr ss_namespace1; - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb_n1_o1; ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb_n1_o1)); EXPECT_TRUE(test::PutSync( @@ -517,9 +517,9 @@ // Re-open the context, load the persisted namespace, and verify we still have // data. context()->CreateSessionNamespace(namespace_id1); - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb_n1_o1)); std::vector<blink::mojom::KeyValuePtr> data; EXPECT_TRUE(test::GetAllSync(leveldb_n1_o1.get(), &data)); @@ -537,9 +537,9 @@ loop.Run(); } context()->CreateSessionNamespace(namespace_id1); - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb_n1_o1)); EXPECT_TRUE(test::GetAllSync(leveldb_n1_o1.get(), &data)); EXPECT_EQ(0ul, data.size()); @@ -644,9 +644,9 @@ { base::RunLoop loop; fake_leveldb_service.SetOnOpenCallback(loop.QuitClosure()); - context()->OpenSessionStorage(kTestProcessId, namespace_id, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace), base::DoNothing()); ss_namespace->OpenArea(origin1, mojo::MakeRequest(&area1)); ss_namespace->OpenArea(origin2, mojo::MakeRequest(&area2)); ss_namespace->OpenArea(origin3, mojo::MakeRequest(&area3)); @@ -718,9 +718,9 @@ EXPECT_EQ(1u, fake_leveldb_service.destroy_requests().size()); // Reconnect area1 to the database, and try to read a value. - context()->OpenSessionStorage(kTestProcessId, namespace_id, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace), base::DoNothing()); ss_namespace->OpenArea(origin1, mojo::MakeRequest(&area1)); base::RunLoop delete_loop; @@ -780,9 +780,9 @@ { base::RunLoop loop; fake_leveldb_service.SetOnOpenCallback(loop.QuitClosure()); - context()->OpenSessionStorage(kTestProcessId, namespace_id, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace), base::DoNothing()); ss_namespace->OpenArea(origin1, mojo::MakeRequest(&area)); loop.Run(); } @@ -852,9 +852,9 @@ // Reconnect a area to the database, and repeatedly write data to it again. // This time all should just keep getting written, and commit errors are // getting ignored. - context()->OpenSessionStorage(kTestProcessId, namespace_id, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace), base::DoNothing()); ss_namespace->OpenArea(origin1, mojo::MakeRequest(&area)); old_value = base::nullopt; for (int i = 0; i < 64; ++i) { @@ -892,9 +892,9 @@ url::Origin origin1 = url::Origin::Create(GURL("http://foobar.com")); context()->CreateSessionNamespace(namespace_id1); blink::mojom::SessionStorageNamespacePtr ss_namespace1; - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb_n1_o1; ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb_n1_o1)); // Put some data. @@ -933,9 +933,9 @@ // Put some data. context()->CreateSessionNamespace(namespace_id); blink::mojom::SessionStorageNamespacePtr ss_namespace; - context()->OpenSessionStorage(kTestProcessId, namespace_id, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr area; ss_namespace->OpenArea(origin, mojo::MakeRequest(&area)); EXPECT_TRUE(test::PutSync(area.get(), key, value, base::nullopt, "source")); @@ -950,9 +950,9 @@ base::RunLoop().RunUntilIdle(); context()->CreateSessionNamespace(namespace_id); - context()->OpenSessionStorage(kTestProcessId, namespace_id, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace), base::DoNothing()); ss_namespace->OpenArea(origin, mojo::MakeRequest(&area)); // We can't access the data anymore. @@ -976,9 +976,9 @@ ShutdownContext(); context()->CreateSessionNamespace(namespace_id); - context()->OpenSessionStorage(kTestProcessId, namespace_id, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace), base::DoNothing()); ss_namespace->OpenArea(origin, mojo::MakeRequest(&area)); ASSERT_TRUE(test::GetAllSync(area.get(), &data)); @@ -992,9 +992,9 @@ // First, test deleting data for a namespace that is open. context()->CreateSessionNamespace(namespace_id1); blink::mojom::SessionStorageNamespacePtr ss_namespace1; - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb_n1_o1; ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb_n1_o1)); @@ -1023,9 +1023,9 @@ context()->DeleteStorage(origin1, namespace_id1, base::DoNothing()); context()->CreateSessionNamespace(namespace_id1); - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb_n1_o1)); data.clear(); EXPECT_TRUE(test::GetAllSync(leveldb_n1_o1.get(), &data)); @@ -1039,9 +1039,9 @@ context()->CreateSessionNamespace(namespace_id1); blink::mojom::SessionStorageNamespacePtr ss_namespace1; - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb; ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb)); @@ -1067,9 +1067,9 @@ // Now open many new wrappers (for different origins) to trigger clean up. for (int i = 1; i <= 100; ++i) { blink::mojom::SessionStorageNamespacePtr ss_namespace1; - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb; ss_namespace1->OpenArea(url::Origin::Create(GURL(base::StringPrintf( "http://example.com:%d", i))), @@ -1080,9 +1080,9 @@ } // And make sure caches were actually cleared. - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb)); std::vector<blink::mojom::KeyValuePtr> data; ASSERT_TRUE(test::GetAllSync(leveldb.get(), &data)); @@ -1096,9 +1096,9 @@ context()->CreateSessionNamespace(namespace_id1); blink::mojom::SessionStorageNamespacePtr ss_namespace1; - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb_n1_o1; ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb_n1_o1)); @@ -1121,9 +1121,9 @@ // This will re-open the context, and load the persisted namespace, but it // should have been deleted due to our backing mode. context()->CreateSessionNamespace(namespace_id1); - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb_n1_o1)); // The data from before should not be here, because the context clears disk @@ -1141,17 +1141,17 @@ context()->CreateSessionNamespace(namespace_id1); blink::mojom::SessionStorageNamespacePtr ss_namespace1; - context()->OpenSessionStorage(kTestProcessId, namespace_id1, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace1)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id1, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace1), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb_n1_o1; ss_namespace1->OpenArea(origin1, mojo::MakeRequest(&leveldb_n1_o1)); context()->CreateSessionNamespace(namespace_id2); blink::mojom::SessionStorageNamespacePtr ss_namespace2; - context()->OpenSessionStorage(kTestProcessId, namespace_id2, - GetBadMessageCallback(), - mojo::MakeRequest(&ss_namespace2)); + context()->OpenSessionStorage( + kTestProcessId, namespace_id2, GetBadMessageCallback(), + mojo::MakeRequest(&ss_namespace2), base::DoNothing()); blink::mojom::StorageAreaAssociatedPtr leveldb_n2_o1; ss_namespace2->OpenArea(origin1, mojo::MakeRequest(&leveldb_n2_o1));
diff --git a/content/browser/download/download_manager_impl.cc b/content/browser/download/download_manager_impl.cc index 2d45e9e..11316e3 100644 --- a/content/browser/download/download_manager_impl.cc +++ b/content/browser/download/download_manager_impl.cc
@@ -505,6 +505,9 @@ info.referrer_url, Referrer::NetReferrerPolicyToBlinkReferrerPolicy( info.referrer_policy)); params.redirect_chain = url_chain; + params.frame_tree_node_id = + RenderFrameHost::GetFrameTreeNodeIdForRoutingId( + info.render_process_id, info.render_frame_id); web_contents->GetController().LoadURLWithParams(params); } if (info.request_handle) @@ -803,7 +806,8 @@ params->referrer_policy())), true, // download. params->render_process_host_id(), params->render_view_host_routing_id(), - params->render_frame_host_routing_id(), PREVIEWS_OFF, resource_context); + params->render_frame_host_routing_id(), params->frame_tree_node_id(), + PREVIEWS_OFF, resource_context); // We treat a download as a main frame load, and thus update the policy URL on // redirects. @@ -914,6 +918,8 @@ params->download_source()); auto* rfh = RenderFrameHost::FromID(params->render_process_host_id(), params->render_frame_host_routing_id()); + if (rfh) + params->set_frame_tree_node_id(rfh->GetFrameTreeNodeId()); BeginDownloadInternal(std::move(params), std::move(blob_data_handle), std::move(blob_url_loader_factory), true, rfh ? rfh->GetSiteInstance()->GetSiteURL() : GURL());
diff --git a/content/browser/download/download_resource_handler.cc b/content/browser/download/download_resource_handler.cc index e595dd5..45486039 100644 --- a/content/browser/download/download_resource_handler.cc +++ b/content/browser/download/download_resource_handler.cc
@@ -120,12 +120,12 @@ void DeleteOnUIThread( std::unique_ptr<DownloadResourceHandler::DownloadTabInfo> tab_info) {} -void NavigateOnUIThread( - const GURL& url, - const std::vector<GURL> url_chain, - const Referrer& referrer, - bool has_user_gesture, - const ResourceRequestInfo::WebContentsGetter& wc_getter) { +void NavigateOnUIThread(const GURL& url, + const std::vector<GURL> url_chain, + const Referrer& referrer, + bool has_user_gesture, + const ResourceRequestInfo::WebContentsGetter& wc_getter, + int frame_tree_node_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); WebContents* web_contents = wc_getter.Run(); @@ -134,6 +134,7 @@ params.has_user_gesture = has_user_gesture; params.referrer = referrer; params.redirect_chain = url_chain; + params.frame_tree_node_id = frame_tree_node_id; web_contents->GetController().LoadURLWithParams(params); } } @@ -209,7 +210,8 @@ Referrer::NetReferrerPolicyToBlinkReferrerPolicy( redirect_info.new_referrer_policy)), GetRequestInfo()->HasUserGesture(), - GetRequestInfo()->GetWebContentsGetterForRequest())); + GetRequestInfo()->GetWebContentsGetterForRequest(), + GetRequestInfo()->frame_tree_node_id())); controller->Cancel(); return; }
diff --git a/content/browser/frame_host/cross_process_frame_connector.cc b/content/browser/frame_host/cross_process_frame_connector.cc index 1024c39..3ce255c 100644 --- a/content/browser/frame_host/cross_process_frame_connector.cc +++ b/content/browser/frame_host/cross_process_frame_connector.cc
@@ -276,7 +276,7 @@ root_view->GestureEventAck(root_event, ack_result); } -void CrossProcessFrameConnector::BubbleScrollEvent( +bool CrossProcessFrameConnector::BubbleScrollEvent( const blink::WebGestureEvent& event) { DCHECK(event.GetType() == blink::WebInputEvent::kGestureScrollBegin || event.GetType() == blink::WebInputEvent::kGestureScrollUpdate || @@ -284,7 +284,7 @@ auto* parent_view = GetParentRenderWidgetHostView(); if (!parent_view) - return; + return false; auto* event_router = parent_view->host()->delegate()->GetInputEventRouter(); @@ -300,7 +300,8 @@ // action of the parent frame to Auto so that this gesture event is allowed. parent_view->host()->input_router()->ForceSetTouchActionAuto(); - event_router->BubbleScrollEvent(parent_view, view_, resent_gesture_event); + return event_router->BubbleScrollEvent(parent_view, view_, + resent_gesture_event); } bool CrossProcessFrameConnector::HasFocus() {
diff --git a/content/browser/frame_host/cross_process_frame_connector.h b/content/browser/frame_host/cross_process_frame_connector.h index cf9648bf..ae968b8 100644 --- a/content/browser/frame_host/cross_process_frame_connector.h +++ b/content/browser/frame_host/cross_process_frame_connector.h
@@ -99,7 +99,7 @@ viz::EventSource source = viz::EventSource::ANY) override; void ForwardAckedTouchpadZoomEvent(const blink::WebGestureEvent& event, InputEventAckState ack_result) override; - void BubbleScrollEvent(const blink::WebGestureEvent& event) override; + bool BubbleScrollEvent(const blink::WebGestureEvent& event) override; bool HasFocus() override; void FocusRootView() override; bool LockMouse() override;
diff --git a/content/browser/frame_host/navigation_controller_impl_browsertest.cc b/content/browser/frame_host/navigation_controller_impl_browsertest.cc index 1214201c..465d40d 100644 --- a/content/browser/frame_host/navigation_controller_impl_browsertest.cc +++ b/content/browser/frame_host/navigation_controller_impl_browsertest.cc
@@ -100,6 +100,16 @@ } }; +// Base class for tests that need to supply modifications to EmbeddedTestServer +// which are required to be complete before it is started. +class NavigationControllerBrowserTestNoServer : public ContentBrowserTest { + protected: + void SetUpOnMainThread() override { + host_resolver()->AddRule("*", "127.0.0.1"); + content::SetupCrossSiteRedirector(embedded_test_server()); + } +}; + // Ensure that tests can navigate subframes cross-site in both default mode and // --site-per-process, but that they only go cross-process in the latter. IN_PROC_BROWSER_TEST_F(NavigationControllerBrowserTest, LoadCrossSiteSubframe) { @@ -8901,4 +8911,49 @@ EXPECT_EQ(1, controller.GetLastCommittedEntryIndex()); } +// Tests that a same document navigation followed by a client redirect +// do not add any more session history entries and going to previous entry +// works. +// It replaces invalidly behaving unit test added for http://crbug.com/40395. +IN_PROC_BROWSER_TEST_F(NavigationControllerBrowserTestNoServer, + ClientRedirectAfterSameDocumentNavigation) { + net::test_server::ControllableHttpResponse response(embedded_test_server(), + "/foo.html"); + ASSERT_TRUE(embedded_test_server()->Start()); + NavigationControllerImpl& controller = static_cast<NavigationControllerImpl&>( + shell()->web_contents()->GetController()); + + // Load an initial page, which the test will eventually go back to. + const GURL start_url(embedded_test_server()->GetURL("/title1.html")); + EXPECT_TRUE(NavigateToURL(shell(), start_url)); + EXPECT_EQ(start_url, controller.GetLastCommittedEntry()->GetURL()); + + const GURL main_url(embedded_test_server()->GetURL("/foo.html")); + const GURL last_url(embedded_test_server()->GetURL("/title3.html")); + + // Navigate to foo.html which will do a same document navigation and client + // redirect. + TestNavigationManager observer(shell()->web_contents(), last_url); + shell()->LoadURL(main_url); + response.WaitForRequest(); + response.Send( + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html; charset=utf-8\r\n" + "\r\n" + "<html><script>" + "window.location.replace('#a');" + "window.location='/title3.html';" + "</script></html>"); + observer.WaitForNavigationFinished(); + + EXPECT_EQ(last_url, controller.GetLastCommittedEntry()->GetURL()); + EXPECT_EQ(2, controller.GetEntryCount()); + EXPECT_TRUE(controller.CanGoBack()); + + TestNavigationObserver back_load_observer(shell()->web_contents()); + controller.GoBack(); + back_load_observer.Wait(); + EXPECT_EQ(start_url, controller.GetLastCommittedEntry()->GetURL()); +} + } // namespace content
diff --git a/content/browser/frame_host/navigation_controller_impl_unittest.cc b/content/browser/frame_host/navigation_controller_impl_unittest.cc index d380682..4413e750 100644 --- a/content/browser/frame_host/navigation_controller_impl_unittest.cc +++ b/content/browser/frame_host/navigation_controller_impl_unittest.cc
@@ -1905,47 +1905,34 @@ const GURL url2("http://foo2"); // Redirection target // First request. - controller.LoadURL( - url1, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); - int entry_id = controller.GetPendingEntry()->GetUniqueID(); + auto navigation = + NavigationSimulatorImpl::CreateBrowserInitiated(url1, contents()); + navigation->Start(); EXPECT_EQ(0U, navigation_entry_changed_counter_); EXPECT_EQ(0U, navigation_list_pruned_counter_); - FrameHostMsg_DidCommitProvisionalLoad_Params params; - params.nav_entry_id = entry_id; - params.did_create_new_entry = true; - params.url = url2; - params.transition = ui::PAGE_TRANSITION_SERVER_REDIRECT; - params.redirects.push_back(GURL("http://foo1")); - params.redirects.push_back(GURL("http://foo2")); - params.should_update_history = false; - params.gesture = NavigationGestureAuto; - params.method = "GET"; - params.page_state = PageState::CreateFromURL(url2); - - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigateWithParams(¶ms, false); + navigation->Redirect(url2); + navigation->Commit(); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; // Second request. - controller.LoadURL( - url1, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); - entry_id = controller.GetPendingEntry()->GetUniqueID(); + auto navigation2 = + NavigationSimulatorImpl::CreateBrowserInitiated(url1, contents()); + navigation2->Start(); EXPECT_TRUE(controller.GetPendingEntry()); EXPECT_EQ(controller.GetPendingEntryIndex(), -1); EXPECT_EQ(url1, controller.GetVisibleEntry()->GetURL()); - params.nav_entry_id = entry_id; - params.did_create_new_entry = false; - EXPECT_EQ(0U, navigation_entry_changed_counter_); EXPECT_EQ(0U, navigation_list_pruned_counter_); + LoadCommittedDetailsObserver observer(contents()); - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigateWithParams(¶ms, false); + navigation2->set_did_create_new_entry(false); + navigation2->Redirect(url2); + navigation2->Commit(); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; @@ -1971,49 +1958,36 @@ const GURL url2("http://foo2"); // Redirection target // First request as POST. - controller.LoadURL( - url1, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); - int entry_id = controller.GetPendingEntry()->GetUniqueID(); - controller.GetVisibleEntry()->SetHasPostData(true); + auto navigation = + NavigationSimulatorImpl::CreateBrowserInitiated(url1, contents()); + navigation->SetMethod("POST"); + navigation->Start(); EXPECT_EQ(0U, navigation_entry_changed_counter_); EXPECT_EQ(0U, navigation_list_pruned_counter_); - FrameHostMsg_DidCommitProvisionalLoad_Params params; - params.nav_entry_id = entry_id; - params.did_create_new_entry = true; - params.url = url2; - params.transition = ui::PAGE_TRANSITION_SERVER_REDIRECT; - params.redirects.push_back(GURL("http://foo1")); - params.redirects.push_back(GURL("http://foo2")); - params.should_update_history = false; - params.gesture = NavigationGestureAuto; - params.method = "POST"; - params.page_state = PageState::CreateFromURL(url2); - - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigateWithParams(¶ms, false); + navigation->Redirect(url2); + navigation->Commit(); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; // Second request. - controller.LoadURL( - url1, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); - entry_id = controller.GetPendingEntry()->GetUniqueID(); + auto navigation2 = + NavigationSimulatorImpl::CreateBrowserInitiated(url1, contents()); + navigation2->Start(); EXPECT_TRUE(controller.GetPendingEntry()); EXPECT_EQ(controller.GetPendingEntryIndex(), -1); EXPECT_EQ(url1, controller.GetVisibleEntry()->GetURL()); - params.nav_entry_id = entry_id; - params.did_create_new_entry = false; - params.method = "GET"; - EXPECT_EQ(0U, navigation_entry_changed_counter_); EXPECT_EQ(0U, navigation_list_pruned_counter_); + LoadCommittedDetailsObserver observer(contents()); - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigateWithParams(¶ms, false); + navigation2->set_did_create_new_entry(false); + navigation2->Redirect(GURL("http://foo2")); + navigation2->Commit(); + EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; @@ -2038,32 +2012,19 @@ const GURL url2("http://foo2"); // Redirection target // First request - controller.LoadURL( - url1, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); - int entry_id = controller.GetPendingEntry()->GetUniqueID(); - + auto navigation = + NavigationSimulatorImpl::CreateBrowserInitiated(url1, contents()); + navigation->Start(); EXPECT_TRUE(controller.GetPendingEntry()); EXPECT_EQ(controller.GetPendingEntryIndex(), -1); EXPECT_EQ(url1, controller.GetVisibleEntry()->GetURL()); - FrameHostMsg_DidCommitProvisionalLoad_Params params; - params.nav_entry_id = entry_id; - params.did_create_new_entry = true; - params.url = url2; - params.transition = ui::PAGE_TRANSITION_SERVER_REDIRECT; - params.redirects.push_back(GURL("http://foo1")); - params.redirects.push_back(GURL("http://foo2")); - params.should_update_history = false; - params.gesture = NavigationGestureAuto; - params.method = "GET"; - params.page_state = PageState::CreateFromURL(url2); - - LoadCommittedDetailsObserver observer(contents()); - EXPECT_EQ(0U, navigation_entry_changed_counter_); EXPECT_EQ(0U, navigation_list_pruned_counter_); - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigateWithParams(¶ms, false); + + LoadCommittedDetailsObserver observer(contents()); + navigation->Redirect(GURL("http://foo2")); + navigation->Commit(); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; @@ -2141,55 +2102,15 @@ navigation_entry_committed_counter_ = 0; // Prereq: add a subframe with an initial auto-subframe navigation. - std::string unique_name("uniqueName0"); - main_test_rfh()->OnCreateChildFrame( - process()->GetNextRoutingID(), - TestRenderFrameHost::CreateStubInterfaceProviderRequest(), - TestRenderFrameHost::CreateStubDocumentInterfaceBrokerRequest(), - TestRenderFrameHost::CreateStubDocumentInterfaceBrokerRequest(), - blink::WebTreeScopeType::kDocument, std::string(), unique_name, false, - base::UnguessableToken::Create(), blink::FramePolicy(), - FrameOwnerProperties(), blink::FrameOwnerElementType::kIframe); - TestRenderFrameHost* subframe = static_cast<TestRenderFrameHost*>( - contents()->GetFrameTree()->root()->child_at(0)->current_frame_host()); const GURL subframe_url("http://foo1/subframe"); - { - FrameHostMsg_DidCommitProvisionalLoad_Params params; - params.nav_entry_id = 0; - params.did_create_new_entry = false; - params.url = subframe_url; - params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME; - params.should_update_history = false; - params.gesture = NavigationGestureUser; - params.method = "GET"; - params.page_state = PageState::CreateFromURL(subframe_url); - - // Navigating should do nothing. - subframe->SendRendererInitiatedNavigationRequest(subframe_url, false); - subframe->PrepareForCommit(); - subframe->SendNavigateWithParams(¶ms, false); - - // We notify of a PageState update here rather than during UpdateState for - // auto subframe navigations. - EXPECT_EQ(1u, navigation_entry_changed_counter_); - } + TestRenderFrameHost* subframe = main_test_rfh()->AppendChild("subframe"); + NavigationSimulator::NavigateAndCommitFromDocument(subframe_url, subframe); + EXPECT_EQ(1u, navigation_entry_changed_counter_); // Now do a new navigation in the frame. const GURL url2("http://foo2"); - FrameHostMsg_DidCommitProvisionalLoad_Params params; - params.nav_entry_id = 0; - params.did_create_new_entry = true; - params.url = url2; - params.transition = ui::PAGE_TRANSITION_MANUAL_SUBFRAME; - params.should_update_history = false; - params.gesture = NavigationGestureUser; - params.method = "GET"; - params.page_state = PageState::CreateFromURL(url2); - LoadCommittedDetailsObserver observer(contents()); - subframe->SendRendererInitiatedNavigationRequest(url2, true); - subframe->PrepareForCommit(); - subframe->SendNavigateWithParams(¶ms, false); + NavigationSimulator::NavigateAndCommitFromDocument(url2, subframe); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; EXPECT_EQ(url1, observer.previous_url()); @@ -2725,96 +2646,6 @@ EXPECT_EQ(1, controller.GetEntryCount()); } -// Tests for http://crbug.com/40395 -// Simulates this: -// <script> -// window.location.replace("#a"); -// window.location='http://foo3/'; -// </script> -TEST_F(NavigationControllerTest, ClientRedirectAfterSameDocumentNavigation) { - NavigationControllerImpl& controller = controller_impl(); - - // Load an initial page. - { - const GURL url("http://foo/"); - NavigationSimulator::NavigateAndCommitFromDocument(url, main_test_rfh()); - EXPECT_EQ(1U, navigation_entry_committed_counter_); - navigation_entry_committed_counter_ = 0; - } - - // Navigate to a new page. - { - const GURL url("http://foo2/"); - NavigationSimulator::NavigateAndCommitFromDocument(url, main_test_rfh()); - EXPECT_EQ(1U, navigation_entry_committed_counter_); - navigation_entry_committed_counter_ = 0; - } - - // Perform same-document navigation using location.replace. - { - const GURL url("http://foo2/#a"); - FrameHostMsg_DidCommitProvisionalLoad_Params params; - params.nav_entry_id = 0; - params.did_create_new_entry = false; - params.should_replace_current_entry = true; - params.url = url; - params.origin = url::Origin::Create(url); - params.transition = ui::PAGE_TRANSITION_LINK; - params.redirects.push_back(url); - params.should_update_history = true; - params.gesture = NavigationGestureAuto; - params.method = "GET"; - params.page_state = PageState::CreateFromURL(url); - - // This should NOT generate a new entry, nor prune the list. - LoadCommittedDetailsObserver observer(contents()); - main_test_rfh()->SendNavigateWithParams(¶ms, true); - EXPECT_EQ(1U, navigation_entry_committed_counter_); - navigation_entry_committed_counter_ = 0; - EXPECT_TRUE(observer.is_same_document()); - EXPECT_TRUE(observer.did_replace_entry()); - EXPECT_EQ(2, controller.GetEntryCount()); - } - - // Perform a client redirect to a new page. - { - const GURL url("http://foo3/"); - FrameHostMsg_DidCommitProvisionalLoad_Params params; - params.nav_entry_id = 0; - params.did_create_new_entry = true; - params.url = url; - params.transition = ui::PAGE_TRANSITION_CLIENT_REDIRECT; - params.redirects.push_back(GURL("http://foo2/#a")); - params.redirects.push_back(url); - params.should_update_history = true; - params.gesture = NavigationGestureAuto; - params.method = "GET"; - params.page_state = PageState::CreateFromURL(url); - - // This SHOULD generate a new entry. - LoadCommittedDetailsObserver observer(contents()); - main_test_rfh()->SendRendererInitiatedNavigationRequest(url, false); - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigateWithParams(¶ms, false); - EXPECT_EQ(1U, navigation_entry_committed_counter_); - navigation_entry_committed_counter_ = 0; - EXPECT_FALSE(observer.is_same_document()); - EXPECT_EQ(3, controller.GetEntryCount()); - } - - // Verify that BACK brings us back to http://foo2/. - { - const GURL url("http://foo2/"); - controller.GoBack(); - int entry_id = controller.GetPendingEntry()->GetUniqueID(); - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigate(entry_id, false, url); - EXPECT_EQ(1U, navigation_entry_committed_counter_); - navigation_entry_committed_counter_ = 0; - EXPECT_EQ(url, controller.GetVisibleEntry()->GetURL()); - } -} - TEST_F(NavigationControllerTest, PushStateWithoutPreviousEntry) { ASSERT_FALSE(controller_impl().GetLastCommittedEntry()); FrameHostMsg_DidCommitProvisionalLoad_Params params;
diff --git a/content/browser/frame_host/navigation_request.h b/content/browser/frame_host/navigation_request.h index 5dd4d9b..379b1849 100644 --- a/content/browser/frame_host/navigation_request.h +++ b/content/browser/frame_host/navigation_request.h
@@ -12,6 +12,7 @@ #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" +#include "base/strings/string_util.h" #include "content/browser/frame_host/navigation_entry_impl.h" #include "content/browser/initiator_csp_context.h" #include "content/browser/loader/navigation_url_loader_delegate.h" @@ -181,6 +182,10 @@ int net_error() { return net_error_; } + const std::string& GetMimeType() { + return response_ ? response_->head.mime_type : base::EmptyString(); + } + void SetWaitingForRendererResponse(); // Creates a NavigationHandle. This should be called after any previous @@ -231,6 +236,10 @@ common_params_.transition = transition; } + void set_has_user_gesture(bool has_user_gesture) { + common_params_.has_user_gesture = has_user_gesture; + } + private: NavigationRequest(FrameTreeNode* frame_tree_node, const CommonNavigationParams& common_params,
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index 2ae899c..ba9cdb72 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -91,7 +91,6 @@ #include "content/browser/renderer_host/render_widget_host_view_child_frame.h" #include "content/browser/renderer_interface_binders.h" #include "content/browser/scoped_active_url.h" -#include "content/browser/serial/serial_service.h" #include "content/browser/speech/speech_recognition_dispatcher_host.h" #include "content/browser/storage_partition_impl.h" #include "content/browser/wake_lock/wake_lock_service_impl.h" @@ -197,6 +196,8 @@ #include "content/browser/android/java_interfaces_impl.h" #include "content/browser/frame_host/render_frame_host_android.h" #include "content/public/browser/android/java_interfaces.h" +#else +#include "content/browser/serial/serial_service.h" #endif #if defined(OS_MACOSX) @@ -4013,8 +4014,10 @@ base::Bind(&SensorProviderProxyImpl::Bind, base::Unretained(sensor_provider_proxy_.get()))); +#if !defined(OS_ANDROID) registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::BindSerialServiceRequest, base::Unretained(this))); +#endif // !defined(OS_ANDROID) // Only save decode stats when BrowserContext provides a VideoPerfHistory. // Off-the-record contexts will internally use an ephemeral history DB. @@ -4103,13 +4106,6 @@ return true; } - // file: URLs can be allowed to access any other origin, based on settings. - if (origin.scheme() == url::kFileScheme) { - WebPreferences prefs = render_view_host_->GetWebkitPreferences(); - if (prefs.allow_universal_access_from_file_urls) - return true; - } - // It is safe to commit into a unique origin, regardless of the URL, as it is // restricted from accessing other origins. if (origin.opaque()) @@ -4358,6 +4354,8 @@ } void RenderFrameHostImpl::StartPendingDeletionOnSubtree() { + ResetNavigationsForPendingDeletion(); + DCHECK_NE(UnloadState::NotRun, unload_state_); for (std::unique_ptr<FrameTreeNode>& child_frame : children_) { for (FrameTreeNode* node : @@ -4411,6 +4409,14 @@ child_rfh->PendingDeletionCheckCompletedOnSubtree(); } +void RenderFrameHostImpl::ResetNavigationsForPendingDeletion() { + for (auto& child : children_) + child->current_frame_host()->ResetNavigationsForPendingDeletion(); + ResetNavigationRequests(); + frame_tree_node_->ResetNavigationRequest(false, false); + frame_tree_node_->render_manager()->CleanUpNavigation(); +} + void RenderFrameHostImpl::UpdateOpener() { TRACE_EVENT1("navigation", "RenderFrameHostImpl::UpdateOpener", "frame_tree_node", frame_tree_node_->frame_tree_node_id()); @@ -4799,7 +4805,7 @@ } mojom::NavigationClient* navigation_client = nullptr; - if (IsPerNavigationMojoInterfaceEnabled() && navigation_request) + if (IsPerNavigationMojoInterfaceEnabled()) navigation_client = navigation_request->GetCommitNavigationClient(); SendCommitFailedNavigation( @@ -5024,8 +5030,35 @@ // out-of-process iframes implementation is ready, we should check for // cross-site URLs that are not allowed to commit in this process. + // MHTML subframes can supply URL at commit time that do not match the process + // lock. For example, it can be either "cid:..." or arbitrary URL at which + // the frame was at the time of generating the MHTML + // (e.g. "http://localhost"). In such cases, don't verify the URL, however + // enforce that the commit is allowed only in the process of the main frame. + if (!frame_tree_node()->IsMainFrame()) { + bool is_in_mhtml = frame_tree_node_->frame_tree() + ->root() + ->current_frame_host() + ->is_mhtml_document(); + if (is_in_mhtml) { + return IsSameSiteInstance( + frame_tree_node()->parent()->current_frame_host()); + } + } + // Give the client a chance to disallow URLs from committing. - return GetContentClient()->browser()->CanCommitURL(GetProcess(), url); + if (!GetContentClient()->browser()->CanCommitURL(GetProcess(), url)) + return false; + + // TODO(nasko): This check should be updated to apply to all URLs, not just + // standard ones. + auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); + if (url.IsStandard() && + !policy->CanAccessDataForOrigin(GetProcess()->GetID(), url)) { + return false; + } + + return true; } void RenderFrameHostImpl::BlockRequestsForFrame() { @@ -5639,6 +5672,7 @@ } #endif +#if !defined(OS_ANDROID) void RenderFrameHostImpl::BindSerialServiceRequest( blink::mojom::SerialServiceRequest request) { if (!serial_service_) @@ -5647,15 +5681,6 @@ serial_service_->Bind(std::move(request)); } -void RenderFrameHostImpl::BindPresentationServiceRequest( - blink::mojom::PresentationServiceRequest request) { - if (!presentation_service_) - presentation_service_ = PresentationServiceImpl::Create(this); - - presentation_service_->Bind(std::move(request)); -} - -#if !defined(OS_ANDROID) void RenderFrameHostImpl::BindAuthenticatorRequest( blink::mojom::AuthenticatorRequest request) { if (!authenticator_impl_) @@ -5665,6 +5690,14 @@ } #endif +void RenderFrameHostImpl::BindPresentationServiceRequest( + blink::mojom::PresentationServiceRequest request) { + if (!presentation_service_) + presentation_service_ = PresentationServiceImpl::Create(this); + + presentation_service_->Bind(std::move(request)); +} + blink::mojom::FileChooserPtr RenderFrameHostImpl::BindFileChooserForTesting() { blink::mojom::FileChooserPtr chooser; FileChooserImpl::Create(this, mojo::MakeRequest(&chooser)); @@ -5981,10 +6014,19 @@ } } + // file: URLs can be allowed to access any other origin, based on settings. + bool bypass_checks_for_file_scheme = false; + if (validated_params->origin.scheme() == url::kFileScheme) { + WebPreferences prefs = render_view_host_->GetWebkitPreferences(); + if (prefs.allow_universal_access_from_file_urls) + bypass_checks_for_file_scheme = true; + } + // Attempts to commit certain off-limits URL should be caught more strictly // than our FilterURL checks. If a renderer violates this policy, it // should be killed. - if (!is_permitted_error_page && !CanCommitURL(validated_params->url)) { + if (!is_permitted_error_page && !bypass_checks_for_file_scheme && + !CanCommitURL(validated_params->url)) { VLOG(1) << "Blocked URL " << validated_params->url.spec(); LogRendererKillCrashKeys(GetSiteInstance()->GetSiteURL()); @@ -5996,7 +6038,8 @@ // Verify that the origin passed from the renderer process is valid and can // be allowed to commit in this RenderFrameHost. - if (!CanCommitOrigin(validated_params->origin, validated_params->url)) { + if (!bypass_checks_for_file_scheme && + !CanCommitOrigin(validated_params->origin, validated_params->url)) { DEBUG_ALIAS_FOR_ORIGIN(origin_debug_alias, validated_params->origin); LogRendererKillCrashKeys(GetSiteInstance()->GetSiteURL()); @@ -6164,8 +6207,19 @@ // request. committed_request->set_transition(validated_params->transition); + committed_request->set_has_user_gesture(validated_params->gesture == + NavigationGestureUser); + UpdateSiteURL(validated_params->url, validated_params->url_is_unreachable); + // Set the state whether this navigation is to an MHTML document, since there + // are certain security checks that we cannot apply to subframes in MHTML + // documents. Do not trust renderer data when determining that, rather use + // the |committed_request|, which was generated and stays browser side. + is_mhtml_document_ = + (committed_request->GetMimeType() == "multipart/related" || + committed_request->GetMimeType() == "message/rfc822"); + accessibility_reset_count_ = 0; frame_tree_node()->navigator()->DidNavigate(this, *validated_params, std::move(committed_request), @@ -6396,14 +6450,16 @@ approx_renderer_start_time, base::TimeTicks::Now()); } - // If we're waiting for an unload ack from this frame and we receive a commit - // message, then the frame was navigating before it received the unload - // request. It will either respond to the unload request soon or our timer - // will expire. Either way, we should ignore this message, because we have - // already committed to destroying this RenderFrameHost. Note that we - // intentionally do not ignore commits that happen while the current tab is - // being closed - see https://crbug.com/805705. - if (is_waiting_for_swapout_ack_) + // When a frame enters pending deletion, it waits for itself and its children + // to properly unload. Receiving DidCommitProvisionalLoad() here while the + // frame is not active means it comes from a navigation that reached the + // ReadyToCommit stage just before the frame entered pending deletion. + // + // We should ignore this message, because we have already committed to + // destroying this RenderFrameHost. Note that we intentionally do not ignore + // commits that happen while the current tab is being closed - see + // https://crbug.com/805705. + if (!is_active()) return; // Retroactive sanity check: @@ -6515,9 +6571,8 @@ NavigationRequest* navigation_request) { DCHECK(navigation_request); return base::BindOnce( - &RenderFrameHostImpl::OnCrossDocumentCommitProcessed, - base::Unretained(this), - navigation_request->navigation_handle()->GetNavigationId()); + &RenderFrameHostImpl::DidCommitPerNavigationMojoInterfaceNavigation, + base::Unretained(this), navigation_request); } } // namespace content
diff --git a/content/browser/frame_host/render_frame_host_impl.h b/content/browser/frame_host/render_frame_host_impl.h index 3dcbda6..9d1335e 100644 --- a/content/browser/frame_host/render_frame_host_impl.h +++ b/content/browser/frame_host/render_frame_host_impl.h
@@ -807,6 +807,8 @@ return active_sandbox_flags_; } + bool is_mhtml_document() { return is_mhtml_document_; } + // Notifies the render frame about a user activation from the browser side. void NotifyUserActivation(); @@ -995,6 +997,10 @@ PendingDeletionCheckCompletedOnSubtree); FRIEND_TEST_ALL_PREFIXES(SitePerProcessBrowserTest, DetachedIframeUnloadHandler); + FRIEND_TEST_ALL_PREFIXES(SitePerProcessBrowserTest, + NavigationCommitInIframePendingDeletionAB); + FRIEND_TEST_ALL_PREFIXES(SitePerProcessBrowserTest, + NavigationCommitInIframePendingDeletionABC); class DroppedInterfaceRequestLogger; @@ -1290,15 +1296,14 @@ void BindNFCRequest(device::mojom::NFCRequest request); #endif +#if !defined(OS_ANDROID) void BindSerialServiceRequest(blink::mojom::SerialServiceRequest request); + void BindAuthenticatorRequest(blink::mojom::AuthenticatorRequest request); +#endif void BindPresentationServiceRequest( blink::mojom::PresentationServiceRequest request); -#if !defined(OS_ANDROID) - void BindAuthenticatorRequest(blink::mojom::AuthenticatorRequest request); -#endif - // service_manager::mojom::InterfaceProvider: void GetInterface(const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe) override; @@ -1486,6 +1491,11 @@ // this frame's subtree. void PendingDeletionCheckCompletedOnSubtree(); + // In this frame and its children, removes every: + // - NavigationRequest. + // - Speculative RenderFrameHost. + void ResetNavigationsForPendingDeletion(); + // For now, RenderFrameHosts indirectly keep RenderViewHosts alive via a // refcount that calls Shutdown when it reaches zero. This allows each // RenderFrameHostManager to just care about RenderFrameHosts, while ensuring @@ -1806,8 +1816,10 @@ // media::mojom::InterfaceFactory calls to the remote "media" service. std::unique_ptr<MediaInterfaceProxy> media_interface_proxy_; +#if !defined(OS_ANDROID) // Hosts blink::mojom::SerialService for the RenderFrame. std::unique_ptr<SerialService> serial_service_; +#endif // Hosts blink::mojom::PresentationService for the RenderFrame. std::unique_ptr<PresentationServiceImpl> presentation_service_; @@ -1965,6 +1977,12 @@ blink::mojom::FrameVisibility visibility_ = blink::mojom::FrameVisibility::kRenderedInViewport; + // Whether the currently committed document is MHTML or not. It is set at + // commit time based on the MIME type of the NavigationRequest that resulted + // in the navigation commit. Setting the value should be based only on + // browser side state as this value is used in security checks. + bool is_mhtml_document_ = false; + // NOTE: This must be the last member. base::WeakPtrFactory<RenderFrameHostImpl> weak_ptr_factory_;
diff --git a/content/browser/frame_host/render_frame_host_manager.cc b/content/browser/frame_host/render_frame_host_manager.cc index 7a3ec25..ee7ee849 100644 --- a/content/browser/frame_host/render_frame_host_manager.cc +++ b/content/browser/frame_host/render_frame_host_manager.cc
@@ -512,6 +512,16 @@ << "Don't call this method for JavaScript URLs as those create a " "temporary NavigationRequest and we don't want to reset an ongoing " "navigation's speculative RFH."; + // A frame that's pending deletion should never be navigated. If this happens, + // log a DumpWithoutCrashing to understand the root cause. + // See https://crbug.com/926820 and https://crbug.com/927705. + if (!current_frame_host()->is_active()) { + NOTREACHED() << "Navigation in an inactive frame"; + NavigationHandle* handle = request.navigation_handle(); + DEBUG_ALIAS_FOR_GURL(url_from, handle->GetPreviousURL()) + DEBUG_ALIAS_FOR_GURL(url_to, handle->GetURL()) + base::debug::DumpWithoutCrashing(); + } // The appropriate RenderFrameHost to commit the navigation. RenderFrameHostImpl* navigation_rfh = nullptr;
diff --git a/content/browser/gpu/browser_gpu_channel_host_factory.cc b/content/browser/gpu/browser_gpu_channel_host_factory.cc index 132fa481..ecec626 100644 --- a/content/browser/gpu/browser_gpu_channel_host_factory.cc +++ b/content/browser/gpu/browser_gpu_channel_host_factory.cc
@@ -37,7 +37,6 @@ #include "gpu/ipc/common/gpu_client_ids.h" #include "gpu/ipc/in_process_command_buffer.h" #include "services/resource_coordinator/public/mojom/memory_instrumentation/constants.mojom.h" -#include "services/service_manager/runner/common/client_util.h" #include "ui/base/ui_base_features.h" #if defined(OS_MACOSX)
diff --git a/content/browser/gpu/gpu_process_host.cc b/content/browser/gpu/gpu_process_host.cc index caf9e5fe..9ebb9d1 100644 --- a/content/browser/gpu/gpu_process_host.cc +++ b/content/browser/gpu/gpu_process_host.cc
@@ -73,7 +73,6 @@ #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/interface_provider.h" -#include "services/service_manager/runner/common/client_util.h" #include "services/service_manager/sandbox/sandbox_type.h" #include "services/service_manager/sandbox/switches.h" #include "services/ws/public/mojom/constants.mojom.h"
diff --git a/content/browser/isolated_origin_browsertest.cc b/content/browser/isolated_origin_browsertest.cc index a438030d..af5a765 100644 --- a/content/browser/isolated_origin_browsertest.cc +++ b/content/browser/isolated_origin_browsertest.cc
@@ -1067,9 +1067,10 @@ // renderer process sending incorrect data to the browser process, so // security checks can be tested. void OpenLocalStorage(const url::Origin& origin, - blink::mojom::StorageAreaRequest request) override { - GetForwardingInterface()->OpenLocalStorage(origin_to_inject_, - std::move(request)); + blink::mojom::StorageAreaRequest request, + OpenLocalStorageCallback done) override { + GetForwardingInterface()->OpenLocalStorage( + origin_to_inject_, std::move(request), std::move(done)); } private:
diff --git a/content/browser/loader/cross_site_document_blocking_browsertest.cc b/content/browser/loader/cross_site_document_blocking_browsertest.cc index 04774e1..63a326d4 100644 --- a/content/browser/loader/cross_site_document_blocking_browsertest.cc +++ b/content/browser/loader/cross_site_document_blocking_browsertest.cc
@@ -736,7 +736,13 @@ EXPECT_EQ(0u, interceptor.response_head().content_length); } -IN_PROC_BROWSER_TEST_P(CrossSiteDocumentBlockingTest, AppCache) { +// Tests what happens in a page covered by AppCache (where the AppCache manifest +// doesn't cover any cross-origin resources). In particular, requests from the +// web page that get proxied by the AppCache to the network (falling back to the +// network because they are not covered by the AppCache manifest) should still +// be subject to CORB. +IN_PROC_BROWSER_TEST_P(CrossSiteDocumentBlockingTest, + AppCache_NetworkFallback) { embedded_test_server()->StartAcceptingConnections(); // Prepare to intercept the network request at the IPC layer. @@ -801,6 +807,38 @@ } } +// Tests what happens in a page covered by AppCache, where the AppCache manifest +// covers cross-origin resources. In this case the cross-origin resource +// requests will be triggered by AppCache-manifest-processing code (rather than +// triggered directly by the web page / renderer process as in +// AppCache_NetworkFallback). Such manifest-triggered requests need to be +// subject to CORB. +// +// This is a regression test for https://crbug.com/927471. +IN_PROC_BROWSER_TEST_P(CrossSiteDocumentBlockingTest, AppCache_InManifest) { + embedded_test_server()->StartAcceptingConnections(); + + // Load the AppCached page and wait until the AppCache is populated (this will + // include the cross-origin + // http://cross-origin.com/site_isolation/nosniff.json from + // site_isolation/appcached_cross_origin_resource.manifest. + base::HistogramTester histograms; + GURL main_url = embedded_test_server()->GetURL( + "/site_isolation/appcached_cross_origin_resource.html"); + EXPECT_TRUE(NavigateToURL(shell(), main_url)); + base::string16 expected_title = base::ASCIIToUTF16("AppCache updated"); + content::TitleWatcher title_watcher(shell()->web_contents(), expected_title); + EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); + + // Verify that the request for nosniff.json was covered by CORB. + FetchHistogramsFromChildProcesses(); + EXPECT_EQ(1, histograms.GetBucketCount( + "SiteIsolation.XSD.Browser.Action", + static_cast<int>(Action::kBlockedWithoutSniffing))); +} + +// Tests that renderer will be terminated if it asks AppCache to initiate a +// request with an invalid |request_initiator|. IN_PROC_BROWSER_TEST_P(CrossSiteDocumentBlockingTest, AppCache_InitiatorEnforcement) { embedded_test_server()->StartAcceptingConnections();
diff --git a/content/browser/loader/resource_dispatcher_host_impl.cc b/content/browser/loader/resource_dispatcher_host_impl.cc index a206be7..a704b83 100644 --- a/content/browser/loader/resource_dispatcher_host_impl.cc +++ b/content/browser/loader/resource_dispatcher_host_impl.cc
@@ -1161,13 +1161,13 @@ int child_id, int render_view_route_id, int render_frame_route_id, + int frame_tree_node_id, PreviewsState previews_state, bool download, ResourceContext* context) { return new ResourceRequestInfoImpl( ResourceRequesterInfo::CreateForDownloadOrPageSave(child_id), - render_view_route_id, - -1, // frame_tree_node_id + render_view_route_id, frame_tree_node_id, ChildProcessHost::kInvalidUniqueID, // plugin_child_id MakeRequestID(), render_frame_route_id, false, // is_main_frame @@ -1744,6 +1744,7 @@ int render_process_host_id, int render_view_routing_id, int render_frame_routing_id, + int frame_tree_node_id, PreviewsState previews_state, ResourceContext* context) { DCHECK(io_thread_task_runner_->BelongsToCurrentThread()); @@ -1753,7 +1754,7 @@ ResourceRequestInfoImpl* info = CreateRequestInfo( render_process_host_id, render_view_routing_id, render_frame_routing_id, - previews_state, is_download, context); + frame_tree_node_id, previews_state, is_download, context); // Request takes ownership. info->AssociateWithRequest(request); }
diff --git a/content/browser/loader/resource_dispatcher_host_impl.h b/content/browser/loader/resource_dispatcher_host_impl.h index 79f72f1..7b9ae66 100644 --- a/content/browser/loader/resource_dispatcher_host_impl.h +++ b/content/browser/loader/resource_dispatcher_host_impl.h
@@ -273,6 +273,7 @@ int render_process_host_id, int render_view_routing_id, int render_frame_routing_id, + int frame_tree_node_id, PreviewsState previews_state, ResourceContext* context); @@ -601,13 +602,13 @@ // Creates ResourceRequestInfoImpl for a download or page save. // |download| should be true if the request is a file download. - ResourceRequestInfoImpl* CreateRequestInfo( - int child_id, - int render_view_route_id, - int render_frame_route_id, - PreviewsState previews_state, - bool download, - ResourceContext* context); + ResourceRequestInfoImpl* CreateRequestInfo(int child_id, + int render_view_route_id, + int render_frame_route_id, + int frame_tree_node_id, + PreviewsState previews_state, + bool download, + ResourceContext* context); // Relationship of resource being authenticated with the top level page. enum HttpAuthRelationType {
diff --git a/content/browser/media/android/media_player_renderer.cc b/content/browser/media/android/media_player_renderer.cc index 707f1c1..e876275 100644 --- a/content/browser/media/android/media_player_renderer.cc +++ b/content/browser/media/android/media_player_renderer.cc
@@ -24,10 +24,6 @@ #include "media/base/android/media_service_throttler.h" #include "media/base/timestamp_constants.h" -// TODO(tguilbert): Remove this ID once MediaPlayerManager has been deleted -// and MediaPlayerBridge updated. See comment in header file. -constexpr int kUnusedAndIrrelevantPlayerId = 0; - namespace content { namespace { @@ -117,13 +113,9 @@ const std::string user_agent = GetContentClient()->browser()->GetUserAgent(); media_player_.reset(new media::MediaPlayerBridge( - kUnusedAndIrrelevantPlayerId, url_params.media_url, - url_params.site_for_cookies, user_agent, + url_params.media_url, url_params.site_for_cookies, user_agent, false, // hide_url_log this, - base::Bind(&MediaPlayerRenderer::OnDecoderResourcesReleased, - weak_factory_.GetWeakPtr()), - GURL(), // frame_url true)); // allow_crendentials media_player_->Initialize(); @@ -169,7 +161,7 @@ return; if (playback_rate == 0) { - media_player_->Pause(true); + media_player_->Pause(); } else { // MediaPlayerBridge's Start() is idempotent. media_player_->Start(); @@ -240,19 +232,7 @@ return g_media_url_interceptor; } -void MediaPlayerRenderer::OnTimeUpdate(int player_id, - base::TimeDelta current_timestamp, - base::TimeTicks current_time_ticks) {} - -void MediaPlayerRenderer::OnMediaMetadataChanged(int player_id, - base::TimeDelta duration, - int width, - int height, - bool success) { - // Always try to propage the video size. - // This call will no-op if |video_size_| is already current. - OnVideoSizeChanged(kUnusedAndIrrelevantPlayerId, width, height); - +void MediaPlayerRenderer::OnMediaDurationChanged(base::TimeDelta duration) { // For HLS streams, the reported duration may be zero for infinite streams. // See http://crbug.com/501213. if (duration.is_zero()) @@ -264,23 +244,16 @@ } } -void MediaPlayerRenderer::OnPlaybackComplete(int player_id) { +void MediaPlayerRenderer::OnPlaybackComplete() { renderer_client_->OnEnded(); } -void MediaPlayerRenderer::OnMediaInterrupted(int player_id) {} - -void MediaPlayerRenderer::OnBufferingUpdate(int player_id, int percentage) {} - -void MediaPlayerRenderer::OnSeekComplete(int player_id, - const base::TimeDelta& current_time) {} - -void MediaPlayerRenderer::OnError(int player_id, int error) { +void MediaPlayerRenderer::OnError(int error) { // Some errors are forwarded to the MediaPlayerListener, but are of no // importance to us. Ignore these errors, which are reported as // MEDIA_ERROR_INVALID_CODE by MediaPlayerListener. if (error == - media::MediaPlayerAndroid::MediaErrorType::MEDIA_ERROR_INVALID_CODE) { + media::MediaPlayerBridge::MediaErrorType::MEDIA_ERROR_INVALID_CODE) { return; } @@ -289,9 +262,7 @@ renderer_client_->OnError(media::PIPELINE_ERROR_EXTERNAL_RENDERER_FAILED); } -void MediaPlayerRenderer::OnVideoSizeChanged(int player_id, - int width, - int height) { +void MediaPlayerRenderer::OnVideoSizeChanged(int width, int height) { // This method is called when we find a video size from metadata or when // |media_player|'s size actually changes. // We therefore may already have the latest video size. @@ -302,17 +273,6 @@ } } -media::MediaPlayerAndroid* MediaPlayerRenderer::GetPlayer(int player_id) { - NOTREACHED(); - return nullptr; -} - -bool MediaPlayerRenderer::RequestPlay(int player_id, - base::TimeDelta duration, - bool has_audio) { - return true; -} - void MediaPlayerRenderer::OnUpdateAudioMutingState(bool muted) { web_contents_muted_ = muted; UpdateVolume(); @@ -322,11 +282,6 @@ web_contents_observer_ = nullptr; } -void MediaPlayerRenderer::OnDecoderResourcesReleased(int player_id) { - // Since we are not using a pool of MediaPlayerAndroid instances, this - // function is not relevant. -} - // static void MediaPlayerRenderer::RegisterMediaUrlInterceptor( media::MediaUrlInterceptor* media_url_interceptor) {
diff --git a/content/browser/media/android/media_player_renderer.h b/content/browser/media/android/media_player_renderer.h index ed0bd58..c53b245 100644 --- a/content/browser/media/android/media_player_renderer.h +++ b/content/browser/media/android/media_player_renderer.h
@@ -12,7 +12,6 @@ #include "content/common/content_export.h" #include "content/public/browser/render_frame_host.h" #include "media/base/android/media_player_bridge.h" -#include "media/base/android/media_player_manager.h" #include "media/base/media_log.h" #include "media/base/media_resource.h" #include "media/base/renderer.h" @@ -35,11 +34,9 @@ // MediaPlayerBridge is tightly coupled with the manager abstraction. // |player_id| is ignored in all MediaPlayerManager calls, as there is only one // MediaPlayer per MediaPlayerRenderer. -// -// TODO(tguilbert): Remove the MediaPlayerManager implementation and update -// MediaPlayerBridge, once WMPA has been deleted. See http://crbug.com/580626 -class CONTENT_EXPORT MediaPlayerRenderer : public media::Renderer, - public media::MediaPlayerManager { +class CONTENT_EXPORT MediaPlayerRenderer + : public media::Renderer, + public media::MediaPlayerBridge::Client { public: // Permits embedders to handle custom urls. static void RegisterMediaUrlInterceptor( @@ -68,28 +65,13 @@ void SetVolume(float volume) override; base::TimeDelta GetMediaTime() override; - // media::MediaPlayerManager implementation + // media::MediaPlayerBridge::Client implementation media::MediaResourceGetter* GetMediaResourceGetter() override; media::MediaUrlInterceptor* GetMediaUrlInterceptor() override; - void OnTimeUpdate(int player_id, - base::TimeDelta current_timestamp, - base::TimeTicks current_time_ticks) override; - void OnMediaMetadataChanged(int player_id, - base::TimeDelta duration, - int width, - int height, - bool success) override; - void OnPlaybackComplete(int player_id) override; - void OnMediaInterrupted(int player_id) override; - void OnBufferingUpdate(int player_id, int percentage) override; - void OnSeekComplete(int player_id, - const base::TimeDelta& current_time) override; - void OnError(int player_id, int error) override; - void OnVideoSizeChanged(int player_id, int width, int height) override; - media::MediaPlayerAndroid* GetPlayer(int player_id) override; - bool RequestPlay(int player_id, - base::TimeDelta duration, - bool has_audio) override; + void OnMediaDurationChanged(base::TimeDelta duration) override; + void OnPlaybackComplete() override; + void OnError(int error) override; + void OnVideoSizeChanged(int width, int height) override; void OnUpdateAudioMutingState(bool muted); void OnWebContentsDestroyed(); @@ -108,9 +90,6 @@ void CreateMediaPlayer(const media::MediaUrlParams& params, const media::PipelineStatusCB& init_cb); - // Used when creating |media_player_|. - void OnDecoderResourcesReleased(int player_id); - // Cancels the pending request started by InitiateScopedSurfaceRequest(), if // it exists. No-ops otherwise. void CancelScopedSurfaceRequest();
diff --git a/content/browser/media/android/media_web_contents_observer_android.cc b/content/browser/media/android/media_web_contents_observer_android.cc index 4810676..1a2d7b8 100644 --- a/content/browser/media/android/media_web_contents_observer_android.cc +++ b/content/browser/media/android/media_web_contents_observer_android.cc
@@ -13,7 +13,6 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "ipc/ipc_message_macros.h" -#include "media/base/android/media_player_android.h" namespace content {
diff --git a/content/browser/media/media_internals.cc b/content/browser/media/media_internals.cc index e88f2a0..344aa3a 100644 --- a/content/browser/media/media_internals.cc +++ b/content/browser/media/media_internals.cc
@@ -481,6 +481,8 @@ uma_name += "VP9."; } else if (player_info.video_codec_name == "h264") { uma_name += "H264."; + } else if (player_info.video_codec_name == "av1") { + uma_name += "AV1."; } else { return uma_name + "Other"; }
diff --git a/content/common/plugin_list.cc b/content/browser/plugin_list.cc similarity index 92% rename from content/common/plugin_list.cc rename to content/browser/plugin_list.cc index cbfa042..a1e2bd9 100644 --- a/content/common/plugin_list.cc +++ b/content/browser/plugin_list.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 "content/common/plugin_list.h" +#include "content/browser/plugin_list.h" #include <stddef.h> @@ -112,8 +112,7 @@ base::AutoLock lock(lock_); for (std::vector<WebPluginInfo>::iterator it = internal_plugins_.begin(); - it != internal_plugins_.end(); - ++it) { + it != internal_plugins_.end(); ++it) { internal_plugins->push_back(*it); } } @@ -130,9 +129,7 @@ return false; } -PluginList::PluginList() - : loading_state_(LOADING_STATE_NEEDS_REFRESH) { -} +PluginList::PluginList() : loading_state_(LOADING_STATE_NEEDS_REFRESH) {} bool PluginList::PrepareForPluginLoading() { base::AutoLock lock(lock_); @@ -160,8 +157,7 @@ GetPluginPathsToLoad(&plugin_paths); for (std::vector<base::FilePath>::const_iterator it = plugin_paths.begin(); - it != plugin_paths.end(); - ++it) { + it != plugin_paths.end(); ++it) { WebPluginInfo plugin_info; LoadPluginIntoPluginList(*it, &new_plugins, &plugin_info); } @@ -169,10 +165,9 @@ SetPlugins(new_plugins); } -bool PluginList::LoadPluginIntoPluginList( - const base::FilePath& path, - std::vector<WebPluginInfo>* plugins, - WebPluginInfo* plugin_info) { +bool PluginList::LoadPluginIntoPluginList(const base::FilePath& path, + std::vector<WebPluginInfo>* plugins, + WebPluginInfo* plugin_info) { if (!ReadPluginInfo(path, plugin_info)) return false; @@ -181,7 +176,7 @@ // TODO: don't load global handlers for now. // WebKit hands to the Plugin before it tries // to handle mimeTypes on its own. - const std::string &mime_type = plugin_info->mime_types[i].mime_type; + const std::string& mime_type = plugin_info->mime_types[i].mime_type; if (mime_type == "*") return false; } @@ -297,15 +292,12 @@ void PluginList::RemoveExtraPluginPathLocked( const base::FilePath& plugin_path) { lock_.AssertAcquired(); - std::vector<base::FilePath>::iterator it = - std::find(extra_plugin_paths_.begin(), extra_plugin_paths_.end(), - plugin_path); + std::vector<base::FilePath>::iterator it = std::find( + extra_plugin_paths_.begin(), extra_plugin_paths_.end(), plugin_path); if (it != extra_plugin_paths_.end()) extra_plugin_paths_.erase(it); } -PluginList::~PluginList() { -} - +PluginList::~PluginList() {} } // namespace content
diff --git a/content/common/plugin_list.h b/content/browser/plugin_list.h similarity index 96% rename from content/common/plugin_list.h rename to content/browser/plugin_list.h index a76f0a6..9f4732f 100644 --- a/content/common/plugin_list.h +++ b/content/browser/plugin_list.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 CONTENT_COMMON_PLUGIN_LIST_H_ -#define CONTENT_COMMON_PLUGIN_LIST_H_ +#ifndef CONTENT_BROWSER_PLUGIN_LIST_H_ +#define CONTENT_BROWSER_PLUGIN_LIST_H_ #include <set> #include <string> @@ -51,8 +51,7 @@ // be loaded using PluginList::LoadPlugin(). // If |add_at_beginning| is true the plugin will be added earlier in // the list so that it can override the MIME types of older registrations. - void RegisterInternalPlugin(const WebPluginInfo& info, - bool add_at_beginning); + void RegisterInternalPlugin(const WebPluginInfo& info, bool add_at_beginning); // Removes a specified internal plugin from the list. The search will match // on the path from the version info previously registered. @@ -167,4 +166,4 @@ } // namespace content -#endif // CONTENT_COMMON_PLUGIN_LIST_H_ +#endif // CONTENT_BROWSER_PLUGIN_LIST_H_
diff --git a/content/common/plugin_list_unittest.cc b/content/browser/plugin_list_unittest.cc similarity index 76% rename from content/common/plugin_list_unittest.cc rename to content/browser/plugin_list_unittest.cc index d28c0eb5..4de87cc 100644 --- a/content/common/plugin_list_unittest.cc +++ b/content/browser/plugin_list_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/common/plugin_list.h" +#include "content/browser/plugin_list.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" @@ -20,9 +20,7 @@ const char* kFooFileType = "foo"; bool Equals(const WebPluginInfo& a, const WebPluginInfo& b) { - return (a.name == b.name && - a.path == b.path && - a.version == b.version && + return (a.name == b.name && a.path == b.path && a.version == b.version && a.desc == b.desc); } @@ -48,8 +46,7 @@ bar_plugin_(base::ASCIIToUTF16("Bar Plugin"), base::FilePath(kBarPath), base::ASCIIToUTF16("2.3.4"), - base::ASCIIToUTF16("bar")) { - } + base::ASCIIToUTF16("bar")) {} void SetUp() override { plugin_list_.RegisterInternalPlugin(bar_plugin_, false); @@ -94,24 +91,20 @@ // The file type of the URL is supported by foo_plugin_. However, // GetPluginInfoArray should not match foo_plugin_ because the MIME type is // application/octet-stream. - plugin_list_.GetPluginInfoArray(target_url, - "application/octet-stream", - false, // allow_wildcard - NULL, // use_stale - &plugins, - &actual_mime_types); + plugin_list_.GetPluginInfoArray(target_url, "application/octet-stream", + false, // allow_wildcard + NULL, // use_stale + &plugins, &actual_mime_types); EXPECT_EQ(0u, plugins.size()); EXPECT_EQ(0u, actual_mime_types.size()); // foo_plugin_ matches due to the MIME type. plugins.clear(); actual_mime_types.clear(); - plugin_list_.GetPluginInfoArray(target_url, - kFooMimeType, - false, // allow_wildcard - NULL, // use_stale - &plugins, - &actual_mime_types); + plugin_list_.GetPluginInfoArray(target_url, kFooMimeType, + false, // allow_wildcard + NULL, // use_stale + &plugins, &actual_mime_types); EXPECT_EQ(1u, plugins.size()); EXPECT_TRUE(Contains(plugins, foo_plugin_)); ASSERT_EQ(1u, actual_mime_types.size()); @@ -120,12 +113,10 @@ // foo_plugin_ matches due to the file type and empty MIME type. plugins.clear(); actual_mime_types.clear(); - plugin_list_.GetPluginInfoArray(target_url, - "", - false, // allow_wildcard - NULL, // use_stale - &plugins, - &actual_mime_types); + plugin_list_.GetPluginInfoArray(target_url, "", + false, // allow_wildcard + NULL, // use_stale + &plugins, &actual_mime_types); EXPECT_EQ(1u, plugins.size()); EXPECT_TRUE(Contains(plugins, foo_plugin_)); ASSERT_EQ(1u, actual_mime_types.size());
diff --git a/content/browser/plugin_service_impl.cc b/content/browser/plugin_service_impl.cc index 7834d3d1..a029fbb 100644 --- a/content/browser/plugin_service_impl.cc +++ b/content/browser/plugin_service_impl.cc
@@ -23,13 +23,13 @@ #include "base/task_runner_util.h" #include "base/threading/thread.h" #include "build/build_config.h" +#include "content/browser/plugin_list.h" #include "content/browser/ppapi_plugin_process_host.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/content_switches_internal.h" #include "content/common/pepper_plugin_list.h" -#include "content/common/plugin_list.h" #include "content/common/view_messages.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h"
diff --git a/content/browser/renderer_host/frame_connector_delegate.cc b/content/browser/renderer_host/frame_connector_delegate.cc index 8fb64e3..4156111 100644 --- a/content/browser/renderer_host/frame_connector_delegate.cc +++ b/content/browser/renderer_host/frame_connector_delegate.cc
@@ -76,6 +76,11 @@ return false; } +bool FrameConnectorDelegate::BubbleScrollEvent( + const blink::WebGestureEvent& event) { + return false; +} + bool FrameConnectorDelegate::HasFocus() { return false; }
diff --git a/content/browser/renderer_host/frame_connector_delegate.h b/content/browser/renderer_host/frame_connector_delegate.h index b82851f..34065ed5 100644 --- a/content/browser/renderer_host/frame_connector_delegate.h +++ b/content/browser/renderer_host/frame_connector_delegate.h
@@ -5,6 +5,7 @@ #ifndef CONTENT_BROWSER_RENDERER_HOST_FRAME_CONNECTOR_DELEGATE_H_ #define CONTENT_BROWSER_RENDERER_HOST_FRAME_CONNECTOR_DELEGATE_H_ +#include "base/compiler_specific.h" #include "base/time/time.h" #include "cc/input/touch_action.h" #include "components/viz/common/surfaces/local_surface_id_allocation.h" @@ -152,9 +153,13 @@ const blink::WebGestureEvent& event, InputEventAckState ack_result) {} - // Gesture events with unused scroll deltas must be bubbled to ancestors - // who may consume the delta. - virtual void BubbleScrollEvent(const blink::WebGestureEvent& event) {} + // A gesture scroll sequence that is not consumed by a child must be bubbled + // to ancestors who may consume it. + // Returns false if the scroll event could not be bubbled. The caller must + // not attempt to bubble the rest of the scroll sequence in this case. + // Otherwise, returns true. + virtual bool BubbleScrollEvent(const blink::WebGestureEvent& event) + WARN_UNUSED_RESULT; // Determines whether the root RenderWidgetHostView (and thus the current // page) has focus.
diff --git a/content/browser/renderer_host/input/autoscroll_browsertest.cc b/content/browser/renderer_host/input/autoscroll_browsertest.cc index ab4eaf03..17199c11 100644 --- a/content/browser/renderer_host/input/autoscroll_browsertest.cc +++ b/content/browser/renderer_host/input/autoscroll_browsertest.cc
@@ -165,8 +165,7 @@ // We don't plan on supporting middle click autoscroll on Android. // See https://crbug.com/686223 #if !defined(OS_ANDROID) -// TODO(sahel): This test is flaky https://crbug.com/838769 -IN_PROC_BROWSER_TEST_F(AutoscrollBrowserTest, DISABLED_AutoscrollFling) { +IN_PROC_BROWSER_TEST_F(AutoscrollBrowserTest, AutoscrollFling) { LoadURL(kAutoscrollDataURL); // Start autoscroll with middle click.
diff --git a/content/browser/renderer_host/input/render_widget_host_latency_tracker_unittest.cc b/content/browser/renderer_host/input/render_widget_host_latency_tracker_unittest.cc index 5da41d3..33662f3c 100644 --- a/content/browser/renderer_host/input/render_widget_host_latency_tracker_unittest.cc +++ b/content/browser/renderer_host/input/render_widget_host_latency_tracker_unittest.cc
@@ -1237,13 +1237,15 @@ } // Send 101 ScrollUpdate events to verify that there is 1 AverageLag record // per 1 second. - for (int i = 0; i <= 100; i++) { + const int kUpdates = 101; + for (int i = 0; i < kUpdates; i++) { // ScrollUpdate SyntheticWebTouchEvent touch; touch.PressPoint(0, 0); ui::LatencyInfo touch_latency(ui::SourceEventType::TOUCH); - touch_latency.set_scroll_update_delta(10); + const int sign = (i < kUpdates / 2) ? 1 : -1; + touch_latency.set_scroll_update_delta(sign * 10); event_time += base::TimeDelta::FromMilliseconds(10); touch_latency.AddLatencyNumberWithTimestamp( ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT, event_time,
diff --git a/content/browser/renderer_host/media/media_stream_manager.cc b/content/browser/renderer_host/media/media_stream_manager.cc index 125dc6e9..6da30c1 100644 --- a/content/browser/renderer_host/media/media_stream_manager.cc +++ b/content/browser/renderer_host/media/media_stream_manager.cc
@@ -197,20 +197,23 @@ MediaStreamType AdjustAudioStreamTypeBasedOnCommandLineSwitches( MediaStreamType stream_type) { - if (stream_type != blink::MEDIA_GUM_DESKTOP_AUDIO_CAPTURE) + if ((stream_type != blink::MEDIA_GUM_DESKTOP_AUDIO_CAPTURE) && + (stream_type != blink::MEDIA_DISPLAY_AUDIO_CAPTURE)) return stream_type; const bool audio_support_flag_for_desktop_share = !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAudioSupportForDesktopShare); - return audio_support_flag_for_desktop_share - ? blink::MEDIA_GUM_DESKTOP_AUDIO_CAPTURE - : blink::MEDIA_NO_SERVICE; + return audio_support_flag_for_desktop_share ? stream_type + : blink::MEDIA_NO_SERVICE; } -// Returns MediaStreamDevice built with DesktopMediaID with fake -// initializers if |kUseFakeDeviceForMediaStream| is set. Returns a -// MediaStreamDevice with default DesktopMediaID otherwise. -MediaStreamDevice MediaStreamDeviceFromFakeDeviceConfig() { +// Returns MediaStreamDevices for getDisplayMedia() calls. +// Returns a video device built with DesktopMediaID with fake initializers if +// |kUseFakeDeviceForMediaStream| is set. Returns a video device with +// default DesktopMediaID otherwise. +// Returns an audio device with default device parameters. +MediaStreamDevices DisplayMediaDevicesFromFakeDeviceConfig(bool request_audio) { + MediaStreamDevices devices; DesktopMediaID::Type desktop_media_type = DesktopMediaID::TYPE_SCREEN; DesktopMediaID::Id desktop_media_id_id = DesktopMediaID::kNullId; media::mojom::DisplayCaptureSurfaceType display_surface = @@ -250,7 +253,14 @@ media_id.ToString(), media_id.ToString()); device.display_media_info = media::mojom::DisplayMediaInformation::New( display_surface, true, media::mojom::CursorCaptureType::NEVER); - return device; + devices.push_back(device); + if (!request_audio) + return devices; + + devices.emplace_back(blink::MEDIA_DISPLAY_AUDIO_CAPTURE, + media::AudioDeviceDescription::kDefaultDeviceId, + "Fake audio"); + return devices; } } // namespace @@ -1141,21 +1151,16 @@ // If using the fake UI, it will just auto-select from the available devices. // The fake UI doesn't work for desktop sharing requests since we can't see // its devices from here; always use the real UI for such requests. The - // processing below for MEDIA_GUM_DESKTOP_VIDEO_CAPTURE is for unittests only. + // processing below for MEDIA_GUM_DESKTOP_VIDEO_CAPTURE is for + // media_stream_dispatcher_host_unittest only. if (fake_ui_factory_ && (request->video_type() != blink::MEDIA_GUM_DESKTOP_VIDEO_CAPTURE || !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kUseFakeUIForMediaStream))) { MediaStreamDevices devices; if (request->video_type() == blink::MEDIA_DISPLAY_VIDEO_CAPTURE) { - devices.push_back(MediaStreamDeviceFromFakeDeviceConfig()); - if (request->audio_type() == blink::MEDIA_DISPLAY_AUDIO_CAPTURE) { - DesktopMediaID media_id(DesktopMediaID::TYPE_SCREEN, - DesktopMediaID::kNullId); - devices.emplace_back( - MediaStreamDevice(blink::MEDIA_DISPLAY_AUDIO_CAPTURE, - media_id.ToString(), media_id.ToString())); - } + devices = DisplayMediaDevicesFromFakeDeviceConfig( + request->audio_type() == blink::MEDIA_DISPLAY_AUDIO_CAPTURE); } else if (request->video_type() == blink::MEDIA_GUM_DESKTOP_VIDEO_CAPTURE) { // Cache the |label| in the device name field, for unit test purpose only.
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index 991f0e7..2e6afef8 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -209,8 +209,6 @@ #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/interface_provider.h" -#include "services/service_manager/runner/common/client_util.h" -#include "services/service_manager/runner/common/switches.h" #include "services/service_manager/sandbox/switches.h" #include "services/service_manager/zygote/common/zygote_buildflags.h" #include "storage/browser/fileapi/sandbox_file_system_backend.h" @@ -3155,10 +3153,6 @@ } } - DCHECK(child_connection_); - renderer_cmd->AppendSwitchASCII(service_manager::switches::kServicePipeToken, - child_connection_->service_token()); - #if defined(OS_WIN) && !defined(OFFICIAL_BUILD) // Needed because we can't show the dialog from the sandbox. Don't pass // --no-sandbox in official builds because that would bypass the bad_flgs
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.cc b/content/browser/renderer_host/render_widget_host_input_event_router.cc index bb83f83e..5fad7ad 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.cc +++ b/content/browser/renderer_host/render_widget_host_input_event_router.cc
@@ -996,7 +996,7 @@ } // namespace -void RenderWidgetHostInputEventRouter::BubbleScrollEvent( +bool RenderWidgetHostInputEventRouter::BubbleScrollEvent( RenderWidgetHostViewBase* target_view, RenderWidgetHostViewChildFrame* resending_view, const blink::WebGestureEvent& event) { @@ -1013,13 +1013,17 @@ // If target_view has unrelated gesture events in progress, do // not proceed. This could cause confusion between independent // scrolls. - // TODO(mcnee): If we are unable to bubble this gesture sequence, we - // should inform the child view, so that it does not go on to send us - // the updates. See https://crbug.com/828422 if (target_view == touchscreen_gesture_target_.target || target_view == touchpad_gesture_target_ || target_view == touch_target_.target) { - return; + return false; + } + + // A view is trying to bubble a separate scroll sequence while we have + // ongoing bubbling. + if (bubbling_gesture_scroll_target_ && + bubbling_gesture_scroll_target_ != resending_view) { + return false; } // This accounts for bubbling through nested OOPIFs. A gesture scroll @@ -1037,18 +1041,22 @@ bubbling_gesture_scroll_target_ = target_view; bubbling_gesture_scroll_source_device_ = event.SourceDevice(); + DCHECK(IsAncestorView(bubbling_gesture_scroll_origin_, + bubbling_gesture_scroll_target_)); } else { // !(event.GetType() == blink::WebInputEvent::kGestureScrollBegin) if (!bubbling_gesture_scroll_target_) { - // The GestureScrollBegin event is not bubbled, don't bubble the rest of - // the scroll events. - return; + // Drop any acked events that come in after bubbling has ended. + // TODO(mcnee): If we inform |bubbling_gesture_scroll_origin_| and the + // intermediate views of the end of bubbling, we could presumably DCHECK + // that we have a target. + return false; } // Don't bubble the GSE events that are generated and sent to intermediate // bubbling targets. if (event.GetType() == blink::WebInputEvent::kGestureScrollEnd && resending_view != bubbling_gesture_scroll_origin_) { - return; + return true; } } @@ -1062,7 +1070,7 @@ if (resending_view == bubbling_gesture_scroll_target_) { ReportBubblingScrollToSameView(event, resending_view); CancelScrollBubbling(); - return; + return false; } bubbling_gesture_scroll_target_->ProcessGestureEvent( @@ -1075,6 +1083,7 @@ bubbling_gesture_scroll_source_device_ = blink::kWebGestureDeviceUninitialized; } + return true; } void RenderWidgetHostInputEventRouter::SendGestureScrollBegin( @@ -1173,23 +1182,9 @@ if (!bubbling_gesture_scroll_target_ || !bubbling_gesture_scroll_origin_) return; - const RenderWidgetHostViewBase* first_bubbling_scroll_target = - bubbling_gesture_scroll_origin_->GetParentView(); - // TODO(mcnee): This seems wrong. We should not be sending an independent - // gesture sequence to any of |bubbling_gesture_scroll_origin_|'s ancestors - // up to and including |bubbling_gesture_scroll_target_|. - // See https://crbug.com/828422 - if (target == bubbling_gesture_scroll_target_) { - // TODO(mcnee): We shouldn't send the scroll end if we're not actually - // cancelling. - SendGestureScrollEnd(bubbling_gesture_scroll_target_, - bubbling_gesture_scroll_source_device_); - if (bubbling_gesture_scroll_target_ == first_bubbling_scroll_target) { - bubbling_gesture_scroll_origin_ = nullptr; - bubbling_gesture_scroll_target_ = nullptr; - bubbling_gesture_scroll_source_device_ = - blink::kWebGestureDeviceUninitialized; - } + if (IsAncestorView(bubbling_gesture_scroll_origin_, target, + bubbling_gesture_scroll_target_)) { + CancelScrollBubbling(); } }
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.h b/content/browser/renderer_host/render_widget_host_input_event_router.h index 9774213..83c695a 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.h +++ b/content/browser/renderer_host/render_widget_host_input_event_router.h
@@ -11,6 +11,7 @@ #include <unordered_map> #include <vector> +#include "base/compiler_specific.h" #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" @@ -99,9 +100,13 @@ const ui::LatencyInfo& latency); // |event| is in root coordinates. - void BubbleScrollEvent(RenderWidgetHostViewBase* target_view, + // Returns false if the router is unable to bubble the scroll event. The + // caller must not attempt to bubble the rest of the scroll sequence in this + // case. Otherwise, returns true. + bool BubbleScrollEvent(RenderWidgetHostViewBase* target_view, RenderWidgetHostViewChildFrame* resending_view, - const blink::WebGestureEvent& event); + const blink::WebGestureEvent& event) + WARN_UNUSED_RESULT; void WillDetachChildView( const RenderWidgetHostViewChildFrame* detaching_view);
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc b/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc index 72f34588..c3f3eec 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc
@@ -296,6 +296,11 @@ return rwhier()->bubbling_gesture_scroll_target_; } + void TestSendNewGestureWhileBubbling( + TestRenderWidgetHostViewChildFrame* bubbling_origin, + RenderWidgetHostViewBase* gesture_target, + bool should_cancel); + TestBrowserThreadBundle thread_bundle_; MockRenderWidgetHostDelegate delegate_; @@ -615,8 +620,8 @@ { ChildViewState child = MakeChildView(view_root_.get()); - rwhier()->BubbleScrollEvent(view_root_.get(), child.view.get(), - scroll_begin); + ASSERT_TRUE(rwhier()->BubbleScrollEvent(view_root_.get(), child.view.get(), + scroll_begin)); EXPECT_EQ(child.view.get(), bubbling_gesture_scroll_origin()); EXPECT_EQ(view_root_.get(), bubbling_gesture_scroll_target()); EXPECT_EQ(blink::WebInputEvent::kGestureScrollBegin, @@ -633,14 +638,14 @@ ChildViewState outer = MakeChildView(view_root_.get()); ChildViewState inner = MakeChildView(outer.view.get()); - rwhier()->BubbleScrollEvent(outer.view.get(), inner.view.get(), - scroll_begin); + ASSERT_TRUE(rwhier()->BubbleScrollEvent(outer.view.get(), inner.view.get(), + scroll_begin)); EXPECT_EQ(inner.view.get(), bubbling_gesture_scroll_origin()); EXPECT_EQ(outer.view.get(), bubbling_gesture_scroll_target()); EXPECT_EQ(blink::WebInputEvent::kGestureScrollBegin, outer.view->last_gesture_seen()); - rwhier()->BubbleScrollEvent(view_root_.get(), outer.view.get(), - scroll_begin); + ASSERT_TRUE(rwhier()->BubbleScrollEvent(view_root_.get(), outer.view.get(), + scroll_begin)); EXPECT_EQ(inner.view.get(), bubbling_gesture_scroll_origin()); EXPECT_EQ(view_root_.get(), bubbling_gesture_scroll_target()); EXPECT_EQ(blink::WebInputEvent::kGestureScrollEnd, @@ -668,7 +673,8 @@ ChildViewState outer = MakeChildView(view_root_.get()); ChildViewState inner = MakeChildView(outer.view.get()); - rwhier()->BubbleScrollEvent(view_root_.get(), outer.view.get(), scroll_begin); + ASSERT_TRUE(rwhier()->BubbleScrollEvent(view_root_.get(), outer.view.get(), + scroll_begin)); EXPECT_EQ(outer.view.get(), bubbling_gesture_scroll_origin()); EXPECT_EQ(view_root_.get(), bubbling_gesture_scroll_target()); EXPECT_EQ(blink::WebInputEvent::kGestureScrollBegin, @@ -681,4 +687,240 @@ view_root_->last_gesture_seen()); } +void RenderWidgetHostInputEventRouterTest::TestSendNewGestureWhileBubbling( + TestRenderWidgetHostViewChildFrame* bubbling_origin, + RenderWidgetHostViewBase* gesture_target, + bool should_cancel) { + gfx::Vector2dF delta(0.f, 10.f); + blink::WebGestureEvent scroll_begin = + SyntheticWebGestureEventBuilder::BuildScrollBegin( + delta.x(), delta.y(), blink::kWebGestureDeviceTouchscreen); + + TestRenderWidgetHostViewChildFrame* cur_target = bubbling_origin; + RenderWidgetHostViewBase* parent = bubbling_origin->GetParentView(); + while (parent) { + ASSERT_TRUE(rwhier()->BubbleScrollEvent(parent, cur_target, scroll_begin)); + EXPECT_EQ(bubbling_origin, bubbling_gesture_scroll_origin()); + EXPECT_EQ(parent, bubbling_gesture_scroll_target()); + if (cur_target != bubbling_origin) { + EXPECT_EQ(blink::WebInputEvent::kGestureScrollEnd, + cur_target->last_gesture_seen()); + } + + if (parent->IsRenderWidgetHostViewChildFrame()) { + TestRenderWidgetHostViewChildFrame* next_child = + static_cast<TestRenderWidgetHostViewChildFrame*>(parent); + EXPECT_EQ(blink::WebInputEvent::kGestureScrollBegin, + next_child->last_gesture_seen()); + cur_target = next_child; + parent = next_child->GetParentView(); + } else { + MockRootRenderWidgetHostView* root = + static_cast<MockRootRenderWidgetHostView*>(parent); + EXPECT_EQ(blink::WebInputEvent::kGestureScrollBegin, + root->last_gesture_seen()); + parent = nullptr; + } + } + + // While bubbling scroll, a new gesture is targeted to |gesture_target|. + + view_root_->SetHittestResult(gesture_target, false); + + blink::WebTouchEvent touch_event( + blink::WebInputEvent::kTouchStart, blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::GetStaticTimeStampForTests()); + touch_event.touches_length = 1; + touch_event.touches[0].state = blink::WebTouchPoint::kStatePressed; + touch_event.unique_touch_event_id = 123; + + rwhier()->RouteTouchEvent(view_root_.get(), &touch_event, + ui::LatencyInfo(ui::SourceEventType::TOUCH)); + EXPECT_EQ(gesture_target, touch_target()); + + blink::WebGestureEvent gesture_event( + blink::WebInputEvent::kGestureTapDown, blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); + gesture_event.unique_touch_event_id = touch_event.unique_touch_event_id; + + rwhier()->RouteGestureEvent(view_root_.get(), &gesture_event, + ui::LatencyInfo(ui::SourceEventType::TOUCH)); + EXPECT_EQ(gesture_target, touchscreen_gesture_target()); + + if (should_cancel) { + EXPECT_EQ(nullptr, bubbling_gesture_scroll_origin()); + EXPECT_EQ(nullptr, bubbling_gesture_scroll_target()); + } else { + EXPECT_NE(nullptr, bubbling_gesture_scroll_origin()); + EXPECT_NE(nullptr, bubbling_gesture_scroll_target()); + } +} + +// If we're bubbling scroll to a view and a new gesture is to be targeted to +// that view, cancel scroll bubbling, so that the view does not have multiple +// gestures happening at the same time. +TEST_F(RenderWidgetHostInputEventRouterTest, + CancelBubblingOnNewGestureToBubblingTarget) { + ChildViewState child = MakeChildView(view_root_.get()); + + TestSendNewGestureWhileBubbling(child.view.get(), view_root_.get(), true); +} + +// Like CancelBubblingOnNewGestureToBubblingTarget, but tests that we also +// cancel in the case of nested bubbling. +TEST_F(RenderWidgetHostInputEventRouterTest, + CancelNestedBubblingOnNewGestureToBubblingTarget) { + ChildViewState outer = MakeChildView(view_root_.get()); + ChildViewState inner = MakeChildView(outer.view.get()); + + TestSendNewGestureWhileBubbling(inner.view.get(), view_root_.get(), true); +} + +// If we're bubbling scroll and a new gesture is to be targeted to an +// intermediate bubbling target, cancel scroll bubbling. +TEST_F(RenderWidgetHostInputEventRouterTest, + CancelNestedBubblingOnNewGestureToIntermediateTarget) { + ChildViewState outer = MakeChildView(view_root_.get()); + ChildViewState inner = MakeChildView(outer.view.get()); + + TestSendNewGestureWhileBubbling(inner.view.get(), outer.view.get(), true); +} + +// If we're bubbling scroll, the child that is bubbling may receive a new +// gesture. Since this doesn't conflict with the bubbling, we should not +// cancel it. +TEST_F(RenderWidgetHostInputEventRouterTest, + ContinueBubblingOnNewGestureToBubblingOrigin) { + ChildViewState child = MakeChildView(view_root_.get()); + + TestSendNewGestureWhileBubbling(child.view.get(), child.view.get(), false); +} + +// If a view tries to bubble a scroll sequence while we are already bubbling +// a scroll sequence from another view, do not bubble the conflicting sequence. +TEST_F(RenderWidgetHostInputEventRouterTest, DoNotBubbleMultipleSequences) { + gfx::Vector2dF delta(0.f, 10.f); + blink::WebGestureEvent scroll_begin = + SyntheticWebGestureEventBuilder::BuildScrollBegin( + delta.x(), delta.y(), blink::kWebGestureDeviceTouchscreen); + + ChildViewState outer1 = MakeChildView(view_root_.get()); + ChildViewState inner1 = MakeChildView(outer1.view.get()); + ChildViewState outer2 = MakeChildView(view_root_.get()); + ChildViewState inner2 = MakeChildView(outer2.view.get()); + + ASSERT_TRUE(rwhier()->BubbleScrollEvent(outer1.view.get(), inner1.view.get(), + scroll_begin)); + EXPECT_EQ(inner1.view.get(), bubbling_gesture_scroll_origin()); + EXPECT_EQ(outer1.view.get(), bubbling_gesture_scroll_target()); + EXPECT_EQ(blink::WebInputEvent::kGestureScrollBegin, + outer1.view->last_gesture_seen()); + + EXPECT_FALSE(rwhier()->BubbleScrollEvent(outer2.view.get(), inner2.view.get(), + scroll_begin)); + + EXPECT_EQ(inner1.view.get(), bubbling_gesture_scroll_origin()); + EXPECT_EQ(outer1.view.get(), bubbling_gesture_scroll_target()); +} + +// If a view tries to bubble scroll and the target view has an unrelated +// gesture in progress, do not bubble the conflicting sequence. +TEST_F(RenderWidgetHostInputEventRouterTest, + DoNotBubbleIfUnrelatedGestureInTarget) { + gfx::Vector2dF delta(0.f, 10.f); + blink::WebGestureEvent scroll_begin = + SyntheticWebGestureEventBuilder::BuildScrollBegin( + delta.x(), delta.y(), blink::kWebGestureDeviceTouchscreen); + + ChildViewState child = MakeChildView(view_root_.get()); + + view_root_->SetHittestResult(view_root_.get(), false); + + blink::WebTouchEvent touch_event( + blink::WebInputEvent::kTouchStart, blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::GetStaticTimeStampForTests()); + touch_event.touches_length = 1; + touch_event.touches[0].state = blink::WebTouchPoint::kStatePressed; + touch_event.unique_touch_event_id = 123; + + rwhier()->RouteTouchEvent(view_root_.get(), &touch_event, + ui::LatencyInfo(ui::SourceEventType::TOUCH)); + EXPECT_EQ(view_root_.get(), touch_target()); + + blink::WebGestureEvent gesture_event( + blink::WebInputEvent::kGestureTapDown, blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); + gesture_event.unique_touch_event_id = touch_event.unique_touch_event_id; + + rwhier()->RouteGestureEvent(view_root_.get(), &gesture_event, + ui::LatencyInfo(ui::SourceEventType::TOUCH)); + EXPECT_EQ(view_root_.get(), touchscreen_gesture_target()); + + // Now that we have a gesture in |view_root_|, suppose that there was a + // previous gesture in |child.view| that has resulted in a scroll which we + // will now attempt to bubble. + + EXPECT_FALSE(rwhier()->BubbleScrollEvent(view_root_.get(), child.view.get(), + scroll_begin)); + EXPECT_EQ(nullptr, bubbling_gesture_scroll_origin()); + EXPECT_EQ(nullptr, bubbling_gesture_scroll_target()); +} + +// Like DoNotBubbleIfUnrelatedGestureInTarget, but considers bubbling from a +// nested view. +TEST_F(RenderWidgetHostInputEventRouterTest, + NestedDoNotBubbleIfUnrelatedGestureInTarget) { + gfx::Vector2dF delta(0.f, 10.f); + blink::WebGestureEvent scroll_begin = + SyntheticWebGestureEventBuilder::BuildScrollBegin( + delta.x(), delta.y(), blink::kWebGestureDeviceTouchscreen); + + ChildViewState outer = MakeChildView(view_root_.get()); + ChildViewState inner = MakeChildView(outer.view.get()); + + view_root_->SetHittestResult(view_root_.get(), false); + + blink::WebTouchEvent touch_event( + blink::WebInputEvent::kTouchStart, blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::GetStaticTimeStampForTests()); + touch_event.touches_length = 1; + touch_event.touches[0].state = blink::WebTouchPoint::kStatePressed; + touch_event.unique_touch_event_id = 123; + + rwhier()->RouteTouchEvent(view_root_.get(), &touch_event, + ui::LatencyInfo(ui::SourceEventType::TOUCH)); + EXPECT_EQ(view_root_.get(), touch_target()); + + blink::WebGestureEvent gesture_event( + blink::WebInputEvent::kGestureTapDown, blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); + gesture_event.unique_touch_event_id = touch_event.unique_touch_event_id; + + rwhier()->RouteGestureEvent(view_root_.get(), &gesture_event, + ui::LatencyInfo(ui::SourceEventType::TOUCH)); + EXPECT_EQ(view_root_.get(), touchscreen_gesture_target()); + + // Now that we have a gesture in |view_root_|, suppose that there was a + // previous gesture in |inner.view| that has resulted in a scroll which we + // will now attempt to bubble. + + // Bubbling to |outer.view| is fine, since it doesn't interfere with the + // gesture in |view_root_|. + ASSERT_TRUE(rwhier()->BubbleScrollEvent(outer.view.get(), inner.view.get(), + scroll_begin)); + EXPECT_EQ(inner.view.get(), bubbling_gesture_scroll_origin()); + EXPECT_EQ(outer.view.get(), bubbling_gesture_scroll_target()); + EXPECT_EQ(blink::WebInputEvent::kGestureScrollBegin, + outer.view->last_gesture_seen()); + + // We cannot bubble any further, as that would interfere with the gesture in + // |view_root_|. + EXPECT_FALSE(rwhier()->BubbleScrollEvent(view_root_.get(), outer.view.get(), + scroll_begin)); + EXPECT_NE(view_root_.get(), bubbling_gesture_scroll_target()); +} + } // namespace content
diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame.cc b/content/browser/renderer_host/render_widget_host_view_child_frame.cc index 909f4f57..4264c56 100644 --- a/content/browser/renderer_host/render_widget_host_view_child_frame.cc +++ b/content/browser/renderer_host/render_widget_host_view_child_frame.cc
@@ -41,7 +41,6 @@ #include "content/public/browser/guest_mode.h" #include "content/public/browser/render_process_host.h" #include "gpu/ipc/common/gpu_messages.h" -#include "services/service_manager/runner/common/client_util.h" #include "third_party/blink/public/platform/web_touch_event.h" #include "ui/base/ui_base_features.h" #include "ui/gfx/geometry/dip_util.h" @@ -294,11 +293,11 @@ // offset. rect.Offset(parent_view->GetViewBounds().OffsetFromOrigin()); } - // TODO(fsamuel): GetViewBounds is a bit of a mess. It's used to determine + // TODO(wjmaclean): GetViewBounds is a bit of a mess. It's used to determine // the size of the renderer content and where to place context menus and so // on. We want the location of the frame in screen coordinates to place // popups but we want the size in local coordinates to produce the right- - // sized CompositorFrames. + // sized CompositorFrames. https://crbug.com/928825. rect.set_size(frame_connector_->local_frame_size_in_dip()); } return rect; @@ -559,9 +558,11 @@ (event.GetType() == blink::WebInputEvent::kGestureScrollBegin || event.GetType() == blink::WebInputEvent::kGestureScrollUpdate || event.GetType() == blink::WebInputEvent::kGestureScrollEnd)) { - frame_connector_->BubbleScrollEvent(event); - if (event.GetType() == blink::WebInputEvent::kGestureScrollEnd) + const bool can_continue = frame_connector_->BubbleScrollEvent(event); + if (event.GetType() == blink::WebInputEvent::kGestureScrollEnd || + !can_continue) { is_scroll_sequence_bubbling_ = false; + } } }
diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame_unittest.cc b/content/browser/renderer_host/render_widget_host_view_child_frame_unittest.cc index 72d509d..bdb8cf2 100644 --- a/content/browser/renderer_host/render_widget_host_view_child_frame_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_view_child_frame_unittest.cc
@@ -71,13 +71,25 @@ return nullptr; } - void BubbleScrollEvent(const blink::WebGestureEvent& event) override { - if (event.GetType() == blink::WebInputEvent::kGestureScrollUpdate) - seen_bubbled_gsu_ = true; + bool BubbleScrollEvent(const blink::WebGestureEvent& event) override { + last_bubbled_event_type_ = event.GetType(); + return can_bubble_; } + blink::WebInputEvent::Type GetAndResetLastBubbledEventType() { + blink::WebInputEvent::Type last = last_bubbled_event_type_; + last_bubbled_event_type_ = blink::WebInputEvent::kUndefined; + return last; + } + + void SetCanBubble(bool can_bubble) { can_bubble_ = can_bubble; } + viz::SurfaceInfo last_surface_info_; - bool seen_bubbled_gsu_ = false; + + private: + blink::WebInputEvent::Type last_bubbled_event_type_ = + blink::WebInputEvent::kUndefined; + bool can_bubble_ = true; }; class RenderWidgetHostViewChildFrameTest : public testing::Test { @@ -317,4 +329,109 @@ EXPECT_EQ(123u, std::get<0>(params).capture_sequence_number); } +// Test that when we have a gesture scroll sequence that is not consumed by the +// child, the events are bubbled so that the parent may consume them. +TEST_F(RenderWidgetHostViewChildFrameTest, UncomsumedGestureScrollBubbled) { + blink::WebGestureEvent scroll_begin = + SyntheticWebGestureEventBuilder::BuildScrollBegin( + 0.f, 10.f, blink::kWebGestureDeviceTouchscreen); + blink::WebGestureEvent scroll_update = + SyntheticWebGestureEventBuilder::BuildScrollUpdate( + 0.f, 10.f, 0, blink::kWebGestureDeviceTouchscreen); + blink::WebGestureEvent scroll_end = SyntheticWebGestureEventBuilder::Build( + blink::WebInputEvent::kGestureScrollEnd, + blink::kWebGestureDeviceTouchscreen); + + view_->GestureEventAck(scroll_begin, + INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS); + EXPECT_EQ(blink::WebInputEvent::kGestureScrollBegin, + test_frame_connector_->GetAndResetLastBubbledEventType()); + view_->GestureEventAck(scroll_update, + INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS); + EXPECT_EQ(blink::WebInputEvent::kGestureScrollUpdate, + test_frame_connector_->GetAndResetLastBubbledEventType()); + view_->GestureEventAck(scroll_end, INPUT_EVENT_ACK_STATE_IGNORED); + EXPECT_EQ(blink::WebInputEvent::kGestureScrollEnd, + test_frame_connector_->GetAndResetLastBubbledEventType()); +} + +// Test that when we have a gesture scroll sequence that is consumed by the +// child, the events are not bubbled to the parent. +TEST_F(RenderWidgetHostViewChildFrameTest, ConsumedGestureScrollNotBubbled) { + blink::WebGestureEvent scroll_begin = + SyntheticWebGestureEventBuilder::BuildScrollBegin( + 0.f, 10.f, blink::kWebGestureDeviceTouchscreen); + blink::WebGestureEvent scroll_update = + SyntheticWebGestureEventBuilder::BuildScrollUpdate( + 0.f, 10.f, 0, blink::kWebGestureDeviceTouchscreen); + blink::WebGestureEvent scroll_end = SyntheticWebGestureEventBuilder::Build( + blink::WebInputEvent::kGestureScrollEnd, + blink::kWebGestureDeviceTouchscreen); + + view_->GestureEventAck(scroll_begin, INPUT_EVENT_ACK_STATE_CONSUMED); + EXPECT_EQ(blink::WebInputEvent::kUndefined, + test_frame_connector_->GetAndResetLastBubbledEventType()); + view_->GestureEventAck(scroll_update, INPUT_EVENT_ACK_STATE_CONSUMED); + EXPECT_EQ(blink::WebInputEvent::kUndefined, + test_frame_connector_->GetAndResetLastBubbledEventType()); + + // Scrolling in a child my reach its extent and no longer be consumed, however + // scrolling is latched to the child so we do not bubble the update. + view_->GestureEventAck(scroll_update, + INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS); + EXPECT_EQ(blink::WebInputEvent::kUndefined, + test_frame_connector_->GetAndResetLastBubbledEventType()); + + view_->GestureEventAck(scroll_end, INPUT_EVENT_ACK_STATE_IGNORED); + EXPECT_EQ(blink::WebInputEvent::kUndefined, + test_frame_connector_->GetAndResetLastBubbledEventType()); +} + +// Test that the child does not continue to attempt to bubble scroll events if +// bubbling has failed for the current scroll gesture. +TEST_F(RenderWidgetHostViewChildFrameTest, + DoNotBubbleRemainingEventsOfRejectedScrollGesture) { + blink::WebGestureEvent scroll_begin = + SyntheticWebGestureEventBuilder::BuildScrollBegin( + 0.f, 10.f, blink::kWebGestureDeviceTouchscreen); + blink::WebGestureEvent scroll_update = + SyntheticWebGestureEventBuilder::BuildScrollUpdate( + 0.f, 10.f, 0, blink::kWebGestureDeviceTouchscreen); + blink::WebGestureEvent scroll_end = SyntheticWebGestureEventBuilder::Build( + blink::WebInputEvent::kGestureScrollEnd, + blink::kWebGestureDeviceTouchscreen); + + test_frame_connector_->SetCanBubble(false); + + view_->GestureEventAck(scroll_begin, + INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS); + EXPECT_EQ(blink::WebInputEvent::kGestureScrollBegin, + test_frame_connector_->GetAndResetLastBubbledEventType()); + + // The GSB was rejected, so the child view must not attempt to bubble the + // remaining events of the scroll sequence. + view_->GestureEventAck(scroll_update, + INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS); + EXPECT_EQ(blink::WebInputEvent::kUndefined, + test_frame_connector_->GetAndResetLastBubbledEventType()); + view_->GestureEventAck(scroll_end, INPUT_EVENT_ACK_STATE_IGNORED); + EXPECT_EQ(blink::WebInputEvent::kUndefined, + test_frame_connector_->GetAndResetLastBubbledEventType()); + + test_frame_connector_->SetCanBubble(true); + + // When we have a new scroll gesture, the view may try bubbling again. + view_->GestureEventAck(scroll_begin, + INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS); + EXPECT_EQ(blink::WebInputEvent::kGestureScrollBegin, + test_frame_connector_->GetAndResetLastBubbledEventType()); + view_->GestureEventAck(scroll_update, + INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS); + EXPECT_EQ(blink::WebInputEvent::kGestureScrollUpdate, + test_frame_connector_->GetAndResetLastBubbledEventType()); + view_->GestureEventAck(scroll_end, INPUT_EVENT_ACK_STATE_IGNORED); + EXPECT_EQ(blink::WebInputEvent::kGestureScrollEnd, + test_frame_connector_->GetAndResetLastBubbledEventType()); +} + } // namespace content
diff --git a/content/browser/renderer_host/render_widget_host_view_cocoa.mm b/content/browser/renderer_host/render_widget_host_view_cocoa.mm index 24e931f..ed18a0a 100644 --- a/content/browser/renderer_host/render_widget_host_view_cocoa.mm +++ b/content/browser/renderer_host/render_widget_host_view_cocoa.mm
@@ -92,9 +92,7 @@ // Whether a keyboard event has been reserved by OSX. BOOL EventIsReservedBySystem(NSEvent* event) { - content::SystemHotkeyHelperMac* helper = - content::SystemHotkeyHelperMac::GetInstance(); - return helper->map()->IsEventReserved(event); + return content::GetSystemHotkeyMap()->IsEventReserved(event); } // TODO(suzhe): Upstream this function.
diff --git a/content/browser/security_exploit_browsertest.cc b/content/browser/security_exploit_browsertest.cc index 83d0a79..45f7063 100644 --- a/content/browser/security_exploit_browsertest.cc +++ b/content/browser/security_exploit_browsertest.cc
@@ -1284,4 +1284,59 @@ EXPECT_EQ(bad_message::INVALID_INITIATOR_ORIGIN, kill_waiter.Wait()); } +namespace { + +// An interceptor class that allows replacing the URL of the commit IPC from +// the renderer process to the browser process. +class DidCommitUrlReplacer : public DidCommitProvisionalLoadInterceptor { + public: + DidCommitUrlReplacer(WebContents* web_contents, const GURL& replacement_url) + : DidCommitProvisionalLoadInterceptor(web_contents), + replacement_url_(replacement_url) {} + ~DidCommitUrlReplacer() override = default; + + protected: + bool WillDispatchDidCommitProvisionalLoad( + RenderFrameHost* render_frame_host, + ::FrameHostMsg_DidCommitProvisionalLoad_Params* params, + mojom::DidCommitProvisionalLoadInterfaceParamsPtr& interface_params) + override { + params->url = replacement_url_; + return true; + } + + private: + GURL replacement_url_; + + DISALLOW_COPY_AND_ASSIGN(DidCommitUrlReplacer); +}; + +} // namespace + +// Test which verifies that when an exploited renderer process sends a commit +// message with URL that the process is not allowed to commit. +IN_PROC_BROWSER_TEST_F(SecurityExploitBrowserTest, DidCommitInvalidURL) { + // Explicitly isolating foo.com helps ensure that this test is applicable on + // platforms without site-per-process. + IsolateOrigin("foo.com"); + + // Navigate to foo.com initially. + GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html")); + EXPECT_TRUE(NavigateToURL(shell(), foo_url)); + + // Create the interceoptor object which will replace the URL of the subsequent + // navigation with bar.com based URL. + GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title3.html")); + DidCommitUrlReplacer url_replacer(shell()->web_contents(), bar_url); + + // Navigate to another URL within foo.com, which would usually be committed + // succsesfuly, but when the URL is modified it should result in the + // termination of the renderer process. + RenderProcessHostKillWaiter kill_waiter( + shell()->web_contents()->GetMainFrame()->GetProcess()); + NavigateToURL(shell(), + embedded_test_server()->GetURL("foo.com", "/title2.html")); + EXPECT_EQ(bad_message::RFH_CAN_COMMIT_URL_BLOCKED, kill_waiter.Wait()); +} + } // namespace content
diff --git a/content/browser/serial/serial_browsertest.cc b/content/browser/serial/serial_browsertest.cc index 1f57636..361bd9d7 100644 --- a/content/browser/serial/serial_browsertest.cc +++ b/content/browser/serial/serial_browsertest.cc
@@ -7,7 +7,6 @@ #include "base/command_line.h" #include "base/unguessable_token.h" -#include "build/build_config.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/serial_chooser.h" #include "content/public/browser/serial_delegate.h" @@ -126,13 +125,7 @@ } // namespace -// https://crbug.com/928712 tracks failure on Android tablets. -#if defined(OS_ANDROID) -#define MAYBE_GetPorts DISABLED_GetPorts -#else -#define MAYBE_GetPorts GetPorts -#endif -IN_PROC_BROWSER_TEST_F(SerialTest, MAYBE_GetPorts) { +IN_PROC_BROWSER_TEST_F(SerialTest, GetPorts) { NavigateToURL(shell(), GetTestUrl(nullptr, "simple_page.html")); // Three ports are added but only two will have permission granted. @@ -158,13 +151,7 @@ EXPECT_EQ(2, result); } -// https://crbug.com/928712 tracks failure on Android tablets. -#if defined(OS_ANDROID) -#define MAYBE_RequestPort DISABLED_RequestPort -#else -#define MAYBE_RequestPort RequestPort -#endif -IN_PROC_BROWSER_TEST_F(SerialTest, MAYBE_RequestPort) { +IN_PROC_BROWSER_TEST_F(SerialTest, RequestPort) { NavigateToURL(shell(), GetTestUrl(nullptr, "simple_page.html")); auto port = device::mojom::SerialPortInfo::New();
diff --git a/content/browser/service_manager/service_manager_context.cc b/content/browser/service_manager/service_manager_context.cc index d75438b..dfdb6d1d 100644 --- a/content/browser/service_manager/service_manager_context.cc +++ b/content/browser/service_manager/service_manager_context.cc
@@ -80,7 +80,6 @@ #include "services/service_manager/public/cpp/manifest.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/mojom/service.mojom.h" -#include "services/service_manager/runner/common/client_util.h" #include "services/service_manager/sandbox/sandbox_type.h" #include "services/service_manager/service_manager.h" #include "services/service_manager/service_process_launcher.h" @@ -529,45 +528,37 @@ // The |service_manager_thread_task_runner_| must have been created before // starting the ServiceManager. DCHECK(service_manager_thread_task_runner_); - service_manager::mojom::ServiceRequest packaged_services_request; - if (service_manager::ServiceManagerIsRemote()) { - auto endpoint = mojo::PlatformChannel::RecoverPassedEndpointFromCommandLine( - *base::CommandLine::ForCurrentProcess()); - auto invitation = mojo::IncomingInvitation::Accept(std::move(endpoint)); - packaged_services_request = - service_manager::GetServiceRequestFromCommandLine(&invitation); - } else { - std::vector<service_manager::Manifest> manifests{ - GetContentBrowserManifest(), GetContentGpuManifest(), - GetContentPackagedServicesManifest(), GetContentPluginManifest(), - GetContentRendererManifest(), GetContentUtilityManifest(), - }; - for (auto& manifest : manifests) { - base::Optional<service_manager::Manifest> overlay = - GetContentClient()->browser()->GetServiceManifestOverlay( - manifest.service_name); - if (overlay) - manifest.Amend(*overlay); - if (!manifest.preloaded_files.empty()) { - std::map<std::string, base::FilePath> preloaded_files_map; - for (const auto& info : manifest.preloaded_files) - preloaded_files_map.emplace(info.key, info.path); - ChildProcessLauncher::SetRegisteredFilesForService( - manifest.service_name, std::move(preloaded_files_map)); - } + std::vector<service_manager::Manifest> manifests{ + GetContentBrowserManifest(), GetContentGpuManifest(), + GetContentPackagedServicesManifest(), GetContentPluginManifest(), + GetContentRendererManifest(), GetContentUtilityManifest(), + }; + for (auto& manifest : manifests) { + base::Optional<service_manager::Manifest> overlay = + GetContentClient()->browser()->GetServiceManifestOverlay( + manifest.service_name); + if (overlay) + manifest.Amend(*overlay); + if (!manifest.preloaded_files.empty()) { + std::map<std::string, base::FilePath> preloaded_files_map; + for (const auto& info : manifest.preloaded_files) + preloaded_files_map.emplace(info.key, info.path); + ChildProcessLauncher::SetRegisteredFilesForService( + manifest.service_name, std::move(preloaded_files_map)); } - for (auto& extra_manifest : - GetContentClient()->browser()->GetExtraServiceManifests()) { - manifests.emplace_back(std::move(extra_manifest)); - } - in_process_context_ = - new InProcessServiceManagerContext(service_manager_thread_task_runner_); - - service_manager::mojom::ServicePtr packaged_services_service; - packaged_services_request = mojo::MakeRequest(&packaged_services_service); - in_process_context_->Start(packaged_services_service.PassInterface(), - std::move(manifests)); } + for (auto& extra_manifest : + GetContentClient()->browser()->GetExtraServiceManifests()) { + manifests.emplace_back(std::move(extra_manifest)); + } + in_process_context_ = + new InProcessServiceManagerContext(service_manager_thread_task_runner_); + + service_manager::mojom::ServicePtr packaged_services_service; + service_manager::mojom::ServiceRequest packaged_services_request = + mojo::MakeRequest(&packaged_services_service); + in_process_context_->Start(packaged_services_service.PassInterface(), + std::move(manifests)); packaged_services_connection_ = ServiceManagerConnection::Create(std::move(packaged_services_request),
diff --git a/content/browser/service_worker/service_worker_context_core.cc b/content/browser/service_worker/service_worker_context_core.cc index 6932e5e..64a0774 100644 --- a/content/browser/service_worker/service_worker_context_core.cc +++ b/content/browser/service_worker/service_worker_context_core.cc
@@ -70,23 +70,23 @@ : ServiceWorkerCapability::SERVICE_WORKER_NO_FETCH_HANDLER); } -void SuccessCollectorCallback(base::OnceClosure done_closure, - bool* overall_success, - blink::ServiceWorkerStatusCode status) { - if (status != blink::ServiceWorkerStatusCode::kOk) { - *overall_success = false; - } - std::move(done_closure).Run(); -} - +// This function will call |callback| after |*expected_calls| reaches zero or +// when an error occurs. In case of an error, |*expected_calls| is set to -1 +// to prevent calling |callback| again. void SuccessReportingCallback( - const bool* success, - base::OnceCallback<void(blink::ServiceWorkerStatusCode)> callback) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - bool result = *success; - std::move(callback).Run(result - ? blink::ServiceWorkerStatusCode::kOk - : blink::ServiceWorkerStatusCode::kErrorFailed); + int* expected_calls, + const base::RepeatingCallback<void(blink::ServiceWorkerStatusCode)>& + callback, + blink::ServiceWorkerStatusCode status) { + if (status != blink::ServiceWorkerStatusCode::kOk) { + *expected_calls = -1; + callback.Run(blink::ServiceWorkerStatusCode::kErrorFailed); + return; + } + (*expected_calls)--; + if (*expected_calls == 0) { + callback.Run(blink::ServiceWorkerStatusCode::kOk); + } } bool IsSameOriginClientProviderHost(const GURL& origin, @@ -512,24 +512,29 @@ std::move(callback).Run(status); return; } - bool* overall_success = new bool(true); + if (registrations.empty()) { + std::move(callback).Run(blink::ServiceWorkerStatusCode::kOk); + return; + } + + int* expected_calls = new int(2 * registrations.size()); // The barrier must be executed twice for each registration: once for - // unregistration and once for deletion. - base::RepeatingClosure barrier = base::BarrierClosure( - 2 * registrations.size(), - base::BindOnce(&SuccessReportingCallback, base::Owned(overall_success), - std::move(callback))); + // unregistration and once for deletion. It will call |callback| immediately + // if an error occurs. + base::RepeatingCallback<void(blink::ServiceWorkerStatusCode)> barrier = + base::BindRepeating(SuccessReportingCallback, base::Owned(expected_calls), + base::AdaptCallbackForRepeating(std::move(callback))); for (const auto& registration : registrations) { DCHECK(registration); if (!registration->is_deleted()) { - RegistrationDeletionListener::WaitForDeletion(registration, barrier); + RegistrationDeletionListener::WaitForDeletion( + registration, + base::BindOnce(barrier, blink::ServiceWorkerStatusCode::kOk)); } else { - barrier.Run(); + barrier.Run(blink::ServiceWorkerStatusCode::kOk); } job_coordinator_->Abort(registration->scope()); - UnregisterServiceWorker( - registration->scope(), - base::BindOnce(&SuccessCollectorCallback, barrier, overall_success)); + UnregisterServiceWorker(registration->scope(), barrier); } }
diff --git a/content/browser/service_worker/service_worker_context_core_unittest.cc b/content/browser/service_worker/service_worker_context_core_unittest.cc index b360646..de8d4ac2 100644 --- a/content/browser/service_worker/service_worker_context_core_unittest.cc +++ b/content/browser/service_worker/service_worker_context_core_unittest.cc
@@ -6,16 +6,23 @@ #include <memory> +#include "base/test/bind_test_util.h" #include "content/browser/service_worker/embedded_worker_test_helper.h" +#include "content/browser/service_worker/service_worker_context_core.h" +#include "content/browser/service_worker/service_worker_context_core_observer.h" +#include "content/browser/service_worker/service_worker_context_wrapper.h" +#include "content/browser/service_worker/service_worker_registration.h" #include "content/browser/service_worker/service_worker_test_utils.h" +#include "content/browser/service_worker/service_worker_version.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_utils.h" #include "testing/gtest/include/gtest/gtest.h" namespace content { -class ServiceWorkerContextCoreTest : public testing::Test { - protected: +class ServiceWorkerContextCoreTest : public testing::Test, + public ServiceWorkerContextCoreObserver { + public: ServiceWorkerContextCoreTest() : thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP) {} @@ -23,14 +30,107 @@ helper_.reset(new EmbeddedWorkerTestHelper(base::FilePath())); } - void TearDown() override { helper_.reset(); } + void TearDown() override { + if (is_observing_context_) { + helper_->context_wrapper()->RemoveObserver(this); + helper_.reset(); + } + } ServiceWorkerContextCore* context() { return helper_->context(); } TestBrowserThreadBundle thread_bundle_; std::unique_ptr<EmbeddedWorkerTestHelper> helper_; + // Runs until |registration| has an active version and it is activated. + void RunUntilActivatedVersion(ServiceWorkerRegistration* registration) { + if (registration->active_version() && + registration->active_version()->status() == + ServiceWorkerVersion::ACTIVATED) + return; + if (!is_observing_context_) { + helper_->context_wrapper()->AddObserver(this); + is_observing_context_ = true; + } + base::RunLoop loop; + scope_for_wait_for_activated_ = registration->scope(); + quit_closure_for_wait_for_activated_ = loop.QuitClosure(); + loop.Run(); + } + + // Registers |script| and waits for the service worker to become activated. + void RegisterServiceWorker( + const GURL& script, + blink::mojom::ServiceWorkerRegistrationOptions options) { + base::RunLoop loop; + blink::ServiceWorkerStatusCode status; + int64_t registration_id; + context()->RegisterServiceWorker( + script, options, + base::BindLambdaForTesting( + [&](blink::ServiceWorkerStatusCode result_status, + const std::string& /* status_message */, + int64_t result_registration_id) { + status = result_status; + registration_id = result_registration_id; + loop.Quit(); + })); + loop.Run(); + EXPECT_EQ(blink::ServiceWorkerStatusCode::kOk, status); + scoped_refptr<ServiceWorkerRegistration> registration = + context()->GetLiveRegistration(registration_id); + ASSERT_TRUE(registration); + RunUntilActivatedVersion(registration.get()); + EXPECT_TRUE(registration->active_version()); + } + + // Wrapper for ServiceWorkerStorage::FindRegistrationForScope. + blink::ServiceWorkerStatusCode FindRegistrationForScope(const GURL& scope) { + base::RunLoop loop; + blink::ServiceWorkerStatusCode status; + context()->storage()->FindRegistrationForScope( + scope, + base::BindLambdaForTesting( + [&](blink::ServiceWorkerStatusCode result_status, + scoped_refptr<ServiceWorkerRegistration> result_registration) { + status = result_status; + loop.Quit(); + })); + loop.Run(); + return status; + } + + // Wrapper for ServiceWorkerContextCore::DeleteForOrigin. + blink::ServiceWorkerStatusCode DeleteForOrigin(const GURL& origin) { + blink::ServiceWorkerStatusCode status; + base::RunLoop loop; + context()->DeleteForOrigin( + origin, base::BindLambdaForTesting( + [&](blink::ServiceWorkerStatusCode result_status) { + status = result_status; + loop.Quit(); + })); + loop.Run(); + return status; + } + + protected: + // ServiceWorkerContextCoreObserver overrides: + void OnVersionStateChanged(int64_t version_id, + const GURL& scope, + ServiceWorkerVersion::Status status) override { + if (status == ServiceWorkerVersion::ACTIVATED && + scope == scope_for_wait_for_activated_ && + quit_closure_for_wait_for_activated_) { + std::move(quit_closure_for_wait_for_activated_).Run(); + } + } + private: + GURL scope_for_wait_for_activated_; + base::OnceClosure quit_closure_for_wait_for_activated_; + bool is_observing_context_ = false; + DISALLOW_COPY_AND_ASSIGN(ServiceWorkerContextCoreTest); }; @@ -62,4 +162,52 @@ EXPECT_FALSE(base::ContainsKey(context()->failure_counts_, kVersionId)); } +TEST_F(ServiceWorkerContextCoreTest, DeleteForOrigin) { + const GURL script("https://www.example.com/a/sw.js"); + const GURL scope("https://www.example.com/a"); + const GURL origin("https://www.example.com"); + + // Register a service worker. + blink::mojom::ServiceWorkerRegistrationOptions options; + options.scope = scope; + RegisterServiceWorker(scope, options); + + // Delete for origin. + EXPECT_EQ(blink::ServiceWorkerStatusCode::kOk, DeleteForOrigin(origin)); + + // The registration should be deleted. + EXPECT_EQ(blink::ServiceWorkerStatusCode::kErrorNotFound, + FindRegistrationForScope(scope)); +} + +// Tests that DeleteForOrigin() doesn't get stuck forever even upon an error +// when trying to unregister. +TEST_F(ServiceWorkerContextCoreTest, DeleteForOrigin_UnregisterFail) { + const GURL script("https://www.example.com/a/sw.js"); + const GURL scope("https://www.example.com/a"); + const GURL origin("https://www.example.com"); + + // Register a service worker. + blink::mojom::ServiceWorkerRegistrationOptions options; + options.scope = scope; + RegisterServiceWorker(scope, options); + + // Start DeleteForOrigin(). + base::RunLoop loop; + blink::ServiceWorkerStatusCode status; + context()->DeleteForOrigin( + origin, base::BindLambdaForTesting( + [&](blink::ServiceWorkerStatusCode result_status) { + status = result_status; + loop.Quit(); + })); + // Disable storage before it finishes. This causes the Unregister job to + // complete with an error. + context()->storage()->Disable(); + loop.Run(); + + // The operation should still complete. + EXPECT_EQ(blink::ServiceWorkerStatusCode::kErrorFailed, status); +} + } // namespace content
diff --git a/content/browser/service_worker/service_worker_job_unittest.cc b/content/browser/service_worker/service_worker_job_unittest.cc index a7e605a..6ce7c6b 100644 --- a/content/browser/service_worker/service_worker_job_unittest.cc +++ b/content/browser/service_worker/service_worker_job_unittest.cc
@@ -26,6 +26,7 @@ #include "content/browser/service_worker/service_worker_registration_object_host.h" #include "content/browser/service_worker/service_worker_registration_status.h" #include "content/browser/service_worker/service_worker_test_utils.h" +#include "content/browser/service_worker/test_service_worker_observer.h" #include "content/common/service_worker/service_worker_utils.h" #include "content/public/test/test_browser_context.h" #include "content/public/test/test_browser_thread_bundle.h" @@ -1240,8 +1241,7 @@ update_helper->SetupInitialRegistration(kNewVersionOrigin); ASSERT_TRUE(registration.get()); update_helper->state_change_log_.clear(); - scoped_refptr<base::TestSimpleTaskRunner> runner( - new base::TestSimpleTaskRunner()); + auto runner = base::MakeRefCounted<base::TestSimpleTaskRunner>(); registration->SetTaskRunnerForTest(runner); // Run the update job. @@ -1256,21 +1256,20 @@ if (blink::ServiceWorkerUtils::IsServicificationEnabled()) { EXPECT_EQ(first_version.get(), registration->active_version()); // The new worker is installed but not yet to be activated. + scoped_refptr<ServiceWorkerVersion> new_version = + registration->waiting_version(); EXPECT_EQ(2u, update_helper->attribute_change_log_.size()); EXPECT_TRUE(RequestTermination(helper_.get(), first_version)); - base::RunLoop().RunUntilIdle(); - // RequestTermination() and following RunUntilIdle() terminated the service - // worker and resulted in calling ServiceWorkerRegistration::OnNoWork(). It - // started the activation procedure, and posted a delayed task to activate - // the worker. RunPendingTasks() runs the posted activation task. - EXPECT_TRUE(runner->HasPendingTask()); - runner->RunPendingTasks(); - - // Make sure that all tasks for activation finish. - base::RunLoop().RunUntilIdle(); + TestServiceWorkerObserver observer(helper_->context_wrapper()); + observer.RunUntilActivated(new_version.get(), runner); } + // Pump the loop again. This ensures |update_helper| observes all + // the status changes, since RunUntilActivated() only ensured + // ServiceWorkerJobTest did. + base::RunLoop().RunUntilIdle(); + // Verify results. ASSERT_TRUE(registration->active_version()); EXPECT_NE(first_version.get(), registration->active_version()); @@ -1362,6 +1361,8 @@ options.scope = GURL("https://www.example.com/one/"); scoped_refptr<ServiceWorkerRegistration> registration = RunRegisterJob( GURL("https://www.example.com/service_worker.js"), options); + auto runner = base::MakeRefCounted<base::TestSimpleTaskRunner>(); + registration->SetTaskRunnerForTest(runner); // Queue an Update. When this runs, it will use the waiting version's script. job_coordinator()->Update(registration.get(), false); @@ -1382,13 +1383,15 @@ // Still waiting, but the waiting version isn't |version| since another // ServiceWorkerVersion is created during the update job and the job wipes // out the older waiting version. + ServiceWorkerVersion* waiting_version = registration->waiting_version(); EXPECT_TRUE(registration->active_version()); - EXPECT_NE(version.get(), registration->waiting_version()); - EXPECT_NE(nullptr, registration->waiting_version()); + EXPECT_TRUE(waiting_version); + EXPECT_NE(version.get(), waiting_version); EXPECT_TRUE( RequestTermination(helper_.get(), registration->active_version())); - base::RunLoop().RunUntilIdle(); + TestServiceWorkerObserver observer(helper_->context_wrapper()); + observer.RunUntilActivated(waiting_version, runner); } // The update job should have created a new version with the new script, @@ -1466,8 +1469,7 @@ scoped_refptr<ServiceWorkerRegistration> registration = RunRegisterJob(script1, options); - scoped_refptr<base::TestSimpleTaskRunner> runner( - new base::TestSimpleTaskRunner()); + auto runner = base::MakeRefCounted<base::TestSimpleTaskRunner>(); registration->SetTaskRunnerForTest(runner); // Add a controllee and queue an unregister to force the uninstalling state. @@ -1482,7 +1484,6 @@ EXPECT_FALSE(registration->is_uninstalling()); EXPECT_EQ(old_version, registration->active_version()); - scoped_refptr<ServiceWorkerVersion> new_version = registration->waiting_version(); @@ -1492,23 +1493,21 @@ EXPECT_EQ(EmbeddedWorkerStatus::RUNNING, new_version->running_status()); EXPECT_EQ(ServiceWorkerVersion::INSTALLED, new_version->status()); + // Make the old version eligible for eviction. old_version->RemoveControllee(host->client_uuid()); if (blink::ServiceWorkerUtils::IsServicificationEnabled()) EXPECT_TRUE(RequestTermination(helper_.get(), old_version)); - base::RunLoop().RunUntilIdle(); + // Wait for activated. + TestServiceWorkerObserver observer(helper_->context_wrapper()); + observer.RunUntilActivated(new_version.get(), runner); + + // Verify state after the new version is activated. EXPECT_FALSE(registration->is_uninstalling()); EXPECT_FALSE(registration->is_uninstalled()); - - // Verify the new version is activated. EXPECT_EQ(nullptr, registration->installing_version()); EXPECT_EQ(nullptr, registration->waiting_version()); EXPECT_EQ(new_version, registration->active_version()); - EXPECT_EQ(ServiceWorkerVersion::ACTIVATING, new_version->status()); - - runner->RunUntilIdle(); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(EmbeddedWorkerStatus::RUNNING, new_version->running_status()); EXPECT_EQ(ServiceWorkerVersion::ACTIVATED, new_version->status()); } @@ -1571,8 +1570,7 @@ scoped_refptr<ServiceWorkerRegistration> registration = RunRegisterJob(script1, options); - scoped_refptr<base::TestSimpleTaskRunner> runner( - new base::TestSimpleTaskRunner()); + auto runner = base::MakeRefCounted<base::TestSimpleTaskRunner>(); registration->SetTaskRunnerForTest(runner); // Add a controllee and queue an unregister to force the uninstalling state. @@ -1600,20 +1598,17 @@ old_version->RemoveControllee(host->client_uuid()); if (blink::ServiceWorkerUtils::IsServicificationEnabled()) EXPECT_TRUE(RequestTermination(helper_.get(), old_version)); - base::RunLoop().RunUntilIdle(); + // Wait for activated. + TestServiceWorkerObserver observer(helper_->context_wrapper()); + observer.RunUntilActivated(new_version.get(), runner); + + // Verify state after the new version is activated. EXPECT_FALSE(registration->is_uninstalling()); EXPECT_FALSE(registration->is_uninstalled()); - - // Verify the new version is activated. EXPECT_EQ(nullptr, registration->installing_version()); EXPECT_EQ(nullptr, registration->waiting_version()); EXPECT_EQ(new_version, registration->active_version()); - EXPECT_EQ(ServiceWorkerVersion::ACTIVATING, new_version->status()); - - runner->RunUntilIdle(); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(EmbeddedWorkerStatus::RUNNING, new_version->running_status()); EXPECT_EQ(ServiceWorkerVersion::ACTIVATED, new_version->status()); } @@ -1626,8 +1621,7 @@ scoped_refptr<ServiceWorkerRegistration> registration = RunRegisterJob(script1, options); - scoped_refptr<base::TestSimpleTaskRunner> runner( - new base::TestSimpleTaskRunner()); + auto runner = base::MakeRefCounted<base::TestSimpleTaskRunner>(); registration->SetTaskRunnerForTest(runner); // Add a controllee and queue an unregister to force the uninstalling state. @@ -1659,20 +1653,17 @@ first_version->RemoveControllee(host->client_uuid()); if (blink::ServiceWorkerUtils::IsServicificationEnabled()) EXPECT_TRUE(RequestTermination(helper_.get(), first_version)); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(registration->is_uninstalling()); - EXPECT_FALSE(registration->is_uninstalled()); + // Wait for activated. + TestServiceWorkerObserver observer(helper_->context_wrapper()); + observer.RunUntilActivated(third_version.get(), runner); // Verify the new version is activated. + EXPECT_FALSE(registration->is_uninstalling()); + EXPECT_FALSE(registration->is_uninstalled()); EXPECT_EQ(nullptr, registration->installing_version()); EXPECT_EQ(nullptr, registration->waiting_version()); EXPECT_EQ(third_version, registration->active_version()); - EXPECT_EQ(ServiceWorkerVersion::ACTIVATING, third_version->status()); - - runner->RunUntilIdle(); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(EmbeddedWorkerStatus::RUNNING, third_version->running_status()); EXPECT_EQ(ServiceWorkerVersion::ACTIVATED, third_version->status()); } @@ -1939,8 +1930,7 @@ scoped_refptr<ServiceWorkerRegistration> registration = RunRegisterJob(script, options); - scoped_refptr<base::TestSimpleTaskRunner> runner( - new base::TestSimpleTaskRunner()); + auto runner = base::MakeRefCounted<base::TestSimpleTaskRunner>(); registration->SetTaskRunnerForTest(runner); // Add a controllee. @@ -1975,9 +1965,11 @@ // RequestTermination() is called. EXPECT_EQ(first_version.get(), registration->active_version()); EXPECT_TRUE(RequestTermination(update_helper, first_version)); - base::RunLoop().RunUntilIdle(); } + TestServiceWorkerObserver observer(helper_->context_wrapper()); + observer.RunUntilStatusChange(new_version.get(), + ServiceWorkerVersion::ACTIVATING); EXPECT_EQ(new_version.get(), registration->active_version()); EXPECT_EQ(ServiceWorkerVersion::ACTIVATING, new_version->status());
diff --git a/content/browser/service_worker/test_service_worker_observer.cc b/content/browser/service_worker/test_service_worker_observer.cc new file mode 100644 index 0000000..288ac82 --- /dev/null +++ b/content/browser/service_worker/test_service_worker_observer.cc
@@ -0,0 +1,62 @@ +// 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. + +#include "content/browser/service_worker/test_service_worker_observer.h" + +#include <utility> + +#include "base/run_loop.h" +#include "base/test/test_simple_task_runner.h" +#include "content/browser/service_worker/service_worker_context_wrapper.h" + +namespace content { + +TestServiceWorkerObserver::TestServiceWorkerObserver( + scoped_refptr<ServiceWorkerContextWrapper> wrapper) + : wrapper_(std::move(wrapper)) { + wrapper_->AddObserver(this); +} + +TestServiceWorkerObserver::~TestServiceWorkerObserver() { + wrapper_->RemoveObserver(this); +} + +void TestServiceWorkerObserver::RunUntilStatusChange( + ServiceWorkerVersion* version, + ServiceWorkerVersion::Status status) { + if (version->status() == status) + return; + + base::RunLoop loop; + version_id_for_status_change_ = version->version_id(); + status_for_status_change_ = status; + DCHECK(!quit_closure_for_status_change_); + quit_closure_for_status_change_ = loop.QuitClosure(); + loop.Run(); +} + +void TestServiceWorkerObserver::RunUntilActivated( + ServiceWorkerVersion* version, + scoped_refptr<base::TestSimpleTaskRunner> runner) { + if (version->status() == ServiceWorkerVersion::ACTIVATED) + return; + + // Call runner->RunUntilIdle() to skip the delay for the activate event in + // ServiceWorkerRegistration. + RunUntilStatusChange(version, ServiceWorkerVersion::ACTIVATING); + runner->RunUntilIdle(); + RunUntilStatusChange(version, ServiceWorkerVersion::ACTIVATED); +} + +void TestServiceWorkerObserver::OnVersionStateChanged( + int64_t version_id, + const GURL& scope, + ServiceWorkerVersion::Status status) { + if (version_id == version_id_for_status_change_ && + status == status_for_status_change_ && quit_closure_for_status_change_) { + std::move(quit_closure_for_status_change_).Run(); + } +} + +} // namespace content
diff --git a/content/browser/service_worker/test_service_worker_observer.h b/content/browser/service_worker/test_service_worker_observer.h new file mode 100644 index 0000000..c4de11f9c --- /dev/null +++ b/content/browser/service_worker/test_service_worker_observer.h
@@ -0,0 +1,59 @@ +// 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. + +#ifndef CONTENT_BROWSER_SERVICE_WORKER_TEST_SERVICE_WORKER_OBSERVER_H_ +#define CONTENT_BROWSER_SERVICE_WORKER_TEST_SERVICE_WORKER_OBSERVER_H_ + +#include "base/macros.h" +#include "base/memory/scoped_refptr.h" +#include "content/browser/service_worker/service_worker_context_core_observer.h" +#include "content/browser/service_worker/service_worker_version.h" + +namespace base { +class TestSimpleTaskRunner; +} + +namespace content { + +class ServiceWorkerContextWrapper; + +// Observes events related to service workers. Exposes convenience methods for +// use in tests. +class TestServiceWorkerObserver : public ServiceWorkerContextCoreObserver { + public: + explicit TestServiceWorkerObserver( + scoped_refptr<ServiceWorkerContextWrapper> wrapper); + ~TestServiceWorkerObserver() override; + + // Returns when |version| reaches |status|. + void RunUntilStatusChange(ServiceWorkerVersion* version, + ServiceWorkerVersion::Status status); + + // Returns when |version| reaches ACTIVATED. |runner| should + // be the version's registration's task runner. This function is + // useful for skipping the 1 second wall time delay for the activate event in + // ServiceWorkerRegistration. If not for that delay, a single + // RunUntilStatusChange() call for ACTIVATED would suffice. + void RunUntilActivated(ServiceWorkerVersion* version, + scoped_refptr<base::TestSimpleTaskRunner> runner); + + private: + // ServiceWorkerContextCoreObserver overrides: + void OnVersionStateChanged(int64_t version_id, + const GURL& scope, + ServiceWorkerVersion::Status status) override; + + scoped_refptr<ServiceWorkerContextWrapper> wrapper_; + + int64_t version_id_for_status_change_ = -1; + ServiceWorkerVersion::Status status_for_status_change_ = + ServiceWorkerVersion::NEW; + base::OnceClosure quit_closure_for_status_change_; + + DISALLOW_COPY_AND_ASSIGN(TestServiceWorkerObserver); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_SERVICE_WORKER_TEST_SERVICE_WORKER_OBSERVER_H_
diff --git a/content/browser/site_per_process_browsertest.cc b/content/browser/site_per_process_browsertest.cc index 72efd82..6052590 100644 --- a/content/browser/site_per_process_browsertest.cc +++ b/content/browser/site_per_process_browsertest.cc
@@ -14448,7 +14448,7 @@ rfh_b->DisableSwapOutTimerForTesting(); rfh_c->DisableSwapOutTimerForTesting(); - RenderFrameDeletedObserver delete_B(rfh_b), delete_C(rfh_c); + RenderFrameDeletedObserver delete_b(rfh_b), delete_c(rfh_c); // 2) Navigate rfh_c to D. NavigateFrameToURL(rfh_c->frame_tree_node(), url_d); @@ -14457,7 +14457,7 @@ EXPECT_EQ(RenderFrameHostImpl::UnloadState::InProgress, rfh_c->unload_state_); RenderFrameHostImpl* rfh_d = rfh_b->child_at(0)->current_frame_host(); - RenderFrameDeletedObserver delete_D(rfh_d); + RenderFrameDeletedObserver delete_d(rfh_d); // Act as if there was a slow unload handler on rfh_d. // The non navigating frames are waiting for FrameHostMsg_Detach. @@ -14473,16 +14473,16 @@ EXPECT_EQ(RenderFrameHostImpl::UnloadState::InProgress, rfh_d->unload_state_); // rfh_d completes its unload event. It deletes the frame, including rfh_c. - EXPECT_FALSE(delete_C.deleted()); - EXPECT_FALSE(delete_D.deleted()); + EXPECT_FALSE(delete_c.deleted()); + EXPECT_FALSE(delete_d.deleted()); rfh_d->OnDetach(); - EXPECT_TRUE(delete_C.deleted()); - EXPECT_TRUE(delete_D.deleted()); + EXPECT_TRUE(delete_c.deleted()); + EXPECT_TRUE(delete_d.deleted()); // rfh_b completes its unload event. - EXPECT_FALSE(delete_B.deleted()); + EXPECT_FALSE(delete_b.deleted()); rfh_b->OnSwapOutACK(); - EXPECT_TRUE(delete_B.deleted()); + EXPECT_TRUE(delete_b.deleted()); } // A set of nested frames A1(B1(A2)) are pending deletion because of a @@ -14719,18 +14719,19 @@ RenderProcessHostKillWaiter kill_waiter( root->current_frame_host()->GetProcess()); - // Create commit params with a different origin than the origin lock - // of the process. + // Create commit params with the same URL as the start one, so URL checks + // pass, but use a different origin than the origin lock of the process. std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params> params = std::make_unique<FrameHostMsg_DidCommitProvisionalLoad_Params>(); params->nav_entry_id = 0; params->did_create_new_entry = false; - params->url = another_url; + params->url = start_url; params->transition = ui::PAGE_TRANSITION_LINK; params->should_update_history = false; params->gesture = NavigationGestureAuto; params->method = "GET"; - params->page_state = PageState::CreateFromURL(another_url); + params->page_state = PageState::CreateFromURL(start_url); + // Use an origin mismatched with the origin lock. params->origin = url::Origin::Create(another_url); auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); @@ -14738,6 +14739,7 @@ EXPECT_EQ("http://a.com/", policy->GetOriginLock(process_id)); EXPECT_EQ(start_url.host(), policy->GetOriginLock(process_id).host()); EXPECT_NE(another_url.host(), policy->GetOriginLock(process_id).host()); + // Simulate a commit IPC. service_manager::mojom::InterfaceProviderPtr interface_provider; blink::mojom::DocumentInterfaceBrokerPtrInfo @@ -14943,4 +14945,112 @@ } } +// Pending navigations must be canceled when a frame becomes pending deletion. +// +// 1) Initial state: A(B). +// 2) Navigation from B to C. The server is slow to respond. +// 3) Deletion of B. +IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, + NavigationCommitInIframePendingDeletionAB) { + GURL url_a(embedded_test_server()->GetURL( + "a.com", "/cross_site_iframe_factory.html?a(b)")); + GURL url_c(embedded_test_server()->GetURL("c.com", "/hung")); + + // 1) Initial state: A(B). + EXPECT_TRUE(NavigateToURL(shell(), url_a)); + RenderFrameHostImpl* rfh_a = web_contents()->GetMainFrame(); + RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host(); + + // RFH B has an unload handler. + auto detach_filter_b = base::MakeRefCounted<DetachMessageFilter>(); + rfh_b->GetProcess()->AddFilter(detach_filter_b.get()); + EXPECT_TRUE(ExecJs(rfh_b, "onunload=function(){}")); + + // 2) Navigation from B to C. The server is slow to respond. + TestNavigationManager navigation_observer(web_contents(), url_c); + EXPECT_TRUE(ExecJs(rfh_b, JsReplace("location.href=$1;", url_c))); + EXPECT_TRUE(navigation_observer.WaitForRequestStart()); + RenderFrameHostImpl* rfh_c = + rfh_b->frame_tree_node()->render_manager()->speculative_frame_host(); + + EXPECT_EQ(RenderFrameHostImpl::UnloadState::NotRun, rfh_a->unload_state_); + EXPECT_EQ(RenderFrameHostImpl::UnloadState::NotRun, rfh_b->unload_state_); + EXPECT_EQ(RenderFrameHostImpl::UnloadState::NotRun, rfh_c->unload_state_); + + // 3) Deletion of B. The unload handler takes times to execute. + RenderFrameDeletedObserver delete_b(rfh_b), delete_c(rfh_c); + EXPECT_TRUE( + ExecJs(rfh_a, JsReplace("document.querySelector('iframe').remove();"))); + EXPECT_FALSE(delete_b.deleted()); + EXPECT_TRUE(delete_c.deleted()); // The speculative RFH is deleted. + EXPECT_EQ(RenderFrameHostImpl::UnloadState::NotRun, rfh_a->unload_state_); + EXPECT_EQ(RenderFrameHostImpl::UnloadState::InProgress, rfh_b->unload_state_); + + // The navigation has been canceled. + navigation_observer.WaitForNavigationFinished(); + EXPECT_FALSE(navigation_observer.was_successful()); + + // |rfh_b| will complete its deletion at some point: + EXPECT_FALSE(delete_b.deleted()); + rfh_b->OnDetach(); + EXPECT_TRUE(delete_b.deleted()); +} + +// Pending navigations must be canceled when a frame becomes pending deletion. +// +// 1) Initial state: A(B(C)). +// 2) Navigation from C to D. The server is slow to respond. +// 3) Deletion of B. +IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, + NavigationCommitInIframePendingDeletionABC) { + GURL url_a(embedded_test_server()->GetURL( + "a.com", "/cross_site_iframe_factory.html?a(b(c))")); + GURL url_d(embedded_test_server()->GetURL("d.com", "/hung")); + + // 1) Initial state: A(B(C)). + EXPECT_TRUE(NavigateToURL(shell(), url_a)); + RenderFrameHostImpl* rfh_a = web_contents()->GetMainFrame(); + RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host(); + RenderFrameHostImpl* rfh_c = rfh_b->child_at(0)->current_frame_host(); + + // RFH C has an unload handler. + auto detach_filter_c = base::MakeRefCounted<DetachMessageFilter>(); + rfh_c->GetProcess()->AddFilter(detach_filter_c.get()); + EXPECT_TRUE(ExecJs(rfh_c, "onunload=function(){}")); + + // 2) Navigation from C to D. The server is slow to respond. + TestNavigationManager navigation_observer(web_contents(), url_d); + EXPECT_TRUE(ExecJs(rfh_c, JsReplace("location.href=$1;", url_d))); + EXPECT_TRUE(navigation_observer.WaitForRequestStart()); + RenderFrameHostImpl* rfh_d = + rfh_c->frame_tree_node()->render_manager()->speculative_frame_host(); + + EXPECT_EQ(RenderFrameHostImpl::UnloadState::NotRun, rfh_a->unload_state_); + EXPECT_EQ(RenderFrameHostImpl::UnloadState::NotRun, rfh_b->unload_state_); + EXPECT_EQ(RenderFrameHostImpl::UnloadState::NotRun, rfh_c->unload_state_); + EXPECT_EQ(RenderFrameHostImpl::UnloadState::NotRun, rfh_d->unload_state_); + + // 3) Deletion of D. The unload handler takes times to execute. + RenderFrameDeletedObserver delete_b(rfh_b), delete_c(rfh_c), delete_d(rfh_d); + EXPECT_TRUE( + ExecJs(rfh_a, JsReplace("document.querySelector('iframe').remove();"))); + EXPECT_FALSE(delete_b.deleted()); + EXPECT_FALSE(delete_c.deleted()); + EXPECT_TRUE(delete_d.deleted()); // The speculative RFH is deleted. + EXPECT_EQ(RenderFrameHostImpl::UnloadState::NotRun, rfh_a->unload_state_); + EXPECT_EQ(RenderFrameHostImpl::UnloadState::Completed, rfh_b->unload_state_); + EXPECT_EQ(RenderFrameHostImpl::UnloadState::InProgress, rfh_c->unload_state_); + + // The navigation has been canceled. + navigation_observer.WaitForNavigationFinished(); + EXPECT_FALSE(navigation_observer.was_successful()); + + // |rfh_b| and |rfh_c| will complete their deletion at some point: + EXPECT_FALSE(delete_b.deleted()); + EXPECT_FALSE(delete_c.deleted()); + rfh_c->OnDetach(); + EXPECT_TRUE(delete_b.deleted()); + EXPECT_TRUE(delete_c.deleted()); +} + } // namespace content
diff --git a/content/browser/site_per_process_hit_test_browsertest.cc b/content/browser/site_per_process_hit_test_browsertest.cc index 9df3997..f8b552e8 100644 --- a/content/browser/site_per_process_hit_test_browsertest.cc +++ b/content/browser/site_per_process_hit_test_browsertest.cc
@@ -1471,6 +1471,180 @@ root_scroll_begin_observer.Wait(); } +namespace { + +// Waits until an event of the given type has been sent to the given +// RenderWidgetHost. +class OutgoingEventWaiter : public RenderWidgetHost::InputEventObserver { + public: + explicit OutgoingEventWaiter(RenderWidgetHostImpl* rwh, + blink::WebInputEvent::Type type) + : rwh_(rwh->GetWeakPtr()), type_(type) { + rwh->AddInputEventObserver(this); + } + + ~OutgoingEventWaiter() override { + if (rwh_) + rwh_->RemoveInputEventObserver(this); + } + + void OnInputEvent(const blink::WebInputEvent& event) override { + if (event.GetType() == type_) { + seen_event_ = true; + if (quit_closure_) + std::move(quit_closure_).Run(); + } + } + + void Wait() { + if (!seen_event_) { + base::RunLoop run_loop; + quit_closure_ = run_loop.QuitClosure(); + run_loop.Run(); + } + } + + private: + base::WeakPtr<RenderWidgetHostImpl> rwh_; + const blink::WebInputEvent::Type type_; + bool seen_event_ = false; + base::OnceClosure quit_closure_; +}; + +// Fails the test if an event of the given type is sent to the given +// RenderWidgetHost. +class BadInputEventObserver : public RenderWidgetHost::InputEventObserver { + public: + explicit BadInputEventObserver(RenderWidgetHostImpl* rwh, + blink::WebInputEvent::Type type) + : rwh_(rwh->GetWeakPtr()), type_(type) { + rwh->AddInputEventObserver(this); + } + + ~BadInputEventObserver() override { + if (rwh_) + rwh_->RemoveInputEventObserver(this); + } + + void OnInputEvent(const blink::WebInputEvent& event) override { + EXPECT_NE(type_, event.GetType()) + << "Unexpected " << blink::WebInputEvent::GetName(event.GetType()); + } + + private: + base::WeakPtr<RenderWidgetHostImpl> rwh_; + const blink::WebInputEvent::Type type_; +}; + +} // namespace + +IN_PROC_BROWSER_TEST_P(SitePerProcessHitTestBrowserTest, + ScrollBubblingTargetWithUnrelatedGesture) { + GURL main_url(embedded_test_server()->GetURL( + "/frame_tree/page_with_positioned_nested_frames.html")); + ASSERT_TRUE(NavigateToURL(shell(), main_url)); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); + ASSERT_EQ(1U, root->child_count()); + FrameTreeNode* parent_iframe_node = root->child_at(0); + ASSERT_EQ(1U, parent_iframe_node->child_count()); + + GURL nested_frame_url(embedded_test_server()->GetURL( + "baz.com", "/page_with_touch_start_janking_main_thread.html")); + NavigateFrameToURL(parent_iframe_node->child_at(0), nested_frame_url); + + RenderWidgetHostViewBase* root_rwhv = static_cast<RenderWidgetHostViewBase*>( + root->current_frame_host()->GetRenderWidgetHost()->GetView()); + RenderWidgetHostViewChildFrame* rwhv_parent = + static_cast<RenderWidgetHostViewChildFrame*>( + parent_iframe_node->current_frame_host() + ->GetRenderWidgetHost() + ->GetView()); + RenderWidgetHostViewChildFrame* rwhv_nested = + static_cast<RenderWidgetHostViewChildFrame*>( + parent_iframe_node->child_at(0) + ->current_frame_host() + ->GetRenderWidgetHost() + ->GetView()); + + RenderWidgetHostInputEventRouter* router = + static_cast<WebContentsImpl*>(shell()->web_contents()) + ->GetInputEventRouter(); + + WaitForHitTestDataOrChildSurfaceReady( + parent_iframe_node->child_at(0)->current_frame_host()); + + OutgoingEventWaiter outgoing_touch_end_waiter( + static_cast<RenderWidgetHostImpl*>(rwhv_nested->GetRenderWidgetHost()), + blink::WebInputEvent::kTouchEnd); + InputEventAckWaiter scroll_end_at_parent( + rwhv_parent->GetRenderWidgetHost(), + blink::WebInputEvent::kGestureScrollEnd); + BadInputEventObserver no_scroll_bubbling_to_root( + static_cast<RenderWidgetHostImpl*>(root_rwhv->GetRenderWidgetHost()), + blink::WebInputEvent::kGestureScrollBegin); + + MainThreadFrameObserver synchronize_threads( + rwhv_nested->GetRenderWidgetHost()); + synchronize_threads.Wait(); + +#if defined(USE_AURA) + // Allow the scroll gesture through under mash. + base::Optional<SystemEventRewriter::ScopedAllow> maybe_scoped_allow_events; + if (features::IsSingleProcessMash()) { + maybe_scoped_allow_events.emplace(&event_rewriter_); + } +#endif + + SyntheticSmoothScrollGestureParams params; + params.gesture_source_type = SyntheticGestureParams::TOUCH_INPUT; + const gfx::PointF location_in_widget(25, 25); + const gfx::PointF location_in_root = + rwhv_nested->TransformPointToRootCoordSpaceF(location_in_widget); + params.anchor = location_in_root; + params.distances.push_back(gfx::Vector2d(0, 100)); + params.prevent_fling = false; + RenderWidgetHostImpl* root_widget_host = + static_cast<RenderWidgetHostImpl*>(root_rwhv->GetRenderWidgetHost()); + auto dont_care_on_complete = + base::BindOnce([](SyntheticGesture::Result result) {}); + root_widget_host->QueueSyntheticGesture( + std::make_unique<SyntheticSmoothScrollGesture>(params), + std::move(dont_care_on_complete)); + + outgoing_touch_end_waiter.Wait(); + + // We are now waiting for the touch events to be acked from the nested OOPIF + // which will result in a scroll gesture that will bubble from the nested + // frame. Meanwhile, we start a new gesture in the main frame. + + const gfx::PointF point_in_root(1, 1); + blink::WebTouchEvent touch_event( + blink::WebInputEvent::kTouchStart, blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::GetStaticTimeStampForTests()); + touch_event.touches_length = 1; + touch_event.touches[0].state = blink::WebTouchPoint::kStatePressed; + SetWebEventPositions(&touch_event.touches[0], point_in_root, root_rwhv); + touch_event.unique_touch_event_id = 1; + InputEventAckWaiter root_touch_waiter(root_rwhv->GetRenderWidgetHost(), + blink::WebInputEvent::kTouchStart); + router->RouteTouchEvent(root_rwhv, &touch_event, + ui::LatencyInfo(ui::SourceEventType::TOUCH)); + root_touch_waiter.Wait(); + + blink::WebGestureEvent gesture_event( + blink::WebInputEvent::kGestureTapDown, blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); + gesture_event.unique_touch_event_id = touch_event.unique_touch_event_id; + router->RouteGestureEvent(root_rwhv, &gesture_event, + ui::LatencyInfo(ui::SourceEventType::TOUCH)); + + scroll_end_at_parent.Wait(); + // By this point, the parent frame attempted to bubble scroll to the main + // frame. |no_scroll_bubbling_to_root| checks that the bubbling stopped at + // the parent. +} + class SitePerProcessEmulatedTouchBrowserTest : public SitePerProcessHitTestBrowserTest { public:
diff --git a/content/browser/startup_helper.cc b/content/browser/startup_helper.cc index 9d979d5..7f13b4c 100644 --- a/content/browser/startup_helper.cc +++ b/content/browser/startup_helper.cc
@@ -24,20 +24,32 @@ // Mobile config, for iOS see ios/web/app/web_main_loop.cc. return std::make_unique<base::TaskScheduler::InitParams>( base::SchedulerWorkerPoolParams( - base::RecommendedMaxNumberOfThreadsInPool(4, 8, 0.2, 0), + base::RecommendedMaxNumberOfThreadsInPool(2, 8, 0.1, 0), base::TimeDelta::FromSeconds(30)), base::SchedulerWorkerPoolParams( - base::RecommendedMaxNumberOfThreadsInPool(6, 8, 0.6, 0), - base::TimeDelta::FromSeconds(30))); + base::RecommendedMaxNumberOfThreadsInPool(2, 8, 0.1, 0), + base::TimeDelta::FromSeconds(30)), + base::SchedulerWorkerPoolParams( + base::RecommendedMaxNumberOfThreadsInPool(3, 8, 0.3, 0), + base::TimeDelta::FromSeconds(30)), + base::SchedulerWorkerPoolParams( + base::RecommendedMaxNumberOfThreadsInPool(3, 8, 0.3, 0), + base::TimeDelta::FromSeconds(60))); #else // Desktop config. return std::make_unique<base::TaskScheduler::InitParams>( base::SchedulerWorkerPoolParams( - base::RecommendedMaxNumberOfThreadsInPool(6, 8, 0.2, 0), + base::RecommendedMaxNumberOfThreadsInPool(3, 8, 0.1, 0), base::TimeDelta::FromSeconds(30)), base::SchedulerWorkerPoolParams( - base::RecommendedMaxNumberOfThreadsInPool(16, 32, 0.6, 0), - base::TimeDelta::FromSeconds(30)) + base::RecommendedMaxNumberOfThreadsInPool(3, 8, 0.1, 0), + base::TimeDelta::FromSeconds(40)), + base::SchedulerWorkerPoolParams( + base::RecommendedMaxNumberOfThreadsInPool(8, 32, 0.3, 0), + base::TimeDelta::FromSeconds(30)), + base::SchedulerWorkerPoolParams( + base::RecommendedMaxNumberOfThreadsInPool(8, 32, 0.3, 0), + base::TimeDelta::FromSeconds(60)) #if defined(OS_WIN) , base::TaskScheduler::InitParams::SharedWorkerPoolEnvironment::COM_MTA
diff --git a/content/browser/storage_partition_impl.cc b/content/browser/storage_partition_impl.cc index bbee352..ba536e4 100644 --- a/content/browser/storage_partition_impl.cc +++ b/content/browser/storage_partition_impl.cc
@@ -919,7 +919,8 @@ void StoragePartitionImpl::OpenLocalStorage( const url::Origin& origin, - blink::mojom::StorageAreaRequest request) { + blink::mojom::StorageAreaRequest request, + OpenLocalStorageCallback callback) { int process_id = bindings_.dispatch_context(); if (!ChildProcessSecurityPolicy::GetInstance()->CanAccessDataForOrigin( process_id, origin.GetURL())) { @@ -927,16 +928,18 @@ bindings_.ReportBadMessage("Access denied for localStorage request"); return; } - dom_storage_context_->OpenLocalStorage(origin, std::move(request)); + dom_storage_context_->OpenLocalStorage(origin, std::move(request), + std::move(callback)); } void StoragePartitionImpl::OpenSessionStorage( const std::string& namespace_id, - blink::mojom::SessionStorageNamespaceRequest request) { + blink::mojom::SessionStorageNamespaceRequest request, + OpenSessionStorageCallback callback) { int process_id = bindings_.dispatch_context(); - dom_storage_context_->OpenSessionStorage(process_id, namespace_id, - bindings_.GetBadMessageCallback(), - std::move(request)); + dom_storage_context_->OpenSessionStorage( + process_id, namespace_id, bindings_.GetBadMessageCallback(), + std::move(request), std::move(callback)); } void StoragePartitionImpl::OnCanSendReportingReports(
diff --git a/content/browser/storage_partition_impl.h b/content/browser/storage_partition_impl.h index 57c2bdc6f..6094e3c 100644 --- a/content/browser/storage_partition_impl.h +++ b/content/browser/storage_partition_impl.h
@@ -154,10 +154,11 @@ // blink::mojom::StoragePartitionService interface. void OpenLocalStorage(const url::Origin& origin, - blink::mojom::StorageAreaRequest request) override; - void OpenSessionStorage( - const std::string& namespace_id, - blink::mojom::SessionStorageNamespaceRequest request) override; + blink::mojom::StorageAreaRequest request, + OpenLocalStorageCallback callback) override; + void OpenSessionStorage(const std::string& namespace_id, + blink::mojom::SessionStorageNamespaceRequest request, + OpenSessionStorageCallback callback) override; // network::mojom::NetworkContextClient interface. void OnCanSendReportingReports(
diff --git a/content/browser/tracing/cast_tracing_agent.cc b/content/browser/tracing/cast_tracing_agent.cc index 7a263c6..fa4ae658 100644 --- a/content/browser/tracing/cast_tracing_agent.cc +++ b/content/browser/tracing/cast_tracing_agent.cc
@@ -165,14 +165,14 @@ // Called from the tracing::ProducerClient on its sequence. void StartTracing( tracing::ProducerClient* producer_client, - const tracing::mojom::DataSourceConfig& data_source_config) override { + const perfetto::DataSourceConfig& data_source_config) override { DCHECK_CALLED_ON_VALID_SEQUENCE(perfetto_sequence_checker_); DCHECK(!producer_client_); DCHECK(!session_); producer_client_ = producer_client; - target_buffer_ = data_source_config.target_buffer; + target_buffer_ = data_source_config.target_buffer(); session_ = std::make_unique<CastSystemTracingSession>(worker_task_runner_); - session_->StartTracing(data_source_config.trace_config, + session_->StartTracing(data_source_config.chrome_config().trace_config(), base::BindOnce(&CastDataSource::SystemTracerStarted, base::Unretained(this))); }
diff --git a/content/browser/tracing/cros_tracing_agent.cc b/content/browser/tracing/cros_tracing_agent.cc index 4f45515..427f6d0 100644 --- a/content/browser/tracing/cros_tracing_agent.cc +++ b/content/browser/tracing/cros_tracing_agent.cc
@@ -102,7 +102,7 @@ // Called from the tracing::ProducerClient on its sequence. void StartTracing( tracing::ProducerClient* producer_client, - const tracing::mojom::DataSourceConfig& data_source_config) override { + const perfetto::DataSourceConfig& data_source_config) override { base::PostTaskWithTraits( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&CrOSDataSource::StartTracingOnUI, @@ -131,17 +131,16 @@ DETACH_FROM_SEQUENCE(ui_sequence_checker_); } - void StartTracingOnUI( - tracing::ProducerClient* producer_client, - const tracing::mojom::DataSourceConfig& data_source_config) { + void StartTracingOnUI(tracing::ProducerClient* producer_client, + const perfetto::DataSourceConfig& data_source_config) { DCHECK_CALLED_ON_VALID_SEQUENCE(ui_sequence_checker_); DCHECK(!producer_client_); DCHECK(!session_); producer_client_ = producer_client; - target_buffer_ = data_source_config.target_buffer; + target_buffer_ = data_source_config.target_buffer(); session_ = std::make_unique<CrOSSystemTracingSession>(); session_->StartTracing( - data_source_config.trace_config, + data_source_config.chrome_config().trace_config(), base::BindOnce(&CrOSDataSource::SystemTracerStartedOnUI, base::Unretained(this))); }
diff --git a/content/browser/url_loader_factory_getter.cc b/content/browser/url_loader_factory_getter.cc index 51ea65b7..3438086 100644 --- a/content/browser/url_loader_factory_getter.cc +++ b/content/browser/url_loader_factory_getter.cc
@@ -200,11 +200,9 @@ if (g_get_network_factory_callback.Get() && !test_factory_) g_get_network_factory_callback.Get().Run(this); - // The |is_corb_enabled| case will only be hit for AppCache scenarios, where - // the URLLoaderInterceptor's test hooks are sufficiently covered at the - // RenderFrameHostImpl level (e.g. intercepting requests coming from the - // renderer, rather than requests generated within - // AppCacheSubresourceURLFactory. + if (is_corb_enabled && test_factory_corb_enabled_) + return test_factory_corb_enabled_; + if (!is_corb_enabled && test_factory_) return test_factory_; @@ -218,10 +216,16 @@ } void URLLoaderFactoryGetter::SetNetworkFactoryForTesting( - network::mojom::URLLoaderFactory* test_factory) { + network::mojom::URLLoaderFactory* test_factory, + bool is_corb_enabled) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - DCHECK(!test_factory_ || !test_factory); - test_factory_ = test_factory; + if (is_corb_enabled) { + DCHECK(!test_factory_corb_enabled_ || !test_factory); + test_factory_corb_enabled_ = test_factory; + } else { + DCHECK(!test_factory_ || !test_factory); + test_factory_ = test_factory; + } } void URLLoaderFactoryGetter::SetGetNetworkFactoryCallbackForTesting(
diff --git a/content/browser/url_loader_factory_getter.h b/content/browser/url_loader_factory_getter.h index 5f18912..cc053a5 100644 --- a/content/browser/url_loader_factory_getter.h +++ b/content/browser/url_loader_factory_getter.h
@@ -87,7 +87,8 @@ // Overrides the network URLLoaderFactory for subsequent requests. Passing a // null pointer will restore the default behavior. CONTENT_EXPORT void SetNetworkFactoryForTesting( - network::mojom::URLLoaderFactory* test_factory); + network::mojom::URLLoaderFactory* test_factory, + bool is_corb_enabled = false); CONTENT_EXPORT network::mojom::URLLoaderFactoryPtr* original_network_factory_for_testing() { @@ -149,6 +150,7 @@ network::mojom::URLLoaderFactoryPtr network_factory_; network::mojom::URLLoaderFactoryPtr network_factory_corb_enabled_; network::mojom::URLLoaderFactory* test_factory_ = nullptr; + network::mojom::URLLoaderFactory* test_factory_corb_enabled_ = nullptr; // Used to re-create |network_factory_| when connection error happens. Can // only be accessed on UI thread. Must be cleared by |StoragePartitionImpl|
diff --git a/content/browser/web_contents/web_contents_impl_browsertest.cc b/content/browser/web_contents/web_contents_impl_browsertest.cc index ac50c6c9..47db5cf5 100644 --- a/content/browser/web_contents/web_contents_impl_browsertest.cc +++ b/content/browser/web_contents/web_contents_impl_browsertest.cc
@@ -930,10 +930,66 @@ return http_response; } + // A basic worker that loads 3p.com/script + if (absolute_url.path() == "/worker.js") { + auto http_response = + std::make_unique<net::test_server::BasicHttpResponse>(); + http_response->set_code(net::HTTP_OK); + + GURL resource = GenURL("3p.com", "/script"); + std::string content = + base::StringPrintf("importScripts('%s');", resource.spec().c_str()); + + http_response->set_content(content); + http_response->set_content_type("application/javascript"); + return http_response; + } + + // A worker that loads a nested /worker.js on an origin provided as a query + // param. + if (absolute_url.path() == "/embedding_worker.js") { + auto http_response = + std::make_unique<net::test_server::BasicHttpResponse>(); + http_response->set_code(net::HTTP_OK); + + GURL resource = + GenURL(base::StringPrintf("%s.com", absolute_url.query().c_str()), + "/worker.js"); + + const char kLoadWorkerScript[] = "let w = new Worker('%s');"; + std::string content = + base::StringPrintf(kLoadWorkerScript, resource.spec().c_str()); + + http_response->set_content(content); + http_response->set_content_type("application/javascript"); + return http_response; + } + return std::unique_ptr<net::test_server::HttpResponse>(); } protected: + bool TestResourceLoadFromDedicatedWorker(const GURL& url, + const GURL& worker) { + // Kill the renderer to clear the in-memory cache. + NavigateToURL(shell(), GURL("chrome:crash")); + + // Observe network requests. + ResourceLoadObserver observer(shell()); + + NavigateToURL(shell(), url); + + const char kLoadWorkerScript[] = "let w = new Worker('%s');"; + std::string create_worker_script = + base::StringPrintf(kLoadWorkerScript, worker.spec().c_str()); + + EXPECT_TRUE(ExecuteScript(shell(), create_worker_script)); + + GURL resource = GenURL("3p.com", "/script"); + observer.WaitForResourceCompletion(resource); + return (*observer.FindResource(resource))->was_cached; + } + // Loads 3p.com/script on page |url|, optionally from |sub_frame| if it's // valid and return if the script was cached or not. bool TestResourceLoad(const GURL& url, const GURL& sub_frame) { @@ -1081,6 +1137,53 @@ GenURL("c.com", "/title1.html"))); } +IN_PROC_BROWSER_TEST_F(WebContentsSplitCacheBrowserTestEnabled, + SplitCacheDedicatedWorkers) { + // Load 3p.com/script from a.com's worker. The first time it's loaded from the + // network and the second it's cached. + EXPECT_FALSE(TestResourceLoadFromDedicatedWorker( + GenURL("a.com", "/title1.html"), GenURL("a.com", "/worker.js"))); + EXPECT_TRUE(TestResourceLoadFromDedicatedWorker( + GenURL("a.com", "/title1.html"), GenURL("a.com", "/worker.js"))); + + // Load 3p.com/script from a worker with a new top frame origin. Due to split + // caching it's a cache miss. + EXPECT_FALSE(TestResourceLoadFromDedicatedWorker( + GenURL("b.com", "/title1.html"), GenURL("b.com", "/worker.js"))); + EXPECT_TRUE(TestResourceLoadFromDedicatedWorker( + GenURL("b.com", "/title1.html"), GenURL("b.com", "/worker.js"))); + + // Load 3p.com/script from a nested worker with a new top-frame origin. Due to + // split caching it's a cache miss. + EXPECT_FALSE(TestResourceLoadFromDedicatedWorker( + GenURL("c.com", "/title1.html"), + GenURL("c.com", "/embedding_worker.js?c"))); + EXPECT_TRUE(TestResourceLoadFromDedicatedWorker( + GenURL("c.com", "/title1.html"), + GenURL("c.com", "/embedding_worker.js?c"))); +} + +IN_PROC_BROWSER_TEST_F(WebContentsSplitCacheBrowserTestDisabled, + SplitCacheDedicatedWorkers) { + // Load 3p.com/script from a.com's worker. The first time it's loaded from the + // network and the second it's cached. + EXPECT_FALSE(TestResourceLoadFromDedicatedWorker( + GenURL("a.com", "/title1.html"), GenURL("a.com", "/worker.js"))); + EXPECT_TRUE(TestResourceLoadFromDedicatedWorker( + GenURL("a.com", "/title1.html"), GenURL("a.com", "/worker.js"))); + + // Load 3p.com/script from b.com's worker. The cache isn't split by top frame + // origin so the resource is already cached. + EXPECT_TRUE(TestResourceLoadFromDedicatedWorker( + GenURL("b.com", "/title1.html"), GenURL("b.com", "/worker.js"))); + + // Load 3p.com/script from a nested worker with a new top-frame origin. The + // cache isn't split by top frame origin so the resource is already cached. + EXPECT_TRUE(TestResourceLoadFromDedicatedWorker( + GenURL("c.com", "/title1.html"), + GenURL("c.com", "/embedding_worker.js?c"))); +} + IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, ResourceLoadCompleteFromLocalResource) { ResourceLoadObserver observer(shell());
diff --git a/content/browser/webauth/authenticator_impl.cc b/content/browser/webauth/authenticator_impl.cc index e498f81..435edbb 100644 --- a/content/browser/webauth/authenticator_impl.cc +++ b/content/browser/webauth/authenticator_impl.cc
@@ -645,6 +645,8 @@ // TODO(kpaulhamus): Fetch and add the Channel ID/Token Binding ID public key // used to communicate with the origin. if (OriginIsCryptoTokenExtension(caller_origin_)) { + // Cryptotoken requests should be proxied without UI. + request_delegate_->DisableUI(); // As Cryptotoken validates the origin, accept the relying party id as the // origin from requests originating from Cryptotoken. The origin is provided // in Cryptotoken requests as the relying party name, which should be used @@ -729,6 +731,9 @@ // TODO(kpaulhamus): Fetch and add the Channel ID/Token Binding ID public key // used to communicate with the origin. if (OriginIsCryptoTokenExtension(caller_origin_)) { + // Cryptotoken requests should be proxied without UI. + request_delegate_->DisableUI(); + // As Cryptotoken validates the origin, accept the relying party id as the // origin from requests originating from Cryptotoken. client_data_json_ = SerializeCollectedClientDataToJson( @@ -881,14 +886,9 @@ // Duplicate registration: the new credential would be created on an // authenticator that already contains one of the credentials in // |exclude_credentials|. - DCHECK(request_delegate_); - request_delegate_->DidFailWithInterestingReason( - AuthenticatorRequestClientDelegate::InterestingFailureReason:: - kKeyAlreadyRegistered); - InvokeCallbackAndCleanup( - std::move(make_credential_response_callback_), - blink::mojom::AuthenticatorStatus::CREDENTIAL_EXCLUDED, nullptr, - Focus::kDoCheck); + + HandleBlockingError( + blink::mojom::AuthenticatorStatus::CREDENTIAL_EXCLUDED); return; case device::FidoReturnCode::kAuthenticatorResponseInvalid: // The response from the authenticator was corrupted. @@ -1038,15 +1038,8 @@ switch (status_code) { case device::FidoReturnCode::kUserConsentButCredentialNotRecognized: - // No authenticators contained the credential. - DCHECK(request_delegate_); - request_delegate_->DidFailWithInterestingReason( - AuthenticatorRequestClientDelegate::InterestingFailureReason:: - kKeyNotRegistered); - InvokeCallbackAndCleanup( - std::move(get_assertion_response_callback_), - blink::mojom::AuthenticatorStatus::CREDENTIAL_NOT_RECOGNIZED, - nullptr); + HandleBlockingError( + blink::mojom::AuthenticatorStatus::CREDENTIAL_NOT_RECOGNIZED); return; case device::FidoReturnCode::kAuthenticatorResponseInvalid: // The response from the authenticator was corrupted. @@ -1085,21 +1078,51 @@ NOTREACHED(); } -void AuthenticatorImpl::FailWithNotAllowedErrorAndCleanup() { +// If WebAuthnUi is enabled, this error blocks until after receiving user +// acknowledgement. Otherwise, the error is returned right away. +void AuthenticatorImpl::HandleBlockingError( + blink::mojom::AuthenticatorStatus status) { + AuthenticatorRequestClientDelegate::InterestingFailureReason reason = + AuthenticatorRequestClientDelegate::InterestingFailureReason::kTimeout; + switch (status) { + case blink::mojom::AuthenticatorStatus::CREDENTIAL_EXCLUDED: + reason = AuthenticatorRequestClientDelegate::InterestingFailureReason:: + kKeyAlreadyRegistered; + break; + case blink::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR: + reason = AuthenticatorRequestClientDelegate::InterestingFailureReason:: + kTimeout; + break; + case blink::mojom::AuthenticatorStatus::CREDENTIAL_NOT_RECOGNIZED: + reason = AuthenticatorRequestClientDelegate::InterestingFailureReason:: + kKeyNotRegistered; + break; + default: + NOTREACHED(); + } + + error_awaiting_user_acknowledgement_ = status; + DCHECK(request_delegate_); + if (!request_delegate_->DoesBlockRequestOnFailure(reason)) { + FailWithErrorAndCleanup(); + } +} // namespace content + +void AuthenticatorImpl::FailWithErrorAndCleanup() { DCHECK(make_credential_response_callback_ || get_assertion_response_callback_); if (make_credential_response_callback_) { - InvokeCallbackAndCleanup( - std::move(make_credential_response_callback_), - blink::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR, nullptr, - Focus::kDontCheck); + InvokeCallbackAndCleanup(std::move(make_credential_response_callback_), + error_awaiting_user_acknowledgement_, nullptr, + Focus::kDontCheck); } else if (get_assertion_response_callback_) { - InvokeCallbackAndCleanup( - std::move(get_assertion_response_callback_), - blink::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR, nullptr); + InvokeCallbackAndCleanup(std::move(get_assertion_response_callback_), + error_awaiting_user_acknowledgement_, nullptr); } } +// TODO(crbug.com/814418): Add web tests to verify timeouts are +// indistinguishable from NOT_ALLOWED_ERROR cases. void AuthenticatorImpl::OnTimeout() { DCHECK(request_delegate_); if (awaiting_attestation_response_) { @@ -1108,12 +1131,7 @@ awaiting_attestation_response_ = false; } - request_delegate_->DidFailWithInterestingReason( - AuthenticatorRequestClientDelegate::InterestingFailureReason::kTimeout); - - // TODO(crbug.com/814418): Add web tests to verify timeouts are - // indistinguishable from NOT_ALLOWED_ERROR cases. - FailWithNotAllowedErrorAndCleanup(); + HandleBlockingError(blink::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR); } void AuthenticatorImpl::Cancel() { @@ -1121,7 +1139,7 @@ if (!make_credential_response_callback_ && !get_assertion_response_callback_) return; - FailWithNotAllowedErrorAndCleanup(); + FailWithErrorAndCleanup(); } void AuthenticatorImpl::InvokeCallbackAndCleanup( @@ -1162,6 +1180,8 @@ client_data_json_.clear(); app_id_.reset(); attestation_requested_ = false; + error_awaiting_user_acknowledgement_ = + blink::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR; } BrowserContext* AuthenticatorImpl::browser_context() const {
diff --git a/content/browser/webauth/authenticator_impl.h b/content/browser/webauth/authenticator_impl.h index 85de240c..9f9f0071b 100644 --- a/content/browser/webauth/authenticator_impl.h +++ b/content/browser/webauth/authenticator_impl.h
@@ -149,13 +149,18 @@ base::Optional<device::AuthenticatorGetAssertionResponse> response_data, base::Optional<device::FidoTransportProtocol> transport_used); - void FailWithNotAllowedErrorAndCleanup(); + void FailWithErrorAndCleanup(); // Runs when timer expires and cancels all issued requests to a U2fDevice. void OnTimeout(); // Runs when the user cancels WebAuthN request via UI dialog. void Cancel(); + // Decides whether or not UI is present that needs to block on user + // acknowledgement before returning the error, and handles the error + // appropriately. + void HandleBlockingError(blink::mojom::AuthenticatorStatus status); + void InvokeCallbackAndCleanup( MakeCredentialCallback callback, blink::mojom::AuthenticatorStatus status, @@ -191,6 +196,8 @@ // awaiting_attestation_response_ is true if the embedder has been queried // about an attestsation decision and the response is still pending. bool awaiting_attestation_response_ = false; + blink::mojom::AuthenticatorStatus error_awaiting_user_acknowledgement_ = + blink::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR; // Owns pipes to this Authenticator from |render_frame_host_|. mojo::Binding<blink::mojom::Authenticator> binding_;
diff --git a/content/browser/webauth/authenticator_impl_unittest.cc b/content/browser/webauth/authenticator_impl_unittest.cc index 076ee3f..54cfcb2 100644 --- a/content/browser/webauth/authenticator_impl_unittest.cc +++ b/content/browser/webauth/authenticator_impl_unittest.cc
@@ -1993,9 +1993,10 @@ failure_reasons_callback_(std::move(failure_reasons_callback)) {} ~MockAuthenticatorRequestDelegateObserver() override = default; - void DidFailWithInterestingReason(InterestingFailureReason reason) override { - ASSERT_TRUE(failure_reasons_callback_); + bool DoesBlockRequestOnFailure(InterestingFailureReason reason) override { + CHECK(failure_reasons_callback_); std::move(failure_reasons_callback_).Run(reason); + return false; } MOCK_METHOD1(
diff --git a/content/child/BUILD.gn b/content/child/BUILD.gn index 0383a74..f454ddf 100644 --- a/content/child/BUILD.gn +++ b/content/child/BUILD.gn
@@ -109,7 +109,6 @@ "//services/resource_coordinator/public/cpp/memory_instrumentation", "//services/service_manager/public/cpp", "//services/service_manager/public/mojom", - "//services/service_manager/runner/common", "//services/tracing/public/cpp", "//skia", "//storage/common",
diff --git a/content/child/child_thread_impl.cc b/content/child/child_thread_impl.cc index 24f6325..ef8341c8 100644 --- a/content/child/child_thread_impl.cc +++ b/content/child/child_thread_impl.cc
@@ -70,7 +70,6 @@ #include "services/service_manager/embedder/switches.h" #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/interface_provider.h" -#include "services/service_manager/runner/common/client_util.h" #include "services/service_manager/sandbox/sandbox_type.h" #if defined(OS_POSIX)
diff --git a/content/common/BUILD.gn b/content/common/BUILD.gn index d64927e..f8f5572 100644 --- a/content/common/BUILD.gn +++ b/content/common/BUILD.gn
@@ -209,8 +209,6 @@ "pepper_plugin_list.h", "pepper_renderer_instance_data.cc", "pepper_renderer_instance_data.h", - "plugin_list.cc", - "plugin_list.h", "possibly_associated_interface_ptr.h", "possibly_associated_interface_ptr_info.h", "possibly_associated_wrapper_shared_url_loader_factory.h", @@ -319,7 +317,6 @@ "//services/network/public/mojom", "//services/resource_coordinator/public/cpp/memory_instrumentation", "//services/service_manager/public/mojom", - "//services/service_manager/runner/common", "//services/service_manager/zygote:zygote_buildflags", "//services/video_capture/public/mojom", "//services/viz/public/interfaces", @@ -422,8 +419,6 @@ "pepper_plugin_list.h", "pepper_renderer_instance_data.cc", "pepper_renderer_instance_data.h", - "plugin_list.cc", - "plugin_list.h", ] }
diff --git a/content/common/cursors/webcursor_ozone.cc b/content/common/cursors/webcursor_ozone.cc index 59f880a..c9b9cb1d 100644 --- a/content/common/cursors/webcursor_ozone.cc +++ b/content/common/cursors/webcursor_ozone.cc
@@ -4,6 +4,8 @@ #include "content/common/cursors/webcursor.h" +#include <algorithm> + #include "third_party/blink/public/platform/web_cursor_info.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/cursor_util.h"
diff --git a/content/common/navigation_client.mojom b/content/common/navigation_client.mojom index 9fee08a7..00e6d8b 100644 --- a/content/common/navigation_client.mojom +++ b/content/common/navigation_client.mojom
@@ -82,6 +82,7 @@ int32 error_code, string? error_page_content, blink.mojom.URLLoaderFactoryBundle? subresource_loader_factories) - => (blink.mojom.CommitResult commit_result); + => (DidCommitProvisionalLoadParams params, + DidCommitProvisionalLoadInterfaceParams? interface_params); };
diff --git a/content/common/service_manager/service_manager_connection_impl.cc b/content/common/service_manager/service_manager_connection_impl.cc index 1226556..b4519fae 100644 --- a/content/common/service_manager/service_manager_connection_impl.cc +++ b/content/common/service_manager/service_manager_connection_impl.cc
@@ -27,7 +27,6 @@ #include "services/service_manager/public/cpp/service_binding.h" #include "services/service_manager/public/mojom/constants.mojom.h" #include "services/service_manager/public/mojom/service_factory.mojom.h" -#include "services/service_manager/runner/common/client_util.h" #if defined(OS_ANDROID) #include "base/android/jni_android.h"
diff --git a/content/public/android/BUILD.gn b/content/public/android/BUILD.gn index e13b76bb..12618de 100644 --- a/content/public/android/BUILD.gn +++ b/content/public/android/BUILD.gn
@@ -294,22 +294,24 @@ java_strings_grd("content_strings_grd") { grd_file = "java/strings/android_content_strings.grd" outputs = [ + "values/android_content_strings.xml", "values-am/android_content_strings.xml", "values-ar/android_content_strings.xml", "values-bg/android_content_strings.xml", + "values-bn/android_content_strings.xml", "values-ca/android_content_strings.xml", "values-cs/android_content_strings.xml", "values-da/android_content_strings.xml", "values-de/android_content_strings.xml", "values-el/android_content_strings.xml", - "values/android_content_strings.xml", "values-en-rGB/android_content_strings.xml", "values-es/android_content_strings.xml", "values-es-rUS/android_content_strings.xml", + "values-et/android_content_strings.xml", "values-fa/android_content_strings.xml", "values-fi/android_content_strings.xml", - "values-tl/android_content_strings.xml", "values-fr/android_content_strings.xml", + "values-gu/android_content_strings.xml", "values-hi/android_content_strings.xml", "values-hr/android_content_strings.xml", "values-hu/android_content_strings.xml", @@ -317,11 +319,15 @@ "values-it/android_content_strings.xml", "values-iw/android_content_strings.xml", "values-ja/android_content_strings.xml", + "values-kn/android_content_strings.xml", "values-ko/android_content_strings.xml", "values-lt/android_content_strings.xml", "values-lv/android_content_strings.xml", - "values-nl/android_content_strings.xml", + "values-ml/android_content_strings.xml", + "values-mr/android_content_strings.xml", + "values-ms/android_content_strings.xml", "values-nb/android_content_strings.xml", + "values-nl/android_content_strings.xml", "values-pl/android_content_strings.xml", "values-pt-rBR/android_content_strings.xml", "values-pt-rPT/android_content_strings.xml", @@ -332,7 +338,10 @@ "values-sr/android_content_strings.xml", "values-sv/android_content_strings.xml", "values-sw/android_content_strings.xml", + "values-ta/android_content_strings.xml", + "values-te/android_content_strings.xml", "values-th/android_content_strings.xml", + "values-tl/android_content_strings.xml", "values-tr/android_content_strings.xml", "values-uk/android_content_strings.xml", "values-vi/android_content_strings.xml",
diff --git a/content/public/android/java/strings/android_content_strings.grd b/content/public/android/java/strings/android_content_strings.grd index 33e8def..f5b9b35 100644 --- a/content/public/android/java/strings/android_content_strings.grd +++ b/content/public/android/java/strings/android_content_strings.grd
@@ -4,6 +4,7 @@ <output filename="values-am/android_content_strings.xml" lang="am" type="android" /> <output filename="values-ar/android_content_strings.xml" lang="ar" type="android" /> <output filename="values-bg/android_content_strings.xml" lang="bg" type="android" /> + <output filename="values-bn/android_content_strings.xml" lang="bn" type="android" /> <output filename="values-ca/android_content_strings.xml" lang="ca" type="android" /> <output filename="values-cs/android_content_strings.xml" lang="cs" type="android" /> <output filename="values-da/android_content_strings.xml" lang="da" type="android" /> @@ -13,10 +14,12 @@ <output filename="values-en-rGB/android_content_strings.xml" lang="en-GB" type="android" /> <output filename="values-es/android_content_strings.xml" lang="es" type="android" /> <output filename="values-es-rUS/android_content_strings.xml" lang="es-419" type="android" /> + <output filename="values-et/android_content_strings.xml" lang="et" type="android" /> <output filename="values-fa/android_content_strings.xml" lang="fa" type="android" /> <output filename="values-fi/android_content_strings.xml" lang="fi" type="android" /> <output filename="values-tl/android_content_strings.xml" lang="fil" type="android" /> <output filename="values-fr/android_content_strings.xml" lang="fr" type="android" /> + <output filename="values-gu/android_content_strings.xml" lang="gu" type="android" /> <output filename="values-hi/android_content_strings.xml" lang="hi" type="android" /> <output filename="values-hr/android_content_strings.xml" lang="hr" type="android" /> <output filename="values-hu/android_content_strings.xml" lang="hu" type="android" /> @@ -24,9 +27,13 @@ <output filename="values-it/android_content_strings.xml" lang="it" type="android" /> <output filename="values-iw/android_content_strings.xml" lang="iw" type="android" /> <output filename="values-ja/android_content_strings.xml" lang="ja" type="android" /> + <output filename="values-kn/android_content_strings.xml" lang="kn" type="android" /> <output filename="values-ko/android_content_strings.xml" lang="ko" type="android" /> <output filename="values-lt/android_content_strings.xml" lang="lt" type="android" /> <output filename="values-lv/android_content_strings.xml" lang="lv" type="android" /> + <output filename="values-ml/android_content_strings.xml" lang="ml" type="android" /> + <output filename="values-mr/android_content_strings.xml" lang="mr" type="android" /> + <output filename="values-ms/android_content_strings.xml" lang="ms" type="android" /> <output filename="values-nl/android_content_strings.xml" lang="nl" type="android" /> <output filename="values-nb/android_content_strings.xml" lang="no" type="android" /> <output filename="values-pl/android_content_strings.xml" lang="pl" type="android" /> @@ -39,6 +46,8 @@ <output filename="values-sr/android_content_strings.xml" lang="sr" type="android" /> <output filename="values-sv/android_content_strings.xml" lang="sv" type="android" /> <output filename="values-sw/android_content_strings.xml" lang="sw" type="android" /> + <output filename="values-ta/android_content_strings.xml" lang="ta" type="android" /> + <output filename="values-te/android_content_strings.xml" lang="te" type="android" /> <output filename="values-th/android_content_strings.xml" lang="th" type="android" /> <output filename="values-tr/android_content_strings.xml" lang="tr" type="android" /> <output filename="values-uk/android_content_strings.xml" lang="uk" type="android" />
diff --git a/content/public/app/content_browser_manifest.cc b/content/public/app/content_browser_manifest.cc index 0e9aca4..8960cf9 100644 --- a/content/public/app/content_browser_manifest.cc +++ b/content/public/app/content_browser_manifest.cc
@@ -125,11 +125,7 @@ .RequireCapability("media", "media:media") .RequireCapability("*", "app") .RequireCapability("content", "navigation") - .RequireCapability("resource_coordinator", "coordination_unit") - .RequireCapability("resource_coordinator", - "coordination_unit_introspector") .RequireCapability("resource_coordinator", "service_callbacks") - .RequireCapability("resource_coordinator", "page_signal") .RequireCapability("service_manager", "service_manager:service_manager") .RequireCapability("chromecast", "multizone")
diff --git a/content/public/browser/authenticator_request_client_delegate.cc b/content/public/browser/authenticator_request_client_delegate.cc index 94b259c..dffc975a 100644 --- a/content/public/browser/authenticator_request_client_delegate.cc +++ b/content/public/browser/authenticator_request_client_delegate.cc
@@ -16,8 +16,10 @@ AuthenticatorRequestClientDelegate::~AuthenticatorRequestClientDelegate() = default; -void AuthenticatorRequestClientDelegate::DidFailWithInterestingReason( - InterestingFailureReason reason) {} +bool AuthenticatorRequestClientDelegate::DoesBlockRequestOnFailure( + InterestingFailureReason reason) { + return false; +} void AuthenticatorRequestClientDelegate::RegisterActionCallbacks( base::OnceClosure cancel_callback, @@ -50,6 +52,12 @@ void AuthenticatorRequestClientDelegate::UpdateLastTransportUsed( device::FidoTransportProtocol transport) {} +void AuthenticatorRequestClientDelegate::DisableUI() {} + +bool AuthenticatorRequestClientDelegate::IsWebAuthnUIEnabled() { + return false; +} + void AuthenticatorRequestClientDelegate::OnTransportAvailabilityEnumerated( device::FidoRequestHandlerBase::TransportAvailabilityInfo data) {}
diff --git a/content/public/browser/authenticator_request_client_delegate.h b/content/public/browser/authenticator_request_client_delegate.h index 6b2e4d0..94f2a17e 100644 --- a/content/public/browser/authenticator_request_client_delegate.h +++ b/content/public/browser/authenticator_request_client_delegate.h
@@ -44,9 +44,14 @@ AuthenticatorRequestClientDelegate(); ~AuthenticatorRequestClientDelegate() override; - // Called when the request fails for the given |reason|, just before this - // delegate is destroyed. - virtual void DidFailWithInterestingReason(InterestingFailureReason reason); + // Called when the request fails for the given |reason|. Embedders may return + // true if they want AuthenticatorImpl to hold off from resolving the WebAuthn + // request with an error, e.g. because they want the user to dismiss an error + // dialog first. In this case, embedders *must* eventually invoke the + // FidoRequestHandlerBase::CancelCallback in order to resolve the request. + // Returning false causes AuthenticatorImpl to resolve the request with the + // error right away. + virtual bool DoesBlockRequestOnFailure(InterestingFailureReason reason); // Supplies callbacks that the embedder can invoke to initiate certain // actions, namely: initiate BLE pairing process, cancel WebAuthN request, and @@ -98,6 +103,12 @@ // WebAuthN UI will default to the same transport type during next API call. virtual void UpdateLastTransportUsed(device::FidoTransportProtocol transport); + // Disables the UI (needed in cases when called by other components, like + // cryptotoken). + virtual void DisableUI(); + + virtual bool IsWebAuthnUIEnabled(); + // device::FidoRequestHandlerBase::TransportAvailabilityObserver: void OnTransportAvailabilityEnumerated( device::FidoRequestHandlerBase::TransportAvailabilityInfo data) override;
diff --git a/content/public/browser/content_browser_client.cc b/content/public/browser/content_browser_client.cc index 7f1cf2d..efbc337 100644 --- a/content/public/browser/content_browser_client.cc +++ b/content/public/browser/content_browser_client.cc
@@ -804,9 +804,11 @@ RenderFrameHost* render_frame_host, mojo::InterfaceRequest<blink::mojom::WebUsbService> request) {} +#if !defined(OS_ANDROID) SerialDelegate* ContentBrowserClient::GetSerialDelegate() { return nullptr; } +#endif bool ContentBrowserClient::ShowPaymentHandlerWindow( content::BrowserContext* browser_context,
diff --git a/content/public/browser/content_browser_client.h b/content/public/browser/content_browser_client.h index c8d15dbf..fbac51d 100644 --- a/content/public/browser/content_browser_client.h +++ b/content/public/browser/content_browser_client.h
@@ -1293,8 +1293,10 @@ RenderFrameHost* render_frame_host, mojo::InterfaceRequest<blink::mojom::WebUsbService> request); +#if !defined(OS_ANDROID) // Allows the embedder to provide an implementation of the Serial API. virtual SerialDelegate* GetSerialDelegate(); +#endif // Attempt to open the Payment Handler window inside its corresponding // PaymentRequest UI surface. Returns true if the ContentBrowserClient
diff --git a/content/public/common/common_param_traits_macros.h b/content/public/common/common_param_traits_macros.h index f2625e0..26a0504 100644 --- a/content/public/common/common_param_traits_macros.h +++ b/content/public/common/common_param_traits_macros.h
@@ -230,6 +230,7 @@ IPC_STRUCT_TRAITS_MEMBER(css_hex_alpha_color_enabled) IPC_STRUCT_TRAITS_MEMBER(enable_media_download_in_product_help) IPC_STRUCT_TRAITS_MEMBER(scroll_top_left_interop_enabled) + IPC_STRUCT_TRAITS_MEMBER(force_dark_mode_enabled) #endif // defined(OS_ANDROID) IPC_STRUCT_TRAITS_MEMBER(default_minimum_page_scale_factor) IPC_STRUCT_TRAITS_MEMBER(default_maximum_page_scale_factor)
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index 070e3e6..51dc6571 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -171,6 +171,9 @@ "FramebustingNeedsSameOriginOrUserGesture", base::FEATURE_ENABLED_BY_DEFAULT}; +const base::Feature kFreezePurgeMemoryBackgroundedOnly{ + "FreezePurgeMemoryBackgroundedOnly", base::FEATURE_DISABLED_BY_DEFAULT}; + // Enables haptic vibration effects on supported gamepads. const base::Feature kGamepadVibration{"GamepadVibration", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index b4e0453..3fd33e0 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -49,6 +49,7 @@ CONTENT_EXPORT extern const base::Feature kFontSrcLocalMatching; CONTENT_EXPORT extern const base::Feature kFramebustingNeedsSameOriginOrUserGesture; +CONTENT_EXPORT extern const base::Feature kFreezePurgeMemoryBackgroundedOnly; CONTENT_EXPORT extern const base::Feature kGamepadVibration; CONTENT_EXPORT extern const base::Feature kGuestViewCrossProcessFrames; CONTENT_EXPORT extern const base::Feature kHeapCompaction;
diff --git a/content/public/common/web_preferences.h b/content/public/common/web_preferences.h index 231b5f3..798b963 100644 --- a/content/public/common/web_preferences.h +++ b/content/public/common/web_preferences.h
@@ -260,6 +260,9 @@ // WebView sets this to false to retain old documentElement behaviour // (http://crbug.com/761016). bool scroll_top_left_interop_enabled; + // Enable forcibly modifying content rendering to result in a light on dark + // colour scheme. + bool force_dark_mode_enabled = false; #else // defined(OS_ANDROID) #endif // defined(OS_ANDROID)
diff --git a/content/renderer/BUILD.gn b/content/renderer/BUILD.gn index 66b68ae..9704049 100644 --- a/content/renderer/BUILD.gn +++ b/content/renderer/BUILD.gn
@@ -755,6 +755,7 @@ # Add back the Linux file which Android shares. set_sources_assignment_filter([]) sources += [ "render_view_linux.cc" ] + set_sources_assignment_filter(sources_assignment_filter) deps += [ "//third_party/android_tools:cpu_features",
diff --git a/content/renderer/compositor/layer_tree_view.cc b/content/renderer/compositor/layer_tree_view.cc index 86cca0a..319ff2f 100644 --- a/content/renderer/compositor/layer_tree_view.cc +++ b/content/renderer/compositor/layer_tree_view.cc
@@ -210,15 +210,7 @@ } } -void LayerTreeView::SetNeverVisible() { - DCHECK(!layer_tree_host_->IsVisible()); - never_visible_ = true; -} - void LayerTreeView::SetVisible(bool visible) { - if (never_visible_) - return; - layer_tree_host_->SetVisible(visible); if (visible && layer_tree_frame_sink_request_failed_while_invisible_)
diff --git a/content/renderer/compositor/layer_tree_view.h b/content/renderer/compositor/layer_tree_view.h index aa54b853..19eb62b 100644 --- a/content/renderer/compositor/layer_tree_view.h +++ b/content/renderer/compositor/layer_tree_view.h
@@ -74,7 +74,6 @@ void Initialize(const cc::LayerTreeSettings& settings, std::unique_ptr<cc::UkmRecorderFactory> ukm_recorder_factory); - void SetNeverVisible(); void SetVisible(bool visible); const base::WeakPtr<cc::InputHandler>& GetInputHandler(); void SetNeedsDisplayOnAllLayers(); @@ -256,7 +255,6 @@ blink::scheduler::WebThreadScheduler* const web_main_thread_scheduler_; const std::unique_ptr<cc::AnimationHost> animation_host_; std::unique_ptr<cc::LayerTreeHost> layer_tree_host_; - bool never_visible_ = false; bool layer_tree_frame_sink_request_failed_while_invisible_ = false;
diff --git a/content/renderer/dom_storage/local_storage_cached_area.cc b/content/renderer/dom_storage/local_storage_cached_area.cc index c04e0e8..1b406b32 100644 --- a/content/renderer/dom_storage/local_storage_cached_area.cc +++ b/content/renderer/dom_storage/local_storage_cached_area.cc
@@ -109,7 +109,7 @@ DCHECK(namespace_id_.empty()); blink::mojom::StorageAreaPtrInfo wrapper_ptr_info; storage_partition_service->OpenLocalStorage( - origin_, mojo::MakeRequest(&wrapper_ptr_info)); + origin_, mojo::MakeRequest(&wrapper_ptr_info), base::DoNothing()); leveldb_.Bind(std::move(wrapper_ptr_info), main_thread_scheduler->IPCTaskRunner()); blink::mojom::StorageAreaObserverAssociatedPtrInfo ptr_info;
diff --git a/content/renderer/dom_storage/local_storage_cached_areas.cc b/content/renderer/dom_storage/local_storage_cached_areas.cc index 32dc5d9..79e455e3 100644 --- a/content/renderer/dom_storage/local_storage_cached_areas.cc +++ b/content/renderer/dom_storage/local_storage_cached_areas.cc
@@ -70,7 +70,8 @@ .first; storage_partition_service_->OpenSessionStorage( source_namespace, - mojo::MakeRequest(&namespace_it->second.session_storage_namespace)); + mojo::MakeRequest(&namespace_it->second.session_storage_namespace), + base::DoNothing()); } DCHECK(namespace_it->second.session_storage_namespace); namespace_it->second.session_storage_namespace->Clone(destination_namespace); @@ -147,7 +148,8 @@ if (!dom_namespace->session_storage_namespace) { storage_partition_service_->OpenSessionStorage( namespace_id, - mojo::MakeRequest(&dom_namespace->session_storage_namespace)); + mojo::MakeRequest(&dom_namespace->session_storage_namespace), + base::DoNothing()); } result = base::MakeRefCounted<LocalStorageCachedArea>( namespace_id, origin, dom_namespace->session_storage_namespace.get(),
diff --git a/content/renderer/dom_storage/mock_leveldb_wrapper.cc b/content/renderer/dom_storage/mock_leveldb_wrapper.cc index 4f7dead..03817120 100644 --- a/content/renderer/dom_storage/mock_leveldb_wrapper.cc +++ b/content/renderer/dom_storage/mock_leveldb_wrapper.cc
@@ -41,16 +41,20 @@ void MockLevelDBWrapper::OpenLocalStorage( const url::Origin& origin, - blink::mojom::StorageAreaRequest database) { + blink::mojom::StorageAreaRequest database, + OpenLocalStorageCallback done) { bindings_.AddBinding(this, std::move(database)); + std::move(done).Run(); } void MockLevelDBWrapper::OpenSessionStorage( const std::string& namespace_id, - blink::mojom::SessionStorageNamespaceRequest request) { + blink::mojom::SessionStorageNamespaceRequest request, + OpenSessionStorageCallback done) { namespace_bindings_.AddBinding( std::make_unique<MockSessionStorageNamespace>(namespace_id, this), std::move(request)); + std::move(done).Run(); } void MockLevelDBWrapper::AddObserver(
diff --git a/content/renderer/dom_storage/mock_leveldb_wrapper.h b/content/renderer/dom_storage/mock_leveldb_wrapper.h index 2a2d4103..32df0552 100644 --- a/content/renderer/dom_storage/mock_leveldb_wrapper.h +++ b/content/renderer/dom_storage/mock_leveldb_wrapper.h
@@ -26,10 +26,11 @@ // StoragePartitionService implementation: void OpenLocalStorage(const url::Origin& origin, - blink::mojom::StorageAreaRequest database) override; - void OpenSessionStorage( - const std::string& namespace_id, - blink::mojom::SessionStorageNamespaceRequest request) override; + blink::mojom::StorageAreaRequest database, + OpenLocalStorageCallback done) override; + void OpenSessionStorage(const std::string& namespace_id, + blink::mojom::SessionStorageNamespaceRequest request, + OpenSessionStorageCallback done) override; // StorageArea implementation: void AddObserver(
diff --git a/content/renderer/loader/web_worker_fetch_context_impl.cc b/content/renderer/loader/web_worker_fetch_context_impl.cc index bd2ef04..79c6c3efb 100644 --- a/content/renderer/loader/web_worker_fetch_context_impl.cc +++ b/content/renderer/loader/web_worker_fetch_context_impl.cc
@@ -287,6 +287,7 @@ new_context->ancestor_frame_id_ = ancestor_frame_id_; new_context->frame_request_blocker_ = frame_request_blocker_; new_context->appcache_host_id_ = appcache_host_id_; + new_context->top_frame_origin_ = top_frame_origin_; child_preference_watchers_.AddPtr(std::move(preference_watcher)); @@ -414,6 +415,14 @@ return site_for_cookies_; } +base::Optional<blink::WebSecurityOrigin> +WebWorkerFetchContextImpl::TopFrameOrigin() const { + // TODO(jkarlin): set_top_frame_origin is only called for dedicated workers. + // Determine the top-frame-origin of a shared worker as well. See + // https://crbug.com/918868. + return top_frame_origin_; +} + void WebWorkerFetchContextImpl::DidRunContentWithCertificateErrors() { Send(new FrameHostMsg_DidRunContentWithCertificateErrors(ancestor_frame_id_)); } @@ -475,6 +484,11 @@ site_for_cookies_ = site_for_cookies; } +void WebWorkerFetchContextImpl::set_top_frame_origin( + const blink::WebSecurityOrigin& top_frame_origin) { + top_frame_origin_ = top_frame_origin; +} + void WebWorkerFetchContextImpl::set_is_secure_context(bool flag) { is_secure_context_ = flag; }
diff --git a/content/renderer/loader/web_worker_fetch_context_impl.h b/content/renderer/loader/web_worker_fetch_context_impl.h index 1aa4704b..7bebcc5 100644 --- a/content/renderer/loader/web_worker_fetch_context_impl.h +++ b/content/renderer/loader/web_worker_fetch_context_impl.h
@@ -92,6 +92,7 @@ void SetIsOnSubframe(bool) override; bool IsOnSubframe() const override; blink::WebURL SiteForCookies() const override; + base::Optional<blink::WebSecurityOrigin> TopFrameOrigin() const override; void DidRunContentWithCertificateErrors() override; void DidDisplayContentWithCertificateErrors() override; void DidRunInsecureContent(const blink::WebSecurityOrigin&, @@ -119,6 +120,7 @@ void set_frame_request_blocker( scoped_refptr<FrameRequestBlocker> frame_request_blocker); void set_site_for_cookies(const blink::WebURL& site_for_cookies); + void set_top_frame_origin(const blink::WebSecurityOrigin& top_frame_origin); // Sets whether the worker context is a secure context. // https://w3c.github.io/webappsec-secure-contexts/ void set_is_secure_context(bool flag); @@ -242,6 +244,7 @@ // blocked. scoped_refptr<FrameRequestBlocker> frame_request_blocker_; GURL site_for_cookies_; + base::Optional<url::Origin> top_frame_origin_; bool is_secure_context_ = false; GURL origin_url_; int appcache_host_id_ = blink::mojom::kAppCacheNoHostId;
diff --git a/content/renderer/media/webrtc/rtc_peer_connection_handler.cc b/content/renderer/media/webrtc/rtc_peer_connection_handler.cc index ec41e007..5369328 100644 --- a/content/renderer/media/webrtc/rtc_peer_connection_handler.cc +++ b/content/renderer/media/webrtc/rtc_peer_connection_handler.cc
@@ -57,6 +57,7 @@ #include "third_party/blink/public/platform/web_url.h" #include "third_party/webrtc/api/rtc_event_log_output.h" #include "third_party/webrtc/pc/media_session.h" +#include "third_party/webrtc/pc/session_description.h" using webrtc::DataChannelInterface; using webrtc::IceCandidateInterface; @@ -2234,7 +2235,7 @@ DCHECK(sdesc); for (const auto& content : sdesc->description()->contents()) { - if (content.type == cricket::NS_JINGLE_RTP) { + if (content.type == cricket::MediaProtocolType::kRtp) { const auto* mdesc = static_cast<cricket::MediaContentDescription*>(content.description); audio = audio || (mdesc->type() == cricket::MEDIA_TYPE_AUDIO);
diff --git a/content/renderer/navigation_client.cc b/content/renderer/navigation_client.cc index 2f14b11..c17226b2 100644 --- a/content/renderer/navigation_client.cc +++ b/content/renderer/navigation_client.cc
@@ -50,7 +50,7 @@ std::unique_ptr<blink::URLLoaderFactoryBundleInfo> subresource_loaders, CommitFailedNavigationCallback callback) { ResetDisconnectionHandler(); - render_frame_->CommitFailedNavigation( + render_frame_->CommitFailedPerNavigationMojoInterfaceNavigation( common_params, commit_params, has_stale_copy_in_cache, error_code, error_page_content, std::move(subresource_loaders), std::move(callback)); }
diff --git a/content/renderer/pepper/pepper_plugin_instance_impl.cc b/content/renderer/pepper/pepper_plugin_instance_impl.cc index 19afe96..37d751c 100644 --- a/content/renderer/pepper/pepper_plugin_instance_impl.cc +++ b/content/renderer/pepper/pepper_plugin_instance_impl.cc
@@ -136,7 +136,6 @@ // nogncheck because dependency on //printing is conditional upon // enable_basic_printing flags. #include "printing/metafile_skia.h" // nogncheck -#include "printing/metafile_skia_wrapper.h" // nogncheck #endif #if defined(OS_CHROMEOS) @@ -1996,8 +1995,7 @@ DCHECK(plugin_print_interface_); // |canvas| should always have an associated metafile. - printing::MetafileSkia* metafile = - printing::MetafileSkiaWrapper::GetMetafileFromCanvas(canvas); + auto* metafile = canvas->GetPrintingMetafile(); DCHECK(metafile); // |ranges_| should be empty IFF |metafile_| is not set.
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index e72285f4..b2cec490 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -3429,7 +3429,46 @@ const base::Optional<std::string>& error_page_content, std::unique_ptr<blink::URLLoaderFactoryBundleInfo> subresource_loader_factories, - CommitFailedNavigationCallback callback) { + mojom::FrameNavigationControl::CommitFailedNavigationCallback callback) { + DCHECK(!navigation_client_impl_); + DCHECK(!IsPerNavigationMojoInterfaceEnabled()); + CommitFailedNavigationInternal( + common_params, commit_params, has_stale_copy_in_cache, error_code, + error_page_content, std::move(subresource_loader_factories), + std::move(callback), + mojom::NavigationClient::CommitFailedNavigationCallback()); +} + +void RenderFrameImpl::CommitFailedPerNavigationMojoInterfaceNavigation( + const CommonNavigationParams& common_params, + const CommitNavigationParams& commit_params, + bool has_stale_copy_in_cache, + int error_code, + const base::Optional<std::string>& error_page_content, + std::unique_ptr<blink::URLLoaderFactoryBundleInfo> + subresource_loader_factories, + mojom::NavigationClient::CommitFailedNavigationCallback + per_navigation_mojo_interface_callback) { + DCHECK(navigation_client_impl_); + DCHECK(IsPerNavigationMojoInterfaceEnabled()); + CommitFailedNavigationInternal( + common_params, commit_params, has_stale_copy_in_cache, error_code, + error_page_content, std::move(subresource_loader_factories), + mojom::FrameNavigationControl::CommitFailedNavigationCallback(), + std::move(per_navigation_mojo_interface_callback)); +} + +void RenderFrameImpl::CommitFailedNavigationInternal( + const CommonNavigationParams& common_params, + const CommitNavigationParams& commit_params, + bool has_stale_copy_in_cache, + int error_code, + const base::Optional<std::string>& error_page_content, + std::unique_ptr<blink::URLLoaderFactoryBundleInfo> + subresource_loader_factories, + mojom::FrameNavigationControl::CommitFailedNavigationCallback callback, + mojom::NavigationClient::CommitFailedNavigationCallback + per_navigation_mojo_interface_callback) { TRACE_EVENT1("navigation,benchmark,rail", "RenderFrameImpl::CommitFailedNavigation", "id", routing_id_); DCHECK( @@ -3551,7 +3590,7 @@ std::unique_ptr<DocumentState> document_state = BuildDocumentStateFromParams( common_params, commit_params, base::TimeTicks(), std::move(callback), - mojom::NavigationClient::CommitNavigationCallback(), nullptr, + std::move(per_navigation_mojo_interface_callback), nullptr, std::move(navigation_client_impl_)); // The load of the error page can result in this frame being removed. @@ -3814,6 +3853,8 @@ worker_fetch_context->set_frame_request_blocker(frame_request_blocker_); worker_fetch_context->set_site_for_cookies( frame_->GetDocument().SiteForCookies()); + worker_fetch_context->set_top_frame_origin( + frame_->GetDocument().TopFrameOrigin()); worker_fetch_context->set_is_secure_context( frame_->GetDocument().IsSecureContext()); worker_fetch_context->set_origin_url(
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index 6eb48a4..d26a27ca 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -601,6 +601,21 @@ std::unique_ptr<blink::URLLoaderFactoryBundleInfo> subresource_loader_factories, CommitFailedNavigationCallback callback) override; + + // This is the version to be used with PerNavigationMojoInterface enabled. + // It essentially works the same way, except the navigation callback is + // the one from NavigationClient mojo interface. + void CommitFailedPerNavigationMojoInterfaceNavigation( + const CommonNavigationParams& common_params, + const CommitNavigationParams& commit_params, + bool has_stale_copy_in_cache, + int error_code, + const base::Optional<std::string>& error_page_content, + std::unique_ptr<blink::URLLoaderFactoryBundleInfo> + subresource_loader_factories, + mojom::NavigationClient::CommitFailedNavigationCallback + per_navigation_mojo_interface_callback); + void CommitSameDocumentNavigation( const CommonNavigationParams& common_params, const CommitNavigationParams& commit_params, @@ -1349,8 +1364,8 @@ blink::mojom::ControllerServiceWorkerInfoPtr controller_service_worker_info); - // This function avoid duplication between CommitNavigation and - // CommitPerNavigationMojoInterfaceNavigation. + // These functions avoid duplication between Commit*Navigation and + // Commit*PerNavigationMojoInterfaceNavigation functions. void CommitNavigationInternal( const network::ResourceResponseHead& head, const CommonNavigationParams& common_params, @@ -1368,6 +1383,18 @@ mojom::NavigationClient::CommitNavigationCallback per_navigation_mojo_interface_callback); + void CommitFailedNavigationInternal( + const CommonNavigationParams& common_params, + const CommitNavigationParams& commit_params, + bool has_stale_copy_in_cache, + int error_code, + const base::Optional<std::string>& error_page_content, + std::unique_ptr<blink::URLLoaderFactoryBundleInfo> + subresource_loader_factories, + mojom::FrameNavigationControl::CommitFailedNavigationCallback callback, + mojom::NavigationClient::CommitFailedNavigationCallback + per_navigation_mojo_interface_callback); + // Stores the WebLocalFrame we are associated with. This is null from the // constructor until BindToFrame() is called, and it is null after // FrameDetached() is called until destruction (which is asynchronous in the
diff --git a/content/renderer/render_frame_proxy.cc b/content/renderer/render_frame_proxy.cc index b2eef59..cc497b9 100644 --- a/content/renderer/render_frame_proxy.cc +++ b/content/renderer/render_frame_proxy.cc
@@ -57,7 +57,6 @@ // nogncheck because dependency on //printing is conditional upon // enable_basic_printing flags. #include "printing/metafile_skia.h" // nogncheck -#include "printing/metafile_skia_wrapper.h" // nogncheck #endif namespace content { @@ -942,8 +941,7 @@ uint32_t RenderFrameProxy::Print(const blink::WebRect& rect, cc::PaintCanvas* canvas) { #if BUILDFLAG(ENABLE_PRINTING) - printing::MetafileSkia* metafile = - printing::MetafileSkiaWrapper::GetMetafileFromCanvas(canvas); + auto* metafile = canvas->GetPrintingMetafile(); DCHECK(metafile); // Create a place holder content for the remote frame so it can be replaced
diff --git a/content/renderer/render_process_impl.cc b/content/renderer/render_process_impl.cc index f71fc7c..2a63b828 100644 --- a/content/renderer/render_process_impl.cc +++ b/content/renderer/render_process_impl.cc
@@ -64,18 +64,24 @@ std::unique_ptr<base::TaskScheduler::InitParams> GetDefaultTaskSchedulerInitParams() { - constexpr int kMaxNumThreadsInBackgroundPool = 2; - constexpr int kMaxNumThreadsInForegroundPoolLowerBound = 3; + constexpr int kMaxNumThreadsInBackgroundPool = 1; + constexpr int kMaxNumThreadsInBackgroundBlockingPool = 1; + constexpr int kMaxNumThreadsInForegroundPoolLowerBound = 2; + constexpr int kMaxNumThreadsInForegroundBlockingPool = 1; constexpr auto kSuggestedReclaimTime = base::TimeDelta::FromSeconds(30); return std::make_unique<base::TaskScheduler::InitParams>( base::SchedulerWorkerPoolParams(kMaxNumThreadsInBackgroundPool, kSuggestedReclaimTime), + base::SchedulerWorkerPoolParams(kMaxNumThreadsInBackgroundBlockingPool, + kSuggestedReclaimTime), base::SchedulerWorkerPoolParams( std::max( kMaxNumThreadsInForegroundPoolLowerBound, content::GetMinThreadsInRendererTaskSchedulerForegroundPool()), - kSuggestedReclaimTime)); + kSuggestedReclaimTime), + base::SchedulerWorkerPoolParams(kMaxNumThreadsInForegroundBlockingPool, + kSuggestedReclaimTime)); } #if defined(DCHECK_IS_CONFIGURABLE)
diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc index cd2ae0fe..f97fc06 100644 --- a/content/renderer/render_thread_impl.cc +++ b/content/renderer/render_thread_impl.cc
@@ -146,6 +146,7 @@ #include "services/ws/public/cpp/gpu/gpu.h" #include "services/ws/public/mojom/constants.mojom.h" #include "skia/ext/skia_memory_dump_provider.h" +#include "third_party/blink/public/common/page/launching_process_state.h" #include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h" #include "third_party/blink/public/platform/web_cache.h" #include "third_party/blink/public/platform/web_image_generator.h" @@ -753,6 +754,8 @@ auto registry = std::make_unique<service_manager::BinderRegistry>(); InitializeWebKit(registry.get()); + is_backgrounded_ = blink::kLaunchingProcessIsBackgrounded; + // In single process the single process is all there is. widget_count_ = 0; hidden_widget_count_ = 0; @@ -1673,6 +1676,7 @@ } else { process_foregrounded_count_++; } + is_backgrounded_ = backgrounded; } void RenderThreadImpl::ProcessPurgeAndSuspend() { @@ -1724,6 +1728,16 @@ low_memory_mode_controller_.reset(new LowMemoryModeController()); } +void RenderThreadImpl::RequestPurgeMemory() { + if (base::FeatureList::IsEnabled( + features::kFreezePurgeMemoryBackgroundedOnly) && + !is_backgrounded_) + return; + base::MemoryPressureListener::NotifyMemoryPressure( + base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL); + base::MemoryPressureListener::SetNotificationsSuppressed(true); +} + bool RenderThreadImpl::GetRendererMemoryMetrics( RendererMemoryMetrics* memory_metrics) const { DCHECK(memory_metrics);
diff --git a/content/renderer/render_thread_impl.h b/content/renderer/render_thread_impl.h index 8eaa1d61..b294fac3 100644 --- a/content/renderer/render_thread_impl.h +++ b/content/renderer/render_thread_impl.h
@@ -477,6 +477,8 @@ blink::mojom::StoragePartitionService* GetStoragePartitionService(); mojom::RendererHost* GetRendererHost(); + void RequestPurgeMemory(); + struct RendererMemoryMetrics { size_t partition_alloc_kb; size_t blink_gc_kb; @@ -623,6 +625,9 @@ // Used on the render thread. std::unique_ptr<VideoCaptureImplManager> vc_manager_; + // Used to keep track of the renderer's backgrounded state. + bool is_backgrounded_; + // The count of RenderWidgets running through this thread. int widget_count_;
diff --git a/content/renderer/render_thread_impl_browsertest.cc b/content/renderer/render_thread_impl_browsertest.cc index 4a1f3a1..01900800 100644 --- a/content/renderer/render_thread_impl_browsertest.cc +++ b/content/renderer/render_thread_impl_browsertest.cc
@@ -17,6 +17,7 @@ #include "base/location.h" #include "base/macros.h" #include "base/memory/discardable_memory.h" +#include "base/memory/memory_pressure_listener.h" #include "base/metrics/field_trial.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" @@ -56,6 +57,7 @@ #include "mojo/core/embedder/scoped_ipc_support.h" #include "mojo/public/cpp/system/invitation.h" #include "services/service_manager/public/cpp/constants.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" #include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h" @@ -237,6 +239,28 @@ protected: IPC::Sender* sender() { return channel_.get(); } + void SetProcessBackgrounded(bool backgrounded) { + mojom::Renderer* renderer_interface = thread_; + renderer_interface->SetProcessBackgrounded(backgrounded); + } + + void RegisterMemoryPressureListener() { + memory_pressure_listener_ = std::make_unique<base::MemoryPressureListener>( + base::BindRepeating(&RenderThreadImplBrowserTest::OnMemoryPressure, + base::Unretained(this))); + } + + void ExpectMemoryPressure( + base::MemoryPressureListener::MemoryPressureLevel level) { + EXPECT_CALL(*this, OnMemoryPressure(level)).Times(1); + run_loop_->RunUntilIdle(); + } + + void ExpectNoMemoryPressure() { + EXPECT_CALL(*this, OnMemoryPressure(testing::_)).Times(0); + run_loop_->RunUntilIdle(); + } + scoped_refptr<TestTaskCounter> test_task_counter_; TestContentClientInitializer content_client_initializer_; std::unique_ptr<ContentRendererClient> content_renderer_client_; @@ -257,9 +281,13 @@ base::FieldTrialList field_trial_list_; + std::unique_ptr<base::MemoryPressureListener> memory_pressure_listener_; + std::unique_ptr<base::RunLoop> run_loop_; private: + MOCK_METHOD1(OnMemoryPressure, + void(base::MemoryPressureListener::MemoryPressureLevel)); DISALLOW_COPY_AND_ASSIGN(RenderThreadImplBrowserTest); }; @@ -290,6 +318,79 @@ EXPECT_EQ(0, test_task_counter_->NumTasksPosted()); } +// Verify that RequestPurgeMemory() triggers a memory pressure notification +// in a backgrounded renderer when the kFreezePurgeMemoryBackgroundedOnly +// feature is disabled. +TEST_F(RenderThreadImplBrowserTest, RequestMemoryPurgeBackgrounded) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures( + {} /* enabled */, + {features::kFreezePurgeMemoryBackgroundedOnly} /* disabled */); + + RegisterMemoryPressureListener(); + + SetProcessBackgrounded(true); + RenderThreadImpl::current()->RequestPurgeMemory(); + ExpectMemoryPressure(base::MemoryPressureListener::MemoryPressureLevel:: + MEMORY_PRESSURE_LEVEL_CRITICAL); + EXPECT_TRUE(base::MemoryPressureListener::AreNotificationsSuppressed()); +} + +// Verify that RequestPurgeMemory() triggers a memory pressure notification +// in a foregrounded renderer when the kFreezePurgeMemoryBackgroundedOnly +// feature is disabled. +TEST_F(RenderThreadImplBrowserTest, RequestMemoryPurgeForegrounded) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures( + {} /* enabled */, + {features::kFreezePurgeMemoryBackgroundedOnly} /* disabled */); + + RegisterMemoryPressureListener(); + + SetProcessBackgrounded(false); + RenderThreadImpl::current()->RequestPurgeMemory(); + ExpectMemoryPressure(base::MemoryPressureListener::MemoryPressureLevel:: + MEMORY_PRESSURE_LEVEL_CRITICAL); + EXPECT_TRUE(base::MemoryPressureListener::AreNotificationsSuppressed()); +} + +// Verify that RequestPurgeMemory() triggers a memory pressure notification +// in a backgrounded renderer when the kFreezePurgeMemoryBackgroundedOnly +// feature is enabled. +TEST_F(RenderThreadImplBrowserTest, + RequestMemoryPurgeBackgroundedPreventForegroundedRenderer) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures( + {features::kFreezePurgeMemoryBackgroundedOnly} /* enabled */, + {} /* disabled */); + + RegisterMemoryPressureListener(); + + SetProcessBackgrounded(true); + RenderThreadImpl::current()->RequestPurgeMemory(); + ExpectMemoryPressure(base::MemoryPressureListener::MemoryPressureLevel:: + MEMORY_PRESSURE_LEVEL_CRITICAL); + EXPECT_TRUE(base::MemoryPressureListener::AreNotificationsSuppressed()); +} + +// Verify that RequestPurgeMemory() does not trigger a memory pressure +// notification in a foregrounded renderer when the +// kFreezePurgeMemoryBackgroundedOnly feature is enabled. +TEST_F(RenderThreadImplBrowserTest, + RequestMemoryPurgeForegroundedPreventForegroundedRenderer) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures( + {features::kFreezePurgeMemoryBackgroundedOnly} /* enabled */, + {} /* disabled */); + + RegisterMemoryPressureListener(); + + SetProcessBackgrounded(false); + RenderThreadImpl::current()->RequestPurgeMemory(); + ExpectNoMemoryPressure(); + EXPECT_FALSE(base::MemoryPressureListener::AreNotificationsSuppressed()); +} + enum NativeBufferFlag { kDisableNativeBuffers, kEnableNativeBuffers }; class RenderThreadImplGpuMemoryBufferBrowserTest
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index fa9b3eca..73b2a3c1 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -879,6 +879,7 @@ WebRuntimeFeatures::EnableCSSHexAlphaColor(prefs.css_hex_alpha_color_enabled); WebRuntimeFeatures::EnableScrollTopLeftInterop( prefs.scroll_top_left_interop_enabled); + settings->SetForceDarkModeEnabled(prefs.force_dark_mode_enabled); #endif // defined(OS_ANDROID) switch (prefs.autoplay_policy) {
diff --git a/content/renderer/render_widget.cc b/content/renderer/render_widget.cc index 582922f2..281cfda 100644 --- a/content/renderer/render_widget.cc +++ b/content/renderer/render_widget.cc
@@ -402,7 +402,9 @@ webwidget_internal_(nullptr), auto_resize_mode_(false), is_hidden_(hidden), - compositor_never_visible_(never_visible), + // When there's no RenderThreadImpl we can't start the compositor without + // crashing, so just behave like a never-visible widget. + compositor_never_visible_(never_visible || !RenderThreadImpl::current()), is_fullscreen_granted_(false), display_mode_(display_mode), ime_event_guard_(nullptr), @@ -1673,20 +1675,12 @@ UpdateSurfaceAndScreenInfo(local_surface_id_allocation_from_parent_, compositor_viewport_pixel_size_, screen_info_); layer_tree_view_->SetContentSourceId(current_content_source_id_); - // For background pages and certain tests, we don't want to trigger - // LayerTreeFrameSink creation. - bool should_generate_frame_sink = - !compositor_never_visible_ && RenderThreadImpl::current(); - if (!should_generate_frame_sink) { - // Prevents SetVisible() from blink from doing anything. - layer_tree_view_->SetNeverVisible(); - } else if (!is_frozen_) { - // Begins the compositor's scheduler to start producing frames. - // Don't do this if the RenderWidget is attached to a RenderViewImpl for a - // proxy main frame, as this RenderWidget is frozen then, and won't be - // used for compositing until a WebFrameWidget is attached. - StartCompositor(); - } + // If the widget is hidden, delay starting the compositor until the user shows + // it. Also if the RenderWidget is frozen, we delay starting the compositor + // until we expect to use the widget, which will be signaled through + // WarmupCompositor(). + if (!is_frozen_ && !is_hidden_) + StartStopCompositor(); DCHECK_NE(MSG_ROUTING_NONE, routing_id_); layer_tree_view_->SetFrameSinkId( @@ -1696,40 +1690,43 @@ if (render_thread) { input_event_queue_ = base::MakeRefCounted<MainThreadEventQueue>( this, render_thread->GetWebMainThreadScheduler()->InputTaskRunner(), - render_thread->GetWebMainThreadScheduler(), should_generate_frame_sink); + render_thread->GetWebMainThreadScheduler(), + /*allow_raf_aligned_input=*/!compositor_never_visible_); } return layer_tree_view_.get(); } -void RenderWidget::StartCompositor() { - if (!is_hidden_) - layer_tree_view_->SetVisible(true); -} +void RenderWidget::StartStopCompositor() { + if (compositor_never_visible_) + return; -void RenderWidget::StopCompositor() { - layer_tree_view_->SetVisible(false); - // Drop all gpu resources, this makes SetVisible(true) more expensive/slower - // but we don't expect to use this RenderWidget again until some possible - // future navigation. This brings us a bit closer to emulating deleting the - // RenderWidget instead of just stopping the compositor. - layer_tree_view_->ReleaseLayerTreeFrameSink(); + if (is_frozen_) { + layer_tree_view_->SetVisible(false); + // Drop all gpu resources, this makes SetVisible(true) more expensive/slower + // but we don't expect to use this RenderWidget again until some possible + // future navigation. This brings us a bit closer to emulating deleting the + // RenderWidget instead of just stopping the compositor. + layer_tree_view_->ReleaseLayerTreeFrameSink(); + } else if (is_hidden_) { + layer_tree_view_->SetVisible(false); + } else { + layer_tree_view_->SetVisible(true); + } } void RenderWidget::SetIsFrozen(bool is_frozen) { DCHECK_NE(is_frozen, is_frozen_); is_frozen_ = is_frozen; - if (is_frozen) - StopCompositor(); - else - StartCompositor(); + // If hidden, then frozen changing doesn't change anything with the + // compositor since when hidden the compositor is always stopped. + if (!is_hidden_) + StartStopCompositor(); } void RenderWidget::WarmupCompositor() { DCHECK(is_frozen_); - - // Tests have no RenderThreadImpl /o\. - if (!RenderThreadImpl::current()) + if (compositor_never_visible_) return; // Keeping things simple. This would cancel any outstanding warmup if we @@ -2427,15 +2424,15 @@ if (render_widget_scheduling_state_) render_widget_scheduling_state_->SetHidden(hidden); - // When the RenderWidget is frozen, visibility of the compositor is overridden - // to always be hidden to prevent it from using resources that are not needed. - // Unfortunately the main RenderWidget for a RenderView must be marked visible - // even if the RenderView has a proxy main frame (and the RenderWidget is - // frozen), in order for the RenderView to use the visibility signal from the - // RenderWidget. This is bad. But we don't need to show the compositor to - // satisfy that requirement. + // TODO(danakj): Frozen RenderWidgets become visible with the RenderView but + // they don't need to anymore, since the RenderView's visibility is controlled + // separately. However even if they become visible, we don't need to start the + // compositor in this case. + // If frozen, then hidden changing doesn't change anything with the + // compositor since when frozen the compositor is always stopped (until + // we WarmupCompositor()). if (!is_frozen_) - layer_tree_view_->SetVisible(!is_hidden_); + StartStopCompositor(); } void RenderWidget::SetIsFullscreen(bool fullscreen) {
diff --git a/content/renderer/render_widget.h b/content/renderer/render_widget.h index c92a81e..ec12d39 100644 --- a/content/renderer/render_widget.h +++ b/content/renderer/render_widget.h
@@ -610,14 +610,16 @@ // Creates the compositor, but leaves it in a stopped state, where it will // not set up IPC channels or begin trying to produce frames until started - // via StartCompositor(). + // via StartStopCompositor(). LayerTreeView* InitializeLayerTreeView(); - // Initiates the compositor to set up IPC channels and begin its scheduler. - void StartCompositor(); - // Pauses the compositor's scheduler and tears down its IPC channels. - void StopCompositor(); + // If appropriate, initiates the compositor to set up IPC channels and begin + // its scheduler. Otherwise, pauses the scheduler and tears down its IPC + // channels. + void StartStopCompositor(); + // Request the window to close from the renderer by sending the request to the + // browser. void DoDeferredClose(); gfx::Size GetSizeForWebWidget() const;
diff --git a/content/renderer/renderer_blink_platform_impl.cc b/content/renderer/renderer_blink_platform_impl.cc index 25f8b59..e258a9b 100644 --- a/content/renderer/renderer_blink_platform_impl.cc +++ b/content/renderer/renderer_blink_platform_impl.cc
@@ -1053,8 +1053,11 @@ //------------------------------------------------------------------------------ void RendererBlinkPlatformImpl::RequestPurgeMemory() { - base::MemoryPressureListener::NotifyMemoryPressure( - base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL); + auto* render_thread = RenderThreadImpl::current(); + // RenderThreadImpl is null in some tests. + if (!render_thread) + return; + render_thread->RequestPurgeMemory(); } void RendererBlinkPlatformImpl::SetMemoryPressureNotificationsSuppressed(
diff --git a/content/renderer/service_worker/service_worker_fetch_context_impl.cc b/content/renderer/service_worker/service_worker_fetch_context_impl.cc index 5d42124..636ac88 100644 --- a/content/renderer/service_worker/service_worker_fetch_context_impl.cc +++ b/content/renderer/service_worker/service_worker_fetch_context_impl.cc
@@ -129,6 +129,13 @@ return worker_script_url_; } +base::Optional<blink::WebSecurityOrigin> +ServiceWorkerFetchContextImpl::TopFrameOrigin() const { + // TODO(jkarlin): Determine what the top-frame-origin of a service worker is. + // See https://crbug.com/918868. + return base::nullopt; +} + std::unique_ptr<blink::WebSocketHandshakeThrottle> ServiceWorkerFetchContextImpl::CreateWebSocketHandshakeThrottle( scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
diff --git a/content/renderer/service_worker/service_worker_fetch_context_impl.h b/content/renderer/service_worker/service_worker_fetch_context_impl.h index d8cb5d6..03efdaf 100644 --- a/content/renderer/service_worker/service_worker_fetch_context_impl.h +++ b/content/renderer/service_worker/service_worker_fetch_context_impl.h
@@ -53,6 +53,8 @@ blink::mojom::ControllerServiceWorkerMode IsControlledByServiceWorker() const override; blink::WebURL SiteForCookies() const override; + base::Optional<blink::WebSecurityOrigin> TopFrameOrigin() const override; + std::unique_ptr<blink::WebSocketHandshakeThrottle> CreateWebSocketHandshakeThrottle( scoped_refptr<base::SingleThreadTaskRunner> task_runner) override;
diff --git a/content/shell/BUILD.gn b/content/shell/BUILD.gn index 62224e0..329b06e 100644 --- a/content/shell/BUILD.gn +++ b/content/shell/BUILD.gn
@@ -658,13 +658,13 @@ bundle_data("content_shell_framework_helpers") { testonly = true sources = [ - "$root_out_dir/crashpad_handler", + "$root_out_dir/chrome_crashpad_handler", ] outputs = [ "{{bundle_contents_dir}}/Helpers/{{source_file_part}}", ] public_deps = [ - "//third_party/crashpad/crashpad/handler:crashpad_handler", + "//components/crash/content/app:chrome_crashpad_handler", ] }
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 9974ace..ae952983 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -56,6 +56,8 @@ "../browser/service_worker/embedded_worker_test_helper.h", "../browser/service_worker/service_worker_test_utils.cc", "../browser/service_worker/service_worker_test_utils.h", + "../browser/service_worker/test_service_worker_observer.cc", + "../browser/service_worker/test_service_worker_observer.h", "../browser/web_package/mock_signed_exchange_handler.cc", "../browser/web_package/mock_signed_exchange_handler.h", "../public/test/audio_service_test_helper.cc", @@ -871,7 +873,6 @@ "../browser/scheduler/responsiveness/native_event_observer_browsertest_win.cc", "../browser/screen_orientation/screen_orientation_browsertest.cc", "../browser/security_exploit_browsertest.cc", - "../browser/serial/serial_browsertest.cc", "../browser/service_manager/service_manager_context_browsertest.cc", "../browser/service_worker/service_worker_browsertest.cc", "../browser/service_worker/service_worker_clients_api_browsertest.cc", @@ -1183,6 +1184,7 @@ # Non-Android. sources += [ "../browser/host_zoom_map_impl_browsertest.cc", + "../browser/serial/serial_browsertest.cc", "../browser/speech/speech_recognition_browsertest.cc", "../browser/zoom_browsertest.cc", ] @@ -1540,6 +1542,7 @@ "../browser/payments/payment_app_content_unittest_base.h", "../browser/payments/payment_app_provider_impl_unittest.cc", "../browser/payments/payment_manager_unittest.cc", + "../browser/plugin_list_unittest.cc", "../browser/presentation/presentation_service_impl_unittest.cc", "../browser/renderer_host/clipboard_host_impl_unittest.cc", "../browser/renderer_host/cursor_manager_unittest.cc", @@ -1713,7 +1716,6 @@ "../common/origin_util_unittest.cc", "../common/page_state_serialization_unittest.cc", "../common/page_zoom_unittest.cc", - "../common/plugin_list_unittest.cc", "../common/service_manager/service_manager_connection_impl_unittest.cc", "../common/service_worker/service_worker_types_unittest.cc", "../common/service_worker/service_worker_utils_unittest.cc", @@ -2190,7 +2192,7 @@ } if (!is_win && !is_mac) { - sources -= [ "../common/plugin_list_unittest.cc" ] + sources -= [ "../browser/plugin_list_unittest.cc" ] } if (use_ozone) {
diff --git a/content/test/data/site_isolation/appcached_cross_origin_resource.html b/content/test/data/site_isolation/appcached_cross_origin_resource.html new file mode 100644 index 0000000..22eab3c --- /dev/null +++ b/content/test/data/site_isolation/appcached_cross_origin_resource.html
@@ -0,0 +1,23 @@ +<!DOCTYPE html> +<html manifest="appcached_cross_origin_resource.manifest"> +<head> + <title>OK</title> + <script type="text/javascript"> + window.applicationCache.addEventListener('cached', onCachedEvent, false); + + function onCachedEvent() { + window.document.title = "AppCache updated"; + } + + function onLoad() { + window.applicationCache.addEventListener('cached', onCachedEvent, false); + } + </script> +</head> + +<body onload="onLoad()"> + Basic AppCache test. The manifest for this page is specified in the + appcached_cross_origin_resource.manifest file. The title of the page is set + to AppCache updated if the cache is successfully updated. +</body> +</html>
diff --git a/content/test/data/site_isolation/appcached_cross_origin_resource.manifest b/content/test/data/site_isolation/appcached_cross_origin_resource.manifest new file mode 100644 index 0000000..49b8aa6 --- /dev/null +++ b/content/test/data/site_isolation/appcached_cross_origin_resource.manifest
@@ -0,0 +1,5 @@ +CACHE MANIFEST +http://cross-origin.com/site_isolation/nosniff.json + +NETWORK: +*
diff --git a/content/test/gpu/gpu_tests/gpu_integration_test.py b/content/test/gpu/gpu_tests/gpu_integration_test.py index 979e90e..a5077956 100644 --- a/content/test/gpu/gpu_tests/gpu_integration_test.py +++ b/content/test/gpu/gpu_tests/gpu_integration_test.py
@@ -3,7 +3,6 @@ # found in the LICENSE file. import logging -import os from telemetry.testing import serially_executed_browser_test_case from telemetry.util import screenshot @@ -72,11 +71,6 @@ cls._finder_options = cls._original_finder_options.Copy() browser_options = cls._finder_options.browser_options - # Enable browser log on Windows to debug the crash (crbug.com/917211). - # TODO(kbr): remove this once the bug is addressed. - if os.name == 'nt': - browser_options.logging_verbosity = browser_options.VERBOSE_LOGGING - # A non-sandboxed, 15-seconds-delayed gpu process is currently running in # the browser to collect gpu info. A command line switch is added here to # skip this gpu process for all gpu integration tests to prevent any
diff --git a/content/test/gpu/gpu_tests/pixel_expectations.py b/content/test/gpu/gpu_tests/pixel_expectations.py index fccaa81..1aede12 100644 --- a/content/test/gpu/gpu_tests/pixel_expectations.py +++ b/content/test/gpu/gpu_tests/pixel_expectations.py
@@ -152,3 +152,9 @@ self.Fail('Pixel_OffscreenCanvasUnaccelerated2D', bug=913223) self.Fail('Pixel_OffscreenCanvasUnaccelerated2DWorker', bug=913223) self.Fail('Pixel_OffscreenCanvasUnaccelerated2DGPUCompositing', bug=913223) + + # Skip on platforms where DXVA vs D3D11 decoder doesn't matter. + self.Skip('Pixel_Video_MP4_DXVA', ['linux', 'android', 'mac', 'chromeos'], + bug=927901) + self.Skip('Pixel_Video_VP9_DXVA', ['linux', 'android', 'mac', 'chromeos'], + bug=927901)
diff --git a/content/test/gpu/gpu_tests/pixel_test_pages.py b/content/test/gpu/gpu_tests/pixel_test_pages.py index 4d97744..7dbb7c3 100644 --- a/content/test/gpu/gpu_tests/pixel_test_pages.py +++ b/content/test/gpu/gpu_tests/pixel_test_pages.py
@@ -246,6 +246,43 @@ ]), PixelTestPage( + 'pixel_video_mp4.html', + base_name + '_Video_MP4_DXVA', + browser_args=['--disable-features=D3D11VideoDecoder'], + test_rect=[0, 0, 240, 135], + revision=0, # Golden image revision is not used + expected_colors=[ + { + 'comment': 'top left video, yellow', + 'location': [5, 5], + 'size': [110, 57], + 'color': [255, 255, 15], + 'tolerance': tolerance + }, + { + 'comment': 'top right video, red', + 'location': [125, 5], + 'size': [110, 57], + 'color': [255, 17, 24], + 'tolerance': tolerance + }, + { + 'comment': 'bottom left video, blue', + 'location': [5, 72], + 'size': [110, 57], + 'color': [12, 12, 255], + 'tolerance': tolerance + }, + { + 'comment': 'bottom right video, green', + 'location': [125, 72], + 'size': [110, 57], + 'color': [44, 255, 16], + 'tolerance': tolerance + } + ]), + + PixelTestPage( 'pixel_video_mp4_four_colors_aspect_4x3.html', base_name + '_Video_MP4_FourColors_Aspect_4x3', test_rect=[0, 0, 240, 135], @@ -467,6 +504,43 @@ } ]), + PixelTestPage( + 'pixel_video_vp9.html', + base_name + '_Video_VP9_DXVA', + browser_args=['--disable-features=D3D11VideoDecoder'], + test_rect=[0, 0, 240, 135], + revision=0, # Golden image revision is not used + expected_colors=[ + { + 'comment': 'top left video, yellow', + 'location': [5, 5], + 'size': [110, 57], + 'color': [255, 255, 15], + 'tolerance': tolerance_vp9 + }, + { + 'comment': 'top right video, red', + 'location': [125, 5], + 'size': [110, 57], + 'color': [255, 17, 24], + 'tolerance': tolerance_vp9 + }, + { + 'comment': 'bottom left video, blue', + 'location': [5, 72], + 'size': [110, 57], + 'color': [12, 12, 255], + 'tolerance': tolerance_vp9 + }, + { + 'comment': 'bottom right video, green', + 'location': [125, 72], + 'size': [110, 57], + 'color': [44, 255, 16], + 'tolerance': tolerance_vp9 + } + ]), + # The MP4 contains H.264 which is primarily hardware decoded on bots. PixelTestPage( 'pixel_video_context_loss.html?src=/media/test/data/four-colors.mp4', @@ -1132,6 +1206,8 @@ '--enable-features=DirectCompositionComplexOverlays,' + 'DirectCompositionNonrootOverlays,' + 'DirectCompositionUnderlays'] + browser_args_YUY2 = browser_args + [ + '--disable-features=DirectCompositionPreferNV12Overlays'] tolerance_dc = 3 @@ -1174,6 +1250,44 @@ ]), PixelTestPage( + 'pixel_video_mp4.html', + base_name + '_DirectComposition_Video_MP4_YUY2', + test_rect=[0, 0, 240, 135], + revision=0, # Golden image revision is not used + browser_args=browser_args_YUY2, + other_args={'expect_yuy2': True}, + expected_colors=[ + { + 'comment': 'top left video, yellow', + 'location': [5, 5], + 'size': [110, 57], + 'color': [255, 255, 15], + 'tolerance': tolerance_dc + }, + { + 'comment': 'top right video, red', + 'location': [125, 5], + 'size': [110, 57], + 'color': [255, 17, 24], + 'tolerance': tolerance_dc + }, + { + 'comment': 'bottom left video, blue', + 'location': [5, 72], + 'size': [110, 57], + 'color': [12, 12, 255], + 'tolerance': tolerance_dc + }, + { + 'comment': 'bottom right video, green', + 'location': [125, 72], + 'size': [110, 57], + 'color': [44, 255, 16], + 'tolerance': tolerance_dc + } + ]), + + PixelTestPage( 'pixel_video_mp4_four_colors_aspect_4x3.html', base_name + '_DirectComposition_Video_MP4_FourColors_Aspect_4x3', test_rect=[0, 0, 240, 135], @@ -1401,6 +1515,44 @@ ]), PixelTestPage( + 'pixel_video_vp9.html', + base_name + '_DirectComposition_Video_VP9_YUY2', + test_rect=[0, 0, 240, 135], + revision=0, # Golden image revision is not used + browser_args=browser_args_YUY2, + other_args={'expect_yuy2': True}, + expected_colors=[ + { + 'comment': 'top left video, yellow', + 'location': [5, 5], + 'size': [110, 57], + 'color': [255, 255, 15], + 'tolerance': tolerance_dc + }, + { + 'comment': 'top right video, red', + 'location': [125, 5], + 'size': [110, 57], + 'color': [255, 17, 24], + 'tolerance': tolerance_dc + }, + { + 'comment': 'bottom left video, blue', + 'location': [5, 72], + 'size': [110, 57], + 'color': [12, 12, 255], + 'tolerance': tolerance_dc + }, + { + 'comment': 'bottom right video, green', + 'location': [125, 72], + 'size': [110, 57], + 'color': [44, 255, 16], + 'tolerance': tolerance_dc + } + ]), + + PixelTestPage( 'pixel_video_underlay.html', base_name + '_DirectComposition_Underlay', test_rect=[0, 0, 240, 136],
diff --git a/content/test/gpu/gpu_tests/trace_integration_test.py b/content/test/gpu/gpu_tests/trace_integration_test.py index bb5310e..cbf2b5b 100644 --- a/content/test/gpu/gpu_tests/trace_integration_test.py +++ b/content/test/gpu/gpu_tests/trace_integration_test.py
@@ -278,14 +278,18 @@ self.fail('Trace markers for GPU category %s were not found' % category) return _TEST_DONE + def _EvaluateSuccess_CheckVideoModeYUY2(self, category, event_iterator): + return self._CheckVideoModeHelper(category, event_iterator, + expect_yuy2=True) + def _EvaluateSuccess_CheckVideoModeNoOverlay(self, category, event_iterator): return self._CheckVideoModeHelper(category, event_iterator, no_overlay=True) def _EvaluateSuccess_CheckVideoMode(self, category, event_iterator): - return self._CheckVideoModeHelper(category, event_iterator, - no_overlay=False) + return self._CheckVideoModeHelper(category, event_iterator) - def _CheckVideoModeHelper(self, category, event_iterator, no_overlay): + def _CheckVideoModeHelper(self, category, event_iterator, no_overlay=False, + expect_yuy2=False): os_name = self.browser.platform.GetOSName() assert os_name and os_name.lower() == 'win' @@ -306,7 +310,7 @@ assert supports_yuy2 or supports_nv12 if not no_overlay: expected_presentation_mode = _SWAP_CHAIN_PRESENTATION_MODE_OVERLAY - if not supports_nv12: + if expect_yuy2 or not supports_nv12: expected_pixel_format = _SWAP_CHAIN_PIXEL_FORMAT_YUY2 pixel_format_history = []
diff --git a/content/test/test_render_frame_host.cc b/content/test/test_render_frame_host.cc index e561611..fdb8d648 100644 --- a/content/test/test_render_frame_host.cc +++ b/content/test/test_render_frame_host.cc
@@ -473,14 +473,21 @@ { auto callback_it = navigation_client_commit_failed_callback_.find(navigation_id); - if (callback_it != navigation_client_commit_failed_callback_.end()) - std::move(callback_it->second).Run(result); + if (callback_it != navigation_client_commit_failed_callback_.end()) { + std::move(callback_it->second) + .Run(std::move(params), + mojom::DidCommitProvisionalLoadInterfaceParams::New( + std::move(interface_provider_request), + std::move(document_interface_broker_content_request), + std::move(document_interface_broker_blink_request))); + did_commit = true; + } } } if (!did_commit) { SendNavigateWithParamsAndInterfaceParams( - params.release(), + params.get(), mojom::DidCommitProvisionalLoadInterfaceParams::New( std::move(interface_provider_request), std::move(document_interface_broker_content_request),
diff --git a/device/fido/authenticator_get_info_response.cc b/device/fido/authenticator_get_info_response.cc index d5f63d4..b7f92b00 100644 --- a/device/fido/authenticator_get_info_response.cc +++ b/device/fido/authenticator_get_info_response.cc
@@ -58,8 +58,8 @@ } AuthenticatorGetInfoResponse& AuthenticatorGetInfoResponse::SetOptions( - AuthenticatorSupportedOptions options) { - options_ = std::move(options); + const AuthenticatorSupportedOptions& options) { + options_ = options; return *this; }
diff --git a/device/fido/authenticator_get_info_response.h b/device/fido/authenticator_get_info_response.h index b6fd9b1..120ca95 100644 --- a/device/fido/authenticator_get_info_response.h +++ b/device/fido/authenticator_get_info_response.h
@@ -37,7 +37,7 @@ AuthenticatorGetInfoResponse& SetExtensions( std::vector<std::string> extensions); AuthenticatorGetInfoResponse& SetOptions( - AuthenticatorSupportedOptions options); + const AuthenticatorSupportedOptions& options); const base::flat_set<ProtocolVersion>& versions() const { return versions_; } const std::array<uint8_t, kAaguidLength>& aaguid() const { return aaguid_; }
diff --git a/device/fido/authenticator_supported_options.cc b/device/fido/authenticator_supported_options.cc index 819bd6a..3e035ba 100644 --- a/device/fido/authenticator_supported_options.cc +++ b/device/fido/authenticator_supported_options.cc
@@ -13,58 +13,20 @@ AuthenticatorSupportedOptions::AuthenticatorSupportedOptions() = default; AuthenticatorSupportedOptions::AuthenticatorSupportedOptions( const AuthenticatorSupportedOptions& other) = default; -AuthenticatorSupportedOptions::AuthenticatorSupportedOptions( - AuthenticatorSupportedOptions&& other) = default; AuthenticatorSupportedOptions& AuthenticatorSupportedOptions::operator=( const AuthenticatorSupportedOptions& other) = default; -AuthenticatorSupportedOptions& AuthenticatorSupportedOptions::operator=( - AuthenticatorSupportedOptions&& other) = default; AuthenticatorSupportedOptions::~AuthenticatorSupportedOptions() = default; -AuthenticatorSupportedOptions& -AuthenticatorSupportedOptions::SetSupportsResidentKey( - bool supports_resident_key) { - supports_resident_key_ = supports_resident_key; - return *this; -} - -AuthenticatorSupportedOptions& -AuthenticatorSupportedOptions::SetUserVerificationAvailability( - UserVerificationAvailability user_verification_availability) { - user_verification_availability_ = user_verification_availability; - return *this; -} - -AuthenticatorSupportedOptions& -AuthenticatorSupportedOptions::SetUserPresenceRequired( - bool user_presence_required) { - user_presence_required_ = user_presence_required; - return *this; -} - -AuthenticatorSupportedOptions& -AuthenticatorSupportedOptions::SetClientPinAvailability( - ClientPinAvailability client_pin_availability) { - client_pin_availability_ = client_pin_availability; - return *this; -} - -AuthenticatorSupportedOptions& -AuthenticatorSupportedOptions::SetIsPlatformDevice(bool is_platform_device) { - is_platform_device_ = is_platform_device; - return *this; -} - cbor::Value ConvertToCBOR(const AuthenticatorSupportedOptions& options) { cbor::Value::MapValue option_map; - option_map.emplace(kResidentKeyMapKey, options.supports_resident_key()); - option_map.emplace(kUserPresenceMapKey, options.user_presence_required()); - option_map.emplace(kPlatformDeviceMapKey, options.is_platform_device()); + option_map.emplace(kResidentKeyMapKey, options.supports_resident_key); + option_map.emplace(kUserPresenceMapKey, options.user_presence_required); + option_map.emplace(kPlatformDeviceMapKey, options.is_platform_device); using UvAvailability = AuthenticatorSupportedOptions::UserVerificationAvailability; - switch (options.user_verification_availability()) { + switch (options.user_verification_availability) { case UvAvailability::kSupportedAndConfigured: option_map.emplace(kUserVerificationMapKey, true); break; @@ -78,7 +40,7 @@ using ClientPinAvailability = AuthenticatorSupportedOptions::ClientPinAvailability; - switch (options.client_pin_availability()) { + switch (options.client_pin_availability) { case ClientPinAvailability::kSupportedAndPinSet: option_map.emplace(kClientPinMapKey, true); break;
diff --git a/device/fido/authenticator_supported_options.h b/device/fido/authenticator_supported_options.h index 0d8fe25..830be6d2 100644 --- a/device/fido/authenticator_supported_options.h +++ b/device/fido/authenticator_supported_options.h
@@ -14,7 +14,7 @@ // Represents CTAP device properties and capabilities received as a response to // AuthenticatorGetInfo command. -class COMPONENT_EXPORT(DEVICE_FIDO) AuthenticatorSupportedOptions { +struct COMPONENT_EXPORT(DEVICE_FIDO) AuthenticatorSupportedOptions { public: enum class UserVerificationAvailability { // e.g. Authenticator with finger print sensor and user's fingerprint is @@ -34,48 +34,24 @@ AuthenticatorSupportedOptions(); AuthenticatorSupportedOptions(const AuthenticatorSupportedOptions& other); - AuthenticatorSupportedOptions(AuthenticatorSupportedOptions&& other); AuthenticatorSupportedOptions& operator=( const AuthenticatorSupportedOptions& other); - AuthenticatorSupportedOptions& operator=( - AuthenticatorSupportedOptions&& other); ~AuthenticatorSupportedOptions(); - AuthenticatorSupportedOptions& SetIsPlatformDevice(bool is_platform_device); - AuthenticatorSupportedOptions& SetSupportsResidentKey( - bool supports_resident_key); - AuthenticatorSupportedOptions& SetUserVerificationAvailability( - UserVerificationAvailability user_verification_required); - AuthenticatorSupportedOptions& SetUserPresenceRequired( - bool user_presence_required); - AuthenticatorSupportedOptions& SetClientPinAvailability( - ClientPinAvailability client_pin_availability); - - bool is_platform_device() const { return is_platform_device_; } - bool supports_resident_key() const { return supports_resident_key_; } - UserVerificationAvailability user_verification_availability() const { - return user_verification_availability_; - } - bool user_presence_required() const { return user_presence_required_; } - ClientPinAvailability client_pin_availability() const { - return client_pin_availability_; - } - - private: // Indicates that the device is attached to the client and therefore can't be // removed and used on another client. - bool is_platform_device_ = false; + bool is_platform_device = false; // Indicates that the device is capable of storing keys on the device itself // and therefore can satisfy the authenticatorGetAssertion request with // allowList parameter not specified or empty. - bool supports_resident_key_ = false; + bool supports_resident_key = false; // Indicates whether the device is capable of verifying the user on its own. - UserVerificationAvailability user_verification_availability_ = + UserVerificationAvailability user_verification_availability = UserVerificationAvailability::kNotSupported; - bool user_presence_required_ = true; + bool user_presence_required = true; // Represents whether client pin in set and stored in device. Set as null // optional if client pin capability is not supported by the authenticator. - ClientPinAvailability client_pin_availability_ = + ClientPinAvailability client_pin_availability = ClientPinAvailability::kNotSupported; };
diff --git a/device/fido/ctap_response_unittest.cc b/device/fido/ctap_response_unittest.cc index aa5a403..128cdec 100644 --- a/device/fido/ctap_response_unittest.cc +++ b/device/fido/ctap_response_unittest.cc
@@ -572,15 +572,15 @@ base::ContainsKey(get_info_response->versions(), ProtocolVersion::kCtap)); EXPECT_TRUE( base::ContainsKey(get_info_response->versions(), ProtocolVersion::kU2f)); - EXPECT_TRUE(get_info_response->options().is_platform_device()); - EXPECT_TRUE(get_info_response->options().supports_resident_key()); - EXPECT_TRUE(get_info_response->options().user_presence_required()); + EXPECT_TRUE(get_info_response->options().is_platform_device); + EXPECT_TRUE(get_info_response->options().supports_resident_key); + EXPECT_TRUE(get_info_response->options().user_presence_required); EXPECT_EQ(AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedAndConfigured, - get_info_response->options().user_verification_availability()); + get_info_response->options().user_verification_availability); EXPECT_EQ(AuthenticatorSupportedOptions::ClientPinAvailability:: kSupportedButPinNotSet, - get_info_response->options().client_pin_availability()); + get_info_response->options().client_pin_availability); } TEST(CTAPResponseTest, TestReadGetInfoResponseWithIncorrectFormat) { @@ -597,14 +597,12 @@ {ProtocolVersion::kCtap, ProtocolVersion::kU2f}, kTestDeviceAaguid); response.SetExtensions({"uvm", "hmac-secret"}); AuthenticatorSupportedOptions options; - options.SetSupportsResidentKey(true); - options.SetIsPlatformDevice(true); - options.SetClientPinAvailability( - AuthenticatorSupportedOptions::ClientPinAvailability:: - kSupportedButPinNotSet); - options.SetUserVerificationAvailability( - AuthenticatorSupportedOptions::UserVerificationAvailability:: - kSupportedAndConfigured); + options.supports_resident_key = true; + options.is_platform_device = true; + options.client_pin_availability = AuthenticatorSupportedOptions:: + ClientPinAvailability::kSupportedButPinNotSet; + options.user_verification_availability = AuthenticatorSupportedOptions:: + UserVerificationAvailability::kSupportedAndConfigured; response.SetOptions(std::move(options)); response.SetMaxMsgSize(1200); response.SetPinProtocols({1});
diff --git a/device/fido/device_response_converter.cc b/device/fido/device_response_converter.cc index a31f7669..11e3e1d3 100644 --- a/device/fido/device_response_converter.cc +++ b/device/fido/device_response_converter.cc
@@ -217,7 +217,7 @@ if (!option_map_it->second.is_bool()) return base::nullopt; - options.SetIsPlatformDevice(option_map_it->second.GetBool()); + options.is_platform_device = option_map_it->second.GetBool(); } option_map_it = option_map.find(CBOR(kResidentKeyMapKey)); @@ -225,7 +225,7 @@ if (!option_map_it->second.is_bool()) return base::nullopt; - options.SetSupportsResidentKey(option_map_it->second.GetBool()); + options.supports_resident_key = option_map_it->second.GetBool(); } option_map_it = option_map.find(CBOR(kUserPresenceMapKey)); @@ -233,7 +233,7 @@ if (!option_map_it->second.is_bool()) return base::nullopt; - options.SetUserPresenceRequired(option_map_it->second.GetBool()); + options.user_presence_required = option_map_it->second.GetBool(); } option_map_it = option_map.find(CBOR(kUserVerificationMapKey)); @@ -242,13 +242,11 @@ return base::nullopt; if (option_map_it->second.GetBool()) { - options.SetUserVerificationAvailability( - AuthenticatorSupportedOptions::UserVerificationAvailability:: - kSupportedAndConfigured); + options.user_verification_availability = AuthenticatorSupportedOptions:: + UserVerificationAvailability::kSupportedAndConfigured; } else { - options.SetUserVerificationAvailability( - AuthenticatorSupportedOptions::UserVerificationAvailability:: - kSupportedButNotConfigured); + options.user_verification_availability = AuthenticatorSupportedOptions:: + UserVerificationAvailability::kSupportedButNotConfigured; } } @@ -258,13 +256,11 @@ return base::nullopt; if (option_map_it->second.GetBool()) { - options.SetClientPinAvailability( - AuthenticatorSupportedOptions::ClientPinAvailability:: - kSupportedAndPinSet); + options.client_pin_availability = AuthenticatorSupportedOptions:: + ClientPinAvailability::kSupportedAndPinSet; } else { - options.SetClientPinAvailability( - AuthenticatorSupportedOptions::ClientPinAvailability:: - kSupportedButPinNotSet); + options.client_pin_availability = AuthenticatorSupportedOptions:: + ClientPinAvailability::kSupportedButPinNotSet; } } response.SetOptions(std::move(options));
diff --git a/device/fido/fido_device_authenticator.cc b/device/fido/fido_device_authenticator.cc index e68c762..d47be3af 100644 --- a/device/fido/fido_device_authenticator.cc +++ b/device/fido/fido_device_authenticator.cc
@@ -61,7 +61,7 @@ // Update the request to the "effective" user verification requirement. // https://w3c.github.io/webauthn/#effective-user-verification-requirement-for-credential-creation - if (Options()->user_verification_availability() == + if (Options()->user_verification_availability == AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedAndConfigured) { request.SetUserVerification(UserVerificationRequirement::kRequired); @@ -84,7 +84,7 @@ // Update the request to the "effective" user verification requirement. // https://w3c.github.io/webauthn/#effective-user-verification-requirement-for-assertion - if (Options()->user_verification_availability() == + if (Options()->user_verification_availability == AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedAndConfigured) { request.SetUserVerification(UserVerificationRequirement::kRequired);
diff --git a/device/fido/get_assertion_request_handler.cc b/device/fido/get_assertion_request_handler.cc index 94e52a68..a10bcf4 100644 --- a/device/fido/get_assertion_request_handler.cc +++ b/device/fido/get_assertion_request_handler.cc
@@ -72,7 +72,7 @@ if (!allow_list || allow_list->empty()) { // Allow list can't be empty for authenticators w/o resident key support. return !authenticator.Options() || - authenticator.Options()->supports_resident_key(); + authenticator.Options()->supports_resident_key; } // Credential ID may be omitted if allow list has size 1. Otherwise, it needs // to match. @@ -113,7 +113,7 @@ return request.user_verification() != UserVerificationRequirement::kRequired || - opt_options->user_verification_availability() == + opt_options->user_verification_availability == AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedAndConfigured; }
diff --git a/device/fido/mac/authenticator.mm b/device/fido/mac/authenticator.mm index cc697d6..8d9f532 100644 --- a/device/fido/mac/authenticator.mm +++ b/device/fido/mac/authenticator.mm
@@ -143,12 +143,11 @@ AuthenticatorSupportedOptions TouchIdAuthenticatorOptions() { AuthenticatorSupportedOptions options; - options.SetIsPlatformDevice(true); - options.SetSupportsResidentKey(true); - options.SetUserVerificationAvailability( - AuthenticatorSupportedOptions::UserVerificationAvailability:: - kSupportedAndConfigured); - options.SetUserPresenceRequired(true); + options.is_platform_device = true; + options.supports_resident_key = true; + options.user_verification_availability = AuthenticatorSupportedOptions:: + UserVerificationAvailability::kSupportedAndConfigured; + options.user_presence_required = true; return options; }
diff --git a/device/fido/make_credential_handler_unittest.cc b/device/fido/make_credential_handler_unittest.cc index c51893c..44fe635 100644 --- a/device/fido/make_credential_handler_unittest.cc +++ b/device/fido/make_credential_handler_unittest.cc
@@ -458,7 +458,7 @@ SuccessfulMakeCredentialWithResidentKeyOption) { auto device = std::make_unique<VirtualCtap2Device>(); AuthenticatorSupportedOptions option; - option.SetSupportsResidentKey(true); + option.supports_resident_key = true; device->SetAuthenticatorSupportedOptions(std::move(option)); auto request_handler =
diff --git a/device/fido/make_credential_request_handler.cc b/device/fido/make_credential_request_handler.cc index 67410bf..0522cd1 100644 --- a/device/fido/make_credential_request_handler.cc +++ b/device/fido/make_credential_request_handler.cc
@@ -36,19 +36,19 @@ if ((authenticator_selection_criteria.authenticator_attachment() == AuthenticatorAttachment::kPlatform && - !opt_options->is_platform_device()) || + !opt_options->is_platform_device) || (authenticator_selection_criteria.authenticator_attachment() == AuthenticatorAttachment::kCrossPlatform && - opt_options->is_platform_device())) + opt_options->is_platform_device)) return false; if (authenticator_selection_criteria.require_resident_key() && - !opt_options->supports_resident_key()) + !opt_options->supports_resident_key) return false; return authenticator_selection_criteria.user_verification_requirement() != UserVerificationRequirement::kRequired || - opt_options->user_verification_availability() == + opt_options->user_verification_availability == UvAvailability::kSupportedAndConfigured; }
diff --git a/device/fido/make_credential_task.cc b/device/fido/make_credential_task.cc index 401b8ea..f05f411 100644 --- a/device/fido/make_credential_task.cc +++ b/device/fido/make_credential_task.cc
@@ -33,7 +33,7 @@ DCHECK(device && device->device_info()); bool client_pin_set = - device->device_info()->options().client_pin_availability() == + device->device_info()->options().client_pin_availability == AuthenticatorSupportedOptions::ClientPinAvailability::kSupportedAndPinSet; bool supports_u2f = base::ContainsKey(device->device_info()->versions(), ProtocolVersion::kU2f);
diff --git a/device/fido/make_credential_task_unittest.cc b/device/fido/make_credential_task_unittest.cc index af609703..b9401ff 100644 --- a/device/fido/make_credential_task_unittest.cc +++ b/device/fido/make_credential_task_unittest.cc
@@ -118,9 +118,8 @@ AuthenticatorGetInfoResponse device_info( {ProtocolVersion::kCtap, ProtocolVersion::kU2f}, kTestDeviceAaguid); AuthenticatorSupportedOptions options; - options.SetClientPinAvailability( - AuthenticatorSupportedOptions::ClientPinAvailability:: - kSupportedAndPinSet); + options.client_pin_availability = + AuthenticatorSupportedOptions::ClientPinAvailability::kSupportedAndPinSet; device_info.SetOptions(std::move(options)); auto device = MockFidoDevice::MakeCtap(std::move(device_info)); @@ -140,9 +139,8 @@ AuthenticatorGetInfoResponse device_info( {ProtocolVersion::kCtap, ProtocolVersion::kU2f}, kTestDeviceAaguid); AuthenticatorSupportedOptions options; - options.SetClientPinAvailability( - AuthenticatorSupportedOptions::ClientPinAvailability:: - kSupportedAndPinSet); + options.client_pin_availability = + AuthenticatorSupportedOptions::ClientPinAvailability::kSupportedAndPinSet; device_info.SetOptions(std::move(options)); auto device = MockFidoDevice::MakeCtap(std::move(device_info));
diff --git a/device/fido/virtual_ctap2_device.cc b/device/fido/virtual_ctap2_device.cc index 0a12d8600..d1fe3d50 100644 --- a/device/fido/virtual_ctap2_device.cc +++ b/device/fido/virtual_ctap2_device.cc
@@ -52,24 +52,24 @@ bool AreMakeCredentialOptionsValid(const AuthenticatorSupportedOptions& options, const CtapMakeCredentialRequest& request) { - if (request.resident_key_required() && !options.supports_resident_key()) + if (request.resident_key_required() && !options.supports_resident_key) return false; return request.user_verification() != UserVerificationRequirement::kRequired || - options.user_verification_availability() == + options.user_verification_availability == AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedAndConfigured; } bool AreGetAssertionOptionsValid(const AuthenticatorSupportedOptions& options, const CtapGetAssertionRequest& request) { - if (request.user_presence_required() && !options.user_presence_required()) + if (request.user_presence_required() && !options.user_presence_required) return false; return request.user_verification() != UserVerificationRequirement::kRequired || - options.user_verification_availability() == + options.user_verification_availability == AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedAndConfigured; } @@ -259,8 +259,8 @@ } void VirtualCtap2Device::SetAuthenticatorSupportedOptions( - AuthenticatorSupportedOptions options) { - device_info_.SetOptions(std::move(options)); + const AuthenticatorSupportedOptions& options) { + device_info_.SetOptions(options); } CtapDeviceResponseCode VirtualCtap2Device::OnMakeCredential(
diff --git a/device/fido/virtual_ctap2_device.h b/device/fido/virtual_ctap2_device.h index 622d424..fab7d8d 100644 --- a/device/fido/virtual_ctap2_device.h +++ b/device/fido/virtual_ctap2_device.h
@@ -38,7 +38,8 @@ void DeviceTransact(std::vector<uint8_t> command, DeviceCallback cb) override; base::WeakPtr<FidoDevice> GetWeakPtr() override; - void SetAuthenticatorSupportedOptions(AuthenticatorSupportedOptions options); + void SetAuthenticatorSupportedOptions( + const AuthenticatorSupportedOptions& options); private: CtapDeviceResponseCode OnMakeCredential(base::span<const uint8_t> request,
diff --git a/docs/linux_build_instructions.md b/docs/linux_build_instructions.md index 87b101d9..3bbcfcd 100644 --- a/docs/linux_build_instructions.md +++ b/docs/linux_build_instructions.md
@@ -369,37 +369,6 @@ $ sudo install-build-deps.sh --no-arm ``` -### Debian - -Some tests require the `ttf-mscorefonts-installer` package from the `contrib` -component. `contrib` packages may have dependencies on non-free software. - -If you need to run tests requiring MS TTF fonts, you can edit your apt -`sources.list` by adding `contrib` to the end of each line beginning with `deb`. -You might end up with something like this: - -``` -deb http://ftp.us.debian.org/debian/ jessie main contrib -deb-src http://ftp.us.debian.org/debian/ jessie main contrib - -deb http://security.debian.org/ jessie/updates main contrib -deb-src http://security.debian.org/ jessie/updates main contrib - -# jessie-updates, previously known as 'volatile' -deb http://ftp.us.debian.org/debian/ jessie-updates main contrib -deb-src http://ftp.us.debian.org/debian/ jessie-updates main contrib -``` - -Next, run: - -``` shell -$ sudo apt-get update -$ sudo apt-get install ttf-mscorefonts-installer -``` - -If you already have the `contrib` component enabled, `install-build-deps.sh` -will install `ttf-mscorefonts-installer` for you. - ### Fedora Instead of running `build/install-build-deps.sh`, run:
diff --git a/docs/threading_and_tasks.md b/docs/threading_and_tasks.md index fef2a9f..5418910 100644 --- a/docs/threading_and_tasks.md +++ b/docs/threading_and_tasks.md
@@ -15,6 +15,32 @@ threads for communication, and we use callback interfaces (implemented by message passing) for most cross-thread requests. +### Nomenclature + * **Thread-unsafe**: The vast majority of types in Chrome are thread-unsafe by + design. Such types/methods cannot be accessed concurrently from different + threads. They should either be accessed from a single + `base::SequencedTaskRunner` (this should be enforced by a `SEQUENCE_CHECKER`) + or be accessed with external synchronization (e.g. locks -- but + [prefer sequences](#Using-Sequences-Instead-of-Locks)). + * **Thread-affine**: Such types/methods need to be always accessed from the + same physical thread (i.e. from the same `base::SingleThreadTaskRunner`). + Short of using a third-party API or having a leaf dependency which is + thread-affine: there's pretty much no reason for a type to be thread-affine + in Chrome. Note that `base::SingleThreadTaskRunner` is-a + `base::SequencedTaskRunner` so thread-affine is a subset of thread-unsafe. + * **Thread-safe**: Such types/methods can be safely accessed concurrently. + * **Thread-compatible**: Such types/methods are initialized once in a + thread-safe manner (either in the single-threaded phase of startup or lazily + through a thread-safe static-local-initialization paradigm a la + `base::NoDestructor`) and can forever after be accessed concurrently in a + read-only manner. + * **Sequence-friendly**: Such types/methods are thread-unsafe types which + support being invoked from a `base::SequencedTaskRunner`. Ideally this would + be the case for all thread-unsafe types but legacy code sometimes has + overzealous checks that enforce thread-affinity in mere thread-unsafe + scenarios. See [Prefer Sequences to Threads](#prefer-sequences-to-threads) + below for more details. + ### Threads Every Chrome process has @@ -70,9 +96,10 @@ resources on smaller machines). Many core APIs were recently made sequence-friendly (classes are rarely -thread-affine -- i.e. only when using thread-local-storage or third-party APIs -that do). But the codebase has long evolved assuming single-threaded contexts... -If your class could run on a sequence but is blocked by an overzealous use of +thread-affine -- i.e. only when using third-party APIs that are thread-affine; +even ThreadLocalStorage has a SequenceLocalStorage equivalent). But the codebase +has long evolved assuming single-threaded contexts... If your class could run on +a sequence but is blocked by an overzealous use of ThreadChecker/ThreadTaskRunnerHandle/SingleThreadTaskRunner in a leaf dependency, consider fixing that dependency for everyone's benefit (or at the very least file a blocking bug against https://crbug.com/675631 and flag your
diff --git a/extensions/browser/api/audio/audio_apitest.cc b/extensions/browser/api/audio/audio_apitest.cc index 740421ab..74ac9fa58 100644 --- a/extensions/browser/api/audio/audio_apitest.cc +++ b/extensions/browser/api/audio/audio_apitest.cc
@@ -9,7 +9,6 @@ #include "base/auto_reset.h" #include "base/command_line.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "build/build_config.h" #include "extensions/common/features/feature_session_type.h" @@ -121,7 +120,6 @@ } protected: - base::MessageLoopForUI message_loop_; std::unique_ptr<base::AutoReset<extensions::FeatureSessionType>> session_feature_type_; chromeos::CrasAudioHandler* cras_audio_handler_; // Not owned.
diff --git a/extensions/browser/api/declarative_net_request/constants.cc b/extensions/browser/api/declarative_net_request/constants.cc index 4f1a1c0..e530344 100644 --- a/extensions/browser/api/declarative_net_request/constants.cc +++ b/extensions/browser/api/declarative_net_request/constants.cc
@@ -35,7 +35,8 @@ const char kRuleCountExceeded[] = "Declarative Net Request: Rule count exceeded. Some rules were ignored."; const char kRuleNotParsedWarning[] = - "Declarative Net Request: Rule at index * couldn't be parsed."; + "Declarative Net Request: Rule at index * couldn't be parsed. Parse error: " + "*."; const char kTooManyParseFailuresWarning[] = "Declarative Net Request: Too many rule parse failures; Reporting the " "first *.";
diff --git a/extensions/browser/api/declarative_net_request/declarative_net_request_api.cc b/extensions/browser/api/declarative_net_request/declarative_net_request_api.cc index ac36cc55..524e7ae 100644 --- a/extensions/browser/api/declarative_net_request/declarative_net_request_api.cc +++ b/extensions/browser/api/declarative_net_request/declarative_net_request_api.cc
@@ -132,9 +132,13 @@ DeclarativeNetRequestAddAllowedPagesFunction::Run() { using Params = api::declarative_net_request::AddAllowedPages::Params; - std::unique_ptr<Params> params(Params::Create(*args_)); + base::string16 error; + std::unique_ptr<Params> params(Params::Create(*args_, &error)); EXTENSION_FUNCTION_VALIDATE(params); + // EXTENSION_FUNCTION_VALIDATE should validate that the arguments are in the + // correct format. Ignore |error|. + return UpdateAllowedPages(params->page_patterns, Action::ADD); } @@ -147,9 +151,13 @@ DeclarativeNetRequestRemoveAllowedPagesFunction::Run() { using Params = api::declarative_net_request::AddAllowedPages::Params; - std::unique_ptr<Params> params(Params::Create(*args_)); + base::string16 error; + std::unique_ptr<Params> params(Params::Create(*args_, &error)); EXTENSION_FUNCTION_VALIDATE(params); + // EXTENSION_FUNCTION_VALIDATE should validate that the arguments are in the + // correct format. Ignore |error|. + return UpdateAllowedPages(params->page_patterns, Action::REMOVE); }
diff --git a/extensions/browser/api/declarative_net_request/utils.cc b/extensions/browser/api/declarative_net_request/utils.cc index edd98535..c90942a9 100644 --- a/extensions/browser/api/declarative_net_request/utils.cc +++ b/extensions/browser/api/declarative_net_request/utils.cc
@@ -19,6 +19,7 @@ #include "base/metrics/histogram_macros.h" #include "base/strings/strcat.h" #include "base/strings/stringprintf.h" +#include "base/strings/utf_string_conversions.h" #include "base/timer/elapsed_timer.h" #include "base/values.h" #include "components/url_pattern_index/url_pattern_index.h" @@ -164,9 +165,8 @@ // Limit the maximum number of rule unparsed warnings to 5. const size_t kMaxUnparsedRulesWarnings = 5; - std::vector<int> unparsed_indices; - unparsed_indices.reserve(kMaxUnparsedRulesWarnings); bool unparsed_warnings_limit_exeeded = false; + size_t unparsed_warning_count = 0; base::ElapsedTimer timer; { @@ -175,16 +175,22 @@ const auto& rules_list = rules.GetList(); for (size_t i = 0; i < rules_list.size(); i++) { - parsed_rule = dnr_api::Rule::FromValue(rules_list[i]); + base::string16 parse_error; + parsed_rule = dnr_api::Rule::FromValue(rules_list[i], &parse_error); // Ignore rules which can't be successfully parsed and show an install // warning for them. A hard error is not thrown to maintain backwards // compatibility. - if (!parsed_rule) { - if (unparsed_indices.size() < kMaxUnparsedRulesWarnings) - unparsed_indices.push_back(i); - else + if (!parsed_rule || !parse_error.empty()) { + if (unparsed_warning_count < kMaxUnparsedRulesWarnings) { + ++unparsed_warning_count; + warnings->push_back( + CreateInstallWarning(ErrorUtils::FormatErrorMessage( + kRuleNotParsedWarning, std::to_string(i), + base::UTF16ToUTF8(parse_error)))); + } else { unparsed_warnings_limit_exeeded = true; + } continue; } @@ -216,17 +222,12 @@ warnings->push_back(CreateInstallWarning(kRuleCountExceeded)); if (unparsed_warnings_limit_exeeded) { - DCHECK_EQ(kMaxUnparsedRulesWarnings, unparsed_indices.size()); + DCHECK_EQ(kMaxUnparsedRulesWarnings, unparsed_warning_count); warnings->push_back(CreateInstallWarning(ErrorUtils::FormatErrorMessage( kTooManyParseFailuresWarning, std::to_string(kMaxUnparsedRulesWarnings)))); } - for (int rule_index : unparsed_indices) { - warnings->push_back(CreateInstallWarning(ErrorUtils::FormatErrorMessage( - kRuleNotParsedWarning, std::to_string(rule_index)))); - } - UMA_HISTOGRAM_TIMES(kIndexAndPersistRulesTimeHistogram, timer.Elapsed()); UMA_HISTOGRAM_COUNTS_100000(kManifestRulesCountHistogram, indexer.indexed_rules_count());
diff --git a/extensions/common/api/declarative_net_request.idl b/extensions/common/api/declarative_net_request.idl index 2c32ce20..337c7ad2 100644 --- a/extensions/common/api/declarative_net_request.idl +++ b/extensions/common/api/declarative_net_request.idl
@@ -4,6 +4,7 @@ // The <code>chrome.declarativeNetRequest</code> API is used to block or // redirect network requests by specifying declarative rules. +[generate_error_messages] namespace declarativeNetRequest { // This describes the resource type of the network request. enum ResourceType {
diff --git a/extensions/common/extension_messages.h b/extensions/common/extension_messages.h index 86b2161..3efca1e 100644 --- a/extensions/common/extension_messages.h +++ b/extensions/common/extension_messages.h
@@ -816,9 +816,9 @@ // Send a message to an extension process. The handle is the value returned // by ExtensionHostMsg_OpenChannelTo*. -IPC_MESSAGE_ROUTED2(ExtensionHostMsg_PostMessage, - extensions::PortId /* port_id */, - extensions::Message) +IPC_MESSAGE_CONTROL2(ExtensionHostMsg_PostMessage, + extensions::PortId /* port_id */, + extensions::Message) // Used to get the extension message bundle. IPC_SYNC_MESSAGE_CONTROL1_1(ExtensionHostMsg_GetMessageBundle,
diff --git a/extensions/renderer/extension_port.cc b/extensions/renderer/extension_port.cc index 47a472e..652d0b7 100644 --- a/extensions/renderer/extension_port.cc +++ b/extensions/renderer/extension_port.cc
@@ -26,8 +26,7 @@ // out for service workers. if (!render_frame) return; - render_frame->Send(new ExtensionHostMsg_PostMessage( - render_frame->GetRoutingID(), id_, *message)); + render_frame->Send(new ExtensionHostMsg_PostMessage(id_, *message)); } void ExtensionPort::Close(bool close_channel) {
diff --git a/extensions/renderer/ipc_message_sender.cc b/extensions/renderer/ipc_message_sender.cc index de40e12..897fc721 100644 --- a/extensions/renderer/ipc_message_sender.cc +++ b/extensions/renderer/ipc_message_sender.cc
@@ -195,11 +195,9 @@ routing_id, port_id, close_channel)); } - void SendPostMessageToPort(int routing_id, - const PortId& port_id, + void SendPostMessageToPort(const PortId& port_id, const Message& message) override { - render_thread_->Send( - new ExtensionHostMsg_PostMessage(routing_id, port_id, message)); + render_thread_->Send(new ExtensionHostMsg_PostMessage(port_id, message)); } private: @@ -348,8 +346,7 @@ NOTIMPLEMENTED(); } - void SendPostMessageToPort(int routing_id, - const PortId& port_id, + void SendPostMessageToPort(const PortId& port_id, const Message& message) override { NOTIMPLEMENTED(); }
diff --git a/extensions/renderer/ipc_message_sender.h b/extensions/renderer/ipc_message_sender.h index 7f6f856..1dcf822 100644 --- a/extensions/renderer/ipc_message_sender.h +++ b/extensions/renderer/ipc_message_sender.h
@@ -82,8 +82,7 @@ virtual void SendCloseMessagePort(int routing_id, const PortId& port_id, bool close_channel) = 0; - virtual void SendPostMessageToPort(int routing_id, - const PortId& port_id, + virtual void SendPostMessageToPort(const PortId& port_id, const Message& message) = 0; // Creates an IPCMessageSender for use on the main thread.
diff --git a/extensions/renderer/native_extension_bindings_system_test_base.h b/extensions/renderer/native_extension_bindings_system_test_base.h index e680c8b..aa76ea9 100644 --- a/extensions/renderer/native_extension_bindings_system_test_base.h +++ b/extensions/renderer/native_extension_bindings_system_test_base.h
@@ -86,10 +86,8 @@ void(int routing_id, const PortId& port_id)); MOCK_METHOD3(SendCloseMessagePort, void(int routing_id, const PortId& port_id, bool close_channel)); - MOCK_METHOD3(SendPostMessageToPort, - void(int routing_id, - const PortId& port_id, - const Message& message)); + MOCK_METHOD2(SendPostMessageToPort, + void(const PortId& port_id, const Message& message)); const ExtensionHostMsg_Request_Params* last_params() const { return last_params_.get();
diff --git a/extensions/renderer/native_renderer_messaging_service.cc b/extensions/renderer/native_renderer_messaging_service.cc index 3e90d4d..44471d5 100644 --- a/extensions/renderer/native_renderer_messaging_service.cc +++ b/extensions/renderer/native_renderer_messaging_service.cc
@@ -120,8 +120,8 @@ if (!ScriptContextIsValid(script_context)) return; - bindings_system_->GetIPCMessageSender()->SendPostMessageToPort( - routing_id, port_id, *message); + bindings_system_->GetIPCMessageSender()->SendPostMessageToPort(port_id, + *message); } void NativeRendererMessagingService::ClosePort(v8::Local<v8::Context> context,
diff --git a/extensions/renderer/native_renderer_messaging_service_unittest.cc b/extensions/renderer/native_renderer_messaging_service_unittest.cc index fc20634a..d3e64ca 100644 --- a/extensions/renderer/native_renderer_messaging_service_unittest.cc +++ b/extensions/renderer/native_renderer_messaging_service_unittest.cc
@@ -281,9 +281,9 @@ FunctionFromString(context, kDispatchMessage); v8::Local<v8::Value> args[] = {port_object}; - EXPECT_CALL(*ipc_message_sender(), - SendPostMessageToPort(MSG_ROUTING_NONE, port_id, - Message(R"({"data":"hello"})", false))); + EXPECT_CALL( + *ipc_message_sender(), + SendPostMessageToPort(port_id, Message(R"({"data":"hello"})", false))); RunFunctionOnGlobal(post_message, context, base::size(args), args); ::testing::Mock::VerifyAndClearExpectations(ipc_message_sender()); } @@ -354,8 +354,7 @@ EXPECT_CALL(*ipc_message_sender(), SendOpenMessageChannel(script_context(), port_id, target, kChannel, include_tls_channel_id)); - EXPECT_CALL(*ipc_message_sender(), - SendPostMessageToPort(MSG_ROUTING_NONE, port_id, message)); + EXPECT_CALL(*ipc_message_sender(), SendPostMessageToPort(port_id, message)); messaging_service()->SendOneTimeMessage(script_context(), target, kChannel, include_tls_channel_id, message, response_callback); @@ -425,9 +424,9 @@ // Post the message to the receiver. The receiver should respond, and the // port should close. - EXPECT_CALL(*ipc_message_sender(), - SendPostMessageToPort(MSG_ROUTING_NONE, port_id, - Message(R"({"data":"hi"})", false))); + EXPECT_CALL( + *ipc_message_sender(), + SendPostMessageToPort(port_id, Message(R"({"data":"hi"})", false))); EXPECT_CALL(*ipc_message_sender(), SendCloseMessagePort(MSG_ROUTING_NONE, port_id, true)); messaging_service()->DeliverMessage(*script_context_set(), port_id,
diff --git a/extensions/renderer/one_time_message_handler.cc b/extensions/renderer/one_time_message_handler.cc index 40348a4..0904bbb 100644 --- a/extensions/renderer/one_time_message_handler.cc +++ b/extensions/renderer/one_time_message_handler.cc
@@ -192,7 +192,7 @@ IPCMessageSender* ipc_sender = bindings_system_->GetIPCMessageSender(); ipc_sender->SendOpenMessageChannel(script_context, new_port_id, target, method_name, include_tls_channel_id); - ipc_sender->SendPostMessageToPort(routing_id, new_port_id, message); + ipc_sender->SendPostMessageToPort(new_port_id, message); // If the sender doesn't provide a response callback, we can immediately // close the channel. Note: we only do this for extension messages, not @@ -475,7 +475,7 @@ return; } IPCMessageSender* ipc_sender = bindings_system_->GetIPCMessageSender(); - ipc_sender->SendPostMessageToPort(routing_id, port_id, *message); + ipc_sender->SendPostMessageToPort(port_id, *message); bool close_channel = true; ipc_sender->SendCloseMessagePort(routing_id, port_id, close_channel); }
diff --git a/extensions/renderer/one_time_message_handler_unittest.cc b/extensions/renderer/one_time_message_handler_unittest.cc index d4442e2..66bae6b 100644 --- a/extensions/renderer/one_time_message_handler_unittest.cc +++ b/extensions/renderer/one_time_message_handler_unittest.cc
@@ -100,8 +100,7 @@ SendOpenMessageChannel(script_context(), port_id, target, messaging_util::kSendMessageChannel, include_tls_channel_id)); - EXPECT_CALL(*ipc_message_sender(), - SendPostMessageToPort(MSG_ROUTING_NONE, port_id, message)); + EXPECT_CALL(*ipc_message_sender(), SendPostMessageToPort(port_id, message)); EXPECT_CALL(*ipc_message_sender(), SendCloseMessagePort(MSG_ROUTING_NONE, port_id, true)); @@ -137,8 +136,7 @@ SendOpenMessageChannel(script_context(), port_id, target, messaging_util::kSendMessageChannel, include_tls_channel_id)); - EXPECT_CALL(*ipc_message_sender(), - SendPostMessageToPort(MSG_ROUTING_NONE, port_id, message)); + EXPECT_CALL(*ipc_message_sender(), SendPostMessageToPort(port_id, message)); message_handler()->SendMessage(script_context(), port_id, target, messaging_util::kSendMessageChannel, @@ -183,8 +181,7 @@ SendOpenMessageChannel(script_context(), port_id, target, messaging_util::kSendMessageChannel, include_tls_channel_id)); - EXPECT_CALL(*ipc_message_sender(), - SendPostMessageToPort(MSG_ROUTING_NONE, port_id, message)); + EXPECT_CALL(*ipc_message_sender(), SendPostMessageToPort(port_id, message)); message_handler()->SendMessage(script_context(), port_id, target, messaging_util::kSendMessageChannel, include_tls_channel_id, message, callback); @@ -285,9 +282,9 @@ // When the listener replies, we should post the reply to the message port and // close the channel. - EXPECT_CALL(*ipc_message_sender(), - SendPostMessageToPort(MSG_ROUTING_NONE, port_id, - Message(R"({"data":"hey"})", false))); + EXPECT_CALL( + *ipc_message_sender(), + SendPostMessageToPort(port_id, Message(R"({"data":"hey"})", false))); EXPECT_CALL(*ipc_message_sender(), SendCloseMessagePort(MSG_ROUTING_NONE, port_id, true)); message_handler()->DeliverMessage(script_context(), message, port_id); @@ -332,8 +329,7 @@ v8::Local<v8::Value> args[] = {reply_arg}; EXPECT_CALL(*ipc_message_sender(), - SendPostMessageToPort(MSG_ROUTING_NONE, port_id, - Message("\"hi\"", false))); + SendPostMessageToPort(port_id, Message("\"hi\"", false))); EXPECT_CALL(*ipc_message_sender(), SendCloseMessagePort(MSG_ROUTING_NONE, port_id, true)); RunFunction(reply.As<v8::Function>(), context, base::size(args), args); @@ -380,9 +376,9 @@ *ipc_message_sender(), SendOpenMessageChannel(script_context(), listener_created_port_id, target, messaging_util::kSendMessageChannel, false)); - EXPECT_CALL(*ipc_message_sender(), - SendPostMessageToPort(MSG_ROUTING_NONE, listener_created_port_id, - listener_sent_message)); + EXPECT_CALL( + *ipc_message_sender(), + SendPostMessageToPort(listener_created_port_id, listener_sent_message)); EXPECT_CALL(*ipc_message_sender(), SendCloseMessagePort(MSG_ROUTING_NONE, original_port_id, false)); @@ -418,8 +414,7 @@ SendOpenMessageChannel(script_context(), original_port_id, target, messaging_util::kSendMessageChannel, false)); EXPECT_CALL(*ipc_message_sender(), - SendPostMessageToPort(MSG_ROUTING_NONE, original_port_id, - original_message)); + SendPostMessageToPort(original_port_id, original_message)); RunFunctionOnGlobal(send_message, context, 0, nullptr); ::testing::Mock::VerifyAndClearExpectations(ipc_message_sender()); @@ -431,8 +426,7 @@ SendOpenMessageChannel(script_context(), new_port_id, target, messaging_util::kSendMessageChannel, false)); EXPECT_CALL(*ipc_message_sender(), - SendPostMessageToPort(MSG_ROUTING_NONE, new_port_id, - Message("\"bar\"", false))); + SendPostMessageToPort(new_port_id, Message("\"bar\"", false))); EXPECT_CALL(*ipc_message_sender(), SendCloseMessagePort(MSG_ROUTING_NONE, original_port_id, true)); const Message reply("\"reply\"", false);
diff --git a/extensions/renderer/runtime_hooks_delegate_unittest.cc b/extensions/renderer/runtime_hooks_delegate_unittest.cc index 4ac14d3..bf26381 100644 --- a/extensions/renderer/runtime_hooks_delegate_unittest.cc +++ b/extensions/renderer/runtime_hooks_delegate_unittest.cc
@@ -431,15 +431,14 @@ expected_target, kEmptyExpectedChannel, kExpectedIncludeTlsChannelId)); Message message(expected_message, false); - EXPECT_CALL( - *ipc_message_sender(), - SendPostMessageToPort(MSG_ROUTING_NONE, expected_port_id, message)); + EXPECT_CALL(*ipc_message_sender(), + SendPostMessageToPort(expected_port_id, message)); // Note: we don't close native message ports immediately. See comment in // OneTimeMessageSender. // if (expected_port_status == CLOSED) { // EXPECT_CALL( // *ipc_message_sender(), - // SendCloseMessagePort(MSG_ROUTING_NONE, expected_port_id, true)); + // SendCloseMessagePort(expected_port_id, true)); // } v8::Local<v8::Function> send_message = FunctionFromString( context, base::StringPrintf(kSendMessageTemplate, args));
diff --git a/extensions/renderer/send_message_tester.cc b/extensions/renderer/send_message_tester.cc index f6c5b521..b26f54a 100644 --- a/extensions/renderer/send_message_tester.cc +++ b/extensions/renderer/send_message_tester.cc
@@ -103,8 +103,7 @@ expected_target, expected_channel, expected_include_tls_channel_id)); Message message(expected_message, false); - EXPECT_CALL(*ipc_sender_, SendPostMessageToPort(MSG_ROUTING_NONE, - expected_port_id, message)); + EXPECT_CALL(*ipc_sender_, SendPostMessageToPort(expected_port_id, message)); if (expected_port_status == CLOSED) { EXPECT_CALL(*ipc_sender_,
diff --git a/fuchsia/BUILD.gn b/fuchsia/BUILD.gn index f682394..09d45205 100644 --- a/fuchsia/BUILD.gn +++ b/fuchsia/BUILD.gn
@@ -15,23 +15,6 @@ defines = [ "WEBRUNNER_IMPLEMENTATION" ] } -source_set("named_message_port_connector") { - sources = [ - "common/named_message_port_connector.cc", - "common/named_message_port_connector.h", - ] - data = [ - "common/named_message_port_connector.js", - ] - deps = [ - ":mem_buffer_common", - ":web_fidl", - "//base", - "//third_party/fuchsia-sdk/sdk:mem", - ] - configs += [ ":webrunner_implementation" ] -} - source_set("mem_buffer_common") { sources = [ "common/fuchsia_export.h", @@ -238,20 +221,14 @@ sources = [ "browser/context_impl_browsertest.cc", "browser/frame_impl_browsertest.cc", - "common/named_message_port_connector_browsertest.cc", ] defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] data = [ "browser/test/data", - "common/test/data", - ] - data_deps = [ - ":named_message_port_connector", ] deps = [ ":browsertest_common", ":mem_buffer_common", - ":named_message_port_connector", ":service_lib", ":test_support", ":test_support",
diff --git a/fuchsia/runners/BUILD.gn b/fuchsia/runners/BUILD.gn index fe19b7b..14ff0a2a 100644 --- a/fuchsia/runners/BUILD.gn +++ b/fuchsia/runners/BUILD.gn
@@ -36,20 +36,22 @@ "cast/cast_component.h", "cast/cast_runner.cc", "cast/cast_runner.h", + "cast/named_message_port_connector.cc", + "cast/named_message_port_connector.h", ] data = [ "cast/cast_channel_bindings.js", + "cast/named_message_port_connector.js", ] deps = [ "//base", "//fuchsia:mem_buffer_common", - "//fuchsia:named_message_port_connector", - "//fuchsia:web_fidl", "//url", ] public_deps = [ ":common", "//fuchsia:cast_fidl", + "//fuchsia:web_fidl", ] configs += [ "//fuchsia:webrunner_implementation" ] visibility = [ ":*" ] @@ -125,6 +127,7 @@ test("cast_runner_browsertests") { sources = [ "cast/cast_channel_bindings_browsertest.cc", + "cast/named_message_port_connector_browsertest.cc", ] defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] data = [ @@ -136,7 +139,6 @@ "//content/public/browser", "//fuchsia:browsertest_common", "//fuchsia:mem_buffer_common", - "//fuchsia:named_message_port_connector", "//fuchsia:test_support", "//testing/gmock", "//testing/gtest",
diff --git a/fuchsia/runners/cast/cast_channel_bindings.cc b/fuchsia/runners/cast/cast_channel_bindings.cc index 3512745b..3dc589a 100644 --- a/fuchsia/runners/cast/cast_channel_bindings.cc +++ b/fuchsia/runners/cast/cast_channel_bindings.cc
@@ -16,7 +16,7 @@ #include "base/path_service.h" #include "base/threading/thread_task_runner_handle.h" #include "fuchsia/common/mem_buffer_util.h" -#include "fuchsia/common/named_message_port_connector.h" +#include "fuchsia/runners/cast/named_message_port_connector.h" // Unique identifier of the Cast Channel message port, used by the JavaScript // API to connect to the port. @@ -24,7 +24,7 @@ CastChannelBindings::CastChannelBindings( chromium::web::Frame* frame, - webrunner::NamedMessagePortConnector* connector, + NamedMessagePortConnector* connector, chromium::cast::CastChannelPtr channel_consumer, base::OnceClosure on_error_closure) : frame_(frame),
diff --git a/fuchsia/runners/cast/cast_channel_bindings.h b/fuchsia/runners/cast/cast_channel_bindings.h index 01146e6..e259140 100644 --- a/fuchsia/runners/cast/cast_channel_bindings.h +++ b/fuchsia/runners/cast/cast_channel_bindings.h
@@ -13,10 +13,7 @@ #include "base/strings/string_piece.h" #include "fuchsia/common/fuchsia_export.h" #include "fuchsia/fidl/chromium/cast/cpp/fidl.h" - -namespace webrunner { -class NamedMessagePortConnector; -} +#include "fuchsia/runners/cast/named_message_port_connector.h" // Handles the injection of cast.__platform__.channel bindings into pages' // scripting context, and establishes a bidirectional message pipe over @@ -33,7 +30,7 @@ // |channel_consumer|: A FIDL service which receives opened Cast Channels. // Both |frame| and |connector| must outlive |this|. CastChannelBindings(chromium::web::Frame* frame, - webrunner::NamedMessagePortConnector* connector, + NamedMessagePortConnector* connector, chromium::cast::CastChannelPtr channel_consumer, base::OnceClosure on_error_closure); ~CastChannelBindings(); @@ -56,7 +53,7 @@ void OnMasterPortError(); chromium::web::Frame* const frame_; - webrunner::NamedMessagePortConnector* const connector_; + NamedMessagePortConnector* const connector_; // A queue of channels waiting to be sent the Cast Channel FIDL service. std::deque<chromium::web::MessagePortPtr> connected_channel_queue_;
diff --git a/fuchsia/runners/cast/cast_channel_bindings_browsertest.cc b/fuchsia/runners/cast/cast_channel_bindings_browsertest.cc index fb00446c..330e3edc 100644 --- a/fuchsia/runners/cast/cast_channel_bindings_browsertest.cc +++ b/fuchsia/runners/cast/cast_channel_bindings_browsertest.cc
@@ -13,7 +13,6 @@ #include "base/test/test_timeouts.h" #include "base/threading/thread_restrictions.h" #include "fuchsia/common/mem_buffer_util.h" -#include "fuchsia/common/named_message_port_connector.h" #include "fuchsia/common/test/test_common.h" #include "fuchsia/common/test/webrunner_browser_test.h" #include "fuchsia/runners/cast/cast_channel_bindings.h" @@ -47,7 +46,7 @@ webrunner::WebRunnerBrowserTest::SetUpOnMainThread(); base::ScopedAllowBlockingForTesting allow_blocking; frame_ = WebRunnerBrowserTest::CreateFrame(this); - connector_ = std::make_unique<webrunner::NamedMessagePortConnector>(); + connector_ = std::make_unique<NamedMessagePortConnector>(); } void OnNavigationStateChanged( @@ -111,7 +110,7 @@ std::unique_ptr<base::RunLoop> navigate_run_loop_; chromium::web::FramePtr frame_; - std::unique_ptr<webrunner::NamedMessagePortConnector> connector_; + std::unique_ptr<NamedMessagePortConnector> connector_; fidl::Binding<chromium::cast::CastChannel> receiver_binding_; // The connected Cast Channel.
diff --git a/fuchsia/runners/cast/cast_component.h b/fuchsia/runners/cast/cast_component.h index 7bb33b8f..fb78584 100644 --- a/fuchsia/runners/cast/cast_component.h +++ b/fuchsia/runners/cast/cast_component.h
@@ -9,9 +9,9 @@ #include <memory> #include "base/fuchsia/service_directory.h" -#include "fuchsia/common/named_message_port_connector.h" #include "fuchsia/fidl/chromium/web/cpp/fidl.h" #include "fuchsia/runners/cast/cast_channel_bindings.h" +#include "fuchsia/runners/cast/named_message_port_connector.h" #include "fuchsia/runners/common/web_component.h" class CastRunner; @@ -38,7 +38,7 @@ OnNavigationStateChangedCallback callback) override; bool constructor_active_ = false; - webrunner::NamedMessagePortConnector connector_; + NamedMessagePortConnector connector_; std::unique_ptr<CastChannelBindings> cast_channel_; fidl::Binding<chromium::web::NavigationEventObserver>
diff --git a/fuchsia/common/named_message_port_connector.cc b/fuchsia/runners/cast/named_message_port_connector.cc similarity index 92% rename from fuchsia/common/named_message_port_connector.cc rename to fuchsia/runners/cast/named_message_port_connector.cc index 41a0eaf1..aba175e8 100644 --- a/fuchsia/common/named_message_port_connector.cc +++ b/fuchsia/runners/cast/named_message_port_connector.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 "fuchsia/common/named_message_port_connector.h" +#include "fuchsia/runners/cast/named_message_port_connector.h" #include <memory> #include <utility> @@ -16,11 +16,10 @@ #include "fuchsia/common/mem_buffer_util.h" #include "fuchsia/fidl/chromium/web/cpp/fidl.h" -namespace webrunner { namespace { const char kBindingsJsPath[] = - FILE_PATH_LITERAL("fuchsia/common/named_message_port_connector.js"); + FILE_PATH_LITERAL("fuchsia/runners/cast/named_message_port_connector.js"); const char kConnectedMessage[] = "connected"; } // namespace @@ -28,7 +27,7 @@ NamedMessagePortConnector::NamedMessagePortConnector() { base::FilePath assets_path; CHECK(base::PathService::Get(base::DIR_ASSETS, &assets_path)); - bindings_script_ = MemBufferFromFile( + bindings_script_ = webrunner::MemBufferFromFile( base::File(assets_path.AppendASCII(kBindingsJsPath), base::File::FLAG_OPEN | base::File::FLAG_READ)); } @@ -88,7 +87,7 @@ handler = registration.handler](chromium::web::WebMessage message) mutable { std::string message_str; - if (!StringFromMemBuffer(message.data, &message_str)) { + if (!webrunner::StringFromMemBuffer(message.data, &message_str)) { LOG(ERROR) << "Couldn't read from message VMO."; return; } @@ -112,7 +111,7 @@ std::vector<std::string> origins = {"*"}; frame->ExecuteJavaScript( - std::move(origins), CloneBuffer(bindings_script_), + std::move(origins), webrunner::CloneBuffer(bindings_script_), chromium::web::ExecuteMode::ON_PAGE_LOAD, [](bool success) { CHECK(success) << "Couldn't inject bindings."; }); } @@ -123,5 +122,3 @@ NamedMessagePortConnector::RegistrationEntry::RegistrationEntry( const RegistrationEntry& other) = default; - -} // namespace webrunner
diff --git a/fuchsia/common/named_message_port_connector.h b/fuchsia/runners/cast/named_message_port_connector.h similarity index 90% rename from fuchsia/common/named_message_port_connector.h rename to fuchsia/runners/cast/named_message_port_connector.h index 352903b8..b7d5bcd 100644 --- a/fuchsia/common/named_message_port_connector.h +++ b/fuchsia/runners/cast/named_message_port_connector.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 FUCHSIA_COMMON_NAMED_MESSAGE_PORT_CONNECTOR_H_ -#define FUCHSIA_COMMON_NAMED_MESSAGE_PORT_CONNECTOR_H_ +#ifndef FUCHSIA_RUNNERS_CAST_NAMED_MESSAGE_PORT_CONNECTOR_H_ +#define FUCHSIA_RUNNERS_CAST_NAMED_MESSAGE_PORT_CONNECTOR_H_ #include <deque> #include <map> @@ -15,8 +15,6 @@ #include "fuchsia/common/fuchsia_export.h" #include "fuchsia/fidl/chromium/web/cpp/fidl.h" -namespace webrunner { - // The implementation actively creates a MessagePort for each registered Id, // passing them all to the web container every time a page-load occurs. It then // waits for the page to acknowledge each MessagePort, before invoking its @@ -65,6 +63,4 @@ DISALLOW_COPY_AND_ASSIGN(NamedMessagePortConnector); }; -} // namespace webrunner - -#endif // FUCHSIA_COMMON_NAMED_MESSAGE_PORT_CONNECTOR_H_ +#endif // FUCHSIA_RUNNERS_CAST_NAMED_MESSAGE_PORT_CONNECTOR_H_
diff --git a/fuchsia/common/named_message_port_connector.js b/fuchsia/runners/cast/named_message_port_connector.js similarity index 100% rename from fuchsia/common/named_message_port_connector.js rename to fuchsia/runners/cast/named_message_port_connector.js
diff --git a/fuchsia/common/named_message_port_connector_browsertest.cc b/fuchsia/runners/cast/named_message_port_connector_browsertest.cc similarity index 78% rename from fuchsia/common/named_message_port_connector_browsertest.cc rename to fuchsia/runners/cast/named_message_port_connector_browsertest.cc index fa88f1cd5..b5739cee6 100644 --- a/fuchsia/common/named_message_port_connector_browsertest.cc +++ b/fuchsia/runners/cast/named_message_port_connector_browsertest.cc
@@ -11,17 +11,15 @@ #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "fuchsia/common/mem_buffer_util.h" -#include "fuchsia/common/named_message_port_connector.h" #include "fuchsia/common/test/test_common.h" #include "fuchsia/common/test/webrunner_browser_test.h" +#include "fuchsia/runners/cast/named_message_port_connector.h" #include "fuchsia/test/promise.h" #include "testing/gmock/include/gmock/gmock-matchers.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/url_constants.h" -namespace webrunner { - // Use a shorter name for NavigationEvent, because it is // referenced frequently in this file. using NavigationDetails = chromium::web::NavigationEvent; @@ -32,7 +30,7 @@ public: NamedMessagePortConnectorTest() : run_timeout_(TestTimeouts::action_timeout()) { - set_test_server_root(base::FilePath("fuchsia/common/test/data")); + set_test_server_root(base::FilePath("fuchsia/runners/cast/testdata")); } ~NamedMessagePortConnectorTest() override = default; @@ -79,33 +77,36 @@ frame_->GetNavigationController(controller.NewRequest()); base::RunLoop receive_port_run_loop; - Promise<chromium::web::MessagePortPtr> message_port( + webrunner::Promise<chromium::web::MessagePortPtr> message_port( receive_port_run_loop.QuitClosure()); connector_.Register( "hello", - base::BindRepeating(&Promise<chromium::web::MessagePortPtr>::ReceiveValue, - base::Unretained(&message_port)), + base::BindRepeating( + &webrunner::Promise<chromium::web::MessagePortPtr>::ReceiveValue, + base::Unretained(&message_port)), frame_.get()); CheckLoadUrl(test_url.spec(), controller.get()); receive_port_run_loop.Run(); chromium::web::WebMessage msg; - msg.data = MemBufferFromString("ping"); - Promise<bool> post_result; + msg.data = webrunner::MemBufferFromString("ping"); + webrunner::Promise<bool> post_result; (*message_port) - ->PostMessage(std::move(msg), - ConvertToFitFunction(post_result.GetReceiveCallback())); + ->PostMessage(std::move(msg), webrunner::ConvertToFitFunction( + post_result.GetReceiveCallback())); std::vector<std::string> test_messages = {"early 1", "early 2", "ack ping"}; for (std::string expected_msg : test_messages) { base::RunLoop run_loop; - Promise<chromium::web::WebMessage> message_receiver(run_loop.QuitClosure()); + webrunner::Promise<chromium::web::WebMessage> message_receiver( + run_loop.QuitClosure()); (*message_port) - ->ReceiveMessage( - ConvertToFitFunction(message_receiver.GetReceiveCallback())); + ->ReceiveMessage(webrunner::ConvertToFitFunction( + message_receiver.GetReceiveCallback())); run_loop.Run(); - EXPECT_EQ(StringFromMemBufferOrDie(message_receiver->data), expected_msg); + EXPECT_EQ(webrunner::StringFromMemBufferOrDie(message_receiver->data), + expected_msg); } // Ensure that the MessagePort is dropped when navigating away. @@ -121,5 +122,3 @@ connector_.Unregister(frame_.get(), "hello"); } - -} // namespace webrunner
diff --git a/fuchsia/common/test/data/connector.html b/fuchsia/runners/cast/testdata/connector.html similarity index 100% rename from fuchsia/common/test/data/connector.html rename to fuchsia/runners/cast/testdata/connector.html
diff --git a/gpu/command_buffer/common/constants.h b/gpu/command_buffer/common/constants.h index 5bbdfa7..4e79b09e 100644 --- a/gpu/command_buffer/common/constants.h +++ b/gpu/command_buffer/common/constants.h
@@ -76,7 +76,8 @@ GPU_IO, IN_PROCESS, - VIZ_OUTPUT_SURFACE, + VIZ_SKIA_OUTPUT_SURFACE, + VIZ_SKIA_OUTPUT_SURFACE_NON_DDL, NUM_COMMAND_BUFFER_NAMESPACES };
diff --git a/headless/BUILD.gn b/headless/BUILD.gn index e09816c..5440be35 100644 --- a/headless/BUILD.gn +++ b/headless/BUILD.gn
@@ -603,12 +603,12 @@ if (is_mac) { copy("mac_helpers") { sources = [ - "$root_out_dir/crashpad_handler", + "$root_out_dir/chrome_crashpad_handler", ] deps = [ "//base", - "//third_party/crashpad/crashpad/handler:crashpad_handler", + "//components/crash/content/app:chrome_crashpad_handler", ] if (is_component_build) {
diff --git a/infra/config/global/cr-buildbucket.cfg b/infra/config/global/cr-buildbucket.cfg index 104a7480a..0f949953 100644 --- a/infra/config/global/cr-buildbucket.cfg +++ b/infra/config/global/cr-buildbucket.cfg
@@ -2406,12 +2406,6 @@ dimensions: "os:Ubuntu-14.04" } builders { - name: "mac-views-rel" - dimensions: "os:Mac-10.13" - dimensions: "cores:4" - mixins: "fyi-ci" - } - builders { name: "NDK Next x64 Builder" dimensions: "os:Ubuntu-14.04" mixins: "android-fyi-ci" @@ -3419,7 +3413,6 @@ dimensions: "cores:" } builders { mixins: "mac-try" mixins: "upload_clang" name: "mac_upload_clang" } - builders { mixins: "mac-try" name: "mac-views-rel" } builders { mixins: "win-optional-gpu-try"
diff --git a/infra/config/global/luci-milo.cfg b/infra/config/global/luci-milo.cfg index 951c8a0..fca1bd0 100644 --- a/infra/config/global/luci-milo.cfg +++ b/infra/config/global/luci-milo.cfg
@@ -1906,6 +1906,11 @@ short_name: "rel" } builders { + name: "buildbucket/luci.chrome.ci/ToTLinuxOfficial" + category: "ToT Linux" + short_name: "ofi" + } + builders { name: "buildbucket/luci.chromium.ci/ToTLinux (dbg)" category: "ToT Linux" short_name: "dbg" @@ -2127,6 +2132,11 @@ short_name: "rel" } builders { + name: "buildbucket/luci.chrome.ci/ToTLinuxOfficial" + category: "ToT Linux" + short_name: "ofi" + } + builders { name: "buildbucket/luci.chromium.ci/ToTLinux (dbg)" category: "ToT Linux" short_name: "dbg" @@ -2556,11 +2566,6 @@ short_name: "beta" } builders { - name: "buildbucket/luci.chromium.ci/mac-views-rel" - category: "mac" - short_name: "views" - } - builders { name: "buildbucket/luci.chromium.ci/mac-jumbo-rel" category: "mac" short_name: "jmb" @@ -4193,9 +4198,6 @@ builders { name: "buildbot/tryserver.chromium.mac/mac_upload_clang" } - builders { - name: "buildbucket/luci.chromium.try/mac-views-rel" - } builder_view_only: true }
diff --git a/infra/config/global/luci-scheduler.cfg b/infra/config/global/luci-scheduler.cfg index a9a20cdc..b1e9172 100644 --- a/infra/config/global/luci-scheduler.cfg +++ b/infra/config/global/luci-scheduler.cfg
@@ -348,7 +348,6 @@ triggers: "mac-jumbo-rel" triggers: "mac-mojo-rel" triggers: "mac-rel" - triggers: "mac-views-rel" triggers: "WebRTC Chromium Android Builder" triggers: "WebRTC Chromium Linux Builder" triggers: "WebRTC Chromium Linux Builder (RBE)" @@ -4387,16 +4386,6 @@ } job { - id: "mac-views-rel" - acl_sets: "default" - buildbucket: { - server: "cr-buildbucket.appspot.com" - bucket: "luci.chromium.ci" - builder: "mac-views-rel" - } -} - -job { id: "win-annotator-rel" acl_sets: "default" buildbucket: {
diff --git a/ios/chrome/app/main_controller.mm b/ios/chrome/app/main_controller.mm index c77ab8c3b..c3534dc 100644 --- a/ios/chrome/app/main_controller.mm +++ b/ios/chrome/app/main_controller.mm
@@ -2194,8 +2194,23 @@ TabModel* targetTabModel = targetBVC.tabModel; Tab* currentTabInTargetBVC = [targetTabModel currentTab]; + + // Don't call loadWithParams for chrome://newtab when it's already loaded. + // Note that it's safe to use -GetVisibleURL here, as it doesn't matter if the + // NTP hasn't finished loading. + if (currentTabInTargetBVC.webState && + IsURLNtp(currentTabInTargetBVC.webState->GetVisibleURL()) && + IsURLNtp(URL)) { + if (tabOpenedCompletion) { + tabOpenedCompletion(); + } + return currentTabInTargetBVC; + } + + // If the current tab isn't an NTP, open a new tab. Be sure to use + // -GetLastCommittedURL incase the NTP is still loading. if (!(currentTabInTargetBVC.webState && - IsURLNtp(currentTabInTargetBVC.webState->GetVisibleURL()))) { + IsURLNtp(currentTabInTargetBVC.webState->GetLastCommittedURL()))) { [targetBVC appendTabAddedCompletion:tabOpenedCompletion]; web::NavigationManager::WebLoadParams params(URL); params.transition_type = transition; @@ -2207,13 +2222,11 @@ inBackground:NO]; } + // Otherwise, load |url| in the current tab. Tab* newTab = currentTabInTargetBVC; - // Don't call loadWithParams for chrome://newtab, it's already loaded. - if (!(IsURLNtp(URL))) { - web::NavigationManager::WebLoadParams params(URL); - params.virtual_url = virtualURL; - [newTab webState]->GetNavigationManager()->LoadURLWithParams(params); - } + web::NavigationManager::WebLoadParams params(URL); + params.virtual_url = virtualURL; + newTab.webState->GetNavigationManager()->LoadURLWithParams(params); if (tabOpenedCompletion) { tabOpenedCompletion(); }
diff --git a/ios/chrome/browser/passwords/notify_auto_signin_view_controller.mm b/ios/chrome/browser/passwords/notify_auto_signin_view_controller.mm index 48fc55e9..9249dea 100644 --- a/ios/chrome/browser/passwords/notify_auto_signin_view_controller.mm +++ b/ios/chrome/browser/passwords/notify_auto_signin_view_controller.mm
@@ -145,15 +145,16 @@ // Fetch user's avatar and update displayed image. if (self.iconURL.is_valid()) { __weak NotifyUserAutoSigninViewController* weakSelf = self; + image_fetcher::ImageFetcherParams params(kTrafficAnnotation); _imageFetcher->FetchImage( - _iconURL.spec(), _iconURL, - base::BindOnce(^(const std::string& id, const gfx::Image& image, + _iconURL, + base::BindOnce(^(const gfx::Image& image, const image_fetcher::RequestMetadata& metadata) { if (!image.IsEmpty()) { weakSelf.avatarView.image = [image.ToUIImage() copy]; } }), - kTrafficAnnotation); + params); } }
diff --git a/ios/chrome/browser/signin/BUILD.gn b/ios/chrome/browser/signin/BUILD.gn index 6faeded7..7d87fab 100644 --- a/ios/chrome/browser/signin/BUILD.gn +++ b/ios/chrome/browser/signin/BUILD.gn
@@ -65,6 +65,7 @@ "//base", "//components/browser_sync", "//components/content_settings/core/browser", + "//components/image_fetcher/core", "//components/image_fetcher/ios", "//components/keyed_service/core", "//components/keyed_service/ios",
diff --git a/ios/chrome/browser/ui/webui/sync_internals/sync_internals_message_handler.cc b/ios/chrome/browser/ui/webui/sync_internals/sync_internals_message_handler.cc index 59430783..fca7ed97 100644 --- a/ios/chrome/browser/ui/webui/sync_internals/sync_internals_message_handler.cc +++ b/ios/chrome/browser/ui/webui/sync_internals/sync_internals_message_handler.cc
@@ -280,7 +280,7 @@ void SyncInternalsMessageHandler::OnProtocolEvent( const syncer::ProtocolEvent& event) { std::unique_ptr<base::DictionaryValue> value( - syncer::ProtocolEvent::ToValue(event, include_specifics_)); + event.ToValue(include_specifics_)); DispatchEvent(syncer::sync_ui_util::kOnProtocolEvent, *value); }
diff --git a/ios/web/public/global_state/ios_global_state.mm b/ios/web/public/global_state/ios_global_state.mm index 2228c72..16bed4f9b 100644 --- a/ios/web/public/global_state/ios_global_state.mm +++ b/ios/web/public/global_state/ios_global_state.mm
@@ -23,29 +23,19 @@ net::NetworkChangeNotifier* g_network_change_notifer = nullptr; base::TaskScheduler::InitParams GetDefaultTaskSchedulerInitParams() { - constexpr int kMinBackgroundThreads = 4; - constexpr int kMaxBackgroundThreads = 16; - constexpr double kCoreMultiplierBackgroundThreads = 0.2; - constexpr int kOffsetBackgroundThreads = 0; - constexpr int kReclaimTimeBackground = 30; - - constexpr int kMinForegroundThreads = 6; - constexpr int kMaxForegroundThreads = 16; - constexpr double kCoreMultiplierForegroundThreads = 0.6; - constexpr int kOffsetForegroundThreads = 0; - constexpr int kReclaimTimeForeground = 30; - return base::TaskScheduler::InitParams( base::SchedulerWorkerPoolParams( - base::RecommendedMaxNumberOfThreadsInPool( - kMinBackgroundThreads, kMaxBackgroundThreads, - kCoreMultiplierBackgroundThreads, kOffsetBackgroundThreads), - base::TimeDelta::FromSeconds(kReclaimTimeBackground)), + base::RecommendedMaxNumberOfThreadsInPool(2, 8, 0.1, 0), + base::TimeDelta::FromSeconds(30)), base::SchedulerWorkerPoolParams( - base::RecommendedMaxNumberOfThreadsInPool( - kMinForegroundThreads, kMaxForegroundThreads, - kCoreMultiplierForegroundThreads, kOffsetForegroundThreads), - base::TimeDelta::FromSeconds(kReclaimTimeForeground))); + base::RecommendedMaxNumberOfThreadsInPool(2, 8, 0.1, 0), + base::TimeDelta::FromSeconds(30)), + base::SchedulerWorkerPoolParams( + base::RecommendedMaxNumberOfThreadsInPool(3, 8, 0.3, 0), + base::TimeDelta::FromSeconds(30)), + base::SchedulerWorkerPoolParams( + base::RecommendedMaxNumberOfThreadsInPool(3, 8, 0.3, 0), + base::TimeDelta::FromSeconds(60))); } } // namespace
diff --git a/ios/web/test/test_web_thread_bundle.cc b/ios/web/test/test_web_thread_bundle.cc index 326ffd4..1e12d6b9 100644 --- a/ios/web/test/test_web_thread_bundle.cc +++ b/ios/web/test/test_web_thread_bundle.cc
@@ -87,7 +87,8 @@ std::make_unique<base::internal::TaskSchedulerImpl>( "ScopedTaskEnvironment")); base::TaskScheduler::GetInstance()->Start( - {worker_pool_params, worker_pool_params}); + {worker_pool_params, worker_pool_params, worker_pool_params, + worker_pool_params}); } } // namespace web
diff --git a/media/audio/audio_debug_recording_session_impl.cc b/media/audio/audio_debug_recording_session_impl.cc index 086c5b4..125e7a15 100644 --- a/media/audio/audio_debug_recording_session_impl.cc +++ b/media/audio/audio_debug_recording_session_impl.cc
@@ -29,9 +29,9 @@ namespace { #if defined(OS_WIN) -#define IntToStringType base::IntToString16 +#define NumberToStringType base::NumberToString16 #else -#define IntToStringType base::IntToString +#define NumberToStringType base::NumberToString #endif bool StreamTypeToStringType(AudioDebugRecordingStreamType stream_type, @@ -68,7 +68,7 @@ base::File::FLAG_WRITE); }, debug_recording_file_path.AddExtension(stream_type_str) - .AddExtension(IntToStringType(id)) + .AddExtension(NumberToStringType(id)) .AddExtension(FILE_PATH_LITERAL("wav"))), std::move(reply_callback)); }
diff --git a/media/audio/audio_debug_recording_session_impl_unittest.cc b/media/audio/audio_debug_recording_session_impl_unittest.cc index cc69925..4706798 100644 --- a/media/audio/audio_debug_recording_session_impl_unittest.cc +++ b/media/audio/audio_debug_recording_session_impl_unittest.cc
@@ -22,9 +22,9 @@ namespace { #if defined(OS_WIN) -#define IntToStringType base::IntToString16 +#define NumberToStringType base::NumberToString16 #else -#define IntToStringType base::IntToString +#define NumberToStringType base::NumberToString #endif const base::FilePath::CharType kBaseFileName[] = @@ -71,7 +71,7 @@ base::FilePath GetFileName(const base::FilePath::StringType& stream_type, uint32_t id) { return base_file_path_.AddExtension(stream_type) - .AddExtension(IntToStringType(id)) + .AddExtension(NumberToStringType(id)) .AddExtension(kWavExtension); }
diff --git a/media/base/android/BUILD.gn b/media/base/android/BUILD.gn index 56ea8d5..d7f7763 100644 --- a/media/base/android/BUILD.gn +++ b/media/base/android/BUILD.gn
@@ -52,13 +52,10 @@ "media_drm_storage.h", "media_drm_storage_bridge.cc", "media_drm_storage_bridge.h", - "media_player_android.cc", - "media_player_android.h", "media_player_bridge.cc", "media_player_bridge.h", "media_player_listener.cc", "media_player_listener.h", - "media_player_manager.h", "media_resource_getter.cc", "media_resource_getter.h", "media_server_crash_listener.cc",
diff --git a/media/base/android/java/src/org/chromium/media/MediaPlayerBridge.java b/media/base/android/java/src/org/chromium/media/MediaPlayerBridge.java index bc60148..aaeef434 100644 --- a/media/base/android/java/src/org/chromium/media/MediaPlayerBridge.java +++ b/media/base/android/java/src/org/chromium/media/MediaPlayerBridge.java
@@ -6,7 +6,6 @@ import android.annotation.SuppressLint; import android.media.MediaPlayer; -import android.media.MediaPlayer.TrackInfo; import android.net.Uri; import android.os.Build; import android.os.ParcelFileDescriptor; @@ -98,48 +97,6 @@ } @CalledByNative - protected boolean hasVideo() { - return hasTrack(TrackInfo.MEDIA_TRACK_TYPE_VIDEO); - } - - @CalledByNative - protected boolean hasAudio() { - return hasTrack(TrackInfo.MEDIA_TRACK_TYPE_AUDIO); - } - - private boolean hasTrack(int trackType) { - try { - TrackInfo trackInfo[] = getLocalPlayer().getTrackInfo(); - - // HLS media does not have the track info, so we treat them conservatively. - if (trackInfo.length == 0) return true; - - for (TrackInfo info : trackInfo) { - // TODO(zqzhang): may be we can have a histogram recording - // media track types in the future. - // See http://crbug.com/571411 - if (trackType == info.getTrackType()) return true; - if (TrackInfo.MEDIA_TRACK_TYPE_UNKNOWN == info.getTrackType()) return true; - } - } catch (RuntimeException e) { - // Exceptions may come from getTrackInfo (IllegalStateException/RuntimeException), or - // from some customized OS returning null TrackInfos (NullPointerException). - return true; - } - return false; - } - - @CalledByNative - protected int getVideoWidth() { - return getLocalPlayer().getVideoWidth(); - } - - @CalledByNative - protected int getVideoHeight() { - return getLocalPlayer().getVideoHeight(); - } - - @CalledByNative protected int getCurrentPosition() { return getLocalPlayer().getCurrentPosition(); } @@ -292,10 +249,6 @@ } } - protected void setOnBufferingUpdateListener(MediaPlayer.OnBufferingUpdateListener listener) { - getLocalPlayer().setOnBufferingUpdateListener(listener); - } - protected void setOnCompletionListener(MediaPlayer.OnCompletionListener listener) { getLocalPlayer().setOnCompletionListener(listener); } @@ -308,32 +261,20 @@ getLocalPlayer().setOnPreparedListener(listener); } - protected void setOnSeekCompleteListener(MediaPlayer.OnSeekCompleteListener listener) { - getLocalPlayer().setOnSeekCompleteListener(listener); - } - protected void setOnVideoSizeChangedListener(MediaPlayer.OnVideoSizeChangedListener listener) { getLocalPlayer().setOnVideoSizeChangedListener(listener); } protected static class AllowedOperations { - private final boolean mCanPause; private final boolean mCanSeekForward; private final boolean mCanSeekBackward; - public AllowedOperations(boolean canPause, boolean canSeekForward, - boolean canSeekBackward) { - mCanPause = canPause; + public AllowedOperations(boolean canSeekForward, boolean canSeekBackward) { mCanSeekForward = canSeekForward; mCanSeekBackward = canSeekBackward; } @CalledByNative("AllowedOperations") - private boolean canPause() { - return mCanPause; - } - - @CalledByNative("AllowedOperations") private boolean canSeekForward() { return mCanSeekForward; } @@ -351,7 +292,6 @@ @CalledByNative protected AllowedOperations getAllowedOperations() { MediaPlayer player = getLocalPlayer(); - boolean canPause = true; boolean canSeekForward = true; boolean canSeekBackward = true; try { @@ -365,15 +305,12 @@ Method hasMethod = metadataClass.getDeclaredMethod("has", int.class); Method getBooleanMethod = metadataClass.getDeclaredMethod("getBoolean", int.class); - int pause = (Integer) metadataClass.getField("PAUSE_AVAILABLE").get(null); int seekForward = (Integer) metadataClass.getField("SEEK_FORWARD_AVAILABLE").get(null); int seekBackward = (Integer) metadataClass.getField("SEEK_BACKWARD_AVAILABLE").get(null); hasMethod.setAccessible(true); getBooleanMethod.setAccessible(true); - canPause = !((Boolean) hasMethod.invoke(data, pause)) - || ((Boolean) getBooleanMethod.invoke(data, pause)); canSeekForward = !((Boolean) hasMethod.invoke(data, seekForward)) || ((Boolean) getBooleanMethod.invoke(data, seekForward)); canSeekBackward = !((Boolean) hasMethod.invoke(data, seekBackward)) @@ -388,7 +325,7 @@ } catch (NoSuchFieldException e) { Log.e(TAG, "Cannot find matching fields in Metadata class: " + e); } - return new AllowedOperations(canPause, canSeekForward, canSeekBackward); + return new AllowedOperations(canSeekForward, canSeekBackward); } private native void nativeOnDidSetDataUriDataSource(long nativeMediaPlayerBridge,
diff --git a/media/base/android/java/src/org/chromium/media/MediaPlayerListener.java b/media/base/android/java/src/org/chromium/media/MediaPlayerListener.java index 079ec91..9c4e601 100644 --- a/media/base/android/java/src/org/chromium/media/MediaPlayerListener.java +++ b/media/base/android/java/src/org/chromium/media/MediaPlayerListener.java
@@ -14,8 +14,6 @@ @JNINamespace("media") class MediaPlayerListener implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, - MediaPlayer.OnBufferingUpdateListener, - MediaPlayer.OnSeekCompleteListener, MediaPlayer.OnVideoSizeChangedListener, MediaPlayer.OnErrorListener { // These values are mirrored as enums in media/base/android/media_player_android.h. @@ -78,16 +76,6 @@ } @Override - public void onSeekComplete(MediaPlayer mp) { - nativeOnSeekComplete(mNativeMediaPlayerListener); - } - - @Override - public void onBufferingUpdate(MediaPlayer mp, int percent) { - nativeOnBufferingUpdate(mNativeMediaPlayerListener, percent); - } - - @Override public void onCompletion(MediaPlayer mp) { nativeOnPlaybackComplete(mNativeMediaPlayerListener); } @@ -102,11 +90,9 @@ long nativeMediaPlayerListener, MediaPlayerBridge mediaPlayerBridge) { final MediaPlayerListener listener = new MediaPlayerListener(nativeMediaPlayerListener); if (mediaPlayerBridge != null) { - mediaPlayerBridge.setOnBufferingUpdateListener(listener); mediaPlayerBridge.setOnCompletionListener(listener); mediaPlayerBridge.setOnErrorListener(listener); mediaPlayerBridge.setOnPreparedListener(listener); - mediaPlayerBridge.setOnSeekCompleteListener(listener); mediaPlayerBridge.setOnVideoSizeChangedListener(listener); } return listener; @@ -123,15 +109,7 @@ long nativeMediaPlayerListener, int width, int height); - private native void nativeOnBufferingUpdate( - long nativeMediaPlayerListener, - int percent); - private native void nativeOnMediaPrepared(long nativeMediaPlayerListener); private native void nativeOnPlaybackComplete(long nativeMediaPlayerListener); - - private native void nativeOnSeekComplete(long nativeMediaPlayerListener); - - private native void nativeOnMediaInterrupted(long nativeMediaPlayerListener); }
diff --git a/media/base/android/media_player_android.cc b/media/base/android/media_player_android.cc deleted file mode 100644 index 5464274..0000000 --- a/media/base/android/media_player_android.cc +++ /dev/null
@@ -1,128 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "media/base/android/media_player_android.h" - -#include <algorithm> - -#include "base/android/scoped_java_ref.h" -#include "base/logging.h" -#include "base/single_thread_task_runner.h" -#include "base/threading/thread_task_runner_handle.h" -#include "media/base/android/media_drm_bridge.h" -#include "media/base/android/media_player_manager.h" - -using base::android::JavaRef; - -namespace { - -const double kDefaultVolume = 1.0; - -} // namespace - -namespace media { - -const double MediaPlayerAndroid::kDefaultVolumeMultiplier = 1.0; - -MediaPlayerAndroid::MediaPlayerAndroid( - int player_id, - MediaPlayerManager* manager, - const OnDecoderResourcesReleasedCB& on_decoder_resources_released_cb, - const GURL& frame_url) - : on_decoder_resources_released_cb_(on_decoder_resources_released_cb), - player_id_(player_id), - volume_(kDefaultVolume), - volume_multiplier_(kDefaultVolumeMultiplier), - manager_(manager), - frame_url_(frame_url), - weak_factory_(this) { - listener_.reset(new MediaPlayerListener(base::ThreadTaskRunnerHandle::Get(), - weak_factory_.GetWeakPtr())); -} - -MediaPlayerAndroid::~MediaPlayerAndroid() {} - -void MediaPlayerAndroid::SetVolume(double volume) { - volume_ = std::max(0.0, std::min(volume, 1.0)); - UpdateEffectiveVolume(); -} - -void MediaPlayerAndroid::SetVolumeMultiplier(double volume_multiplier) { - volume_multiplier_ = std::max(0.0, std::min(volume_multiplier, 1.0)); - UpdateEffectiveVolume(); -} - -double MediaPlayerAndroid::GetEffectiveVolume() const { - return volume_ * volume_multiplier_; -} - -void MediaPlayerAndroid::UpdateEffectiveVolume() { - UpdateEffectiveVolumeInternal(GetEffectiveVolume()); -} - -// For most subclasses we can delete on the caller thread. -void MediaPlayerAndroid::DeleteOnCorrectThread() { - delete this; -} - -GURL MediaPlayerAndroid::GetUrl() { - return GURL(); -} - -GURL MediaPlayerAndroid::GetSiteForCookies() { - return GURL(); -} - -void MediaPlayerAndroid::SetCdm( - const scoped_refptr<ContentDecryptionModule>& /* cdm */) { - // Players that support EME should override this. - LOG(ERROR) << "EME not supported on base MediaPlayerAndroid class."; - return; -} - -void MediaPlayerAndroid::OnVideoSizeChanged(int width, int height) { - manager_->OnVideoSizeChanged(player_id(), width, height); -} - -void MediaPlayerAndroid::OnMediaError(int error_type) { - manager_->OnError(player_id(), error_type); -} - -void MediaPlayerAndroid::OnBufferingUpdate(int percent) { - manager_->OnBufferingUpdate(player_id(), percent); -} - -void MediaPlayerAndroid::OnPlaybackComplete() { - manager_->OnPlaybackComplete(player_id()); -} - -void MediaPlayerAndroid::OnMediaInterrupted() { - manager_->OnMediaInterrupted(player_id()); -} - -void MediaPlayerAndroid::OnSeekComplete() { - manager_->OnSeekComplete(player_id(), GetCurrentTime()); -} - -void MediaPlayerAndroid::OnMediaPrepared() {} - -void MediaPlayerAndroid::AttachListener( - const JavaRef<jobject>& j_media_player) { - listener_->CreateMediaPlayerListener(j_media_player); -} - -void MediaPlayerAndroid::DetachListener() { - listener_->ReleaseMediaPlayerListenerResources(); -} - -void MediaPlayerAndroid::DestroyListenerOnUIThread() { - weak_factory_.InvalidateWeakPtrs(); - listener_.reset(); -} - -base::WeakPtr<MediaPlayerAndroid> MediaPlayerAndroid::WeakPtrForUIThread() { - return weak_factory_.GetWeakPtr(); -} - -} // namespace media
diff --git a/media/base/android/media_player_android.h b/media/base/android/media_player_android.h deleted file mode 100644 index e96728b5..0000000 --- a/media/base/android/media_player_android.h +++ /dev/null
@@ -1,188 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MEDIA_BASE_ANDROID_MEDIA_PLAYER_ANDROID_H_ -#define MEDIA_BASE_ANDROID_MEDIA_PLAYER_ANDROID_H_ - -#include <jni.h> - -#include <memory> -#include <string> - -#include "base/android/scoped_java_ref.h" -#include "base/callback.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "base/time/time.h" -#include "media/base/android/media_player_listener.h" -#include "media/base/media_export.h" -#include "ui/gfx/geometry/size.h" -#include "ui/gl/android/scoped_java_surface.h" -#include "url/gurl.h" - -namespace media { - -class ContentDecryptionModule; -class MediaPlayerManager; - -// This class serves as the base class for different media player -// implementations on Android. Subclasses need to provide their own -// MediaPlayerAndroid::Create() implementation. -class MEDIA_EXPORT MediaPlayerAndroid { - public: - virtual ~MediaPlayerAndroid(); - - // Error types for MediaErrorCB. - enum MediaErrorType { - MEDIA_ERROR_FORMAT, - MEDIA_ERROR_DECODE, - MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK, - MEDIA_ERROR_INVALID_CODE, - MEDIA_ERROR_SERVER_DIED, - }; - - static const double kDefaultVolumeMultiplier; - - // Callback when the player releases decoding resources. - typedef base::Callback<void(int player_id)> OnDecoderResourcesReleasedCB; - - // Virtual destructor. - // For most subclasses we can delete on the caller thread. - virtual void DeleteOnCorrectThread(); - - // Passing an external java surface object to the player. - virtual void SetVideoSurface(gl::ScopedJavaSurface surface) = 0; - - // Start playing the media. - virtual void Start() = 0; - - // Pause the media. - virtual void Pause(bool is_media_related_action) = 0; - - // Seek to a particular position, based on renderer signaling actual seek - // with MediaPlayerHostMsg_Seek. If eventual success, OnSeekComplete() will be - // called. - virtual void SeekTo(base::TimeDelta timestamp) = 0; - - // Release the player resources. - virtual void Release() = 0; - - // Set the player volume, and take effect immediately. - // The volume should be between 0.0 and 1.0. - void SetVolume(double volume); - - // Set the player volume multiplier, and take effect immediately. - // The volume should be between 0.0 and 1.0. - void SetVolumeMultiplier(double volume_multiplier); - - // Get the media information from the player. - virtual bool HasVideo() const = 0; - virtual bool HasAudio() const = 0; - virtual int GetVideoWidth() = 0; - virtual int GetVideoHeight() = 0; - virtual base::TimeDelta GetDuration() = 0; - virtual base::TimeDelta GetCurrentTime() = 0; - virtual bool IsPlaying() = 0; - virtual bool CanPause() = 0; - virtual bool CanSeekForward() = 0; - virtual bool CanSeekBackward() = 0; - virtual bool IsPlayerReady() = 0; - virtual GURL GetUrl(); - virtual GURL GetSiteForCookies(); - - // Associates the |cdm| with this player. - virtual void SetCdm(const scoped_refptr<ContentDecryptionModule>& cdm); - - // Requests playback permission from MediaPlayerManager. - // Overridden in MediaCodecPlayer to pass data between threads. - virtual void RequestPermissionAndPostResult(base::TimeDelta duration, - bool has_audio) {} - - // Overridden in MediaCodecPlayer to pass data between threads. - virtual void OnMediaMetadataChanged(base::TimeDelta duration, - const gfx::Size& video_size) {} - - // Overridden in MediaCodecPlayer to pass data between threads. - virtual void OnTimeUpdate(base::TimeDelta current_timestamp, - base::TimeTicks current_time_ticks) {} - - int player_id() { return player_id_; } - - GURL frame_url() { return frame_url_; } - - // Attach/Detaches |listener_| for listening to all the media events. If - // |j_media_player| is NULL, |listener_| only listens to the system media - // events. Otherwise, it also listens to the events from |j_media_player|. - void AttachListener(const base::android::JavaRef<jobject>& j_media_player); - void DetachListener(); - - protected: - MediaPlayerAndroid( - int player_id, - MediaPlayerManager* manager, - const OnDecoderResourcesReleasedCB& on_decoder_resources_released_cb, - const GURL& frame_url); - - // TODO(qinmin): Simplify the MediaPlayerListener class to only listen to - // media interrupt events. And have a separate child class to listen to all - // the events needed by MediaPlayerBridge. http://crbug.com/422597. - // MediaPlayerListener callbacks. - virtual void OnVideoSizeChanged(int width, int height); - virtual void OnMediaError(int error_type); - virtual void OnBufferingUpdate(int percent); - virtual void OnPlaybackComplete(); - virtual void OnMediaInterrupted(); - virtual void OnSeekComplete(); - virtual void OnMediaPrepared(); - - double GetEffectiveVolume() const; - void UpdateEffectiveVolume(); - - // When destroying a subclassed object on a non-UI thread - // it is still required to destroy the |listener_| related stuff - // on the UI thread. - void DestroyListenerOnUIThread(); - - MediaPlayerManager* manager() { return manager_; } - - base::WeakPtr<MediaPlayerAndroid> WeakPtrForUIThread(); - - OnDecoderResourcesReleasedCB on_decoder_resources_released_cb_; - - private: - // Set the effective player volume, implemented by children classes. - virtual void UpdateEffectiveVolumeInternal(double effective_volume) = 0; - - friend class MediaPlayerListener; - - // Player ID assigned to this player. - int player_id_; - - // The player volume. Should be between 0.0 and 1.0. - double volume_; - - // The player volume multiplier. Should be between 0.0 and 1.0. This - // should be a cached version of the MediaSession volume multiplier, - // and should keep updated. - double volume_multiplier_; - - // Resource manager for all the media players. - MediaPlayerManager* manager_; - - // Url for the frame that contains this player. - GURL frame_url_; - - // Listener object that listens to all the media player events. - std::unique_ptr<MediaPlayerListener> listener_; - - // Weak pointer passed to |listener_| for callbacks. - // NOTE: Weak pointers must be invalidated before all other member variables. - base::WeakPtrFactory<MediaPlayerAndroid> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(MediaPlayerAndroid); -}; - -} // namespace media - -#endif // MEDIA_BASE_ANDROID_MEDIA_PLAYER_ANDROID_H_
diff --git a/media/base/android/media_player_bridge.cc b/media/base/android/media_player_bridge.cc index cc86dc03..e3f5404 100644 --- a/media/base/android/media_player_bridge.cc +++ b/media/base/android/media_player_bridge.cc
@@ -4,6 +4,7 @@ #include "media/base/android/media_player_bridge.h" +#include <algorithm> #include <utility> #include "base/android/jni_android.h" @@ -13,9 +14,9 @@ #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_util.h" +#include "base/threading/thread_task_runner_handle.h" #include "jni/MediaPlayerBridge_jni.h" #include "media/base/android/media_common_android.h" -#include "media/base/android/media_player_manager.h" #include "media/base/android/media_resource_getter.h" #include "media/base/android/media_url_interceptor.h" #include "media/base/timestamp_constants.h" @@ -35,23 +36,17 @@ UMA_EXIT_STATUS_MAX = UMA_EXIT_ERROR, }; +const double kDefaultVolume = 1.0; + } // namespace -MediaPlayerBridge::MediaPlayerBridge( - int player_id, - const GURL& url, - const GURL& site_for_cookies, - const std::string& user_agent, - bool hide_url_log, - MediaPlayerManager* manager, - const OnDecoderResourcesReleasedCB& on_decoder_resources_released_cb, - const GURL& frame_url, - bool allow_credentials) - : MediaPlayerAndroid(player_id, - manager, - on_decoder_resources_released_cb, - frame_url), - prepared_(false), +MediaPlayerBridge::MediaPlayerBridge(const GURL& url, + const GURL& site_for_cookies, + const std::string& user_agent, + bool hide_url_log, + Client* client, + bool allow_credentials) + : prepared_(false), pending_play_(false), should_seek_on_prepare_(false), url_(url), @@ -60,14 +55,18 @@ hide_url_log_(hide_url_log), width_(0), height_(0), - can_pause_(true), can_seek_forward_(true), can_seek_backward_(true), + volume_(kDefaultVolume), allow_credentials_(allow_credentials), is_active_(false), has_error_(false), has_ever_started_(false), - weak_factory_(this) {} + client_(client), + weak_factory_(this) { + listener_ = std::make_unique<MediaPlayerListener>( + base::ThreadTaskRunnerHandle::Get(), weak_factory_.GetWeakPtr()); +} MediaPlayerBridge::~MediaPlayerBridge() { if (!j_media_player_bridge_.is_null()) { @@ -93,7 +92,7 @@ if (allow_credentials_) { media::MediaResourceGetter* resource_getter = - manager()->GetMediaResourceGetter(); + client_->GetMediaResourceGetter(); resource_getter->GetCookies( url_, site_for_cookies_, @@ -109,13 +108,14 @@ j_media_player_bridge_.Reset(Java_MediaPlayerBridge_create( env, reinterpret_cast<intptr_t>(this))); - UpdateEffectiveVolume(); + UpdateVolumeInternal(); AttachListener(j_media_player_bridge_); } -void MediaPlayerBridge::SetDuration(base::TimeDelta duration) { +void MediaPlayerBridge::PropagateDuration(base::TimeDelta duration) { duration_ = duration; + client_->OnMediaDurationChanged(duration_); } void MediaPlayerBridge::SetVideoSurface(gl::ScopedJavaSurface surface) { @@ -142,7 +142,7 @@ CreateJavaMediaPlayerBridge(); if (url_.SchemeIsFileSystem()) { - manager()->GetMediaResourceGetter()->GetPlatformPathFromURL( + client_->GetMediaResourceGetter()->GetPlatformPathFromURL( url_, base::BindOnce(&MediaPlayerBridge::SetDataSource, weak_factory_.GetWeakPtr())); return; @@ -209,7 +209,7 @@ *offset = kUnsetValue; *size = kUnsetValue; media::MediaUrlInterceptor* url_interceptor = - manager()->GetMediaUrlInterceptor(); + client_->GetMediaUrlInterceptor(); if (url_interceptor && url_interceptor->Intercept(url, fd, offset, size)) { DCHECK_NE(kUnsetValue, *fd); DCHECK_NE(kUnsetValue, *offset); @@ -234,14 +234,14 @@ void MediaPlayerBridge::OnCookiesRetrieved(const std::string& cookies) { cookies_ = cookies; - manager()->GetMediaResourceGetter()->GetAuthCredentials( - url_, - base::Bind(&MediaPlayerBridge::OnAuthCredentialsRetrieved, - weak_factory_.GetWeakPtr())); + client_->GetMediaResourceGetter()->GetAuthCredentials( + url_, base::BindOnce(&MediaPlayerBridge::OnAuthCredentialsRetrieved, + weak_factory_.GetWeakPtr())); } void MediaPlayerBridge::OnAuthCredentialsRetrieved( - const base::string16& username, const base::string16& password) { + const base::string16& username, + const base::string16& password) { GURL::ReplacementsW replacements; if (!username.empty()) { replacements.SetUsernameStr(username); @@ -274,7 +274,7 @@ } } -void MediaPlayerBridge::Pause(bool is_media_related_action) { +void MediaPlayerBridge::Pause() { if (j_media_player_bridge_.is_null()) { pending_play_ = false; } else { @@ -288,9 +288,7 @@ } bool MediaPlayerBridge::IsPlaying() { - if (!prepared_) - return pending_play_; - + DCHECK(prepared_); JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); jboolean result = @@ -298,39 +296,13 @@ return result; } -bool MediaPlayerBridge::HasVideo() const { - DCHECK(prepared_); - JNIEnv* env = base::android::AttachCurrentThread(); - return Java_MediaPlayerBridge_hasVideo(env, j_media_player_bridge_); -} - -bool MediaPlayerBridge::HasAudio() const { - DCHECK(prepared_); - JNIEnv* env = base::android::AttachCurrentThread(); - return Java_MediaPlayerBridge_hasAudio(env, j_media_player_bridge_); -} - -int MediaPlayerBridge::GetVideoWidth() { - if (!prepared_) - return width_; - JNIEnv* env = base::android::AttachCurrentThread(); - return Java_MediaPlayerBridge_getVideoWidth(env, j_media_player_bridge_); -} - -int MediaPlayerBridge::GetVideoHeight() { - if (!prepared_) - return height_; - JNIEnv* env = base::android::AttachCurrentThread(); - return Java_MediaPlayerBridge_getVideoHeight(env, j_media_player_bridge_); -} - void MediaPlayerBridge::SeekTo(base::TimeDelta timestamp) { // Record the time to seek when OnMediaPrepared() is called. pending_seek_ = timestamp; should_seek_on_prepare_ = true; if (prepared_) - SeekInternal(GetCurrentTime(), timestamp); + SeekInternal(timestamp); } base::TimeDelta MediaPlayerBridge::GetCurrentTime() { @@ -342,8 +314,8 @@ } base::TimeDelta MediaPlayerBridge::GetDuration() { - if (!prepared_) - return duration_; + DCHECK(prepared_); + JNIEnv* env = base::android::AttachCurrentThread(); const int duration_ms = Java_MediaPlayerBridge_getDuration(env, j_media_player_bridge_); @@ -354,11 +326,9 @@ void MediaPlayerBridge::Release() { is_active_ = false; - on_decoder_resources_released_cb_.Run(player_id()); if (j_media_player_bridge_.is_null()) return; - time_update_timer_.Stop(); if (prepared_) { pending_seek_ = GetCurrentTime(); should_seek_on_prepare_ = true; @@ -373,7 +343,12 @@ DetachListener(); } -void MediaPlayerBridge::UpdateEffectiveVolumeInternal(double effective_volume) { +void MediaPlayerBridge::SetVolume(double volume) { + volume_ = std::max(0.0, std::min(volume, 1.0)); + UpdateVolumeInternal(); +} + +void MediaPlayerBridge::UpdateVolumeInternal() { if (j_media_player_bridge_.is_null()) { return; } @@ -381,14 +356,13 @@ JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); - Java_MediaPlayerBridge_setVolume(env, j_media_player_bridge_, - effective_volume); + Java_MediaPlayerBridge_setVolume(env, j_media_player_bridge_, volume_); } void MediaPlayerBridge::OnVideoSizeChanged(int width, int height) { width_ = width; height_ = height; - MediaPlayerAndroid::OnVideoSizeChanged(width, height); + client_->OnVideoSizeChanged(width, height); } void MediaPlayerBridge::OnMediaError(int error_type) { @@ -404,17 +378,11 @@ if (error_type == MEDIA_ERROR_SERVER_DIED) error_type = MEDIA_ERROR_INVALID_CODE; - MediaPlayerAndroid::OnMediaError(error_type); + client_->OnError(error_type); } void MediaPlayerBridge::OnPlaybackComplete() { - time_update_timer_.Stop(); - MediaPlayerAndroid::OnPlaybackComplete(); -} - -void MediaPlayerBridge::OnMediaInterrupted() { - time_update_timer_.Stop(); - MediaPlayerAndroid::OnMediaInterrupted(); + client_->OnPlaybackComplete(); } void MediaPlayerBridge::OnMediaPrepared() { @@ -422,14 +390,14 @@ return; prepared_ = true; - duration_ = GetDuration(); + PropagateDuration(GetDuration()); UpdateAllowedOperations(); // If media player was recovered from a saved state, consume all the pending // events. if (should_seek_on_prepare_) { - PendingSeekInternal(pending_seek_); + SeekInternal(pending_seek_); pending_seek_ = base::TimeDelta::FromMilliseconds(0); should_seek_on_prepare_ = false; } @@ -441,9 +409,6 @@ StartInternal(); pending_play_ = false; } - - manager()->OnMediaMetadataChanged( - player_id(), duration_, width_, height_, true); } ScopedJavaLocalRef<jobject> MediaPlayerBridge::GetAllowedOperations() { @@ -454,13 +419,24 @@ j_media_player_bridge_); } +void MediaPlayerBridge::AttachListener(const JavaRef<jobject>& j_media_player) { + listener_->CreateMediaPlayerListener(j_media_player); +} + +void MediaPlayerBridge::DetachListener() { + listener_->ReleaseMediaPlayerListenerResources(); +} + +base::WeakPtr<MediaPlayerBridge> MediaPlayerBridge::WeakPtrForUIThread() { + return weak_factory_.GetWeakPtr(); +} + void MediaPlayerBridge::UpdateAllowedOperations() { JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); ScopedJavaLocalRef<jobject> allowedOperations = GetAllowedOperations(); - can_pause_ = Java_AllowedOperations_canPause(env, allowedOperations); can_seek_forward_ = Java_AllowedOperations_canSeekForward(env, allowedOperations); can_seek_backward_ = @@ -468,40 +444,25 @@ } void MediaPlayerBridge::StartInternal() { - if (!manager()->RequestPlay(player_id(), duration_, HasAudio())) { - Pause(true); - return; - } - JNIEnv* env = base::android::AttachCurrentThread(); Java_MediaPlayerBridge_start(env, j_media_player_bridge_); - if (!time_update_timer_.IsRunning()) { - time_update_timer_.Start( - FROM_HERE, - base::TimeDelta::FromMilliseconds(kTimeUpdateInterval), - this, &MediaPlayerBridge::OnTimeUpdateTimerFired); - } } void MediaPlayerBridge::PauseInternal() { JNIEnv* env = base::android::AttachCurrentThread(); Java_MediaPlayerBridge_pause(env, j_media_player_bridge_); - time_update_timer_.Stop(); } -void MediaPlayerBridge::PendingSeekInternal(const base::TimeDelta& time) { - SeekInternal(GetCurrentTime(), time); -} +void MediaPlayerBridge::SeekInternal(base::TimeDelta time) { + base::TimeDelta current_time = GetCurrentTime(); -bool MediaPlayerBridge::SeekInternal(base::TimeDelta current_time, - base::TimeDelta time) { // Seeking on content like live streams may cause the media player to // get stuck in an error state. - if (time < current_time && !CanSeekBackward()) - return false; + if (time < current_time && !can_seek_backward_) + return; - if (time >= current_time && !CanSeekForward()) - return false; + if (time >= current_time && !can_seek_forward_) + return; if (time > duration_) time = duration_; @@ -510,39 +471,13 @@ // error state. if (time < base::TimeDelta()) { DCHECK_EQ(-1.0, time.InMillisecondsF()); - return false; + return; } JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); int time_msec = static_cast<int>(time.InMilliseconds()); Java_MediaPlayerBridge_seekTo(env, j_media_player_bridge_, time_msec); - return true; -} - -void MediaPlayerBridge::OnTimeUpdateTimerFired() { - base::TimeDelta current_timestamp = GetCurrentTime(); - if (last_time_update_timestamp_ == current_timestamp) - return; - manager()->OnTimeUpdate(player_id(), current_timestamp, - base::TimeTicks::Now()); - last_time_update_timestamp_ = current_timestamp; -} - -bool MediaPlayerBridge::CanPause() { - return can_pause_; -} - -bool MediaPlayerBridge::CanSeekForward() { - return can_seek_forward_; -} - -bool MediaPlayerBridge::CanSeekBackward() { - return can_seek_backward_; -} - -bool MediaPlayerBridge::IsPlayerReady() { - return prepared_; } GURL MediaPlayerBridge::GetUrl() {
diff --git a/media/base/android/media_player_bridge.h b/media/base/android/media_player_bridge.h index a48d6ad..dfe10664 100644 --- a/media/base/android/media_player_bridge.h +++ b/media/base/android/media_player_bridge.h
@@ -9,6 +9,7 @@ #include <stdint.h> #include <map> +#include <memory> #include <string> #include "base/android/scoped_java_ref.h" @@ -18,12 +19,15 @@ #include "base/strings/string16.h" #include "base/time/time.h" #include "base/timer/timer.h" -#include "media/base/android/media_player_android.h" +#include "media/base/android/media_player_listener.h" +#include "media/base/media_export.h" +#include "ui/gl/android/scoped_java_surface.h" #include "url/gurl.h" namespace media { -class MediaPlayerManager; +class MediaResourceGetter; +class MediaUrlInterceptor; // This class serves as a bridge between the native code and Android MediaPlayer // Java class. For more information on Android MediaPlayer, check @@ -34,81 +38,114 @@ // will cache those information in case the mediaplayer gets released. // The class uses the corresponding MediaPlayerBridge Java class to talk to // the Android MediaPlayer instance. -class MEDIA_EXPORT MediaPlayerBridge : public MediaPlayerAndroid { +class MEDIA_EXPORT MediaPlayerBridge { public: + class Client { + public: + // Returns a pointer to the MediaResourceGetter object. + virtual MediaResourceGetter* GetMediaResourceGetter() = 0; + + // Returns a pointer to the MediaUrlInterceptor object or null. + virtual MediaUrlInterceptor* GetMediaUrlInterceptor() = 0; + + // Called when media duration is first detected or changes. + virtual void OnMediaDurationChanged(base::TimeDelta duration) = 0; + + // Called when playback completed. + virtual void OnPlaybackComplete() = 0; + + // Called when error happens. + virtual void OnError(int error) = 0; + + // Called when video size has changed. + virtual void OnVideoSizeChanged(int width, int height) = 0; + }; + + // Error types for MediaErrorCB. + enum MediaErrorType { + MEDIA_ERROR_FORMAT, + MEDIA_ERROR_DECODE, + MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK, + MEDIA_ERROR_INVALID_CODE, + MEDIA_ERROR_SERVER_DIED, + }; + // Construct a MediaPlayerBridge object. This object needs to call |manager|'s // RequestMediaResources() before decoding the media stream. This allows // |manager| to track unused resources and free them when needed. // MediaPlayerBridge also forwards Android MediaPlayer callbacks to // the |manager| when needed. - MediaPlayerBridge( - int player_id, - const GURL& url, - const GURL& site_for_cookies, - const std::string& user_agent, - bool hide_url_log, - MediaPlayerManager* manager, - const OnDecoderResourcesReleasedCB& on_decoder_resources_released_cb, - const GURL& frame_url, - bool allow_credentials); - ~MediaPlayerBridge() override; + MediaPlayerBridge(const GURL& url, + const GURL& site_for_cookies, + const std::string& user_agent, + bool hide_url_log, + Client* client, + bool allow_credentials); + virtual ~MediaPlayerBridge(); // Initialize this object and extract the metadata from the media. - virtual void Initialize(); + void Initialize(); - // MediaPlayerAndroid implementation. - void SetVideoSurface(gl::ScopedJavaSurface surface) override; - void Start() override; - void Pause(bool is_media_related_action) override; - void SeekTo(base::TimeDelta timestamp) override; - void Release() override; - bool HasVideo() const override; - bool HasAudio() const override; - int GetVideoWidth() override; - int GetVideoHeight() override; - base::TimeDelta GetCurrentTime() override; - base::TimeDelta GetDuration() override; - bool IsPlaying() override; - bool CanPause() override; - bool CanSeekForward() override; - bool CanSeekBackward() override; - bool IsPlayerReady() override; - GURL GetUrl() override; - GURL GetSiteForCookies() override; + // Methods to partially expose the underlying MediaPlayer. + void SetVideoSurface(gl::ScopedJavaSurface surface); + void Pause(); + void SeekTo(base::TimeDelta timestamp); + base::TimeDelta GetCurrentTime(); + + // Starts media playback. + // The first call to this method will call Prepare() and create the underlying + // MediaPlayer for the first time. + void Start(); + + // The media URL given to the underlying MediaPlayer. + GURL GetUrl(); + + // The site whose cookies should be given to the MediaPlayer if needed. + GURL GetSiteForCookies(); + + // Set the player volume, and take effect immediately. + // The volume should be between 0.0 and 1.0. + void SetVolume(double volume); void OnDidSetDataUriDataSource( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, jboolean success); - protected: - void SetDuration(base::TimeDelta time); + private: + friend class MediaPlayerListener; + friend class MediaPlayerBridgeTest; - virtual void PendingSeekInternal(const base::TimeDelta& time); + // Releases the resources such as the underlying MediaPlayer and + // MediaPlayerListener. + void Release(); + + base::TimeDelta GetDuration(); + void PropagateDuration(base::TimeDelta time); + bool IsPlaying(); // Prepare the player for playback, asynchronously. When succeeds, // OnMediaPrepared() will be called. Otherwise, OnMediaError() will // be called with an error type. - virtual void Prepare(); + void Prepare(); - // MediaPlayerAndroid implementation. - void OnVideoSizeChanged(int width, int height) override; - void OnMediaError(int error_type) override; - void OnPlaybackComplete() override; - void OnMediaInterrupted() override; - void OnMediaPrepared() override; + // MediaPlayerListener callbacks. + void OnVideoSizeChanged(int width, int height); + void OnMediaError(int error_type); + void OnPlaybackComplete(); + void OnMediaPrepared(); // Create the corresponding Java class instance. - virtual void CreateJavaMediaPlayerBridge(); + void CreateJavaMediaPlayerBridge(); // Get allowed operations from the player. - virtual base::android::ScopedJavaLocalRef<jobject> GetAllowedOperations(); + base::android::ScopedJavaLocalRef<jobject> GetAllowedOperations(); - private: - friend class MediaPlayerBridgeTest; - - // MediaPlayerAndroid implementation - void UpdateEffectiveVolumeInternal(double effective_volume) override; + // Attach/Detaches |listener_| for listening to all the media events. If + // |j_media_player| is NULL, |listener_| only listens to the system media + // events. Otherwise, it also listens to the events from |j_media_player|. + void AttachListener(const base::android::JavaRef<jobject>& j_media_player); + void DetachListener(); // Set the data source for the media player. void SetDataSource(const std::string& url); @@ -117,11 +154,9 @@ void StartInternal(); void PauseInternal(); - // Returns true if the Java MediaPlayerBridge's seekTo method is called - bool SeekInternal(base::TimeDelta current_time, base::TimeDelta time); - - // Called when |time_update_timer_| fires. - void OnTimeUpdateTimerFired(); + // Calls Java MediaPlayerBridge's seekTo method, or no-ops if the operation + // is not allowed (based off of |can_seek_forward_| and |can_seek_backward_|). + void SeekInternal(base::TimeDelta time); // Update allowed operations from the player. void UpdateAllowedOperations(); @@ -132,13 +167,15 @@ // Callback function passed to |resource_getter_|. Called when the auth // credentials are retrieved. - void OnAuthCredentialsRetrieved( - const base::string16& username, const base::string16& password); + void OnAuthCredentialsRetrieved(const base::string16& username, + const base::string16& password); // Extract the media metadata from a url, asynchronously. // OnMediaMetadataExtracted() will be called when this call finishes. void ExtractMediaMetadata(const std::string& url); - void OnMediaMetadataExtracted(base::TimeDelta duration, int width, int height, + void OnMediaMetadataExtracted(base::TimeDelta duration, + int width, + int height, bool success); // Returns true if a MediaUrlInterceptor registered by the embedder has @@ -148,6 +185,11 @@ int64_t* offset, int64_t* size); + // Sets the underlying MediaPlayer's volume. + void UpdateVolumeInternal(); + + base::WeakPtr<MediaPlayerBridge> WeakPtrForUIThread(); + // Whether the player is prepared for playback. bool prepared_; @@ -177,11 +219,12 @@ int width_; int height_; - // Meta data about actions can be taken. - bool can_pause_; bool can_seek_forward_; bool can_seek_backward_; + // The player volume. Should be between 0.0 and 1.0. + double volume_; + // Cookies for |url_|. std::string cookies_; @@ -191,15 +234,9 @@ // Java MediaPlayerBridge instance. base::android::ScopedJavaGlobalRef<jobject> j_media_player_bridge_; - base::RepeatingTimer time_update_timer_; - - base::TimeDelta last_time_update_timestamp_; - // Whether user credentials are allowed to be passed. bool allow_credentials_; - // Helper variables for UMA reporting. - // Whether the preparation for playback or the playback is currently going on. // This flag is set in Start() and cleared in Pause() and Release(). Used for // UMA reporting only. @@ -211,6 +248,13 @@ // The flag is set if Start() has been called at least once. bool has_ever_started_; + // A reference to the owner of |this|. + Client* client_; + + // Listener object that listens to all the media player events. + std::unique_ptr<MediaPlayerListener> listener_; + + // Weak pointer passed to |listener_| for callbacks. // NOTE: Weak pointers must be invalidated before all other member variables. base::WeakPtrFactory<MediaPlayerBridge> weak_factory_;
diff --git a/media/base/android/media_player_bridge_unittest.cc b/media/base/android/media_player_bridge_unittest.cc index cc60f990..54bbd5c 100644 --- a/media/base/android/media_player_bridge_unittest.cc +++ b/media/base/android/media_player_bridge_unittest.cc
@@ -6,7 +6,6 @@ #include "base/bind.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" -#include "media/base/android/media_player_manager.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -14,33 +13,17 @@ namespace { -class MockMediaPlayerManager : public MediaPlayerManager { +using testing::_; +using testing::StrictMock; + +class MockMediaPlayerBridgeClient : public MediaPlayerBridge::Client { public: MOCK_METHOD0(GetMediaResourceGetter, MediaResourceGetter*()); MOCK_METHOD0(GetMediaUrlInterceptor, MediaUrlInterceptor*()); - MOCK_METHOD3(OnTimeUpdate, - void(int player_id, - base::TimeDelta current_timestamp, - base::TimeTicks current_time_ticks)); - MOCK_METHOD5(OnMediaMetadataChanged, - void(int player_id, - base::TimeDelta duration, - int width, - int height, - bool success)); - MOCK_METHOD1(OnPlaybackComplete, void(int player_id)); - MOCK_METHOD1(OnMediaInterrupted, void(int player_id)); - MOCK_METHOD2(OnBufferingUpdate, void(int player_id, int percentage)); - MOCK_METHOD2(OnSeekComplete, - void(int player_id, const base::TimeDelta& current_time)); - MOCK_METHOD2(OnError, void(int player_id, int error)); - MOCK_METHOD3(OnVideoSizeChanged, void(int player_id, int width, int height)); - MOCK_METHOD2(OnAudibleStateChanged, void(int player_id, bool is_audible_now)); - MOCK_METHOD1(GetPlayer, MediaPlayerAndroid*(int player_id)); - MOCK_METHOD3(RequestPlay, - bool(int player_id, base::TimeDelta duration, bool has_audio)); - - void OnMediaResourcesRequested(int player_id) {} + MOCK_METHOD1(OnMediaDurationChanged, void(base::TimeDelta duration)); + MOCK_METHOD0(OnPlaybackComplete, void()); + MOCK_METHOD1(OnError, void(int error)); + MOCK_METHOD2(OnVideoSizeChanged, void(int width, int height)); }; } // anonymous namespace @@ -48,63 +31,60 @@ class MediaPlayerBridgeTest : public testing::Test { public: MediaPlayerBridgeTest() - : bridge_(0, - GURL(), - GURL(), - "", - false, - &manager_, - base::Bind(&MockMediaPlayerManager::OnMediaResourcesRequested, - base::Unretained(&manager_)), - GURL(), - false) {} + : bridge_(GURL(), GURL(), "", false, &client_, false) {} - void SetCanSeekForward(bool can_seek_forward) { - bridge_.can_seek_forward_ = can_seek_forward; + protected: + void SimulateDurationChange(base::TimeDelta duration) { + bridge_.PropagateDuration(duration); } - void SetCanSeekBackward(bool can_seek_backward) { - bridge_.can_seek_backward_ = can_seek_backward; + void SimulateVideoSizeChanged(int width, int height) { + bridge_.OnVideoSizeChanged(width, height); } - bool SeekInternal(const base::TimeDelta& current_time, base::TimeDelta time) { - return bridge_.SeekInternal(current_time, time); - } + void SimulateError(int error) { bridge_.OnMediaError(error); } - private: + void SimulatePlaybackCompleted() { bridge_.OnPlaybackComplete(); } + // A message loop needs to be instantiated in order for the test to run // properly. base::MessageLoop message_loop_; - MockMediaPlayerManager manager_; + StrictMock<MockMediaPlayerBridgeClient> client_; MediaPlayerBridge bridge_; DISALLOW_COPY_AND_ASSIGN(MediaPlayerBridgeTest); }; -TEST_F(MediaPlayerBridgeTest, PreventForwardSeekWhenItIsNotPossible) { - // Simulate the Java MediaPlayerBridge reporting that forward seeks are not - // possible - SetCanSeekForward(false); - SetCanSeekBackward(true); +TEST_F(MediaPlayerBridgeTest, Client_OnMediaMetadataChanged) { + const base::TimeDelta kDuration = base::TimeDelta::FromSeconds(20); - // If this assertion fails, seeks will be allowed which will result in a - // crash because j_media_player_bridge_ cannot be properly instantiated - // during this test. - ASSERT_FALSE( - SeekInternal(base::TimeDelta(), base::TimeDelta::FromSeconds(10))); + EXPECT_CALL(client_, OnMediaDurationChanged(kDuration)); + + SimulateDurationChange(kDuration); } -TEST_F(MediaPlayerBridgeTest, PreventBackwardSeekWhenItIsNotPossible) { - // Simulate the Java MediaPlayerBridge reporting that backward seeks are not - // possible - SetCanSeekForward(true); - SetCanSeekBackward(false); +TEST_F(MediaPlayerBridgeTest, Client_OnVideoSizeChanged) { + const int kWidth = 1600; + const int kHeight = 900; - // If this assertion fails, seeks will be allowed which will result in a - // crash because j_media_player_bridge_ cannot be properly instantiated - // during this test. - ASSERT_FALSE( - SeekInternal(base::TimeDelta::FromSeconds(10), base::TimeDelta())); + EXPECT_CALL(client_, OnVideoSizeChanged(kWidth, kHeight)); + + SimulateVideoSizeChanged(kWidth, kHeight); +} + +TEST_F(MediaPlayerBridgeTest, Client_OnPlaybackComplete) { + EXPECT_CALL(client_, OnPlaybackComplete()); + + SimulatePlaybackCompleted(); +} + +TEST_F(MediaPlayerBridgeTest, Client_OnError) { + // MEDIA_ERROR_INVALID_CODE should still be propagated. + EXPECT_CALL(client_, OnError(_)).Times(1); + SimulateError(MediaPlayerBridge::MediaErrorType::MEDIA_ERROR_INVALID_CODE); + + EXPECT_CALL(client_, OnError(_)).Times(1); + SimulateError(MediaPlayerBridge::MediaErrorType::MEDIA_ERROR_FORMAT); } } // namespace media
diff --git a/media/base/android/media_player_listener.cc b/media/base/android/media_player_listener.cc index 16227a3..d26a832 100644 --- a/media/base/android/media_player_listener.cc +++ b/media/base/android/media_player_listener.cc
@@ -11,7 +11,7 @@ #include "base/logging.h" #include "base/single_thread_task_runner.h" #include "jni/MediaPlayerListener_jni.h" -#include "media/base/android/media_player_android.h" +#include "media/base/android/media_player_bridge.h" using base::android::AttachCurrentThread; using base::android::CheckException; @@ -23,9 +23,8 @@ MediaPlayerListener::MediaPlayerListener( const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, - base::WeakPtr<MediaPlayerAndroid> media_player) - : task_runner_(task_runner), - media_player_(media_player) { + base::WeakPtr<MediaPlayerBridge> media_player) + : task_runner_(task_runner), media_player_(media_player) { DCHECK(task_runner_.get()); DCHECK(media_player_); } @@ -49,9 +48,9 @@ void MediaPlayerListener::OnMediaError(JNIEnv* /* env */, const JavaParamRef<jobject>& /* obj */, jint error_type) { - task_runner_->PostTask(FROM_HERE, - base::BindOnce(&MediaPlayerAndroid::OnMediaError, - media_player_, error_type)); + task_runner_->PostTask( + FROM_HERE, base::BindOnce(&MediaPlayerBridge::OnMediaError, media_player_, + error_type)); } void MediaPlayerListener::OnVideoSizeChanged( @@ -60,33 +59,16 @@ jint width, jint height) { task_runner_->PostTask(FROM_HERE, - base::BindOnce(&MediaPlayerAndroid::OnVideoSizeChanged, + base::BindOnce(&MediaPlayerBridge::OnVideoSizeChanged, media_player_, width, height)); } -void MediaPlayerListener::OnBufferingUpdate( - JNIEnv* /* env */, - const JavaParamRef<jobject>& /* obj */, - jint percent) { - task_runner_->PostTask(FROM_HERE, - base::BindOnce(&MediaPlayerAndroid::OnBufferingUpdate, - media_player_, percent)); -} - void MediaPlayerListener::OnPlaybackComplete( JNIEnv* /* env */, const JavaParamRef<jobject>& /* obj */) { task_runner_->PostTask( FROM_HERE, - base::BindOnce(&MediaPlayerAndroid::OnPlaybackComplete, media_player_)); -} - -void MediaPlayerListener::OnSeekComplete( - JNIEnv* /* env */, - const JavaParamRef<jobject>& /* obj */) { - task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&MediaPlayerAndroid::OnSeekComplete, media_player_)); + base::BindOnce(&MediaPlayerBridge::OnPlaybackComplete, media_player_)); } void MediaPlayerListener::OnMediaPrepared( @@ -94,15 +76,7 @@ const JavaParamRef<jobject>& /* obj */) { task_runner_->PostTask( FROM_HERE, - base::BindOnce(&MediaPlayerAndroid::OnMediaPrepared, media_player_)); -} - -void MediaPlayerListener::OnMediaInterrupted( - JNIEnv* /* env */, - const JavaParamRef<jobject>& /* obj */) { - task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&MediaPlayerAndroid::OnMediaInterrupted, media_player_)); + base::BindOnce(&MediaPlayerBridge::OnMediaPrepared, media_player_)); } } // namespace media
diff --git a/media/base/android/media_player_listener.h b/media/base/android/media_player_listener.h index 6e81368d..8c7c5ed 100644 --- a/media/base/android/media_player_listener.h +++ b/media/base/android/media_player_listener.h
@@ -18,10 +18,10 @@ namespace media { -class MediaPlayerAndroid; +class MediaPlayerBridge; // Acts as a thread proxy between java MediaPlayerListener object and -// MediaPlayerAndroid so that callbacks are posted onto the UI thread. +// MediaPlayerBridge so that callbacks are posted onto the UI thread. class MediaPlayerListener { public: // Construct a native MediaPlayerListener object. Callbacks from the java @@ -29,7 +29,7 @@ // |task_runner|. MediaPlayerListener( const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, - base::WeakPtr<MediaPlayerAndroid> media_player); + base::WeakPtr<MediaPlayerBridge> media_player); virtual ~MediaPlayerListener(); // Called by the Java MediaPlayerListener and mirrored to corresponding @@ -47,13 +47,8 @@ void OnPlaybackComplete( JNIEnv* /* env */, const base::android::JavaParamRef<jobject>& /* obj */); - void OnSeekComplete(JNIEnv* /* env */, - const base::android::JavaParamRef<jobject>& /* obj */); void OnMediaPrepared(JNIEnv* /* env */, const base::android::JavaParamRef<jobject>& /* obj */); - void OnMediaInterrupted( - JNIEnv* /* env */, - const base::android::JavaParamRef<jobject>& /* obj */); // Create a Java MediaPlayerListener object and listens to all the media // related events from system and |media_player|. If |media_player| is NULL, @@ -66,8 +61,8 @@ // The message loop where |media_player_| lives. scoped_refptr<base::SingleThreadTaskRunner> task_runner_; - // The MediaPlayerAndroid object all the callbacks should be sent to. - base::WeakPtr<MediaPlayerAndroid> media_player_; + // The MediaPlayerBridge object all the callbacks should be sent to. + base::WeakPtr<MediaPlayerBridge> media_player_; base::android::ScopedJavaGlobalRef<jobject> j_media_player_listener_;
diff --git a/media/base/android/media_player_manager.h b/media/base/android/media_player_manager.h deleted file mode 100644 index 9c76414..0000000 --- a/media/base/android/media_player_manager.h +++ /dev/null
@@ -1,78 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MEDIA_BASE_ANDROID_MEDIA_PLAYER_MANAGER_H_ -#define MEDIA_BASE_ANDROID_MEDIA_PLAYER_MANAGER_H_ - -#include "base/time/time.h" -#include "media/base/media_export.h" - -namespace media { - -class MediaPlayerAndroid; -class MediaResourceGetter; -class MediaUrlInterceptor; - -// This class is responsible for managing active MediaPlayerAndroid objects. -class MEDIA_EXPORT MediaPlayerManager { - public: - virtual ~MediaPlayerManager() {} - - // Returns a pointer to the MediaResourceGetter object. - virtual MediaResourceGetter* GetMediaResourceGetter() = 0; - - // Returns a pointer to the MediaUrlInterceptor object or null. - virtual MediaUrlInterceptor* GetMediaUrlInterceptor() = 0; - - // Called when time update messages need to be sent. Args: player ID, - // current timestamp, current time ticks. - virtual void OnTimeUpdate(int player_id, - base::TimeDelta current_timestamp, - base::TimeTicks current_time_ticks) = 0; - - // Called when media metadata changed. Args: player ID, duration of the - // media, width, height, whether the metadata is successfully extracted. - virtual void OnMediaMetadataChanged( - int player_id, - base::TimeDelta duration, - int width, - int height, - bool success) = 0; - - // Called when playback completed. Args: player ID. - virtual void OnPlaybackComplete(int player_id) = 0; - - // Called when media download was interrupted. Args: player ID. - virtual void OnMediaInterrupted(int player_id) = 0; - - // Called when buffering has changed. Args: player ID, percentage - // of the media. - virtual void OnBufferingUpdate(int player_id, int percentage) = 0; - - // Called when seek completed. Args: player ID, current time. - virtual void OnSeekComplete( - int player_id, - const base::TimeDelta& current_time) = 0; - - // Called when error happens. Args: player ID, error type. - virtual void OnError(int player_id, int error) = 0; - - // Called when video size has changed. Args: player ID, width, height. - virtual void OnVideoSizeChanged(int player_id, int width, int height) = 0; - - // Returns the player with the specified id. - virtual MediaPlayerAndroid* GetPlayer(int player_id) = 0; - - // Called by the player to request the playback for given duration. The - // manager should use this opportunity to check if the current context is - // appropriate for a media to play. - // Returns whether the request was granted. - virtual bool RequestPlay(int player_id, - base::TimeDelta duration, - bool has_audio) = 0; -}; - -} // namespace media - -#endif // MEDIA_BASE_ANDROID_MEDIA_PLAYER_MANAGER_H_
diff --git a/media/base/test_helpers.h b/media/base/test_helpers.h index c581531a..7d8eb7865 100644 --- a/media/base/test_helpers.h +++ b/media/base/test_helpers.h
@@ -311,8 +311,8 @@ MATCHER_P2(AudioNonKeyframe, pts_microseconds, dts_microseconds, "") { return CONTAINS_STRING( arg, std::string("Bytestream with audio frame PTS ") + - base::IntToString(pts_microseconds) + "us and DTS " + - base::IntToString(dts_microseconds) + + base::NumberToString(pts_microseconds) + "us and DTS " + + base::NumberToString(dts_microseconds) + "us indicated the frame is not a random access point (key " "frame). All audio frames are expected to be key frames."); } @@ -323,15 +323,15 @@ "") { return CONTAINS_STRING( arg, "Skipping splice frame generation: first new buffer at " + - base::IntToString(new_microseconds) + + base::NumberToString(new_microseconds) + "us begins at or before existing buffer at " + - base::IntToString(existing_microseconds) + "us."); + base::NumberToString(existing_microseconds) + "us."); } MATCHER_P(SkippingSpliceAlreadySpliced, time_microseconds, "") { return CONTAINS_STRING( arg, "Skipping splice frame generation: overlapped buffers at " + - base::IntToString(time_microseconds) + + base::NumberToString(time_microseconds) + "us are in a previously buffered splice."); } @@ -341,8 +341,8 @@ "") { return CONTAINS_STRING( arg, "Skipping audio splice trimming at PTS=" + - base::IntToString(pts_microseconds) + "us. Found only " + - base::IntToString(overlap_microseconds) + + base::NumberToString(pts_microseconds) + "us. Found only " + + base::NumberToString(overlap_microseconds) + "us of overlap, need at least 1000us. Multiple occurrences may " "result in loss of A/V sync."); } @@ -355,7 +355,7 @@ MATCHER_P(WebMSimpleBlockDurationEstimated, estimated_duration_ms, "") { return CONTAINS_STRING(arg, "Estimating WebM block duration=" + - base::IntToString(estimated_duration_ms)); + base::NumberToString(estimated_duration_ms)); } MATCHER_P(WebMNegativeTimecodeOffset, timecode_string, "") { @@ -378,17 +378,19 @@ trim_duration_us, "") { return CONTAINS_STRING( - arg, "Audio buffer splice at PTS=" + base::IntToString(splice_time_us) + - "us. Trimmed tail of overlapped buffer (PTS=" + - base::IntToString(overlapped_start_us) + "us) by " + - base::IntToString(trim_duration_us)); + arg, + "Audio buffer splice at PTS=" + base::NumberToString(splice_time_us) + + "us. Trimmed tail of overlapped buffer (PTS=" + + base::NumberToString(overlapped_start_us) + "us) by " + + base::NumberToString(trim_duration_us)); } MATCHER_P2(NoSpliceForBadMux, overlapped_buffer_count, splice_time_us, "") { - return CONTAINS_STRING(arg, "Media is badly muxed. Detected " + - base::IntToString(overlapped_buffer_count) + - " overlapping audio buffers at time " + - base::IntToString(splice_time_us)); + return CONTAINS_STRING(arg, + "Media is badly muxed. Detected " + + base::NumberToString(overlapped_buffer_count) + + " overlapping audio buffers at time " + + base::NumberToString(splice_time_us)); } MATCHER_P(BufferingByPtsDts, by_pts_bool, "") { @@ -399,8 +401,8 @@ MATCHER_P3(NegativeDtsFailureWhenByDts, frame_type, pts_us, dts_us, "") { return CONTAINS_STRING( arg, std::string(frame_type) + " frame with PTS " + - base::IntToString(pts_us) + "us has negative DTS " + - base::IntToString(dts_us) + + base::NumberToString(pts_us) + "us has negative DTS " + + base::NumberToString(dts_us) + "us after applying timestampOffset, handling any discontinuity, " "and filtering against append window"); } @@ -408,8 +410,8 @@ MATCHER_P2(DiscardingEmptyFrame, pts_us, dts_us, "") { return CONTAINS_STRING(arg, "Discarding empty audio or video coded frame, PTS=" + - base::IntToString(pts_us) + - "us, DTS=" + base::IntToString(dts_us) + "us"); + base::NumberToString(pts_us) + + "us, DTS=" + base::NumberToString(dts_us) + "us"); } MATCHER_P4(TruncatedFrame, @@ -429,7 +431,7 @@ MATCHER_P2(DroppedFrame, frame_type, pts_us, "") { return CONTAINS_STRING(arg, "Dropping " + std::string(frame_type) + " frame") && - CONTAINS_STRING(arg, "PTS " + base::IntToString(pts_us)); + CONTAINS_STRING(arg, "PTS " + base::NumberToString(pts_us)); } MATCHER_P3(DroppedFrameCheckAppendWindow, @@ -441,8 +443,8 @@ "Dropping " + std::string(frame_type) + " frame") && CONTAINS_STRING( arg, "outside append window [" + - base::Int64ToString(append_window_start_us) + "us," + - base::Int64ToString(append_window_end_us) + "us"); + base::NumberToString(append_window_start_us) + "us," + + base::NumberToString(append_window_end_us) + "us"); } } // namespace media
diff --git a/media/base/video_frame_metadata.cc b/media/base/video_frame_metadata.cc index c567846a3..19d3efbf 100644 --- a/media/base/video_frame_metadata.cc +++ b/media/base/video_frame_metadata.cc
@@ -17,7 +17,7 @@ // Map enum key to internal std::string key used by base::DictionaryValue. inline std::string ToInternalKey(VideoFrameMetadata::Key key) { DCHECK_LT(key, VideoFrameMetadata::NUM_KEYS); - return base::IntToString(static_cast<int>(key)); + return base::NumberToString(static_cast<int>(key)); } } // namespace
diff --git a/media/blink/multibuffer_data_source_unittest.cc b/media/blink/multibuffer_data_source_unittest.cc index 421ecba8..d9f5c36 100644 --- a/media/blink/multibuffer_data_source_unittest.cc +++ b/media/blink/multibuffer_data_source_unittest.cc
@@ -1478,7 +1478,7 @@ response.SetHTTPStatusCode(200); response.SetHTTPHeaderField( WebString::FromUTF8("Content-Length"), - WebString::FromUTF8(base::Int64ToString(kDataSize / 2))); + WebString::FromUTF8(base::NumberToString(kDataSize / 2))); response.SetExpectedContentLength(kDataSize / 2); Respond(response); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize / 2));
diff --git a/media/blink/test_response_generator.cc b/media/blink/test_response_generator.cc index 46a9285..b9b3296c6 100644 --- a/media/blink/test_response_generator.cc +++ b/media/blink/test_response_generator.cc
@@ -31,7 +31,7 @@ response.SetHTTPHeaderField( WebString::FromUTF8("Content-Length"), - WebString::FromUTF8(base::Int64ToString(content_length_))); + WebString::FromUTF8(base::NumberToString(content_length_))); response.SetExpectedContentLength(content_length_); return response; } @@ -80,7 +80,7 @@ if ((flags & kNoContentLength) == 0) { response.SetHTTPHeaderField( WebString::FromUTF8("Content-Length"), - WebString::FromUTF8(base::Int64ToString(range_content_length))); + WebString::FromUTF8(base::NumberToString(range_content_length))); response.SetExpectedContentLength(range_content_length); } return response;
diff --git a/media/blink/webmediacapabilitiesclient_impl.cc b/media/blink/webmediacapabilitiesclient_impl.cc index 69e7783e..f234b4e1 100644 --- a/media/blink/webmediacapabilitiesclient_impl.cc +++ b/media/blink/webmediacapabilitiesclient_impl.cc
@@ -9,18 +9,15 @@ #include "base/bind.h" #include "base/bind_helpers.h" -#include "media/base/audio_codecs.h" #include "media/base/key_system_names.h" #include "media/base/mime_util.h" #include "media/base/supported_types.h" #include "media/base/video_codecs.h" #include "media/base/video_color_space.h" #include "media/blink/webcontentdecryptionmoduleaccess_impl.h" -#include "media/filters/stream_parser_factory.h" #include "media/mojo/interfaces/media_types.mojom.h" #include "mojo/public/cpp/bindings/associated_interface_ptr.h" #include "services/service_manager/public/cpp/connector.h" -#include "third_party/blink/public/platform/modules/media_capabilities/web_audio_configuration.h" #include "third_party/blink/public/platform/modules/media_capabilities/web_media_capabilities_info.h" #include "third_party/blink/public/platform/modules/media_capabilities/web_media_decoding_configuration.h" #include "third_party/blink/public/platform/modules/media_capabilities/web_video_configuration.h" @@ -66,54 +63,6 @@ return video_supported; } -bool CheckMseSupport(const blink::WebMediaConfiguration& configuration) { - DCHECK_EQ(blink::MediaConfigurationType::kMediaSource, configuration.type); - - // For MSE queries, we assume the queried audio and video streams will be - // placed into separate source buffers. - // TODO(chcunningham): Clarify this assumption in the spec. - - // Media MIME API expects a vector of codec strings. We query audio and video - // separately, so |codec_string|.size() should always be 1 or 0 (when no - // codecs parameter is required for the given mime type). - std::vector<std::string> codec_vector; - - if (configuration.audio_configuration) { - const blink::WebAudioConfiguration& audio_config = - configuration.audio_configuration.value(); - - if (!audio_config.codec.Ascii().empty()) - codec_vector.push_back(audio_config.codec.Ascii()); - - if (!media::StreamParserFactory::IsTypeSupported( - audio_config.mime_type.Ascii(), codec_vector)) { - DVLOG(2) << __func__ << " MSE does not support audio config: " - << audio_config.mime_type.Ascii() << " " - << (codec_vector.empty() ? "" : codec_vector[1]); - return false; - } - } - - if (configuration.video_configuration) { - const blink::WebVideoConfiguration& video_config = - configuration.video_configuration.value(); - - codec_vector.clear(); - if (!video_config.codec.Ascii().empty()) - codec_vector.push_back(video_config.codec.Ascii()); - - if (!media::StreamParserFactory::IsTypeSupported( - video_config.mime_type.Ascii(), codec_vector)) { - DVLOG(2) << __func__ << " MSE does not support video config: " - << video_config.mime_type.Ascii() << " " - << (codec_vector.empty() ? "" : codec_vector[1]); - return false; - } - } - - return true; -} - WebMediaCapabilitiesClientImpl::WebMediaCapabilitiesClientImpl() = default; WebMediaCapabilitiesClientImpl::~WebMediaCapabilitiesClientImpl() = default; @@ -145,22 +94,6 @@ std::unique_ptr<blink::WebMediaCapabilitiesDecodingInfo> info( new blink::WebMediaCapabilitiesDecodingInfo()); - // MSE support is cheap to check (regex matching). Do it first. - if (configuration.type == blink::MediaConfigurationType::kMediaSource && - !CheckMseSupport(configuration)) { - info->supported = info->smooth = info->power_efficient = false; - callbacks->OnSuccess(std::move(info)); - return; - } - - // Audio-only checks should stop here. - // TODO: remove when MSE checks more to Blink. - if (!configuration.video_configuration) { - info->supported = info->smooth = info->power_efficient = true; - callbacks->OnSuccess(std::move(info)); - return; - } - DCHECK(configuration.video_configuration); const blink::WebVideoConfiguration& video_config = configuration.video_configuration.value();
diff --git a/media/blink/websourcebuffer_impl.cc b/media/blink/websourcebuffer_impl.cc index 2c65678..dc5c56ce 100644 --- a/media/blink/websourcebuffer_impl.cc +++ b/media/blink/websourcebuffer_impl.cc
@@ -226,7 +226,7 @@ trackInfo.track_type = mediaTrackTypeToBlink(track->type()); trackInfo.id = blink::WebString::FromUTF8(track->id()); trackInfo.byte_stream_track_id = blink::WebString::FromUTF8( - base::UintToString(track->bytestream_track_id())); + base::NumberToString(track->bytestream_track_id())); trackInfo.kind = blink::WebString::FromUTF8(track->kind()); trackInfo.label = blink::WebString::FromUTF8(track->label()); trackInfo.language = blink::WebString::FromUTF8(track->language());
diff --git a/media/capture/video/android/video_capture_device_factory_android.cc b/media/capture/video/android/video_capture_device_factory_android.cc index ae4e875..4a7e12c 100644 --- a/media/capture/video/android/video_capture_device_factory_android.cc +++ b/media/capture/video/android/video_capture_device_factory_android.cc
@@ -74,7 +74,7 @@ Java_VideoCaptureFactory_getFacingMode(env, camera_id); const std::string display_name = base::android::ConvertJavaStringToUTF8(device_name); - const std::string device_id = base::IntToString(camera_id); + const std::string device_id = base::NumberToString(camera_id); // Android cameras are not typically USB devices, and the model_id is // currently only used for USB model identifiers, so this implementation
diff --git a/media/cdm/cdm_adapter_unittest.cc b/media/cdm/cdm_adapter_unittest.cc index 771161fc..123cb8f 100644 --- a/media/cdm/cdm_adapter_unittest.cc +++ b/media/cdm/cdm_adapter_unittest.cc
@@ -121,7 +121,7 @@ CdmAdapterTestBase() { base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kOverrideEnabledCdmInterfaceVersion, - base::IntToString(GetCdmInterfaceVersion())); + base::NumberToString(GetCdmInterfaceVersion())); } ~CdmAdapterTestBase() override { CdmModule::ResetInstanceForTesting(); }
diff --git a/media/filters/chunk_demuxer.cc b/media/filters/chunk_demuxer.cc index 39cc4a12..d928477 100644 --- a/media/filters/chunk_demuxer.cc +++ b/media/filters/chunk_demuxer.cc
@@ -1337,7 +1337,7 @@ // static MediaTrack::Id ChunkDemuxer::GenerateMediaTrackId() { static unsigned g_track_count = 0; - return base::UintToString(++g_track_count); + return base::NumberToString(++g_track_count); } ChunkDemuxerStream* ChunkDemuxer::CreateDemuxerStream(
diff --git a/media/filters/ffmpeg_demuxer.cc b/media/filters/ffmpeg_demuxer.cc index d4e784b..e474785 100644 --- a/media/filters/ffmpeg_demuxer.cc +++ b/media/filters/ffmpeg_demuxer.cc
@@ -1438,7 +1438,7 @@ media_track = media_tracks->AddAudioTrack(audio_config, track_id, "main", track_label, track_language); - media_track->set_id(base::UintToString(track_id)); + media_track->set_id(base::NumberToString(track_id)); DCHECK(track_id_to_demux_stream_map_.find(media_track->id()) == track_id_to_demux_stream_map_.end()); track_id_to_demux_stream_map_[media_track->id()] = streams_[i].get(); @@ -1450,7 +1450,7 @@ media_track = media_tracks->AddVideoTrack(video_config, track_id, "main", track_label, track_language); - media_track->set_id(base::UintToString(track_id)); + media_track->set_id(base::NumberToString(track_id)); DCHECK(track_id_to_demux_stream_map_.find(media_track->id()) == track_id_to_demux_stream_map_.end()); track_id_to_demux_stream_map_[media_track->id()] = streams_[i].get(); @@ -1603,7 +1603,7 @@ ++audio_track_count; std::string suffix = ""; if (audio_track_count > 1) - suffix = "_track" + base::IntToString(audio_track_count); + suffix = "_track" + base::NumberToString(audio_track_count); const AVCodecParameters* audio_parameters = avctx->streams[i]->codecpar; const AudioDecoderConfig& audio_config = stream->audio_decoder_config(); params.SetString("audio_codec_name" + suffix, @@ -1618,7 +1618,7 @@ ++video_track_count; std::string suffix = ""; if (video_track_count > 1) - suffix = "_track" + base::IntToString(video_track_count); + suffix = "_track" + base::NumberToString(video_track_count); const AVStream* video_av_stream = avctx->streams[i]; const AVCodecParameters* video_parameters = video_av_stream->codecpar; const VideoDecoderConfig& video_config = stream->video_decoder_config();
diff --git a/media/filters/source_buffer_state_unittest.cc b/media/filters/source_buffer_state_unittest.cc index 04fe3fe..95163e3 100644 --- a/media/filters/source_buffer_state_unittest.cc +++ b/media/filters/source_buffer_state_unittest.cc
@@ -146,7 +146,7 @@ ChunkDemuxerStream* CreateDemuxerStream(DemuxerStream::Type type) { static unsigned track_id = 0; demuxer_streams_.push_back(base::WrapUnique(new ChunkDemuxerStream( - type, base::UintToString(++track_id), range_api_))); + type, base::NumberToString(++track_id), range_api_))); return demuxer_streams_.back().get(); }
diff --git a/media/filters/source_buffer_stream_unittest.cc b/media/filters/source_buffer_stream_unittest.cc index c4b9f111..8ffcce6 100644 --- a/media/filters/source_buffer_stream_unittest.cc +++ b/media/filters/source_buffer_stream_unittest.cc
@@ -70,7 +70,7 @@ "Media append that overlapped current playback " "position caused time gap in playing VIDEO stream " "because the next keyframe is " + - base::IntToString(skip_milliseconds) + + base::NumberToString(skip_milliseconds) + "ms beyond last overlapped frame. Media may " "appear temporarily frozen."); }
diff --git a/media/filters/video_decoder_stream_unittest.cc b/media/filters/video_decoder_stream_unittest.cc index 3dc02e3..2c2d419 100644 --- a/media/filters/video_decoder_stream_unittest.cc +++ b/media/filters/video_decoder_stream_unittest.cc
@@ -44,7 +44,7 @@ const int kNumBuffersInOneConfig = 5; static std::string GetDecoderName(int i) { - return std::string("VideoDecoder") + base::IntToString(i); + return std::string("VideoDecoder") + base::NumberToString(i); } struct VideoDecoderStreamTestParams {
diff --git a/media/formats/webm/webm_cluster_parser_unittest.cc b/media/formats/webm/webm_cluster_parser_unittest.cc index ddacc0d5..197df7a4 100644 --- a/media/formats/webm/webm_cluster_parser_unittest.cc +++ b/media/formats/webm/webm_cluster_parser_unittest.cc
@@ -43,7 +43,7 @@ MATCHER_P(OpusPacketDurationTooHigh, actual_duration_ms, "") { return CONTAINS_STRING( arg, "Warning, demuxed Opus packet with encoded duration: " + - base::IntToString(actual_duration_ms) + + base::NumberToString(static_cast<int64_t>(actual_duration_ms)) + "ms. Should be no greater than 120ms."); } @@ -52,9 +52,11 @@ opus_duration_ms, "") { return CONTAINS_STRING( - arg, "BlockDuration (" + base::IntToString(block_duration_ms) + + arg, "BlockDuration (" + + base::NumberToString(static_cast<int64_t>(block_duration_ms)) + "ms) differs significantly from encoded duration (" + - base::IntToString(opus_duration_ms) + "ms)."); + base::NumberToString(static_cast<int64_t>(opus_duration_ms)) + + "ms)."); } namespace {
diff --git a/media/formats/webm/webm_content_encodings_client_unittest.cc b/media/formats/webm/webm_content_encodings_client_unittest.cc index 9dcc12c..65f81937 100644 --- a/media/formats/webm/webm_content_encodings_client_unittest.cc +++ b/media/formats/webm/webm_content_encodings_client_unittest.cc
@@ -45,7 +45,7 @@ MATCHER_P(UnexpectedContentEncAlgo, algo, "") { return CONTAINS_STRING( - arg, "Unexpected ContentEncAlgo " + base::IntToString(algo) + "."); + arg, "Unexpected ContentEncAlgo " + base::NumberToString(algo) + "."); } class WebMContentEncodingsClientTest : public testing::Test {
diff --git a/media/formats/webm/webm_tracks_parser.cc b/media/formats/webm/webm_tracks_parser.cc index e3941ae..59838d9 100644 --- a/media/formats/webm/webm_tracks_parser.cc +++ b/media/formats/webm/webm_tracks_parser.cc
@@ -266,7 +266,7 @@ MEDIA_LOG(DEBUG, media_log_) << "Ignoring text track " << track_num_; ignored_tracks_.insert(track_num_); } else { - std::string track_num = base::Int64ToString(track_num_); + std::string track_num = base::NumberToString(track_num_); text_tracks_[track_num_] = TextTrackConfig( text_track_kind, track_name_, track_language_, track_num); }
diff --git a/media/gpu/h264_decoder.cc b/media/gpu/h264_decoder.cc index 0fa01797..73dcb62 100644 --- a/media/gpu/h264_decoder.cc +++ b/media/gpu/h264_decoder.cc
@@ -1425,10 +1425,7 @@ size_t H264Decoder::GetNumReferenceFrames() const { // Use the maximum number of pictures in the Decoded Picture Buffer plus one // for the one being currently egressed. - // Another +1 is experimentally needed for high-to-high resolution changes. - // TODO(mcasas): Figure out why +2 instead of +1, see crbug.com/909926 and - // http://crrev.com/c/1363807/9/media/gpu/h264_decoder.cc#1449. - return dpb_.max_num_pics() + 2; + return dpb_.max_num_pics() + 1; } // static
diff --git a/media/gpu/jpeg_encode_accelerator_unittest.cc b/media/gpu/jpeg_encode_accelerator_unittest.cc index 920e5c2e..f6fe7bcc 100644 --- a/media/gpu/jpeg_encode_accelerator_unittest.cc +++ b/media/gpu/jpeg_encode_accelerator_unittest.cc
@@ -371,9 +371,9 @@ &sw_encoded_size, &elapsed_sw)); g_env->LogToFile("hw_encode_time", - base::Int64ToString(elapsed_hw.InMicroseconds())); + base::NumberToString(elapsed_hw.InMicroseconds())); g_env->LogToFile("sw_encode_time", - base::Int64ToString(elapsed_sw.InMicroseconds())); + base::NumberToString(elapsed_sw.InMicroseconds())); if (g_save_to_file) { SaveToFile(test_image, hw_encoded_size, sw_encoded_size);
diff --git a/media/gpu/test/video_frame_file_writer.cc b/media/gpu/test/video_frame_file_writer.cc index 12c55118..fd8af99 100644 --- a/media/gpu/test/video_frame_file_writer.cc +++ b/media/gpu/test/video_frame_file_writer.cc
@@ -123,7 +123,7 @@ { base::AutoLock auto_lock(frame_writer_lock_); filename = output_folder_.Append("frame_.png") - .InsertBeforeExtension(base::IntToString(frame_index)); + .InsertBeforeExtension(base::NumberToString(frame_index)); } // Write the PNG data to file.
diff --git a/media/gpu/vaapi/vaapi_video_decode_accelerator.cc b/media/gpu/vaapi/vaapi_video_decode_accelerator.cc index b58943f..0a62f89 100644 --- a/media/gpu/vaapi/vaapi_video_decode_accelerator.cc +++ b/media/gpu/vaapi/vaapi_video_decode_accelerator.cc
@@ -536,13 +536,19 @@ // If we are in BufferAllocationMode::kNone, split the requested |num_pics| // between VA reference frames and client PictureBuffers proper. - if (buffer_allocation_mode_ == BufferAllocationMode::kReduced) + if (IsBufferAllocationModeReducedOrSuperReduced()) requested_num_reference_frames_ = num_reference_frames; else requested_num_reference_frames_ = 0; requested_num_pics_ = num_pics - requested_num_reference_frames_; + // Add an extra allocation for |client_| and |decoder_| in the kReduced case. + if (buffer_allocation_mode_ == BufferAllocationMode::kReduced) { + requested_num_reference_frames_++; + requested_num_pics_++; + } + VLOGF(2) << " |requested_num_pics_| = " << requested_num_pics_ << "; |requested_num_reference_frames_| = " << requested_num_reference_frames_; @@ -558,7 +564,7 @@ base::AutoLock auto_lock(lock_); const size_t expected_max_available_va_surfaces = - buffer_allocation_mode_ == BufferAllocationMode::kReduced + IsBufferAllocationModeReducedOrSuperReduced() ? previously_requested_num_reference_frames_ : pictures_.size(); @@ -703,7 +709,7 @@ DCHECK_EQ(va_surface_ids.size(), buffers.size()); } else { const size_t requested_num_surfaces = - buffer_allocation_mode_ == BufferAllocationMode::kReduced + IsBufferAllocationModeReducedOrSuperReduced() ? requested_num_reference_frames_ : pictures_.size(); CHECK_NE(requested_num_surfaces, 0u); @@ -1027,7 +1033,7 @@ available_va_surfaces_.pop_front(); TRACE_COUNTER_ID2("media,gpu", "Vaapi VASurfaceIDs", this, "used", - (buffer_allocation_mode_ == BufferAllocationMode::kReduced + (IsBufferAllocationModeReducedOrSuperReduced() ? requested_num_reference_frames_ : pictures_.size()) - available_va_surfaces_.size(), @@ -1066,13 +1072,12 @@ base::AutoLock auto_lock(lock_); available_va_surfaces_.push_back(va_surface_id); if (buffer_allocation_mode_ != BufferAllocationMode::kNone) { - TRACE_COUNTER_ID2( - "media,gpu", "Vaapi VASurfaceIDs", this, "used", - (buffer_allocation_mode_ == BufferAllocationMode::kReduced - ? requested_num_reference_frames_ - : pictures_.size()) - - available_va_surfaces_.size(), - "available", available_va_surfaces_.size()); + TRACE_COUNTER_ID2("media,gpu", "Vaapi VASurfaceIDs", this, "used", + (IsBufferAllocationModeReducedOrSuperReduced() + ? requested_num_reference_frames_ + : pictures_.size()) - + available_va_surfaces_.size(), + "available", available_va_surfaces_.size()); } surfaces_available_.Signal(); } @@ -1087,7 +1092,7 @@ } VaapiVideoDecodeAccelerator::BufferAllocationMode -VaapiVideoDecodeAccelerator::DecideBufferAllocationMode() { +VaapiVideoDecodeAccelerator::DecideBufferAllocationMode() const { // TODO(crbug.com/912295): Enable a better BufferAllocationMode for IMPORT // |output_mode_| as well. if (output_mode_ == VideoDecodeAccelerator::Config::OutputMode::IMPORT) @@ -1110,12 +1115,25 @@ // request the |client_| to allocate less than the usual |decoder_|s // GetRequiredNumOfPictures(). // TODO(crbug.com/912295): enable for previous architectures. - if (IsSkyLakeOrLater()) - return BufferAllocationMode::kReduced; + if (IsSkyLakeOrLater()) { + // Another +1 is experimentally needed for high-to-high resolution changes. + // TODO(mcasas): Figure out why and why only H264, see crbug.com/912295 and + // http://crrev.com/c/1363807/9/media/gpu/h264_decoder.cc#1449. + if (profile_ >= H264PROFILE_MIN && profile_ <= H264PROFILE_MAX) + return BufferAllocationMode::kReduced; + + return BufferAllocationMode::kSuperReduced; + } return BufferAllocationMode::kNormal; } +bool VaapiVideoDecodeAccelerator::IsBufferAllocationModeReducedOrSuperReduced() + const { + return buffer_allocation_mode_ == BufferAllocationMode::kSuperReduced || + buffer_allocation_mode_ == BufferAllocationMode::kReduced; +} + bool VaapiVideoDecodeAccelerator::OnMemoryDump( const base::trace_event::MemoryDumpArgs& args, base::trace_event::ProcessMemoryDump* pmd) { @@ -1142,7 +1160,7 @@ // calculated size is an estimation since we don't know the internal VA // strides, texture compression, headers, etc, but is a good lower boundary. const size_t requested_num_surfaces = - buffer_allocation_mode_ == BufferAllocationMode::kReduced + IsBufferAllocationModeReducedOrSuperReduced() ? requested_num_reference_frames_ : pictures_.size(); dump->AddScalar(MemoryAllocatorDump::kNameSize,
diff --git a/media/gpu/vaapi/vaapi_video_decode_accelerator.h b/media/gpu/vaapi/vaapi_video_decode_accelerator.h index 22d0c29..adb79cc 100644 --- a/media/gpu/vaapi/vaapi_video_decode_accelerator.h +++ b/media/gpu/vaapi/vaapi_video_decode_accelerator.h
@@ -194,6 +194,9 @@ kNone, // Using a reduced amount of |client_|s provided PictureBuffers and // |decoder_|s GetNumReferenceFrames() internallly. + kSuperReduced, + // Similar to kSuperReduced, but we have to increase slightly the amount of + // PictureBuffers allocated for the |client_|. kReduced, // Using |client_|s provided PictureBuffers and as many internally // allocated. @@ -202,7 +205,8 @@ // Decides the concrete buffer allocation mode, depending on the hardware // platform and other parameters. - BufferAllocationMode DecideBufferAllocationMode(); + BufferAllocationMode DecideBufferAllocationMode() const; + bool IsBufferAllocationModeReducedOrSuperReduced() const; // VAVDA state. enum State {
diff --git a/media/gpu/vaapi/vaapi_video_decode_accelerator_unittest.cc b/media/gpu/vaapi/vaapi_video_decode_accelerator_unittest.cc index 9091772..c32265ef 100644 --- a/media/gpu/vaapi/vaapi_video_decode_accelerator_unittest.cc +++ b/media/gpu/vaapi/vaapi_video_decode_accelerator_unittest.cc
@@ -171,7 +171,7 @@ vda_.buffer_allocation_mode_ = GetParam().decode_using_client_picture_buffers ? VaapiVideoDecodeAccelerator::BufferAllocationMode::kNone - : VaapiVideoDecodeAccelerator::BufferAllocationMode::kReduced; + : VaapiVideoDecodeAccelerator::BufferAllocationMode::kSuperReduced; vda_.state_ = VaapiVideoDecodeAccelerator::kIdle; } @@ -238,7 +238,7 @@ const size_t expected_num_picture_buffers_requested = vda_.buffer_allocation_mode_ == - VaapiVideoDecodeAccelerator::BufferAllocationMode::kReduced + VaapiVideoDecodeAccelerator::BufferAllocationMode::kSuperReduced ? num_pictures - kNumReferenceFrames : num_pictures;
diff --git a/media/gpu/windows/d3d11_cdm_proxy.cc b/media/gpu/windows/d3d11_cdm_proxy.cc index b188fc5..930da80 100644 --- a/media/gpu/windows/d3d11_cdm_proxy.cc +++ b/media/gpu/windows/d3d11_cdm_proxy.cc
@@ -163,7 +163,7 @@ // Return true on success. bool RegisterHardwareContentProtectionTeardown(ComPtr<ID3D11Device> device); - // Regiesters for power events, specifically power suspend event. + // Regiesters for power events, specifically power resume event. // Returns true on success. bool RegisterPowerEvents(); @@ -172,7 +172,7 @@ // base::PowerObserver implementation. Other power events are not relevant to // this class. - void OnSuspend() override; + void OnResume() override; // Stops watching for events. Good for clean up. void StopWatching(); @@ -543,6 +543,26 @@ void D3D11CdmProxy::NotifyHardwareContentProtectionTeardown() { cdm_context_->OnHardwareReset(); client_->NotifyHardwareReset(); + Reset(); +} + +void D3D11CdmProxy::Reset() { + client_ = nullptr; + initialized_ = false; + crypto_session_map_.clear(); + device_.Reset(); + device_context_.Reset(); + video_device_.Reset(); + video_device1_.Reset(); + video_context_.Reset(); + video_context1_.Reset(); + // Note that this deregisters hardware reset event watcher. It shouldn't + // notify the clients until this is reinitialized. Also the client is set to + // null in this method. + hardware_event_watcher_ = nullptr; + crypto_session_map_.clear(); + private_input_size_ = 0; + private_output_size_ = 0; } D3D11CdmProxy::HardwareEventWatcher::~HardwareEventWatcher() { @@ -627,7 +647,7 @@ teardown_callback_.Run(); } -void D3D11CdmProxy::HardwareEventWatcher::OnSuspend() { +void D3D11CdmProxy::HardwareEventWatcher::OnResume() { teardown_callback_.Run(); }
diff --git a/media/gpu/windows/d3d11_cdm_proxy.h b/media/gpu/windows/d3d11_cdm_proxy.h index 1fb77103f..8b62d2f 100644 --- a/media/gpu/windows/d3d11_cdm_proxy.h +++ b/media/gpu/windows/d3d11_cdm_proxy.h
@@ -75,6 +75,9 @@ void NotifyHardwareContentProtectionTeardown(); + // Reset the state of this instance to be reinitializable. + void Reset(); + const GUID crypto_type_; const CdmProxy::Protocol protocol_; const FunctionIdMap function_id_map_; @@ -90,6 +93,8 @@ // Counter for assigning IDs to crypto sessions. uint32_t next_crypto_session_id_ = 1; + // Everything from here until weak ptr factory (which must be at the end) + // should be reset in Reset(). Client* client_ = nullptr; bool initialized_ = false;
diff --git a/media/gpu/windows/d3d11_cdm_proxy_unittest.cc b/media/gpu/windows/d3d11_cdm_proxy_unittest.cc index ff24d6b..cee91d5 100644 --- a/media/gpu/windows/d3d11_cdm_proxy_unittest.cc +++ b/media/gpu/windows/d3d11_cdm_proxy_unittest.cc
@@ -24,6 +24,7 @@ using ::testing::_; using ::testing::AllOf; using ::testing::AtLeast; +using ::testing::AtMost; using ::testing::DoAll; using ::testing::Invoke; using ::testing::InvokeWithoutArgs; @@ -51,8 +52,13 @@ class MockPowerMonitorSource : public base::PowerMonitorSource { public: - // Use this method to send a power suspend event. - void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); } + // Use this method to send a power resume event. + void Resume() { + // Due to how ProcessPowerEvent() works, it has to be suspended first to + // resume. + ProcessPowerEvent(SUSPEND_EVENT); + ProcessPowerEvent(RESUME_EVENT); + } MOCK_METHOD0(Shutdown, void()); MOCK_METHOD0(IsOnBatteryPowerImpl, bool()); @@ -92,7 +98,7 @@ function_id_map[kTestFunction] = kTestFunctionId; // Use NiceMock because we don't care about base::PowerMonitorSource events - // other than calling Suspend() directly. + // other than calling Resume() directly. auto mock_power_monitor_source = std::make_unique<NiceMock<MockPowerMonitorSource>>(); mock_power_monitor_source_ = mock_power_monitor_source.get(); @@ -189,8 +195,8 @@ Return(S_OK))); } - // Helper method to do Initialize(). Only useful if the test doesn't require - // access to the mocks later. + // Helper method to do Initialize(). The returned mock objects are accessible + // thru member variables. void Initialize(CdmProxy::Client* client, CdmProxy::InitializeCB callback) { EXPECT_CALL(create_device_mock_, Create(_, D3D_DRIVER_TYPE_HARDWARE, _, _, _, _, _, _, _, _)); @@ -235,10 +241,33 @@ Mock::VerifyAndClearExpectations(video_context1_mock_.Get()); } + // Test case where the proxy is initialized and then hardware content + // protection teardown is notified. + void HardwareContentProtectionTeardown() { + base::RunLoop run_loop; + + EXPECT_CALL(callback_mock_, + InitializeCallback(CdmProxy::Status::kOk, _, _)); + ASSERT_NO_FATAL_FAILURE(Initialize( + &client_, base::BindOnce(&CallbackMock::InitializeCallback, + base::Unretained(&callback_mock_)))); + + EXPECT_CALL(client_, NotifyHardwareReset()); + + base::MockCallback<CdmContext::EventCB> event_cb; + auto callback_registration = + proxy_->GetCdmContext()->RegisterEventCB(event_cb.Get()); + EXPECT_CALL(event_cb, Run(CdmContext::Event::kHardwareContextLost)) + .WillOnce(InvokeWithoutArgs([&run_loop]() { run_loop.Quit(); })); + + SetEvent(teardown_event_); + run_loop.Run(); + } + MockProxyClient client_; std::unique_ptr<D3D11CdmProxy> proxy_; std::unique_ptr<base::PowerMonitor> power_monitor_; - // Owned by power_monitor_. Use this to simulate a power-suspend. + // Owned by power_monitor_. Use this to simulate a power-resume. MockPowerMonitorSource* mock_power_monitor_source_; D3D11CreateDeviceMock create_device_mock_; @@ -291,22 +320,16 @@ // Hardware content protection teardown is notified to the proxy. // Verify that the client is notified. TEST_F(D3D11CdmProxyTest, HardwareContentProtectionTeardown) { - base::RunLoop run_loop; + EXPECT_NO_FATAL_FAILURE(HardwareContentProtectionTeardown()); +} - EXPECT_CALL(client_, NotifyHardwareReset()); - - base::MockCallback<CdmContext::EventCB> event_cb; - auto callback_registration = - proxy_->GetCdmContext()->RegisterEventCB(event_cb.Get()); - EXPECT_CALL(event_cb, Run(CdmContext::Event::kHardwareContextLost)) - .WillOnce(InvokeWithoutArgs([&run_loop]() { run_loop.Quit(); })); - +// Verify that initialization after hardware content protection teardown works.. +TEST_F(D3D11CdmProxyTest, HardwareContentProtectionTeardownThenInitialize) { + ASSERT_NO_FATAL_FAILURE(HardwareContentProtectionTeardown()); EXPECT_CALL(callback_mock_, InitializeCallback(CdmProxy::Status::kOk, _, _)); ASSERT_NO_FATAL_FAILURE( Initialize(&client_, base::BindOnce(&CallbackMock::InitializeCallback, base::Unretained(&callback_mock_)))); - SetEvent(teardown_event_); - run_loop.Run(); } // Verify that failing to register to hardware content protection teardown @@ -326,18 +349,41 @@ } // Verify that the client is notified on power suspend. -TEST_F(D3D11CdmProxyTest, PowerSuspend) { +TEST_F(D3D11CdmProxyTest, PowerResume) { base::RunLoop run_loop; - EXPECT_CALL(client_, NotifyHardwareReset()).WillOnce(Invoke([&run_loop]() { - run_loop.Quit(); - })); - EXPECT_CALL(callback_mock_, InitializeCallback(CdmProxy::Status::kOk, _, _)); ASSERT_NO_FATAL_FAILURE( Initialize(&client_, base::BindOnce(&CallbackMock::InitializeCallback, base::Unretained(&callback_mock_)))); - mock_power_monitor_source_->Suspend(); + + EXPECT_CALL(client_, NotifyHardwareReset()).WillOnce(Invoke([&run_loop]() { + run_loop.Quit(); + })); + + mock_power_monitor_source_->Resume(); + run_loop.Run(); +} + +// IRL power resume is notified and then hardware content protection teardown +// is notified. Make sure that the two notifications don't signal the clients +// more than once (without being reinitialized in between the notifications). +// Note that this test uses QuitWhenIdle(). If both notifications are processed +// this test will run forever. +TEST_F(D3D11CdmProxyTest, PowerResumeAndHardwareContentProtectionTeardown) { + base::RunLoop run_loop; + + EXPECT_CALL(callback_mock_, InitializeCallback(CdmProxy::Status::kOk, _, _)); + ASSERT_NO_FATAL_FAILURE( + Initialize(&client_, base::BindOnce(&CallbackMock::InitializeCallback, + base::Unretained(&callback_mock_)))); + + EXPECT_CALL(client_, NotifyHardwareReset()) + .Times(1) + .WillOnce(Invoke([&run_loop]() { run_loop.QuitWhenIdle(); })); + + mock_power_monitor_source_->Resume(); + SetEvent(teardown_event_); run_loop.Run(); } @@ -744,14 +790,6 @@ TEST_F(D3D11CdmProxyTest, ClearKeysAfterHardwareContentProtectionTeardown) { base::RunLoop run_loop; - EXPECT_CALL(client_, NotifyHardwareReset()).WillOnce(Invoke([&run_loop]() { - run_loop.Quit(); - })); - - base::WeakPtr<CdmContext> context = proxy_->GetCdmContext(); - ASSERT_TRUE(context); - CdmProxyContext* proxy_context = context->GetCdmProxyContext(); - uint32_t crypto_session_id_from_initialize = 0; EXPECT_CALL(callback_mock_, InitializeCallback(CdmProxy::Status::kOk, kTestProtocol, _)) @@ -775,9 +813,17 @@ base::BindOnce(&CallbackMock::SetKeyCallback, base::Unretained(&callback_mock_))); + EXPECT_CALL(client_, NotifyHardwareReset()).WillOnce(Invoke([&run_loop]() { + run_loop.Quit(); + })); + SetEvent(teardown_event_); run_loop.Run(); + base::WeakPtr<CdmContext> context = proxy_->GetCdmContext(); + ASSERT_TRUE(context); + CdmProxyContext* proxy_context = context->GetCdmProxyContext(); + std::string key_id_str(kKeyId.begin(), kKeyId.end()); auto decrypt_context = proxy_context->GetD3D11DecryptContext(kTestKeyType, key_id_str);
diff --git a/media/media_options.gni b/media/media_options.gni index 9ab94f0..362f1edc 100644 --- a/media/media_options.gni +++ b/media/media_options.gni
@@ -86,8 +86,7 @@ is_cast_using_cma_backend = true # Dav1d is only enabled when av1 decoding is enabled. - # TODO(dalecurtis): Re-enable once bugs fixed. https://crbug.com/924370. - enable_dav1d_decoder = false + enable_dav1d_decoder = enable_av1_decoder } # enable_hls_sample_aes can only be true if enable_mse_mpeg2ts_stream_parser is.
diff --git a/media/midi/midi_manager_mac.cc b/media/midi/midi_manager_mac.cc index ecd6e9d..96fdf9c7 100644 --- a/media/midi/midi_manager_mac.cc +++ b/media/midi/midi_manager_mac.cc
@@ -19,7 +19,7 @@ #include "media/midi/midi_service.h" #include "media/midi/task_service.h" -using base::IntToString; +using base::NumberToString; using base::SysCFStringRefToUTF8; using midi::mojom::PortState; using midi::mojom::Result; @@ -72,7 +72,7 @@ result = MIDIObjectGetIntegerProperty( endpoint, kMIDIPropertyDriverVersion, &version_number); if (result == noErr) { - version = IntToString(version_number); + version = NumberToString(version_number); } else { // kMIDIPropertyDriverVersion is not supported in IAC driver providing // endpoints, and the result will be kMIDIUnknownProperty (-10835). @@ -85,7 +85,7 @@ result = MIDIObjectGetIntegerProperty( endpoint, kMIDIPropertyUniqueID, &id_number); if (result == noErr) { - id = IntToString(id_number); + id = NumberToString(id_number); } else { // On connecting some devices, e.g., nano KONTROL2, unknown endpoints // appear and disappear quickly and they fail on queries.
diff --git a/net/socket/socks5_client_socket.cc b/net/socket/socks5_client_socket.cc index fe00fc8..832afa6 100644 --- a/net/socket/socks5_client_socket.cc +++ b/net/socket/socks5_client_socket.cc
@@ -33,7 +33,7 @@ SOCKS5ClientSocket::SOCKS5ClientSocket( std::unique_ptr<StreamSocket> transport_socket, - const HostResolver::RequestInfo& req_info, + const HostPortPair& destination, const NetworkTrafficAnnotationTag& traffic_annotation) : io_callback_(base::BindRepeating(&SOCKS5ClientSocket::OnIOComplete, base::Unretained(this))), @@ -44,7 +44,7 @@ bytes_received_(0), read_header_size(kReadHeaderSize), was_ever_used_(false), - host_request_info_(req_info), + destination_(destination), net_log_(transport_socket_->NetLog()), traffic_annotation_(traffic_annotation) {} @@ -272,7 +272,7 @@ int SOCKS5ClientSocket::DoGreetWrite() { // Since we only have 1 byte to send the hostname length in, if the // URL has a hostname longer than 255 characters we can't send it. - if (0xFF < host_request_info_.hostname().size()) { + if (0xFF < destination_.host().size()) { net_log_.AddEvent(NetLogEventType::SOCKS_HOSTNAME_TOO_BIG); return ERR_SOCKS_CONNECTION_FAILED; } @@ -359,14 +359,13 @@ handshake->push_back(kEndPointDomain); // The type of the address. - DCHECK_GE(static_cast<size_t>(0xFF), host_request_info_.hostname().size()); + DCHECK_GE(static_cast<size_t>(0xFF), destination_.host().size()); // First add the size of the hostname, followed by the hostname. - handshake->push_back(static_cast<unsigned char>( - host_request_info_.hostname().size())); - handshake->append(host_request_info_.hostname()); + handshake->push_back(static_cast<unsigned char>(destination_.host().size())); + handshake->append(destination_.host()); - uint16_t nw_port = base::HostToNet16(host_request_info_.port()); + uint16_t nw_port = base::HostToNet16(destination_.port()); handshake->append(reinterpret_cast<char*>(&nw_port), sizeof(nw_port)); return OK; } @@ -460,13 +459,13 @@ // read, we substract 1 byte from the additional request size. SocksEndPointAddressType address_type = static_cast<SocksEndPointAddressType>(buffer_[3]); - if (address_type == kEndPointDomain) + if (address_type == kEndPointDomain) { read_header_size += static_cast<uint8_t>(buffer_[4]); - else if (address_type == kEndPointResolvedIPv4) + } else if (address_type == kEndPointResolvedIPv4) { read_header_size += sizeof(struct in_addr) - 1; - else if (address_type == kEndPointResolvedIPv6) + } else if (address_type == kEndPointResolvedIPv6) { read_header_size += sizeof(struct in6_addr) - 1; - else { + } else { net_log_.AddEvent(NetLogEventType::SOCKS_UNKNOWN_ADDRESS_TYPE, NetLog::IntCallback("address_type", buffer_[3])); return ERR_SOCKS_CONNECTION_FAILED;
diff --git a/net/socket/socks5_client_socket.h b/net/socket/socks5_client_socket.h index aa8da1c3..6fe59e0 100644 --- a/net/socket/socks5_client_socket.h +++ b/net/socket/socks5_client_socket.h
@@ -16,9 +16,9 @@ #include "net/base/address_list.h" #include "net/base/completion_callback.h" #include "net/base/completion_repeating_callback.h" +#include "net/base/host_port_pair.h" #include "net/base/net_errors.h" #include "net/base/net_export.h" -#include "net/dns/host_resolver.h" #include "net/log/net_log_with_source.h" #include "net/socket/stream_socket.h" #include "net/traffic_annotation/network_traffic_annotation.h" @@ -30,14 +30,14 @@ // Currently no SOCKSv5 authentication is supported. class NET_EXPORT_PRIVATE SOCKS5ClientSocket : public StreamSocket { public: - // |req_info| contains the hostname and port to which the socket above will + // |destination| contains the hostname and port to which the socket above will // communicate to via the SOCKS layer. // // Although SOCKS 5 supports 3 different modes of addressing, we will // always pass it a hostname. This means the DNS resolving is done // proxy side. SOCKS5ClientSocket(std::unique_ptr<StreamSocket> transport_socket, - const HostResolver::RequestInfo& req_info, + const HostPortPair& destination, const NetworkTrafficAnnotationTag& traffic_annotation); // On destruction Disconnect() is called. @@ -152,7 +152,7 @@ bool was_ever_used_; - HostResolver::RequestInfo host_request_info_; + const HostPortPair destination_; NetLogWithSource net_log_;
diff --git a/net/socket/socks5_client_socket_fuzzer.cc b/net/socket/socks5_client_socket_fuzzer.cc index 783184c..ad2a9a92 100644 --- a/net/socket/socks5_client_socket_fuzzer.cc +++ b/net/socket/socks5_client_socket_fuzzer.cc
@@ -33,8 +33,8 @@ new net::FuzzedSocket(&data_provider, &test_net_log)); CHECK_EQ(net::OK, fuzzed_socket->Connect(callback.callback())); - net::HostResolver::RequestInfo request_info(net::HostPortPair("foo", 80)); - net::SOCKS5ClientSocket socket(std::move(fuzzed_socket), request_info, + net::SOCKS5ClientSocket socket(std::move(fuzzed_socket), + net::HostPortPair("foo", 80), TRAFFIC_ANNOTATION_FOR_TESTS); int result = socket.Connect(callback.callback()); callback.GetResult(result);
diff --git a/net/socket/socks5_client_socket_unittest.cc b/net/socket/socks5_client_socket_unittest.cc index 0f42457..5f44d95 100644 --- a/net/socket/socks5_client_socket_unittest.cc +++ b/net/socket/socks5_client_socket_unittest.cc
@@ -113,10 +113,9 @@ // The SOCKS5ClientSocket takes ownership of |tcp_sock_|, but keep a // non-owning pointer to it. - return std::make_unique<SOCKS5ClientSocket>( - base::WrapUnique(tcp_sock_), - HostResolver::RequestInfo(HostPortPair(hostname, port)), - TRAFFIC_ANNOTATION_FOR_TESTS); + return std::make_unique<SOCKS5ClientSocket>(base::WrapUnique(tcp_sock_), + HostPortPair(hostname, port), + TRAFFIC_ANNOTATION_FOR_TESTS); } // Tests a complete SOCKS5 handshake and the disconnection. @@ -384,10 +383,9 @@ // |socket| takes ownership of |tagging_sock|, but keep a non-owning pointer // to it. - SOCKS5ClientSocket socket( - std::unique_ptr<StreamSocket>(tagging_sock), - HostResolver::RequestInfo(HostPortPair("localhost", 80)), - TRAFFIC_ANNOTATION_FOR_TESTS); + SOCKS5ClientSocket socket(std::unique_ptr<StreamSocket>(tagging_sock), + HostPortPair("localhost", 80), + TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_EQ(tagging_sock->tag(), SocketTag()); #if defined(OS_ANDROID)
diff --git a/net/socket/socks_client_socket.cc b/net/socket/socks_client_socket.cc index af298ff..9e5b158 100644 --- a/net/socket/socks_client_socket.cc +++ b/net/socket/socks_client_socket.cc
@@ -12,6 +12,7 @@ #include "base/stl_util.h" #include "base/sys_byteorder.h" #include "net/base/io_buffer.h" +#include "net/dns/public/dns_query_type.h" #include "net/log/net_log.h" #include "net/log/net_log_event_type.h" #include "net/traffic_annotation/network_traffic_annotation.h" @@ -60,7 +61,7 @@ SOCKSClientSocket::SOCKSClientSocket( std::unique_ptr<StreamSocket> transport_socket, - const HostResolver::RequestInfo& req_info, + const HostPortPair& destination, RequestPriority priority, HostResolver* host_resolver, const NetworkTrafficAnnotationTag& traffic_annotation) @@ -71,7 +72,7 @@ bytes_received_(0), was_ever_used_(false), host_resolver_(host_resolver), - host_request_info_(req_info), + destination_(destination), priority_(priority), net_log_(transport_socket_->NetLog()), traffic_annotation_(traffic_annotation) {} @@ -104,7 +105,7 @@ void SOCKSClientSocket::Disconnect() { completed_handshake_ = false; - request_.reset(); + resolve_host_request_.reset(); transport_socket_->Disconnect(); // Reset other states to make sure they aren't mistakenly used later. @@ -301,11 +302,14 @@ next_state_ = STATE_RESOLVE_HOST_COMPLETE; // SOCKS4 only supports IPv4 addresses, so only try getting the IPv4 // addresses for the target host. - host_request_info_.set_address_family(ADDRESS_FAMILY_IPV4); - return host_resolver_->Resolve( - host_request_info_, priority_, &addresses_, - base::Bind(&SOCKSClientSocket::OnIOComplete, base::Unretained(this)), - &request_, net_log_); + HostResolver::ResolveHostParameters parameters; + parameters.dns_query_type = DnsQueryType::A; + parameters.initial_priority = priority_; + resolve_host_request_ = + host_resolver_->CreateRequest(destination_, net_log_, parameters); + + return resolve_host_request_->Start( + base::BindOnce(&SOCKSClientSocket::OnIOComplete, base::Unretained(this))); } int SOCKSClientSocket::DoResolveHostComplete(int result) { @@ -325,10 +329,12 @@ SOCKS4ServerRequest request; request.version = kSOCKSVersion4; request.command = kSOCKSStreamRequest; - request.nw_port = base::HostToNet16(host_request_info_.port()); + request.nw_port = base::HostToNet16(destination_.port()); - DCHECK(!addresses_.empty()); - const IPEndPoint& endpoint = addresses_.front(); + DCHECK(resolve_host_request_->GetAddressResults() && + !resolve_host_request_->GetAddressResults().value().empty()); + const IPEndPoint& endpoint = + resolve_host_request_->GetAddressResults().value().front(); // We disabled IPv6 results when resolving the hostname, so none of the // results in the list will be IPv6.
diff --git a/net/socket/socks_client_socket.h b/net/socket/socks_client_socket.h index 74f1548..6f66b57 100644 --- a/net/socket/socks_client_socket.h +++ b/net/socket/socks_client_socket.h
@@ -16,6 +16,7 @@ #include "base/memory/ref_counted.h" #include "net/base/address_list.h" #include "net/base/completion_once_callback.h" +#include "net/base/host_port_pair.h" #include "net/base/net_errors.h" #include "net/base/net_export.h" #include "net/dns/host_resolver.h" @@ -28,10 +29,10 @@ // The SOCKS client socket implementation class NET_EXPORT_PRIVATE SOCKSClientSocket : public StreamSocket { public: - // |req_info| contains the hostname and port to which the socket above will + // |destination| contains the hostname and port to which the socket above will // communicate to via the socks layer. For testing the referrer is optional. SOCKSClientSocket(std::unique_ptr<StreamSocket> transport_socket, - const HostResolver::RequestInfo& req_info, + const HostPortPair& destination, RequestPriority priority, HostResolver* host_resolver, const NetworkTrafficAnnotationTag& traffic_annotation); @@ -135,9 +136,8 @@ // Used to resolve the hostname to which the SOCKS proxy will connect. HostResolver* host_resolver_; - std::unique_ptr<HostResolver::Request> request_; - AddressList addresses_; - HostResolver::RequestInfo host_request_info_; + std::unique_ptr<HostResolver::ResolveHostRequest> resolve_host_request_; + const HostPortPair destination_; RequestPriority priority_; NetLogWithSource net_log_;
diff --git a/net/socket/socks_client_socket_fuzzer.cc b/net/socket/socks_client_socket_fuzzer.cc index 4a5ce22c..6f300f9 100644 --- a/net/socket/socks_client_socket_fuzzer.cc +++ b/net/socket/socks_client_socket_fuzzer.cc
@@ -53,11 +53,9 @@ new net::FuzzedSocket(&data_provider, &test_net_log)); CHECK_EQ(net::OK, fuzzed_socket->Connect(callback.callback())); - net::HostResolver::RequestInfo request_info(net::HostPortPair("foo", 80)); - - net::SOCKSClientSocket socket(std::move(fuzzed_socket), request_info, - net::DEFAULT_PRIORITY, &mock_host_resolver, - TRAFFIC_ANNOTATION_FOR_TESTS); + net::SOCKSClientSocket socket( + std::move(fuzzed_socket), net::HostPortPair("foo", 80), + net::DEFAULT_PRIORITY, &mock_host_resolver, TRAFFIC_ANNOTATION_FOR_TESTS); int result = socket.Connect(callback.callback()); callback.GetResult(result); return 0;
diff --git a/net/socket/socks_client_socket_unittest.cc b/net/socket/socks_client_socket_unittest.cc index 346ee80..14f68216 100644 --- a/net/socket/socks_client_socket_unittest.cc +++ b/net/socket/socks_client_socket_unittest.cc
@@ -96,92 +96,10 @@ // non-owning pointer to it. tcp_sock_ = socket.get(); return std::make_unique<SOCKSClientSocket>( - std::move(socket), - HostResolver::RequestInfo(HostPortPair(hostname, port)), DEFAULT_PRIORITY, + std::move(socket), HostPortPair(hostname, port), DEFAULT_PRIORITY, host_resolver, TRAFFIC_ANNOTATION_FOR_TESTS); } -// Implementation of HostResolver that never completes its resolve request. -// We use this in the test "DisconnectWhileHostResolveInProgress" to make -// sure that the outstanding resolve request gets cancelled. -class HangingHostResolverWithCancel : public HostResolver { - public: - HangingHostResolverWithCancel() : outstanding_request_(NULL) {} - - std::unique_ptr<ResolveHostRequest> CreateRequest( - const HostPortPair& host, - const NetLogWithSource& net_log, - const base::Optional<ResolveHostParameters>& optional_parameters) - override { - NOTIMPLEMENTED(); - return nullptr; - } - - int Resolve(const RequestInfo& info, - RequestPriority priority, - AddressList* addresses, - CompletionOnceCallback callback, - std::unique_ptr<Request>* out_req, - const NetLogWithSource& net_log) override { - DCHECK(addresses); - DCHECK_EQ(false, callback.is_null()); - EXPECT_FALSE(HasOutstandingRequest()); - outstanding_request_ = new RequestImpl(this); - out_req->reset(outstanding_request_); - return ERR_IO_PENDING; - } - - int ResolveFromCache(const RequestInfo& info, - AddressList* addresses, - const NetLogWithSource& net_log) override { - NOTIMPLEMENTED(); - return ERR_UNEXPECTED; - } - - int ResolveStaleFromCache(const RequestInfo& info, - AddressList* addresses, - HostCache::EntryStaleness* stale_info, - const NetLogWithSource& net_log) override { - NOTIMPLEMENTED(); - return ERR_UNEXPECTED; - } - - bool HasCached(base::StringPiece hostname, - HostCache::Entry::Source* source_out, - HostCache::EntryStaleness* stale_out) const override { - NOTIMPLEMENTED(); - return false; - } - - void RemoveRequest(Request* req) { - EXPECT_TRUE(HasOutstandingRequest()); - EXPECT_EQ(outstanding_request_, req); - outstanding_request_ = nullptr; - } - - bool HasOutstandingRequest() { return outstanding_request_ != nullptr; } - - private: - class RequestImpl : public HostResolver::Request { - public: - RequestImpl(HangingHostResolverWithCancel* resolver) - : resolver_(resolver) {} - ~RequestImpl() override { - DCHECK(resolver_); - resolver_->RemoveRequest(this); - } - - void ChangeRequestPriority(RequestPriority priority) override {} - - private: - HangingHostResolverWithCancel* resolver_; - }; - - Request* outstanding_request_; - - DISALLOW_COPY_AND_ASSIGN(HangingHostResolverWithCancel); -}; - // Tests a complete handshake and the disconnection. TEST_F(SOCKSClientSocketTest, CompleteHandshake) { // Run the test twice. Once with ReadIfReady() and once with Read(). @@ -461,8 +379,7 @@ // Calls Disconnect() while a host resolve is in progress. The outstanding host // resolve should be cancelled. TEST_F(SOCKSClientSocketTest, DisconnectWhileHostResolveInProgress) { - std::unique_ptr<HangingHostResolverWithCancel> hanging_resolver( - new HangingHostResolverWithCancel()); + auto hanging_resolver = std::make_unique<HangingHostResolver>(); // Doesn't matter what the socket data is, we will never use it -- garbage. MockWrite data_writes[] = { MockWrite(SYNCHRONOUS, "", 0) }; @@ -478,13 +395,10 @@ EXPECT_FALSE(user_sock_->IsConnected()); EXPECT_FALSE(user_sock_->IsConnectedAndIdle()); - // The host resolver should have received the resolve request. - EXPECT_TRUE(hanging_resolver->HasOutstandingRequest()); - // Disconnect the SOCKS socket -- this should cancel the outstanding resolve. + ASSERT_EQ(0, hanging_resolver->num_cancellations()); user_sock_->Disconnect(); - - EXPECT_FALSE(hanging_resolver->HasOutstandingRequest()); + EXPECT_EQ(1, hanging_resolver->num_cancellations()); EXPECT_FALSE(user_sock_->IsConnected()); EXPECT_FALSE(user_sock_->IsConnectedAndIdle()); @@ -527,10 +441,9 @@ // |connection| takes ownership of |tagging_sock|, but keep a // non-owning pointer to it. MockHostResolver host_resolver; - SOCKSClientSocket socket( - std::unique_ptr<StreamSocket>(tagging_sock), - HostResolver::RequestInfo(HostPortPair("localhost", 80)), - DEFAULT_PRIORITY, &host_resolver, TRAFFIC_ANNOTATION_FOR_TESTS); + SOCKSClientSocket socket(std::unique_ptr<StreamSocket>(tagging_sock), + HostPortPair("localhost", 80), DEFAULT_PRIORITY, + &host_resolver, TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_EQ(tagging_sock->tag(), SocketTag()); #if defined(OS_ANDROID)
diff --git a/net/socket/socks_connect_job.cc b/net/socket/socks_connect_job.cc index 1ee4078..59eb246 100644 --- a/net/socket/socks_connect_job.cc +++ b/net/socket/socks_connect_job.cc
@@ -4,8 +4,9 @@ #include "net/socket/socks_connect_job.h" +#include <utility> + #include "base/bind.h" -#include "net/base/host_port_pair.h" #include "net/base/net_errors.h" #include "net/log/net_log_source_type.h" #include "net/log/net_log_with_source.h"
diff --git a/net/socket/socks_connect_job.h b/net/socket/socks_connect_job.h index cc64e7c1..919da9d 100644 --- a/net/socket/socks_connect_job.h +++ b/net/socket/socks_connect_job.h
@@ -12,15 +12,14 @@ #include "base/memory/ref_counted.h" #include "base/time/time.h" #include "net/base/completion_once_callback.h" +#include "net/base/host_port_pair.h" #include "net/base/net_export.h" #include "net/base/request_priority.h" -#include "net/dns/host_resolver.h" #include "net/socket/connect_job.h" #include "net/traffic_annotation/network_traffic_annotation.h" namespace net { -class HostPortPair; class StreamSocket; class TransportSocketParams; @@ -35,7 +34,7 @@ const scoped_refptr<TransportSocketParams>& transport_params() const { return transport_params_; } - const HostResolver::RequestInfo& destination() const { return destination_; } + const HostPortPair& destination() const { return destination_; } bool is_socks_v5() const { return socks_v5_; } const NetworkTrafficAnnotationTag traffic_annotation() { @@ -49,7 +48,7 @@ // The transport (likely TCP) connection must point toward the proxy server. const scoped_refptr<TransportSocketParams> transport_params_; // This is the HTTP destination. - HostResolver::RequestInfo destination_; + const HostPortPair destination_; const bool socks_v5_; NetworkTrafficAnnotationTag traffic_annotation_;
diff --git a/net/third_party/quic/core/frames/quic_message_frame.cc b/net/third_party/quic/core/frames/quic_message_frame.cc index 7c686c5..735953b 100644 --- a/net/third_party/quic/core/frames/quic_message_frame.cc +++ b/net/third_party/quic/core/frames/quic_message_frame.cc
@@ -9,17 +9,20 @@ namespace quic { -QuicMessageFrame::QuicMessageFrame() : message_id(0) {} +QuicMessageFrame::QuicMessageFrame() + : message_id(0), data(nullptr), message_length(0) {} -QuicMessageFrame::QuicMessageFrame(QuicMessageId message_id, - QuicStringPiece message_data) - : message_id(message_id), message_data(message_data) {} +QuicMessageFrame::QuicMessageFrame(QuicMessageId message_id) + : message_id(message_id), data(nullptr), message_length(0) {} + +QuicMessageFrame::QuicMessageFrame(const char* data, QuicPacketLength length) + : message_id(0), data(data), message_length(length) {} QuicMessageFrame::~QuicMessageFrame() {} std::ostream& operator<<(std::ostream& os, const QuicMessageFrame& s) { os << " message_id: " << s.message_id - << ", message_length: " << s.message_data.length() << " }\n"; + << ", message_length: " << s.message_length << " }\n"; return os; }
diff --git a/net/third_party/quic/core/frames/quic_message_frame.h b/net/third_party/quic/core/frames/quic_message_frame.h index 575e154..13762f88 100644 --- a/net/third_party/quic/core/frames/quic_message_frame.h +++ b/net/third_party/quic/core/frames/quic_message_frame.h
@@ -6,14 +6,26 @@ #define NET_THIRD_PARTY_QUIC_CORE_FRAMES_QUIC_MESSAGE_FRAME_H_ #include "net/third_party/quic/core/quic_types.h" +#include "net/third_party/quic/platform/api/quic_containers.h" #include "net/third_party/quic/platform/api/quic_export.h" +#include "net/third_party/quic/platform/api/quic_mem_slice.h" #include "net/third_party/quic/platform/api/quic_string_piece.h" namespace quic { +typedef QuicInlinedVector<QuicMemSlice, 1> QuicMessageData; + struct QUIC_EXPORT_PRIVATE QuicMessageFrame { QuicMessageFrame(); - QuicMessageFrame(QuicMessageId message_id, QuicStringPiece message_data); + explicit QuicMessageFrame(QuicMessageId message_id); + QuicMessageFrame(const char* data, QuicPacketLength length); + + QuicMessageFrame(const QuicMessageFrame& other) = delete; + QuicMessageFrame& operator=(const QuicMessageFrame& other) = delete; + + QuicMessageFrame(QuicMessageFrame&& other) = default; + QuicMessageFrame& operator=(QuicMessageFrame&& other) = default; + ~QuicMessageFrame(); friend QUIC_EXPORT_PRIVATE std::ostream& operator<<( @@ -23,8 +35,13 @@ // message_id is only used on the sender side and does not get serialized on // wire. QuicMessageId message_id; - // The actual data. - QuicString message_data; + // Not owned, only used on read path. + const char* data; + // Total length of message_data, must be fit into one packet. + QuicPacketLength message_length; + + // The actual message data which is reference counted, used on write path. + QuicMessageData message_data; }; } // namespace quic
diff --git a/net/third_party/quic/core/http/end_to_end_test.cc b/net/third_party/quic/core/http/end_to_end_test.cc index 6fd0fc0..0b236311 100644 --- a/net/third_party/quic/core/http/end_to_end_test.cc +++ b/net/third_party/quic/core/http/end_to_end_test.cc
@@ -3502,22 +3502,30 @@ QuicStringPiece message_buffer(message_string); QuicRandom* random = QuicConnectionPeer::GetHelper(client_connection)->GetRandomGenerator(); + QuicMemSliceStorage storage(nullptr, 0, nullptr, 0); { QuicConnection::ScopedPacketFlusher flusher( client_session->connection(), QuicConnection::SEND_ACK_IF_PENDING); // Verify the largest message gets successfully sent. EXPECT_EQ(MessageResult(MESSAGE_STATUS_SUCCESS, 1), - client_session->SendMessage( + client_session->SendMessage(MakeSpan( + client_session->connection() + ->helper() + ->GetStreamSendBufferAllocator(), QuicStringPiece(message_buffer.data(), - client_session->GetLargestMessagePayload()))); + client_session->GetLargestMessagePayload()), + &storage))); // Send more messages with size (0, largest_payload] until connection is // write blocked. const int kTestMaxNumberOfMessages = 100; for (size_t i = 2; i <= kTestMaxNumberOfMessages; ++i) { size_t message_length = random->RandUint64() % client_session->GetLargestMessagePayload() + 1; - MessageResult result = client_session->SendMessage( - QuicStringPiece(message_buffer.data(), message_length)); + MessageResult result = client_session->SendMessage(MakeSpan( + client_session->connection() + ->helper() + ->GetStreamSendBufferAllocator(), + QuicStringPiece(message_buffer.data(), message_length), &storage)); if (result.status == MESSAGE_STATUS_BLOCKED) { // Connection is write blocked. break; @@ -3527,12 +3535,17 @@ } client_->WaitForDelayedAcks(); - EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE, - client_session - ->SendMessage(QuicStringPiece( - message_buffer.data(), - client_session->GetLargestMessagePayload() + 1)) - .status); + EXPECT_EQ( + MESSAGE_STATUS_TOO_LARGE, + client_session + ->SendMessage(MakeSpan( + client_session->connection() + ->helper() + ->GetStreamSendBufferAllocator(), + QuicStringPiece(message_buffer.data(), + client_session->GetLargestMessagePayload() + 1), + &storage)) + .status); EXPECT_EQ(QUIC_NO_ERROR, client_->connection_error()); }
diff --git a/net/third_party/quic/core/quic_connection.cc b/net/third_party/quic/core/quic_connection.cc index 7db206ef..e4b0f5af 100644 --- a/net/third_party/quic/core/quic_connection.cc +++ b/net/third_party/quic/core/quic_connection.cc
@@ -1317,7 +1317,8 @@ if (debug_visitor_ != nullptr) { debug_visitor_->OnMessageFrame(frame); } - visitor_->OnMessageReceived(frame.message_data); + visitor_->OnMessageReceived( + QuicStringPiece(frame.data, frame.message_length)); should_last_packet_instigate_acks_ = true; return connected_; } @@ -3508,13 +3509,13 @@ } MessageStatus QuicConnection::SendMessage(QuicMessageId message_id, - QuicStringPiece message) { + QuicMemSliceSpan message) { if (transport_version() <= QUIC_VERSION_44) { QUIC_BUG << "MESSAGE frame is not supported for version " << transport_version(); return MESSAGE_STATUS_UNSUPPORTED; } - if (message.length() > GetLargestMessagePayload()) { + if (message.total_length() > GetLargestMessagePayload()) { return MESSAGE_STATUS_TOO_LARGE; } if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
diff --git a/net/third_party/quic/core/quic_connection.h b/net/third_party/quic/core/quic_connection.h index 691d4d0..051969c5 100644 --- a/net/third_party/quic/core/quic_connection.h +++ b/net/third_party/quic/core/quic_connection.h
@@ -745,7 +745,7 @@ // Tries to send |message| and returns the message status. virtual MessageStatus SendMessage(QuicMessageId message_id, - QuicStringPiece message); + QuicMemSliceSpan message); // Returns the largest payload that will fit into a single MESSAGE frame. QuicPacketLength GetLargestMessagePayload() const;
diff --git a/net/third_party/quic/core/quic_connection_test.cc b/net/third_party/quic/core/quic_connection_test.cc index 2e214c2..fb18f95 100644 --- a/net/third_party/quic/core/quic_connection_test.cc +++ b/net/third_party/quic/core/quic_connection_test.cc
@@ -7560,6 +7560,7 @@ } QuicString message(connection_.GetLargestMessagePayload() * 2, 'a'); QuicStringPiece message_data(message); + QuicMemSliceStorage storage(nullptr, 0, nullptr, 0); { QuicConnection::ScopedPacketFlusher flusher(&connection_, QuicConnection::SEND_ACK); @@ -7568,22 +7569,32 @@ // get sent, one contains stream frame, and the other only contains the // message frame. EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2); - EXPECT_EQ(MESSAGE_STATUS_SUCCESS, - connection_.SendMessage( - 1, QuicStringPiece(message_data.data(), - connection_.GetLargestMessagePayload()))); + EXPECT_EQ( + MESSAGE_STATUS_SUCCESS, + connection_.SendMessage( + 1, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(), + QuicStringPiece(message_data.data(), + connection_.GetLargestMessagePayload()), + &storage))); } // Fail to send a message if connection is congestion control blocked. EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false)); - EXPECT_EQ(MESSAGE_STATUS_BLOCKED, connection_.SendMessage(2, "message")); + EXPECT_EQ( + MESSAGE_STATUS_BLOCKED, + connection_.SendMessage( + 2, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(), + "message", &storage))); // Always fail to send a message which cannot fit into one packet. EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); EXPECT_EQ( MESSAGE_STATUS_TOO_LARGE, connection_.SendMessage( - 3, QuicStringPiece(message_data.data(), - connection_.GetLargestMessagePayload() + 1))); + 3, + MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(), + QuicStringPiece(message_data.data(), + connection_.GetLargestMessagePayload() + 1), + &storage))); } // Test to check that the path challenge/path response logic works
diff --git a/net/third_party/quic/core/quic_framer.cc b/net/third_party/quic/core/quic_framer.cc index 49fde715..2626092 100644 --- a/net/third_party/quic/core/quic_framer.cc +++ b/net/third_party/quic/core/quic_framer.cc
@@ -3413,7 +3413,9 @@ bool no_message_length, QuicMessageFrame* frame) { if (no_message_length) { - frame->message_data = QuicString(reader->ReadRemainingPayload()); + QuicStringPiece remaining(reader->ReadRemainingPayload()); + frame->data = remaining.data(); + frame->message_length = remaining.length(); return true; } @@ -3429,7 +3431,8 @@ return false; } - frame->message_data = QuicString(message_piece); + frame->data = message_piece.data(); + frame->message_length = message_length; return true; } @@ -3777,7 +3780,7 @@ case MESSAGE_FRAME: return GetMessageFrameSize(version_.transport_version, last_frame_in_packet, - frame.message_frame->message_data.length()); + frame.message_frame->message_length); case PADDING_FRAME: DCHECK(false); return 0; @@ -4711,12 +4714,15 @@ if (!writer->WriteUInt8(type_byte)) { return false; } - if (!last_frame_in_packet && - !writer->WriteVarInt62(frame.message_data.length())) { + if (!last_frame_in_packet && !writer->WriteVarInt62(frame.message_length)) { return false; } - return writer->WriteBytes(frame.message_data.data(), - frame.message_data.length()); + for (const auto& slice : frame.message_data) { + if (!writer->WriteBytes(slice.data(), slice.length())) { + return false; + } + } + return true; } bool QuicFramer::RaiseError(QuicErrorCode error) {
diff --git a/net/third_party/quic/core/quic_framer_test.cc b/net/third_party/quic/core/quic_framer_test.cc index a97e69a1..1e6c966 100644 --- a/net/third_party/quic/core/quic_framer_test.cc +++ b/net/third_party/quic/core/quic_framer_test.cc
@@ -278,7 +278,8 @@ bool OnMessageFrame(const QuicMessageFrame& frame) override { ++frame_count_; - message_frames_.push_back(QuicMakeUnique<QuicMessageFrame>(frame)); + message_frames_.push_back( + QuicMakeUnique<QuicMessageFrame>(frame.data, frame.message_length)); return true; } @@ -614,6 +615,7 @@ QuicTime start_; QuicFramer framer_; test::TestQuicVisitor visitor_; + SimpleBufferAllocator allocator_; }; // Multiple test cases of QuicFramerTest use byte arrays to define packets for @@ -4782,8 +4784,8 @@ PACKET_8BYTE_CONNECTION_ID, PACKET_0BYTE_CONNECTION_ID)); ASSERT_EQ(2u, visitor_.message_frames_.size()); - EXPECT_EQ(7u, visitor_.message_frames_[0]->message_data.length()); - EXPECT_EQ(8u, visitor_.message_frames_[1]->message_data.length()); + EXPECT_EQ(7u, visitor_.message_frames_[0]->message_length); + EXPECT_EQ(8u, visitor_.message_frames_[1]->message_length); CheckFramingBoundaries(packet45, QUIC_INVALID_MESSAGE_DATA); } @@ -8157,9 +8159,13 @@ header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; + QuicMemSliceStorage storage(nullptr, 0, nullptr, 0); - QuicMessageFrame frame(1, "message"); - QuicMessageFrame frame2(2, "message2"); + QuicMessageFrame frame(1); + MakeSpan(&allocator_, "message", &storage).SaveMemSlicesAsMessageData(&frame); + QuicMessageFrame frame2(2); + MakeSpan(&allocator_, "message2", &storage) + .SaveMemSlicesAsMessageData(&frame2); QuicFrames frames = {QuicFrame(&frame), QuicFrame(&frame2)}; // clang-format off
diff --git a/net/third_party/quic/core/quic_packet_creator.cc b/net/third_party/quic/core/quic_packet_creator.cc index d629bc1..05879038 100644 --- a/net/third_party/quic/core/quic_packet_creator.cc +++ b/net/third_party/quic/core/quic_packet_creator.cc
@@ -456,7 +456,7 @@ !queued_frames_.empty() && queued_frames_.back().type == MESSAGE_FRAME; if (has_trailing_message_frame) { return QuicDataWriter::GetVarInt62Len( - queued_frames_.back().message_frame->message_data.length()); + queued_frames_.back().message_frame->message_length); } // If the last frame in the packet is a stream frame, then it will expand to // include the stream_length field when a new frame is added.
diff --git a/net/third_party/quic/core/quic_packet_creator_test.cc b/net/third_party/quic/core/quic_packet_creator_test.cc index 50e4a47a..c4b676a 100644 --- a/net/third_party/quic/core/quic_packet_creator_test.cc +++ b/net/third_party/quic/core/quic_packet_creator_test.cc
@@ -256,6 +256,7 @@ TestPacketCreator creator_; SerializedPacket serialized_packet_; SimpleDataProducer producer_; + SimpleBufferAllocator allocator_; }; // Run all packet creator tests with all supported versions of QUIC, and with @@ -1489,22 +1490,29 @@ .Times(3) .WillRepeatedly( Invoke(this, &QuicPacketCreatorTest::ClearSerializedPacketForTests)); + QuicMemSliceStorage storage(nullptr, 0, nullptr, 0); // Verify that there is enough room for the largest message payload. EXPECT_TRUE( creator_.HasRoomForMessageFrame(creator_.GetLargestMessagePayload())); QuicString message(creator_.GetLargestMessagePayload(), 'a'); - EXPECT_TRUE(creator_.AddSavedFrame( - QuicFrame(new QuicMessageFrame(1, message)), NOT_RETRANSMISSION)); + QuicMessageFrame* message_frame = new QuicMessageFrame(1); + MakeSpan(&allocator_, message, &storage) + .SaveMemSlicesAsMessageData(message_frame); + EXPECT_TRUE( + creator_.AddSavedFrame(QuicFrame(message_frame), NOT_RETRANSMISSION)); EXPECT_TRUE(creator_.HasPendingFrames()); creator_.Flush(); - EXPECT_TRUE(creator_.AddSavedFrame( - QuicFrame(new QuicMessageFrame(2, "message")), NOT_RETRANSMISSION)); + QuicMessageFrame* frame2 = new QuicMessageFrame(2); + MakeSpan(&allocator_, "message", &storage).SaveMemSlicesAsMessageData(frame2); + EXPECT_TRUE(creator_.AddSavedFrame(QuicFrame(frame2), NOT_RETRANSMISSION)); EXPECT_TRUE(creator_.HasPendingFrames()); // Verify if a new frame is added, 1 byte message length will be added. EXPECT_EQ(1u, creator_.ExpansionOnNewFrame()); - EXPECT_TRUE(creator_.AddSavedFrame( - QuicFrame(new QuicMessageFrame(3, "message2")), NOT_RETRANSMISSION)); + QuicMessageFrame* frame3 = new QuicMessageFrame(3); + MakeSpan(&allocator_, "message2", &storage) + .SaveMemSlicesAsMessageData(frame3); + EXPECT_TRUE(creator_.AddSavedFrame(QuicFrame(frame3), NOT_RETRANSMISSION)); EXPECT_EQ(1u, creator_.ExpansionOnNewFrame()); creator_.Flush(); @@ -1513,16 +1521,17 @@ EXPECT_TRUE(creator_.ConsumeData( QuicUtils::GetCryptoStreamId(client_framer_.transport_version()), &iov_, 1u, iov_.iov_len, 0u, 0u, false, false, NOT_RETRANSMISSION, &frame)); - EXPECT_TRUE(creator_.AddSavedFrame( - QuicFrame(new QuicMessageFrame(1, "message")), NOT_RETRANSMISSION)); + QuicMessageFrame* frame4 = new QuicMessageFrame(4); + MakeSpan(&allocator_, "message", &storage).SaveMemSlicesAsMessageData(frame4); + EXPECT_TRUE(creator_.AddSavedFrame(QuicFrame(frame4), NOT_RETRANSMISSION)); EXPECT_TRUE(creator_.HasPendingFrames()); // Verify there is not enough room for largest payload. EXPECT_FALSE( creator_.HasRoomForMessageFrame(creator_.GetLargestMessagePayload())); // Add largest message will causes the flush of the stream frame. - QuicMessageFrame message_frame(2, message); - EXPECT_FALSE( - creator_.AddSavedFrame(QuicFrame(&message_frame), NOT_RETRANSMISSION)); + QuicMessageFrame frame5(5); + MakeSpan(&allocator_, message, &storage).SaveMemSlicesAsMessageData(&frame5); + EXPECT_FALSE(creator_.AddSavedFrame(QuicFrame(&frame5), NOT_RETRANSMISSION)); EXPECT_FALSE(creator_.HasPendingFrames()); } @@ -1532,13 +1541,15 @@ } QuicString message_data(kDefaultMaxPacketSize, 'a'); QuicStringPiece message_buffer(message_data); + QuicMemSliceStorage storage(nullptr, 0, nullptr, 0); // Test all possible size of message frames. for (size_t message_size = 0; message_size <= creator_.GetLargestMessagePayload(); ++message_size) { - EXPECT_TRUE(creator_.AddSavedFrame( - QuicFrame(new QuicMessageFrame( - 0, QuicStringPiece(message_buffer.data(), message_size))), - NOT_RETRANSMISSION)); + QuicMessageFrame* frame = new QuicMessageFrame(0); + MakeSpan(&allocator_, QuicStringPiece(message_buffer.data(), message_size), + &storage) + .SaveMemSlicesAsMessageData(frame); + EXPECT_TRUE(creator_.AddSavedFrame(QuicFrame(frame), NOT_RETRANSMISSION)); EXPECT_TRUE(creator_.HasPendingFrames()); size_t expansion_bytes = message_size >= 64 ? 2 : 1;
diff --git a/net/third_party/quic/core/quic_packet_generator.cc b/net/third_party/quic/core/quic_packet_generator.cc index df7974a..d963c97 100644 --- a/net/third_party/quic/core/quic_packet_generator.cc +++ b/net/third_party/quic/core/quic_packet_generator.cc
@@ -418,17 +418,19 @@ } MessageStatus QuicPacketGenerator::AddMessageFrame(QuicMessageId message_id, - QuicStringPiece message) { + QuicMemSliceSpan message) { QUIC_BUG_IF(!flusher_attached_) << "Packet flusher is not attached when " "generator tries to add message frame."; - if (message.length() > GetLargestMessagePayload()) { + const QuicByteCount message_length = message.total_length(); + if (message_length > GetLargestMessagePayload()) { return MESSAGE_STATUS_TOO_LARGE; } SendQueuedFrames(/*flush=*/false); - if (!packet_creator_.HasRoomForMessageFrame(message.length())) { + if (!packet_creator_.HasRoomForMessageFrame(message_length)) { packet_creator_.Flush(); } - QuicMessageFrame* frame = new QuicMessageFrame(message_id, message); + QuicMessageFrame* frame = new QuicMessageFrame(message_id); + message.SaveMemSlicesAsMessageData(frame); const bool success = packet_creator_.AddSavedFrame(QuicFrame(frame), next_transmission_type_); if (!success) {
diff --git a/net/third_party/quic/core/quic_packet_generator.h b/net/third_party/quic/core/quic_packet_generator.h index da9794b..a3380c5 100644 --- a/net/third_party/quic/core/quic_packet_generator.h +++ b/net/third_party/quic/core/quic_packet_generator.h
@@ -50,6 +50,7 @@ #include "net/third_party/quic/core/quic_sent_packet_manager.h" #include "net/third_party/quic/core/quic_types.h" #include "net/third_party/quic/platform/api/quic_export.h" +#include "net/third_party/quic/platform/api/quic_mem_slice_span.h" namespace quic { @@ -210,7 +211,7 @@ // Tries to add a message frame containing |message| and returns the status. MessageStatus AddMessageFrame(QuicMessageId message_id, - QuicStringPiece message); + QuicMemSliceSpan message); // Returns the largest payload that will fit into a single MESSAGE frame. QuicPacketLength GetLargestMessagePayload() const;
diff --git a/net/third_party/quic/core/quic_packet_generator_test.cc b/net/third_party/quic/core/quic_packet_generator_test.cc index f1d6201..a6d7e9e8d3 100644 --- a/net/third_party/quic/core/quic_packet_generator_test.cc +++ b/net/third_party/quic/core/quic_packet_generator_test.cc
@@ -266,6 +266,7 @@ std::vector<SerializedPacket> packets_; QuicAckFrame ack_frame_; struct iovec iov_; + SimpleBufferAllocator allocator_; private: std::unique_ptr<char[]> data_array_; @@ -1370,6 +1371,7 @@ if (framer_.transport_version() <= QUIC_VERSION_44) { return; } + quic::QuicMemSliceStorage storage(nullptr, 0, nullptr, 0); delegate_.SetCanWriteAnything(); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); @@ -1378,21 +1380,29 @@ generator_.ConsumeData( QuicUtils::GetHeadersStreamId(framer_.transport_version()), &iov_, 1u, iov_.iov_len, 0, FIN); - EXPECT_EQ(MESSAGE_STATUS_SUCCESS, generator_.AddMessageFrame(1, "message")); + EXPECT_EQ(MESSAGE_STATUS_SUCCESS, + generator_.AddMessageFrame( + 1, MakeSpan(&allocator_, "message", &storage))); EXPECT_TRUE(generator_.HasQueuedFrames()); EXPECT_TRUE(generator_.HasRetransmittableFrames()); // Add a message which causes the flush of current packet. - EXPECT_EQ(MESSAGE_STATUS_SUCCESS, - generator_.AddMessageFrame( - 2, QuicString(generator_.GetLargestMessagePayload(), 'a'))); + EXPECT_EQ( + MESSAGE_STATUS_SUCCESS, + generator_.AddMessageFrame( + 2, MakeSpan(&allocator_, + QuicString(generator_.GetLargestMessagePayload(), 'a'), + &storage))); EXPECT_TRUE(generator_.HasRetransmittableFrames()); // Failed to send messages which cannot fit into one packet. EXPECT_EQ( MESSAGE_STATUS_TOO_LARGE, generator_.AddMessageFrame( - 3, QuicString(generator_.GetLargestMessagePayload() + 10, 'a'))); + 3, + MakeSpan(&allocator_, + QuicString(generator_.GetLargestMessagePayload() + 10, 'a'), + &storage))); } } // namespace test
diff --git a/net/third_party/quic/core/quic_session.cc b/net/third_party/quic/core/quic_session.cc index a18da979..cf9eee8 100644 --- a/net/third_party/quic/core/quic_session.cc +++ b/net/third_party/quic/core/quic_session.cc
@@ -1545,7 +1545,7 @@ connection_->SetTransmissionType(type); } -MessageResult QuicSession::SendMessage(QuicStringPiece message) { +MessageResult QuicSession::SendMessage(QuicMemSliceSpan message) { if (!IsEncryptionEstablished()) { return {MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED, 0}; }
diff --git a/net/third_party/quic/core/quic_session.h b/net/third_party/quic/core/quic_session.h index f78a231..7044e913 100644 --- a/net/third_party/quic/core/quic_session.h +++ b/net/third_party/quic/core/quic_session.h
@@ -161,11 +161,17 @@ QuicStreamOffset offset, StreamSendingState state); - // Called by application to send |message|. Returns the message result which - // includes the message status and message ID (valid if the write succeeds). - // SendMessage flushes a message packet even it is not full. If the - // application wants to bundle other data in the same packet, please consider - // adding a packet flusher around the SendMessage and/or WritevData calls. + // Called by application to send |message|. Data copy can be avoided if + // |message| is provided in reference counted memory. + // Please note, |message| provided in reference counted memory would be moved + // internally when message is successfully sent. Thereafter, it would be + // undefined behavior if callers try to access the slices through their own + // copy of the span object. + // Returns the message result which includes the message status and message ID + // (valid if the write succeeds). SendMessage flushes a message packet even it + // is not full. If the application wants to bundle other data in the same + // packet, please consider adding a packet flusher around the SendMessage + // and/or WritevData calls. // // OnMessageAcked and OnMessageLost are called when a particular message gets // acked or lost. @@ -175,7 +181,7 @@ // blocked. In this case the caller can retry sending message again when // connection becomes available, for example after getting OnCanWrite() // callback. - MessageResult SendMessage(QuicStringPiece message); + MessageResult SendMessage(QuicMemSliceSpan message); // Called when message with |message_id| gets acked. virtual void OnMessageAcked(QuicMessageId message_id);
diff --git a/net/third_party/quic/core/quic_session_test.cc b/net/third_party/quic/core/quic_session_test.cc index 5ea178af..6f7d803 100644 --- a/net/third_party/quic/core/quic_session_test.cc +++ b/net/third_party/quic/core/quic_session_test.cc
@@ -1934,8 +1934,11 @@ TEST_P(QuicSessionTestServer, SendMessage) { // Cannot send message when encryption is not established. EXPECT_FALSE(session_.IsCryptoHandshakeConfirmed()); + quic::QuicMemSliceStorage storage(nullptr, 0, nullptr, 0); EXPECT_EQ(MessageResult(MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED, 0), - session_.SendMessage("")); + session_.SendMessage( + MakeSpan(connection_->helper()->GetStreamSendBufferAllocator(), + "", &storage))); // Finish handshake. CryptoHandshakeMessage handshake_message; @@ -1943,23 +1946,29 @@ EXPECT_TRUE(session_.IsCryptoHandshakeConfirmed()); QuicStringPiece message; - QuicMessageFrame frame(1, message); EXPECT_CALL(*connection_, SendMessage(1, _)) .WillOnce(Return(MESSAGE_STATUS_SUCCESS)); EXPECT_EQ(MessageResult(MESSAGE_STATUS_SUCCESS, 1), - session_.SendMessage(message)); + session_.SendMessage( + MakeSpan(connection_->helper()->GetStreamSendBufferAllocator(), + message, &storage))); // Verify message_id increases. EXPECT_CALL(*connection_, SendMessage(2, _)) .WillOnce(Return(MESSAGE_STATUS_TOO_LARGE)); EXPECT_EQ(MessageResult(MESSAGE_STATUS_TOO_LARGE, 0), - session_.SendMessage(message)); + session_.SendMessage( + MakeSpan(connection_->helper()->GetStreamSendBufferAllocator(), + message, &storage))); // Verify unsent message does not consume a message_id. EXPECT_CALL(*connection_, SendMessage(2, _)) .WillOnce(Return(MESSAGE_STATUS_SUCCESS)); - QuicMessageFrame frame2(2, message); EXPECT_EQ(MessageResult(MESSAGE_STATUS_SUCCESS, 2), - session_.SendMessage(message)); + session_.SendMessage( + MakeSpan(connection_->helper()->GetStreamSendBufferAllocator(), + message, &storage))); + QuicMessageFrame frame(1); + QuicMessageFrame frame2(2); EXPECT_FALSE(session_.IsFrameOutstanding(QuicFrame(&frame))); EXPECT_FALSE(session_.IsFrameOutstanding(QuicFrame(&frame2)));
diff --git a/net/third_party/quic/platform/api/quic_mem_slice_span.h b/net/third_party/quic/platform/api/quic_mem_slice_span.h index 73805da4..8c06290 100644 --- a/net/third_party/quic/platform/api/quic_mem_slice_span.h +++ b/net/third_party/quic/platform/api/quic_mem_slice_span.h
@@ -35,6 +35,12 @@ return impl_.SaveMemSlicesInSendBuffer(send_buffer); } + // Save data buffers as message data in |message_frame|. |message_frame| will + // hold a reference to all data buffers. + void SaveMemSlicesAsMessageData(QuicMessageFrame* message_frame) { + impl_.SaveMemSlicesAsMessageData(message_frame); + } + // Return data of the span at |index| by the form of a QuicStringPiece. QuicStringPiece GetData(int index) { return impl_.GetData(index); }
diff --git a/net/third_party/quic/platform/impl/quic_mem_slice_span_impl.cc b/net/third_party/quic/platform/impl/quic_mem_slice_span_impl.cc index 90ac7f4..9be0c78 100644 --- a/net/third_party/quic/platform/impl/quic_mem_slice_span_impl.cc +++ b/net/third_party/quic/platform/impl/quic_mem_slice_span_impl.cc
@@ -4,6 +4,7 @@ #include "net/third_party/quic/platform/impl/quic_mem_slice_span_impl.h" +#include "net/third_party/quic/core/frames/quic_message_frame.h" #include "net/third_party/quic/core/quic_stream_send_buffer.h" #include "net/third_party/quic/platform/api/quic_bug_tracker.h" @@ -41,6 +42,19 @@ return saved_length; } +void QuicMemSliceSpanImpl::SaveMemSlicesAsMessageData( + QuicMessageFrame* message_frame) { + for (size_t i = 0; i < num_buffers_; ++i) { + if (lengths_[i] == 0) { + // Skip empty buffer. + continue; + } + message_frame->message_length += lengths_[i]; + message_frame->message_data.push_back( + QuicMemSlice(QuicMemSliceImpl(buffers_[i], lengths_[i]))); + } +} + QuicByteCount QuicMemSliceSpanImpl::total_length() { QuicByteCount length = 0; for (size_t i = 0; i < num_buffers_; ++i) {
diff --git a/net/third_party/quic/platform/impl/quic_mem_slice_span_impl.h b/net/third_party/quic/platform/impl/quic_mem_slice_span_impl.h index 50e9826..88c0912 100644 --- a/net/third_party/quic/platform/impl/quic_mem_slice_span_impl.h +++ b/net/third_party/quic/platform/impl/quic_mem_slice_span_impl.h
@@ -13,6 +13,7 @@ namespace quic { class QuicStreamSendBuffer; +struct QuicMessageFrame; // QuicMemSliceSpanImpl wraps a MemSlice span. class QUIC_EXPORT_PRIVATE QuicMemSliceSpanImpl { @@ -32,6 +33,9 @@ // saved mem slices. QuicByteCount SaveMemSlicesInSendBuffer(QuicStreamSendBuffer* send_buffer); + // Save data buffers as message data in |message_frame|. + void SaveMemSlicesAsMessageData(QuicMessageFrame* message_frame); + QuicStringPiece GetData(size_t index) { return QuicStringPiece(buffers_[index]->data(), lengths_[index]); }
diff --git a/net/third_party/quic/quartc/quartc_session.cc b/net/third_party/quic/quartc/quartc_session.cc index ff5cff0..f4597cf5 100644 --- a/net/third_party/quic/quartc/quartc_session.cc +++ b/net/third_party/quic/quartc/quartc_session.cc
@@ -6,6 +6,7 @@ #include "net/third_party/quic/core/tls_client_handshaker.h" #include "net/third_party/quic/core/tls_server_handshaker.h" +#include "net/third_party/quic/platform/api/quic_mem_slice_storage.h" #include "net/third_party/quic/platform/api/quic_ptr_util.h" namespace quic { @@ -232,7 +233,12 @@ void QuartcSession::ProcessSendMessageQueue() { while (!send_message_queue_.empty()) { - MessageResult result = SendMessage(send_message_queue_.front()); + struct iovec iov = {const_cast<char*>(send_message_queue_.front().data()), + send_message_queue_.front().length()}; + QuicMemSliceStorage storage( + &iov, 1, connection()->helper()->GetStreamSendBufferAllocator(), + send_message_queue_.front().length()); + MessageResult result = SendMessage(storage.ToSpan()); const size_t message_size = send_message_queue_.front().size();
diff --git a/net/third_party/quic/test_tools/quic_test_utils.cc b/net/third_party/quic/test_tools/quic_test_utils.cc index 237fec7..6a988a1 100644 --- a/net/third_party/quic/test_tools/quic_test_utils.cc +++ b/net/third_party/quic/test_tools/quic_test_utils.cc
@@ -1140,5 +1140,18 @@ : default_type; } +QuicMemSliceSpan MakeSpan(QuicBufferAllocator* allocator, + QuicStringPiece message_data, + QuicMemSliceStorage* storage) { + if (message_data.length() == 0) { + *storage = QuicMemSliceStorage(nullptr, 0, allocator, kMaxPacketSize); + return storage->ToSpan(); + } + struct iovec iov = {const_cast<char*>(message_data.data()), + message_data.length()}; + *storage = QuicMemSliceStorage(&iov, 1, allocator, kMaxPacketSize); + return storage->ToSpan(); +} + } // namespace test } // namespace quic
diff --git a/net/third_party/quic/test_tools/quic_test_utils.h b/net/third_party/quic/test_tools/quic_test_utils.h index 25c8d5c..f48168c 100644 --- a/net/third_party/quic/test_tools/quic_test_utils.h +++ b/net/third_party/quic/test_tools/quic_test_utils.h
@@ -25,6 +25,7 @@ #include "net/third_party/quic/core/quic_packet_writer.h" #include "net/third_party/quic/core/quic_sent_packet_manager.h" #include "net/third_party/quic/core/quic_simple_buffer_allocator.h" +#include "net/third_party/quic/platform/api/quic_mem_slice_storage.h" #include "net/third_party/quic/platform/api/quic_ptr_util.h" #include "net/third_party/quic/platform/api/quic_string_piece.h" #include "net/third_party/quic/test_tools/mock_clock.h" @@ -512,7 +513,7 @@ MOCK_METHOD2(OnStreamReset, void(QuicStreamId, QuicRstStreamErrorCode)); MOCK_METHOD1(SendControlFrame, bool(const QuicFrame& frame)); - MOCK_METHOD2(SendMessage, MessageStatus(QuicMessageId, QuicStringPiece)); + MOCK_METHOD2(SendMessage, MessageStatus(QuicMessageId, QuicMemSliceSpan)); MOCK_METHOD3(OnConnectionClosed, void(QuicErrorCode error, const QuicString& error_details, @@ -1191,6 +1192,12 @@ bool is_incoming, StreamType default_type); +// Utility function that stores message_data in |storage| and returns a +// QuicMemSliceSpan. +QuicMemSliceSpan MakeSpan(QuicBufferAllocator* allocator, + QuicStringPiece message_data, + QuicMemSliceStorage* storage); + } // namespace test } // namespace quic
diff --git a/net/third_party/quic/test_tools/simple_quic_framer.cc b/net/third_party/quic/test_tools/simple_quic_framer.cc index 330dc8d..96278c9 100644 --- a/net/third_party/quic/test_tools/simple_quic_framer.cc +++ b/net/third_party/quic/test_tools/simple_quic_framer.cc
@@ -181,7 +181,7 @@ } bool OnMessageFrame(const QuicMessageFrame& frame) override { - message_frames_.push_back(frame); + message_frames_.emplace_back(frame.data, frame.message_length); return true; }
diff --git a/printing/BUILD.gn b/printing/BUILD.gn index 65cb521e..119a5539 100644 --- a/printing/BUILD.gn +++ b/printing/BUILD.gn
@@ -37,8 +37,6 @@ "metafile.h", "metafile_skia.cc", "metafile_skia.h", - "metafile_skia_wrapper.cc", - "metafile_skia_wrapper.h", "native_drawing_context.h", "nup_parameters.cc", "nup_parameters.h",
diff --git a/printing/metafile_skia_wrapper.cc b/printing/metafile_skia_wrapper.cc deleted file mode 100644 index 1896de70..0000000 --- a/printing/metafile_skia_wrapper.cc +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "printing/metafile_skia_wrapper.h" -#include "third_party/skia/include/core/SkMetaData.h" -#include "third_party/skia/include/core/SkRefCnt.h" - -namespace printing { - -namespace { - -const char kMetafileKey[] = "CrMetafile"; - -} // namespace - -// static -void MetafileSkiaWrapper::SetMetafileOnCanvas(cc::PaintCanvas* canvas, - MetafileSkia* metafile) { - sk_sp<MetafileSkiaWrapper> wrapper; - // Can't use sk_make_sp<>() because the constructor is private. - if (metafile) - wrapper = sk_sp<MetafileSkiaWrapper>(new MetafileSkiaWrapper(metafile)); - - SkMetaData& meta = canvas->getMetaData(); - meta.setRefCnt(kMetafileKey, wrapper.get()); -} - -// static -MetafileSkia* MetafileSkiaWrapper::GetMetafileFromCanvas( - cc::PaintCanvas* canvas) { - SkMetaData& meta = canvas->getMetaData(); - SkRefCnt* value; - if (!meta.findRefCnt(kMetafileKey, &value) || !value) - return nullptr; - - return static_cast<MetafileSkiaWrapper*>(value)->metafile_; -} - -MetafileSkiaWrapper::MetafileSkiaWrapper(MetafileSkia* metafile) - : metafile_(metafile) {} - -} // namespace printing
diff --git a/printing/metafile_skia_wrapper.h b/printing/metafile_skia_wrapper.h deleted file mode 100644 index 8db0915..0000000 --- a/printing/metafile_skia_wrapper.h +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PRINTING_METAFILE_SKIA_WRAPPER_H_ -#define PRINTING_METAFILE_SKIA_WRAPPER_H_ - -#include "cc/paint/paint_canvas.h" -#include "printing/printing_export.h" -#include "third_party/skia/include/core/SkRefCnt.h" - -namespace printing { - -class MetafileSkia; - -// A wrapper class with static methods to set and retrieve a MetafileSkia -// on an SkCanvas. The ownership of the metafile is not affected and it -// is the caller's responsibility to ensure that the metafile remains valid -// as long as the canvas. -class PRINTING_EXPORT MetafileSkiaWrapper : public SkRefCnt { - public: - static void SetMetafileOnCanvas(cc::PaintCanvas* canvas, - MetafileSkia* metafile); - - static MetafileSkia* GetMetafileFromCanvas(cc::PaintCanvas* canvas); - - private: - explicit MetafileSkiaWrapper(MetafileSkia* metafile); - - MetafileSkia* metafile_; -}; - -} // namespace printing - -#endif // PRINTING_METAFILE_SKIA_WRAPPER_H_
diff --git a/remoting/client/plugin/chromoting_instance.cc b/remoting/client/plugin/chromoting_instance.cc index 352d366..59a5390 100644 --- a/remoting/client/plugin/chromoting_instance.cc +++ b/remoting/client/plugin/chromoting_instance.cc
@@ -228,14 +228,17 @@ // Initialize TaskScheduler. TaskScheduler::StartWithDefaultParams() doesn't // work on NACL. base::TaskScheduler::Create("RemotingChromeApp"); - // TODO(etiennep): Change this to 2 in future CL. - constexpr int kBackgroundMaxThreads = 3; - constexpr int kForegroundMaxThreads = 3; + constexpr int kBackgroundMaxThreads = 1; + constexpr int kBackgroundBlockingMaxThreads = 2; + constexpr int kForegroundMaxThreads = 1; + constexpr int kForegroundBlockingMaxThreads = 2; constexpr base::TimeDelta kSuggestedReclaimTime = base::TimeDelta::FromSeconds(30); base::TaskScheduler::GetInstance()->Start( {{kBackgroundMaxThreads, kSuggestedReclaimTime}, - {kForegroundMaxThreads, kSuggestedReclaimTime}}); + {kBackgroundBlockingMaxThreads, kSuggestedReclaimTime}, + {kForegroundMaxThreads, kSuggestedReclaimTime}, + {kForegroundBlockingMaxThreads, kSuggestedReclaimTime}}); return true; }
diff --git a/remoting/host/setup/start_host_main.cc b/remoting/host/setup/start_host_main.cc index b64b41e..8a7898b1 100644 --- a/remoting/host/setup/start_host_main.cc +++ b/remoting/host/setup/start_host_main.cc
@@ -119,10 +119,6 @@ g_active_run_loop->Quit(); } -std::string GetAuthorizationCodeUri() { - return remoting::GetOauthStartUrl(remoting::GetDefaultOauthRedirectUrl()); -} - } // namespace int StartHostMain(int argc, char** argv) { @@ -175,6 +171,14 @@ return 1; } + if (auth_code.empty() || redirect_url.empty()) { + fprintf(stdout, + "You need a web browser to use this command. Please visit\n"); + fprintf(stdout, + "https://remotedesktop.google.com/headless for instructions.\n"); + return 1; + } + if (host_name.empty()) { fprintf(stdout, "Enter a name for this computer: "); fflush(stdout); @@ -210,14 +214,6 @@ } } - if (auth_code.empty()) { - fprintf(stdout, "\nAuthorization URL for Production services:\n"); - fprintf(stdout, "%s\n\n", GetAuthorizationCodeUri().c_str()); - fprintf(stdout, "Enter an authorization code: "); - fflush(stdout); - auth_code = ReadString(true); - } - // Provide message loops and threads for the URLRequestContextGetter. base::MessageLoop message_loop; g_message_loop = &message_loop; @@ -236,9 +232,6 @@ std::unique_ptr<HostStarter> host_starter(HostStarter::Create( remoting::ServiceUrls::GetInstance()->directory_hosts_url(), url_loader_factory_owner.GetURLLoaderFactory())); - if (redirect_url.empty()) { - redirect_url = remoting::GetDefaultOauthRedirectUrl(); - } host_starter->StartHost(host_name, host_pin, /*consent_to_data_collection=*/true, auth_code, redirect_url, base::Bind(&OnDone));
diff --git a/services/identity/public/cpp/DEPS b/services/identity/public/cpp/DEPS index 01ac2ce..8084961 100644 --- a/services/identity/public/cpp/DEPS +++ b/services/identity/public/cpp/DEPS
@@ -26,5 +26,8 @@ "identity_manager_unittest.cc": [ "+google_apis/gaia/oauth2_token_service_delegate.h", "+services/network/test/test_url_loader_factory.h", + ], + "accounts_mutator_impl_unittest.cc": [ + "+components/image_fetcher" ] }
diff --git a/services/resource_coordinator/BUILD.gn b/services/resource_coordinator/BUILD.gn index 2462ccdf..ba407a5 100644 --- a/services/resource_coordinator/BUILD.gn +++ b/services/resource_coordinator/BUILD.gn
@@ -9,22 +9,6 @@ # Others modules should only need the public targets. source_set("lib") { sources = [ - "coordination_unit/coordination_unit_base.cc", - "coordination_unit/coordination_unit_base.h", - "coordination_unit/coordination_unit_graph.cc", - "coordination_unit/coordination_unit_graph.h", - "coordination_unit/coordination_unit_introspector_impl.cc", - "coordination_unit/coordination_unit_introspector_impl.h", - "coordination_unit/coordination_unit_provider_impl.cc", - "coordination_unit/coordination_unit_provider_impl.h", - "coordination_unit/frame_coordination_unit_impl.cc", - "coordination_unit/frame_coordination_unit_impl.h", - "coordination_unit/page_coordination_unit_impl.cc", - "coordination_unit/page_coordination_unit_impl.h", - "coordination_unit/process_coordination_unit_impl.cc", - "coordination_unit/process_coordination_unit_impl.h", - "coordination_unit/system_coordination_unit_impl.cc", - "coordination_unit/system_coordination_unit_impl.h", "memory_instrumentation/coordinator_impl.cc", "memory_instrumentation/coordinator_impl.h", "memory_instrumentation/graph.cc", @@ -39,21 +23,8 @@ "memory_instrumentation/queued_request_dispatcher.h", "memory_instrumentation/switches.cc", "memory_instrumentation/switches.h", - "observers/background_metrics_reporter.h", - "observers/coordination_unit_graph_observer.cc", - "observers/coordination_unit_graph_observer.h", - "observers/metrics_collector.cc", - "observers/metrics_collector.h", - "observers/page_signal_generator_impl.cc", - "observers/page_signal_generator_impl.h", - "observers/working_set_trimmer_win.cc", - "observers/working_set_trimmer_win.h", - "resource_coordinator_clock.cc", - "resource_coordinator_clock.h", "resource_coordinator_service.cc", "resource_coordinator_service.h", - "webui_graph_dump_impl.cc", - "webui_graph_dump_impl.h", ] configs += [ "//build/config/compiler:wexit_time_destructors" ] @@ -77,34 +48,15 @@ testonly = true sources = [ - "coordination_unit/coordination_unit_base_unittest.cc", - "coordination_unit/coordination_unit_graph_unittest.cc", - "coordination_unit/coordination_unit_test_harness.cc", - "coordination_unit/coordination_unit_test_harness.h", - "coordination_unit/frame_coordination_unit_impl_unittest.cc", - "coordination_unit/mock_coordination_unit_graphs.cc", - "coordination_unit/mock_coordination_unit_graphs.h", - "coordination_unit/page_coordination_unit_impl_unittest.cc", - "coordination_unit/process_coordination_unit_impl_unittest.cc", - "coordination_unit/system_coordination_unit_impl_unittest.cc", "memory_instrumentation/coordinator_impl_unittest.cc", "memory_instrumentation/graph_processor_unittest.cc", "memory_instrumentation/graph_unittest.cc", "memory_instrumentation/process_map_unittest.cc", - "observers/coordination_unit_graph_observer_unittest.cc", - "observers/metrics_collector_unittest.cc", - "observers/page_signal_generator_impl_unittest.cc", - "observers/working_set_trimmer_win_unittest.cc", "public/cpp/memory_instrumentation/memory_instrumentation_mojom_traits_unittest.cc", "public/cpp/memory_instrumentation/os_metrics_unittest.cc", "public/cpp/memory_instrumentation/tracing_integration_unittest.cc", - "webui_graph_dump_impl_unittest.cc", ] - if (!is_android) { - sources += [ "resource_coordinator_service_unittest.cc" ] - } - deps = [ ":lib", "//base", @@ -112,6 +64,7 @@ "//components/ukm:test_support", "//mojo/public/cpp/bindings", "//services/resource_coordinator/public/cpp:resource_coordinator_cpp", + "//services/resource_coordinator/public/cpp/memory_instrumentation:memory_instrumentation", "//services/service_manager/public/cpp", "//services/service_manager/public/cpp/test:test_support", "//services/service_manager/public/mojom",
diff --git a/services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h b/services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h deleted file mode 100644 index 949e19f..0000000 --- a/services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h +++ /dev/null
@@ -1,107 +0,0 @@ -// Copyright 2017 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 SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_FRAME_COORDINATION_UNIT_IMPL_H_ -#define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_FRAME_COORDINATION_UNIT_IMPL_H_ - -#include "base/macros.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_base.h" - -namespace resource_coordinator { - -class PageCoordinationUnitImpl; -class ProcessCoordinationUnitImpl; - -// Frame Coordination Units form a tree structure, each FrameCoordinationUnit at -// most has one parent that is a FrameCoordinationUnit. -// A Frame Coordination Unit will have parents only if navigation committed. -class FrameCoordinationUnitImpl - : public CoordinationUnitInterface<FrameCoordinationUnitImpl, - mojom::FrameCoordinationUnit, - mojom::FrameCoordinationUnitRequest> { - public: - static CoordinationUnitType Type() { return CoordinationUnitType::kFrame; } - - FrameCoordinationUnitImpl( - const CoordinationUnitID& id, - CoordinationUnitGraph* graph, - std::unique_ptr<service_manager::ServiceKeepaliveRef> keepalive_ref); - ~FrameCoordinationUnitImpl() override; - - // FrameCoordinationUnit implementation. - void SetProcess(const CoordinationUnitID& cu_id) override; - void AddChildFrame(const CoordinationUnitID& cu_id) override; - void RemoveChildFrame(const CoordinationUnitID& cu_id) override; - void SetNetworkAlmostIdle(bool idle) override; - void SetLifecycleState(mojom::LifecycleState state) override; - void SetHasNonEmptyBeforeUnload(bool has_nonempty_beforeunload) override; - void SetInterventionPolicy(mojom::PolicyControlledIntervention intervention, - mojom::InterventionPolicy policy) override; - void OnNonPersistentNotificationCreated() override; - - FrameCoordinationUnitImpl* GetParentFrameCoordinationUnit() const; - PageCoordinationUnitImpl* GetPageCoordinationUnit() const; - ProcessCoordinationUnitImpl* GetProcessCoordinationUnit() const; - bool IsMainFrame() const; - - mojom::LifecycleState lifecycle_state() const { return lifecycle_state_; } - bool has_nonempty_beforeunload() const { return has_nonempty_beforeunload_; } - - // Returns true if all intervention policies have been set for this frame. - bool AreAllInterventionPoliciesSet() const; - - const std::set<FrameCoordinationUnitImpl*>& - child_frame_coordination_units_for_testing() const { - return child_frame_coordination_units_; - } - - // Sets the same policy for all intervention types in this frame. Causes - // Page::OnFrameInterventionPolicyChanged to be invoked. - void SetAllInterventionPoliciesForTesting(mojom::InterventionPolicy policy); - - private: - friend class PageCoordinationUnitImpl; - friend class ProcessCoordinationUnitImpl; - - // CoordinationUnitInterface implementation. - void OnEventReceived(mojom::Event event) override; - void OnPropertyChanged(mojom::PropertyType property_type, - int64_t value) override; - - bool HasFrameCoordinationUnitInAncestors( - FrameCoordinationUnitImpl* frame_cu) const; - bool HasFrameCoordinationUnitInDescendants( - FrameCoordinationUnitImpl* frame_cu) const; - - // The following methods will be called by other FrameCoordinationUnitImpl, - // PageCoordinationUnitImpl and ProcessCoordinationUnitImpl respectively to - // manipulate their relationship. - void AddParentFrame(FrameCoordinationUnitImpl* parent_frame_cu); - bool AddChildFrame(FrameCoordinationUnitImpl* child_frame_cu); - void RemoveParentFrame(FrameCoordinationUnitImpl* parent_frame_cu); - bool RemoveChildFrame(FrameCoordinationUnitImpl* child_frame_cu); - void AddPageCoordinationUnit(PageCoordinationUnitImpl* page_cu); - void AddProcessCoordinationUnit(ProcessCoordinationUnitImpl* process_cu); - void RemovePageCoordinationUnit(PageCoordinationUnitImpl* page_cu); - void RemoveProcessCoordinationUnit(ProcessCoordinationUnitImpl* process_cu); - - FrameCoordinationUnitImpl* parent_frame_coordination_unit_; - PageCoordinationUnitImpl* page_coordination_unit_; - ProcessCoordinationUnitImpl* process_coordination_unit_; - std::set<FrameCoordinationUnitImpl*> child_frame_coordination_units_; - - mojom::LifecycleState lifecycle_state_ = mojom::LifecycleState::kRunning; - bool has_nonempty_beforeunload_ = false; - - // Intervention policy for this frame. These are communicated from the - // renderer process and are controlled by origin trials. - mojom::InterventionPolicy intervention_policy_ - [static_cast<size_t>(mojom::PolicyControlledIntervention::kMaxValue) + 1]; - - DISALLOW_COPY_AND_ASSIGN(FrameCoordinationUnitImpl); -}; - -} // namespace resource_coordinator - -#endif // SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_FRAME_COORDINATION_UNIT_IMPL_H_
diff --git a/services/resource_coordinator/coordination_unit/page_coordination_unit_impl_unittest.cc b/services/resource_coordinator/coordination_unit/page_coordination_unit_impl_unittest.cc deleted file mode 100644 index fc1a4be..0000000 --- a/services/resource_coordinator/coordination_unit/page_coordination_unit_impl_unittest.cc +++ /dev/null
@@ -1,426 +0,0 @@ -// Copyright 2017 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 "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" - -#include "base/test/simple_test_tick_clock.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_test_harness.h" -#include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/mock_coordination_unit_graphs.h" -#include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" -#include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" -#include "services/resource_coordinator/resource_coordinator_clock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace resource_coordinator { - -namespace { - -class PageCoordinationUnitImplTest : public CoordinationUnitTestHarness { - public: - void SetUp() override { - ResourceCoordinatorClock::SetClockForTesting(&clock_); - - // Sets a valid starting time. - clock_.SetNowTicks(base::TimeTicks::Now()); - } - - void TearDown() override { - ResourceCoordinatorClock::ResetClockForTesting(); - } - - protected: - void AdvanceClock(base::TimeDelta delta) { clock_.Advance(delta); } - - private: - base::SimpleTestTickClock clock_; -}; - -} // namespace - -TEST_F(PageCoordinationUnitImplTest, AddFrameBasic) { - auto page_cu = CreateCoordinationUnit<PageCoordinationUnitImpl>(); - auto frame1_cu = CreateCoordinationUnit<FrameCoordinationUnitImpl>(); - auto frame2_cu = CreateCoordinationUnit<FrameCoordinationUnitImpl>(); - auto frame3_cu = CreateCoordinationUnit<FrameCoordinationUnitImpl>(); - - page_cu->AddFrame(frame1_cu->id()); - page_cu->AddFrame(frame2_cu->id()); - page_cu->AddFrame(frame3_cu->id()); - EXPECT_EQ(3u, page_cu->GetFrameCoordinationUnits().size()); -} - -TEST_F(PageCoordinationUnitImplTest, AddReduplicativeFrame) { - auto page_cu = CreateCoordinationUnit<PageCoordinationUnitImpl>(); - auto frame1_cu = CreateCoordinationUnit<FrameCoordinationUnitImpl>(); - auto frame2_cu = CreateCoordinationUnit<FrameCoordinationUnitImpl>(); - - page_cu->AddFrame(frame1_cu->id()); - page_cu->AddFrame(frame2_cu->id()); - page_cu->AddFrame(frame1_cu->id()); - EXPECT_EQ(2u, page_cu->GetFrameCoordinationUnits().size()); -} - -TEST_F(PageCoordinationUnitImplTest, RemoveFrame) { - auto page_cu = CreateCoordinationUnit<PageCoordinationUnitImpl>(); - auto frame_cu = CreateCoordinationUnit<FrameCoordinationUnitImpl>(); - - // Parent-child relationships have not been established yet. - EXPECT_EQ(0u, page_cu->GetFrameCoordinationUnits().size()); - EXPECT_FALSE(frame_cu->GetPageCoordinationUnit()); - - page_cu->AddFrame(frame_cu->id()); - - // Ensure correct Parent-child relationships have been established. - EXPECT_EQ(1u, page_cu->GetFrameCoordinationUnits().size()); - EXPECT_EQ(1u, page_cu->GetFrameCoordinationUnits().count(frame_cu.get())); - EXPECT_EQ(page_cu.get(), frame_cu->GetPageCoordinationUnit()); - - page_cu->RemoveFrame(frame_cu->id()); - - // Parent-child relationships should no longer exist. - EXPECT_EQ(0u, page_cu->GetFrameCoordinationUnits().size()); - EXPECT_FALSE(frame_cu->GetPageCoordinationUnit()); -} - -TEST_F(PageCoordinationUnitImplTest, - CalculatePageCPUUsageForSinglePageInSingleProcess) { - MockSinglePageInSingleProcessCoordinationUnitGraph cu_graph( - coordination_unit_graph()); - cu_graph.process->SetCPUUsage(40); - EXPECT_EQ(40, cu_graph.page->GetCPUUsage()); -} - -TEST_F(PageCoordinationUnitImplTest, - CalculatePageCPUUsageForMultiplePagesInSingleProcess) { - MockMultiplePagesInSingleProcessCoordinationUnitGraph cu_graph( - coordination_unit_graph()); - cu_graph.process->SetCPUUsage(40); - EXPECT_EQ(20, cu_graph.page->GetCPUUsage()); - EXPECT_EQ(20, cu_graph.other_page->GetCPUUsage()); -} - -TEST_F(PageCoordinationUnitImplTest, - CalculatePageCPUUsageForSinglePageWithMultipleProcesses) { - MockSinglePageWithMultipleProcessesCoordinationUnitGraph cu_graph( - coordination_unit_graph()); - cu_graph.process->SetCPUUsage(40); - cu_graph.other_process->SetCPUUsage(30); - EXPECT_EQ(70, cu_graph.page->GetCPUUsage()); -} - -TEST_F(PageCoordinationUnitImplTest, - CalculatePageCPUUsageForMultiplePagesWithMultipleProcesses) { - MockMultiplePagesWithMultipleProcessesCoordinationUnitGraph cu_graph( - coordination_unit_graph()); - cu_graph.process->SetCPUUsage(40); - cu_graph.other_process->SetCPUUsage(30); - EXPECT_EQ(20, cu_graph.page->GetCPUUsage()); - EXPECT_EQ(50, cu_graph.other_page->GetCPUUsage()); -} - -TEST_F(PageCoordinationUnitImplTest, - CalculatePageEQTForSinglePageInSingleProcess) { - MockSinglePageInSingleProcessCoordinationUnitGraph cu_graph( - coordination_unit_graph()); - - cu_graph.process->SetExpectedTaskQueueingDuration( - base::TimeDelta::FromMilliseconds(1)); - - int64_t eqt; - EXPECT_TRUE(cu_graph.page->GetExpectedTaskQueueingDuration(&eqt)); - EXPECT_EQ(1, eqt); -} - -TEST_F(PageCoordinationUnitImplTest, - CalculatePageEQTForMultiplePagesInSingleProcess) { - MockMultiplePagesInSingleProcessCoordinationUnitGraph cu_graph( - coordination_unit_graph()); - - cu_graph.process->SetExpectedTaskQueueingDuration( - base::TimeDelta::FromMilliseconds(1)); - - int64_t eqt; - EXPECT_TRUE(cu_graph.page->GetExpectedTaskQueueingDuration(&eqt)); - EXPECT_EQ(1, eqt); - eqt = 0; - EXPECT_TRUE(cu_graph.other_page->GetExpectedTaskQueueingDuration(&eqt)); - EXPECT_EQ(1, eqt); -} - -TEST_F(PageCoordinationUnitImplTest, TimeSinceLastVisibilityChange) { - MockSinglePageInSingleProcessCoordinationUnitGraph cu_graph( - coordination_unit_graph()); - - cu_graph.page->SetVisibility(true); - EXPECT_TRUE(cu_graph.page->IsVisible()); - AdvanceClock(base::TimeDelta::FromSeconds(42)); - EXPECT_EQ(base::TimeDelta::FromSeconds(42), - cu_graph.page->TimeSinceLastVisibilityChange()); - - cu_graph.page->SetVisibility(false); - AdvanceClock(base::TimeDelta::FromSeconds(23)); - EXPECT_EQ(base::TimeDelta::FromSeconds(23), - cu_graph.page->TimeSinceLastVisibilityChange()); - EXPECT_FALSE(cu_graph.page->IsVisible()); -} - -TEST_F(PageCoordinationUnitImplTest, TimeSinceLastNavigation) { - MockSinglePageInSingleProcessCoordinationUnitGraph cu_graph( - coordination_unit_graph()); - // Before any commit events, timedelta should be 0. - EXPECT_TRUE(cu_graph.page->TimeSinceLastNavigation().is_zero()); - - // 1st navigation. - cu_graph.page->OnMainFrameNavigationCommitted( - ResourceCoordinatorClock::NowTicks(), 10u, "http://www.example.org"); - EXPECT_EQ("http://www.example.org", cu_graph.page->main_frame_url()); - EXPECT_EQ(10u, cu_graph.page->navigation_id()); - AdvanceClock(base::TimeDelta::FromSeconds(11)); - EXPECT_EQ(base::TimeDelta::FromSeconds(11), - cu_graph.page->TimeSinceLastNavigation()); - - // 2nd navigation. - cu_graph.page->OnMainFrameNavigationCommitted( - ResourceCoordinatorClock::NowTicks(), 20u, - "http://www.example.org/bobcat"); - EXPECT_EQ("http://www.example.org/bobcat", cu_graph.page->main_frame_url()); - EXPECT_EQ(20u, cu_graph.page->navigation_id()); - AdvanceClock(base::TimeDelta::FromSeconds(17)); - EXPECT_EQ(base::TimeDelta::FromSeconds(17), - cu_graph.page->TimeSinceLastNavigation()); -} - -TEST_F(PageCoordinationUnitImplTest, IsLoading) { - MockSinglePageInSingleProcessCoordinationUnitGraph cu_graph( - coordination_unit_graph()); - auto* page_cu = cu_graph.page.get(); - - // First attempt should fail, as the property is unset. - int64_t loading = 0; - EXPECT_FALSE(page_cu->GetProperty(mojom::PropertyType::kIsLoading, &loading)); - - // Set to false and the property should read false. - page_cu->SetIsLoading(false); - EXPECT_TRUE(page_cu->GetProperty(mojom::PropertyType::kIsLoading, &loading)); - EXPECT_EQ(0u, loading); - - // Set to true and the property should read true. - page_cu->SetIsLoading(true); - EXPECT_TRUE(page_cu->GetProperty(mojom::PropertyType::kIsLoading, &loading)); - EXPECT_EQ(1u, loading); - - // Set to false and the property should read false again. - page_cu->SetIsLoading(false); - EXPECT_TRUE(page_cu->GetProperty(mojom::PropertyType::kIsLoading, &loading)); - EXPECT_EQ(0u, loading); -} - -TEST_F(PageCoordinationUnitImplTest, OnAllFramesInPageFrozen) { - const int64_t kRunning = - static_cast<int64_t>(mojom::LifecycleState::kRunning); - const int64_t kFrozen = static_cast<int64_t>(mojom::LifecycleState::kFrozen); - - MockSinglePageWithMultipleProcessesCoordinationUnitGraph cu_graph( - coordination_unit_graph()); - - EXPECT_EQ(kRunning, cu_graph.page->GetPropertyOrDefault( - mojom::PropertyType::kLifecycleState, kRunning)); - - // 1/2 frames in the page is frozen. Expect the page to still be running. - cu_graph.frame->SetLifecycleState(mojom::LifecycleState::kFrozen); - EXPECT_EQ(kRunning, cu_graph.page->GetPropertyOrDefault( - mojom::PropertyType::kLifecycleState, kRunning)); - - // 2/2 frames in the process are frozen. We expect the page to be frozen. - cu_graph.child_frame->SetLifecycleState(mojom::LifecycleState::kFrozen); - EXPECT_EQ(kFrozen, cu_graph.page->GetPropertyOrDefault( - mojom::PropertyType::kLifecycleState, kRunning)); - - // Unfreeze a frame and expect the page to be running again. - cu_graph.frame->SetLifecycleState(mojom::LifecycleState::kRunning); - EXPECT_EQ(kRunning, cu_graph.page->GetPropertyOrDefault( - mojom::PropertyType::kLifecycleState, kRunning)); - - // Refreeze that frame and expect the page to be frozen again. - cu_graph.frame->SetLifecycleState(mojom::LifecycleState::kFrozen); - EXPECT_EQ(kFrozen, cu_graph.page->GetPropertyOrDefault( - mojom::PropertyType::kLifecycleState, kRunning)); -} - -namespace { - -const size_t kInterventionCount = - static_cast<size_t>(mojom::PolicyControlledIntervention::kMaxValue) + 1; - -void ExpectRawInterventionPolicy(mojom::InterventionPolicy policy, - const PageCoordinationUnitImpl* page_cu) { - for (size_t i = 0; i < kInterventionCount; ++i) { - EXPECT_EQ(policy, page_cu->GetRawInterventionPolicyForTesting( - static_cast<mojom::PolicyControlledIntervention>(i))); - } -} - -void ExpectInterventionPolicy(mojom::InterventionPolicy policy, - PageCoordinationUnitImpl* page_cu) { - for (size_t i = 0; i < kInterventionCount; ++i) { - EXPECT_EQ(policy, page_cu->GetInterventionPolicy( - static_cast<mojom::PolicyControlledIntervention>(i))); - } -} - -void ExpectInitialInterventionPolicyAggregationWorks( - CoordinationUnitGraph* cu_graph, - mojom::InterventionPolicy f0_policy, - mojom::InterventionPolicy f1_policy, - mojom::InterventionPolicy f0_policy_aggregated, - mojom::InterventionPolicy f0f1_policy_aggregated) { - // Create two frames not tied to any page. - TestCoordinationUnitWrapper<FrameCoordinationUnitImpl> f0 = - TestCoordinationUnitWrapper<FrameCoordinationUnitImpl>::Create(cu_graph); - TestCoordinationUnitWrapper<FrameCoordinationUnitImpl> f1 = - TestCoordinationUnitWrapper<FrameCoordinationUnitImpl>::Create(cu_graph); - - // Set frame policies before attaching to a page CU. - f0->SetAllInterventionPoliciesForTesting(f0_policy); - f1->SetAllInterventionPoliciesForTesting(f1_policy); - - // Check the initial values before any frames are added. - TestCoordinationUnitWrapper<PageCoordinationUnitImpl> page = - TestCoordinationUnitWrapper<PageCoordinationUnitImpl>::Create(cu_graph); - EXPECT_EQ(0u, page->GetInterventionPolicyFramesReportedForTesting()); - ExpectRawInterventionPolicy(mojom::InterventionPolicy::kUnknown, page.get()); - ExpectInterventionPolicy(mojom::InterventionPolicy::kUnknown, page.get()); - - // Add a frame and expect the values to be invalidated. Reaggregate and - // ensure the appropriate value results. - page->AddFrame(f0->id()); - EXPECT_EQ(1u, page->GetInterventionPolicyFramesReportedForTesting()); - ExpectRawInterventionPolicy(mojom::InterventionPolicy::kUnknown, page.get()); - ExpectInterventionPolicy(f0_policy_aggregated, page.get()); - - // Do it again. This time the raw values should be the same as the - // aggregated values above. - page->AddFrame(f1->id()); - EXPECT_EQ(2u, page->GetInterventionPolicyFramesReportedForTesting()); - ExpectRawInterventionPolicy(mojom::InterventionPolicy::kUnknown, page.get()); - ExpectInterventionPolicy(f0f1_policy_aggregated, page.get()); - - // Remove a frame and expect the values to be invalidated again. - f1.reset(); - EXPECT_EQ(1u, page->GetInterventionPolicyFramesReportedForTesting()); - ExpectRawInterventionPolicy(mojom::InterventionPolicy::kUnknown, page.get()); - ExpectInterventionPolicy(f0_policy_aggregated, page.get()); -} - -} // namespace - -TEST_F(PageCoordinationUnitImplTest, InitialInterventionPolicy) { - auto* cu_graph = coordination_unit_graph(); - - // Tests all possible transitions where the frame CU has its policy values - // set before being attached to the page CU. This affectively tests the - // aggregation logic in isolation. - - // Default x [Default, OptIn, OptOut] - - ExpectInitialInterventionPolicyAggregationWorks( - cu_graph, mojom::InterventionPolicy::kDefault /* f0_policy */, - mojom::InterventionPolicy::kDefault /* f1_policy */, - mojom::InterventionPolicy::kDefault /* f0_policy_aggregated */, - mojom::InterventionPolicy::kDefault /* f0f1_policy_aggregated */); - - ExpectInitialInterventionPolicyAggregationWorks( - cu_graph, mojom::InterventionPolicy::kDefault /* f0_policy */, - mojom::InterventionPolicy::kOptIn /* f1_policy */, - mojom::InterventionPolicy::kDefault /* f0_policy_aggregated */, - mojom::InterventionPolicy::kOptIn /* f0f1_policy_aggregated */); - - ExpectInitialInterventionPolicyAggregationWorks( - cu_graph, mojom::InterventionPolicy::kDefault /* f0_policy */, - mojom::InterventionPolicy::kOptOut /* f1_policy */, - mojom::InterventionPolicy::kDefault /* f0_policy_aggregated */, - mojom::InterventionPolicy::kOptOut /* f0f1_policy_aggregated */); - - // OptIn x [Default, OptIn, OptOut] - - ExpectInitialInterventionPolicyAggregationWorks( - cu_graph, mojom::InterventionPolicy::kOptIn /* f0_policy */, - mojom::InterventionPolicy::kDefault /* f1_policy */, - mojom::InterventionPolicy::kOptIn /* f0_policy_aggregated */, - mojom::InterventionPolicy::kOptIn /* f0f1_policy_aggregated */); - - ExpectInitialInterventionPolicyAggregationWorks( - cu_graph, mojom::InterventionPolicy::kOptIn /* f0_policy */, - mojom::InterventionPolicy::kOptIn /* f1_policy */, - mojom::InterventionPolicy::kOptIn /* f0_policy_aggregated */, - mojom::InterventionPolicy::kOptIn /* f0f1_policy_aggregated */); - - ExpectInitialInterventionPolicyAggregationWorks( - cu_graph, mojom::InterventionPolicy::kOptIn /* f0_policy */, - mojom::InterventionPolicy::kOptOut /* f1_policy */, - mojom::InterventionPolicy::kOptIn /* f0_policy_aggregated */, - mojom::InterventionPolicy::kOptOut /* f0f1_policy_aggregated */); - - // OptOut x [Default, OptIn, OptOut] - - ExpectInitialInterventionPolicyAggregationWorks( - cu_graph, mojom::InterventionPolicy::kOptOut /* f0_policy */, - mojom::InterventionPolicy::kDefault /* f1_policy */, - mojom::InterventionPolicy::kOptOut /* f0_policy_aggregated */, - mojom::InterventionPolicy::kOptOut /* f0f1_policy_aggregated */); - - ExpectInitialInterventionPolicyAggregationWorks( - cu_graph, mojom::InterventionPolicy::kOptOut /* f0_policy */, - mojom::InterventionPolicy::kOptIn /* f1_policy */, - mojom::InterventionPolicy::kOptOut /* f0_policy_aggregated */, - mojom::InterventionPolicy::kOptOut /* f0f1_policy_aggregated */); - - ExpectInitialInterventionPolicyAggregationWorks( - cu_graph, mojom::InterventionPolicy::kOptOut /* f0_policy */, - mojom::InterventionPolicy::kOptOut /* f1_policy */, - mojom::InterventionPolicy::kOptOut /* f0_policy_aggregated */, - mojom::InterventionPolicy::kOptOut /* f0f1_policy_aggregated */); -} - -TEST_F(PageCoordinationUnitImplTest, IncrementalInterventionPolicy) { - auto* cu_graph = coordination_unit_graph(); - - TestCoordinationUnitWrapper<PageCoordinationUnitImpl> page = - TestCoordinationUnitWrapper<PageCoordinationUnitImpl>::Create(cu_graph); - - // Create two frames and immediately attach them to the page. - TestCoordinationUnitWrapper<FrameCoordinationUnitImpl> f0 = - TestCoordinationUnitWrapper<FrameCoordinationUnitImpl>::Create(cu_graph); - TestCoordinationUnitWrapper<FrameCoordinationUnitImpl> f1 = - TestCoordinationUnitWrapper<FrameCoordinationUnitImpl>::Create(cu_graph); - EXPECT_EQ(0u, page->GetInterventionPolicyFramesReportedForTesting()); - page->AddFrame(f0->id()); - EXPECT_EQ(0u, page->GetInterventionPolicyFramesReportedForTesting()); - page->AddFrame(f1->id()); - EXPECT_EQ(0u, page->GetInterventionPolicyFramesReportedForTesting()); - - // Set the policies on the first frame. This should be observed by the page - // CU, but aggregation should still not be possible. - f0->SetAllInterventionPoliciesForTesting(mojom::InterventionPolicy::kDefault); - EXPECT_EQ(1u, page->GetInterventionPolicyFramesReportedForTesting()); - ExpectRawInterventionPolicy(mojom::InterventionPolicy::kUnknown, page.get()); - ExpectInterventionPolicy(mojom::InterventionPolicy::kUnknown, page.get()); - - // Now set the policy on the second frame. This should be observed and an - // aggregated page policy value should now be available. - f1->SetAllInterventionPoliciesForTesting(mojom::InterventionPolicy::kDefault); - EXPECT_EQ(2u, page->GetInterventionPolicyFramesReportedForTesting()); - ExpectRawInterventionPolicy(mojom::InterventionPolicy::kUnknown, page.get()); - ExpectInterventionPolicy(mojom::InterventionPolicy::kDefault, page.get()); - - // Change the policy value on a frame and expect a new aggregation to be - // required. - f1->SetAllInterventionPoliciesForTesting(mojom::InterventionPolicy::kOptIn); - EXPECT_EQ(2u, page->GetInterventionPolicyFramesReportedForTesting()); - ExpectRawInterventionPolicy(mojom::InterventionPolicy::kUnknown, page.get()); - ExpectInterventionPolicy(mojom::InterventionPolicy::kOptIn, page.get()); -} - -} // namespace resource_coordinator
diff --git a/services/resource_coordinator/coordination_unit/system_coordination_unit_impl.h b/services/resource_coordinator/coordination_unit/system_coordination_unit_impl.h deleted file mode 100644 index 123508d..0000000 --- a/services/resource_coordinator/coordination_unit/system_coordination_unit_impl.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_SYSTEM_COORDINATION_UNIT_IMPL_H_ -#define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_SYSTEM_COORDINATION_UNIT_IMPL_H_ - -#include "base/macros.h" -#include "base/time/time.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_base.h" - -namespace resource_coordinator { - -class SystemCoordinationUnitImpl - : public CoordinationUnitInterface<SystemCoordinationUnitImpl, - mojom::SystemCoordinationUnit, - mojom::SystemCoordinationUnitRequest> { - public: - static CoordinationUnitType Type() { return CoordinationUnitType::kSystem; } - - SystemCoordinationUnitImpl( - const CoordinationUnitID& id, - CoordinationUnitGraph* graph, - std::unique_ptr<service_manager::ServiceKeepaliveRef> keepalive_ref); - ~SystemCoordinationUnitImpl() override; - - // mojom::SystemCoordinationUnit implementation: - void OnProcessCPUUsageReady() override; - void DistributeMeasurementBatch( - mojom::ProcessResourceMeasurementBatchPtr measurement_batch) override; - - // Accessors for the start/end times bracketing when the last performance - // measurement occurred. - base::TimeTicks last_measurement_start_time() const { - return last_measurement_start_time_; - } - base::TimeTicks last_measurement_end_time() const { - return last_measurement_end_time_; - } - - private: - base::TimeTicks last_measurement_start_time_; - base::TimeTicks last_measurement_end_time_; - - // CoordinationUnitInterface implementation: - void OnEventReceived(mojom::Event event) override; - void OnPropertyChanged(mojom::PropertyType property_type, - int64_t value) override; - - DISALLOW_COPY_AND_ASSIGN(SystemCoordinationUnitImpl); -}; - -} // namespace resource_coordinator - -#endif // SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_SYSTEM_COORDINATION_UNIT_IMPL_H_
diff --git a/services/resource_coordinator/manifest.json b/services/resource_coordinator/manifest.json index 4350409..d1ed8ff 100644 --- a/services/resource_coordinator/manifest.json +++ b/services/resource_coordinator/manifest.json
@@ -10,13 +10,7 @@ "app": [ "memory_instrumentation.mojom.Coordinator" ], - "coordination_unit_introspector": [ - "resource_coordinator.mojom.CoordinationUnitIntrospector" - ], - "coordination_unit": [ "resource_coordinator.mojom.CoordinationUnitProvider" ], "heap_profiler_helper": [ "memory_instrumentation.mojom.HeapProfilerHelper" ], - "page_signal": [ "resource_coordinator.mojom.PageSignalGenerator" ], - "webui_graph_dump": [ "resource_coordinator.mojom.WebUIGraphDump" ], "tests": [ "*" ] }, "requires": {
diff --git a/services/resource_coordinator/public/cpp/BUILD.gn b/services/resource_coordinator/public/cpp/BUILD.gn index 3fec0f16..8d8620e 100644 --- a/services/resource_coordinator/public/cpp/BUILD.gn +++ b/services/resource_coordinator/public/cpp/BUILD.gn
@@ -32,23 +32,8 @@ ] } -component("resource_coordinator_cpp") { - sources = [ - "frame_resource_coordinator.cc", - "frame_resource_coordinator.h", - "page_resource_coordinator.cc", - "page_resource_coordinator.h", - "process_resource_coordinator.cc", - "process_resource_coordinator.h", - "resource_coordinator_interface.h", - "system_resource_coordinator.cc", - "system_resource_coordinator.h", - ] - - configs += [ "//build/config/compiler:wexit_time_destructors" ] - - defines = [ "IS_SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_IMPL" ] - +# TODO(siggi): Remove this target and redirect users to specific dependencies. +source_set("resource_coordinator_cpp") { public_deps = [ ":resource_coordinator_cpp_base", ":resource_coordinator_cpp_features",
diff --git a/services/resource_coordinator/public/cpp/frame_resource_coordinator.h b/services/resource_coordinator/public/cpp/frame_resource_coordinator.h deleted file mode 100644 index bf2424d..0000000 --- a/services/resource_coordinator/public/cpp/frame_resource_coordinator.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright 2017 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 SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_FRAME_RESOURCE_COORDINATOR_H_ -#define SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_FRAME_RESOURCE_COORDINATOR_H_ - -#include "base/memory/weak_ptr.h" -#include "base/threading/thread_checker.h" -#include "services/resource_coordinator/public/cpp/resource_coordinator_interface.h" -#include "services/resource_coordinator/public/mojom/coordination_unit.mojom.h" - -namespace resource_coordinator { - -class ProcessResourceCoordinator; - -class COMPONENT_EXPORT(SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP) - FrameResourceCoordinator - : public ResourceCoordinatorInterface<mojom::FrameCoordinationUnitPtr, - mojom::FrameCoordinationUnitRequest> { - public: - FrameResourceCoordinator(service_manager::Connector* connector); - ~FrameResourceCoordinator() override; - - void SetProcess(const ProcessResourceCoordinator& process); - void AddChildFrame(const FrameResourceCoordinator& child); - void RemoveChildFrame(const FrameResourceCoordinator& child); - - // Closes the connection to the service. - void reset() { service_.reset(); } - - private: - void ConnectToService(mojom::CoordinationUnitProviderPtr& provider, - const CoordinationUnitID& cu_id) override; - - void SetProcessByID(const CoordinationUnitID& process_id); - void AddChildFrameByID(const CoordinationUnitID& child_id); - void RemoveChildFrameByID(const CoordinationUnitID& child_id); - - THREAD_CHECKER(thread_checker_); - - // The WeakPtrFactory should come last so the weak ptrs are invalidated - // before the rest of the member variables. - base::WeakPtrFactory<FrameResourceCoordinator> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(FrameResourceCoordinator); -}; - -} // namespace resource_coordinator - -#endif // SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_FRAME_RESOURCE_COORDINATOR_H_
diff --git a/services/resource_coordinator/public/cpp/page_resource_coordinator.h b/services/resource_coordinator/public/cpp/page_resource_coordinator.h deleted file mode 100644 index d4bc029..0000000 --- a/services/resource_coordinator/public/cpp/page_resource_coordinator.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2017 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 SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_PAGE_RESOURCE_COORDINATOR_H_ -#define SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_PAGE_RESOURCE_COORDINATOR_H_ - -#include "base/memory/weak_ptr.h" -#include "base/threading/thread_checker.h" -#include "base/time/time.h" -#include "services/resource_coordinator/public/cpp/frame_resource_coordinator.h" -#include "services/resource_coordinator/public/cpp/resource_coordinator_interface.h" -#include "services/resource_coordinator/public/mojom/coordination_unit.mojom.h" - -namespace resource_coordinator { - -class COMPONENT_EXPORT(SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP) - PageResourceCoordinator - : public ResourceCoordinatorInterface<mojom::PageCoordinationUnitPtr, - mojom::PageCoordinationUnitRequest> { - public: - PageResourceCoordinator(service_manager::Connector* connector); - ~PageResourceCoordinator() override; - - void SetIsLoading(bool is_loading); - void SetVisibility(bool visible); - void SetUKMSourceId(int64_t ukm_source_id); - void OnFaviconUpdated(); - void OnTitleUpdated(); - void OnMainFrameNavigationCommitted(base::TimeTicks navigation_committed_time, - uint64_t navigation_id, - const std::string& url); - - void AddFrame(const FrameResourceCoordinator& frame); - void RemoveFrame(const FrameResourceCoordinator& frame); - - private: - void ConnectToService(mojom::CoordinationUnitProviderPtr& provider, - const CoordinationUnitID& cu_id) override; - - void AddFrameByID(const CoordinationUnitID& cu_id); - void RemoveFrameByID(const CoordinationUnitID& cu_id); - - THREAD_CHECKER(thread_checker_); - - // The WeakPtrFactory should come last so the weak ptrs are invalidated - // before the rest of the member variables. - base::WeakPtrFactory<PageResourceCoordinator> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(PageResourceCoordinator); -}; - -} // namespace resource_coordinator - -#endif // SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_PAGE_RESOURCE_COORDINATOR_H_
diff --git a/services/resource_coordinator/public/cpp/process_resource_coordinator.h b/services/resource_coordinator/public/cpp/process_resource_coordinator.h deleted file mode 100644 index 882c5b3..0000000 --- a/services/resource_coordinator/public/cpp/process_resource_coordinator.h +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright 2017 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 SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_PROCESS_RESOURCE_COORDINATOR_H_ -#define SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_PROCESS_RESOURCE_COORDINATOR_H_ - -#include "base/memory/weak_ptr.h" -#include "base/process/process.h" -#include "base/threading/thread_checker.h" -#include "services/resource_coordinator/public/cpp/frame_resource_coordinator.h" -#include "services/resource_coordinator/public/cpp/resource_coordinator_interface.h" -#include "services/resource_coordinator/public/mojom/coordination_unit.mojom.h" - -namespace resource_coordinator { - -class COMPONENT_EXPORT(SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP) - ProcessResourceCoordinator : public ResourceCoordinatorInterface< - mojom::ProcessCoordinationUnitPtr, - mojom::ProcessCoordinationUnitRequest> { - public: - ProcessResourceCoordinator(service_manager::Connector* connector); - ~ProcessResourceCoordinator() override; - - // Must be called immediately after the process is launched. - void OnProcessLaunched(const base::Process& process); - - void SetCPUUsage(double usage); - void SetProcessExitStatus(int32_t exit_status); - - private: - void ConnectToService(mojom::CoordinationUnitProviderPtr& provider, - const CoordinationUnitID& cu_id) override; - - THREAD_CHECKER(thread_checker_); - - // The WeakPtrFactory should come last so the weak ptrs are invalidated - // before the rest of the member variables. - base::WeakPtrFactory<ProcessResourceCoordinator> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(ProcessResourceCoordinator); -}; - -} // namespace resource_coordinator - -#endif // SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_PROCESS_RESOURCE_COORDINATOR_H_
diff --git a/services/resource_coordinator/public/cpp/system_resource_coordinator.cc b/services/resource_coordinator/public/cpp/system_resource_coordinator.cc deleted file mode 100644 index bdd6c602..0000000 --- a/services/resource_coordinator/public/cpp/system_resource_coordinator.cc +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "services/resource_coordinator/public/cpp/system_resource_coordinator.h" - -namespace resource_coordinator { - -SystemResourceCoordinator::SystemResourceCoordinator( - service_manager::Connector* connector) - : ResourceCoordinatorInterface() { - CoordinationUnitID new_cu_id(CoordinationUnitType::kSystem, - CoordinationUnitID::RANDOM_ID); - ResourceCoordinatorInterface::ConnectToService(connector, new_cu_id); -} - -SystemResourceCoordinator::~SystemResourceCoordinator() = default; - -void SystemResourceCoordinator::DistributeMeasurementBatch( - mojom::ProcessResourceMeasurementBatchPtr batch) { - if (!service_) - return; - service_->DistributeMeasurementBatch(std::move(batch)); -} - -void SystemResourceCoordinator::ConnectToService( - mojom::CoordinationUnitProviderPtr& provider, - const CoordinationUnitID& cu_id) { - provider->GetSystemCoordinationUnit(mojo::MakeRequest(&service_)); -} - -} // namespace resource_coordinator
diff --git a/services/resource_coordinator/public/cpp/system_resource_coordinator.h b/services/resource_coordinator/public/cpp/system_resource_coordinator.h deleted file mode 100644 index 2ce3258f..0000000 --- a/services/resource_coordinator/public/cpp/system_resource_coordinator.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_SYSTEM_RESOURCE_COORDINATOR_H_ -#define SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_SYSTEM_RESOURCE_COORDINATOR_H_ - -#include "services/resource_coordinator/public/cpp/resource_coordinator_interface.h" -#include "services/resource_coordinator/public/mojom/coordination_unit.mojom.h" - -namespace resource_coordinator { - -class COMPONENT_EXPORT(SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP) - SystemResourceCoordinator : public ResourceCoordinatorInterface< - mojom::SystemCoordinationUnitPtr, - mojom::SystemCoordinationUnitRequest> { - public: - SystemResourceCoordinator(service_manager::Connector* connector); - ~SystemResourceCoordinator() override; - - void DistributeMeasurementBatch( - mojom::ProcessResourceMeasurementBatchPtr batch); - - private: - void ConnectToService(mojom::CoordinationUnitProviderPtr& provider, - const CoordinationUnitID& cu_id) override; - - DISALLOW_COPY_AND_ASSIGN(SystemResourceCoordinator); -}; - -} // namespace resource_coordinator - -#endif // SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_SYSTEM_RESOURCE_COORDINATOR_H_
diff --git a/services/resource_coordinator/resource_coordinator_service.cc b/services/resource_coordinator/resource_coordinator_service.cc index 3894d1b..ac977a1 100644 --- a/services/resource_coordinator/resource_coordinator_service.cc +++ b/services/resource_coordinator/resource_coordinator_service.cc
@@ -6,57 +6,23 @@ #include <utility> -#include "base/bind.h" #include "base/feature_list.h" +#include "base/timer/timer.h" #include "build/build_config.h" #include "services/metrics/public/cpp/mojo_ukm_recorder.h" #include "services/resource_coordinator/memory_instrumentation/coordinator_impl.h" -#include "services/resource_coordinator/observers/metrics_collector.h" -#include "services/resource_coordinator/observers/page_signal_generator_impl.h" #include "services/resource_coordinator/public/cpp/resource_coordinator_features.h" -#if defined(OS_WIN) -#include "services/resource_coordinator/observers/working_set_trimmer_win.h" -#endif - namespace resource_coordinator { ResourceCoordinatorService::ResourceCoordinatorService( service_manager::mojom::ServiceRequest request) : service_binding_(this, std::move(request)), - service_keepalive_(&service_binding_, base::nullopt /* idle_timeout */), - introspector_(&coordination_unit_graph_) {} + service_keepalive_(&service_binding_, base::nullopt /* idle_timeout */) {} ResourceCoordinatorService::~ResourceCoordinatorService() = default; void ResourceCoordinatorService::OnStart() { - ukm_recorder_ = ukm::MojoUkmRecorder::Create(service_binding_.GetConnector()); - - registry_.AddInterface( - base::Bind(&CoordinationUnitIntrospectorImpl::BindToInterface, - base::Unretained(&introspector_))); - - // Register new |CoordinationUnitGraphObserver| implementations here. - auto page_signal_generator_impl = std::make_unique<PageSignalGeneratorImpl>(); - registry_.AddInterface( - base::Bind(&PageSignalGeneratorImpl::BindToInterface, - base::Unretained(page_signal_generator_impl.get()))); - coordination_unit_graph_.RegisterObserver( - std::move(page_signal_generator_impl)); - - coordination_unit_graph_.RegisterObserver( - std::make_unique<MetricsCollector>()); - -#if defined(OS_WIN) - if (base::FeatureList::IsEnabled(features::kEmptyWorkingSet)) { - coordination_unit_graph_.RegisterObserver( - std::make_unique<WorkingSetTrimmer>()); - } -#endif - - coordination_unit_graph_.OnStart(®istry_, &service_keepalive_); - coordination_unit_graph_.set_ukm_recorder(ukm_recorder_.get()); - // TODO(chiniforooshan): The abstract class Coordinator in the // public/cpp/memory_instrumentation directory should not be needed anymore. // We should be able to delete that and rename @@ -71,8 +37,6 @@ registry_.AddInterface(base::BindRepeating( &memory_instrumentation::CoordinatorImpl::BindHeapProfilerHelperRequest, base::Unretained(memory_instrumentation_coordinator_.get()))); - registry_.AddInterface(base::BindRepeating( - &ResourceCoordinatorService::BindWebUIGraphDump, base::Unretained(this))); } void ResourceCoordinatorService::OnBindInterface( @@ -83,31 +47,4 @@ source_info); } -void ResourceCoordinatorService::BindWebUIGraphDump( - mojom::WebUIGraphDumpRequest request, - const service_manager::BindSourceInfo& source_info) { - std::unique_ptr<WebUIGraphDumpImpl> graph_dump = - std::make_unique<WebUIGraphDumpImpl>(&coordination_unit_graph_); - - auto error_callback = - base::BindOnce(&ResourceCoordinatorService::OnGraphDumpConnectionError, - base::Unretained(this), graph_dump.get()); - graph_dump->Bind(std::move(request), std::move(error_callback)); - - graph_dumps_.push_back(std::move(graph_dump)); -} - -void ResourceCoordinatorService::OnGraphDumpConnectionError( - WebUIGraphDumpImpl* graph_dump) { - const auto it = std::find_if( - graph_dumps_.begin(), graph_dumps_.end(), - [graph_dump](const std::unique_ptr<WebUIGraphDumpImpl>& graph_dump_ptr) { - return graph_dump_ptr.get() == graph_dump; - }); - - DCHECK(it != graph_dumps_.end()); - - graph_dumps_.erase(it); -} - } // namespace resource_coordinator
diff --git a/services/resource_coordinator/resource_coordinator_service.h b/services/resource_coordinator/resource_coordinator_service.h index bb8a9cd..3c63ebf 100644 --- a/services/resource_coordinator/resource_coordinator_service.h +++ b/services/resource_coordinator/resource_coordinator_service.h
@@ -13,10 +13,9 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "services/metrics/public/cpp/mojo_ukm_recorder.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_graph.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_introspector_impl.h" + #include "services/resource_coordinator/memory_instrumentation/coordinator_impl.h" -#include "services/resource_coordinator/webui_graph_dump_impl.h" + #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" @@ -37,31 +36,16 @@ const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe) override; - ukm::MojoUkmRecorder* ukm_recorder() { return ukm_recorder_.get(); } - CoordinationUnitGraph* coordination_unit_graph() { - return &coordination_unit_graph_; - } - private: - void BindWebUIGraphDump(mojom::WebUIGraphDumpRequest request, - const service_manager::BindSourceInfo& source_info); - void OnGraphDumpConnectionError(WebUIGraphDumpImpl* graph_dump); - service_manager::ServiceBinding service_binding_; service_manager::ServiceKeepalive service_keepalive_; service_manager::BinderRegistryWithArgs< const service_manager::BindSourceInfo&> registry_; - CoordinationUnitGraph coordination_unit_graph_; - CoordinationUnitIntrospectorImpl introspector_; - std::unique_ptr<ukm::MojoUkmRecorder> ukm_recorder_; std::unique_ptr<memory_instrumentation::CoordinatorImpl> memory_instrumentation_coordinator_; - // Current graph dump instances. - std::vector<std::unique_ptr<WebUIGraphDumpImpl>> graph_dumps_; - // WeakPtrFactory members should always come last so WeakPtrs are destructed // before other members. base::WeakPtrFactory<ResourceCoordinatorService> weak_factory_{this};
diff --git a/services/resource_coordinator/resource_coordinator_service_unittest.cc b/services/resource_coordinator/resource_coordinator_service_unittest.cc deleted file mode 100644 index a9caa50..0000000 --- a/services/resource_coordinator/resource_coordinator_service_unittest.cc +++ /dev/null
@@ -1,124 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <memory> - -#include "base/bind.h" -#include "base/macros.h" -#include "base/run_loop.h" -#include "base/test/scoped_task_environment.h" -#include "mojo/public/cpp/bindings/binding.h" -#include "services/resource_coordinator/public/cpp/frame_resource_coordinator.h" -#include "services/resource_coordinator/public/cpp/page_resource_coordinator.h" -#include "services/resource_coordinator/public/cpp/process_resource_coordinator.h" -#include "services/resource_coordinator/public/cpp/system_resource_coordinator.h" -#include "services/resource_coordinator/public/mojom/coordination_unit_provider.mojom.h" -#include "services/resource_coordinator/public/mojom/service_constants.mojom.h" -#include "services/resource_coordinator/resource_coordinator_service.h" -#include "services/service_manager/public/cpp/test/test_connector_factory.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace resource_coordinator { - -class ResourceCoordinatorTest : public testing::Test { - public: - ResourceCoordinatorTest() - : service_( - test_connector_factory_.RegisterInstance(mojom::kServiceName)) { - // The resource_coordinator service may attempt to connect to the metrics - // service. Allow these requests to be silently ignored rather than - // bringing up or simulating the metrics service just for unit tests. - test_connector_factory_.set_ignore_unknown_service_requests(true); - } - - ~ResourceCoordinatorTest() override {} - - void GetIDCallback(const CoordinationUnitID& cu_id) { - loop_->Quit(); - } - - // Given a CU, tests that it works by invoking GetID and waiting for the - // response. This test will hang (and eventually fail) if the response does - // not come back from the remote endpoint. - template <typename CoordinationUnitPtrType> - void TestCUImpl(CoordinationUnitPtrType cu) { - base::RunLoop loop; - loop_ = &loop; - cu->GetID(base::BindOnce(&ResourceCoordinatorTest::GetIDCallback, - base::Unretained(this))); - loop.Run(); - loop_ = nullptr; - } - - // Variant that works with mojo interface pointers. - template <typename CoordinationUnitPtrType> - void TestCU(CoordinationUnitPtrType& cu) { - TestCUImpl<CoordinationUnitPtrType&>(cu); - } - - // Variant that works with pointers to FooResourceCoordinator wrappers. - template <typename CoordinationUnitPtrType> - void TestCU(CoordinationUnitPtrType* cu) { - TestCUImpl<CoordinationUnitPtrType*>(cu); - } - - protected: - service_manager::Connector* connector() { - return test_connector_factory_.GetDefaultConnector(); - } - - private: - base::test::ScopedTaskEnvironment task_environment_; - service_manager::TestConnectorFactory test_connector_factory_; - ResourceCoordinatorService service_; - - base::RunLoop* loop_ = nullptr; - - DISALLOW_COPY_AND_ASSIGN(ResourceCoordinatorTest); -}; - -TEST_F(ResourceCoordinatorTest, ResourceCoordinatorInstantiate) { - // Get the CU provider interface. - mojom::CoordinationUnitProviderPtr provider; - connector()->BindInterface(mojom::kServiceName, mojo::MakeRequest(&provider)); - - // Create and test a dummy FrameCU. - CoordinationUnitID frame_id(CoordinationUnitType::kFrame, - CoordinationUnitID::RANDOM_ID); - mojom::FrameCoordinationUnitPtr frame_cu; - provider->CreateFrameCoordinationUnit(mojo::MakeRequest(&frame_cu), frame_id); - TestCU(frame_cu); - - // Create and test a dummy PageCU. - CoordinationUnitID page_id(CoordinationUnitType::kPage, - CoordinationUnitID::RANDOM_ID); - mojom::PageCoordinationUnitPtr page_cu; - provider->CreatePageCoordinationUnit(mojo::MakeRequest(&page_cu), page_id); - TestCU(page_cu); - - // Create and test a dummy SystemCU. - mojom::SystemCoordinationUnitPtr system_cu; - provider->GetSystemCoordinationUnit(mojo::MakeRequest(&system_cu)); - TestCU(system_cu); - - // Create and test a dummy ProcessCU. - CoordinationUnitID process_id(CoordinationUnitType::kProcess, - CoordinationUnitID::RANDOM_ID); - mojom::ProcessCoordinationUnitPtr process_cu; - provider->CreateProcessCoordinationUnit(mojo::MakeRequest(&process_cu), - process_id); - TestCU(process_cu); - - // Also test the convenience headers for creating and communicating with CUs. - FrameResourceCoordinator frame_rc(connector()); - TestCU(&frame_rc); - PageResourceCoordinator page_rc(connector()); - TestCU(&page_rc); - ProcessResourceCoordinator process_rc(connector()); - TestCU(&process_rc); - SystemResourceCoordinator system_rc(connector()); - TestCU(&system_rc); -} - -} // namespace resource_coordinator
diff --git a/services/resource_coordinator/webui_graph_dump_impl.h b/services/resource_coordinator/webui_graph_dump_impl.h deleted file mode 100644 index 9b75d0f..0000000 --- a/services/resource_coordinator/webui_graph_dump_impl.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2017 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 SERVICES_RESOURCE_COORDINATOR_WEBUI_GRAPH_DUMP_IMPL_H_ -#define SERVICES_RESOURCE_COORDINATOR_WEBUI_GRAPH_DUMP_IMPL_H_ - -#include "mojo/public/cpp/bindings/binding.h" -#include "services/resource_coordinator/public/mojom/webui_graph_dump.mojom.h" - -namespace resource_coordinator { - -class CoordinationUnitGraph; - -class WebUIGraphDumpImpl : public mojom::WebUIGraphDump { - public: - explicit WebUIGraphDumpImpl(CoordinationUnitGraph* graph); - ~WebUIGraphDumpImpl() override; - - // WebUIGraphDump implementation. - void GetCurrentGraph(GetCurrentGraphCallback callback) override; - - // Bind this instance to |request| with the |error_handler|. - void Bind(mojom::WebUIGraphDumpRequest request, - base::OnceClosure error_handler); - - private: - CoordinationUnitGraph* graph_; - mojo::Binding<mojom::WebUIGraphDump> binding_; - - DISALLOW_COPY_AND_ASSIGN(WebUIGraphDumpImpl); -}; - -} // namespace resource_coordinator - -#endif // SERVICES_RESOURCE_COORDINATOR_WEBUI_GRAPH_DUMP_IMPL_H_
diff --git a/services/service_manager/BUILD.gn b/services/service_manager/BUILD.gn index 161671d..7e921ce 100644 --- a/services/service_manager/BUILD.gn +++ b/services/service_manager/BUILD.gn
@@ -47,7 +47,6 @@ "//services/catalog/public/mojom:constants", "//services/service_manager/public/cpp", "//services/service_manager/public/mojom", - "//services/service_manager/runner/common", "//services/service_manager/sandbox", ] @@ -57,7 +56,10 @@ "service_process_launcher.h", ] - deps += [ "//mojo/core/embedder" ] + deps += [ + "//mojo/core/embedder", + "//services/service_manager/public/cpp/service_executable:switches", + ] } if (is_linux) {
diff --git a/services/service_manager/connect_params.h b/services/service_manager/connect_params.h index 14d15913..5fe5121 100644 --- a/services/service_manager/connect_params.h +++ b/services/service_manager/connect_params.h
@@ -74,6 +74,11 @@ return std::move(interface_pipe_); } + void set_priority(mojom::BindInterfacePriority priority) { + priority_ = priority; + } + mojom::BindInterfacePriority priority() const { return priority_; } + void set_connection_callback(ConnectionCallback callback) { connection_callback_ = std::move(callback); } @@ -100,6 +105,8 @@ mojom::PIDReceiverRequest pid_receiver_request_; std::string interface_name_; mojo::ScopedMessagePipeHandle interface_pipe_; + mojom::BindInterfacePriority priority_ = + mojom::BindInterfacePriority::kImportant; ConnectionCallback connection_callback_; // These values are supplied to the response callback for WarmService()/
diff --git a/services/service_manager/embedder/BUILD.gn b/services/service_manager/embedder/BUILD.gn index 2c0d006..5ab17d3 100644 --- a/services/service_manager/embedder/BUILD.gn +++ b/services/service_manager/embedder/BUILD.gn
@@ -48,9 +48,8 @@ "//services/service_manager", "//services/service_manager/public/cpp", "//services/service_manager/public/cpp/service_executable:support", + "//services/service_manager/public/cpp/service_executable:switches", "//services/service_manager/public/mojom", - "//services/service_manager/runner:init", - "//services/service_manager/runner/common", ] if (!is_nacl) {
diff --git a/services/service_manager/embedder/main.cc b/services/service_manager/embedder/main.cc index febe7676..46ae054 100644 --- a/services/service_manager/embedder/main.cc +++ b/services/service_manager/embedder/main.cc
@@ -37,9 +37,7 @@ #include "services/service_manager/embedder/switches.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_executable/service_executable_environment.h" -#include "services/service_manager/runner/common/client_util.h" -#include "services/service_manager/runner/common/switches.h" -#include "services/service_manager/runner/init.h" +#include "services/service_manager/public/cpp/service_executable/switches.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_paths.h" #include "ui/base/ui_base_switches.h" @@ -157,7 +155,14 @@ } void NonEmbedderProcessInit() { - service_manager::InitializeLogging(); + logging::LoggingSettings settings; + settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG; + logging::InitLogging(settings); + // To view log output with IDs and timestamps use "adb logcat -v threadtime". + logging::SetLogItems(true, // Process ID + true, // Thread ID + true, // Timestamp + true); // Tick count #if !defined(OFFICIAL_BUILD) // Initialize stack dumping before initializing sandbox to make sure symbol @@ -173,25 +178,6 @@ base::TaskScheduler::CreateAndStartWithDefaultParams("ServiceManagerProcess"); } -void WaitForDebuggerIfNecessary() { - if (!ServiceManagerIsRemote()) - return; - - const auto& command_line = *base::CommandLine::ForCurrentProcess(); - const std::string service_name = - command_line.GetSwitchValueASCII(switches::kServiceName); - if (service_name != - command_line.GetSwitchValueASCII(::switches::kWaitForDebugger)) { - return; - } - - // Include the pid as logging may not have been initialized yet (the pid - // printed out by logging is wrong). - LOG(WARNING) << "waiting for debugger to attach for service " << service_name - << " pid=" << base::Process::Current().Pid(); - base::debug::WaitForDebugger(120, true); -} - int RunServiceManager(MainDelegate* delegate) { NonEmbedderProcessInit(); @@ -230,7 +216,6 @@ int RunService(MainDelegate* delegate) { NonEmbedderProcessInit(); - WaitForDebuggerIfNecessary(); InitializeResources();
diff --git a/services/service_manager/public/cpp/connector.cc b/services/service_manager/public/cpp/connector.cc index 89ce2f0..3b07cfcc 100644 --- a/services/service_manager/public/cpp/connector.cc +++ b/services/service_manager/public/cpp/connector.cc
@@ -62,6 +62,7 @@ void Connector::BindInterface(const ServiceFilter& filter, const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe, + mojom::BindInterfacePriority priority, BindInterfaceCallback callback) { auto service_overrides_iter = local_binder_overrides_.find(filter); if (service_overrides_iter != local_binder_overrides_.end()) { @@ -76,7 +77,7 @@ return; connector_->BindInterface(filter, interface_name, std::move(interface_pipe), - std::move(callback)); + priority, std::move(callback)); } std::unique_ptr<Connector> Connector::Clone() {
diff --git a/services/service_manager/public/cpp/connector.h b/services/service_manager/public/cpp/connector.h index 741a9ec..faba6825 100644 --- a/services/service_manager/public/cpp/connector.h +++ b/services/service_manager/public/cpp/connector.h
@@ -7,6 +7,7 @@ #include <map> #include <memory> +#include <utility> #include "base/callback.h" #include "base/optional.h" @@ -143,6 +144,7 @@ mojo::InterfaceRequest<Interface> request, BindInterfaceCallback callback = {}) { BindInterface(filter, Interface::Name_, request.PassMessagePipe(), + mojom::BindInterfacePriority::kImportant, std::move(callback)); } @@ -166,10 +168,28 @@ std::move(request)); } + template <typename Interface> + void BindInterface(const std::string& service_name, + mojo::InterfaceRequest<Interface> request, + mojom::BindInterfacePriority priority) { + return BindInterface(ServiceFilter::ByName(service_name), Interface::Name_, + request.PassMessagePipe(), priority, nullptr); + } + void BindInterface(const ServiceFilter& filter, const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe, - BindInterfaceCallback callback = {}); + BindInterfaceCallback callback = {}) { + BindInterface(filter, interface_name, std::move(interface_pipe), + mojom::BindInterfacePriority::kImportant, + std::move(callback)); + } + + void BindInterface(const ServiceFilter& filter, + const std::string& interface_name, + mojo::ScopedMessagePipeHandle interface_pipe, + mojom::BindInterfacePriority priority, + BindInterfaceCallback callback); // Creates a new instance of this class which may be passed to another thread. // The returned object may be passed across sequences until any of its public
diff --git a/services/service_manager/public/cpp/service_executable/BUILD.gn b/services/service_manager/public/cpp/service_executable/BUILD.gn index dc723ac..6d4b312 100644 --- a/services/service_manager/public/cpp/service_executable/BUILD.gn +++ b/services/service_manager/public/cpp/service_executable/BUILD.gn
@@ -9,12 +9,11 @@ ] deps = [ + ":switches", "//mojo/core/embedder", "//mojo/public/cpp/platform", "//mojo/public/cpp/system", "//services/service_manager/public/cpp", - "//services/service_manager/runner:init", - "//services/service_manager/runner/common", "//services/service_manager/sandbox", ] @@ -32,6 +31,13 @@ } } +source_set("switches") { + sources = [ + "switches.cc", + "switches.h", + ] +} + # Service executable targets should link against this to get a boilerplate entry # point which accepts canonical command-line arguments to establish a connection # to the Service Manager. In order to link properly, dependents must ensure that @@ -52,7 +58,7 @@ deps = [ ":support", "//base", + "//base:base_static", "//base:i18n", - "//services/service_manager/runner:init", ] }
diff --git a/services/service_manager/public/cpp/service_executable/main.cc b/services/service_manager/public/cpp/service_executable/main.cc index 3e56810..d29d2aa 100644 --- a/services/service_manager/public/cpp/service_executable/main.cc +++ b/services/service_manager/public/cpp/service_executable/main.cc
@@ -5,23 +5,62 @@ #include "base/at_exit.h" #include "base/base_switches.h" #include "base/command_line.h" +#include "base/debug/debugger.h" #include "base/debug/stack_trace.h" #include "base/feature_list.h" +#include "base/files/file_path.h" #include "base/i18n/icu_util.h" #include "base/logging.h" #include "base/macros.h" #include "base/process/launch.h" +#include "base/stl_util.h" +#include "base/strings/string_split.h" +#include "base/strings/stringprintf.h" +#include "base/strings/utf_string_conversions.h" #include "base/task/task_scheduler/task_scheduler.h" #include "build/build_config.h" #include "services/service_manager/public/cpp/service_executable/service_executable_environment.h" #include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/public/mojom/service.mojom.h" -#include "services/service_manager/runner/init.h" #if defined(OS_MACOSX) #include "base/mac/bundle_locations.h" #endif +namespace { + +void WaitForDebuggerIfNecessary() { + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(::switches::kWaitForDebugger)) { + std::vector<std::string> apps_to_debug = base::SplitString( + command_line->GetSwitchValueASCII(::switches::kWaitForDebugger), ",", + base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); + std::string app = "launcher"; + base::FilePath exe_path = + command_line->GetProgram().BaseName().RemoveExtension(); + for (const auto& app_name : apps_to_debug) { + if (base::FilePath().AppendASCII(app_name) == exe_path) { + app = app_name; + break; + } + } + if (apps_to_debug.empty() || base::ContainsValue(apps_to_debug, app)) { +#if defined(OS_WIN) + base::string16 appw = base::UTF8ToUTF16(app); + base::string16 message = base::UTF8ToUTF16( + base::StringPrintf("%s - %ld", app.c_str(), GetCurrentProcessId())); + MessageBox(NULL, message.c_str(), appw.c_str(), MB_OK | MB_SETFOREGROUND); +#else + LOG(ERROR) << app << " waiting for GDB. pid: " << getpid(); + base::debug::WaitForDebugger(60, true); +#endif + } + } +} + +} // namespace + int main(int argc, char** argv) { base::AtExitManager at_exit; base::CommandLine::Init(argc, argv); @@ -30,7 +69,14 @@ base::RouteStdioToConsole(false); #endif - service_manager::InitializeLogging(); + logging::LoggingSettings settings; + settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG; + logging::InitLogging(settings); + // To view log output with IDs and timestamps use "adb logcat -v threadtime". + logging::SetLogItems(true, // Process ID + true, // Thread ID + true, // Timestamp + true); // Tick count base::i18n::InitializeICU(); @@ -45,7 +91,7 @@ command_line->GetSwitchValueASCII(switches::kEnableFeatures), command_line->GetSwitchValueASCII(switches::kDisableFeatures)); - service_manager::WaitForDebuggerIfNecessary(); + WaitForDebuggerIfNecessary(); service_manager::ServiceExecutableEnvironment environment; ServiceMain(environment.TakeServiceRequestFromCommandLine()); base::TaskScheduler::GetInstance()->Shutdown();
diff --git a/services/service_manager/public/cpp/service_executable/service_executable_environment.cc b/services/service_manager/public/cpp/service_executable/service_executable_environment.cc index d120f2a..57d22fa0 100644 --- a/services/service_manager/public/cpp/service_executable/service_executable_environment.cc +++ b/services/service_manager/public/cpp/service_executable/service_executable_environment.cc
@@ -16,8 +16,7 @@ #include "mojo/public/cpp/platform/platform_channel.h" #include "mojo/public/cpp/system/invitation.h" #include "mojo/public/cpp/system/message_pipe.h" -#include "services/service_manager/runner/common/client_util.h" -#include "services/service_manager/runner/common/switches.h" +#include "services/service_manager/public/cpp/service_executable/switches.h" #include "services/service_manager/sandbox/sandbox.h" #include "services/service_manager/sandbox/switches.h" @@ -79,7 +78,9 @@ auto invitation = mojo::IncomingInvitation::Accept( mojo::PlatformChannel::RecoverPassedEndpointFromCommandLine( *base::CommandLine::ForCurrentProcess())); - return GetServiceRequestFromCommandLine(&invitation); + return mojom::ServiceRequest(invitation.ExtractMessagePipe( + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + switches::kServiceRequestAttachmentName))); } } // namespace service_manager
diff --git a/services/service_manager/public/cpp/service_executable/switches.cc b/services/service_manager/public/cpp/service_executable/switches.cc new file mode 100644 index 0000000..9a84d6c9 --- /dev/null +++ b/services/service_manager/public/cpp/service_executable/switches.cc
@@ -0,0 +1,20 @@ +// 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. + +#include "services/service_manager/public/cpp/service_executable/switches.h" + +namespace service_manager { +namespace switches { + +// Indicates the name of the service to run. Useful for debugging, or if a +// service executable is built to support being run as a number of potential +// different services. +const char kServiceName[] = "service-name"; + +// The name of the |service_manager::mojom::ServiceRequest| message pipe handle +// that is attached to the incoming Mojo invitation received by the service. +const char kServiceRequestAttachmentName[] = "service-request-attachment-name"; + +} // namespace switches +} // namespace service_manager
diff --git a/services/service_manager/public/cpp/service_executable/switches.h b/services/service_manager/public/cpp/service_executable/switches.h new file mode 100644 index 0000000..0199bcd52 --- /dev/null +++ b/services/service_manager/public/cpp/service_executable/switches.h
@@ -0,0 +1,19 @@ +// 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. + +#ifndef SERVICES_SERVICE_MANAGER_PUBLIC_CPP_SERVICE_EXECUTABLE_SWITCHES_H_ +#define SERVICES_SERVICE_MANAGER_PUBLIC_CPP_SERVICE_EXECUTABLE_SWITCHES_H_ + +namespace service_manager { +namespace switches { + +// All switches in alphabetical order. The switches should be documented +// alongside the definition of their values in the .cc file. +extern const char kServiceName[]; +extern const char kServiceRequestAttachmentName[]; + +} // namespace switches +} // namespace service_manager + +#endif // SERVICES_SERVICE_MANAGER_PUBLIC_CPP_SERVICE_EXECUTABLE_SWITCHES_H_
diff --git a/services/service_manager/public/cpp/test/test_connector_factory.cc b/services/service_manager/public/cpp/test/test_connector_factory.cc index 72fe2112..6dfa2981 100644 --- a/services/service_manager/public/cpp/test/test_connector_factory.cc +++ b/services/service_manager/public/cpp/test/test_connector_factory.cc
@@ -46,6 +46,7 @@ void BindInterface(const ServiceFilter& service_filter, const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe, + mojom::BindInterfacePriority priority, BindInterfaceCallback callback) override { auto* proxy = GetServiceProxy(service_filter.service_name()); if (!proxy && factory_->ignore_unknown_service_requests()) {
diff --git a/services/service_manager/public/java/src/org/chromium/services/service_manager/Connector.java b/services/service_manager/public/java/src/org/chromium/services/service_manager/Connector.java index e6ed4eb9b..6b4fdcee 100644 --- a/services/service_manager/public/java/src/org/chromium/services/service_manager/Connector.java +++ b/services/service_manager/public/java/src/org/chromium/services/service_manager/Connector.java
@@ -43,7 +43,8 @@ org.chromium.service_manager.mojom.Connector.BindInterfaceResponse callback = new ConnectorBindInterfaceResponseImpl(); - mConnector.bindInterface(filter, interfaceName, request.passHandle(), callback); + mConnector.bindInterface(filter, interfaceName, request.passHandle(), + org.chromium.service_manager.mojom.BindInterfacePriority.IMPORTANT, callback); } @Override
diff --git a/services/service_manager/public/mojom/connector.mojom b/services/service_manager/public/mojom/connector.mojom index 4848cd1..a90f2dd 100644 --- a/services/service_manager/public/mojom/connector.mojom +++ b/services/service_manager/public/mojom/connector.mojom
@@ -25,6 +25,22 @@ ACCESS_DENIED }; +// Used with BindInterface to indicate how the Service Manager should treat an +// individual interface request. +enum BindInterfacePriority { + // The request is important and the Service Manager should try to keep the + // destination service instance alive until it receives the request. This is + // generally the default mode of operation that clients want. + kImportant, + + // Allows the Service Manager to route the request to a service instance which + // may die by the time the request arrives. BindInterface calls which use this + // priority may be inherently flaky, but this behavior can be desirable in + // cases where a service manages its lifetime independent of whether the given + // interface is in use (e.g. for shared client support like tracing). + kBestEffort, +}; + // A collection of metadata that disambiguates instances in the service manager. struct Identity { // A name identifying a service. @@ -105,7 +121,8 @@ // request. BindInterface(ServiceFilter filter, string interface_name, - handle<message_pipe> interface_pipe) + handle<message_pipe> interface_pipe, + BindInterfacePriority priority) => (ConnectResult result, Identity? identity); // Asks the Service Manager for details about the service named
diff --git a/services/service_manager/runner/BUILD.gn b/services/service_manager/runner/BUILD.gn deleted file mode 100644 index 488a8e7..0000000 --- a/services/service_manager/runner/BUILD.gn +++ /dev/null
@@ -1,17 +0,0 @@ -# Copyright 2016 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -source_set("init") { - sources = [ - "init.cc", - "init.h", - ] - - deps = [ - "//base", - "//base:base_static", - "//base:i18n", - "//services/service_manager/runner/common", - ] -}
diff --git a/services/service_manager/runner/common/BUILD.gn b/services/service_manager/runner/common/BUILD.gn deleted file mode 100644 index 0e57a974..0000000 --- a/services/service_manager/runner/common/BUILD.gn +++ /dev/null
@@ -1,22 +0,0 @@ -# Copyright 2016 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -source_set("common") { - sources = [ - "client_util.cc", - "client_util.h", - "switches.cc", - "switches.h", - ] - - deps = [ - "//base", - "//mojo/public/cpp/bindings", - ] - - public_deps = [ - "//mojo/public/cpp/system", - "//services/service_manager/public/mojom", - ] -}
diff --git a/services/service_manager/runner/common/client_util.cc b/services/service_manager/runner/common/client_util.cc deleted file mode 100644 index 375839a9..0000000 --- a/services/service_manager/runner/common/client_util.cc +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "services/service_manager/runner/common/client_util.h" - -#include <string> - -#include "base/command_line.h" -#include "base/rand_util.h" -#include "base/strings/string_number_conversions.h" -#include "mojo/public/cpp/system/invitation.h" -#include "services/service_manager/runner/common/switches.h" - -namespace service_manager { - -mojom::ServicePtr PassServiceRequestOnCommandLine( - mojo::OutgoingInvitation* invitation, - base::CommandLine* command_line) { - mojom::ServicePtr client; - auto pipe_name = base::NumberToString(base::RandUint64()); - client.Bind( - mojom::ServicePtrInfo(invitation->AttachMessagePipe(pipe_name), 0)); - command_line->AppendSwitchASCII(switches::kServicePipeToken, pipe_name); - return client; -} - -mojom::ServiceRequest GetServiceRequestFromCommandLine( - mojo::IncomingInvitation* invitation) { - std::string pipe_name = - base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kServicePipeToken); - return mojom::ServiceRequest(invitation->ExtractMessagePipe(pipe_name)); -} - -bool ServiceManagerIsRemote() { - return base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kServicePipeToken); -} - -} // namespace service_manager
diff --git a/services/service_manager/runner/common/client_util.h b/services/service_manager/runner/common/client_util.h deleted file mode 100644 index 8c25050f..0000000 --- a/services/service_manager/runner/common/client_util.h +++ /dev/null
@@ -1,42 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef SERVICES_SERVICE_MANAGER_RUNNER_COMMON_CLIENT_UTIL_H_ -#define SERVICES_SERVICE_MANAGER_RUNNER_COMMON_CLIENT_UTIL_H_ - -#include "services/service_manager/public/mojom/service.mojom.h" - -namespace base { -class CommandLine; -} - -namespace mojo { -class IncomingInvitation; -class OutgoingInvitation; -} - -namespace service_manager { - -// Creates a new Service pipe for connection to a not-yet-launched child process -// and returns one end of it. The other end is passed via a token in -// |command_line|. The launched process may extract the corresponding -// ServiceRequest by calling GetServiceRequestFromCommandLine(). -mojom::ServicePtr PassServiceRequestOnCommandLine( - mojo::OutgoingInvitation* invitation, - base::CommandLine* command_line); - -// Extracts a ServiceRequest from the command line of the current process. -// The parent of this process should have passed a request using -// PassServiceRequestOnCommandLine(). -mojom::ServiceRequest GetServiceRequestFromCommandLine( - mojo::IncomingInvitation* invitation); - -// Returns true if the ServiceRequest came via the command line from a service -// manager -// instance in another process. -bool ServiceManagerIsRemote(); - -} // namespace service_manager - -#endif // SERVICES_SERVICE_MANAGER_RUNNER_COMMON_CLIENT_UTIL_H_
diff --git a/services/service_manager/runner/common/switches.cc b/services/service_manager/runner/common/switches.cc deleted file mode 100644 index 169688b..0000000 --- a/services/service_manager/runner/common/switches.cc +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "services/service_manager/runner/common/switches.h" - -namespace service_manager { -namespace switches { - -// Specified on the command line of service processes to indicate which service -// should be run. Useful when the service process binary may act as one of many -// different embedded services. -const char kServiceName[] = "service-name"; - -// Provides a child process with a token string they can exchange for a message -// pipe whose other end is bound to a service_manager::Service binding in the -// Service Manager. -const char kServicePipeToken[] = "service-pipe-token"; - -} // namespace switches -} // namespace service_manager
diff --git a/services/service_manager/runner/common/switches.h b/services/service_manager/runner/common/switches.h deleted file mode 100644 index ed839d9e..0000000 --- a/services/service_manager/runner/common/switches.h +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef SERVICES_SERVICE_MANAGER_RUNNER_COMMON_SWITCHES_H_ -#define SERVICES_SERVICE_MANAGER_RUNNER_COMMON_SWITCHES_H_ - -namespace service_manager { -namespace switches { - -// All switches in alphabetical order. The switches should be documented -// alongside the definition of their values in the .cc file. -extern const char kServiceName[]; -extern const char kServicePipeToken[]; - -} // namespace switches -} // namespace service_manager - -#endif // SERVICES_SERVICE_MANAGER_RUNNER_COMMON_SWITCHES_H_
diff --git a/services/service_manager/runner/init.cc b/services/service_manager/runner/init.cc deleted file mode 100644 index f598822..0000000 --- a/services/service_manager/runner/init.cc +++ /dev/null
@@ -1,91 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "services/service_manager/runner/init.h" - -#include <stdint.h> - -#include "base/base_switches.h" -#include "base/command_line.h" -#include "base/debug/debugger.h" -#include "base/files/file_path.h" -#include "base/i18n/icu_util.h" -#include "base/logging.h" -#include "base/stl_util.h" -#include "base/strings/string_split.h" -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "services/service_manager/runner/common/switches.h" - -#if defined(OS_WIN) -#include <windows.h> -#elif (OS_POSIX) -#include <unistd.h> -#endif - -namespace service_manager { - -void InitializeLogging() { - logging::LoggingSettings settings; - settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG; - logging::InitLogging(settings); - // To view log output with IDs and timestamps use "adb logcat -v threadtime". - logging::SetLogItems(true, // Process ID - true, // Thread ID - true, // Timestamp - true); // Tick count -} - -void WaitForDebuggerIfNecessary() { - const base::CommandLine* command_line = - base::CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(::switches::kWaitForDebugger)) { - std::vector<std::string> apps_to_debug = base::SplitString( - command_line->GetSwitchValueASCII(::switches::kWaitForDebugger), ",", - base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); - std::string app = "launcher"; - base::FilePath exe_path = - command_line->GetProgram().BaseName().RemoveExtension(); - for (const auto& app_name : apps_to_debug) { - if (base::FilePath().AppendASCII(app_name) == exe_path) { - app = app_name; - break; - } - } - if (apps_to_debug.empty() || base::ContainsValue(apps_to_debug, app)) { -#if defined(OS_WIN) - base::string16 appw = base::UTF8ToUTF16(app); - base::string16 message = base::UTF8ToUTF16( - base::StringPrintf("%s - %ld", app.c_str(), GetCurrentProcessId())); - MessageBox(NULL, message.c_str(), appw.c_str(), MB_OK | MB_SETFOREGROUND); -#else - LOG(ERROR) << app << " waiting for GDB. pid: " << getpid(); - base::debug::WaitForDebugger(60, true); -#endif - } - } -} - -NO_SANITIZE("cfi-icall") -void CallLibraryEarlyInitialization(base::NativeLibrary app_library) { - // Do whatever warming that the service wants. - -#if ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_FILE - typedef void (*LibraryEarlyInitFunction)(const uint8_t*); - LibraryEarlyInitFunction init_function = - reinterpret_cast<LibraryEarlyInitFunction>( - base::GetFunctionPointerFromNativeLibrary(app_library, - "InitializeBase")); - CHECK(init_function); - // Get the ICU data that we prewarmed in the runner and then pass it to - // the copy of icu in the mojo binary that we're running. - const uint8_t* icu_data = base::i18n::GetRawIcuMemory(); - init_function(icu_data); -#endif // ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_FILE - - // TODO(erg): All chromium binaries load base. We might want to make a - // general system for other people. -} - -} // namespace service_manager
diff --git a/services/service_manager/runner/init.h b/services/service_manager/runner/init.h deleted file mode 100644 index a437c8f..0000000 --- a/services/service_manager/runner/init.h +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef SERVICES_SERVICE_MANAGER_RUNNER_INIT_H_ -#define SERVICES_SERVICE_MANAGER_RUNNER_INIT_H_ - -#include "base/native_library.h" - -namespace service_manager { - -// Initialization routines shared by desktop and Android main functions. -void InitializeLogging(); - -void WaitForDebuggerIfNecessary(); - -// Calls "LibraryEarlyInitialization" in |app_library| if it exists. We do -// common initialization there now. -void CallLibraryEarlyInitialization(base::NativeLibrary app_library); - -} // namespace service_manager - -#endif // SERVICES_SERVICE_MANAGER_RUNNER_INIT_H_
diff --git a/services/service_manager/service_manager.cc b/services/service_manager/service_manager.cc index d4f2d8f..7e9c217 100644 --- a/services/service_manager/service_manager.cc +++ b/services/service_manager/service_manager.cc
@@ -258,12 +258,18 @@ params->set_response_data(mojom::ConnectResult::SUCCEEDED, identity_); - pending_service_connections_++; + base::OnceClosure on_bind_interface_complete; + if (params->priority() == mojom::BindInterfacePriority::kImportant) { + pending_service_connections_++; + on_bind_interface_complete = + base::BindOnce(&Instance::OnConnectComplete, base::Unretained(this)); + } + service_->OnBindInterface( BindSourceInfo(params->source(), GetRequestedCapabilities(source_spec, identity_)), params->interface_name(), params->TakeInterfaceRequestPipe(), - base::BindOnce(&Instance::OnConnectComplete, base::Unretained(this))); + std::move(on_bind_interface_complete)); return true; } @@ -445,6 +451,7 @@ void BindInterface(const service_manager::ServiceFilter& target_filter, const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe, + mojom::BindInterfacePriority priority, BindInterfaceCallback callback) override { mojom::ConnectResult result = ValidateConnectParams(target_filter, interface_name); @@ -458,6 +465,7 @@ params->set_target(target_filter); params->set_interface_request_info(interface_name, std::move(interface_pipe)); + params->set_priority(priority); params->set_connection_callback(std::move(callback)); service_manager_->Connect(std::move(params)); }
diff --git a/services/service_manager/service_process_launcher.cc b/services/service_manager/service_process_launcher.cc index 46a4932f..916a11f 100644 --- a/services/service_manager/service_process_launcher.cc +++ b/services/service_manager/service_process_launcher.cc
@@ -15,8 +15,10 @@ #include "base/path_service.h" #include "base/process/kill.h" #include "base/process/launch.h" +#include "base/rand_util.h" #include "base/run_loop.h" #include "base/sequence_checker.h" +#include "base/strings/string_number_conversions.h" #include "base/synchronization/lock.h" #include "base/task/post_task.h" #include "base/task_runner_util.h" @@ -26,9 +28,10 @@ #include "mojo/public/cpp/platform/platform_channel.h" #include "mojo/public/cpp/system/core.h" #include "mojo/public/cpp/system/invitation.h" -#include "services/service_manager/runner/common/client_util.h" -#include "services/service_manager/runner/common/switches.h" +#include "services/service_manager/public/cpp/service_executable/switches.h" +#include "services/service_manager/public/mojom/service.mojom.h" #include "services/service_manager/sandbox/switches.h" +#include "services/service_manager/switches.h" #if defined(OS_LINUX) #include "sandbox/linux/services/namespace_sandbox.h" @@ -140,6 +143,17 @@ return client; } +// static +mojom::ServicePtr ServiceProcessLauncher::PassServiceRequestOnCommandLine( + mojo::OutgoingInvitation* invitation, + base::CommandLine* command_line) { + const auto attachment_name = base::NumberToString(base::RandUint64()); + command_line->AppendSwitchASCII(switches::kServiceRequestAttachmentName, + attachment_name); + return mojom::ServicePtr{ + mojom::ServicePtrInfo{invitation->AttachMessagePipe(attachment_name), 0}}; +} + base::ProcessId ServiceProcessLauncher::ProcessState::LaunchInBackground( const Identity& target, SandboxType sandbox_type,
diff --git a/services/service_manager/service_process_launcher.h b/services/service_manager/service_process_launcher.h index e69cfa2d..50b968dac 100644 --- a/services/service_manager/service_process_launcher.h +++ b/services/service_manager/service_process_launcher.h
@@ -19,6 +19,10 @@ #include "services/service_manager/sandbox/sandbox_type.h" #include "services/service_manager/service_process_launcher_delegate.h" +namespace mojo { +class OutgoingInvitation; +} + namespace service_manager { class Identity; @@ -47,6 +51,16 @@ SandboxType sandbox_type, ProcessReadyCallback callback); + // Exposed publicly for use in tests. Creates a new Service pipe, passing the + // ServiceRequest end through |*invitation| with an identifier stashed in + // |*command_line| that a launched service executable can use to recover it + // from the invitation. + // + // Returns the corresponding ServicePtr endpoint. + static mojom::ServicePtr PassServiceRequestOnCommandLine( + mojo::OutgoingInvitation* invitation, + base::CommandLine* command_line); + private: class ProcessState;
diff --git a/services/service_manager/switches.h b/services/service_manager/switches.h index 68b5f1b8..07f183b 100644 --- a/services/service_manager/switches.h +++ b/services/service_manager/switches.h
@@ -11,6 +11,7 @@ // All switches in alphabetical order. The switches should be documented // alongside the definition of their values in the .cc file. extern const char kEnableTracing[]; +extern const char kServiceRequestAttachmentName[]; } // namespace switches } // namespace service_manager
diff --git a/services/service_manager/tests/BUILD.gn b/services/service_manager/tests/BUILD.gn index e9906e5..cfbfe3bd 100644 --- a/services/service_manager/tests/BUILD.gn +++ b/services/service_manager/tests/BUILD.gn
@@ -70,8 +70,8 @@ "//mojo/public/cpp/platform", "//mojo/public/cpp/system", "//services/service_manager/public/cpp", + "//services/service_manager/public/cpp/service_executable:switches", "//services/service_manager/public/mojom", - "//services/service_manager/runner/common", ] }
diff --git a/services/service_manager/tests/lifecycle/BUILD.gn b/services/service_manager/tests/lifecycle/BUILD.gn index 0aac78ee..04cffb0 100644 --- a/services/service_manager/tests/lifecycle/BUILD.gn +++ b/services/service_manager/tests/lifecycle/BUILD.gn
@@ -18,7 +18,6 @@ "//services/service_manager/public/cpp", "//services/service_manager/public/cpp/test:test_support", "//services/service_manager/public/mojom", - "//services/service_manager/runner/common", "//testing/gtest", ]
diff --git a/services/service_manager/tests/service_manager/BUILD.gn b/services/service_manager/tests/service_manager/BUILD.gn index 29de43a..43dedc31 100644 --- a/services/service_manager/tests/service_manager/BUILD.gn +++ b/services/service_manager/tests/service_manager/BUILD.gn
@@ -25,7 +25,6 @@ "//services/service_manager/public/cpp", "//services/service_manager/public/cpp/test:test_support", "//services/service_manager/public/mojom", - "//services/service_manager/runner/common", "//testing/gtest", ] @@ -90,7 +89,5 @@ "//build/win:default_exe_manifest", "//services/service_manager/public/cpp", "//services/service_manager/public/mojom", - "//services/service_manager/runner:init", - "//services/service_manager/runner/common", ] }
diff --git a/services/service_manager/tests/service_manager/service_manager_unittest.cc b/services/service_manager/tests/service_manager/service_manager_unittest.cc index 78f09fc..5a0c78c 100644 --- a/services/service_manager/tests/service_manager/service_manager_unittest.cc +++ b/services/service_manager/tests/service_manager/service_manager_unittest.cc
@@ -33,7 +33,7 @@ #include "services/service_manager/public/cpp/service_binding.h" #include "services/service_manager/public/cpp/test/test_service_manager.h" #include "services/service_manager/public/mojom/service_manager.mojom.h" -#include "services/service_manager/runner/common/client_util.h" +#include "services/service_manager/service_process_launcher.h" #include "services/service_manager/tests/service_manager/service_manager.test-mojom.h" #include "services/service_manager/tests/service_manager/test_manifests.h" #include "testing/gtest/include/gtest/gtest.h" @@ -265,8 +265,8 @@ mojo::OutgoingInvitation invitation; service_manager::mojom::ServicePtr client = - service_manager::PassServiceRequestOnCommandLine(&invitation, - &child_command_line); + ServiceProcessLauncher::PassServiceRequestOnCommandLine( + &invitation, &child_command_line); service_manager::mojom::PIDReceiverPtr receiver; connector()->RegisterServiceInstance( service_manager::Identity(kTestTargetName, kSystemInstanceGroup,
diff --git a/services/service_manager/tests/util.cc b/services/service_manager/tests/util.cc index 03380bd7..072efd5 100644 --- a/services/service_manager/tests/util.cc +++ b/services/service_manager/tests/util.cc
@@ -20,10 +20,10 @@ #include "mojo/public/cpp/platform/platform_channel.h" #include "mojo/public/cpp/system/invitation.h" #include "services/service_manager/public/cpp/connector.h" +#include "services/service_manager/public/cpp/service_executable/switches.h" #include "services/service_manager/public/mojom/connector.mojom.h" #include "services/service_manager/public/mojom/service.mojom.h" #include "services/service_manager/public/mojom/service_factory.mojom.h" -#include "services/service_manager/runner/common/switches.h" namespace service_manager { namespace test { @@ -66,7 +66,8 @@ mojo::OutgoingInvitation invitation; auto pipe_name = base::NumberToString(base::RandUint64()); mojo::ScopedMessagePipeHandle pipe = invitation.AttachMessagePipe(pipe_name); - child_command_line.AppendSwitchASCII(switches::kServicePipeToken, pipe_name); + child_command_line.AppendSwitchASCII(switches::kServiceRequestAttachmentName, + pipe_name); service_manager::mojom::ServicePtr client; client.Bind(mojo::InterfacePtrInfo<service_manager::mojom::Service>(
diff --git a/services/tracing/perfetto/json_trace_exporter.cc b/services/tracing/perfetto/json_trace_exporter.cc index 2eb46db0a..3bc386d 100644 --- a/services/tracing/perfetto/json_trace_exporter.cc +++ b/services/tracing/perfetto/json_trace_exporter.cc
@@ -14,10 +14,6 @@ #include "base/logging.h" #include "base/strings/stringprintf.h" #include "base/trace_event/trace_event.h" -#include "build/build_config.h" -#include "services/tracing/public/mojom/perfetto_service.mojom.h" -#include "third_party/perfetto/include/perfetto/tracing/core/trace_config.h" -#include "third_party/perfetto/include/perfetto/tracing/core/trace_packet.h" #include "third_party/perfetto/protos/perfetto/trace/chrome/chrome_trace_event.pbzero.h" #include "third_party/perfetto/protos/perfetto/trace/chrome/chrome_trace_packet.pb.h" @@ -261,6 +257,49 @@ *out += "}}"; } +std::unique_ptr<base::DictionaryValue> ConvertTraceStatsToDict( + const perfetto::protos::TraceStats& trace_stats) { + auto dict = std::make_unique<base::DictionaryValue>(); + dict->SetInteger("producers_connected", trace_stats.producers_connected()); + dict->SetInteger("producers_seen", trace_stats.producers_seen()); + dict->SetInteger("data_sources_registered", + trace_stats.data_sources_registered()); + dict->SetInteger("data_sources_seen", trace_stats.data_sources_seen()); + dict->SetInteger("tracing_sessions", trace_stats.tracing_sessions()); + dict->SetInteger("total_buffers", trace_stats.total_buffers()); + auto buf_list = std::make_unique<base::ListValue>(); + for (const auto& buf_stats : trace_stats.buffer_stats()) { + base::Value buf_value(base::Value::Type::DICTIONARY); + base::DictionaryValue* buf_dict; + buf_value.GetAsDictionary(&buf_dict); + buf_dict->SetInteger("buffer_size", buf_stats.buffer_size()); + buf_dict->SetInteger("bytes_written", buf_stats.bytes_written()); + buf_dict->SetInteger("bytes_overwritten", buf_stats.bytes_overwritten()); + buf_dict->SetInteger("bytes_read", buf_stats.bytes_read()); + buf_dict->SetInteger("padding_bytes_written", + buf_stats.padding_bytes_written()); + buf_dict->SetInteger("padding_bytes_cleared", + buf_stats.padding_bytes_cleared()); + buf_dict->SetInteger("chunks_written", buf_stats.chunks_written()); + buf_dict->SetInteger("chunks_rewritten", buf_stats.chunks_rewritten()); + buf_dict->SetInteger("chunks_overwritten", buf_stats.chunks_overwritten()); + buf_dict->SetInteger("chunks_discarded", buf_stats.chunks_discarded()); + buf_dict->SetInteger("chunks_read", buf_stats.chunks_read()); + buf_dict->SetInteger("chunks_committed_out_of_order", + buf_stats.chunks_committed_out_of_order()); + buf_dict->SetInteger("write_wrap_count", buf_stats.write_wrap_count()); + buf_dict->SetInteger("patches_succeeded", buf_stats.patches_succeeded()); + buf_dict->SetInteger("patches_failed", buf_stats.patches_failed()); + buf_dict->SetInteger("readaheads_succeeded", + buf_stats.readaheads_succeeded()); + buf_dict->SetInteger("readaheads_failed", buf_stats.readaheads_failed()); + buf_dict->SetInteger("abi_violations", buf_stats.abi_violations()); + buf_list->GetList().push_back(std::move(buf_value)); + } + dict->SetList("buffer_stats", std::move(buf_list)); + return dict; +} + } // namespace void AppendProtoDictAsJSON(std::string* out, @@ -282,77 +321,14 @@ out->append("}"); } -JSONTraceExporter::JSONTraceExporter(const std::string& config, - perfetto::TracingService* service) - : config_(config), metadata_(std::make_unique<base::DictionaryValue>()) { - consumer_endpoint_ = service->ConnectConsumer(this, /*uid=*/0); - - // Start tracing. - perfetto::TraceConfig trace_config; - trace_config.add_buffers()->set_size_kb(4096 * 100); - - // Perfetto uses clock_gettime for its internal snapshotting, which gets - // blocked by the sandboxed and isn't needed for Chrome regardless. - trace_config.set_disable_clock_snapshotting(true); - - auto* trace_event_config = trace_config.add_data_sources()->mutable_config(); - trace_event_config->set_name(mojom::kTraceEventDataSourceName); - trace_event_config->set_target_buffer(0); - auto* chrome_config = trace_event_config->mutable_chrome_config(); - chrome_config->set_trace_config(config_); - -// Only CrOS and Cast support system tracing. -#if defined(OS_CHROMEOS) || (defined(IS_CHROMECAST) && defined(OS_LINUX)) - auto* system_trace_config = trace_config.add_data_sources()->mutable_config(); - system_trace_config->set_name(mojom::kSystemTraceDataSourceName); - system_trace_config->set_target_buffer(0); - auto* system_chrome_config = system_trace_config->mutable_chrome_config(); - system_chrome_config->set_trace_config(config_); -#endif - -#if defined(OS_CHROMEOS) - auto* arc_trace_config = trace_config.add_data_sources()->mutable_config(); - arc_trace_config->set_name(mojom::kArcTraceDataSourceName); - arc_trace_config->set_target_buffer(0); - auto* arc_chrome_config = arc_trace_config->mutable_chrome_config(); - arc_chrome_config->set_trace_config(config_); -#endif - - auto* trace_metadata_config = - trace_config.add_data_sources()->mutable_config(); - trace_metadata_config->set_name(mojom::kMetaDataSourceName); - trace_metadata_config->set_target_buffer(0); - - consumer_endpoint_->EnableTracing(trace_config); +JSONTraceExporter::JSONTraceExporter(OnTraceEventJSONCallback callback) + : json_callback_(callback), + metadata_(std::make_unique<base::DictionaryValue>()) { + DCHECK(json_callback_); } JSONTraceExporter::~JSONTraceExporter() = default; -void JSONTraceExporter::OnConnect() {} - -void JSONTraceExporter::OnDisconnect() {} - -void JSONTraceExporter::OnTracingDisabled() { - consumer_endpoint_->ReadBuffers(); -} - -// This is called by the Coordinator interface, mainly used by the -// TracingController which in turn is used by the tracing UI etc -// to start/stop tracing. -void JSONTraceExporter::StopAndFlush(OnTraceEventJSONCallback callback) { - DCHECK(!json_callback_ && callback); - json_callback_ = callback; - - consumer_endpoint_->DisableTracing(); -} - -void JSONTraceExporter::GetTraceStats(OnTraceStatsCallback callback) { - DCHECK(!stats_callback_ && callback); - stats_callback_ = std::move(callback); - - consumer_endpoint_->GetTraceStats(); -} - void JSONTraceExporter::OnTraceData(std::vector<perfetto::TracePacket> packets, bool has_more) { DCHECK(json_callback_); @@ -375,6 +351,12 @@ bool decoded = encoded_packet.Decode(&packet); DCHECK(decoded); + if (packet.has_trace_stats()) { + metadata_->SetDictionary("perfetto_trace_stats", + ConvertTraceStatsToDict(packet.trace_stats())); + continue; + } + if (!packet.has_chrome_events()) { continue; } @@ -479,19 +461,4 @@ json_callback_.Run(out, metadata_.get(), has_more); } -// Consumer Detach / Attach is not used in Chrome. -void JSONTraceExporter::OnDetach(bool) { - NOTREACHED(); -} - -void JSONTraceExporter::OnAttach(bool, const perfetto::TraceConfig&) { - NOTREACHED(); -} - -void JSONTraceExporter::OnTraceStats(bool success, - const perfetto::TraceStats& stats) { - DCHECK(stats_callback_); - std::move(stats_callback_).Run(success, stats); -} - } // namespace tracing
diff --git a/services/tracing/perfetto/json_trace_exporter.h b/services/tracing/perfetto/json_trace_exporter.h index fb0ca83..4d74f74 100644 --- a/services/tracing/perfetto/json_trace_exporter.h +++ b/services/tracing/perfetto/json_trace_exporter.h
@@ -12,8 +12,7 @@ #include "base/callback.h" #include "base/macros.h" #include "base/values.h" -#include "third_party/perfetto/include/perfetto/tracing/core/consumer.h" -#include "third_party/perfetto/include/perfetto/tracing/core/tracing_service.h" +#include "third_party/perfetto/include/perfetto/tracing/core/trace_packet.h" namespace perfetto { namespace protos { @@ -28,54 +27,30 @@ void AppendProtoDictAsJSON(std::string* out, const perfetto::protos::ChromeTracedValue& dict); -// This is a Perfetto consumer which will enable Perfetto tracing -// and subscribe to ChromeTraceEvent data sources. Any received -// protos will be converted to the legacy JSON Chrome Tracing -// format. -class JSONTraceExporter : public perfetto::Consumer { +// Converts proto-encoded trace data into the legacy JSON trace format. +// Conversion happens on-the-fly as new trace packets are received. +class JSONTraceExporter { public: - // The owner of JSONTraceExporter should make sure to destroy - // |service| before destroying this. - JSONTraceExporter(const std::string& config, - perfetto::TracingService* service); - - ~JSONTraceExporter() override; - using OnTraceEventJSONCallback = base::RepeatingCallback<void(const std::string& json, base::DictionaryValue* metadata, bool has_more)>; - void StopAndFlush(OnTraceEventJSONCallback callback); - using OnTraceStatsCallback = - base::OnceCallback<void(bool success, const perfetto::TraceStats& stats)>; - void GetTraceStats(OnTraceStatsCallback callback); + JSONTraceExporter(OnTraceEventJSONCallback callback); + virtual ~JSONTraceExporter(); - // perfetto::Consumer implementation. - // This gets called by the Perfetto service as control signals, - // and to send finished protobufs over. - void OnConnect() override; - void OnDisconnect() override; - void OnTracingDisabled() override; - void OnTraceData(std::vector<perfetto::TracePacket> packets, - bool has_more) override; - void OnDetach(bool success) override; - void OnAttach(bool success, const perfetto::TraceConfig&) override; - void OnTraceStats(bool success, const perfetto::TraceStats&) override; + // Called to notify the exporter of new trace packets. Will call the + // |json_callback| passed in the constructor with the converted trace data. + void OnTraceData(std::vector<perfetto::TracePacket> packets, bool has_more); private: OnTraceEventJSONCallback json_callback_; - OnTraceStatsCallback stats_callback_; bool has_output_json_preamble_ = false; bool has_output_first_event_ = false; - std::string config_; std::unique_ptr<base::DictionaryValue> metadata_; std::string legacy_system_ftrace_output_; std::string legacy_system_trace_events_; - // Keep last to avoid edge-cases where its callbacks come in mid-destruction. - std::unique_ptr<perfetto::TracingService::ConsumerEndpoint> - consumer_endpoint_; DISALLOW_COPY_AND_ASSIGN(JSONTraceExporter); };
diff --git a/services/tracing/perfetto/json_trace_exporter_unittest.cc b/services/tracing/perfetto/json_trace_exporter_unittest.cc index 169551f..a0093f9 100644 --- a/services/tracing/perfetto/json_trace_exporter_unittest.cc +++ b/services/tracing/perfetto/json_trace_exporter_unittest.cc
@@ -26,137 +26,15 @@ namespace tracing { -class MockService : public perfetto::TracingService { - public: - explicit MockService(base::MessageLoop* message_loop); - - void OnTracingEnabled(const std::string& config); - void WaitForTracingEnabled(); - - void OnTracingDisabled(); - void WaitForTracingDisabled(); - - const std::string& tracing_enabled_with_config() const { - return tracing_enabled_with_config_; - } - - // perfetto::TracingService implementation. - std::unique_ptr<ProducerEndpoint> ConnectProducer( - perfetto::Producer*, - uid_t uid, - const std::string& name, - size_t shared_buffer_size_hint_bytes = 0) override; - - std::unique_ptr<ConsumerEndpoint> ConnectConsumer(perfetto::Consumer*, - uid_t) override; - - void SetSMBScrapingEnabled(bool enabled) override; - - private: - base::MessageLoop* message_loop_; - - base::RunLoop wait_for_tracing_enabled_; - base::RunLoop wait_for_tracing_disabled_; - std::string tracing_enabled_with_config_; -}; - -class MockConsumerEndpoint : public perfetto::TracingService::ConsumerEndpoint { - public: - explicit MockConsumerEndpoint(MockService* mock_service) - : mock_service_(mock_service) { - CHECK(mock_service); - } - - void EnableTracing( - const perfetto::TraceConfig& config, - perfetto::base::ScopedFile = perfetto::base::ScopedFile()) override { - EXPECT_EQ(mojom::kTraceEventDataSourceName, - config.data_sources()[0].config().name()); - mock_service_->OnTracingEnabled( - config.data_sources()[0].config().chrome_config().trace_config()); - } - void DisableTracing() override { mock_service_->OnTracingDisabled(); } - void ReadBuffers() override {} - void FreeBuffers() override {} - void Flush(uint32_t timeout_ms, FlushCallback callback) override { - callback(true); - } - - // Unused in chrome, only meaningful when using TraceConfig.deferred_start. - void StartTracing() override {} - - // Unused in chrome. - void Detach(const std::string& /*key*/) override {} - void Attach(const std::string& /*key*/) override {} - void GetTraceStats() override {} - - private: - MockService* mock_service_; -}; - -MockService::MockService(base::MessageLoop* message_loop) - : message_loop_(message_loop) { - DCHECK(message_loop); -} - -void MockService::OnTracingEnabled(const std::string& config) { - tracing_enabled_with_config_ = config; - wait_for_tracing_enabled_.Quit(); -} - -void MockService::WaitForTracingEnabled() { - wait_for_tracing_enabled_.Run(); -} - -void MockService::OnTracingDisabled() { - wait_for_tracing_disabled_.Quit(); -} - -void MockService::WaitForTracingDisabled() { - wait_for_tracing_disabled_.Run(); -} - -void MockService::SetSMBScrapingEnabled(bool enabled) {} - -// perfetto::TracingService implementation. -std::unique_ptr<perfetto::TracingService::ProducerEndpoint> -MockService::ConnectProducer(perfetto::Producer*, - uid_t uid, - const std::string& name, - size_t shared_buffer_size_hint_bytes) { - NOTREACHED(); - return nullptr; -} - -std::unique_ptr<perfetto::TracingService::ConsumerEndpoint> -MockService::ConnectConsumer(perfetto::Consumer* consumer, uid_t) { - message_loop_->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&perfetto::Consumer::OnConnect, - base::Unretained(consumer))); - - return std::make_unique<MockConsumerEndpoint>(this); -} - class JSONTraceExporterTest : public testing::Test { public: void SetUp() override { - message_loop_ = std::make_unique<base::MessageLoop>(); - service_ = std::make_unique<MockService>(message_loop_.get()); + json_trace_exporter_.reset(new JSONTraceExporter(base::BindRepeating( + &JSONTraceExporterTest::OnTraceEventJSON, base::Unretained(this)))); } void TearDown() override { - service_.reset(); json_trace_exporter_.reset(); - message_loop_.reset(); - } - - void CreateJSONTraceExporter(const std::string& config) { - json_trace_exporter_.reset(new JSONTraceExporter(config, service_.get())); - } - - void StopAndFlush() { - json_trace_exporter_->StopAndFlush(base::BindRepeating( - &JSONTraceExporterTest::OnTraceEventJSON, base::Unretained(this))); } void OnTraceEventJSON(const std::string& json, @@ -242,31 +120,18 @@ return trace_analyzer_.get(); } - MockService* service() { return service_.get(); } const base::DictionaryValue* parsed_trace_data() const { return parsed_trace_data_.get(); } private: - std::unique_ptr<MockService> service_; std::unique_ptr<JSONTraceExporter> json_trace_exporter_; std::unique_ptr<base::MessageLoop> message_loop_; std::unique_ptr<trace_analyzer::TraceAnalyzer> trace_analyzer_; std::unique_ptr<base::DictionaryValue> parsed_trace_data_; }; -TEST_F(JSONTraceExporterTest, EnableTracingWithGivenConfig) { - const char kDummyTraceConfig[] = "trace_all_the_things"; - CreateJSONTraceExporter(kDummyTraceConfig); - service()->WaitForTracingEnabled(); - EXPECT_EQ(kDummyTraceConfig, service()->tracing_enabled_with_config()); -} - TEST_F(JSONTraceExporterTest, TestMetadata) { - CreateJSONTraceExporter("foo"); - service()->WaitForTracingEnabled(); - StopAndFlush(); - perfetto::protos::TracePacket trace_packet_proto; { @@ -299,7 +164,6 @@ FinalizePacket(trace_packet_proto); - service()->WaitForTracingDisabled(); auto* metadata = parsed_trace_data()->FindKey("metadata"); EXPECT_TRUE(metadata); EXPECT_EQ(metadata->FindKey("int_metadata")->GetInt(), 42); @@ -311,25 +175,16 @@ } TEST_F(JSONTraceExporterTest, TestBasicEvent) { - CreateJSONTraceExporter("foo"); - service()->WaitForTracingEnabled(); - StopAndFlush(); - perfetto::protos::TracePacket trace_packet_proto; auto* new_trace_event = trace_packet_proto.mutable_chrome_events()->add_trace_events(); SetTestPacketBasicData(new_trace_event); FinalizePacket(trace_packet_proto); - service()->WaitForTracingDisabled(); ValidateAndGetBasicTestPacket(); } TEST_F(JSONTraceExporterTest, TestStringTable) { - CreateJSONTraceExporter("foo"); - service()->WaitForTracingEnabled(); - StopAndFlush(); - perfetto::protos::TracePacket trace_packet_proto; auto* new_trace_event = trace_packet_proto.mutable_chrome_events()->add_trace_events(); @@ -364,8 +219,6 @@ FinalizePacket(trace_packet_proto); - service()->WaitForTracingDisabled(); - auto* trace_event = trace_analyzer()->FindFirstOf( trace_analyzer::Query(trace_analyzer::Query::EVENT_NAME) == trace_analyzer::Query::String("foo_name")); @@ -378,10 +231,6 @@ } TEST_F(JSONTraceExporterTest, TestEventWithBoolArgs) { - CreateJSONTraceExporter("foo"); - service()->WaitForTracingEnabled(); - StopAndFlush(); - perfetto::protos::TracePacket trace_packet_proto; auto* new_trace_event = trace_packet_proto.mutable_chrome_events()->add_trace_events(); @@ -401,7 +250,6 @@ FinalizePacket(trace_packet_proto); - service()->WaitForTracingDisabled(); auto* trace_event = ValidateAndGetBasicTestPacket(); EXPECT_TRUE(trace_event->GetKnownArgAsBool("foo1")); @@ -409,10 +257,6 @@ } TEST_F(JSONTraceExporterTest, TestEventWithUintArgs) { - CreateJSONTraceExporter("foo"); - service()->WaitForTracingEnabled(); - StopAndFlush(); - perfetto::protos::TracePacket trace_packet_proto; auto* new_trace_event = trace_packet_proto.mutable_chrome_events()->add_trace_events(); @@ -432,7 +276,6 @@ FinalizePacket(trace_packet_proto); - service()->WaitForTracingDisabled(); auto* trace_event = ValidateAndGetBasicTestPacket(); EXPECT_EQ(1, trace_event->GetKnownArgAsDouble("foo1")); @@ -440,10 +283,6 @@ } TEST_F(JSONTraceExporterTest, TestEventWithIntArgs) { - CreateJSONTraceExporter("foo"); - service()->WaitForTracingEnabled(); - StopAndFlush(); - perfetto::protos::TracePacket trace_packet_proto; auto* new_trace_event = trace_packet_proto.mutable_chrome_events()->add_trace_events(); @@ -463,7 +302,6 @@ FinalizePacket(trace_packet_proto); - service()->WaitForTracingDisabled(); auto* trace_event = ValidateAndGetBasicTestPacket(); EXPECT_EQ(1, trace_event->GetKnownArgAsDouble("foo1")); @@ -471,10 +309,6 @@ } TEST_F(JSONTraceExporterTest, TestEventWithDoubleArgs) { - CreateJSONTraceExporter("foo"); - service()->WaitForTracingEnabled(); - StopAndFlush(); - perfetto::protos::TracePacket trace_packet_proto; auto* new_trace_event = trace_packet_proto.mutable_chrome_events()->add_trace_events(); @@ -494,7 +328,6 @@ FinalizePacket(trace_packet_proto); - service()->WaitForTracingDisabled(); auto* trace_event = ValidateAndGetBasicTestPacket(); EXPECT_EQ(1.0, trace_event->GetKnownArgAsDouble("foo1")); @@ -502,10 +335,6 @@ } TEST_F(JSONTraceExporterTest, TestEventWithStringArgs) { - CreateJSONTraceExporter("foo"); - service()->WaitForTracingEnabled(); - StopAndFlush(); - perfetto::protos::TracePacket trace_packet_proto; auto* new_trace_event = trace_packet_proto.mutable_chrome_events()->add_trace_events(); @@ -525,7 +354,6 @@ FinalizePacket(trace_packet_proto); - service()->WaitForTracingDisabled(); auto* trace_event = ValidateAndGetBasicTestPacket(); EXPECT_EQ("bar1", trace_event->GetKnownArgAsString("foo1")); @@ -533,10 +361,6 @@ } TEST_F(JSONTraceExporterTest, TestEventWithPointerArgs) { - CreateJSONTraceExporter("foo"); - service()->WaitForTracingEnabled(); - StopAndFlush(); - perfetto::protos::TracePacket trace_packet_proto; auto* new_trace_event = trace_packet_proto.mutable_chrome_events()->add_trace_events(); @@ -556,7 +380,6 @@ FinalizePacket(trace_packet_proto); - service()->WaitForTracingDisabled(); auto* trace_event = ValidateAndGetBasicTestPacket(); EXPECT_EQ("0x1", trace_event->GetKnownArgAsString("foo1")); @@ -564,10 +387,6 @@ } TEST_F(JSONTraceExporterTest, TestEventWithConvertableArgs) { - CreateJSONTraceExporter("foo"); - service()->WaitForTracingEnabled(); - StopAndFlush(); - perfetto::protos::TracePacket trace_packet_proto; auto* new_trace_event = trace_packet_proto.mutable_chrome_events()->add_trace_events(); @@ -587,7 +406,6 @@ FinalizePacket(trace_packet_proto); - service()->WaitForTracingDisabled(); auto* trace_event = ValidateAndGetBasicTestPacket(); EXPECT_EQ("conv_value1", trace_event->GetKnownArgAsString("foo1")); @@ -595,10 +413,6 @@ } TEST_F(JSONTraceExporterTest, TestEventWithTracedValueArg) { - CreateJSONTraceExporter("foo"); - service()->WaitForTracingEnabled(); - StopAndFlush(); - perfetto::protos::TracePacket trace_packet_proto; auto* new_trace_event = trace_packet_proto.mutable_chrome_events()->add_trace_events(); @@ -612,7 +426,6 @@ FinalizePacket(trace_packet_proto); - service()->WaitForTracingDisabled(); auto* trace_event = ValidateAndGetBasicTestPacket(); auto arg_value = trace_event->GetKnownArgAsValue("foo1"); @@ -716,10 +529,6 @@ } TEST_F(JSONTraceExporterTest, TestLegacyUserTrace) { - CreateJSONTraceExporter("foo"); - service()->WaitForTracingEnabled(); - StopAndFlush(); - perfetto::protos::TracePacket trace_packet_proto; auto* new_trace_event = @@ -736,7 +545,6 @@ FinalizePacket(trace_packet_proto); - service()->WaitForTracingDisabled(); ValidateAndGetBasicTestPacket(); const trace_analyzer::TraceEvent* trace_event = trace_analyzer()->FindFirstOf( @@ -754,27 +562,18 @@ } TEST_F(JSONTraceExporterTest, TestLegacySystemFtrace) { - CreateJSONTraceExporter("foo"); - service()->WaitForTracingEnabled(); - StopAndFlush(); - std::string ftrace = "#dummy data"; perfetto::protos::TracePacket trace_packet_proto; trace_packet_proto.mutable_chrome_events()->add_legacy_ftrace_output(ftrace); FinalizePacket(trace_packet_proto); - service()->WaitForTracingDisabled(); auto* sys_trace = parsed_trace_data()->FindKey("systemTraceEvents"); EXPECT_TRUE(sys_trace); EXPECT_EQ(sys_trace->GetString(), ftrace); } TEST_F(JSONTraceExporterTest, TestLegacySystemTraceEvents) { - CreateJSONTraceExporter("foo"); - service()->WaitForTracingEnabled(); - StopAndFlush(); - perfetto::protos::TracePacket trace_packet_proto; auto* json_trace = @@ -788,8 +587,6 @@ FinalizePacket(trace_packet_proto); - service()->WaitForTracingDisabled(); - auto* sys_trace = parsed_trace_data()->FindKey("systemTraceEvents"); EXPECT_TRUE(sys_trace); EXPECT_EQ(sys_trace->FindKey("name")->GetString(), "MySysTrace");
diff --git a/services/tracing/perfetto/perfetto_tracing_coordinator.cc b/services/tracing/perfetto/perfetto_tracing_coordinator.cc index 009dc15..b2bbc8a7 100644 --- a/services/tracing/perfetto/perfetto_tracing_coordinator.cc +++ b/services/tracing/perfetto/perfetto_tracing_coordinator.cc
@@ -8,26 +8,78 @@ #include <utility> #include "base/bind.h" +#include "build/build_config.h" #include "mojo/public/cpp/system/data_pipe_utils.h" #include "services/tracing/perfetto/json_trace_exporter.h" #include "services/tracing/perfetto/perfetto_service.h" +#include "services/tracing/public/mojom/perfetto_service.mojom.h" +#include "third_party/perfetto/include/perfetto/tracing/core/consumer.h" +#include "third_party/perfetto/include/perfetto/tracing/core/trace_config.h" #include "third_party/perfetto/include/perfetto/tracing/core/trace_stats.h" +#include "third_party/perfetto/include/perfetto/tracing/core/tracing_service.h" namespace tracing { -// A TracingSession is used to wrap all the associated -// state of an on-going tracing session, for easy setup -// and cleanup. -class PerfettoTracingCoordinator::TracingSession { +// A TracingSession acts as a perfetto consumer and is used to wrap all the +// associated state of an on-going tracing session, for easy setup and cleanup. +// +// TODO(eseckler): Make it possible to have multiple active sessions +// concurrently. Also support configuring the output format of a session (JSON +// vs. proto). +class PerfettoTracingCoordinator::TracingSession : public perfetto::Consumer { public: TracingSession(const std::string& config, base::OnceClosure tracing_over_callback) - : tracing_over_callback_(std::move(tracing_over_callback)) { - json_trace_exporter_ = std::make_unique<JSONTraceExporter>( - config, PerfettoService::GetInstance()->GetService()); + : json_trace_exporter_(std::make_unique<JSONTraceExporter>( + base::BindRepeating(&TracingSession::OnJSONTraceEventCallback, + base::Unretained(this)))), + tracing_over_callback_(std::move(tracing_over_callback)) { + perfetto::TracingService* service = + PerfettoService::GetInstance()->GetService(); + consumer_endpoint_ = service->ConnectConsumer(this, /*uid=*/0); + + // Start tracing. + perfetto::TraceConfig trace_config; + trace_config.add_buffers()->set_size_kb(4096 * 100); + + // Perfetto uses clock_gettime for its internal snapshotting, which gets + // blocked by the sandboxed and isn't needed for Chrome regardless. + trace_config.set_disable_clock_snapshotting(true); + + auto* trace_event_config = + trace_config.add_data_sources()->mutable_config(); + trace_event_config->set_name(mojom::kTraceEventDataSourceName); + trace_event_config->set_target_buffer(0); + auto* chrome_config = trace_event_config->mutable_chrome_config(); + chrome_config->set_trace_config(config); + +// Only CrOS and Cast support system tracing. +#if defined(OS_CHROMEOS) || (defined(IS_CHROMECAST) && defined(OS_LINUX)) + auto* system_trace_config = + trace_config.add_data_sources()->mutable_config(); + system_trace_config->set_name(mojom::kSystemTraceDataSourceName); + system_trace_config->set_target_buffer(0); + auto* system_chrome_config = system_trace_config->mutable_chrome_config(); + system_chrome_config->set_trace_config(config); +#endif + +#if defined(OS_CHROMEOS) + auto* arc_trace_config = trace_config.add_data_sources()->mutable_config(); + arc_trace_config->set_name(mojom::kArcTraceDataSourceName); + arc_trace_config->set_target_buffer(0); + auto* arc_chrome_config = arc_trace_config->mutable_chrome_config(); + arc_chrome_config->set_trace_config(config); +#endif + + auto* trace_metadata_config = + trace_config.add_data_sources()->mutable_config(); + trace_metadata_config->set_name(mojom::kMetaDataSourceName); + trace_metadata_config->set_target_buffer(0); + + consumer_endpoint_->EnableTracing(trace_config); } - ~TracingSession() { + ~TracingSession() override { if (!stop_and_flush_callback_.is_null()) { base::ResetAndReturn(&stop_and_flush_callback_) .Run(base::Value(base::Value::Type::DICTIONARY)); @@ -40,9 +92,7 @@ StopAndFlushCallback callback) { stream_ = std::move(stream); stop_and_flush_callback_ = std::move(callback); - - json_trace_exporter_->StopAndFlush(base::BindRepeating( - &TracingSession::OnJSONTraceEventCallback, base::Unretained(this))); + consumer_endpoint_->DisableTracing(); } void OnJSONTraceEventCallback(const std::string& json, @@ -70,11 +120,31 @@ return; } request_buffer_usage_callback_ = std::move(callback); - json_trace_exporter_->GetTraceStats( - base::BindOnce(&TracingSession::OnTraceStats, base::Unretained(this))); + consumer_endpoint_->GetTraceStats(); } - void OnTraceStats(bool success, const perfetto::TraceStats& stats) { + // perfetto::Consumer implementation. + // This gets called by the Perfetto service as control signals, + // and to send finished protobufs over. + void OnConnect() override {} + + void OnDisconnect() override {} + + void OnTracingDisabled() override { consumer_endpoint_->ReadBuffers(); } + + void OnTraceData(std::vector<perfetto::TracePacket> packets, + bool has_more) override { + json_trace_exporter_->OnTraceData(std::move(packets), has_more); + } + + // Consumer Detach / Attach is not used in Chrome. + void OnDetach(bool success) override { NOTREACHED(); } + + void OnAttach(bool success, const perfetto::TraceConfig&) override { + NOTREACHED(); + } + + void OnTraceStats(bool success, const perfetto::TraceStats& stats) override { DCHECK(request_buffer_usage_callback_); if (!success) { std::move(request_buffer_usage_callback_).Run(false, 0.0f, 0); @@ -102,6 +172,10 @@ base::OnceClosure tracing_over_callback_; RequestBufferUsageCallback request_buffer_usage_callback_; + // Keep last to avoid edge-cases where its callbacks come in mid-destruction. + std::unique_ptr<perfetto::TracingService::ConsumerEndpoint> + consumer_endpoint_; + DISALLOW_COPY_AND_ASSIGN(TracingSession); };
diff --git a/services/tracing/perfetto/producer_host.cc b/services/tracing/perfetto/producer_host.cc index 27a97cd..e804c21 100644 --- a/services/tracing/perfetto/producer_host.cc +++ b/services/tracing/perfetto/producer_host.cc
@@ -68,14 +68,9 @@ void ProducerHost::StartDataSource(perfetto::DataSourceInstanceID id, const perfetto::DataSourceConfig& config) { - // TODO(oysteine): Send full DataSourceConfig, not just the name/target_buffer - // and Chrome Tracing string. - auto data_source_config = mojom::DataSourceConfig::New(); - data_source_config->name = config.name(); - data_source_config->target_buffer = config.target_buffer(); - - data_source_config->trace_config = config.chrome_config().trace_config(); - producer_client_->StartDataSource(id, std::move(data_source_config)); + // The type traits will send the base fields in the DataSourceConfig and also + // the ChromeConfig other configs are dropped. + producer_client_->StartDataSource(id, config); } void ProducerHost::StopDataSource(perfetto::DataSourceInstanceID id) {
diff --git a/services/tracing/perfetto/test_utils.cc b/services/tracing/perfetto/test_utils.cc index d662027c..ec9abbe2 100644 --- a/services/tracing/perfetto/test_utils.cc +++ b/services/tracing/perfetto/test_utils.cc
@@ -39,9 +39,9 @@ void TestDataSource::StartTracing( ProducerClient* producer_client, - const mojom::DataSourceConfig& data_source_config) { + const perfetto::DataSourceConfig& data_source_config) { producer_client_ = producer_client; - target_buffer_ = data_source_config.target_buffer; + target_buffer_ = data_source_config.target_buffer(); if (send_packet_count_ > 0) { std::unique_ptr<perfetto::TraceWriter> writer = @@ -82,7 +82,7 @@ void MockProducerClient::StartDataSource( uint64_t id, - mojom::DataSourceConfigPtr data_source_config) { + const perfetto::DataSourceConfig& data_source_config) { ProducerClient::StartDataSource(id, std::move(data_source_config)); if (client_enabled_callback_) {
diff --git a/services/tracing/perfetto/test_utils.h b/services/tracing/perfetto/test_utils.h index 7246c122..34d6d52 100644 --- a/services/tracing/perfetto/test_utils.h +++ b/services/tracing/perfetto/test_utils.h
@@ -29,8 +29,9 @@ void WritePacketBigly(); // DataSourceBase implementation - void StartTracing(ProducerClient* producer_client, - const mojom::DataSourceConfig& data_source_config) override; + void StartTracing( + ProducerClient* producer_client, + const perfetto::DataSourceConfig& data_source_config) override; void StopTracing( base::OnceClosure stop_complete_callback = base::OnceClosure()) override; void Flush(base::RepeatingClosure flush_complete_callback) override; @@ -51,8 +52,9 @@ void SetupDataSource(const std::string& data_source_name); - void StartDataSource(uint64_t id, - mojom::DataSourceConfigPtr data_source_config) override; + void StartDataSource( + uint64_t id, + const perfetto::DataSourceConfig& data_source_config) override; void StopDataSource(uint64_t id, StopDataSourceCallback callback) override;
diff --git a/services/tracing/public/cpp/perfetto/producer_client.cc b/services/tracing/public/cpp/perfetto/producer_client.cc index 3c249d3..7653756 100644 --- a/services/tracing/public/cpp/perfetto/producer_client.cc +++ b/services/tracing/public/cpp/perfetto/producer_client.cc
@@ -45,7 +45,7 @@ void ProducerClient::DataSourceBase::StartTracingWithID( uint64_t data_source_id, ProducerClient* producer_client, - const mojom::DataSourceConfig& data_source_config) { + const perfetto::DataSourceConfig& data_source_config) { data_source_id_ = data_source_id; StartTracing(producer_client, data_source_config); } @@ -180,14 +180,13 @@ void ProducerClient::StartDataSource( uint64_t id, - mojom::DataSourceConfigPtr data_source_config) { + const perfetto::DataSourceConfig& data_source_config) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(data_source_config); // TODO(oysteine): Support concurrent tracing sessions. for (auto* data_source : data_sources_) { - if (data_source->name() == data_source_config->name) { - data_source->StartTracingWithID(id, this, *data_source_config); + if (data_source->name() == data_source_config.name()) { + data_source->StartTracingWithID(id, this, data_source_config); return; } }
diff --git a/services/tracing/public/cpp/perfetto/producer_client.h b/services/tracing/public/cpp/perfetto/producer_client.h index a154ed8..32fde716 100644 --- a/services/tracing/public/cpp/perfetto/producer_client.h +++ b/services/tracing/public/cpp/perfetto/producer_client.h
@@ -50,13 +50,14 @@ explicit DataSourceBase(const std::string& name); virtual ~DataSourceBase(); - void StartTracingWithID(uint64_t data_source_id, - ProducerClient* producer_client, - const mojom::DataSourceConfig& data_source_config); + void StartTracingWithID( + uint64_t data_source_id, + ProducerClient* producer_client, + const perfetto::DataSourceConfig& data_source_config); virtual void StartTracing( ProducerClient* producer_client, - const mojom::DataSourceConfig& data_source_config) = 0; + const perfetto::DataSourceConfig& data_source_config) = 0; virtual void StopTracing( base::OnceClosure stop_complete_callback = base::OnceClosure()) = 0; @@ -108,8 +109,9 @@ // Called through Mojo by the ProducerHost on the service-side to control // tracing and toggle specific DataSources. void OnTracingStart(mojo::ScopedSharedBufferHandle shared_memory) override; - void StartDataSource(uint64_t id, - mojom::DataSourceConfigPtr data_source_config) override; + void StartDataSource( + uint64_t id, + const perfetto::DataSourceConfig& data_source_config) override; void StopDataSource(uint64_t id, StopDataSourceCallback callback) override; void Flush(uint64_t flush_request_id,
diff --git a/services/tracing/public/cpp/perfetto/trace_event_data_source.cc b/services/tracing/public/cpp/perfetto/trace_event_data_source.cc index fc8a8f298..c50862b3 100644 --- a/services/tracing/public/cpp/perfetto/trace_event_data_source.cc +++ b/services/tracing/public/cpp/perfetto/trace_event_data_source.cc
@@ -98,11 +98,11 @@ void TraceEventMetadataSource::StartTracing( ProducerClient* producer_client, - const mojom::DataSourceConfig& data_source_config) { + const perfetto::DataSourceConfig& data_source_config) { // TODO(eseckler): Once we support streaming of trace data, it would make // sense to emit the metadata on startup, so the UI can display it right away. trace_writer_ = - producer_client->CreateTraceWriter(data_source_config.target_buffer); + producer_client->CreateTraceWriter(data_source_config.target_buffer()); } void TraceEventMetadataSource::StopTracing( @@ -497,26 +497,27 @@ void TraceEventDataSource::StartTracing( ProducerClient* producer_client, - const mojom::DataSourceConfig& data_source_config) { + const perfetto::DataSourceConfig& data_source_config) { std::unique_ptr<perfetto::StartupTraceWriterRegistry> unbound_writer_registry; { base::AutoLock lock(lock_); DCHECK(!producer_client_); producer_client_ = producer_client; - target_buffer_ = data_source_config.target_buffer; + target_buffer_ = data_source_config.target_buffer(); // Reduce lock contention by binding the registry without holding the lock. unbound_writer_registry = std::move(startup_writer_registry_); } if (unbound_writer_registry) { producer_client->BindStartupTraceWriterRegistry( - std::move(unbound_writer_registry), data_source_config.target_buffer); + std::move(unbound_writer_registry), data_source_config.target_buffer()); } else { RegisterWithTraceLog(); } - auto trace_config = TraceConfig(data_source_config.trace_config); + auto trace_config = + TraceConfig(data_source_config.chrome_config().trace_config()); TraceLog::GetInstance()->SetEnabled(trace_config, TraceLog::RECORDING_MODE); ResetHistograms(trace_config); }
diff --git a/services/tracing/public/cpp/perfetto/trace_event_data_source.h b/services/tracing/public/cpp/perfetto/trace_event_data_source.h index bb1028d..a1f9eb7 100644 --- a/services/tracing/public/cpp/perfetto/trace_event_data_source.h +++ b/services/tracing/public/cpp/perfetto/trace_event_data_source.h
@@ -39,8 +39,9 @@ // ProducerClient::DataSourceBase implementation, called by // ProducerClent. - void StartTracing(ProducerClient* producer_client, - const mojom::DataSourceConfig& data_source_config) override; + void StartTracing( + ProducerClient* producer_client, + const perfetto::DataSourceConfig& data_source_config) override; void StopTracing(base::OnceClosure stop_complete_callback) override; void Flush(base::RepeatingClosure flush_complete_callback) override; @@ -78,8 +79,9 @@ // which will clear the stored pointer to it, before it // gets destroyed. ProducerClient::CreateTraceWriter can be // called by the TraceEventDataSource on any thread. - void StartTracing(ProducerClient* producer_client, - const mojom::DataSourceConfig& data_source_config) override; + void StartTracing( + ProducerClient* producer_client, + const perfetto::DataSourceConfig& data_source_config) override; // Called from the ProducerClient. void StopTracing(base::OnceClosure stop_complete_callback) override;
diff --git a/services/tracing/public/cpp/perfetto/trace_event_data_source_unittest.cc b/services/tracing/public/cpp/perfetto/trace_event_data_source_unittest.cc index f311421..e2a5eff 100644 --- a/services/tracing/public/cpp/perfetto/trace_event_data_source_unittest.cc +++ b/services/tracing/public/cpp/perfetto/trace_event_data_source_unittest.cc
@@ -224,9 +224,8 @@ producer_client_ = std::make_unique<MockProducerClient>( scoped_task_environment_.GetMainThreadTaskRunner()); - auto data_source_config = mojom::DataSourceConfig::New(); - TraceEventDataSource::GetInstance()->StartTracing(producer_client(), - *data_source_config); + TraceEventDataSource::GetInstance()->StartTracing( + producer_client(), perfetto::DataSourceConfig()); } MockProducerClient* producer_client() { return producer_client_.get(); } @@ -295,8 +294,8 @@ CreateTraceEventDataSource(); - auto data_source_config = mojom::DataSourceConfig::New(); - metadata_source->StartTracing(producer_client(), *data_source_config); + metadata_source->StartTracing(producer_client(), + perfetto::DataSourceConfig()); base::RunLoop wait_for_stop; metadata_source->StopTracing(wait_for_stop.QuitClosure());
diff --git a/services/tracing/public/cpp/tracing_features.cc b/services/tracing/public/cpp/tracing_features.cc index 08887d9..66704a3b 100644 --- a/services/tracing/public/cpp/tracing_features.cc +++ b/services/tracing/public/cpp/tracing_features.cc
@@ -20,14 +20,8 @@ base::FEATURE_DISABLED_BY_DEFAULT}; // Runs the tracing service as an in-process browser service. -const base::Feature kTracingServiceInProcess { - "TracingServiceInProcess", -#if defined(OS_ANDROID) - base::FEATURE_ENABLED_BY_DEFAULT -#else - base::FEATURE_DISABLED_BY_DEFAULT -#endif -}; +const base::Feature kTracingServiceInProcess{"TracingServiceInProcess", + base::FEATURE_ENABLED_BY_DEFAULT}; } // namespace features
diff --git a/services/tracing/public/mojom/chrome_config_struct_traits.cc b/services/tracing/public/mojom/chrome_config_struct_traits.cc new file mode 100644 index 0000000..5280078 --- /dev/null +++ b/services/tracing/public/mojom/chrome_config_struct_traits.cc
@@ -0,0 +1,22 @@ +// 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. + +#include "services/tracing/public/mojom/chrome_config_struct_traits.h" + +#include <utility> + +namespace mojo { +// static +bool StructTraits< + tracing::mojom::ChromeConfigDataView, + perfetto::ChromeConfig>::Read(tracing::mojom::ChromeConfigDataView data, + perfetto::ChromeConfig* out) { + std::string config; + if (!data.ReadTraceConfig(&config)) { + return false; + } + out->set_trace_config(std::move(config)); + return true; +} +} // namespace mojo
diff --git a/services/tracing/public/mojom/chrome_config_struct_traits.h b/services/tracing/public/mojom/chrome_config_struct_traits.h new file mode 100644 index 0000000..e6c4437 --- /dev/null +++ b/services/tracing/public/mojom/chrome_config_struct_traits.h
@@ -0,0 +1,30 @@ +// 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. + +// This defines mappings from mojom IPC representations to their native perfetto +// equivalents. + +#ifndef SERVICES_TRACING_PUBLIC_MOJOM_CHROME_CONFIG_STRUCT_TRAITS_H_ +#define SERVICES_TRACING_PUBLIC_MOJOM_CHROME_CONFIG_STRUCT_TRAITS_H_ + +#include <string> + +#include "mojo/public/cpp/bindings/struct_traits.h" +#include "services/tracing/public/mojom/perfetto_service.mojom.h" +#include "third_party/perfetto/include/perfetto/tracing/core/chrome_config.h" + +namespace mojo { +template <> +class StructTraits<tracing::mojom::ChromeConfigDataView, + perfetto::ChromeConfig> { + public: + static const std::string& trace_config(const perfetto::ChromeConfig& src) { + return src.trace_config(); + } + + static bool Read(tracing::mojom::ChromeConfigDataView data, + perfetto::ChromeConfig* out); +}; +} // namespace mojo +#endif // SERVICES_TRACING_PUBLIC_MOJOM_CHROME_CONFIG_STRUCT_TRAITS_H_
diff --git a/services/tracing/public/mojom/data_source_config_struct_traits.cc b/services/tracing/public/mojom/data_source_config_struct_traits.cc new file mode 100644 index 0000000..bd1ca60 --- /dev/null +++ b/services/tracing/public/mojom/data_source_config_struct_traits.cc
@@ -0,0 +1,30 @@ +// 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. + +#include "services/tracing/public/mojom/data_source_config_struct_traits.h" + +#include <utility> + +#include "services/tracing/public/mojom/chrome_config_struct_traits.h" + +namespace mojo { +bool StructTraits<tracing::mojom::DataSourceConfigDataView, + perfetto::DataSourceConfig>:: + Read(tracing::mojom::DataSourceConfigDataView data, + perfetto::DataSourceConfig* out) { + std::string name, legacy_config; + perfetto::ChromeConfig config; + if (!data.ReadName(&name) || !data.ReadChromeConfig(&config) || + !data.ReadLegacyConfig(&legacy_config)) { + return false; + } + out->set_name(name); + out->set_target_buffer(data.target_buffer()); + out->set_trace_duration_ms(data.trace_duration_ms()); + out->set_tracing_session_id(data.tracing_session_id()); + *out->mutable_chrome_config() = std::move(config); + out->set_legacy_config(legacy_config); + return true; +} +} // namespace mojo
diff --git a/services/tracing/public/mojom/data_source_config_struct_traits.h b/services/tracing/public/mojom/data_source_config_struct_traits.h new file mode 100644 index 0000000..9a2fda2e --- /dev/null +++ b/services/tracing/public/mojom/data_source_config_struct_traits.h
@@ -0,0 +1,48 @@ +// 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. + +// This defines mappings from mojom IPC representations to their native perfetto +// equivalents. + +#ifndef SERVICES_TRACING_PUBLIC_MOJOM_DATA_SOURCE_CONFIG_STRUCT_TRAITS_H_ +#define SERVICES_TRACING_PUBLIC_MOJOM_DATA_SOURCE_CONFIG_STRUCT_TRAITS_H_ + +#include <string> + +#include "mojo/public/cpp/bindings/struct_traits.h" +#include "services/tracing/public/mojom/perfetto_service.mojom.h" +#include "third_party/perfetto/include/perfetto/tracing/core/chrome_config.h" +#include "third_party/perfetto/include/perfetto/tracing/core/data_source_config.h" + +namespace mojo { +template <> +class StructTraits<tracing::mojom::DataSourceConfigDataView, + perfetto::DataSourceConfig> { + public: + static const std::string& name(const perfetto::DataSourceConfig& src) { + return src.name(); + } + static uint32_t target_buffer(const perfetto::DataSourceConfig& src) { + return src.target_buffer(); + } + static uint32_t trace_duration_ms(const perfetto::DataSourceConfig& src) { + return src.trace_duration_ms(); + } + static uint64_t tracing_session_id(const perfetto::DataSourceConfig& src) { + return src.tracing_session_id(); + } + static const perfetto::ChromeConfig& chrome_config( + const perfetto::DataSourceConfig& src) { + return src.chrome_config(); + } + static const std::string& legacy_config( + const perfetto::DataSourceConfig& src) { + return src.legacy_config(); + } + + static bool Read(tracing::mojom::DataSourceConfigDataView data, + perfetto::DataSourceConfig* out); +}; +} // namespace mojo +#endif // SERVICES_TRACING_PUBLIC_MOJOM_DATA_SOURCE_CONFIG_STRUCT_TRAITS_H_
diff --git a/services/tracing/public/mojom/perfetto_service.mojom b/services/tracing/public/mojom/perfetto_service.mojom index 5046816..dc9175a 100644 --- a/services/tracing/public/mojom/perfetto_service.mojom +++ b/services/tracing/public/mojom/perfetto_service.mojom
@@ -63,10 +63,22 @@ uint64 flush_request_id; }; +// Passed as part of DataSourceConfig +struct ChromeConfig { + // TODO(crbug/928687): Once we've completed removing the old IPC layer we + // should convert this into a struct that represents a + // base::trace_event::TraceConfig object rather then the json encoded string + // used currently. + string trace_config; +}; + struct DataSourceConfig { string name; - string trace_config; uint32 target_buffer; + uint32 trace_duration_ms; + uint64 tracing_session_id; + ChromeConfig chrome_config; + string legacy_config; }; struct DataSourceRegistration {
diff --git a/services/tracing/public/mojom/perfetto_service.typemap b/services/tracing/public/mojom/perfetto_service.typemap index c19a6e3..4495c73 100644 --- a/services/tracing/public/mojom/perfetto_service.typemap +++ b/services/tracing/public/mojom/perfetto_service.typemap
@@ -1,12 +1,21 @@ mojom = "//services/tracing/public/mojom/perfetto_service.mojom" public_headers = [ "//third_party/perfetto/include/perfetto/tracing/core/commit_data_request.h", + "//third_party/perfetto/include/perfetto/tracing/core/data_source_config.h", + "//third_party/perfetto/include/perfetto/tracing/core/chrome_config.h", ] -traits_headers = - [ "//services/tracing/public/mojom/commit_data_request_struct_traits.h" ] +traits_headers = [ + "//services/tracing/public/mojom/commit_data_request_struct_traits.h", + "//services/tracing/public/mojom/data_source_config_struct_traits.h", + "//services/tracing/public/mojom/chrome_config_struct_traits.h", +] sources = [ + "//services/tracing/public/mojom/chrome_config_struct_traits.cc", + "//services/tracing/public/mojom/chrome_config_struct_traits.h", "//services/tracing/public/mojom/commit_data_request_struct_traits.cc", "//services/tracing/public/mojom/commit_data_request_struct_traits.h", + "//services/tracing/public/mojom/data_source_config_struct_traits.cc", + "//services/tracing/public/mojom/data_source_config_struct_traits.h", ] public_deps = [ "//third_party/perfetto:libperfetto", @@ -16,4 +25,6 @@ "tracing.mojom.ChunksToMove=perfetto::CommitDataRequest::ChunksToMove", "tracing.mojom.ChunkPatch=perfetto::CommitDataRequest::ChunkToPatch::Patch", "tracing.mojom.ChunkToPatch=perfetto::CommitDataRequest::ChunkToPatch", + "tracing.mojom.DataSourceConfig=perfetto::DataSourceConfig", + "tracing.mojom.ChromeConfig=perfetto::ChromeConfig", ]
diff --git a/services/ws/focus_handler.cc b/services/ws/focus_handler.cc index 1b98a85e..ad9ad5d 100644 --- a/services/ws/focus_handler.cc +++ b/services/ws/focus_handler.cc
@@ -93,6 +93,15 @@ return true; } +void FocusHandler::SetCanFocus(aura::Window* window, bool can_focus) { + if (window && (window_tree_->IsClientCreatedWindow(window) || + window_tree_->IsClientRootWindow(window))) { + window->SetProperty(kCanFocus, can_focus); + } else { + DVLOG(1) << "SetCanFocus failed (invalid or unknown window)"; + } +} + bool FocusHandler::IsFocusableWindow(aura::Window* window) const { if (!window) return true; // Used to clear focus.
diff --git a/services/ws/focus_handler.h b/services/ws/focus_handler.h index c44cbde..f53a92f 100644 --- a/services/ws/focus_handler.h +++ b/services/ws/focus_handler.h
@@ -27,6 +27,9 @@ // Sets focus to |window| (which may be null). Returns true on success. bool SetFocus(aura::Window* window); + // Sets whether |window| can be focused. + void SetCanFocus(aura::Window* window, bool can_focus); + private: // Returns true if |window| can be focused. bool IsFocusableWindow(aura::Window* window) const;
diff --git a/services/ws/focus_handler_unittest.cc b/services/ws/focus_handler_unittest.cc index 6df49dd..e166fb2 100644 --- a/services/ws/focus_handler_unittest.cc +++ b/services/ws/focus_handler_unittest.cc
@@ -11,7 +11,6 @@ #include "services/ws/event_test_utils.h" #include "services/ws/public/mojom/window_tree_constants.mojom.h" -#include "services/ws/window_properties.h" #include "services/ws/window_service.h" #include "services/ws/window_service_test_setup.h" #include "services/ws/window_tree_test_helper.h" @@ -79,13 +78,13 @@ top_level->AddChild(window); // SetFocus() should still fail as |window| isn't visible. EXPECT_FALSE(setup.window_tree_test_helper()->SetFocus(window)); - window->SetProperty(kCanFocus, false); + setup.window_tree_test_helper()->SetCanFocus(window, false); window->Show(); - // SetFocus() should fail as kCanFocus is false. + // SetFocus() should fail as SetCanFocus(false) was called. EXPECT_FALSE(setup.window_tree_test_helper()->SetFocus(window)); - window->ClearProperty(kCanFocus); + setup.window_tree_test_helper()->SetCanFocus(window, true); EXPECT_TRUE(setup.window_tree_test_helper()->SetFocus(window)); }
diff --git a/services/ws/public/mojom/window_tree.mojom b/services/ws/public/mojom/window_tree.mojom index 7559292..dbfe1128 100644 --- a/services/ws/public/mojom/window_tree.mojom +++ b/services/ws/public/mojom/window_tree.mojom
@@ -290,11 +290,14 @@ // Sets focus to the specified window, use 0 to clear focus. For a window to // get focus the following has to happen: the window is drawn, the window has - // been marked as focusable and the window is in a container the WindowManager - // has identified as allowing activation (see - // WindowManagerClient::AddActivationParent()). + // been marked as focusable (see SetCanFocus()) and the window is in a + // container the WindowManager has identified as allowing activation + // (see WindowManagerClient::AddActivationParent()). SetFocus(uint32 change_id, uint64 window_id); + // Marks the specified window as being able to receive focus. + SetCanFocus(uint64 window_id, bool can_focus); + // Sets the cursor when the pointer is inside |window_id|. SetCursor(uint32 change_id, uint64 window_id, ui.mojom.Cursor cursor);
diff --git a/services/ws/window_tree.cc b/services/ws/window_tree.cc index 61e7eaab..8dba67a4 100644 --- a/services/ws/window_tree.cc +++ b/services/ws/window_tree.cc
@@ -1072,7 +1072,8 @@ const base::Optional<std::vector<uint8_t>>& value) { aura::Window* window = GetWindowByClientId(window_id); DVLOG(3) << "SetWindowProperty client=" << client_id_ - << " client window_id=" << window_id.ToString(); + << " client window_id=" << window_id.ToString() + << " property=" << name; if (!window) { DVLOG(1) << "SetWindowProperty failed (no window)"; return false; @@ -1887,6 +1888,11 @@ change_id, SetFocusImpl(MakeClientWindowId(transport_window_id))); } +void WindowTree::SetCanFocus(Id transport_window_id, bool can_focus) { + focus_handler_.SetCanFocus(GetWindowByTransportId(transport_window_id), + can_focus); +} + void WindowTree::SetCursor(uint32_t change_id, Id transport_window_id, ui::Cursor cursor) {
diff --git a/services/ws/window_tree.h b/services/ws/window_tree.h index 3710bc0..b5366847 100644 --- a/services/ws/window_tree.h +++ b/services/ws/window_tree.h
@@ -455,6 +455,7 @@ uint32_t embed_flags, EmbedUsingTokenCallback callback) override; void SetFocus(uint32_t change_id, Id transport_window_id) override; + void SetCanFocus(Id transport_window_id, bool can_focus) override; void SetCursor(uint32_t change_id, Id transport_window_id, ui::Cursor cursor) override;
diff --git a/services/ws/window_tree_test_helper.cc b/services/ws/window_tree_test_helper.cc index 7a066e94..4d98b99 100644 --- a/services/ws/window_tree_test_helper.cc +++ b/services/ws/window_tree_test_helper.cc
@@ -156,6 +156,11 @@ return window_tree_->SetFocusImpl(ClientWindowIdForWindow(window)); } +void WindowTreeTestHelper::SetCanFocus(aura::Window* window, bool can_focus) { + window_tree_->SetCanFocus(window_tree_->TransportIdForWindow(window), + can_focus); +} + void WindowTreeTestHelper::SetCursor(aura::Window* window, ui::Cursor cursor) { window_tree_->SetCursorImpl(ClientWindowIdForWindow(window), cursor); }
diff --git a/services/ws/window_tree_test_helper.h b/services/ws/window_tree_test_helper.h index 9c585d23..f9c4b9e8 100644 --- a/services/ws/window_tree_test_helper.h +++ b/services/ws/window_tree_test_helper.h
@@ -98,6 +98,7 @@ void SetEventTargetingPolicy(aura::Window* window, mojom::EventTargetingPolicy policy); bool SetFocus(aura::Window* window); + void SetCanFocus(aura::Window* window, bool can_focus); void SetCursor(aura::Window* window, ui::Cursor cursor); void OnWindowInputEventAck(uint32_t event_id, mojom::EventResult result); bool StackAbove(aura::Window* above_window, aura::Window* below_window);
diff --git a/skia/config/SkUserConfig.h b/skia/config/SkUserConfig.h index fc09db84..1d4d99c 100644 --- a/skia/config/SkUserConfig.h +++ b/skia/config/SkUserConfig.h
@@ -144,6 +144,11 @@ #define SK_USE_LEGACY_DISTANCE_FIELDS #endif +// skbug.com/4783 +#ifndef SK_SUPPORT_LEGACY_DRAWLOOPER +#define SK_SUPPORT_LEGACY_DRAWLOOPER +#endif + // Skia is enabling this feature soon. Chrome probably does // not want it for M64 #ifndef SK_DISABLE_EXPLICIT_GPU_RESOURCE_ALLOCATION
diff --git a/skia/ext/platform_canvas.cc b/skia/ext/platform_canvas.cc index 5c179bf9..4258dff 100644 --- a/skia/ext/platform_canvas.cc +++ b/skia/ext/platform_canvas.cc
@@ -7,7 +7,6 @@ #include "base/logging.h" #include "base/memory/ptr_util.h" #include "build/build_config.h" -#include "third_party/skia/include/core/SkMetaData.h" #include "third_party/skia/include/core/SkTypes.h" namespace skia {
diff --git a/testing/android/native_test/java/src/org/chromium/native_test/NativeBrowserTestActivity.java b/testing/android/native_test/java/src/org/chromium/native_test/NativeBrowserTestActivity.java index 92fc4693..c5b2e23 100644 --- a/testing/android/native_test/java/src/org/chromium/native_test/NativeBrowserTestActivity.java +++ b/testing/android/native_test/java/src/org/chromium/native_test/NativeBrowserTestActivity.java
@@ -26,6 +26,7 @@ }; private NativeTest mTest = new NativeTest(); + private boolean mStarted; @Override public void onCreate(Bundle savedInstanceState) { @@ -39,6 +40,15 @@ @Override public void onStart() { + // onStart can be called any number of times see: + // https://developer.android.com/guide/components/activities/activity-lifecycle#onstart + // We only want to run the test once (or bad things can happen) so bail out if we've + // already started. + if (mStarted) { + super.onStart(); + return; + } + mStarted = true; deletePrivateDataDirectory(); initializeBrowserProcess(); super.onStart();
diff --git a/testing/buildbot/chromium.clang.json b/testing/buildbot/chromium.clang.json index 69b7bec0..f1aa588bd 100644 --- a/testing/buildbot/chromium.clang.json +++ b/testing/buildbot/chromium.clang.json
@@ -11412,6 +11412,603 @@ } ] }, + "ToTLinuxOfficial": { + "gtest_tests": [ + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "accessibility_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "angle_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "app_shell_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "aura_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "base_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "blink_common_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "blink_fuzzer_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "blink_heap_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "blink_platform_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "boringssl_crypto_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "boringssl_ssl_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 10 + }, + "test": "browser_tests" + }, + { + "args": [ + "--enable-features=NetworkService" + ], + "name": "network_service_browser_tests", + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 15 + }, + "test": "browser_tests" + }, + { + "args": [ + "--enable-features=WebUIPolymer2", + "--disable-features=WebUIPolymer2Exceptions", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + ], + "name": "webui_polymer2_browser_tests", + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 4 + }, + "test": "browser_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cacheinvalidation_unittests" + }, + { + "args": [ + "--gtest_filter=-*UsingRealWebcam*" + ], + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "capture_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cast_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cc_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "chrome_app_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "chromedriver_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "components_browsertests" + }, + { + "args": [ + "--enable-features=NetworkService" + ], + "name": "network_service_components_browsertests", + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "components_browsertests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "components_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "compositor_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 6 + }, + "test": "content_browsertests" + }, + { + "args": [ + "--enable-features=NetworkService" + ], + "name": "network_service_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 2 + }, + "test": "content_browsertests" + }, + { + "args": [ + "--enable-perfetto", + "--gtest_filter=TracingControllerTest.*" + ], + "name": "perfetto_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "content_browsertests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "content_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cronet_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cronet_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "crypto_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "dbus_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "device_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "display_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "events_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "extensions_browsertests" + }, + { + "args": [ + "--enable-features=NetworkService" + ], + "name": "network_service_extensions_browsertests", + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "extensions_browsertests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "extensions_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "filesystem_service_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gcm_unit_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gfx_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gin_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "google_apis_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gpu_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "headless_browsertests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "headless_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 3 + }, + "test": "interactive_ui_tests" + }, + { + "args": [ + "--enable-features=NetworkService" + ], + "name": "network_service_interactive_ui_tests", + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 3 + }, + "test": "interactive_ui_tests" + }, + { + "args": [ + "--enable-features=WebUIPolymer2", + "--disable-features=WebUIPolymer2Exceptions", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + ], + "name": "webui_polymer2_interactive_ui_tests", + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "interactive_ui_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "ipc_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "jingle_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "latency_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "leveldb_service_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "libjingle_xmpp_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "media_blink_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "media_service_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "media_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "message_center_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "midi_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "mojo_core_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "mojo_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "nacl_helper_nonsfi_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "nacl_loader_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "native_theme_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "net_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "pdf_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "ppapi_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "printing_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "remoting_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "sandbox_linux_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "service_manager_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "services_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "shell_dialogs_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "skia_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "snapshot_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "sql_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "storage_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "sync_integration_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "traffic_annotation_auditor_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "ui_base_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "ui_touch_selection_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "unit_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "url_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "views_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "viz_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "vr_common_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "vr_pixeltests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "webkit_unit_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "wm_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "wtf_unittests" + } + ], + "scripts": [ + { + "name": "check_gn_headers", + "script": "check_gn_headers.py" + } + ] + }, "ToTLinuxTSan": { "additional_compile_targets": [ "all"
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index c73b36f..224d3f5c 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -10027,6 +10027,7 @@ { "args": [ "--additional-driver-flag=--no-sandbox", + "--additional-env-var=LLVM_PROFILE_FILE=${ISOLATED_OUTDIR}/profraw/default-%8m.profraw", "--num-retries=3" ], "isolate_coverage_data": true, @@ -12429,775 +12430,6 @@ } ] }, - "mac-views-rel": { - "gtest_tests": [ - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "accessibility_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "app_shell_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_common_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_fuzzer_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "boringssl_crypto_tests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "boringssl_ssl_tests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows", - "--test-launcher-filter-file=../../testing/buildbot/filters/mac_window_server_killers.browser_tests.filter", - "--gtest_shuffle" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "args": [ - "--disable-features=VizDisplayCompositor", - "--enable-features=ViewsBrowserWindows" - ], - "name": "non_viz_browser_tests", - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "args": [ - "--enable-features=WebUIPolymer2,ViewsBrowserWindows", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" - ], - "name": "webui_polymer2_browser_tests", - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 4 - }, - "test": "browser_tests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "args": [ - "--gtest_filter=-*UsingRealWebcam*", - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cast_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cc_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chromedriver_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_browsertests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 6 - }, - "test": "content_browsertests" - }, - { - "args": [ - "--disable-features=VizDisplayCompositor", - "--enable-features=ViewsBrowserWindows" - ], - "name": "non_viz_content_browsertests", - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "content_browsertests" - }, - { - "args": [ - "--enable-perfetto", - "--gtest_filter=TracingControllerTest.*", - "--enable-features=ViewsBrowserWindows" - ], - "name": "perfetto_content_browsertests", - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "args": [ - "--enable-features=VizDisplayCompositor,ViewsBrowserWindows" - ], - "name": "viz_content_browsertests", - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "content_browsertests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "args": [ - "--disable-features=VizDisplayCompositor", - "--enable-features=ViewsBrowserWindows" - ], - "name": "non_viz_content_unittests", - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "args": [ - "--enable-features=VizDisplayCompositor,ViewsBrowserWindows" - ], - "name": "viz_content_unittests", - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cronet_tests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cronet_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "display_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "events_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_browsertests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "filesystem_service_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gfx_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gin_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "headless_browsertests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "headless_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 3 - }, - "test": "interactive_ui_tests" - }, - { - "args": [ - "--enable-features=WebUIPolymer2,ViewsBrowserWindows", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" - ], - "name": "webui_polymer2_interactive_ui_tests", - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "interactive_ui_tests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "latency_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "leveldb_service_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "libjingle_xmpp_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_service_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "message_center_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "nacl_loader_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sandbox_mac_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "service_manager_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "shell_dialogs_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "snapshot_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "storage_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sync_integration_tests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_touch_selection_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "viz_unittests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "args": [ - "--enable-features=ViewsBrowserWindows" - ], - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - } - ] - }, "mac10.10-blink-rel-dummy": { "isolated_scripts": [ {
diff --git a/testing/buildbot/chromium.perf.fyi.json b/testing/buildbot/chromium.perf.fyi.json index 784671b0..4b7f49e 100644 --- a/testing/buildbot/chromium.perf.fyi.json +++ b/testing/buildbot/chromium.perf.fyi.json
@@ -272,7 +272,7 @@ "--benchmarks=loading.desktop.network_service", "-v", "--upload-results", - "--output-format=chartjson", + "--output-format=histograms", "--browser=release" ], "isolate_name": "performance_test_suite",
diff --git a/testing/buildbot/generate_buildbot_json.py b/testing/buildbot/generate_buildbot_json.py index 047421f2..739ca42 100755 --- a/testing/buildbot/generate_buildbot_json.py +++ b/testing/buildbot/generate_buildbot_json.py
@@ -884,6 +884,7 @@ for c in milo_configs: for l in self.read_file(c).splitlines(): if (not 'name: "buildbucket/luci.chromium.' in l and + not 'name: "buildbucket/luci.chrome.' in l and not 'name: "buildbot/chromium.' in l and not 'name: "buildbot/tryserver.chromium.' in l): continue
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index 97a864f..2cc1887 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -119,14 +119,6 @@ '--gtest_shuffle', ], }, - 'mac-views-rel': { - # A subset of tests seem to cause WindowServer deaths on VMs. - # crbug.com/828031 et al. - 'args': [ - '--test-launcher-filter-file=../../testing/buildbot/filters/mac_window_server_killers.browser_tests.filter', - '--gtest_shuffle', - ], - }, # chromium.mac 'Mac10.10 Tests': { # A subset of tests seem to cause WindowServer deaths on VMs. @@ -767,7 +759,6 @@ 'Mac10.13 Tests (dbg)', 'Mac ASan 64 Tests (1)', 'Mac ASan 64 Tests (1)', - 'mac-views-rel', 'ToTMacASan', ], 'modifications': { @@ -832,7 +823,6 @@ 'Mac10.13 Tests (dbg)', 'Mac ASan 64 Tests (1)', 'Mac ASan 64 Tests (1)', - 'mac-views-rel', 'ToTMacASan', ], }, @@ -854,7 +844,6 @@ 'Mac10.13 Tests (dbg)', 'Mac ASan 64 Tests (1)', 'Mac ASan 64 Tests (1)', - 'mac-views-rel', 'ToTMacASan', ], }, @@ -893,7 +882,6 @@ 'Mac10.13 Tests (dbg)', 'Mac ASan 64 Tests (1)', 'Mac ASan 64 Tests (1)', - 'mac-views-rel', 'ToTMacASan', ], }, @@ -914,7 +902,6 @@ 'Mac10.13 Tests (dbg)', 'Mac ASan 64 Tests (1)', 'Mac ASan 64 Tests (1)', - 'mac-views-rel', 'ToTMacASan', ], 'modifications': {
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index 9bb494e2..7d7faa4c 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -2276,6 +2276,7 @@ 'webkit_layout_tests': { 'args': [ '--additional-driver-flag=--no-sandbox', + '--additional-env-var=LLVM_PROFILE_FILE=${ISOLATED_OUTDIR}/profraw/default-%8m.profraw', '--num-retries=3', ], 'isolate_name': 'webkit_layout_tests_exparchive',
diff --git a/testing/buildbot/tryserver.chromium.linux.json b/testing/buildbot/tryserver.chromium.linux.json index 7b007528..e2a0d2f9 100644 --- a/testing/buildbot/tryserver.chromium.linux.json +++ b/testing/buildbot/tryserver.chromium.linux.json
@@ -685,6 +685,7 @@ { "args": [ "--additional-driver-flag=--no-sandbox", + "--additional-env-var=LLVM_PROFILE_FILE=${ISOLATED_OUTDIR}/profraw/default-%8m.profraw", "--num-retries=3" ], "isolate_coverage_data": true,
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index 25ab1921..662dc96 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -848,6 +848,13 @@ 'gtest_tests': 'chromium_linux_gtests', }, }, + # Used on an internal builder. + 'ToTLinuxOfficial': { + 'test_suites': { + 'gtest_tests': 'chromium_linux_gtests', + 'scripts': 'check_gn_headers_script', + }, + }, 'ToTLinuxTSan': { 'additional_compile_targets': [ 'all', @@ -1566,14 +1573,6 @@ 'isolated_scripts': 'chromium_rel_isolated_scripts', }, }, - 'mac-views-rel': { - 'test_suites': { - 'gtest_tests': 'chromium_mac_fyi_gtests', - }, - 'args': [ - '--enable-features=ViewsBrowserWindows', - ], - }, 'mac10.10-blink-rel-dummy': { 'test_suites': { 'isolated_scripts': 'chromium_webkit_isolated_scripts',
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index b986124..0c64fa3 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -1564,6 +1564,21 @@ ] } ], + "DirectCompositionUseNV12DecodeSwapChain": [ + { + "platforms": [ + "windows" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "DirectCompositionUseNV12DecodeSwapChain" + ] + } + ] + } + ], "DownloadHomeMoreButton": [ { "platforms": [ @@ -2932,6 +2947,18 @@ }, "enable_features": [ "NewNetErrorPageUI" + ], + "disable_features": [ + "AutoFetchOnNetErrorPage" + ] + }, + { + "name": "Enabled_AutoFetch", + "enable_features": [ + "AutoFetchOnNetErrorPage" + ], + "disable_features": [ + "NewNetErrorPageUI" ] } ] @@ -4586,26 +4613,6 @@ ] } ], - "SyncUSSAutofillWalletData": [ - { - "platforms": [ - "android", - "chromeos", - "ios", - "linux", - "mac", - "windows" - ], - "experiments": [ - { - "name": "Enabled", - "enable_features": [ - "SyncUSSAutofillWalletData" - ] - } - ] - } - ], "TabRanker": [ { "platforms": [ @@ -5085,6 +5092,25 @@ ] } ], + "V8WasmCodeCache": [ + { + "platforms": [ + "android", + "chromeos", + "linux", + "mac", + "windows" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "WasmCodeCache" + ] + } + ] + } + ], "V8WasmTrapHandler": [ { "platforms": [
diff --git a/third_party/ashmem/README.chromium b/third_party/ashmem/README.chromium index 36f8f77b..ee9d9a7 100644 --- a/third_party/ashmem/README.chromium +++ b/third_party/ashmem/README.chromium
@@ -8,3 +8,6 @@ 0001-Add-ashmem-get-prot-region.path: Add ashmem_get_prot_region() declaration and implementation to return the current protection mask of a given Ashmem region. + 0002-Use-AShareMemory-functions-when-possible.patch: + Use ASharedMemory_xxx() functions from libandroid.so when possible + in order to prepare for future devices without ashmem support.
diff --git a/third_party/ashmem/ashmem-dev.c b/third_party/ashmem/ashmem-dev.c index 52b3f47..25a33cdc 100644 --- a/third_party/ashmem/ashmem-dev.c +++ b/third_party/ashmem/ashmem-dev.c
@@ -14,23 +14,115 @@ * limitations under the License. */ -/* - * Implementation of the user-space ashmem API for devices, which have our - * ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version, - * used by the simulator. - */ +#include "ashmem.h" +#include <dlfcn.h> +#include <errno.h> #include <unistd.h> +#include <stdlib.h> #include <string.h> +#include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> +#include <sys/stat.h> /* for fdstat() */ #include <fcntl.h> #include <linux/ashmem.h> -#include "ashmem.h" +#include <sys/system_properties.h> -#define ASHMEM_DEVICE "/dev/ashmem" +#define ASHMEM_DEVICE "/dev/ashmem" + +/* Technical note regarding reading system properties. + * + * Try to use the new __system_property_read_callback API that appeared in + * Android O / API level 26 when available. Otherwise use the deprecated + * __system_property_get function. + * + * For more technical details from an NDK maintainer, see: + * https://bugs.chromium.org/p/chromium/issues/detail?id=392191#c17 + */ + +/* Weak symbol import */ +void __system_property_read_callback( + const prop_info* info, + void (*callback)( + void* cookie, const char* name, const char* value, uint32_t serial), + void* cookie) __attribute__((weak)); + +/* Callback used with __system_property_read_callback. */ +static void prop_read_int(void* cookie, + const char* name, + const char* value, + uint32_t serial) { + *(int *)cookie = atoi(value); + (void)name; + (void)serial; +} + +static int system_property_get_int(const char* name) { + int result = 0; + if (__system_property_read_callback) { + const prop_info* info = __system_property_find(name); + if (info) + __system_property_read_callback(info, &prop_read_int, &result); + } else { + char value[PROP_VALUE_MAX] = {}; + if (__system_property_get(name, value) >= 1) + result = atoi(value); + } + return result; +} + +static int device_api_level() { + static int s_api_level = -1; + if (s_api_level < 0) + s_api_level = system_property_get_int("ro.build.version.sdk"); + return s_api_level; +} + +typedef enum { + ASHMEM_STATUS_INIT, + ASHMEM_STATUS_NOT_SUPPORTED, + ASHMEM_STATUS_SUPPORTED, +} AshmemStatus; + +static AshmemStatus s_ashmem_status = ASHMEM_STATUS_INIT; +static dev_t s_ashmem_dev; + +/* Return the dev_t of a given file path, or 0 if not available, */ +static dev_t ashmem_find_dev(const char* path) { + struct stat st; + dev_t result = 0; + if (stat(path, &st) == 0 && S_ISCHR(st.st_mode)) + result = st.st_dev; + return result; +} + +static AshmemStatus ashmem_get_status(void) { + /* NOTE: No need to make this thread-safe, assuming that + * all threads will find the same value. */ + if (s_ashmem_status != ASHMEM_STATUS_INIT) + return s_ashmem_status; + + s_ashmem_dev = ashmem_find_dev(ASHMEM_DEVICE); + s_ashmem_status = (s_ashmem_dev == 0) ? ASHMEM_STATUS_NOT_SUPPORTED + : ASHMEM_STATUS_SUPPORTED; + return s_ashmem_status; +} + +/* Returns true iff the ashmem device ioctl should be used for a given fd. + * NOTE: Try not to use fstat() when possible to avoid performance issues. */ +static int ashmem_dev_fd_check(int fd) { + if (device_api_level() <= __ANDROID_API_O_MR1__) + return 1; + if (ashmem_get_status() == ASHMEM_STATUS_SUPPORTED) { + struct stat st; + return (fstat(fd, &st) == 0 && S_ISCHR(st.st_mode) && + st.st_dev != 0 && st.st_dev == s_ashmem_dev); + } + return 0; +} /* * ashmem_create_region - creates a new ashmem region and returns the file @@ -39,67 +131,133 @@ * `name' is an optional label to give the region (visible in /proc/pid/maps) * `size' is the size of the region, in page-aligned bytes */ -int ashmem_create_region(const char *name, size_t size) -{ - int fd, ret; +static int ashmem_dev_create_region(const char *name, size_t size) { + int fd = open(ASHMEM_DEVICE, O_RDWR); + if (fd < 0) + return fd; - fd = open(ASHMEM_DEVICE, O_RDWR); - if (fd < 0) - return fd; + int ret; + if (name) { + char buf[ASHMEM_NAME_LEN]; + strlcpy(buf, name, sizeof(buf)); + ret = ioctl(fd, ASHMEM_SET_NAME, buf); + if (ret < 0) + goto error; + } + ret = ioctl(fd, ASHMEM_SET_SIZE, size); + if (ret < 0) + goto error; - if (name) { - char buf[ASHMEM_NAME_LEN]; - - strlcpy(buf, name, sizeof(buf)); - ret = ioctl(fd, ASHMEM_SET_NAME, buf); - if (ret < 0) - goto error; - } - - ret = ioctl(fd, ASHMEM_SET_SIZE, size); - if (ret < 0) - goto error; - - return fd; + return fd; error: - close(fd); - return ret; + close(fd); + return ret; } -int ashmem_set_prot_region(int fd, int prot) -{ - return ioctl(fd, ASHMEM_SET_PROT_MASK, prot); +static int ashmem_dev_set_prot_region(int fd, int prot) { + return ioctl(fd, ASHMEM_SET_PROT_MASK, prot); } -int ashmem_get_prot_region(int fd) -{ - return ioctl(fd, ASHMEM_GET_PROT_MASK); +static int ashmem_dev_get_prot_region(int fd) { + return ioctl(fd, ASHMEM_GET_PROT_MASK); } -int ashmem_pin_region(int fd, size_t offset, size_t len) -{ - struct ashmem_pin pin = { offset, len }; - return ioctl(fd, ASHMEM_PIN, &pin); +static int ashmem_dev_pin_region(int fd, size_t offset, size_t len) { + struct ashmem_pin pin = { offset, len }; + return ioctl(fd, ASHMEM_PIN, &pin); } -int ashmem_unpin_region(int fd, size_t offset, size_t len) -{ - struct ashmem_pin pin = { offset, len }; - return ioctl(fd, ASHMEM_UNPIN, &pin); +static int ashmem_dev_unpin_region(int fd, size_t offset, size_t len) { + struct ashmem_pin pin = { offset, len }; + return ioctl(fd, ASHMEM_UNPIN, &pin); } -int ashmem_get_size_region(int fd) -{ +static size_t ashmem_dev_get_size_region(int fd) { return ioctl(fd, ASHMEM_GET_SIZE, NULL); } -int ashmem_purge_all(void) -{ - const int fd = open(ASHMEM_DEVICE, O_RDWR); - if (fd < 0) - return fd; - const int ret = ioctl(fd, ASHMEM_PURGE_ALL_CACHES, 0); - close(fd); - return ret; +// Starting with API level 26, the following functions from +// libandroid.so should be used to create shared memory regions. +typedef int(*ASharedMemory_createFunc)(const char*, size_t); +typedef size_t(*ASharedMemory_getSizeFunc)(int fd); +typedef int(*ASharedMemory_setProtFunc)(int fd, int prot); + +// Function pointers to shared memory functions. +typedef struct { + ASharedMemory_createFunc create; + ASharedMemory_getSizeFunc getSize; + ASharedMemory_setProtFunc setProt; +} ASharedMemoryFuncs; + +const ASharedMemoryFuncs* ashmem_get_funcs() { + static ASharedMemoryFuncs s_ashmem_funcs = {}; + ASharedMemoryFuncs* funcs = &s_ashmem_funcs; + if (funcs->create == NULL) { + if (device_api_level() >= __ANDROID_API_O__) { + /* Leaked intentionally! */ + void* lib = dlopen("libandroid.so", RTLD_NOW); + funcs->create = (ASharedMemory_createFunc) + dlsym(lib, "ASharedMemory_create"); + funcs->getSize = (ASharedMemory_getSizeFunc) + dlsym(lib, "ASharedMemory_getSize"); + funcs->setProt = (ASharedMemory_setProtFunc) + dlsym(lib, "ASharedMemory_setProt"); + } else { + funcs->create = &ashmem_dev_create_region; + funcs->getSize = &ashmem_dev_get_size_region; + funcs->setProt = &ashmem_dev_set_prot_region; + } + } + return funcs; +} + +int ashmem_create_region(const char* name, size_t size) { + return ashmem_get_funcs()->create(name, size); +} + +int ashmem_set_prot_region(int fd, int prot) { + return ashmem_get_funcs()->setProt(fd, prot); +} + +int ashmem_get_prot_region(int fd) { + if (ashmem_dev_fd_check(fd)) + return ashmem_dev_get_prot_region(fd); + /* There are only two practical values to return here: either + * PROT_READ|PROT_WRITE or just PROT_READ, so try to determine + * the flags by trying to mmap() the region read-write first. + */ + int result = PROT_READ; + const size_t page_size = (size_t)sysconf(_SC_PAGESIZE); + void* m = mmap(NULL, page_size, PROT_READ|PROT_WRITE, + MAP_PRIVATE, fd, 0); + if (m != MAP_FAILED) { + munmap(m, page_size); + result = PROT_READ|PROT_WRITE; + } + return result; +} + +int ashmem_pin_region(int fd, size_t offset, size_t len) { + if (ashmem_dev_fd_check(fd)) + return ashmem_dev_pin_region(fd, offset, len); + return ASHMEM_NOT_PURGED; +} + +int ashmem_unpin_region(int fd, size_t offset, size_t len) { + if (ashmem_dev_fd_check(fd)) + return ashmem_dev_unpin_region(fd, offset, len); + /* NOTE: It is not possible to use madvise() here because it requires a + * memory address. This could be done in the caller though, instead of + * this function. */ + return 0; +} + +int ashmem_get_size_region(int fd) { + /* NOTE: Original API returns an int. Avoid breaking it. */ + return (int)ashmem_get_funcs()->getSize(fd); +} + +int ashmem_device_is_supported(void) { + return ashmem_get_status() == ASHMEM_STATUS_SUPPORTED; }
diff --git a/third_party/ashmem/ashmem.h b/third_party/ashmem/ashmem.h index d8afccbd..f3675c9 100644 --- a/third_party/ashmem/ashmem.h +++ b/third_party/ashmem/ashmem.h
@@ -16,13 +16,20 @@ extern "C" { #endif +/* Returns true if the ashmem device is supported on this device. + * Not that even if the device is not supported, + * ashmem_{create,set_prot,get_prot,get_size}_region() will still work + * because they will use the ASharedMemory functions from libandroid.so + * instead. But ashmem_{pin,unpin}_region() will be no-ops. + */ +int ashmem_device_is_supported(void); + int ashmem_create_region(const char *name, size_t size); int ashmem_set_prot_region(int fd, int prot); int ashmem_get_prot_region(int fd); int ashmem_pin_region(int fd, size_t offset, size_t len); int ashmem_unpin_region(int fd, size_t offset, size_t len); int ashmem_get_size_region(int fd); -int ashmem_purge_all(void); #ifdef __cplusplus }
diff --git a/third_party/ashmem/patches/0002-Use-ASharedMemory-functions-when-possible.patch b/third_party/ashmem/patches/0002-Use-ASharedMemory-functions-when-possible.patch new file mode 100644 index 0000000..d958065 --- /dev/null +++ b/third_party/ashmem/patches/0002-Use-ASharedMemory-functions-when-possible.patch
@@ -0,0 +1,332 @@ +diff --git a/third_party/ashmem/ashmem-dev.c b/third_party/ashmem/ashmem-dev.c +index 52b3f47eeae0..25a33cdcd0c8 100644 +--- a/third_party/ashmem/ashmem-dev.c ++++ b/third_party/ashmem/ashmem-dev.c +@@ -14,23 +14,115 @@ + * limitations under the License. + */ + +-/* +- * Implementation of the user-space ashmem API for devices, which have our +- * ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version, +- * used by the simulator. +- */ ++#include "ashmem.h" + ++#include <dlfcn.h> ++#include <errno.h> + #include <unistd.h> ++#include <stdlib.h> + #include <string.h> ++#include <sys/mman.h> + #include <sys/types.h> + #include <sys/stat.h> + #include <sys/ioctl.h> ++#include <sys/stat.h> /* for fdstat() */ + #include <fcntl.h> + + #include <linux/ashmem.h> +-#include "ashmem.h" ++#include <sys/system_properties.h> + +-#define ASHMEM_DEVICE "/dev/ashmem" ++#define ASHMEM_DEVICE "/dev/ashmem" ++ ++/* Technical note regarding reading system properties. ++ * ++ * Try to use the new __system_property_read_callback API that appeared in ++ * Android O / API level 26 when available. Otherwise use the deprecated ++ * __system_property_get function. ++ * ++ * For more technical details from an NDK maintainer, see: ++ * https://bugs.chromium.org/p/chromium/issues/detail?id=392191#c17 ++ */ ++ ++/* Weak symbol import */ ++void __system_property_read_callback( ++ const prop_info* info, ++ void (*callback)( ++ void* cookie, const char* name, const char* value, uint32_t serial), ++ void* cookie) __attribute__((weak)); ++ ++/* Callback used with __system_property_read_callback. */ ++static void prop_read_int(void* cookie, ++ const char* name, ++ const char* value, ++ uint32_t serial) { ++ *(int *)cookie = atoi(value); ++ (void)name; ++ (void)serial; ++} ++ ++static int system_property_get_int(const char* name) { ++ int result = 0; ++ if (__system_property_read_callback) { ++ const prop_info* info = __system_property_find(name); ++ if (info) ++ __system_property_read_callback(info, &prop_read_int, &result); ++ } else { ++ char value[PROP_VALUE_MAX] = {}; ++ if (__system_property_get(name, value) >= 1) ++ result = atoi(value); ++ } ++ return result; ++} ++ ++static int device_api_level() { ++ static int s_api_level = -1; ++ if (s_api_level < 0) ++ s_api_level = system_property_get_int("ro.build.version.sdk"); ++ return s_api_level; ++} ++ ++typedef enum { ++ ASHMEM_STATUS_INIT, ++ ASHMEM_STATUS_NOT_SUPPORTED, ++ ASHMEM_STATUS_SUPPORTED, ++} AshmemStatus; ++ ++static AshmemStatus s_ashmem_status = ASHMEM_STATUS_INIT; ++static dev_t s_ashmem_dev; ++ ++/* Return the dev_t of a given file path, or 0 if not available, */ ++static dev_t ashmem_find_dev(const char* path) { ++ struct stat st; ++ dev_t result = 0; ++ if (stat(path, &st) == 0 && S_ISCHR(st.st_mode)) ++ result = st.st_dev; ++ return result; ++} ++ ++static AshmemStatus ashmem_get_status(void) { ++ /* NOTE: No need to make this thread-safe, assuming that ++ * all threads will find the same value. */ ++ if (s_ashmem_status != ASHMEM_STATUS_INIT) ++ return s_ashmem_status; ++ ++ s_ashmem_dev = ashmem_find_dev(ASHMEM_DEVICE); ++ s_ashmem_status = (s_ashmem_dev == 0) ? ASHMEM_STATUS_NOT_SUPPORTED ++ : ASHMEM_STATUS_SUPPORTED; ++ return s_ashmem_status; ++} ++ ++/* Returns true iff the ashmem device ioctl should be used for a given fd. ++ * NOTE: Try not to use fstat() when possible to avoid performance issues. */ ++static int ashmem_dev_fd_check(int fd) { ++ if (device_api_level() <= __ANDROID_API_O_MR1__) ++ return 1; ++ if (ashmem_get_status() == ASHMEM_STATUS_SUPPORTED) { ++ struct stat st; ++ return (fstat(fd, &st) == 0 && S_ISCHR(st.st_mode) && ++ st.st_dev != 0 && st.st_dev == s_ashmem_dev); ++ } ++ return 0; ++} + + /* + * ashmem_create_region - creates a new ashmem region and returns the file +@@ -39,67 +131,133 @@ + * `name' is an optional label to give the region (visible in /proc/pid/maps) + * `size' is the size of the region, in page-aligned bytes + */ +-int ashmem_create_region(const char *name, size_t size) +-{ +- int fd, ret; ++static int ashmem_dev_create_region(const char *name, size_t size) { ++ int fd = open(ASHMEM_DEVICE, O_RDWR); ++ if (fd < 0) ++ return fd; + +- fd = open(ASHMEM_DEVICE, O_RDWR); +- if (fd < 0) +- return fd; ++ int ret; ++ if (name) { ++ char buf[ASHMEM_NAME_LEN]; ++ strlcpy(buf, name, sizeof(buf)); ++ ret = ioctl(fd, ASHMEM_SET_NAME, buf); ++ if (ret < 0) ++ goto error; ++ } ++ ret = ioctl(fd, ASHMEM_SET_SIZE, size); ++ if (ret < 0) ++ goto error; + +- if (name) { +- char buf[ASHMEM_NAME_LEN]; ++ return fd; + +- strlcpy(buf, name, sizeof(buf)); +- ret = ioctl(fd, ASHMEM_SET_NAME, buf); +- if (ret < 0) +- goto error; +- } ++error: ++ close(fd); ++ return ret; ++} + +- ret = ioctl(fd, ASHMEM_SET_SIZE, size); +- if (ret < 0) +- goto error; ++static int ashmem_dev_set_prot_region(int fd, int prot) { ++ return ioctl(fd, ASHMEM_SET_PROT_MASK, prot); ++} + +- return fd; ++static int ashmem_dev_get_prot_region(int fd) { ++ return ioctl(fd, ASHMEM_GET_PROT_MASK); ++} + +-error: +- close(fd); +- return ret; ++static int ashmem_dev_pin_region(int fd, size_t offset, size_t len) { ++ struct ashmem_pin pin = { offset, len }; ++ return ioctl(fd, ASHMEM_PIN, &pin); + } + +-int ashmem_set_prot_region(int fd, int prot) +-{ +- return ioctl(fd, ASHMEM_SET_PROT_MASK, prot); ++static int ashmem_dev_unpin_region(int fd, size_t offset, size_t len) { ++ struct ashmem_pin pin = { offset, len }; ++ return ioctl(fd, ASHMEM_UNPIN, &pin); + } + +-int ashmem_get_prot_region(int fd) +-{ +- return ioctl(fd, ASHMEM_GET_PROT_MASK); ++static size_t ashmem_dev_get_size_region(int fd) { ++ return ioctl(fd, ASHMEM_GET_SIZE, NULL); + } + +-int ashmem_pin_region(int fd, size_t offset, size_t len) +-{ +- struct ashmem_pin pin = { offset, len }; +- return ioctl(fd, ASHMEM_PIN, &pin); ++// Starting with API level 26, the following functions from ++// libandroid.so should be used to create shared memory regions. ++typedef int(*ASharedMemory_createFunc)(const char*, size_t); ++typedef size_t(*ASharedMemory_getSizeFunc)(int fd); ++typedef int(*ASharedMemory_setProtFunc)(int fd, int prot); ++ ++// Function pointers to shared memory functions. ++typedef struct { ++ ASharedMemory_createFunc create; ++ ASharedMemory_getSizeFunc getSize; ++ ASharedMemory_setProtFunc setProt; ++} ASharedMemoryFuncs; ++ ++const ASharedMemoryFuncs* ashmem_get_funcs() { ++ static ASharedMemoryFuncs s_ashmem_funcs = {}; ++ ASharedMemoryFuncs* funcs = &s_ashmem_funcs; ++ if (funcs->create == NULL) { ++ if (device_api_level() >= __ANDROID_API_O__) { ++ /* Leaked intentionally! */ ++ void* lib = dlopen("libandroid.so", RTLD_NOW); ++ funcs->create = (ASharedMemory_createFunc) ++ dlsym(lib, "ASharedMemory_create"); ++ funcs->getSize = (ASharedMemory_getSizeFunc) ++ dlsym(lib, "ASharedMemory_getSize"); ++ funcs->setProt = (ASharedMemory_setProtFunc) ++ dlsym(lib, "ASharedMemory_setProt"); ++ } else { ++ funcs->create = &ashmem_dev_create_region; ++ funcs->getSize = &ashmem_dev_get_size_region; ++ funcs->setProt = &ashmem_dev_set_prot_region; ++ } ++ } ++ return funcs; + } + +-int ashmem_unpin_region(int fd, size_t offset, size_t len) +-{ +- struct ashmem_pin pin = { offset, len }; +- return ioctl(fd, ASHMEM_UNPIN, &pin); ++int ashmem_create_region(const char* name, size_t size) { ++ return ashmem_get_funcs()->create(name, size); + } + +-int ashmem_get_size_region(int fd) +-{ +- return ioctl(fd, ASHMEM_GET_SIZE, NULL); ++int ashmem_set_prot_region(int fd, int prot) { ++ return ashmem_get_funcs()->setProt(fd, prot); + } + +-int ashmem_purge_all(void) +-{ +- const int fd = open(ASHMEM_DEVICE, O_RDWR); +- if (fd < 0) +- return fd; +- const int ret = ioctl(fd, ASHMEM_PURGE_ALL_CACHES, 0); +- close(fd); +- return ret; ++int ashmem_get_prot_region(int fd) { ++ if (ashmem_dev_fd_check(fd)) ++ return ashmem_dev_get_prot_region(fd); ++ /* There are only two practical values to return here: either ++ * PROT_READ|PROT_WRITE or just PROT_READ, so try to determine ++ * the flags by trying to mmap() the region read-write first. ++ */ ++ int result = PROT_READ; ++ const size_t page_size = (size_t)sysconf(_SC_PAGESIZE); ++ void* m = mmap(NULL, page_size, PROT_READ|PROT_WRITE, ++ MAP_PRIVATE, fd, 0); ++ if (m != MAP_FAILED) { ++ munmap(m, page_size); ++ result = PROT_READ|PROT_WRITE; ++ } ++ return result; ++} ++ ++int ashmem_pin_region(int fd, size_t offset, size_t len) { ++ if (ashmem_dev_fd_check(fd)) ++ return ashmem_dev_pin_region(fd, offset, len); ++ return ASHMEM_NOT_PURGED; ++} ++ ++int ashmem_unpin_region(int fd, size_t offset, size_t len) { ++ if (ashmem_dev_fd_check(fd)) ++ return ashmem_dev_unpin_region(fd, offset, len); ++ /* NOTE: It is not possible to use madvise() here because it requires a ++ * memory address. This could be done in the caller though, instead of ++ * this function. */ ++ return 0; ++} ++ ++int ashmem_get_size_region(int fd) { ++ /* NOTE: Original API returns an int. Avoid breaking it. */ ++ return (int)ashmem_get_funcs()->getSize(fd); ++} ++ ++int ashmem_device_is_supported(void) { ++ return ashmem_get_status() == ASHMEM_STATUS_SUPPORTED; + } +diff --git a/third_party/ashmem/ashmem.h b/third_party/ashmem/ashmem.h +index d8afccbd2a6e..f3675c98b19a 100644 +--- a/third_party/ashmem/ashmem.h ++++ b/third_party/ashmem/ashmem.h +@@ -16,13 +16,20 @@ + extern "C" { + #endif + ++/* Returns true if the ashmem device is supported on this device. ++ * Not that even if the device is not supported, ++ * ashmem_{create,set_prot,get_prot,get_size}_region() will still work ++ * because they will use the ASharedMemory functions from libandroid.so ++ * instead. But ashmem_{pin,unpin}_region() will be no-ops. ++ */ ++int ashmem_device_is_supported(void); ++ + int ashmem_create_region(const char *name, size_t size); + int ashmem_set_prot_region(int fd, int prot); + int ashmem_get_prot_region(int fd); + int ashmem_pin_region(int fd, size_t offset, size_t len); + int ashmem_unpin_region(int fd, size_t offset, size_t len); + int ashmem_get_size_region(int fd); +-int ashmem_purge_all(void); + + #ifdef __cplusplus + }
diff --git a/third_party/blink/public/mojom/background_fetch/background_fetch.mojom b/third_party/blink/public/mojom/background_fetch/background_fetch.mojom index eca2cf3..942ef21 100644 --- a/third_party/blink/public/mojom/background_fetch/background_fetch.mojom +++ b/third_party/blink/public/mojom/background_fetch/background_fetch.mojom
@@ -176,7 +176,7 @@ string developer_id, string unique_id, FetchAPIRequest? request_to_match, - QueryParams? cache_query_params, + CacheQueryOptions? cache_query_options, bool match_all) => (array<BackgroundFetchSettledFetch> fetches); // Registers the |observer| to receive events for the given registration
diff --git a/third_party/blink/public/mojom/cache_storage/cache_storage.mojom b/third_party/blink/public/mojom/cache_storage/cache_storage.mojom index 0d1387b..a9775d9 100644 --- a/third_party/blink/public/mojom/cache_storage/cache_storage.mojom +++ b/third_party/blink/public/mojom/cache_storage/cache_storage.mojom
@@ -38,15 +38,15 @@ }; // Controls how requests are matched in the Cache API. -struct QueryParams { +struct CacheQueryOptions { bool ignore_search = false; bool ignore_method = false; bool ignore_vary = false; }; // Controls how requests are matched in the CacheStorage API. -struct MultiQueryParams { - QueryParams query_params; +struct MultiCacheQueryOptions { + CacheQueryOptions query_options; mojo_base.mojom.String16? cache_name; }; @@ -66,9 +66,9 @@ // otherwise. blink.mojom.FetchAPIResponse? response; - // If the |operation_type| is kDelete, then the |match_params| must be + // If the |operation_type| is kDelete, then the |match_options| must be // defined, null otherwise. - QueryParams? match_params; + CacheQueryOptions? match_options; }; // Result of Open method. |status| is only set if there is a failure. @@ -101,18 +101,18 @@ // defined on spec: https://w3c.github.io/ServiceWorker/#cache-interface interface CacheStorageCache { // Returns the first cached response that matches |request| according to - // options specified on |query_params|. - Match(blink.mojom.FetchAPIRequest request, QueryParams query_params) + // options specified on |query_options|. + Match(blink.mojom.FetchAPIRequest request, CacheQueryOptions query_options) => (MatchResult result); // Returns all cached responses that match |request| according to options - // specified on |query_params|. - MatchAll(blink.mojom.FetchAPIRequest? request, QueryParams query_params) + // specified on |query_options|. + MatchAll(blink.mojom.FetchAPIRequest? request, CacheQueryOptions query_options) => (MatchAllResult result); // Returns all keys (which are requests) of matching |request| and - // |query_params|. - Keys(blink.mojom.FetchAPIRequest? request, QueryParams query_params) + // |query_options|. + Keys(blink.mojom.FetchAPIRequest? request, CacheQueryOptions query_options) => (CacheKeysResult result); // Perform a batch of operations, used for PUT and DELETE operations. @@ -138,9 +138,9 @@ Keys() => (array<mojo_base.mojom.String16> keys); // Returns the first cached response that matches |request| and - // |match_params|. It can search on all caches if |cache_name| isn't provided - // on |match_params|. - Match(blink.mojom.FetchAPIRequest request, MultiQueryParams match_params) + // |match_options|. It can search on all caches if |cache_name| isn't provided + // on |match_options|. + Match(blink.mojom.FetchAPIRequest request, MultiCacheQueryOptions match_options) => (MatchResult result); // Opens and returns a mojo interface to a cache, it creates if doesn't exist.
diff --git a/third_party/blink/public/mojom/dom_storage/storage_partition_service.mojom b/third_party/blink/public/mojom/dom_storage/storage_partition_service.mojom index 2873860..6042fd0 100644 --- a/third_party/blink/public/mojom/dom_storage/storage_partition_service.mojom +++ b/third_party/blink/public/mojom/dom_storage/storage_partition_service.mojom
@@ -13,8 +13,15 @@ // TODO(mek): If more than just DOMStorage related interfaces get added this // should probably move to some other directory. interface StoragePartitionService { + // TODO(dmurph): Change this back to non-sync after the cause of the renderer + // hang is discovered. http://crbug.com/927534 + [Sync] OpenLocalStorage(url.mojom.Origin origin, - StorageArea& area); + StorageArea& area) => (); + + // TODO(dmurph): Change this back to non-sync after the cause of the renderer + // hang is discovered. http://crbug.com/927534 + [Sync] OpenSessionStorage(string namespace_id, - SessionStorageNamespace& session_namespace); + SessionStorageNamespace& session_namespace) => (); };
diff --git a/third_party/blink/public/platform/task_type.h b/third_party/blink/public/platform/task_type.h index 4c16d7c2..4d9e491 100644 --- a/third_party/blink/public/platform/task_type.h +++ b/third_party/blink/public/platform/task_type.h
@@ -166,10 +166,6 @@ // * //components/webcrypto kInternalWebCrypto = 27, - // Tasks to execute IndexedDB's callbacks. Tasks with this type are posted by: - // * //content/renderer/indexed_db - kInternalIndexedDB = 28, - // Tasks to execute media-related things like logging or playback. Tasks with // this type are mainly posted by: // * //content/renderer/media
diff --git a/third_party/blink/public/platform/web_feature.mojom b/third_party/blink/public/platform/web_feature.mojom index 15fed44f..481322c 100644 --- a/third_party/blink/public/platform/web_feature.mojom +++ b/third_party/blink/public/platform/web_feature.mojom
@@ -2219,6 +2219,7 @@ kV8HTMLMediaElement_Remote_AttributeGetter = 2779, kV8RemotePlayback_WatchAvailability_Method = 2780, kV8RemotePlayback_Prompt_Method = 2781, + kLayoutJankExplicitlyRequested = 2782, // Add new features immediately above this line. Don't change assigned // numbers of any item, and don't reuse removed slots.
diff --git a/third_party/blink/public/platform/web_worker_fetch_context.h b/third_party/blink/public/platform/web_worker_fetch_context.h index 47bbbe61..96400c2 100644 --- a/third_party/blink/public/platform/web_worker_fetch_context.h +++ b/third_party/blink/public/platform/web_worker_fetch_context.h
@@ -110,6 +110,11 @@ // See content::URLRequest::site_for_cookies() for details. virtual WebURL SiteForCookies() const = 0; + // The top-frame-origin for the worker. For a dedicated worker this is the + // top-frame origin of the page that created the worker. For a shared worker + // this is unset. + virtual base::Optional<WebSecurityOrigin> TopFrameOrigin() const = 0; + // Reports the certificate error to the browser process. virtual void DidRunContentWithCertificateErrors() {} virtual void DidDisplayContentWithCertificateErrors() {}
diff --git a/third_party/blink/public/web/web_document.h b/third_party/blink/public/web/web_document.h index 6ab2d5c4..815c12f 100644 --- a/third_party/blink/public/web/web_document.h +++ b/third_party/blink/public/web/web_document.h
@@ -91,6 +91,7 @@ // cookie blocking. BLINK_EXPORT WebURL SiteForCookies() const; + BLINK_EXPORT WebSecurityOrigin TopFrameOrigin() const; BLINK_EXPORT WebElement DocumentElement() const; BLINK_EXPORT WebElement Body() const; BLINK_EXPORT WebElement Head();
diff --git a/third_party/blink/public/web/web_settings.h b/third_party/blink/public/web/web_settings.h index c1848e77..11dfe26 100644 --- a/third_party/blink/public/web/web_settings.h +++ b/third_party/blink/public/web/web_settings.h
@@ -288,6 +288,7 @@ virtual void SetLazyImageLoadingDistanceThresholdPx2G(int) = 0; virtual void SetLazyImageLoadingDistanceThresholdPx3G(int) = 0; virtual void SetLazyImageLoadingDistanceThresholdPx4G(int) = 0; + virtual void SetForceDarkModeEnabled(bool) = 0; protected: ~WebSettings() = default;
diff --git a/third_party/blink/renderer/bindings/core/v8/local_window_proxy.cc b/third_party/blink/renderer/bindings/core/v8/local_window_proxy.cc index 9c3e848f..c4220bd 100644 --- a/third_party/blink/renderer/bindings/core/v8/local_window_proxy.cc +++ b/third_party/blink/renderer/bindings/core/v8/local_window_proxy.cc
@@ -66,6 +66,12 @@ namespace blink { +namespace { + +constexpr char kGlobalProxyLabel[] = "WindowProxy::global_proxy_"; + +} // namespace + void LocalWindowProxy::Trace(blink::Visitor* visitor) { visitor->Trace(script_state_); WindowProxy::Trace(visitor); @@ -161,6 +167,7 @@ v8::Local<v8::Context> context = script_state_->GetContext(); if (global_proxy_.IsEmpty()) { global_proxy_.Set(GetIsolate(), context->Global()); + global_proxy_.Get().AnnotateStrongRetainer(kGlobalProxyLabel); CHECK(!global_proxy_.IsEmpty()); }
diff --git a/third_party/blink/renderer/bindings/core/v8/script_streamer.cc b/third_party/blink/renderer/bindings/core/v8/script_streamer.cc index 5aaee51..fe53aa48 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_streamer.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_streamer.cc
@@ -47,6 +47,9 @@ } void Produce(const uint8_t* data, size_t length) { + TRACE_EVENT_WITH_FLOW1(TRACE_DISABLED_BY_DEFAULT("v8.compile"), + "v8.streamingCompile.sendData", this, + TRACE_EVENT_FLAG_FLOW_OUT, "length", length); MutexLocker locker(mutex_); DCHECK(!finished_); data_.push_back(std::make_pair(data, length)); @@ -54,6 +57,9 @@ } void Finish() { + TRACE_EVENT_WITH_FLOW0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), + "v8.streamingCompile.finishData", this, + TRACE_EVENT_FLAG_FLOW_OUT); MutexLocker locker(mutex_); finished_ = true; have_data_.Signal(); @@ -61,8 +67,14 @@ void Consume(const uint8_t** data, size_t* length) { MutexLocker locker(mutex_); - while (!TryGetData(data, length)) + while (!TryGetData(data, length)) { + TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), + "v8.streamingCompile.waitForData"); have_data_.Wait(); + TRACE_EVENT_WITH_FLOW1(TRACE_DISABLED_BY_DEFAULT("v8.compile"), + "v8.streamingCompile.receivedData", this, + TRACE_EVENT_FLAG_FLOW_IN, "length", *length); + } } private: @@ -312,8 +324,10 @@ void RunScriptStreamingTask( std::unique_ptr<v8::ScriptCompiler::ScriptStreamingTask> task, ScriptStreamer* streamer) { - TRACE_EVENT1( - "v8,devtools.timeline", "v8.parseOnBackground", "data", + TRACE_EVENT_WITH_FLOW1( + "v8,devtools.timeline," TRACE_DISABLED_BY_DEFAULT("v8.compile"), + "v8.parseOnBackground", streamer, + TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT, "data", inspector_parse_script_event::Data(streamer->ScriptResourceIdentifier(), streamer->ScriptURLString())); // Running the task can and will block: SourceStream::GetSomeData will get @@ -415,6 +429,12 @@ return; } + TRACE_EVENT_WITH_FLOW1( + TRACE_DISABLED_BY_DEFAULT("v8.compile"), "v8.streamingCompile.start", + this, TRACE_EVENT_FLAG_FLOW_OUT, "data", + inspector_parse_script_event::Data(this->ScriptResourceIdentifier(), + this->ScriptURLString())); + if (RuntimeEnabledFeatures::ScheduledScriptStreamingEnabled()) { // Script streaming tasks are high priority, as they can block the parser, // and they can (and probably will) block during their own execution as @@ -522,6 +542,13 @@ } void ScriptStreamer::StreamingComplete() { + TRACE_EVENT_WITH_FLOW2( + TRACE_DISABLED_BY_DEFAULT("v8.compile"), "v8.streamingCompile.complete", + this, TRACE_EVENT_FLAG_FLOW_IN, "streaming_suppressed", + streaming_suppressed_, "data", + inspector_parse_script_event::Data(this->ScriptResourceIdentifier(), + this->ScriptURLString())); + // The background task is completed; do the necessary ramp-down in the main // thread. DCHECK(IsMainThread());
diff --git a/third_party/blink/renderer/bindings/core/v8/script_streamer_thread.cc b/third_party/blink/renderer/bindings/core/v8/script_streamer_thread.cc index bcedd546..e1b3c34c 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_streamer_thread.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_streamer_thread.cc
@@ -71,6 +71,11 @@ "v8,devtools.timeline", "v8.parseOnBackground", "data", inspector_parse_script_event::Data(streamer->ScriptResourceIdentifier(), streamer->ScriptURLString())); + TRACE_EVENT_WITH_FLOW1( + TRACE_DISABLED_BY_DEFAULT("v8.compile"), "v8.streamingCompile.run", + streamer, TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT, "data", + inspector_parse_script_event::Data(streamer->ScriptResourceIdentifier(), + streamer->ScriptURLString())); // Running the task can and will block: SourceStream::GetSomeData will get // called and it will block and wait for data from the network. task->Run();
diff --git a/third_party/blink/renderer/controller/BUILD.gn b/third_party/blink/renderer/controller/BUILD.gn index 6d18142..56bfdc0 100644 --- a/third_party/blink/renderer/controller/BUILD.gn +++ b/third_party/blink/renderer/controller/BUILD.gn
@@ -18,6 +18,7 @@ deps = [ "//skia", "//third_party/blink/renderer/core", + "//third_party/blink/renderer/core:testing", "//third_party/blink/renderer/modules", "//third_party/blink/renderer/platform", "//v8",
diff --git a/third_party/blink/renderer/controller/blink_leak_detector.cc b/third_party/blink/renderer/controller/blink_leak_detector.cc index d7b2bcef..a5837cc 100644 --- a/third_party/blink/renderer/controller/blink_leak_detector.cc +++ b/third_party/blink/renderer/controller/blink_leak_detector.cc
@@ -15,6 +15,7 @@ #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" #include "third_party/blink/renderer/core/page/page.h" +#include "third_party/blink/renderer/core/testing/internal_settings.h" #include "third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.h" #include "third_party/blink/renderer/core/workers/worker_thread.h" #include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h" @@ -65,6 +66,11 @@ for (auto resource_fetcher : ResourceFetcher::MainThreadFetchers()) resource_fetcher->PrepareForLeakDetection(); + // Internal settings are ScriptWrappable and thus may retain documents + // depending on whether the garbage collector(s) are able to find the settings + // object through the Page supplement. + InternalSettings::PrepareForLeakDetection(); + // Task queue may contain delayed object destruction tasks. // This method is called from navigation hook inside FrameLoader, // so previous document is still held by the loader until the next event loop.
diff --git a/third_party/blink/renderer/core/animation/animation_effect.cc b/third_party/blink/renderer/core/animation/animation_effect.cc index ffd0a173..4489299 100644 --- a/third_party/blink/renderer/core/animation/animation_effect.cc +++ b/third_party/blink/renderer/core/animation/animation_effect.cc
@@ -267,10 +267,17 @@ current_iteration, kLocalIterationDuration, iteration_time, timing_); } + const bool was_canceled = current_phase != calculated_.phase && + current_phase == AnimationEffect::kPhaseNone; + calculated_.phase = current_phase; + // If the animation was canceled, we need to fire the event condition before + // updating the timing so that the cancelation time can be determined. + if (was_canceled && event_delegate_) + event_delegate_->OnEventCondition(*this); + calculated_.current_iteration = current_iteration; calculated_.progress = progress; - calculated_.phase = current_phase; calculated_.is_in_effect = !IsNull(active_time); calculated_.is_in_play = GetPhase() == kPhaseActive; calculated_.is_current = GetPhase() == kPhaseBefore || IsInPlay();
diff --git a/third_party/blink/renderer/core/animation/css/css_animations.cc b/third_party/blink/renderer/core/animation/css/css_animations.cc index 16bc2d66..151cc0e7 100644 --- a/third_party/blink/renderer/core/animation/css/css_animations.cc +++ b/third_party/blink/renderer/core/animation/css/css_animations.cc
@@ -1234,6 +1234,19 @@ } } + if (GetDocument().HasListenerType(Document::kTransitionCancelListener)) { + if (current_phase == AnimationEffect::kPhaseNone) { + double cancel_iteration_time = + animation_node.Progress().has_value() + ? animation_node.Progress().value() * + animation_node.SpecifiedTiming() + .iteration_duration->InSecondsF() + : StartTimeFromDelay( + animation_node.SpecifiedTiming().start_delay); + EnqueueEvent(event_type_names::kTransitioncancel, cancel_iteration_time); + } + } + previous_phase_ = current_phase; }
diff --git a/third_party/blink/renderer/core/css/media_query_exp.cc b/third_party/blink/renderer/core/css/media_query_exp.cc index 02a0ce8..76b3e301 100644 --- a/third_party/blink/renderer/core/css/media_query_exp.cc +++ b/third_party/blink/renderer/core/css/media_query_exp.cc
@@ -79,11 +79,8 @@ } } - if (RuntimeEnabledFeatures::MediaQueryPrefersReducedMotionEnabled()) { - if (media_feature == kPrefersReducedMotionMediaFeature) { - return ident == CSSValueNoPreference || ident == CSSValueReduce; - } - } + if (media_feature == kPrefersReducedMotionMediaFeature) + return ident == CSSValueNoPreference || ident == CSSValueReduce; return false; } @@ -201,8 +198,7 @@ media_feature == kColorGamutMediaFeature || media_feature == kImmersiveMediaFeature || media_feature == kPrefersColorSchemeMediaFeature || - (RuntimeEnabledFeatures::MediaQueryPrefersReducedMotionEnabled() && - media_feature == kPrefersReducedMotionMediaFeature); + media_feature == kPrefersReducedMotionMediaFeature; } bool MediaQueryExp::IsViewportDependent() const {
diff --git a/third_party/blink/renderer/core/css/style_engine_test.cc b/third_party/blink/renderer/core/css/style_engine_test.cc index 5d41dae4..e0b3642 100644 --- a/third_party/blink/renderer/core/css/style_engine_test.cc +++ b/third_party/blink/renderer/core/css/style_engine_test.cc
@@ -1510,7 +1510,6 @@ } TEST_F(StyleEngineTest, MediaQueriesChangePrefersReducedMotion) { - RuntimeEnabledFeatures::SetMediaQueryPrefersReducedMotionEnabled(true); GetDocument().body()->SetInnerHTMLFromString(R"HTML( <style> body { color: red }
diff --git a/third_party/blink/renderer/core/dom/document.cc b/third_party/blink/renderer/core/dom/document.cc index e8565a7..52401bba 100644 --- a/third_party/blink/renderer/core/dom/document.cc +++ b/third_party/blink/renderer/core/dom/document.cc
@@ -5285,6 +5285,8 @@ // Need to re-evaluate time-to-effect-change for any running animations. View()->ScheduleAnimation(); } + } else if (event_type == event_type_names::kTransitioncancel) { + AddListenerType(kTransitionCancelListener); } else if (event_type == event_type_names::kTransitionrun) { AddListenerType(kTransitionRunListener); } else if (event_type == event_type_names::kTransitionstart) {
diff --git a/third_party/blink/renderer/core/dom/document.h b/third_party/blink/renderer/core/dom/document.h index c34d7ee1..2e0fbe1 100644 --- a/third_party/blink/renderer/core/dom/document.h +++ b/third_party/blink/renderer/core/dom/document.h
@@ -866,9 +866,10 @@ kTransitionRunListener = 1 << 9, kTransitionStartListener = 1 << 10, kTransitionEndListener = 1 << 11, - kScrollListener = 1 << 12, - kLoadListenerAtCapturePhaseOrAtStyleElement = 1 << 13 - // 2 bits remaining + kTransitionCancelListener = 1 << 12, + kScrollListener = 1 << 13, + kLoadListenerAtCapturePhaseOrAtStyleElement = 1 << 14 + // 1 bit remaining }; bool HasListenerType(ListenerType listener_type) const {
diff --git a/third_party/blink/renderer/core/events/event_type_names.json5 b/third_party/blink/renderer/core/events/event_type_names.json5 index 0ab3eb2..df904c6 100644 --- a/third_party/blink/renderer/core/events/event_type_names.json5 +++ b/third_party/blink/renderer/core/events/event_type_names.json5
@@ -279,6 +279,7 @@ "touchmove", "touchstart", "track", + "transitioncancel", "transitionend", "transitionrun", "transitionstart",
diff --git a/third_party/blink/renderer/core/exported/web_document.cc b/third_party/blink/renderer/core/exported/web_document.cc index 49a6ac70..754aa4d 100644 --- a/third_party/blink/renderer/core/exported/web_document.cc +++ b/third_party/blink/renderer/core/exported/web_document.cc
@@ -138,6 +138,10 @@ return ConstUnwrap<Document>()->SiteForCookies(); } +WebSecurityOrigin WebDocument::TopFrameOrigin() const { + return ConstUnwrap<Document>()->TopFrameOrigin(); +} + WebElement WebDocument::DocumentElement() const { return WebElement(ConstUnwrap<Document>()->documentElement()); }
diff --git a/third_party/blink/renderer/core/exported/web_settings_impl.cc b/third_party/blink/renderer/core/exported/web_settings_impl.cc index fa301dc..37b1913e 100644 --- a/third_party/blink/renderer/core/exported/web_settings_impl.cc +++ b/third_party/blink/renderer/core/exported/web_settings_impl.cc
@@ -754,6 +754,10 @@ settings_->SetLazyImageLoadingDistanceThresholdPx4G(distance_px); } +void WebSettingsImpl::SetForceDarkModeEnabled(bool enabled) { + settings_->SetForceDarkModeEnabled(enabled); +} + STATIC_ASSERT_ENUM(WebSettings::ImageAnimationPolicy::kAllowed, kImageAnimationPolicyAllowed); STATIC_ASSERT_ENUM(WebSettings::ImageAnimationPolicy::kAnimateOnce,
diff --git a/third_party/blink/renderer/core/exported/web_settings_impl.h b/third_party/blink/renderer/core/exported/web_settings_impl.h index 912aa33..783d5e3 100644 --- a/third_party/blink/renderer/core/exported/web_settings_impl.h +++ b/third_party/blink/renderer/core/exported/web_settings_impl.h
@@ -217,6 +217,8 @@ void SetLazyImageLoadingDistanceThresholdPx3G(int) override; void SetLazyImageLoadingDistanceThresholdPx4G(int) override; + void SetForceDarkModeEnabled(bool) override; + bool RenderVSyncNotificationEnabled() const { return render_v_sync_notification_enabled_; }
diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc index 2550bead..03b5aa0a 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.cc +++ b/third_party/blink/renderer/core/exported/web_view_impl.cc
@@ -1289,14 +1289,11 @@ // means the main frame's WebWidget remains valid while the main frame is // being detached (and in particular while its unload handlers run). { - // TODO(danakj): We should close the widget client too not just the view - // client. - // AsWidget().client = nullptr; + AsWidget().client = nullptr; if (does_composite_) GetPage()->WillCloseLayerTreeView(*layer_tree_view_, nullptr); - SetRootLayer(nullptr); animation_host_ = nullptr; mutator_dispatcher_ = nullptr; layer_tree_view_ = nullptr;
diff --git a/third_party/blink/renderer/core/frame/settings.cc b/third_party/blink/renderer/core/frame/settings.cc index 1c2bbcf..d8720f4 100644 --- a/third_party/blink/renderer/core/frame/settings.cc +++ b/third_party/blink/renderer/core/frame/settings.cc
@@ -106,4 +106,18 @@ return ScrollbarTheme::MockScrollbarsEnabled(); } +void Settings::SetForceDarkModeEnabled(bool enabled) { + if (force_dark_mode_ == enabled) + return; + force_dark_mode_ = enabled; + + if (force_dark_mode_) { + SetHighContrastMode(HighContrastMode::kInvertLightness); + SetHighContrastImagePolicy(HighContrastImagePolicy::kFilterSmart); + } else { + SetHighContrastMode(HighContrastMode::kOff); + } + Invalidate(SettingsDelegate::kStyleChange); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/frame/settings.h b/third_party/blink/renderer/core/frame/settings.h index 3df729d..e27e2b1 100644 --- a/third_party/blink/renderer/core/frame/settings.h +++ b/third_party/blink/renderer/core/frame/settings.h
@@ -81,6 +81,9 @@ return text_autosizing_window_size_override_; } + void SetForceDarkModeEnabled(bool enabled); + bool ForceDarkModeEnabled() const { return force_dark_mode_; } + SETTINGS_GETTERS_AND_SETTERS // FIXME: This does not belong here. @@ -100,6 +103,7 @@ IntSize text_autosizing_window_size_override_; bool text_autosizing_enabled_ : 1; bool bypass_csp_ = false; + bool force_dark_mode_ = false; SETTINGS_MEMBER_VARIABLES
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc index 517e357..03e4a1dd 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc
@@ -309,7 +309,7 @@ // The page rect gets scaled and translated, so specify the entire // print content area here as the recording rect. FloatRect bounds(0, 0, printed_page_height_, printed_page_width_); - PaintRecordBuilder builder(&canvas->getMetaData()); + PaintRecordBuilder builder(canvas->GetPrintingMetafile()); builder.Context().SetPrinting(true); builder.Context().BeginRecording(bounds); float scale = SpoolPage(builder.Context(), page_number); @@ -337,7 +337,7 @@ int total_height = num_pages * (page_size_in_pixels.Height() + 1) - 1; FloatRect all_pages_rect(0, 0, page_width, total_height); - PaintRecordBuilder builder(&canvas->getMetaData()); + PaintRecordBuilder builder(canvas->GetPrintingMetafile()); GraphicsContext& context = builder.Context(); context.SetPrinting(true); context.BeginRecording(all_pages_rect); @@ -403,7 +403,8 @@ PropertyTreeState property_tree_state = frame_view->GetLayoutView()->FirstFragment().LocalBorderBoxProperties(); - PaintRecordBuilder builder(&context.Canvas()->getMetaData(), &context); + PaintRecordBuilder builder(context.Canvas()->GetPrintingMetafile(), + &context); frame_view->PaintContentsOutsideOfLifecycle( builder.Context(), kGlobalPaintNormalPhase, CullRect(page_rect)); @@ -487,7 +488,7 @@ // NativeTheme doesn't play well with scaling. Scaling is done browser side // instead. Returns the scale to be applied. float SpoolPage(GraphicsContext& context, int page_number) override { - PaintRecordBuilder builder(&context.Canvas()->getMetaData()); + PaintRecordBuilder builder(context.Canvas()->GetPrintingMetafile()); plugin_->PrintPage(page_number, builder.Context()); context.DrawRecord(builder.EndRecording());
diff --git a/third_party/blink/renderer/core/input/mouse_event_manager.cc b/third_party/blink/renderer/core/input/mouse_event_manager.cc index 17c58aca..e1ca5a0 100644 --- a/third_party/blink/renderer/core/input/mouse_event_manager.cc +++ b/third_party/blink/renderer/core/input/mouse_event_manager.cc
@@ -490,7 +490,7 @@ frame_->GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); Element* element = element_under_mouse_; - for (; element; element = element->ParentOrShadowHostElement()) { + for (; element; element = FlatTreeTraversal::ParentElement(*element)) { if (element->IsFocusable() && element->IsFocusedElementInDocument()) return WebInputEventResult::kNotHandled; if (element->IsMouseFocusable())
diff --git a/third_party/blink/renderer/core/layout/jank_tracker.cc b/third_party/blink/renderer/core/layout/jank_tracker.cc index 0a73af9..e6f8120 100644 --- a/third_party/blink/renderer/core/layout/jank_tracker.cc +++ b/third_party/blink/renderer/core/layout/jank_tracker.cc
@@ -235,7 +235,8 @@ WindowPerformance* performance = DOMWindowPerformance::performance(*frame.DomWindow()); if (performance && - performance->HasObserverFor(PerformanceEntry::kLayoutJank)) { + (performance->HasObserverFor(PerformanceEntry::kLayoutJank) || + performance->ShouldBufferEntries())) { performance->AddLayoutJankFraction(jank_fraction); } }
diff --git a/third_party/blink/renderer/core/loader/base_fetch_context.h b/third_party/blink/renderer/core/loader/base_fetch_context.h index 39b9cd6..f4d562c 100644 --- a/third_party/blink/renderer/core/loader/base_fetch_context.h +++ b/third_party/blink/renderer/core/loader/base_fetch_context.h
@@ -47,6 +47,10 @@ void Trace(blink::Visitor*) override; virtual KURL GetSiteForCookies() const = 0; + + // Returns the origin of the top frame in the document. + virtual scoped_refptr<const SecurityOrigin> GetTopFrameOrigin() const = 0; + virtual SubresourceFilter* GetSubresourceFilter() const = 0; virtual PreviewsResourceLoadingHints* GetPreviewsResourceLoadingHints() const = 0;
diff --git a/third_party/blink/renderer/core/loader/base_fetch_context_test.cc b/third_party/blink/renderer/core/loader/base_fetch_context_test.cc index 0d01242..4558be5 100644 --- a/third_party/blink/renderer/core/loader/base_fetch_context_test.cc +++ b/third_party/blink/renderer/core/loader/base_fetch_context_test.cc
@@ -51,6 +51,10 @@ // BaseFetchContext overrides: KURL GetSiteForCookies() const override { return KURL(); } + scoped_refptr<const blink::SecurityOrigin> GetTopFrameOrigin() + const override { + return SecurityOrigin::CreateUniqueOpaque(); + } bool AllowScriptFromSource(const KURL&) const override { return false; } SubresourceFilter* GetSubresourceFilter() const override { return nullptr; } PreviewsResourceLoadingHints* GetPreviewsResourceLoadingHints()
diff --git a/third_party/blink/renderer/core/loader/document_loader.cc b/third_party/blink/renderer/core/loader/document_loader.cc index 4dda8c2..255d21c5 100644 --- a/third_party/blink/renderer/core/loader/document_loader.cc +++ b/third_party/blink/renderer/core/loader/document_loader.cc
@@ -1170,14 +1170,21 @@ return; } + bool use_isolated_code_cache = + RuntimeEnabledFeatures::CacheInlineScriptCodeEnabled() && + ShouldUseIsolatedCodeCache(mojom::RequestContextType::HYPERLINK, + response_); + + // The |cached_metadata_handler_| is created, even when + // |use_isolated_code_cache| is false to support the parts that don't + // go throught the site-isolated-code-cache. auto cached_metadata_sender = CachedMetadataSender::Create( response_, blink::mojom::CodeCacheType::kJavascript, requestor_origin_); cached_metadata_handler_ = MakeGarbageCollected<SourceKeyedCachedMetadataHandler>( WTF::TextEncoding(), std::move(cached_metadata_sender)); - body_loader_->StartLoadingBody( - this, ShouldUseIsolatedCodeCache(mojom::RequestContextType::HYPERLINK, - response_)); + + body_loader_->StartLoadingBody(this, use_isolated_code_cache); } void DocumentLoader::DidInstallNewDocument(Document* document) {
diff --git a/third_party/blink/renderer/core/loader/frame_fetch_context.cc b/third_party/blink/renderer/core/loader/frame_fetch_context.cc index 8ff2581..4bbc0b8 100644 --- a/third_party/blink/renderer/core/loader/frame_fetch_context.cc +++ b/third_party/blink/renderer/core/loader/frame_fetch_context.cc
@@ -275,6 +275,17 @@ return document->SiteForCookies(); } +scoped_refptr<const SecurityOrigin> FrameFetchContext::GetTopFrameOrigin() + const { + if (GetResourceFetcherProperties().IsDetached()) + return frozen_state_->top_frame_origin; + + Document* document = frame_or_imported_document_->GetDocument(); + if (!document) + document = GetFrame()->GetDocument(); + return document->TopFrameOrigin(); +} + SubresourceFilter* FrameFetchContext::GetSubresourceFilter() const { if (GetResourceFetcherProperties().IsDetached()) return nullptr; @@ -873,17 +884,6 @@ ->IsSameSchemeHostPort(SecurityOrigin::Create(url).get()); } -scoped_refptr<const SecurityOrigin> FrameFetchContext::GetTopFrameOrigin() - const { - if (GetResourceFetcherProperties().IsDetached()) - return frozen_state_->top_frame_origin; - - Document* document = frame_or_imported_document_->GetDocument(); - if (!document) - document = GetFrame()->GetDocument(); - return document->TopFrameOrigin(); -} - bool FrameFetchContext::ShouldBlockRequestByInspector(const KURL& url) const { if (GetResourceFetcherProperties().IsDetached()) return false;
diff --git a/third_party/blink/renderer/core/loader/frame_fetch_context.h b/third_party/blink/renderer/core/loader/frame_fetch_context.h index 56c3e956..17f6896db 100644 --- a/third_party/blink/renderer/core/loader/frame_fetch_context.h +++ b/third_party/blink/renderer/core/loader/frame_fetch_context.h
@@ -168,6 +168,7 @@ // BaseFetchContext overrides: KURL GetSiteForCookies() const override; + scoped_refptr<const SecurityOrigin> GetTopFrameOrigin() const override; SubresourceFilter* GetSubresourceFilter() const override; PreviewsResourceLoadingHints* GetPreviewsResourceLoadingHints() const override; @@ -220,9 +221,6 @@ // frame's main resource. bool IsFirstPartyOrigin(const KURL& url) const; - // Returns the origin of the top frame in the document. - scoped_refptr<const SecurityOrigin> GetTopFrameOrigin() const; - CoreProbeSink* Probe() const; Member<const FrameOrImportedDocument> frame_or_imported_document_;
diff --git a/third_party/blink/renderer/core/loader/frame_fetch_context_test.cc b/third_party/blink/renderer/core/loader/frame_fetch_context_test.cc index 7ec17b14..5dc01e34 100644 --- a/third_party/blink/renderer/core/loader/frame_fetch_context_test.cc +++ b/third_party/blink/renderer/core/loader/frame_fetch_context_test.cc
@@ -176,6 +176,10 @@ GetFetchContext()->SetFirstPartyCookie(request); } + scoped_refptr<const SecurityOrigin> GetTopFrameOrigin() { + return GetFetchContext()->GetTopFrameOrigin(); + } + std::unique_ptr<DummyPageHolder> dummy_page_holder; // We don't use the DocumentLoader directly in any tests, but need to keep it // around as long as the ResourceFetcher and Document live due to indirect @@ -1336,6 +1340,32 @@ EXPECT_EQ(document_url.GetString(), request.SiteForCookies().GetString()); } +TEST_F(FrameFetchContextTest, TopFrameOrigin) { + const KURL url("https://www.example.com/hoge/fuga"); + ResourceRequest request(url); + const KURL document_url("https://www2.example.com/foo/bar"); + scoped_refptr<SecurityOrigin> origin = SecurityOrigin::Create(document_url); + + document->SetSecurityOrigin(origin); + document->SetURL(document_url); + + EXPECT_EQ(origin, GetTopFrameOrigin()); +} + +TEST_F(FrameFetchContextTest, TopFrameOriginDetached) { + const KURL url("https://www.example.com/hoge/fuga"); + ResourceRequest request(url); + const KURL document_url("https://www2.example.com/foo/bar"); + scoped_refptr<SecurityOrigin> origin = SecurityOrigin::Create(document_url); + + document->SetSecurityOrigin(origin); + document->SetURL(document_url); + + dummy_page_holder = nullptr; + + EXPECT_EQ(origin, GetTopFrameOrigin()); +} + // Tests if "Intervention" header is added for frame with Client Lo-Fi enabled. TEST_F(FrameFetchContextMockedLocalFrameClientTest, ClientLoFiInterventionHeader) {
diff --git a/third_party/blink/renderer/core/loader/worker_fetch_context.cc b/third_party/blink/renderer/core/loader/worker_fetch_context.cc index a3744770..2e7f9c08 100644 --- a/third_party/blink/renderer/core/loader/worker_fetch_context.cc +++ b/third_party/blink/renderer/core/loader/worker_fetch_context.cc
@@ -47,6 +47,22 @@ return web_context_->SiteForCookies(); } +scoped_refptr<const SecurityOrigin> WorkerFetchContext::GetTopFrameOrigin() + const { + base::Optional<WebSecurityOrigin> top_frame_origin = + web_context_->TopFrameOrigin(); + + // TODO(crbug.com/918868) The top frame origin of shared and service + // workers is unknown. + if (!top_frame_origin) { + DCHECK(global_scope_->IsSharedWorkerGlobalScope() || + global_scope_->IsServiceWorkerGlobalScope()); + return scoped_refptr<const SecurityOrigin>(); + } + + return *top_frame_origin; +} + SubresourceFilter* WorkerFetchContext::GetSubresourceFilter() const { return subresource_filter_.Get(); } @@ -273,6 +289,8 @@ ResourceRequest& out_request) { FrameLoader::UpgradeInsecureRequest(out_request, global_scope_); SetFirstPartyCookie(out_request); + if (!out_request.TopFrameOrigin()) + out_request.SetTopFrameOrigin(GetTopFrameOrigin()); } void WorkerFetchContext::SetFirstPartyCookie(ResourceRequest& out_request) {
diff --git a/third_party/blink/renderer/core/loader/worker_fetch_context.h b/third_party/blink/renderer/core/loader/worker_fetch_context.h index 7402475b..67562d0 100644 --- a/third_party/blink/renderer/core/loader/worker_fetch_context.h +++ b/third_party/blink/renderer/core/loader/worker_fetch_context.h
@@ -35,6 +35,8 @@ // BaseFetchContext implementation: KURL GetSiteForCookies() const override; + scoped_refptr<const SecurityOrigin> GetTopFrameOrigin() const override; + SubresourceFilter* GetSubresourceFilter() const override; PreviewsResourceLoadingHints* GetPreviewsResourceLoadingHints() const override;
diff --git a/third_party/blink/renderer/core/page/drag_controller.cc b/third_party/blink/renderer/core/page/drag_controller.cc index 3b0b20a..2dfcd7d 100644 --- a/third_party/blink/renderer/core/page/drag_controller.cc +++ b/third_party/blink/renderer/core/page/drag_controller.cc
@@ -215,6 +215,7 @@ void DragController::DragEnded() { drag_initiator_ = nullptr; did_initiate_drag_ = false; + drag_state_ = nullptr; page_->GetDragCaret().Clear(); }
diff --git a/third_party/blink/renderer/core/paint/nine_piece_image_painter.cc b/third_party/blink/renderer/core/paint/nine_piece_image_painter.cc index c669091..0e2acf21 100644 --- a/third_party/blink/renderer/core/paint/nine_piece_image_painter.cc +++ b/third_party/blink/renderer/core/paint/nine_piece_image_painter.cc
@@ -17,20 +17,19 @@ namespace { -std::tuple<bool, float> CalculateSpaceNeeded(const float destination, - const float source) { +base::Optional<float> CalculateSpaceNeeded(const float destination, + const float source) { DCHECK_GT(source, 0); DCHECK_GT(destination, 0); float repeat_tiles_count = floorf(destination / source); if (!repeat_tiles_count) - return std::make_tuple(false, -1); + return base::nullopt; float space = destination; space -= source * repeat_tiles_count; space /= repeat_tiles_count + 1.0; - - return std::make_tuple(true, space); + return space; } struct TileParameters { @@ -39,50 +38,41 @@ float spacing; }; -bool ComputeTileParameters(ENinePieceImageRule tile_rule, - float dst_pos, - float dst_extent, - float src_pos, - float src_extent, - float provided_tile_scale_factor, - TileParameters& tile) { - tile.scale_factor = provided_tile_scale_factor; +base::Optional<TileParameters> ComputeTileParameters( + ENinePieceImageRule tile_rule, + float dst_pos, + float dst_extent, + float src_pos, + float src_extent, + float in_scale_factor) { switch (tile_rule) { case kRoundImageRule: { float repetitions = - std::max(1.0f, roundf(dst_extent / (src_extent * tile.scale_factor))); - tile.scale_factor = dst_extent / (src_extent * repetitions); - tile.phase = src_pos * tile.scale_factor; - tile.spacing = 0; - break; + std::max(1.0f, roundf(dst_extent / (src_extent * in_scale_factor))); + float scale_factor = dst_extent / (src_extent * repetitions); + return TileParameters{scale_factor, src_pos * scale_factor, 0}; } case kRepeatImageRule: { - float scaled_tile_extent = src_extent * tile.scale_factor; + float scaled_tile_extent = src_extent * in_scale_factor; // We want to construct the phase such that the pattern is centered (when // stretch is not set for a particular rule). - tile.phase = src_pos * tile.scale_factor; - tile.phase -= (dst_extent - scaled_tile_extent) / 2; - tile.spacing = 0; - break; + float phase = src_pos * in_scale_factor; + phase -= (dst_extent - scaled_tile_extent) / 2; + return TileParameters{in_scale_factor, phase, 0}; } case kSpaceImageRule: { - std::tuple<bool, float> space = + base::Optional<float> spacing = CalculateSpaceNeeded(dst_extent, src_extent); - if (!std::get<0>(space)) - return false; - tile.spacing = std::get<1>(space); - tile.scale_factor = 1; - tile.phase = src_pos - tile.spacing; - break; + if (!spacing) + return base::nullopt; + return TileParameters{1, src_pos - *spacing, *spacing}; } case kStretchImageRule: - tile.phase = src_pos * tile.scale_factor; - tile.spacing = 0; - break; + return TileParameters{in_scale_factor, src_pos * in_scale_factor, 0}; default: NOTREACHED(); } - return true; + return base::nullopt; } void PaintPieces(GraphicsContext& context, @@ -119,23 +109,21 @@ &draw_info.source); } else { // TODO(cavalcantii): see crbug.com/662513. - TileParameters h_tile, v_tile; - if (!ComputeTileParameters( - draw_info.tile_rule.horizontal, draw_info.destination.X(), - draw_info.destination.Width(), draw_info.source.X(), - draw_info.source.Width(), draw_info.tile_scale.Width(), h_tile)) - continue; - if (!ComputeTileParameters( - draw_info.tile_rule.vertical, draw_info.destination.Y(), - draw_info.destination.Height(), draw_info.source.Y(), - draw_info.source.Height(), draw_info.tile_scale.Height(), - v_tile)) + base::Optional<TileParameters> h_tile = ComputeTileParameters( + draw_info.tile_rule.horizontal, draw_info.destination.X(), + draw_info.destination.Width(), draw_info.source.X(), + draw_info.source.Width(), draw_info.tile_scale.Width()); + base::Optional<TileParameters> v_tile = ComputeTileParameters( + draw_info.tile_rule.vertical, draw_info.destination.Y(), + draw_info.destination.Height(), draw_info.source.Y(), + draw_info.source.Height(), draw_info.tile_scale.Height()); + if (!h_tile || !v_tile) continue; - FloatSize tile_scale_factor(h_tile.scale_factor, v_tile.scale_factor); - FloatPoint tile_phase(draw_info.destination.X() - h_tile.phase, - draw_info.destination.Y() - v_tile.phase); - FloatSize tile_spacing(h_tile.spacing, v_tile.spacing); + FloatSize tile_scale_factor(h_tile->scale_factor, v_tile->scale_factor); + FloatPoint tile_phase(draw_info.destination.X() - h_tile->phase, + draw_info.destination.Y() - v_tile->phase); + FloatSize tile_spacing(h_tile->spacing, v_tile->spacing); // TODO(cavalcantii): see crbug.com/662507. base::Optional<ScopedInterpolationQuality> interpolation_quality_scope;
diff --git a/third_party/blink/renderer/core/script/classic_pending_script.cc b/third_party/blink/renderer/core/script/classic_pending_script.cc index 8349537..4ead543f 100644 --- a/third_party/blink/renderer/core/script/classic_pending_script.cc +++ b/third_party/blink/renderer/core/script/classic_pending_script.cc
@@ -11,6 +11,7 @@ #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/scriptable_document_parser.h" #include "third_party/blink/renderer/core/frame/local_frame.h" +#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h" #include "third_party/blink/renderer/core/loader/document_loader.h" #include "third_party/blink/renderer/core/loader/resource/script_resource.h" #include "third_party/blink/renderer/core/loader/subresource_integrity_helper.h" @@ -18,6 +19,7 @@ #include "third_party/blink/renderer/core/script/script_loader.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/histogram.h" +#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h" #include "third_party/blink/renderer/platform/loader/allowed_by_nosniff.h" #include "third_party/blink/renderer/platform/loader/fetch/cached_metadata.h" #include "third_party/blink/renderer/platform/loader/fetch/memory_cache.h" @@ -263,6 +265,13 @@ options_, cross_origin); } + TRACE_EVENT_WITH_FLOW1( + TRACE_DISABLED_BY_DEFAULT("v8.compile"), + "ClassicPendingScript::NotifyFinished", this, TRACE_EVENT_FLAG_FLOW_OUT, + "data", + inspector_parse_script_event::Data(GetResource()->Identifier(), + GetResource()->Url().GetString())); + bool error_occurred = GetResource()->ErrorOccurred() || integrity_failure_; AdvanceReadyState(error_occurred ? kErrorOccurred : kReady); } @@ -360,6 +369,11 @@ RecordStreamingHistogram(GetSchedulingType(), streamer_ready, not_streamed_reason); + TRACE_EVENT_WITH_FLOW1(TRACE_DISABLED_BY_DEFAULT("v8.compile"), + "ClassicPendingScript::GetSource", this, + TRACE_EVENT_FLAG_FLOW_IN, "not_streamed_reason", + not_streamed_reason); + ScriptSourceCode source_code(streamer_ready ? streamer : nullptr, resource, not_streamed_reason); // The base URL for external classic script is
diff --git a/third_party/blink/renderer/core/testing/internal_settings.cc b/third_party/blink/renderer/core/testing/internal_settings.cc index d0846c2..2606b835 100644 --- a/third_party/blink/renderer/core/testing/internal_settings.cc +++ b/third_party/blink/renderer/core/testing/internal_settings.cc
@@ -549,4 +549,12 @@ GetSettings()->SetAutoplayPolicy(policy); } +void InternalSettings::PrepareForLeakDetection() { + // Prepares for leak detection by removing all InternalSetting objects from + // Pages. + for (Page* page : Page::OrdinaryPages()) { + page->RemoveSupplement<InternalSettings>(); + } +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/testing/internal_settings.h b/third_party/blink/renderer/core/testing/internal_settings.h index 84a6b178..da670b1 100644 --- a/third_party/blink/renderer/core/testing/internal_settings.h +++ b/third_party/blink/renderer/core/testing/internal_settings.h
@@ -51,6 +51,8 @@ public: static const char kSupplementName[]; + static void PrepareForLeakDetection(); + class Backup { DISALLOW_NEW();
diff --git a/third_party/blink/renderer/core/timing/performance.cc b/third_party/blink/renderer/core/timing/performance.cc index bf0de7d..7fdf28fb 100644 --- a/third_party/blink/renderer/core/timing/performance.cc +++ b/third_party/blink/renderer/core/timing/performance.cc
@@ -44,6 +44,7 @@ #include "third_party/blink/renderer/core/loader/document_loader.h" #include "third_party/blink/renderer/core/timing/performance_element_timing.h" #include "third_party/blink/renderer/core/timing/performance_event_timing.h" +#include "third_party/blink/renderer/core/timing/performance_layout_jank.h" #include "third_party/blink/renderer/core/timing/performance_long_task_timing.h" #include "third_party/blink/renderer/core/timing/performance_mark.h" #include "third_party/blink/renderer/core/timing/performance_mark_options.h" @@ -157,9 +158,10 @@ using PerformanceObserverVector = HeapVector<Member<PerformanceObserver>>; -static const size_t kDefaultResourceTimingBufferSize = 250; +constexpr size_t kDefaultResourceTimingBufferSize = 250; constexpr size_t kDefaultEventTimingBufferSize = 150; constexpr size_t kDefaultElementTimingBufferSize = 150; +constexpr size_t kDefaultLayoutJankBufferSize = 150; Performance::Performance( TimeTicks time_origin, @@ -209,6 +211,7 @@ entries.AppendVector(resource_timing_buffer_); entries.AppendVector(event_timing_buffer_); entries.AppendVector(element_timing_buffer_); + entries.AppendVector(layout_jank_buffer_); if (first_input_timing_) entries.push_back(first_input_timing_); if (!navigation_timing_) @@ -291,9 +294,11 @@ break; case PerformanceEntry::kTaskAttribution: break; - // TODO(npm): decide which layout jank entries are accessible via the - // performance buffer. case PerformanceEntry::kLayoutJank: + UseCounter::Count(GetExecutionContext(), + WebFeature::kLayoutJankExplicitlyRequested); + for (const auto& layout_jank : layout_jank_buffer_) + entries.push_back(layout_jank); break; case PerformanceEntry::kInvalid: break; @@ -321,6 +326,16 @@ } } + if (entry_type.IsNull() || type == PerformanceEntry::kLayoutJank) { + for (const auto& layout_jank : layout_jank_buffer_) { + if (layout_jank->name() == name) + entries.push_back(layout_jank); + } + } + if (type == PerformanceEntry::kLayoutJank) { + UseCounter::Count(GetExecutionContext(), + WebFeature::kLayoutJankExplicitlyRequested); + } if (entry_type.IsNull() || type == PerformanceEntry::kElement) { for (const auto& element : element_timing_buffer_) { if (element->name() == name) @@ -609,6 +624,11 @@ DispatchEvent(*Event::Create(event_type_names::kEventtimingbufferfull)); } +void Performance::AddLayoutJankBuffer(PerformanceLayoutJank& entry) { + if (layout_jank_buffer_.size() < kDefaultLayoutJankBufferSize) + layout_jank_buffer_.push_back(&entry); +} + unsigned Performance::ElementTimingBufferSize() const { return element_timing_buffer_.size(); } @@ -982,6 +1002,7 @@ visitor->Trace(resource_timing_secondary_buffer_); visitor->Trace(element_timing_buffer_); visitor->Trace(event_timing_buffer_); + visitor->Trace(layout_jank_buffer_); visitor->Trace(navigation_timing_); visitor->Trace(user_timing_); visitor->Trace(first_paint_timing_);
diff --git a/third_party/blink/renderer/core/timing/performance.h b/third_party/blink/renderer/core/timing/performance.h index 853ba64..b41d030 100644 --- a/third_party/blink/renderer/core/timing/performance.h +++ b/third_party/blink/renderer/core/timing/performance.h
@@ -58,6 +58,7 @@ class MemoryInfo; class PerformanceElementTiming; class PerformanceEventTiming; +class PerformanceLayoutJank; class PerformanceMark; class PerformanceMeasure; class PerformanceNavigation; @@ -172,6 +173,8 @@ DEFINE_ATTRIBUTE_EVENT_LISTENER(eventtimingbufferfull, kEventtimingbufferfull); + void AddLayoutJankBuffer(PerformanceLayoutJank&); + PerformanceMark* mark(ScriptState*, const AtomicString& mark_name, ExceptionState&); @@ -312,6 +315,7 @@ unsigned event_timing_buffer_max_size_; PerformanceEntryVector element_timing_buffer_; unsigned element_timing_buffer_max_size_; + PerformanceEntryVector layout_jank_buffer_; Member<PerformanceEntry> navigation_timing_; TraceWrapperMember<UserTiming> user_timing_; Member<PerformanceEntry> first_paint_timing_;
diff --git a/third_party/blink/renderer/core/timing/performance_layout_jank.idl b/third_party/blink/renderer/core/timing/performance_layout_jank.idl index 0f155690..a50bfc4 100644 --- a/third_party/blink/renderer/core/timing/performance_layout_jank.idl +++ b/third_party/blink/renderer/core/timing/performance_layout_jank.idl
@@ -3,7 +3,7 @@ // found in the LICENSE file. // https://gist.github.com/skobes/2f296da1b0a88cc785a4bf10a42bca07 -[OriginTrialEnabled=LayoutJankAPI] +[Exposed=Window, OriginTrialEnabled=LayoutJankAPI] interface PerformanceLayoutJank : PerformanceEntry { readonly attribute double fraction;
diff --git a/third_party/blink/renderer/core/timing/performance_observer.cc b/third_party/blink/renderer/core/timing/performance_observer.cc index 546f3be..5850cc8 100644 --- a/third_party/blink/renderer/core/timing/performance_observer.cc +++ b/third_party/blink/renderer/core/timing/performance_observer.cc
@@ -156,6 +156,10 @@ } filter_options_ |= entry_type; } + if (filter_options_ & PerformanceEntry::kLayoutJank) { + UseCounter::Count(GetExecutionContext(), + WebFeature::kLayoutJankExplicitlyRequested); + } if (is_registered_) performance_->UpdatePerformanceObserverFilterOptions(); else
diff --git a/third_party/blink/renderer/core/timing/window_performance.cc b/third_party/blink/renderer/core/timing/window_performance.cc index 7cf9c4bc..89924e9 100644 --- a/third_party/blink/renderer/core/timing/window_performance.cc +++ b/third_party/blink/renderer/core/timing/window_performance.cc
@@ -446,8 +446,11 @@ void WindowPerformance::AddLayoutJankFraction(double jank_fraction) { DCHECK(origin_trials::LayoutJankAPIEnabled(GetExecutionContext())); - PerformanceEntry* entry = PerformanceLayoutJank::Create(jank_fraction); - NotifyObserversOfEntry(*entry); + PerformanceLayoutJank* entry = PerformanceLayoutJank::Create(jank_fraction); + if (HasObserverFor(PerformanceEntry::kLayoutJank)) + NotifyObserversOfEntry(*entry); + if (ShouldBufferEntries()) + AddLayoutJankBuffer(*entry); } } // namespace blink
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/TimelineUIUtils.js b/third_party/blink/renderer/devtools/front_end/timeline/TimelineUIUtils.js index 3993199..1bba2d8 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/TimelineUIUtils.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/TimelineUIUtils.js
@@ -1016,6 +1016,7 @@ contentHelper.appendTextRow(ls`Type`, eventData['type']); break; + case recordTypes.MarkFirstPaint: case recordTypes.MarkFCP: case recordTypes.MarkFMP: case recordTypes.MarkLoad: @@ -1826,15 +1827,15 @@ tall = true; break; case recordTypes.MarkFirstPaint: - color = 'hsl(180, 45%, 79%)'; + color = '#228847'; tall = true; break; case recordTypes.MarkFCP: - color = '#208043'; + color = '#1A6937'; tall = true; break; case recordTypes.MarkFMP: - color = '#14522B'; + color = '#134A26'; tall = true; break; case recordTypes.TimeStamp:
diff --git a/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModel.js b/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModel.js index 4d61d98..2b440bc3c 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModel.js +++ b/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModel.js
@@ -1219,7 +1219,7 @@ CommitLoad: 'CommitLoad', MarkLoad: 'MarkLoad', MarkDOMContent: 'MarkDOMContent', - MarkFirstPaint: 'MarkFirstPaint', + MarkFirstPaint: 'firstPaint', MarkFCP: 'firstContentfulPaint', MarkFMP: 'firstMeaningfulPaint',
diff --git a/third_party/blink/renderer/modules/BUILD.gn b/third_party/blink/renderer/modules/BUILD.gn index e2d05b47..c8af8ce 100644 --- a/third_party/blink/renderer/modules/BUILD.gn +++ b/third_party/blink/renderer/modules/BUILD.gn
@@ -249,6 +249,7 @@ "accessibility/testing/accessibility_test.cc", "accessibility/testing/accessibility_test.h", "animationworklet/animation_worklet_global_scope_test.cc", + "animationworklet/animation_worklet_proxy_client_test.cc", "animationworklet/worklet_animation_test.cc", "background_fetch/background_fetch_icon_loader_test.cc", "background_fetch/background_fetch_manager_test.cc",
diff --git a/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client.cc b/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client.cc index bcda509..d13c5ec 100644 --- a/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client.cc +++ b/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client.cc
@@ -45,10 +45,17 @@ next_global_scope_switch_countdown_(0), current_stateless_global_scope_index_(0) { DCHECK(IsMainThread()); - mutator_items_.emplace_back(std::move(compositor_mutator_dispatcher), - std::move(compositor_mutator_runner)); - mutator_items_.emplace_back(std::move(main_thread_mutator_dispatcher), - std::move(main_thread_mutator_runner)); + + // The dispatchers are weak pointers that may come from another thread. It's + // illegal to check them here. Instead, the task runners are checked. + if (compositor_mutator_runner) { + mutator_items_.emplace_back(std::move(compositor_mutator_dispatcher), + std::move(compositor_mutator_runner)); + } + if (main_thread_mutator_runner) { + mutator_items_.emplace_back(std::move(main_thread_mutator_dispatcher), + std::move(main_thread_mutator_runner)); + } } void AnimationWorkletProxyClient::Trace(blink::Visitor* visitor) { @@ -68,7 +75,6 @@ // registered names are synced before resolving the load promise therefore it // is safe to use a post task here. for (auto& mutator_item : mutator_items_) { - DCHECK(mutator_item.mutator_runner); PostCrossThreadTask( *mutator_item.mutator_runner, FROM_HERE, CrossThreadBind( @@ -101,7 +107,6 @@ state_ = RunState::kWorking; for (auto& mutator_item : mutator_items_) { - DCHECK(mutator_item.mutator_runner); PostCrossThreadTask( *mutator_item.mutator_runner, FROM_HERE, CrossThreadBind(&AnimationWorkletMutatorDispatcherImpl:: @@ -116,7 +121,6 @@ // At worklet scope termination break the reference to the clients if it is // still alive. for (auto& mutator_item : mutator_items_) { - DCHECK(mutator_item.mutator_runner); PostCrossThreadTask( *mutator_item.mutator_runner, FROM_HERE, CrossThreadBind(&AnimationWorkletMutatorDispatcherImpl::
diff --git a/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client.h b/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client.h index 7f91dc3..f30b9507 100644 --- a/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client.h +++ b/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client.h
@@ -63,6 +63,8 @@ private: FRIEND_TEST_ALL_PREFIXES(AnimationWorkletGlobalScopeTest, SelectGlobalScope); + FRIEND_TEST_ALL_PREFIXES(AnimationWorkletProxyClientTest, + AnimationWorkletProxyClientConstruction); // Separate global scope selectors are used instead of overriding // Worklet::SelectGlobalScope since two different selection mechanisms are
diff --git a/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client_test.cc b/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client_test.cc new file mode 100644 index 0000000..e29ead3 --- /dev/null +++ b/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client_test.cc
@@ -0,0 +1,46 @@ +// 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. + +#include "third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client.h" + +#include <memory> + +#include "base/memory/weak_ptr.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h" +#include "third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.h" + +namespace blink { + +class AnimationWorkletProxyClientTest : public RenderingTest { + public: + AnimationWorkletProxyClientTest() + : RenderingTest(SingleChildLocalFrameClient::Create()) {} +}; + +TEST_F(AnimationWorkletProxyClientTest, + AnimationWorkletProxyClientConstruction) { + AnimationWorkletProxyClient* proxy_client = + MakeGarbageCollected<AnimationWorkletProxyClient>(1, nullptr, nullptr, + nullptr, nullptr); + EXPECT_TRUE(proxy_client->mutator_items_.IsEmpty()); + + auto mutator = std::make_unique<AnimationWorkletMutatorDispatcherImpl>(true); + scoped_refptr<base::SingleThreadTaskRunner> mutator_task_runner = + mutator->GetTaskRunner(); + base::WeakPtrFactory<AnimationWorkletMutatorDispatcherImpl> + mutator_dispatcher_factory(mutator.get()); + + proxy_client = MakeGarbageCollected<AnimationWorkletProxyClient>( + 1, nullptr, nullptr, mutator_dispatcher_factory.GetWeakPtr(), + mutator_task_runner); + EXPECT_EQ(proxy_client->mutator_items_.size(), 1u); + + proxy_client = MakeGarbageCollected<AnimationWorkletProxyClient>( + 1, mutator_dispatcher_factory.GetWeakPtr(), mutator_task_runner, + mutator_dispatcher_factory.GetWeakPtr(), mutator_task_runner); + EXPECT_EQ(proxy_client->mutator_items_.size(), 2u); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.cc b/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.cc index 1e85daf..a37cf2c 100644 --- a/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.cc +++ b/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.cc
@@ -49,12 +49,12 @@ const String& developer_id, const String& unique_id, mojom::blink::FetchAPIRequestPtr request_to_match, - mojom::blink::QueryParamsPtr cache_query_params, + mojom::blink::CacheQueryOptionsPtr cache_query_options, bool match_all, mojom::blink::BackgroundFetchService::MatchRequestsCallback callback) { GetService()->MatchRequests( GetSupplementable()->RegistrationId(), developer_id, unique_id, - std::move(request_to_match), std::move(cache_query_params), match_all, + std::move(request_to_match), std::move(cache_query_options), match_all, std::move(callback)); }
diff --git a/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h b/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h index 12212a8..e6d038c6 100644 --- a/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h +++ b/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h
@@ -63,14 +63,14 @@ // Matches completed requests for the fetch associated with the |developer_id| // and |unique_id| and returns the {request, response} pairs based on the rest // of the arguments. If |filter_by_request| is true, only response(s) for - // |request_to_match| are returned. |cache_query_params|s are options for the + // |request_to_match| are returned. |cache_query_options|s are options for the // query to the cache storage. |match_all|, when true, returns all responses // from the result set, and when false, returns only the first one. void MatchRequests( const String& developer_id, const String& unique_id, mojom::blink::FetchAPIRequestPtr request_to_match, - mojom::blink::QueryParamsPtr cache_query_params, + mojom::blink::CacheQueryOptionsPtr cache_query_options, bool match_all, mojom::blink::BackgroundFetchService::MatchRequestsCallback callback);
diff --git a/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.cc b/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.cc index 5c48f407..05106c7 100644 --- a/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.cc +++ b/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.cc
@@ -4,6 +4,8 @@ #include "third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h" +#include <utility> + #include "base/metrics/histogram_macros.h" #include "base/optional.h" #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h" @@ -169,10 +171,10 @@ const RequestOrUSVString& request, const CacheQueryOptions* options, ExceptionState& exception_state) { - return MatchImpl(script_state, - base::make_optional<RequestOrUSVString>(request), - Cache::ToQueryParams(options), exception_state, - /* match_all = */ false); + return MatchImpl( + script_state, base::make_optional<RequestOrUSVString>(request), + mojom::blink::CacheQueryOptions::From(options), exception_state, + /* match_all = */ false); } ScriptPromise BackgroundFetchRegistration::matchAll( @@ -190,13 +192,14 @@ ExceptionState& exception_state) { return MatchImpl( script_state, base::make_optional<RequestOrUSVString>(request), - Cache::ToQueryParams(options), exception_state, /* match_all = */ true); + mojom::blink::CacheQueryOptions::From(options), exception_state, + /* match_all = */ true); } ScriptPromise BackgroundFetchRegistration::MatchImpl( ScriptState* script_state, base::Optional<RequestOrUSVString> request, - mojom::blink::QueryParamsPtr cache_query_params, + mojom::blink::CacheQueryOptionsPtr cache_query_options, ExceptionState& exception_state, bool match_all) { DCHECK(script_state); @@ -236,7 +239,7 @@ BackgroundFetchBridge::From(registration_) ->MatchRequests( developer_id_, unique_id_, std::move(request_to_match), - std::move(cache_query_params), match_all, + std::move(cache_query_options), match_all, WTF::Bind(&BackgroundFetchRegistration::DidGetMatchingRequests, WrapPersistent(this), WrapPersistent(resolver), match_all)); return promise;
diff --git a/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h b/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h index 4c8b41a..0f45142 100644 --- a/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h +++ b/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h
@@ -113,11 +113,12 @@ private: void DidAbort(ScriptPromiseResolver* resolver, mojom::blink::BackgroundFetchError error); - ScriptPromise MatchImpl(ScriptState* script_state, - base::Optional<RequestOrUSVString> request, - mojom::blink::QueryParamsPtr cache_query_params, - ExceptionState& exception_state, - bool match_all); + ScriptPromise MatchImpl( + ScriptState* script_state, + base::Optional<RequestOrUSVString> request, + mojom::blink::CacheQueryOptionsPtr cache_query_options, + ExceptionState& exception_state, + bool match_all); void DidGetMatchingRequests( ScriptPromiseResolver* resolver, bool return_all,
diff --git a/third_party/blink/renderer/modules/cache_storage/cache.cc b/third_party/blink/renderer/modules/cache_storage/cache.cc index b07fafd..277c259 100644 --- a/third_party/blink/renderer/modules/cache_storage/cache.cc +++ b/third_party/blink/renderer/modules/cache_storage/cache.cc
@@ -662,16 +662,6 @@ return KeysImpl(script_state, new_request, options); } -// static -mojom::blink::QueryParamsPtr Cache::ToQueryParams( - const CacheQueryOptions* options) { - mojom::blink::QueryParamsPtr query_params = mojom::blink::QueryParams::New(); - query_params->ignore_search = options->ignoreSearch(); - query_params->ignore_method = options->ignoreMethod(); - query_params->ignore_vary = options->ignoreVary(); - return query_params; -} - Cache::Cache(GlobalFetch::ScopedFetcher* fetcher, CacheStorage* cache_storage, mojom::blink::CacheStorageCacheAssociatedPtrInfo cache_ptr_info, @@ -700,7 +690,8 @@ // alive during the operation. Otherwise GC might prevent the callback // from ever being executed. cache_ptr_->Match( - request->CreateFetchAPIRequest(), ToQueryParams(options), + request->CreateFetchAPIRequest(), + mojom::blink::CacheQueryOptions::From(options), WTF::Bind( [](ScriptPromiseResolver* resolver, TimeTicks start_time, const CacheQueryOptions* options, Cache* _, @@ -762,7 +753,8 @@ // alive during the operation. Otherwise GC might prevent the callback // from ever being executed. cache_ptr_->MatchAll( - std::move(fetch_api_request), ToQueryParams(options), + std::move(fetch_api_request), + mojom::blink::CacheQueryOptions::From(options), WTF::Bind( [](ScriptPromiseResolver* resolver, TimeTicks start_time, const CacheQueryOptions* options, Cache* _, @@ -853,7 +845,7 @@ auto& operation = batch_operations.back(); operation->operation_type = mojom::blink::OperationType::kDelete; operation->request = request->CreateFetchAPIRequest(); - operation->match_params = ToQueryParams(options); + operation->match_options = mojom::blink::CacheQueryOptions::From(options); // Make sure to bind the Cache object to keep the mojo interface pointer // alive during the operation. Otherwise GC might prevent the callback @@ -1024,7 +1016,8 @@ // alive during the operation. Otherwise GC might prevent the callback // from ever being executed. cache_ptr_->Keys( - std::move(fetch_api_request), ToQueryParams(options), + std::move(fetch_api_request), + mojom::blink::CacheQueryOptions::From(options), WTF::Bind( [](ScriptPromiseResolver* resolver, TimeTicks start_time, const CacheQueryOptions* options, Cache* _,
diff --git a/third_party/blink/renderer/modules/cache_storage/cache.h b/third_party/blink/renderer/modules/cache_storage/cache.h index e7fe158..78c8aeb 100644 --- a/third_party/blink/renderer/modules/cache_storage/cache.h +++ b/third_party/blink/renderer/modules/cache_storage/cache.h
@@ -6,8 +6,8 @@ #define THIRD_PARTY_BLINK_RENDERER_MODULES_CACHE_STORAGE_CACHE_H_ #include <memory> -#include "base/macros.h" +#include "base/macros.h" #include "third_party/blink/public/mojom/cache_storage/cache_storage.mojom-blink.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/core/fetch/global_fetch.h" @@ -18,6 +18,24 @@ #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/vector.h" +namespace mojo { + +using blink::mojom::blink::CacheQueryOptions; +using blink::mojom::blink::CacheQueryOptionsPtr; + +template <> +struct TypeConverter<CacheQueryOptionsPtr, const blink::CacheQueryOptions*> { + static CacheQueryOptionsPtr Convert(const blink::CacheQueryOptions* input) { + CacheQueryOptionsPtr output = CacheQueryOptions::New(); + output->ignore_search = input->ignoreSearch(); + output->ignore_method = input->ignoreMethod(); + output->ignore_vary = input->ignoreVary(); + return output; + } +}; + +} // namespace mojo + namespace blink { class CacheStorage; @@ -70,8 +88,6 @@ const CacheQueryOptions*, ExceptionState&); - static mojom::blink::QueryParamsPtr ToQueryParams(const CacheQueryOptions*); - void Trace(blink::Visitor*) override; private:
diff --git a/third_party/blink/renderer/modules/cache_storage/cache_storage.cc b/third_party/blink/renderer/modules/cache_storage/cache_storage.cc index 14527a0..b78652a 100644 --- a/third_party/blink/renderer/modules/cache_storage/cache_storage.cc +++ b/third_party/blink/renderer/modules/cache_storage/cache_storage.cc
@@ -23,23 +23,23 @@ namespace mojo { -using blink::mojom::blink::MultiQueryParams; -using blink::mojom::blink::MultiQueryParamsPtr; -using blink::mojom::blink::QueryParams; -using blink::mojom::blink::QueryParamsPtr; +using blink::mojom::blink::CacheQueryOptions; +using blink::mojom::blink::CacheQueryOptionsPtr; +using blink::mojom::blink::MultiCacheQueryOptions; +using blink::mojom::blink::MultiCacheQueryOptionsPtr; template <> -struct TypeConverter<MultiQueryParamsPtr, +struct TypeConverter<MultiCacheQueryOptionsPtr, const blink::MultiCacheQueryOptions*> { - static MultiQueryParamsPtr Convert( + static MultiCacheQueryOptionsPtr Convert( const blink::MultiCacheQueryOptions* input) { - QueryParamsPtr query_params = QueryParams::New(); - query_params->ignore_search = input->ignoreSearch(); - query_params->ignore_method = input->ignoreMethod(); - query_params->ignore_vary = input->ignoreVary(); + CacheQueryOptionsPtr query_options = CacheQueryOptions::New(); + query_options->ignore_search = input->ignoreSearch(); + query_options->ignore_method = input->ignoreMethod(); + query_options->ignore_vary = input->ignoreVary(); - MultiQueryParamsPtr output = MultiQueryParams::New(); - output->query_params = std::move(query_params); + MultiCacheQueryOptionsPtr output = MultiCacheQueryOptions::New(); + output->query_options = std::move(query_options); output->cache_name = input->cacheName(); return output; } @@ -219,7 +219,7 @@ // callback from ever being executed. cache_storage_ptr_->Match( request->CreateFetchAPIRequest(), - mojom::blink::MultiQueryParams::From(options), + mojom::blink::MultiCacheQueryOptions::From(options), WTF::Bind( [](ScriptPromiseResolver* resolver, TimeTicks start_time, const MultiCacheQueryOptions* options, CacheStorage* _,
diff --git a/third_party/blink/renderer/modules/cache_storage/cache_test.cc b/third_party/blink/renderer/modules/cache_storage/cache_test.cc index b21d68d7..e5d9be8 100644 --- a/third_party/blink/renderer/modules/cache_storage/cache_test.cc +++ b/third_party/blink/renderer/modules/cache_storage/cache_test.cc
@@ -117,7 +117,7 @@ ErrorCacheForTests(const mojom::blink::CacheStorageError error) : error_(error), expected_url_(nullptr), - expected_query_params_(nullptr), + expected_query_options_(nullptr), expected_batch_operations_(nullptr) {} std::string GetAndClearLastErrorWebCacheMethodCalled() { @@ -132,9 +132,9 @@ void SetExpectedUrl(const String* expected_url) { expected_url_ = expected_url; } - void SetExpectedQueryParams( - const mojom::blink::QueryParamsPtr* expected_query_params) { - expected_query_params_ = expected_query_params; + void SetExpectedCacheQueryOptions( + const mojom::blink::CacheQueryOptionsPtr* expected_query_options) { + expected_query_options_ = expected_query_options; } void SetExpectedBatchOperations(const Vector<mojom::blink::BatchOperationPtr>* expected_batch_operations) { @@ -142,34 +142,34 @@ } void Match(mojom::blink::FetchAPIRequestPtr fetch_api_request, - mojom::blink::QueryParamsPtr query_params, + mojom::blink::CacheQueryOptionsPtr query_options, MatchCallback callback) override { last_error_web_cache_method_called_ = "dispatchMatch"; CheckUrlIfProvided(fetch_api_request->url); - CheckQueryParamsIfProvided(query_params); + CheckCacheQueryOptionsIfProvided(query_options); mojom::blink::MatchResultPtr result = mojom::blink::MatchResult::New(); result->set_status(error_); std::move(callback).Run(std::move(result)); } void MatchAll(mojom::blink::FetchAPIRequestPtr fetch_api_request, - mojom::blink::QueryParamsPtr query_params, + mojom::blink::CacheQueryOptionsPtr query_options, MatchAllCallback callback) override { last_error_web_cache_method_called_ = "dispatchMatchAll"; if (fetch_api_request) CheckUrlIfProvided(fetch_api_request->url); - CheckQueryParamsIfProvided(query_params); + CheckCacheQueryOptionsIfProvided(query_options); mojom::blink::MatchAllResultPtr result = mojom::blink::MatchAllResult::New(); result->set_status(error_); std::move(callback).Run(std::move(result)); } void Keys(mojom::blink::FetchAPIRequestPtr fetch_api_request, - mojom::blink::QueryParamsPtr query_params, + mojom::blink::CacheQueryOptionsPtr query_options, KeysCallback callback) override { last_error_web_cache_method_called_ = "dispatchKeys"; if (fetch_api_request && !fetch_api_request->url.IsEmpty()) { CheckUrlIfProvided(fetch_api_request->url); - CheckQueryParamsIfProvided(query_params); + CheckCacheQueryOptionsIfProvided(query_options); } mojom::blink::CacheKeysResultPtr result = mojom::blink::CacheKeysResult::New(); @@ -198,11 +198,11 @@ EXPECT_EQ(*expected_url_, url); } - void CheckQueryParamsIfProvided( - const mojom::blink::QueryParamsPtr& query_params) { - if (!expected_query_params_) + void CheckCacheQueryOptionsIfProvided( + const mojom::blink::CacheQueryOptionsPtr& query_options) { + if (!expected_query_options_) return; - CompareQueryParamsForTest(*expected_query_params_, query_params); + CompareCacheQueryOptionsForTest(*expected_query_options_, query_options); } void CheckBatchOperationsIfProvided( @@ -229,29 +229,30 @@ batch_operations[i]->response->url_list[j]); } } - if (expected_batch_operations[i]->match_params || - batch_operations[i]->match_params) { - CompareQueryParamsForTest(expected_batch_operations[i]->match_params, - batch_operations[i]->match_params); + if (expected_batch_operations[i]->match_options || + batch_operations[i]->match_options) { + CompareCacheQueryOptionsForTest( + expected_batch_operations[i]->match_options, + batch_operations[i]->match_options); } } } private: - static void CompareQueryParamsForTest( - const mojom::blink::QueryParamsPtr& expected_query_params, - const mojom::blink::QueryParamsPtr& query_params) { - EXPECT_EQ(expected_query_params->ignore_search, - query_params->ignore_search); - EXPECT_EQ(expected_query_params->ignore_method, - query_params->ignore_method); - EXPECT_EQ(expected_query_params->ignore_vary, query_params->ignore_vary); + static void CompareCacheQueryOptionsForTest( + const mojom::blink::CacheQueryOptionsPtr& expected_query_options, + const mojom::blink::CacheQueryOptionsPtr& query_options) { + EXPECT_EQ(expected_query_options->ignore_search, + query_options->ignore_search); + EXPECT_EQ(expected_query_options->ignore_method, + query_options->ignore_method); + EXPECT_EQ(expected_query_options->ignore_vary, query_options->ignore_vary); } const mojom::blink::CacheStorageError error_; const String* expected_url_; - const mojom::blink::QueryParamsPtr* expected_query_params_; + const mojom::blink::CacheQueryOptionsPtr* expected_query_options_; const Vector<mojom::blink::BatchOperationPtr>* expected_batch_operations_; std::string last_error_web_cache_method_called_; @@ -444,10 +445,10 @@ const String url = "http://www.cache.arguments.test/"; test_cache()->SetExpectedUrl(&url); - mojom::blink::QueryParamsPtr expected_query_params = - mojom::blink::QueryParams::New(); - expected_query_params->ignore_vary = true; - test_cache()->SetExpectedQueryParams(&expected_query_params); + mojom::blink::CacheQueryOptionsPtr expected_query_options = + mojom::blink::CacheQueryOptions::New(); + expected_query_options->ignore_vary = true; + test_cache()->SetExpectedCacheQueryOptions(&expected_query_options); CacheQueryOptions* options = CacheQueryOptions::Create(); options->setIgnoreVary(1); @@ -513,9 +514,9 @@ CreateCache(fetcher, std::make_unique<NotImplementedErrorCache>()); DCHECK(cache); - mojom::blink::QueryParamsPtr expected_query_params = - mojom::blink::QueryParams::New(); - test_cache()->SetExpectedQueryParams(&expected_query_params); + mojom::blink::CacheQueryOptionsPtr expected_query_options = + mojom::blink::CacheQueryOptions::New(); + test_cache()->SetExpectedCacheQueryOptions(&expected_query_options); CacheQueryOptions* options = CacheQueryOptions::Create(); @@ -535,7 +536,7 @@ auto& delete_operation = expected_delete_operations.back(); delete_operation->operation_type = mojom::blink::OperationType::kDelete; delete_operation->request = request->CreateFetchAPIRequest(); - delete_operation->match_params = expected_query_params->Clone(); + delete_operation->match_options = expected_query_options->Clone(); } test_cache()->SetExpectedBatchOperations(&expected_delete_operations); @@ -587,7 +588,7 @@ // From WebServiceWorkerCache: void Match(mojom::blink::FetchAPIRequestPtr fetch_api_request, - mojom::blink::QueryParamsPtr query_params, + mojom::blink::CacheQueryOptionsPtr query_options, MatchCallback callback) override { mojom::blink::MatchResultPtr result = mojom::blink::MatchResult::New(); result->set_response(std::move(response_)); @@ -632,7 +633,7 @@ : requests_(std::move(requests)) {} void Keys(mojom::blink::FetchAPIRequestPtr fetch_api_request, - mojom::blink::QueryParamsPtr query_params, + mojom::blink::CacheQueryOptionsPtr query_options, KeysCallback callback) override { mojom::blink::CacheKeysResultPtr result = mojom::blink::CacheKeysResult::New(); @@ -688,7 +689,7 @@ : responses_(std::move(responses)) {} void MatchAll(mojom::blink::FetchAPIRequestPtr fetch_api_request, - mojom::blink::QueryParamsPtr query_params, + mojom::blink::CacheQueryOptionsPtr query_options, MatchAllCallback callback) override { mojom::blink::MatchAllResultPtr result = mojom::blink::MatchAllResult::New();
diff --git a/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.cc b/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.cc index a8e2148..6bf1099 100644 --- a/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.cc +++ b/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.cc
@@ -254,7 +254,8 @@ request->redirect_mode, request->integrity, request->priority, request->fetch_window_id, request->keepalive, request->is_reload, request->is_history_navigation); - cache_ptr_->Match(std::move(request), mojom::blink::QueryParams::New(), + cache_ptr_->Match(std::move(request), + mojom::blink::CacheQueryOptions::New(), WTF::Bind( [](scoped_refptr<ResponsesAccumulator> accumulator, mojom::blink::FetchAPIRequestPtr request, @@ -372,7 +373,7 @@ void Dispatch(std::unique_ptr<GetCacheKeysForRequestData> self) { cache_ptr_->Keys( - nullptr /* request */, mojom::blink::QueryParams::New(), + nullptr /* request */, mojom::blink::CacheQueryOptions::New(), WTF::Bind( [](DataRequestParams params, std::unique_ptr<GetCacheKeysForRequestData> self, @@ -660,12 +661,12 @@ request->url = KURL(request_url); request->method = String("GET"); - auto multi_query_params = mojom::blink::MultiQueryParams::New(); - multi_query_params->query_params = mojom::blink::QueryParams::New(); - multi_query_params->cache_name = cache_name; + auto multi_query_options = mojom::blink::MultiCacheQueryOptions::New(); + multi_query_options->query_options = mojom::blink::CacheQueryOptions::New(); + multi_query_options->cache_name = cache_name; cache_storage->Match( - std::move(request), std::move(multi_query_params), + std::move(request), std::move(multi_query_options), WTF::Bind( [](std::unique_ptr<RequestCachedResponseCallback> callback, mojom::blink::MatchResultPtr result) {
diff --git a/third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.idl b/third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.idl index 81799c8a..2a7f93f 100644 --- a/third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.idl +++ b/third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.idl
@@ -15,6 +15,6 @@ void bezierCurveTo(unrestricted float cp1x, unrestricted float cp1y, unrestricted float cp2x, unrestricted float cp2y, unrestricted float x, unrestricted float y); [RaisesException] void arcTo(unrestricted float x1, unrestricted float y1, unrestricted float x2, unrestricted float y2, unrestricted float radius); void rect(unrestricted float x, unrestricted float y, unrestricted float width, unrestricted float height); - [RaisesException] void arc(unrestricted float x, unrestricted float y, unrestricted float radius, unrestricted float startAngle, unrestricted float endAngle, [DefaultValue=Undefined] optional boolean anticlockwise); - [RaisesException] void ellipse(unrestricted float x, unrestricted float y, unrestricted float radiusX, unrestricted float radiusY, unrestricted float rotation, unrestricted float startAngle, unrestricted float endAngle, [DefaultValue=Undefined] optional boolean anticlockwise); + [RaisesException] void arc(unrestricted float x, unrestricted float y, unrestricted float radius, unrestricted float startAngle, unrestricted float endAngle, optional boolean anticlockwise = false); + [RaisesException] void ellipse(unrestricted float x, unrestricted float y, unrestricted float radiusX, unrestricted float radiusY, unrestricted float rotation, unrestricted float startAngle, unrestricted float endAngle, optional boolean anticlockwise = false); };
diff --git a/third_party/blink/renderer/modules/indexeddb/idb_database.cc b/third_party/blink/renderer/modules/indexeddb/idb_database.cc index 6c48bda..e8d4ec88 100644 --- a/third_party/blink/renderer/modules/indexeddb/idb_database.cc +++ b/third_party/blink/renderer/modules/indexeddb/idb_database.cc
@@ -105,7 +105,7 @@ v8::Isolate* isolate) : ContextLifecycleObserver(context), backend_(std::move(backend)), - event_queue_(EventQueue::Create(context, TaskType::kInternalIndexedDB)), + event_queue_(EventQueue::Create(context, TaskType::kDatabaseAccess)), database_callbacks_(callbacks), isolate_(isolate) { database_callbacks_->Connect(this);
diff --git a/third_party/blink/renderer/modules/indexeddb/idb_factory.cc b/third_party/blink/renderer/modules/indexeddb/idb_factory.cc index ac2d5ca..bf84551 100644 --- a/third_party/blink/renderer/modules/indexeddb/idb_factory.cc +++ b/third_party/blink/renderer/modules/indexeddb/idb_factory.cc
@@ -219,7 +219,7 @@ mojo::MakeRequest(&web_idb_factory_host_info)); web_idb_factory_ = std::make_unique<WebIDBFactoryImpl>( std::move(web_idb_factory_host_info), - execution_context->GetTaskRunner(TaskType::kInternalIndexedDB)); + execution_context->GetTaskRunner(TaskType::kDatabaseAccess)); } return web_idb_factory_.get(); }
diff --git a/third_party/blink/renderer/modules/indexeddb/idb_request.cc b/third_party/blink/renderer/modules/indexeddb/idb_request.cc index 0434292..513aa1c 100644 --- a/third_party/blink/renderer/modules/indexeddb/idb_request.cc +++ b/third_party/blink/renderer/modules/indexeddb/idb_request.cc
@@ -137,7 +137,7 @@ metrics_(std::move(metrics)), source_(source), event_queue_(EventQueue::Create(ExecutionContext::From(script_state), - TaskType::kInternalIndexedDB)) {} + TaskType::kDatabaseAccess)) {} IDBRequest::~IDBRequest() { DCHECK((ready_state_ == DONE && metrics_.IsEmpty()) ||
diff --git a/third_party/blink/renderer/modules/indexeddb/idb_transaction.cc b/third_party/blink/renderer/modules/indexeddb/idb_transaction.cc index c962574..cad856d 100644 --- a/third_party/blink/renderer/modules/indexeddb/idb_transaction.cc +++ b/third_party/blink/renderer/modules/indexeddb/idb_transaction.cc
@@ -92,7 +92,7 @@ scope_(scope), state_(kActive), event_queue_( - EventQueue::Create(execution_context, TaskType::kInternalIndexedDB)) { + EventQueue::Create(execution_context, TaskType::kDatabaseAccess)) { DCHECK(database_); DCHECK(!scope_.IsEmpty()) << "Observer transactions must operate " "on a well-defined set of stores"; @@ -110,7 +110,7 @@ mode_(mode), scope_(scope), event_queue_(EventQueue::Create(ExecutionContext::From(script_state), - TaskType::kInternalIndexedDB)) { + TaskType::kDatabaseAccess)) { DCHECK(database_); DCHECK(!scope_.IsEmpty()) << "Non-versionchange transactions must operate " "on a well-defined set of stores"; @@ -139,7 +139,7 @@ state_(kInactive), old_database_metadata_(old_metadata), event_queue_( - EventQueue::Create(execution_context, TaskType::kInternalIndexedDB)) { + EventQueue::Create(execution_context, TaskType::kDatabaseAccess)) { DCHECK(database_); DCHECK(open_db_request_); DCHECK(scope_.IsEmpty());
diff --git a/third_party/blink/renderer/modules/indexeddb/web_idb_callbacks_impl.cc b/third_party/blink/renderer/modules/indexeddb/web_idb_callbacks_impl.cc index 2e1709e..78cebd1 100644 --- a/third_party/blink/renderer/modules/indexeddb/web_idb_callbacks_impl.cc +++ b/third_party/blink/renderer/modules/indexeddb/web_idb_callbacks_impl.cc
@@ -72,8 +72,8 @@ WebIDBCallbacksImpl::WebIDBCallbacksImpl(IDBRequest* request) : request_(request) { - task_runner_ = request_->GetExecutionContext()->GetTaskRunner( - TaskType::kInternalIndexedDB); + task_runner_ = + request_->GetExecutionContext()->GetTaskRunner(TaskType::kDatabaseAccess); probe::AsyncTaskScheduled(request_->GetExecutionContext(), indexed_db_names::kIndexedDB, this); }
diff --git a/third_party/blink/renderer/modules/media_capabilities/DEPS b/third_party/blink/renderer/modules/media_capabilities/DEPS index 8d65089..1a84f0e 100644 --- a/third_party/blink/renderer/modules/media_capabilities/DEPS +++ b/third_party/blink/renderer/modules/media_capabilities/DEPS
@@ -1,6 +1,7 @@ include_rules = [ "+media/base/mime_util.h", "+media/base/supported_types.h", + "+media/filters/stream_parser_factory.h", "-third_party/blink/renderer/modules", "+third_party/blink/renderer/modules/encryptedmedia", "+third_party/blink/renderer/modules/media_capabilities",
diff --git a/third_party/blink/renderer/modules/media_capabilities/media_capabilities.cc b/third_party/blink/renderer/modules/media_capabilities/media_capabilities.cc index cb323b58..89f1806 100644 --- a/third_party/blink/renderer/modules/media_capabilities/media_capabilities.cc +++ b/third_party/blink/renderer/modules/media_capabilities/media_capabilities.cc
@@ -8,6 +8,7 @@ #include "media/base/mime_util.h" #include "media/base/supported_types.h" +#include "media/filters/stream_parser_factory.h" #include "third_party/blink/public/platform/modules/media_capabilities/web_media_capabilities_client.h" #include "third_party/blink/public/platform/modules/media_capabilities/web_media_capabilities_info.h" #include "third_party/blink/public/platform/modules/media_capabilities/web_media_configuration.h" @@ -40,35 +41,6 @@ constexpr const char* kVideoMimeTypePrefix = "video/"; constexpr const char* kCodecsMimeTypeParam = "codecs"; -// Returns whether the AudioConfiguration is supported. -// Sends console warnings if the codec string was badly formatted. -bool IsAudioConfigurationSupported(const WebAudioConfiguration& audio_config, - String* console_warning) { - media::AudioCodec audio_codec = media::kUnknownAudioCodec; - bool is_audio_codec_ambiguous = true; - - if (!media::ParseAudioCodecString(audio_config.mime_type.Ascii(), - audio_config.codec.Ascii(), - &is_audio_codec_ambiguous, &audio_codec)) { - console_warning->append(("Failed to parse audio contentType: " + - audio_config.mime_type.Ascii() + - "; codecs=" + audio_config.codec.Ascii()) - .c_str()); - - return false; - } - - if (is_audio_codec_ambiguous) { - console_warning->append(("Invalid (ambiguous) audio codec string: " + - audio_config.codec.Ascii()) - .c_str()); - - return false; - } - - return media::IsSupportedAudioType({audio_codec}); -} - // Computes the effective framerate value based on the framerate field passed to // the VideoConfiguration. It will return the parsed string as a double or // compute the value in case of it is of the form "a/b". @@ -336,6 +308,94 @@ return web_configuration; } +// Utility function that will create a MediaCapabilitiesDecodingInfo object with +// all the values set to either true or false. +MediaCapabilitiesDecodingInfo* CreateDecodingInfoWith(bool value) { + MediaCapabilitiesDecodingInfo* info = MediaCapabilitiesDecodingInfo::Create(); + info->setSupported(value); + info->setSmooth(value); + info->setPowerEfficient(value); + + return info; +} + +bool CheckMseSupport(const WebMediaConfiguration& configuration) { + DCHECK_EQ(MediaConfigurationType::kMediaSource, configuration.type); + + // For MSE queries, we assume the queried audio and video streams will be + // placed into separate source buffers. + // TODO(chcunningham): Clarify this assumption in the spec. + + // Media MIME API expects a vector of codec strings. We query audio and video + // separately, so |codec_string|.size() should always be 1 or 0 (when no + // codecs parameter is required for the given mime type). + std::vector<std::string> codec_vector; + + if (configuration.audio_configuration) { + const WebAudioConfiguration& audio_config = + configuration.audio_configuration.value(); + + if (!audio_config.codec.Ascii().empty()) + codec_vector.push_back(audio_config.codec.Ascii()); + + if (!media::StreamParserFactory::IsTypeSupported( + audio_config.mime_type.Ascii(), codec_vector)) { + DVLOG(2) << __func__ << " MSE does not support audio config: " + << audio_config.mime_type.Ascii() << " " + << (codec_vector.empty() ? "" : codec_vector[1]); + return false; + } + } + + if (configuration.video_configuration) { + const WebVideoConfiguration& video_config = + configuration.video_configuration.value(); + + codec_vector.clear(); + if (!video_config.codec.Ascii().empty()) + codec_vector.push_back(video_config.codec.Ascii()); + + if (!media::StreamParserFactory::IsTypeSupported( + video_config.mime_type.Ascii(), codec_vector)) { + DVLOG(2) << __func__ << " MSE does not support video config: " + << video_config.mime_type.Ascii() << " " + << (codec_vector.empty() ? "" : codec_vector[1]); + return false; + } + } + + return true; +} + +// Returns whether the AudioConfiguration is supported. +// Sends console warnings if the codec string was badly formatted. +bool IsAudioConfigurationSupported(const WebAudioConfiguration& audio_config, + String* console_warning) { + media::AudioCodec audio_codec = media::kUnknownAudioCodec; + bool is_audio_codec_ambiguous = true; + + if (!media::ParseAudioCodecString(audio_config.mime_type.Ascii(), + audio_config.codec.Ascii(), + &is_audio_codec_ambiguous, &audio_codec)) { + console_warning->append(("Failed to parse audio contentType: " + + audio_config.mime_type.Ascii() + + "; codecs=" + audio_config.codec.Ascii()) + .c_str()); + + return false; + } + + if (is_audio_codec_ambiguous) { + console_warning->append(("Invalid (ambiguous) audio codec string: " + + audio_config.codec.Ascii()) + .c_str()); + + return false; + } + + return media::IsSupportedAudioType({audio_codec}); +} + } // anonymous namespace MediaCapabilities::MediaCapabilities() = default; @@ -392,6 +452,14 @@ ToWebMediaConfiguration(configuration); DCHECK(message.IsEmpty()); + + // MSE support is cheap to check (regex matching). Do it first. + if (web_config.type == MediaConfigurationType::kMediaSource && + !CheckMseSupport(web_config)) { + resolver->Resolve(WrapPersistent(CreateDecodingInfoWith(false))); + return promise; + } + bool audio_supported = true; if (configuration->hasAudio()) { @@ -401,11 +469,7 @@ // No need to check video capabilities if video not included in configuration // or when audio is already known to be unsupported. - // NOTE: at the moment, it is excluding MSE audio streams as they need to - // still be checked at the //media level. - if (!audio_supported || - (!configuration->hasVideo() && - web_config.type != MediaConfigurationType::kMediaSource)) { + if (!audio_supported || !configuration->hasVideo()) { // The call to IsAudioConfiguraationSupported may have returned a console // message to print. It would only happen when |audio_supported| is false. if (!message.IsEmpty()) { @@ -416,13 +480,7 @@ } } - Persistent<MediaCapabilitiesDecodingInfo> info( - MediaCapabilitiesDecodingInfo::Create()); - info->setSupported(audio_supported); - info->setSmooth(audio_supported); - info->setPowerEfficient(audio_supported); - - resolver->Resolve(std::move(info)); + resolver->Resolve(WrapPersistent(CreateDecodingInfoWith(audio_supported))); return promise; }
diff --git a/third_party/blink/renderer/modules/media_controls/BUILD.gn b/third_party/blink/renderer/modules/media_controls/BUILD.gn index 4ab9dd5..e7f5c2c 100644 --- a/third_party/blink/renderer/modules/media_controls/BUILD.gn +++ b/third_party/blink/renderer/modules/media_controls/BUILD.gn
@@ -72,6 +72,8 @@ "elements/media_control_timeline_metrics.h", "elements/media_control_toggle_closed_captions_button_element.cc", "elements/media_control_toggle_closed_captions_button_element.h", + "elements/media_control_volume_control_container_element.cc", + "elements/media_control_volume_control_container_element.h", "elements/media_control_volume_slider_element.cc", "elements/media_control_volume_slider_element.h", "media_controls_display_cutout_delegate.cc",
diff --git a/third_party/blink/renderer/modules/media_controls/elements/media_control_mute_button_element.cc b/third_party/blink/renderer/modules/media_controls/elements/media_control_mute_button_element.cc index 631f997e..fff3a88 100644 --- a/third_party/blink/renderer/modules/media_controls/elements/media_control_mute_button_element.cc +++ b/third_party/blink/renderer/modules/media_controls/elements/media_control_mute_button_element.cc
@@ -70,15 +70,11 @@ } if (!IsOverflowElement()) { - if (event.type() == event_type_names::kMouseover || - event.type() == event_type_names::kFocus) { + if (event.type() == event_type_names::kFocus) GetMediaControls().OpenVolumeSliderIfNecessary(); - } - if (event.type() == event_type_names::kMouseout || - event.type() == event_type_names::kBlur) { + if (event.type() == event_type_names::kBlur) GetMediaControls().CloseVolumeSliderIfNecessary(); - } } MediaControlInputElement::DefaultEventHandler(event);
diff --git a/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_control_container_element.cc b/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_control_container_element.cc new file mode 100644 index 0000000..80794540 --- /dev/null +++ b/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_control_container_element.cc
@@ -0,0 +1,44 @@ +// 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. + +#include "third_party/blink/renderer/modules/media_controls/elements/media_control_volume_control_container_element.h" + +#include "third_party/blink/renderer/core/dom/dom_token_list.h" +#include "third_party/blink/renderer/core/dom/events/event.h" +#include "third_party/blink/renderer/modules/media_controls/elements/media_control_consts.h" +#include "third_party/blink/renderer/modules/media_controls/elements/media_control_elements_helper.h" +#include "third_party/blink/renderer/modules/media_controls/media_controls_impl.h" + +namespace blink { + +MediaControlVolumeControlContainerElement:: + MediaControlVolumeControlContainerElement(MediaControlsImpl& media_controls) + : MediaControlDivElement(media_controls, kMediaIgnore) { + SetShadowPseudoId( + AtomicString("-webkit-media-controls-volume-control-container")); + MediaControlElementsHelper::CreateDiv( + "-webkit-media-controls-volume-control-hover-background", this); + + if (MediaControlsImpl::IsModern()) + CloseContainer(); +} + +void MediaControlVolumeControlContainerElement::OpenContainer() { + classList().Remove(kClosedCSSClass); +} + +void MediaControlVolumeControlContainerElement::CloseContainer() { + classList().Add(kClosedCSSClass); +} + +void MediaControlVolumeControlContainerElement::DefaultEventHandler( + Event& event) { + if (event.type() == event_type_names::kMouseover) + GetMediaControls().OpenVolumeSliderIfNecessary(); + + if (event.type() == event_type_names::kMouseout) + GetMediaControls().CloseVolumeSliderIfNecessary(); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_control_container_element.h b/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_control_container_element.h new file mode 100644 index 0000000..bbb0221 --- /dev/null +++ b/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_control_container_element.h
@@ -0,0 +1,28 @@ +// 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. + +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CONTROLS_ELEMENTS_MEDIA_CONTROL_VOLUME_CONTROL_CONTAINER_ELEMENT_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CONTROLS_ELEMENTS_MEDIA_CONTROL_VOLUME_CONTROL_CONTAINER_ELEMENT_H_ + +#include "third_party/blink/renderer/modules/media_controls/elements/media_control_div_element.h" + +namespace blink { + +class MediaControlsImpl; + +class MediaControlVolumeControlContainerElement final + : public MediaControlDivElement { + public: + explicit MediaControlVolumeControlContainerElement(MediaControlsImpl&); + + void OpenContainer(); + void CloseContainer(); + + private: + void DefaultEventHandler(Event&) override; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CONTROLS_ELEMENTS_MEDIA_CONTROL_VOLUME_CONTROL_CONTAINER_ELEMENT_H_
diff --git a/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.cc b/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.cc index 4c23feb..e127650 100644 --- a/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.cc +++ b/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.cc
@@ -93,15 +93,11 @@ SetVolumeInternal(volume); } - if (event.type() == event_type_names::kMouseover || - event.type() == event_type_names::kFocus) { + if (event.type() == event_type_names::kFocus) GetMediaControls().OpenVolumeSliderIfNecessary(); - } - if (event.type() == event_type_names::kMouseout || - event.type() == event_type_names::kBlur) { + if (event.type() == event_type_names::kBlur) GetMediaControls().CloseVolumeSliderIfNecessary(); - } } void MediaControlVolumeSliderElement::SetVolumeInternal(double volume) {
diff --git a/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc b/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc index 1e45d06..dcb0c0a 100644 --- a/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc +++ b/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc
@@ -79,6 +79,7 @@ #include "third_party/blink/renderer/modules/media_controls/elements/media_control_text_track_list_element.h" #include "third_party/blink/renderer/modules/media_controls/elements/media_control_timeline_element.h" #include "third_party/blink/renderer/modules/media_controls/elements/media_control_toggle_closed_captions_button_element.h" +#include "third_party/blink/renderer/modules/media_controls/elements/media_control_volume_control_container_element.h" #include "third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.h" #include "third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate.h" #include "third_party/blink/renderer/modules/media_controls/media_controls_media_event_listener.h" @@ -373,6 +374,7 @@ duration_display_(nullptr), mute_button_(nullptr), volume_slider_(nullptr), + volume_control_container_(nullptr), toggle_closed_captions_button_(nullptr), text_track_list_(nullptr), overflow_list_(nullptr), @@ -507,11 +509,15 @@ // | +-HTMLDivElement // | | (-internal-media-controls-button-spacer) // | | {if ModernMediaControls is enabled and is video element} -// | +-MediaControlMuteButtonElement -// | | (-webkit-media-controls-mute-button) -// | +-MediaControlVolumeSliderElement -// | | (-webkit-media-controls-volume-slider) -// | | {if not ModernMediaControlsEnabled} +// | +-MediaControlVolumeControlContainerElement +// | | | (-webkit-media-controls-volume-control-container) +// | | +-HTMLDivElement +// | | | (-webkit-media-controls-volume-control-hover-background) +// | | +-MediaControlMuteButtonElement +// | | | (-webkit-media-controls-mute-button) +// | | +-MediaControlVolumeSliderElement +// | | (-webkit-media-controls-volume-slider) +// | | {if not ModernMediaControlsEnabled} // | +-MediaControlPictureInPictureButtonElement // | | (-webkit-media-controls-picture-in-picture-button) // | +-MediaControlFullscreenButtonElement @@ -591,6 +597,8 @@ mute_button_ = MakeGarbageCollected<MediaControlMuteButtonElement>(*this); volume_slider_ = MakeGarbageCollected<MediaControlVolumeSliderElement>(*this); + volume_control_container_ = + MakeGarbageCollected<MediaControlVolumeControlContainerElement>(*this); if (PreferHiddenVolumeControls(GetDocument())) volume_slider_->SetIsWanted(false); @@ -695,14 +703,9 @@ // On modern controls, the volume slider is to the left of the mute button. if (IsModern()) { - volume_control_container_ = MediaControlElementsHelper::CreateDiv( - "-webkit-media-controls-volume-control-container", button_panel); - MediaControlElementsHelper::CreateDiv( - "-webkit-media-controls-volume-control-hover-background", - volume_control_container_); MaybeParserAppendChild(volume_control_container_, volume_slider_); volume_control_container_->ParserAppendChild(mute_button_); - HideVolumeControlHoverBackground(); + button_panel->ParserAppendChild(volume_control_container_); } else { button_panel->ParserAppendChild(mute_button_); MaybeParserAppendChild(button_panel, volume_slider_); @@ -1406,7 +1409,7 @@ element->SetDoesFit(does_fit); if (element == mute_button_.Get() && IsModern()) - SetVolumeControlContainerIsWanted(does_fit); + volume_control_container_->SetIsWanted(does_fit); // The element does fit and is sticky so we should allocate space for it. If // we cannot fit this element we should stop allocating space for other @@ -1438,7 +1441,7 @@ last_element->SetOverflowElementIsWanted(true); if (last_element == mute_button_.Get() && IsModern()) - SetVolumeControlContainerIsWanted(false); + volume_control_container_->SetIsWanted(false); } MaybeRecordElementsDisplayed(); @@ -2308,7 +2311,7 @@ void MediaControlsImpl::VolumeSliderWantedTimerFired(TimerBase*) { volume_slider_->OpenSlider(); - ShowVolumeControlHoverBackground(); + volume_control_container_->OpenContainer(); } void MediaControlsImpl::OpenVolumeSliderIfNecessary() { @@ -2316,7 +2319,7 @@ if (volume_slider_->IsFocused() || mute_button_->IsFocused()) { // When we're focusing with the keyboard, we don't need the delay. volume_slider_->OpenSlider(); - ShowVolumeControlHoverBackground(); + volume_control_container_->OpenContainer(); } else { volume_slider_wanted_timer_.StartOneShot( WebTestSupport::IsRunningWebTest() ? kTimeToShowVolumeSliderTest @@ -2329,31 +2332,13 @@ void MediaControlsImpl::CloseVolumeSliderIfNecessary() { if (ShouldCloseVolumeSlider()) { volume_slider_->CloseSlider(); - HideVolumeControlHoverBackground(); + volume_control_container_->CloseContainer(); if (volume_slider_wanted_timer_.IsActive()) volume_slider_wanted_timer_.Stop(); } } -void MediaControlsImpl::ShowVolumeControlHoverBackground() { - volume_control_container_->classList().Remove(kClosedCSSClass); -} - -void MediaControlsImpl::HideVolumeControlHoverBackground() { - volume_control_container_->classList().Add(kClosedCSSClass); -} - -void MediaControlsImpl::SetVolumeControlContainerIsWanted( - bool is_wanted) const { - if (is_wanted) { - volume_control_container_->RemoveInlineStyleProperty(CSSPropertyDisplay); - } else { - volume_control_container_->SetInlineStyleProperty(CSSPropertyDisplay, - CSSValueNone); - } -} - bool MediaControlsImpl::ShouldOpenVolumeSlider() const { if (!volume_slider_ || !IsModern()) return false; @@ -2365,7 +2350,7 @@ if (!volume_slider_ || !IsModern()) return false; - return !(volume_slider_->IsHovered() || mute_button_->IsHovered() || + return !(volume_control_container_->IsHovered() || volume_slider_->IsFocused() || mute_button_->IsFocused()); }
diff --git a/third_party/blink/renderer/modules/media_controls/media_controls_impl.h b/third_party/blink/renderer/modules/media_controls/media_controls_impl.h index 393f4e73..6f7a7f35 100644 --- a/third_party/blink/renderer/modules/media_controls/media_controls_impl.h +++ b/third_party/blink/renderer/modules/media_controls/media_controls_impl.h
@@ -64,6 +64,7 @@ class MediaControlTextTrackListElement; class MediaControlTimelineElement; class MediaControlToggleClosedCaptionsButtonElement; +class MediaControlVolumeControlContainerElement; class MediaControlVolumeSliderElement; class MediaDownloadInProductHelpManager; class ShadowRoot; @@ -282,9 +283,6 @@ bool ShouldOpenVolumeSlider() const; bool ShouldCloseVolumeSlider() const; - void ShowVolumeControlHoverBackground(); - void HideVolumeControlHoverBackground(); - void SetVolumeControlContainerIsWanted(bool) const; void ElementSizeChangedTimerFired(TimerBase*); @@ -370,6 +368,7 @@ Member<MediaControlRemainingTimeDisplayElement> duration_display_; Member<MediaControlMuteButtonElement> mute_button_; Member<MediaControlVolumeSliderElement> volume_slider_; + Member<MediaControlVolumeControlContainerElement> volume_control_container_; Member<MediaControlToggleClosedCaptionsButtonElement> toggle_closed_captions_button_; Member<MediaControlTextTrackListElement> text_track_list_; @@ -399,8 +398,6 @@ bool is_paused_for_scrubbing_ : 1; bool is_scrubbing_ = false; - Member<HTMLDivElement> volume_control_container_; - // Watches the video element for resize and updates media controls as // necessary. Member<ResizeObserver> resize_observer_;
diff --git a/third_party/blink/renderer/modules/plugins/plugin_array.idl b/third_party/blink/renderer/modules/plugins/plugin_array.idl index 2ada86b..f7d7a43 100644 --- a/third_party/blink/renderer/modules/plugins/plugin_array.idl +++ b/third_party/blink/renderer/modules/plugins/plugin_array.idl
@@ -27,5 +27,5 @@ readonly attribute unsigned long length; getter Plugin? item(unsigned long index); getter Plugin? namedItem(DOMString name); - void refresh([DefaultValue=Undefined] optional boolean reload); + void refresh(optional boolean reload = false); };
diff --git a/third_party/blink/renderer/modules/storage/cached_storage_area.cc b/third_party/blink/renderer/modules/storage/cached_storage_area.cc index 35a114e..21ce9fe0 100644 --- a/third_party/blink/renderer/modules/storage/cached_storage_area.cc +++ b/third_party/blink/renderer/modules/storage/cached_storage_area.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/modules/storage/cached_storage_area.h" +#include "base/debug/crash_logging.h" #include "base/metrics/histogram_macros.h" #include "base/numerics/safe_conversions.h" #include "base/rand_util.h" @@ -423,6 +424,13 @@ void CachedStorageArea::EnsureLoaded() { if (map_) return; + // TODO(dmurph): Change this back to non-sync after the cause of the renderer + // hang is discovered. http://crbug.com/927534 + static base::debug::CrashKeyString* dom_storage_type = + base::debug::AllocateCrashKeyString("dom_storage_type", + base::debug::CrashKeySize::Size32); + base::debug::ScopedCrashKeyString auto_clear( + dom_storage_type, IsSessionStorage() ? "ss" : "ls"); // There might be something weird happening during the sync call that destroys // this object. Keep a reference to either fix or rule out that this is the
diff --git a/third_party/blink/renderer/modules/storage/storage_controller_test.cc b/third_party/blink/renderer/modules/storage/storage_controller_test.cc index 3c49809..7cc8ba1 100644 --- a/third_party/blink/renderer/modules/storage/storage_controller_test.cc +++ b/third_party/blink/renderer/modules/storage/storage_controller_test.cc
@@ -28,12 +28,16 @@ : public mojom::blink::StoragePartitionService { public: void OpenLocalStorage(const scoped_refptr<const SecurityOrigin>& origin, - mojom::blink::StorageAreaRequest request) override {} + mojom::blink::StorageAreaRequest request, + OpenLocalStorageCallback done) override { + std::move(done).Run(); + } - void OpenSessionStorage( - const String& namespace_id, - mojom::blink::SessionStorageNamespaceRequest request) override { + void OpenSessionStorage(const String& namespace_id, + mojom::blink::SessionStorageNamespaceRequest request, + OpenSessionStorageCallback done) override { session_storage_opens++; + std::move(done).Run(); } void GetSessionStorageUsage(int32_t* out) const {
diff --git a/third_party/blink/renderer/modules/storage/storage_namespace_test.cc b/third_party/blink/renderer/modules/storage/storage_namespace_test.cc index 24ed63a..31dd9b6 100644 --- a/third_party/blink/renderer/modules/storage/storage_namespace_test.cc +++ b/third_party/blink/renderer/modules/storage/storage_namespace_test.cc
@@ -22,11 +22,16 @@ : public mojom::blink::StoragePartitionService { public: void OpenLocalStorage(const scoped_refptr<const SecurityOrigin>& origin, - mojom::blink::StorageAreaRequest request) override {} + mojom::blink::StorageAreaRequest request, + OpenLocalStorageCallback callback) override { + std::move(callback).Run(); + } - void OpenSessionStorage( - const String& namespace_id, - mojom::blink::SessionStorageNamespaceRequest request) override {} + void OpenSessionStorage(const String& namespace_id, + mojom::blink::SessionStorageNamespaceRequest request, + OpenSessionStorageCallback callback) override { + std::move(callback).Run(); + } }; } // namespace
diff --git a/third_party/blink/renderer/modules/webaudio/audio_buffer_source_node.cc b/third_party/blink/renderer/modules/webaudio/audio_buffer_source_node.cc index 016fdb99..8ac66b371 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_buffer_source_node.cc +++ b/third_party/blink/renderer/modules/webaudio/audio_buffer_source_node.cc
@@ -274,10 +274,6 @@ // Get local copy. double virtual_read_index = virtual_read_index_; - // We should never start the the source before the start time, so - // start_time_offset should always be negative or 0. - DCHECK_LE(start_time_offset, 0); - // Adjust the read index by the start_time_offset (compensated by the playback // rate) because we always start output on a frame boundary with interpolation // if necessary.
diff --git a/third_party/blink/renderer/modules/webaudio/audio_node.h b/third_party/blink/renderer/modules/webaudio/audio_node.h index 94168c9..49ea5db 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_node.h +++ b/third_party/blink/renderer/modules/webaudio/audio_node.h
@@ -38,7 +38,7 @@ #include "third_party/blink/renderer/platform/wtf/vector.h" // Higher values produce more debugging output. -#define DEBUG_AUDIONODE_REFERENCES 1 +#define DEBUG_AUDIONODE_REFERENCES 0 namespace blink {
diff --git a/third_party/blink/renderer/modules/webaudio/audio_scheduled_source_node.cc b/third_party/blink/renderer/modules/webaudio/audio_scheduled_source_node.cc index 54d9875..15a015f 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_scheduled_source_node.cc +++ b/third_party/blink/renderer/modules/webaudio/audio_scheduled_source_node.cc
@@ -122,6 +122,8 @@ // SCHEDULED_STATE to PLAYING_STATE. SetPlaybackState(PLAYING_STATE); // Determine the offset of the true start time from the starting frame. + // NOTE: start_frame_offset is usually negative, but may not be because of + // the rounding that may happen in computing |start_frame| above. start_frame_offset = start_time_ * sample_rate - start_frame; } else { start_frame_offset = 0; @@ -135,7 +137,6 @@ if (!non_silent_frames_to_process) { // Output silence. - DCHECK_LE(start_frame_offset, 0); output_bus->Zero(); return std::make_tuple(quantum_frame_offset, non_silent_frames_to_process, start_frame_offset); @@ -179,7 +180,6 @@ Finish(); } - DCHECK_LE(start_frame_offset, 0); return std::make_tuple(quantum_frame_offset, non_silent_frames_to_process, start_frame_offset); }
diff --git a/third_party/blink/renderer/platform/BUILD.gn b/third_party/blink/renderer/platform/BUILD.gn index e99295d..0831adfb 100644 --- a/third_party/blink/renderer/platform/BUILD.gn +++ b/third_party/blink/renderer/platform/BUILD.gn
@@ -500,7 +500,6 @@ "data_resource_helper.h", "date_components.cc", "date_components.h", - "dom_node_id.h", "drag_image.cc", "drag_image.h", "exported/file_path_conversion.cc", @@ -885,6 +884,7 @@ "graphics/decoding_image_generator.h", "graphics/deferred_image_decoder.cc", "graphics/deferred_image_decoder.h", + "graphics/dom_node_id.h", "graphics/draw_looper_builder.cc", "graphics/draw_looper_builder.h", "graphics/filters/distant_light_source.cc",
diff --git a/third_party/blink/renderer/platform/audio/audio_utilities.cc b/third_party/blink/renderer/platform/audio/audio_utilities.cc index 14d96f75a..cfe0b7dd 100644 --- a/third_party/blink/renderer/platform/audio/audio_utilities.cc +++ b/third_party/blink/renderer/platform/audio/audio_utilities.cc
@@ -70,17 +70,33 @@ double sample_rate, enum SampleFrameRounding rounding_mode) { DCHECK_GE(time, 0); - double frame; + + // To compute the desired frame number, we pretend we're actually running the + // context at a much higher sample rate (by a factor of |oversample_factor|). + // Round this to get the nearest frame number at the higher rate. Then + // convert back to the original rate to get a new frame number that may not be + // an integer. Then use the specified |rounding_mode| to round this to the + // integer frame number that we need. + // + // Doing this partially solves the issue where Fs * (k / Fs) != k when doing + // floating point arithmtic for integer k and Fs is the sample rate. By + // oversampling and rounding, we'll get k back most of the time. + // + // The oversampling factor MUST be a power of two so as not to introduce + // additional round-off in computing the oversample frame number. + const double oversample_factor = 1024; + double frame = + round(time * sample_rate * oversample_factor) / oversample_factor; switch (rounding_mode) { case kRoundToNearest: - frame = round(time * sample_rate); + frame = round(frame); break; case kRoundDown: - frame = floor(time * sample_rate); + frame = floor(frame); break; case kRoundUp: - frame = ceil(time * sample_rate); + frame = ceil(frame); break; default: NOTREACHED();
diff --git a/third_party/blink/renderer/platform/bindings/parkable_string.cc b/third_party/blink/renderer/platform/bindings/parkable_string.cc index df13aa4a..976b5d4 100644 --- a/third_party/blink/renderer/platform/bindings/parkable_string.cc +++ b/third_party/blink/renderer/platform/bindings/parkable_string.cc
@@ -151,8 +151,33 @@ // // See |Park()| for (1), |OnParkingCompleteOnMainThread()| for 2-3, and // |Unpark()| for (4). +// +// Each state can be combined with a string that is either old or +// young. Examples below: +// - kUnParked: +// - Old: old strings are not necessarily parked +// - Young: a string starts young and unparked. +// - kParkingInProgress: +// - Old: The string wasn't touched since parking started +// - Young: The string was either touched or locked since parking started +// - kParked: +// - Old: Parked, and not touched nor locked since then +// - Young: Lock() makes a string young but doesn't unpark it. enum class ParkableStringImpl::State { kUnparked, kParkingInProgress, kParked }; +// Current "ownership" status of the underlying data. +// +// - kUnreferencedExternally: |string_| is not referenced externally, and the +// class is free to change it. +// - kTooManyReferences: |string_| has multiple references pointing to it, +// cannot change it. +// - kLocked: |this| is locked. +enum class ParkableStringImpl::Status { + kUnreferencedExternally, + kTooManyReferences, + kLocked +}; + ParkableStringImpl::ParkableStringImpl(scoped_refptr<StringImpl>&& impl, ParkableState parkable) : mutex_(), @@ -160,6 +185,7 @@ state_(State::kUnparked), string_(std::move(impl)), compressed_(nullptr), + is_young_(true), may_be_parked_(parkable == ParkableState::kParkable), is_8bit_(string_.Is8Bit()), length_(string_.length()) @@ -189,8 +215,20 @@ void ParkableStringImpl::Lock() { MutexLocker locker(mutex_); lock_depth_ += 1; + // Make young as this is a strong (but not certain) indication that the string + // will be accessed soon. + MakeYoung(); } +#if defined(ADDRESS_SANITIZER) + +void ParkableStringImpl::LockWithoutMakingYoung() { + MutexLocker locker(mutex_); + lock_depth_ += 1; +} + +#endif // defined(ADDRESS_SANITIZER) + void ParkableStringImpl::Unlock() { MutexLocker locker(mutex_); DCHECK_GT(lock_depth_, 0); @@ -205,9 +243,10 @@ // to use the string until the end of the current owning thread task. // Requires DCHECK_IS_ON() for the |owning_thread_| check. // - // Checking the owning thread first as CanParkNow() can only be called from - // the owning thread. - if (owning_thread_ == CurrentThread() && CanParkNow()) { + // Checking the owning thread first as |CurrentStatus()| can only be called + // from the owning thread. + if (owning_thread_ == CurrentThread() && may_be_parked() && + CurrentStatus() == Status::kUnreferencedExternally) { AsanPoisonString(string_); } #endif // defined(ADDRESS_SANITIZER) && DCHECK_IS_ON() @@ -219,9 +258,15 @@ compressed_ = nullptr; } +void ParkableStringImpl::MakeYoung() { + mutex_.AssertAcquired(); + is_young_ = true; +} + const String& ParkableStringImpl::ToString() { AssertOnValidThread(); MutexLocker locker(mutex_); + MakeYoung(); AsanUnpoisonString(string_); Unpark(); @@ -233,49 +278,101 @@ return length_ * (is_8bit() ? sizeof(LChar) : sizeof(UChar)); } -bool ParkableStringImpl::Park(ParkingMode mode) { - AssertOnValidThread(); +ParkableStringImpl::AgeOrParkResult ParkableStringImpl::MaybeAgeOrParkString() { MutexLocker locker(mutex_); - DCHECK(may_be_parked_); - if (state_ == State::kUnparked && CanParkNow()) { - // Parking can proceed synchronously. - if (has_compressed_data()) { - RecordParkingAction(ParkingAction::kParkedInBackground); - state_ = State::kParked; - ParkableStringManager::Instance().OnParked(this, string_.Impl()); + AssertOnValidThread(); + DCHECK(may_be_parked()); + DCHECK(!is_parked()); - // Must unpoison the memory before releasing it. - AsanUnpoisonString(string_); - string_ = String(); - } else if (mode == ParkingMode::kAlways) { - // |string_|'s data should not be touched except in the compression task. - AsanPoisonString(string_); - // |params| keeps |this| alive until |OnParkingCompleteOnMainThread()|. - auto params = std::make_unique<CompressionTaskParams>( - this, string_.Bytes(), string_.CharactersSizeInBytes(), - Thread::Current()->GetTaskRunner()); - background_scheduler::PostOnBackgroundThread( - FROM_HERE, CrossThreadBind(&ParkableStringImpl::CompressInBackground, - WTF::Passed(std::move(params)))); - state_ = State::kParkingInProgress; + Status status = CurrentStatus(); + if (is_young()) { + if (status == Status::kUnreferencedExternally) + is_young_ = false; + } else { + if (state_ == State::kParkingInProgress) + return AgeOrParkResult::kSuccessOrTransientFailure; + + if (CanParkNow()) { + ParkInternal(ParkingMode::kAlways); + return AgeOrParkResult::kSuccessOrTransientFailure; } } - return state_ == State::kParked || state_ == State::kParkingInProgress; + // External references to a string can be long-lived, cannot provide a + // progress guarantee for this string. + return status == Status::kTooManyReferences + ? AgeOrParkResult::kNonTransientFailure + : AgeOrParkResult::kSuccessOrTransientFailure; +} + +bool ParkableStringImpl::Park(ParkingMode mode) { + MutexLocker locker(mutex_); + AssertOnValidThread(); + DCHECK(may_be_parked()); + + if (state_ == State::kParkingInProgress || state_ == State::kParked) + return true; + + // Making the string old to cancel parking if it is accessed/locked before + // parking is complete. + is_young_ = false; + if (!CanParkNow()) + return false; + + ParkInternal(mode); + return true; +} + +void ParkableStringImpl::ParkInternal(ParkingMode mode) { + mutex_.AssertAcquired(); + DCHECK_EQ(State::kUnparked, state_); + DCHECK(!is_young()); + DCHECK(CanParkNow()); + + // Parking can proceed synchronously. + if (has_compressed_data()) { + RecordParkingAction(ParkingAction::kParkedInBackground); + state_ = State::kParked; + ParkableStringManager::Instance().OnParked(this, string_.Impl()); + + // Must unpoison the memory before releasing it. + AsanUnpoisonString(string_); + string_ = String(); + } else if (mode == ParkingMode::kAlways) { + // |string_|'s data should not be touched except in the compression task. + AsanPoisonString(string_); + // |params| keeps |this| alive until |OnParkingCompleteOnMainThread()|. + auto params = std::make_unique<CompressionTaskParams>( + this, string_.Bytes(), string_.CharactersSizeInBytes(), + Thread::Current()->GetTaskRunner()); + background_scheduler::PostOnBackgroundThread( + FROM_HERE, CrossThreadBind(&ParkableStringImpl::CompressInBackground, + WTF::Passed(std::move(params)))); + state_ = State::kParkingInProgress; + } } bool ParkableStringImpl::is_parked() const { return state_ == State::kParked; } -bool ParkableStringImpl::CanParkNow() const { +ParkableStringImpl::Status ParkableStringImpl::CurrentStatus() const { + AssertOnValidThread(); mutex_.AssertAcquired(); + DCHECK(may_be_parked()); // Can park iff: - // - the string is eligible to parking - // - There are no external reference to |string_|. Since |this| holds a - // reference to it, then we are the only one. // - |this| is not locked. - return may_be_parked_ && string_.Impl()->HasOneRef() && lock_depth_ == 0; + // - There are no external reference to |string_|. Since |this| holds a + // reference to |string_|, it must the only one. + if (lock_depth_ != 0) + return Status::kLocked; + if (!string_.Impl()->HasOneRef()) + return Status::kTooManyReferences; + return Status::kUnreferencedExternally; +} + +bool ParkableStringImpl::CanParkNow() const { + return CurrentStatus() == Status::kUnreferencedExternally && !is_young(); } void ParkableStringImpl::Unpark() { @@ -333,21 +430,23 @@ std::unique_ptr<Vector<uint8_t>> compressed) { MutexLocker locker(mutex_); DCHECK_EQ(State::kParkingInProgress, state_); + + // Always keep the compressed data. Compression is expensive, so even if the + // uncompressed representation cannot be discarded now, avoid compressing + // multiple times. This will allow synchronous parking next time. + DCHECK(!compressed_); + if (compressed) + compressed_ = std::move(compressed); + // Between |Park()| and now, things may have happened: // 1. |ToString()| or // 2. |Lock()| may have been called. // - // We only care about "surviving" calls, that is iff the string returned by - // |ToString()| is still alive, or whether we are still locked. Since this - // function is protected by the lock, no concurrent modifications can occur. - // - // Finally, since this is a distinct task from any one that can call - // |ToString()|, the invariant that the pointer stays valid until the next - // task is preserved. - if (CanParkNow() && compressed) { + // Both of these will make the string young again, and if so we don't + // discard the compressed representation yet. + if (CanParkNow() && compressed_) { RecordParkingAction(ParkingAction::kParkedInBackground); state_ = State::kParked; - compressed_ = std::move(compressed); ParkableStringManager::Instance().OnParked(this, string_.Impl()); // Must unpoison the memory before releasing it. @@ -368,7 +467,12 @@ #if defined(ADDRESS_SANITIZER) // Lock the string to prevent a concurrent |Unlock()| on the main thread from // poisoning the string in the meantime. - params->string->Lock(); + // + // Don't make the string young at the same time, otherwise parking would + // always be cancelled on the main thread with address sanitizer, since the + // |OnParkingCompleteOnMainThread()| callback would be executed on a young + // string. + params->string->LockWithoutMakingYoung(); #endif // defined(ADDRESS_SANITIZER) // Compression touches the string. AsanUnpoisonString(params->string->string_);
diff --git a/third_party/blink/renderer/platform/bindings/parkable_string.h b/third_party/blink/renderer/platform/bindings/parkable_string.h index 7372323..719f8aa 100644 --- a/third_party/blink/renderer/platform/bindings/parkable_string.h +++ b/third_party/blink/renderer/platform/bindings/parkable_string.h
@@ -51,6 +51,10 @@ enum class ParkableState { kParkable, kNotParkable }; enum class ParkingMode { kIfCompressedDataExists, kAlways }; + enum class AgeOrParkResult { + kSuccessOrTransientFailure, + kNonTransientFailure + }; // Not all parkable strings can actually be parked. If |parkable| is // kNotParkable, then one cannot call |Park()|, and the underlying StringImpl @@ -72,12 +76,26 @@ unsigned length() const { return length_; } unsigned CharactersSizeInBytes() const; + // Tries to either age or park a string: + // + // - If the string is already old, tries to park it. + // - Otherwise, tries to age it. + // + // The action doesn't necessarily succeed. either due to a temporary + // or potentially lasting condition. + // + // As parking may be synchronous, this can call back into + // ParkableStringManager. + AgeOrParkResult MaybeAgeOrParkString(); + // A parked string cannot be accessed until it has been |Unpark()|-ed. // // Parking may be synchronous, and will be if compressed data is already // available. If |mode| is |kIfCompressedDataExists|, then parking will always // be synchronous. // + // Must not be called if |may_be_parked()| returns false. + // // Returns true if the string is being parked or has been parked. bool Park(ParkingMode mode); // Returns true iff the string can be parked. This does not mean that the @@ -96,12 +114,29 @@ return compressed_->size(); } + // A string can either be "young" or "old". It starts young, and transitions + // are: + // Young -> Old: By calling |MaybeAgeOrParkString()|. + // Old -> Young: When the string is accessed, either by |Lock()|-ing it or + // calling |ToString()|. + bool is_young() const { return is_young_; } + private: enum class State; + enum class Status; - // Whether the string can be parked now. Must be called with |mutex_| held, - // and the return value is valid as long as the mutex is held. +#if defined(ADDRESS_SANITIZER) + // See |CompressInBackground()|. Doesn't make the string young. + // May be called from any thread. + void LockWithoutMakingYoung(); +#endif // defined(ADDRESS_SANITIZER) + // May be called from any thread. Must acquire |mutex_| first. + void MakeYoung(); + // Whether the string is referenced or locked. Must be called with |mutex_| + // held, and the return value is valid as long as |mutex_| is held. + Status CurrentStatus() const; bool CanParkNow() const; + void ParkInternal(ParkingMode mode); void Unpark(); // Called on the main thread after compression is done. // |params| is the same as the one passed to |CompressInBackground()|, @@ -120,9 +155,10 @@ State state_; String string_; std::unique_ptr<Vector<uint8_t>> compressed_; + bool is_young_ : 1; - const bool may_be_parked_; - const bool is_8bit_; + const bool may_be_parked_ : 1; + const bool is_8bit_ : 1; const unsigned length_; #if DCHECK_IS_ON()
diff --git a/third_party/blink/renderer/platform/bindings/parkable_string_manager.cc b/third_party/blink/renderer/platform/bindings/parkable_string_manager.cc index adf81acf..fe162fd0 100644 --- a/third_party/blink/renderer/platform/bindings/parkable_string_manager.cc +++ b/third_party/blink/renderer/platform/bindings/parkable_string_manager.cc
@@ -36,6 +36,17 @@ } }; +Vector<ParkableStringImpl*> GetUnparkedStrings( + const HashMap<StringImpl*, ParkableStringImpl*, PtrHash<StringImpl>>& + unparked_strings) { + WTF::Vector<ParkableStringImpl*> unparked; + unparked.ReserveCapacity(unparked_strings.size()); + for (ParkableStringImpl* str : unparked_strings.Values()) + unparked.push_back(str); + + return unparked; +} + } // namespace // static @@ -172,12 +183,14 @@ auto new_parkable_string = base::MakeRefCounted<ParkableStringImpl>( std::move(string), ParkableStringImpl::ParkableState::kParkable); unparked_strings_.insert(raw_ptr, new_parkable_string.get()); + ScheduleAgingTaskIfNeeded(); return new_parkable_string; } void ParkableStringManager::Remove(ParkableStringImpl* string, StringImpl* maybe_unparked_string) { DCHECK(IsMainThread()); + DCHECK(string->may_be_parked()); if (string->is_parked()) { auto it = parked_strings_.find(string); DCHECK(it != parked_strings_.end()); @@ -193,6 +206,7 @@ void ParkableStringManager::OnParked(ParkableStringImpl* newly_parked_string, StringImpl* previous_unparked_string) { DCHECK(IsMainThread()); + DCHECK(newly_parked_string->may_be_parked()); DCHECK(newly_parked_string->is_parked()); auto it = unparked_strings_.find(previous_unparked_string); DCHECK(it != unparked_strings_.end()); @@ -203,11 +217,13 @@ void ParkableStringManager::OnUnparked(ParkableStringImpl* was_parked_string, StringImpl* new_unparked_string) { DCHECK(IsMainThread()); + DCHECK(was_parked_string->may_be_parked()); DCHECK(!was_parked_string->is_parked()); auto it = parked_strings_.find(was_parked_string); DCHECK(it != parked_strings_.end()); parked_strings_.erase(it); unparked_strings_.insert(new_unparked_string, was_parked_string); + ScheduleAgingTaskIfNeeded(); } void ParkableStringManager::ParkAll(ParkableStringImpl::ParkingMode mode) { @@ -227,10 +243,8 @@ // and |unparked_strings_| can contain a few 10s of strings (and we will // trigger expensive compression), or this is a subsequent one, and // |unparked_strings_| will have few entries. - WTF::Vector<ParkableStringImpl*> unparked; - unparked.ReserveCapacity(unparked_strings_.size()); - for (ParkableStringImpl* str : unparked_strings_.Values()) - unparked.push_back(str); + WTF::Vector<ParkableStringImpl*> unparked = + GetUnparkedStrings(unparked_strings_); for (ParkableStringImpl* str : unparked) { str->Park(mode); @@ -302,6 +316,53 @@ } } +void ParkableStringManager::AgeStringsAndPark() { + if (!base::FeatureList::IsEnabled(kCompressParkableStringsInForeground)) + return; + + has_pending_aging_task_ = false; + + WTF::Vector<ParkableStringImpl*> unparked = + GetUnparkedStrings(unparked_strings_); + + bool can_make_progress = false; + for (ParkableStringImpl* str : unparked) { + if (str->MaybeAgeOrParkString() == + ParkableStringImpl::AgeOrParkResult::kSuccessOrTransientFailure) + can_make_progress = true; + } + + // Some strings will never be parkable because there are lasting external + // references to them. Don't endlessely reschedule the aging task if we are + // not making progress (that is, no new string was either aged or parked). + // + // This ensures that the tasks will stop getting scheduled, assuming that + // the renderer is otherwise idle. Note that we cannot use "idle" tasks as + // we need to age and park strings after the renderer becomes idle, meaning + // that this has to run when the idle tasks are not. As a consequence, it + // is important to make sure that this will not reschedule tasks forever. + bool reschedule = !unparked_strings_.IsEmpty() && can_make_progress; + if (reschedule) + ScheduleAgingTaskIfNeeded(); +} + +void ParkableStringManager::ScheduleAgingTaskIfNeeded() { + if (!base::FeatureList::IsEnabled(kCompressParkableStringsInForeground)) + return; + + if (has_pending_aging_task_) + return; + + scoped_refptr<base::SingleThreadTaskRunner> task_runner = + Thread::Current()->GetTaskRunner(); + task_runner->PostDelayedTask( + FROM_HERE, + base::BindOnce(&ParkableStringManager::AgeStringsAndPark, + base::Unretained(this)), + base::TimeDelta::FromSeconds(kAgingIntervalInSeconds)); + has_pending_aging_task_ = true; +} + void ParkableStringManager::PurgeMemory() { DCHECK(IsMainThread()); DCHECK(base::FeatureList::IsEnabled(kCompressParkableStringsInBackground)); @@ -322,6 +383,7 @@ void ParkableStringManager::ResetForTesting() { backgrounded_ = false; waiting_to_record_stats_ = false; + has_pending_aging_task_ = false; should_record_stats_ = false; unparked_strings_.clear(); parked_strings_.clear(); @@ -330,6 +392,7 @@ ParkableStringManager::ParkableStringManager() : backgrounded_(false), waiting_to_record_stats_(false), + has_pending_aging_task_(false), should_record_stats_(false), unparked_strings_(), parked_strings_() {
diff --git a/third_party/blink/renderer/platform/bindings/parkable_string_manager.h b/third_party/blink/renderer/platform/bindings/parkable_string_manager.h index 54e7631..3a68651 100644 --- a/third_party/blink/renderer/platform/bindings/parkable_string_manager.h +++ b/third_party/blink/renderer/platform/bindings/parkable_string_manager.h
@@ -23,6 +23,8 @@ const base::Feature kCompressParkableStringsInBackground{ "CompressParkableStringsInBackground", base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kCompressParkableStringsInForeground{ + "CompressParkableStringsInForeground", base::FEATURE_DISABLED_BY_DEFAULT}; class PLATFORM_EXPORT ParkableStringManagerDumpProvider : public base::trace_event::MemoryDumpProvider { @@ -63,6 +65,7 @@ static bool ShouldPark(const StringImpl& string); // Public for testing. + constexpr static int kAgingIntervalInSeconds = 2; constexpr static int kParkingDelayInSeconds = 10; constexpr static int kStatisticsRecordingDelayInSeconds = 30; @@ -79,18 +82,22 @@ void ParkAll(ParkableStringImpl::ParkingMode mode); void ParkAllIfRendererBackgrounded(ParkableStringImpl::ParkingMode mode); void DropStringsWithCompressedDataAndRecordStatistics(); + void AgeStringsAndPark(); + void ScheduleAgingTaskIfNeeded(); + void ResetForTesting(); ParkableStringManager(); bool backgrounded_; bool waiting_to_record_stats_; + bool has_pending_aging_task_; bool should_record_stats_; HashMap<StringImpl*, ParkableStringImpl*, PtrHash<StringImpl>> unparked_strings_; HashSet<ParkableStringImpl*, PtrHash<ParkableStringImpl>> parked_strings_; - friend class ParkableStringTest; + friend class ParkableStringTestBase; FRIEND_TEST_ALL_PREFIXES(ParkableStringTest, SynchronousCompression); DISALLOW_COPY_AND_ASSIGN(ParkableStringManager); };
diff --git a/third_party/blink/renderer/platform/bindings/parkable_string_test.cc b/third_party/blink/renderer/platform/bindings/parkable_string_test.cc index 3b278fc..5969c974 100644 --- a/third_party/blink/renderer/platform/bindings/parkable_string_test.cc +++ b/third_party/blink/renderer/platform/bindings/parkable_string_test.cc
@@ -36,9 +36,9 @@ } // namespace -class ParkableStringTest : public ::testing::Test { +class ParkableStringTestBase : public ::testing::Test { public: - ParkableStringTest() + ParkableStringTestBase() : ::testing::Test(), scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME), @@ -47,6 +47,32 @@ protected: void RunPostedTasks() { scoped_task_environment_.RunUntilIdle(); } + bool ParkAndWait(const ParkableString& string) { + bool success = + string.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways); + RunPostedTasks(); + return success; + } + + void SetUp() override { ParkableStringManager::Instance().ResetForTesting(); } + + void TearDown() override { + // No leaks. + CHECK_EQ(0u, ParkableStringManager::Instance().Size()); + // Delayed tasks may remain, clear the queues. + scoped_task_environment_.FastForwardUntilNoTasksRemain(); + RunPostedTasks(); + } + + base::test::ScopedTaskEnvironment scoped_task_environment_; + base::test::ScopedFeatureList scoped_feature_list_; +}; + +class ParkableStringTest : public ParkableStringTestBase { + public: + ParkableStringTest() : ParkableStringTestBase() {} + + protected: void WaitForDelayedParking() { scoped_task_environment_.FastForwardBy(base::TimeDelta::FromSeconds( ParkableStringManager::kParkingDelayInSeconds)); @@ -59,13 +85,6 @@ RunPostedTasks(); } - bool ParkAndWait(const ParkableString& string) { - bool return_value = - string.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways); - RunPostedTasks(); - return return_value; - } - ParkableString CreateAndParkAll() { auto& manager = ParkableStringManager::Instance(); // Checking that there are no other strings, to make sure this doesn't @@ -80,21 +99,10 @@ } void SetUp() override { - ParkableStringManager::Instance().ResetForTesting(); + ParkableStringTestBase::SetUp(); scoped_feature_list_.InitAndEnableFeature( kCompressParkableStringsInBackground); } - - void TearDown() override { - // No leaks. - CHECK_EQ(0u, ParkableStringManager::Instance().Size()); - // Delayed tasks may remain, clear the queues. - scoped_task_environment_.FastForwardUntilNoTasksRemain(); - RunPostedTasks(); - } - - base::test::ScopedTaskEnvironment scoped_task_environment_; - base::test::ScopedFeatureList scoped_feature_list_; }; // The main aim of this test is to check that the compressed size of a string @@ -184,6 +192,9 @@ EXPECT_FALSE(parkable.Impl()->is_parked()); EXPECT_TRUE( parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways)); + // Should not crash, it is allowed to call |Park()| twice in a row. + EXPECT_TRUE( + parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways)); parkable = ParkableString(); // release the reference. RunPostedTasks(); // Should not crash. } @@ -222,14 +233,22 @@ { ParkableString parkable(MakeLargeString().ReleaseImpl()); - // Transient |Lock()| or |ToString()| doesn't cancel parking. + // Transient |Lock()| or |ToString()| cancel parking. EXPECT_TRUE( parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways)); parkable.Impl()->Lock(); parkable.Impl()->ToString(); parkable.Impl()->Unlock(); RunPostedTasks(); + EXPECT_FALSE(parkable.Impl()->is_parked()); + + // In order to test synchronous parking below, need to park the string + // first. + EXPECT_TRUE( + parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways)); + RunPostedTasks(); EXPECT_TRUE(parkable.Impl()->is_parked()); + parkable.ToString(); // Synchronous parking respects locking and external references. parkable.ToString(); @@ -250,6 +269,23 @@ } } +TEST_F(ParkableStringTest, AbortedParkingRetainsCompressedData) { + ParkableString parkable(MakeLargeString().ReleaseImpl()); + EXPECT_TRUE(parkable.may_be_parked()); + EXPECT_FALSE(parkable.Impl()->is_parked()); + + EXPECT_TRUE(parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways)); + parkable.ToString(); // Cancels parking. + RunPostedTasks(); + EXPECT_FALSE(parkable.Impl()->is_parked()); + // Compressed data is not discarded. + EXPECT_TRUE(parkable.Impl()->has_compressed_data()); + + // Synchronous parking. + EXPECT_TRUE(parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways)); + EXPECT_TRUE(parkable.Impl()->is_parked()); +} + TEST_F(ParkableStringTest, Unpark) { base::HistogramTester histogram_tester; @@ -671,4 +707,164 @@ EXPECT_THAT(dump->entries(), Contains(Eq(ByRef(metadata)))); } +class ParkableStringForegroundParkingTest : public ParkableStringTestBase { + public: + ParkableStringForegroundParkingTest() : ParkableStringTestBase() {} + + protected: + void WaitForAging() { + ASSERT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + scoped_task_environment_.FastForwardBy(base::TimeDelta::FromSeconds( + ParkableStringManager::kAgingIntervalInSeconds)); + RunPostedTasks(); + } + + void SetUp() override { + ParkableStringTestBase::SetUp(); + scoped_feature_list_.InitAndEnableFeature( + kCompressParkableStringsInForeground); + } + + void TearDown() override { + while (scoped_task_environment_.MainThreadHasPendingTask()) + WaitForAging(); + + ParkableStringTestBase::TearDown(); + } +}; + +TEST_F(ParkableStringForegroundParkingTest, Aging) { + ParkableString parkable(MakeLargeString().ReleaseImpl()); + EXPECT_TRUE(parkable.Impl()->is_young()); + WaitForAging(); + EXPECT_FALSE(parkable.Impl()->is_young()); + + parkable.Lock(); + EXPECT_TRUE(parkable.Impl()->is_young()); + // Locked strings don't age. + WaitForAging(); + EXPECT_TRUE(parkable.Impl()->is_young()); + parkable.Unlock(); + WaitForAging(); + EXPECT_FALSE(parkable.Impl()->is_young()); + + parkable.ToString(); + EXPECT_TRUE(parkable.Impl()->is_young()); + // No external reference, can age again. + WaitForAging(); + EXPECT_FALSE(parkable.Impl()->is_young()); + + // External references prevent a string from aging. + String retained = parkable.ToString(); + EXPECT_TRUE(parkable.Impl()->is_young()); + WaitForAging(); + EXPECT_TRUE(parkable.Impl()->is_young()); +} + +TEST_F(ParkableStringForegroundParkingTest, OldStringsAreParked) { + ParkableString parkable(MakeLargeString().ReleaseImpl()); + EXPECT_TRUE(parkable.Impl()->is_young()); + WaitForAging(); + EXPECT_FALSE(parkable.Impl()->is_young()); + WaitForAging(); + EXPECT_TRUE(parkable.Impl()->is_parked()); + + // Unparked, two aging cycles before parking. + parkable.ToString(); + EXPECT_FALSE(parkable.Impl()->is_parked()); + WaitForAging(); + EXPECT_FALSE(parkable.Impl()->is_parked()); + WaitForAging(); + EXPECT_TRUE(parkable.Impl()->is_parked()); + + // Unparked, two consecutive no-access aging cycles before parking. + parkable.ToString(); + EXPECT_FALSE(parkable.Impl()->is_parked()); + WaitForAging(); + EXPECT_FALSE(parkable.Impl()->is_parked()); + parkable.ToString(); + WaitForAging(); + EXPECT_FALSE(parkable.Impl()->is_parked()); +} + +TEST_F(ParkableStringForegroundParkingTest, AgingTicksStopsAndRestarts) { + ParkableString parkable(MakeLargeString().ReleaseImpl()); + EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + WaitForAging(); + EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + WaitForAging(); + // Nothing more to do, the tick is not re-scheduled. + WaitForAging(); + EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + + // Unparking, the tick restarts. + parkable.ToString(); + EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + WaitForAging(); + WaitForAging(); + // And stops again. 2 ticks to park the string (age, then park), and one + // checking that there is nothing left to do. + EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + + // New string, restarting the tick, temporarily. + ParkableString parkable2(MakeLargeString().ReleaseImpl()); + WaitForAging(); + WaitForAging(); + WaitForAging(); + EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); +} + +TEST_F(ParkableStringForegroundParkingTest, AgingTicksStopsWithNoProgress) { + ParkableString parkable(MakeLargeString().ReleaseImpl()); + String retained = parkable.ToString(); + + EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + WaitForAging(); + // The only string is referenced externally, nothing aging can change. + EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + + ParkableString parkable2(MakeLargeString().ReleaseImpl()); + WaitForAging(); + EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + WaitForAging(); + EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_TRUE(parkable2.Impl()->is_parked()); + EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + WaitForAging(); + // Once |parkable2| has been parked, back to the case where the only + // remaining strings are referenced externally. + EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); +} + +TEST_F(ParkableStringForegroundParkingTest, OnlyOneAgingTask) { + ParkableString parkable1(MakeLargeString().ReleaseImpl()); + ParkableString parkable2(MakeLargeString().ReleaseImpl()); + + // Park both, and wait for the tick to stop. + WaitForAging(); + WaitForAging(); + EXPECT_TRUE(parkable1.Impl()->is_parked()); + EXPECT_TRUE(parkable2.Impl()->is_parked()); + WaitForAging(); + EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + + parkable1.ToString(); + parkable2.ToString(); + EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(1u, scoped_task_environment_.GetPendingMainThreadTaskCount()); +} + +TEST_F(ParkableStringForegroundParkingTest, AgingParkingInProgress) { + ParkableString parkable(MakeLargeString().ReleaseImpl()); + + WaitForAging(); + parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways); + // Aging should work if the string is being parked. + WaitForAging(); + // The aging task is rescheduled. + EXPECT_EQ(1u, scoped_task_environment_.GetPendingMainThreadTaskCount()); + + EXPECT_TRUE(parkable.Impl()->is_parked()); +} + } // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.h b/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.h index 4aa67917..0cde2ac65 100644 --- a/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.h +++ b/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.h
@@ -72,6 +72,10 @@ MutatorClient* client() { return client_; } + scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner() { + return host_queue_; + } + private: class OutputVectorRef; @@ -96,10 +100,6 @@ // dictionary. AnimationWorkletMutatorToTaskRunnerMap mutator_map_; - scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner() { - return host_queue_; - } - template <typename ClientType> static std::unique_ptr<ClientType> CreateClient( base::WeakPtr<AnimationWorkletMutatorDispatcherImpl>* weak_interface,
diff --git a/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc b/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc index 98b0b45..84d39b6 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc
@@ -50,21 +50,12 @@ #include "third_party/skia/include/core/SkData.h" #include "third_party/skia/include/core/SkSurface.h" -namespace { -enum { - InvalidMailboxIndex = -1, - MaxCanvasAnimationBacklog = 2, // Make sure the the GPU is never more than - // two animation frames behind. -}; -} // namespace - namespace blink { Canvas2DLayerBridge::Canvas2DLayerBridge(const IntSize& size, AccelerationMode acceleration_mode, const CanvasColorParams& color_params) : logger_(std::make_unique<Logger>()), - bytes_allocated_(0), have_recorded_draw_commands_(false), is_hidden_(false), is_deferral_enabled_(true), @@ -86,33 +77,30 @@ recorder_->getRecordingCanvas()->clear( color_params_.GetOpacityMode() == kOpaque ? SK_ColorBLACK : SK_ColorTRANSPARENT); - DidDraw(FloatRect(FloatPoint(0, 0), FloatSize(size_))); + DidDraw(FloatRect(0.f, 0.f, size_.Width(), size_.Height())); } } Canvas2DLayerBridge::~Canvas2DLayerBridge() { UMA_HISTOGRAM_BOOLEAN("Blink.Canvas.2DLayerBridgeIsDeferred", is_deferral_enabled_); - if (IsHibernating()) logger_->ReportHibernationEvent(kHibernationEndedWithTeardown); ResetResourceProvider(); - if (layer_ && acceleration_mode_ != kDisableAcceleration) { + if (!layer_) + return; + + if (acceleration_mode_ != kDisableAcceleration) { GraphicsLayer::UnregisterContentsLayer(layer_.get()); layer_->ClearTexture(); - // Orphaning the layer is required to trigger the recration of a new layer + // Orphaning the layer is required to trigger the recreation of a new layer // in the case where destruction is caused by a canvas resize. Test: // virtual/gpu/fast/canvas/canvas-resize-after-paint-without-layout.html layer_->RemoveFromParent(); } - - DCHECK(!bytes_allocated_); - - if (layer_) { - layer_->ClearClient(); - layer_ = nullptr; - } + layer_->ClearClient(); + layer_ = nullptr; } void Canvas2DLayerBridge::StartRecording() { @@ -124,21 +112,15 @@ // and clip. canvas->save(); - if (resource_host_) { + if (resource_host_) resource_host_->RestoreCanvasMatrixClipStack(canvas); - } recording_pixel_count_ = 0; } -void Canvas2DLayerBridge::SetLoggerForTesting(std::unique_ptr<Logger> logger) { - logger_ = std::move(logger); -} - void Canvas2DLayerBridge::ResetResourceProvider() { - if (resource_host_) { + if (resource_host_) resource_host_->ReplaceResourceProvider(nullptr); - } } bool Canvas2DLayerBridge::ShouldAccelerate(AccelerationHint hint) const { @@ -162,8 +144,9 @@ if (accelerate && (!context_provider_wrapper || context_provider_wrapper->ContextProvider() ->ContextGL() - ->GetGraphicsResetStatusKHR() != GL_NO_ERROR)) + ->GetGraphicsResetStatusKHR() != GL_NO_ERROR)) { accelerate = false; + } return accelerate; } @@ -304,12 +287,14 @@ AccelerationHint adjusted_hint = want_acceleration ? kPreferAcceleration : kPreferNoAcceleration; - // We call Impl directly here, to allow HTMLCanvasElement to call us - // in GetOrCreateCanvasResourceProvider. + // We call GetOrCreateCanvasResourceProviderImpl directly here to prevent a + // circular callstack from HTMLCanvasElement. resource_provider = resource_host_->GetOrCreateCanvasResourceProviderImpl(adjusted_hint); + if (!resource_provider) + return nullptr; - if (resource_provider && IsAccelerated() && !layer_) { + if (IsAccelerated() && !layer_) { layer_ = cc::TextureLayer::CreateForMailbox(this); layer_->SetIsDrawable(true); layer_->SetContentsOpaque(ColorParams().GetOpacityMode() == kOpaque); @@ -319,49 +304,46 @@ GraphicsLayer::RegisterContentsLayer(layer_.get()); } - if (resource_provider && IsHibernating()) { - if (resource_provider->IsAccelerated()) { - logger_->ReportHibernationEvent(kHibernationEndedNormally); + if (!IsHibernating()) + return resource_provider; + + if (resource_provider->IsAccelerated()) { + logger_->ReportHibernationEvent(kHibernationEndedNormally); + } else { + if (IsHidden()) { + logger_->ReportHibernationEvent( + kHibernationEndedWithSwitchToBackgroundRendering); } else { - if (IsHidden()) { - logger_->ReportHibernationEvent( - kHibernationEndedWithSwitchToBackgroundRendering); - } else { - logger_->ReportHibernationEvent(kHibernationEndedWithFallbackToSW); - } - } - - PaintFlags copy_paint; - copy_paint.setBlendMode(SkBlendMode::kSrc); - PaintImageBuilder builder = PaintImageBuilder::WithDefault(); - builder.set_image(hibernation_image_, PaintImage::GetNextContentId()); - builder.set_id(PaintImage::GetNextId()); - resource_provider->Canvas()->drawImage(builder.TakePaintImage(), 0, 0, - ©_paint); - hibernation_image_.reset(); - - if (resource_host_) { - if (!is_deferral_enabled_) { - resource_host_->RestoreCanvasMatrixClipStack( - resource_provider->Canvas()); - } - - // shouldBeDirectComposited() may have changed. - resource_host_->SetNeedsCompositingUpdate(); + logger_->ReportHibernationEvent(kHibernationEndedWithFallbackToSW); } } + PaintFlags copy_paint; + copy_paint.setBlendMode(SkBlendMode::kSrc); + PaintImageBuilder builder = PaintImageBuilder::WithDefault(); + builder.set_image(hibernation_image_, PaintImage::GetNextContentId()); + builder.set_id(PaintImage::GetNextId()); + resource_provider->Canvas()->drawImage(builder.TakePaintImage(), 0, 0, + ©_paint); + hibernation_image_.reset(); + + if (resource_host_) { + if (!is_deferral_enabled_) + resource_host_->RestoreCanvasMatrixClipStack(resource_provider->Canvas()); + + // shouldBeDirectComposited() may have changed. + resource_host_->SetNeedsCompositingUpdate(); + } return resource_provider; } cc::PaintCanvas* Canvas2DLayerBridge::Canvas() { DCHECK(resource_host_); - if (!is_deferral_enabled_) { - if (GetOrCreateResourceProvider()) - return ResourceProvider()->Canvas(); - return nullptr; - } - return recorder_->getRecordingCanvas(); + if (is_deferral_enabled_) + return recorder_->getRecordingCanvas(); + if (GetOrCreateResourceProvider()) + return ResourceProvider()->Canvas(); + return nullptr; } void Canvas2DLayerBridge::DisableDeferral(DisableDeferralReason reason) { @@ -450,9 +432,8 @@ resource_host_->ReplaceResourceProvider(std::move(old_resource_provider)); } } - if (!IsHidden() && IsHibernating()) { + if (!IsHidden() && IsHibernating()) GetOrCreateResourceProvider(); // Rude awakening - } } void Canvas2DLayerBridge::DrawFullImage(const cc::PaintImage& image) { @@ -466,6 +447,7 @@ int y) { if (!GetOrCreateResourceProvider()) return false; + if (x <= 0 && y <= 0 && x + orig_info.width() >= size_.Width() && y + orig_info.height() >= size_.Height()) { SkipQueuedDrawCommands(); @@ -477,7 +459,6 @@ ResourceProvider()->WritePixels(orig_info, pixels, row_bytes, x, y); DidDraw(FloatRect(x, y, orig_info.width(), orig_info.height())); - return true; } @@ -488,37 +469,36 @@ have_recorded_draw_commands_ = false; } - if (is_deferral_enabled_) { - if (rate_limiter_) - rate_limiter_->Reset(); - } + if (is_deferral_enabled_ && rate_limiter_) + rate_limiter_->Reset(); } void Canvas2DLayerBridge::FlushRecording() { - if (have_recorded_draw_commands_ && GetOrCreateResourceProvider()) { - TRACE_EVENT0("cc", "Canvas2DLayerBridge::flushRecording"); + if (!have_recorded_draw_commands_ || !GetOrCreateResourceProvider()) + return; - cc::PaintCanvas* canvas = ResourceProvider()->Canvas(); - { - sk_sp<PaintRecord> recording = recorder_->finishRecordingAsPicture(); - canvas->drawPicture(recording); - } + TRACE_EVENT0("cc", "Canvas2DLayerBridge::flushRecording"); - // Rastering the recording would have locked images, since we've flushed - // all recorded ops, we should relase all locked images as well. - // A new null check on the resource provider is necessary just in case - // the playback crashed the context. - if (GetOrCreateResourceProvider()) - ResourceProvider()->ReleaseLockedImages(); - - if (is_deferral_enabled_) - StartRecording(); - have_recorded_draw_commands_ = false; + cc::PaintCanvas* canvas = ResourceProvider()->Canvas(); + { + sk_sp<PaintRecord> recording = recorder_->finishRecordingAsPicture(); + canvas->drawPicture(recording); } + + // Rastering the recording would have locked images, since we've flushed + // all recorded ops, we should release all locked images as well. + // A new null check on the resource provider is necessary just in case + // the playback crashed the context. + if (GetOrCreateResourceProvider()) + ResourceProvider()->ReleaseLockedImages(); + + if (is_deferral_enabled_) + StartRecording(); + have_recorded_draw_commands_ = false; } -bool Canvas2DLayerBridge::IsValid() const { - return const_cast<Canvas2DLayerBridge*>(this)->CheckResourceProviderValid(); +bool Canvas2DLayerBridge::IsValid() { + return CheckResourceProviderValid(); } bool Canvas2DLayerBridge::CheckResourceProviderValid() { @@ -582,12 +562,10 @@ DCHECK(layer_); // This explodes if FinalizeFrame() was not called. frames_since_last_commit_ = 0; - if (rate_limiter_) { + if (rate_limiter_) rate_limiter_->Reset(); - } - // if hibernating but not hidden, we want to wake up from - // hibernation + // If hibernating but not hidden, we want to wake up from hibernation. if ((IsHibernating() || software_rendering_while_hidden_) && IsHidden()) return false; @@ -620,27 +598,27 @@ void Canvas2DLayerBridge::DidDraw(const FloatRect& rect) { if (snapshot_state_ == kDidAcquireSnapshot) snapshot_state_ = kDrawnToAfterSnapshot; - if (is_deferral_enabled_) { - have_recorded_draw_commands_ = true; - IntRect pixel_bounds = EnclosingIntRect(rect); - base::CheckedNumeric<int> pixel_bounds_size = pixel_bounds.Width(); - pixel_bounds_size *= pixel_bounds.Height(); - recording_pixel_count_ += pixel_bounds_size; - if (!recording_pixel_count_.IsValid()) { - DisableDeferral(kDisableDeferralReasonExpensiveOverdrawHeuristic); - return; - } - base::CheckedNumeric<int> threshold_size = size_.Width(); - threshold_size *= size_.Height(); - threshold_size *= canvas_heuristic_parameters::kExpensiveOverdrawThreshold; - if (!threshold_size.IsValid()) { - DisableDeferral(kDisableDeferralReasonExpensiveOverdrawHeuristic); - return; - } - if (recording_pixel_count_.ValueOrDie() >= threshold_size.ValueOrDie()) { - DisableDeferral(kDisableDeferralReasonExpensiveOverdrawHeuristic); - } + if (!is_deferral_enabled_) + return; + + have_recorded_draw_commands_ = true; + IntRect pixel_bounds = EnclosingIntRect(rect); + base::CheckedNumeric<int> pixel_bounds_size = pixel_bounds.Width(); + pixel_bounds_size *= pixel_bounds.Height(); + recording_pixel_count_ += pixel_bounds_size; + if (!recording_pixel_count_.IsValid()) { + DisableDeferral(kDisableDeferralReasonExpensiveOverdrawHeuristic); + return; } + base::CheckedNumeric<int> threshold_size = size_.Width(); + threshold_size *= size_.Height(); + threshold_size *= canvas_heuristic_parameters::kExpensiveOverdrawThreshold; + if (!threshold_size.IsValid()) { + DisableDeferral(kDisableDeferralReasonExpensiveOverdrawHeuristic); + return; + } + if (recording_pixel_count_.ValueOrDie() >= threshold_size.ValueOrDie()) + DisableDeferral(kDisableDeferralReasonExpensiveOverdrawHeuristic); } void Canvas2DLayerBridge::FinalizeFrame() { @@ -652,20 +630,18 @@ return; ++frames_since_last_commit_; - if (frames_since_last_commit_ >= 2) { ResourceProvider()->FlushSkia(); - if (IsAccelerated()) { - if (!rate_limiter_) { - rate_limiter_ = - SharedContextRateLimiter::Create(MaxCanvasAnimationBacklog); - } + if (IsAccelerated() && !rate_limiter_) { + // Make sure the GPU is never more than two animation frames behind. + constexpr unsigned kMaxCanvasAnimationBacklog = 2; + rate_limiter_ = + SharedContextRateLimiter::Create(kMaxCanvasAnimationBacklog); } } - if (rate_limiter_) { + if (rate_limiter_) rate_limiter_->Tick(); - } } void Canvas2DLayerBridge::DoPaintInvalidation(const FloatRect& dirty_rect) {
diff --git a/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.h b/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.h index 398ee687..0bfdfb2 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.h +++ b/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.h
@@ -27,6 +27,7 @@ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_CANVAS_2D_LAYER_BRIDGE_H_ #include <memory> +#include <utility> #include "base/macros.h" #include "base/memory/scoped_refptr.h" @@ -109,7 +110,7 @@ virtual bool IsAccelerated() const; cc::PaintCanvas* Canvas(); - bool IsValid() const; + bool IsValid(); bool WritePixels(const SkImageInfo&, const void* pixels, size_t row_bytes, @@ -158,13 +159,19 @@ virtual ~Logger() = default; }; - void SetLoggerForTesting(std::unique_ptr<Logger>); + void SetLoggerForTesting(std::unique_ptr<Logger> logger) { + logger_ = std::move(logger); + } CanvasResourceProvider* GetOrCreateResourceProvider( AccelerationHint = kPreferAcceleration); CanvasResourceProvider* ResourceProvider() const; void FlushRecording(); private: + friend class Canvas2DLayerBridgeTest; + friend class CanvasRenderingContext2DTest; + friend class HTMLCanvasPainterTestForCAP; + bool IsHidden() { return is_hidden_; } bool CheckResourceProviderValid(); void ResetResourceProvider(); @@ -179,24 +186,19 @@ scoped_refptr<cc::TextureLayer> layer_; std::unique_ptr<SharedContextRateLimiter> rate_limiter_; std::unique_ptr<Logger> logger_; - int msaa_sample_count_; int frames_since_last_commit_ = 0; - size_t bytes_allocated_; bool have_recorded_draw_commands_; bool is_hidden_; + // See the implementation of DisableDeferral() for more information. bool is_deferral_enabled_; bool software_rendering_while_hidden_; bool hibernation_scheduled_ = false; bool dont_use_idle_scheduling_for_testing_ = false; bool context_lost_ = false; - friend class Canvas2DLayerBridgeTest; - friend class CanvasRenderingContext2DTest; - friend class HTMLCanvasPainterTestForCAP; - - AccelerationMode acceleration_mode_; - CanvasColorParams color_params_; - IntSize size_; + const AccelerationMode acceleration_mode_; + const CanvasColorParams color_params_; + const IntSize size_; base::CheckedNumeric<int> recording_pixel_count_; enum SnapshotState {
diff --git a/third_party/blink/renderer/platform/graphics/graphics_context.cc b/third_party/blink/renderer/platform/graphics/graphics_context.cc index 4889d7f6..30a2c99 100644 --- a/third_party/blink/renderer/platform/graphics/graphics_context.cc +++ b/third_party/blink/renderer/platform/graphics/graphics_context.cc
@@ -89,11 +89,12 @@ GraphicsContext::GraphicsContext(PaintController& paint_controller, DisabledMode disable_context_or_painting, - SkMetaData* meta_data) + printing::MetafileSkia* metafile) : canvas_(nullptr), paint_controller_(paint_controller), paint_state_stack_(), paint_state_index_(0), + metafile_(metafile), #if DCHECK_IS_ON() layer_count_(0), disable_destruction_checks_(false), @@ -101,11 +102,7 @@ disabled_state_(disable_context_or_painting), device_scale_factor_(1.0f), printing_(false), - has_meta_data_(!!meta_data), in_drawing_recorder_(false) { - if (meta_data) - meta_data_ = *meta_data; - // FIXME: Do some tests to determine how many states are typically used, and // allocate several here. paint_state_stack_.push_back(GraphicsContextState::Create()); @@ -331,8 +328,8 @@ DCHECK(!canvas_); canvas_ = paint_recorder_.beginRecording(bounds); - if (has_meta_data_) - canvas_->getMetaData() = meta_data_; + if (metafile_) + canvas_->SetPrintingMetafile(metafile_); } namespace {
diff --git a/third_party/blink/renderer/platform/graphics/graphics_context.h b/third_party/blink/renderer/platform/graphics/graphics_context.h index 5712a42..af3b81cb 100644 --- a/third_party/blink/renderer/platform/graphics/graphics_context.h +++ b/third_party/blink/renderer/platform/graphics/graphics_context.h
@@ -46,7 +46,6 @@ #include "third_party/blink/renderer/platform/wtf/allocator.h" #include "third_party/blink/renderer/platform/wtf/forward.h" #include "third_party/skia/include/core/SkClipOp.h" -#include "third_party/skia/include/core/SkMetaData.h" #include "third_party/skia/include/core/SkRefCnt.h" class SkPath; @@ -74,7 +73,7 @@ explicit GraphicsContext(PaintController&, DisabledMode = kNothingDisabled, - SkMetaData* = nullptr); + printing::MetafileSkia* = nullptr); ~GraphicsContext(); @@ -455,8 +454,6 @@ const FloatRoundedRect& rounded_hole_rect, const Color&); - const SkMetaData& MetaData() const { return meta_data_; } - class HighContrastFlags; bool ShouldApplyHighContrastFilterToImage(Image&); Color ApplyHighContrastFilter(const Color& input) const; @@ -479,7 +476,7 @@ PaintRecorder paint_recorder_; - SkMetaData meta_data_; + printing::MetafileSkia* metafile_; #if DCHECK_IS_ON() int layer_count_; @@ -495,7 +492,6 @@ HighContrastImageClassifier high_contrast_image_classifier_; unsigned printing_ : 1; - unsigned has_meta_data_ : 1; unsigned in_drawing_recorder_ : 1; DISALLOW_COPY_AND_ASSIGN(GraphicsContext);
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_record_builder.cc b/third_party/blink/renderer/platform/graphics/paint/paint_record_builder.cc index 2787d1a..dd2a0c1 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_record_builder.cc +++ b/third_party/blink/renderer/platform/graphics/paint/paint_record_builder.cc
@@ -10,7 +10,7 @@ namespace blink { -PaintRecordBuilder::PaintRecordBuilder(SkMetaData* meta_data, +PaintRecordBuilder::PaintRecordBuilder(printing::MetafileSkia* metafile, GraphicsContext* containing_context, PaintController* paint_controller) : paint_controller_(nullptr) { @@ -34,7 +34,7 @@ containing_context ? &containing_context->high_contrast_settings() : nullptr; context_ = std::make_unique<GraphicsContext>(*paint_controller_, - disabled_mode, meta_data); + disabled_mode, metafile); if (high_contrast_settings) context_->SetHighContrast(*high_contrast_settings);
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_record_builder.h b/third_party/blink/renderer/platform/graphics/paint/paint_record_builder.h index 22c5527..cf06d563 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_record_builder.h +++ b/third_party/blink/renderer/platform/graphics/paint/paint_record_builder.h
@@ -15,8 +15,6 @@ #include "third_party/blink/renderer/platform/platform_export.h" #include "third_party/skia/include/core/SkRefCnt.h" -class SkMetaData; - namespace cc { class PaintCanvas; } @@ -39,7 +37,7 @@ // PropertyTreeState::Root() before beginning to record. // TODO(wangxianzhu): Remove the input PaintController feature for // CompositeAfterPaint. - PaintRecordBuilder(SkMetaData* metadata = nullptr, + PaintRecordBuilder(printing::MetafileSkia* metafile = nullptr, GraphicsContext* containing_context = nullptr, PaintController* = nullptr); ~PaintRecordBuilder() override;
diff --git a/third_party/blink/renderer/platform/graphics/test/mock_paint_canvas.h b/third_party/blink/renderer/platform/graphics/test/mock_paint_canvas.h index dc1227c62..8dcbe94ac 100644 --- a/third_party/blink/renderer/platform/graphics/test/mock_paint_canvas.h +++ b/third_party/blink/renderer/platform/graphics/test/mock_paint_canvas.h
@@ -9,7 +9,6 @@ #include "testing/gmock/include/gmock/gmock.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_flags.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_image.h" -#include "third_party/skia/include/core/SkMetaData.h" namespace cc { class SkottieWrapper; @@ -19,7 +18,6 @@ class MockPaintCanvas : public cc::PaintCanvas { public: - MOCK_METHOD0(getMetaData, SkMetaData&()); MOCK_CONST_METHOD0(imageInfo, SkImageInfo()); MOCK_METHOD0(flush, void()); MOCK_METHOD0(save, int()); @@ -103,6 +101,8 @@ void(AnnotationType type, const SkRect& rect, sk_sp<SkData> data)); + MOCK_METHOD0(GetPrintingMetafile, printing::MetafileSkia*()); + MOCK_METHOD1(SetPrintingMetafile, void(printing::MetafileSkia*)); }; } // 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 ec139f2b..ef0a80ad 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -788,9 +788,6 @@ name: "MediaQueryPrefersColorScheme", }, { - name: "MediaQueryPrefersReducedMotion", - }, - { name: "MediaQueryShape", status: "experimental", },
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.cc b/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.cc index 193328f..1a485e0f7 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.cc
@@ -412,7 +412,6 @@ // TODO(nhiroki): Throttle them again after we're convinced that it's safe // or provide a mechanism that web pages can opt-out it if throttling is not // desirable. - case TaskType::kDatabaseAccess: case TaskType::kDOMManipulation: case TaskType::kHistoryTraversal: case TaskType::kEmbed: @@ -445,8 +444,8 @@ // Media events should not be deferred to ensure that media playback is // smooth. case TaskType::kMediaElementEvent: + case TaskType::kDatabaseAccess: case TaskType::kInternalWebCrypto: - case TaskType::kInternalIndexedDB: case TaskType::kInternalMedia: case TaskType::kInternalMediaRealTime: case TaskType::kInternalUserInteraction:
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl_unittest.cc b/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl_unittest.cc index b6e906d..1b48b5ea5 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl_unittest.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl_unittest.cc
@@ -1598,7 +1598,8 @@ // expected. This test will fail if these task types are moved to different // default queues. EXPECT_EQ(GetTaskQueue(TaskType::kJavascriptTimer), ThrottleableTaskQueue()); - EXPECT_EQ(GetTaskQueue(TaskType::kDatabaseAccess), DeferrableTaskQueue()); + EXPECT_EQ(GetTaskQueue(TaskType::kWebSocket), DeferrableTaskQueue()); + EXPECT_EQ(GetTaskQueue(TaskType::kDatabaseAccess), PausableTaskQueue()); EXPECT_EQ(GetTaskQueue(TaskType::kPostedMessage), PausableTaskQueue()); EXPECT_EQ(GetTaskQueue(TaskType::kInternalIPC), UnpausableTaskQueue()); EXPECT_EQ(GetTaskQueue(TaskType::kNetworking), LoadingTaskQueue()); @@ -1638,8 +1639,7 @@ : ThrottleAndFreezeTaskTypesExperimentTest( std::map<std::string, std::string>{ // Leading spaces are allowed. - {kThrottleableTaskTypesListParam, - "PostedMessage, DatabaseAccess"}, + {kThrottleableTaskTypesListParam, "PostedMessage"}, {kFreezableTaskTypesListParam, "PostedMessage, MediaElementEvent,DOMManipulation"}}, "Group1") {} @@ -1663,10 +1663,9 @@ task_queue->GetQueueTraits(), MainThreadTaskQueue::QueueTraits().SetCanBeFrozen(true).SetCanBePaused( true)); + task_queue = GetTaskQueue(TaskType::kDatabaseAccess); EXPECT_EQ(task_queue->GetQueueTraits(), MainThreadTaskQueue::QueueTraits() - .SetCanBeThrottled(true) - .SetCanBeDeferred(true) .SetCanBePaused(true)); task_queue = GetTaskQueue(TaskType::kDOMManipulation); @@ -1680,10 +1679,6 @@ task_queue = GetTaskQueue(TaskType::kInternalIPC); EXPECT_EQ(task_queue->GetQueueTraits(), MainThreadTaskQueue::QueueTraits()); - task_queue = GetTaskQueue(TaskType::kInternalIndexedDB); - EXPECT_EQ(task_queue->GetQueueTraits(), - MainThreadTaskQueue::QueueTraits().SetCanBePaused(true)); - task_queue = GetTaskQueue(TaskType::kMiscPlatformAPI); EXPECT_EQ( task_queue->GetQueueTraits(), @@ -1724,10 +1719,8 @@ true)); task_queue = GetTaskQueue(TaskType::kDatabaseAccess); - EXPECT_EQ( - task_queue->GetQueueTraits(), - MainThreadTaskQueue::QueueTraits().SetCanBeDeferred(true).SetCanBePaused( - true)); + EXPECT_EQ(task_queue->GetQueueTraits(), + MainThreadTaskQueue::QueueTraits().SetCanBePaused(true)); task_queue = GetTaskQueue(TaskType::kDOMManipulation); EXPECT_EQ(task_queue->GetQueueTraits(), MainThreadTaskQueue::QueueTraits() @@ -1740,10 +1733,6 @@ task_queue = GetTaskQueue(TaskType::kInternalIPC); EXPECT_EQ(task_queue->GetQueueTraits(), MainThreadTaskQueue::QueueTraits()); - task_queue = GetTaskQueue(TaskType::kInternalIndexedDB); - EXPECT_EQ(task_queue->GetQueueTraits(), - MainThreadTaskQueue::QueueTraits().SetCanBePaused(true)); - task_queue = GetTaskQueue(TaskType::kMiscPlatformAPI); EXPECT_EQ( task_queue->GetQueueTraits(), @@ -1758,8 +1747,7 @@ : ThrottleAndFreezeTaskTypesExperimentTest( std::map<std::string, std::string>{ {kFreezableTaskTypesListParam, ""}, - {kThrottleableTaskTypesListParam, - "PostedMessage,DatabaseAccess"}}, + {kThrottleableTaskTypesListParam, "PostedMessage"}}, "Group3") {} }; @@ -1783,8 +1771,6 @@ task_queue = GetTaskQueue(TaskType::kDatabaseAccess); EXPECT_EQ(task_queue->GetQueueTraits(), MainThreadTaskQueue::QueueTraits() - .SetCanBeThrottled(true) - .SetCanBeDeferred(true) .SetCanBePaused(true)); task_queue = GetTaskQueue(TaskType::kDOMManipulation); @@ -1798,10 +1784,6 @@ task_queue = GetTaskQueue(TaskType::kInternalIPC); EXPECT_EQ(task_queue->GetQueueTraits(), MainThreadTaskQueue::QueueTraits()); - task_queue = GetTaskQueue(TaskType::kInternalIndexedDB); - EXPECT_EQ(task_queue->GetQueueTraits(), - MainThreadTaskQueue::QueueTraits().SetCanBePaused(true)); - task_queue = GetTaskQueue(TaskType::kMiscPlatformAPI); EXPECT_EQ( task_queue->GetQueueTraits(),
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.cc b/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.cc index e044c7d..cc2ef10 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.cc
@@ -252,8 +252,8 @@ page_lifecycle_state_tracker_->SetPageLifecycleState( PageLifecycleState::kHiddenForegrounded); } + Platform::Current()->SetMemoryPressureNotificationsSuppressed(false); } - Platform::Current()->SetMemoryPressureNotificationsSuppressed(frozen); } void PageSchedulerImpl::SetKeepActive(bool keep_active) {
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/task_type_names.cc b/third_party/blink/renderer/platform/scheduler/main_thread/task_type_names.cc index 66916aa..ba300e04 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/task_type_names.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/task_type_names.cc
@@ -83,8 +83,6 @@ return "InternalTest"; case TaskType::kInternalWebCrypto: return "InternalWebCrypto"; - case TaskType::kInternalIndexedDB: - return "InternalIndexedDB"; case TaskType::kInternalMedia: return "InternalMedia"; case TaskType::kInternalMediaRealTime:
diff --git a/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler.cc b/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler.cc index d3e0a98..ab90e8e 100644 --- a/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler.cc +++ b/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler.cc
@@ -157,7 +157,6 @@ case TaskType::kInternalDefault: case TaskType::kInternalLoading: case TaskType::kInternalWebCrypto: - case TaskType::kInternalIndexedDB: case TaskType::kInternalMedia: case TaskType::kInternalMediaRealTime: case TaskType::kInternalUserInteraction:
diff --git a/third_party/blink/renderer/platform/testing/image_decode_bench.cc b/third_party/blink/renderer/platform/testing/image_decode_bench.cc index 7edc57f..dcece3b 100644 --- a/third_party/blink/renderer/platform/testing/image_decode_bench.cc +++ b/third_party/blink/renderer/platform/testing/image_decode_bench.cc
@@ -16,6 +16,7 @@ // using the image corpora used to assess Blink image decode performance. See // http://crbug.com/398235#c103 and http://crbug.com/258324#c5 +#include <chrono> #include <fstream> #include "base/command_line.h" @@ -26,7 +27,6 @@ #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/platform/image-decoders/image_decoder.h" #include "third_party/blink/renderer/platform/shared_buffer.h" -#include "third_party/blink/renderer/platform/wtf/time.h" namespace blink { @@ -62,7 +62,7 @@ data, all_data_received, ImageDecoder::kAlphaPremultiplied, ImageDecoder::kDefaultBitDepth, ColorBehavior::Ignore()); - auto start = CurrentTimeTicks(); + auto start = std::chrono::steady_clock::now(); decoder->SetData(data, all_data_received); size_t frame_count = decoder->FrameCount(); @@ -71,11 +71,12 @@ DecodeFailure(image); } - image->time += (CurrentTimeTicks() - start).InSecondsF(); + auto end = std::chrono::steady_clock::now(); if (!frame_count || decoder->Failed()) DecodeFailure(image); + image->time += std::chrono::duration<double>(end - start).count(); image->width = decoder->Size().Width(); image->height = decoder->Size().Height(); image->frames = frame_count;
diff --git a/third_party/blink/renderer/platform/wtf/threading.h b/third_party/blink/renderer/platform/wtf/threading.h index ad6c743b..89c3a1e 100644 --- a/third_party/blink/renderer/platform/wtf/threading.h +++ b/third_party/blink/renderer/platform/wtf/threading.h
@@ -40,10 +40,6 @@ namespace WTF { -// Initializes global state required by |currentThread|. -// Needs to be called once during program execution, before |currentThread|. -WTF_EXPORT void InitializeCurrentThread(); - WTF_EXPORT base::PlatformThreadId CurrentThread(); #if DCHECK_IS_ON()
diff --git a/third_party/blink/web_tests/FlagExpectations/enable-blink-features=LayoutNG b/third_party/blink/web_tests/FlagExpectations/enable-blink-features=LayoutNG index ca32327a..bcd4902 100644 --- a/third_party/blink/web_tests/FlagExpectations/enable-blink-features=LayoutNG +++ b/third_party/blink/web_tests/FlagExpectations/enable-blink-features=LayoutNG
@@ -262,7 +262,7 @@ crbug.com/591099 external/wpt/fetch/api/redirect/redirect-count.any.worker.html [ Pass ] crbug.com/591099 external/wpt/fetch/api/request/request-keepalive-quota.html?include=slow-2 [ Pass ] crbug.com/591099 external/wpt/fullscreen/api/element-ready-check-containing-iframe-manual.html [ Pass ] -crbug.com/591099 external/wpt/geolocation-API/PositionOptions.https.html [ Failure Pass ] +crbug.com/591099 external/wpt/geolocation-API/PositionOptions.https.html [ Failure ] crbug.com/591099 external/wpt/html/browsers/origin/cross-origin-objects/cross-origin-objects.html [ Pass ] crbug.com/591099 external/wpt/html/browsers/the-window-object/window-open-noopener.html?_parent [ Pass ] crbug.com/591099 external/wpt/html/browsers/the-window-object/window-open-noopener.html?_top [ Pass ] @@ -298,6 +298,7 @@ crbug.com/591099 fast/writing-mode/auto-sizing-orthogonal-flows.html [ Failure ] crbug.com/591099 fast/writing-mode/percentage-height-orthogonal-writing-modes.html [ Failure ] crbug.com/591099 fast/writing-mode/table-percent-width-quirk.html [ Pass ] +crbug.com/591099 http/tests/devtools/elements/highlight/highlight-css-grid.js [ Failure ] crbug.com/927467 http/tests/devtools/elements/navigate-styles-sidebar-with-arrow-keys.js [ Crash ] crbug.com/927467 http/tests/devtools/elements/styles-1/commit-selector.js [ Crash ] crbug.com/927467 http/tests/devtools/elements/styles-3/styles-disable-property-after-selector-edit.js [ Crash ] @@ -345,7 +346,11 @@ crbug.com/824918 virtual/layout_ng_experimental/ [ Skip ] crbug.com/591099 virtual/mouseevent_fractional/fast/events/touch/compositor-touch-hit-rects-continuation.html [ Failure ] crbug.com/591099 virtual/new-remote-playback-pipeline/ [ Skip ] -crbug.com/591099 virtual/not-site-per-process/http/tests/devtools/isolated-code-cache/same-origin-test.js [ Failure Pass ] +crbug.com/591099 virtual/not-site-per-process/http/tests/devtools/isolated-code-cache/same-origin-test.js [ Pass ] +crbug.com/591099 virtual/omt-worker-fetch/external/wpt/referrer-policy/no-referrer/http-rp/same-origin/http-http/shared-worker/keep-origin-redirect/generic.http.html [ Pass ] +crbug.com/591099 virtual/omt-worker-fetch/external/wpt/referrer-policy/no-referrer/http-rp/same-origin/http-http/shared-worker/no-redirect/generic.http.html [ Pass ] +crbug.com/591099 virtual/omt-worker-fetch/external/wpt/referrer-policy/no-referrer/meta-referrer/same-origin/http-http/shared-worker/keep-origin-redirect/generic.http.html [ Pass ] +crbug.com/591099 virtual/omt-worker-fetch/external/wpt/referrer-policy/no-referrer/meta-referrer/same-origin/http-http/shared-worker/no-redirect/generic.http.html [ Pass ] crbug.com/591099 virtual/outofblink-cors-ns/external/wpt/fetch/api/redirect/redirect-count.any.html [ Pass ] crbug.com/591099 virtual/outofblink-cors-ns/external/wpt/fetch/api/redirect/redirect-count.any.worker.html [ Pass ] crbug.com/591099 virtual/outofblink-cors-ns/external/wpt/fetch/api/request/request-keepalive-quota.html?include=slow-2 [ Pass ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 29b9717..ce40db9 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -5256,12 +5256,6 @@ # Sheriff 2018-06-11 crbug.com/850202 [ Linux ] http/tests/devtools/network/network-filters.js [ Pass Failure Timeout ] -# Disable tests temporarily while waiting for -# https://github.com/web-platform-tests/wpt/pull/14867 to land. -crbug.com/922195 external/wpt/longtask-timing/supported-longtask-types.any.worker.html [ Failure ] -crbug.com/922195 external/wpt/navigation-timing/supported_navigation_type.any.worker.html [ Failure ] -crbug.com/922195 virtual/paint-timing/external/wpt/paint-timing/supported-paint-type.any.worker.html [ Failure ] - crbug.com/853360 [ Mac ] fast/css/input-search-padding.html [ Failure ] crbug.com/853360 [ Mac ] fast/forms/calendar-picker/calendar-picker-appearance-ar.html [ Failure ] crbug.com/853360 [ Mac ] fast/forms/calendar-picker/calendar-picker-appearance-minimum-date.html [ Failure ] @@ -6042,3 +6036,7 @@ # Recently became flaky on multiple platforms (Linux and Windows primarily) crbug.com/927769 fast/webgl/OffscreenCanvas-webgl-preserveDrawingBuffer.html [ Skip ] + +# Sheriff 2019-02-06 +crbug.com/929122 [ Linux ] external/wpt/html/dom/interfaces.worker.html [ Timeout Failure ] +crbug.com/929355 [ Linux ] external/wpt/webrtc/RTCPeerConnection-track-stats.https.html [ Failure ]
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_5.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_5.json index 9f0c2c00..7ce3e4c 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_5.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_5.json
@@ -186004,6 +186004,46 @@ {} ] ], + "streams/readable-streams/async-iterator.any-expected.txt": [ + [ + {} + ] + ], + "streams/readable-streams/async-iterator.any.serviceworker-expected.txt": [ + [ + {} + ] + ], + "streams/readable-streams/async-iterator.any.sharedworker-expected.txt": [ + [ + {} + ] + ], + "streams/readable-streams/async-iterator.any.worker-expected.txt": [ + [ + {} + ] + ], + "streams/readable-streams/brand-checks.any-expected.txt": [ + [ + {} + ] + ], + "streams/readable-streams/brand-checks.any.serviceworker-expected.txt": [ + [ + {} + ] + ], + "streams/readable-streams/brand-checks.any.sharedworker-expected.txt": [ + [ + {} + ] + ], + "streams/readable-streams/brand-checks.any.worker-expected.txt": [ + [ + {} + ] + ], "streams/readable-streams/general.any-expected.txt": [ [ {} @@ -186024,6 +186064,26 @@ {} ] ], + "streams/readable-streams/patched-global.any-expected.txt": [ + [ + {} + ] + ], + "streams/readable-streams/patched-global.any.serviceworker-expected.txt": [ + [ + {} + ] + ], + "streams/readable-streams/patched-global.any.sharedworker-expected.txt": [ + [ + {} + ] + ], + "streams/readable-streams/patched-global.any.worker-expected.txt": [ + [ + {} + ] + ], "streams/resources/constructor-ordering.js": [ [ {} @@ -279380,6 +279440,30 @@ {} ] ], + "streams/readable-streams/async-iterator.any.js": [ + [ + "/streams/readable-streams/async-iterator.any.html", + {} + ], + [ + "/streams/readable-streams/async-iterator.any.js", + { + "jsshell": true + } + ], + [ + "/streams/readable-streams/async-iterator.any.serviceworker.html", + {} + ], + [ + "/streams/readable-streams/async-iterator.any.sharedworker.html", + {} + ], + [ + "/streams/readable-streams/async-iterator.any.worker.html", + {} + ] + ], "streams/readable-streams/bad-strategies.any.js": [ [ "/streams/readable-streams/bad-strategies.any.html", @@ -392960,7 +393044,7 @@ "support" ], "domparsing/XMLSerializer-serializeToString.html": [ - "8ee4aa486f63674831842c5c4e5aceaec7e2d491", + "7c084e78ded7258eaf7f9576d6f837f9518b862f", "testharness" ], "domparsing/createContextualFragment.html": [ @@ -449671,6 +449755,26 @@ "83c737bef4a9018ba1b6298fe7eb0e3c3dc38119", "support" ], + "streams/readable-streams/async-iterator.any-expected.txt": [ + "53fe193b1ea3943662e890a2b9bcbfcfc9aaa718", + "support" + ], + "streams/readable-streams/async-iterator.any.js": [ + "c59cbeb682018991692b3d2f443b7ca2da38a94e", + "testharness" + ], + "streams/readable-streams/async-iterator.any.serviceworker-expected.txt": [ + "53fe193b1ea3943662e890a2b9bcbfcfc9aaa718", + "support" + ], + "streams/readable-streams/async-iterator.any.sharedworker-expected.txt": [ + "53fe193b1ea3943662e890a2b9bcbfcfc9aaa718", + "support" + ], + "streams/readable-streams/async-iterator.any.worker-expected.txt": [ + "53fe193b1ea3943662e890a2b9bcbfcfc9aaa718", + "support" + ], "streams/readable-streams/bad-strategies.any.js": [ "5dab51ef771ee48e537a5f9a9f8cb7514d411797", "testharness" @@ -449679,10 +449783,26 @@ "cde5603f2403452576e4d01426f277921082bcd3", "testharness" ], + "streams/readable-streams/brand-checks.any-expected.txt": [ + "8c91f96bc3d162f7aba979787934e29180769292", + "support" + ], "streams/readable-streams/brand-checks.any.js": [ - "2906494bdf6b378d07f6fbb916a8f6cb63681b63", + "521e4360667b96dae29ce225e374d5c665004bc9", "testharness" ], + "streams/readable-streams/brand-checks.any.serviceworker-expected.txt": [ + "8c91f96bc3d162f7aba979787934e29180769292", + "support" + ], + "streams/readable-streams/brand-checks.any.sharedworker-expected.txt": [ + "8c91f96bc3d162f7aba979787934e29180769292", + "support" + ], + "streams/readable-streams/brand-checks.any.worker-expected.txt": [ + "8c91f96bc3d162f7aba979787934e29180769292", + "support" + ], "streams/readable-streams/cancel.any.js": [ "75bd9c7ab24e9b24792df3f0bd520baca83ab419", "testharness" @@ -449708,29 +449828,45 @@ "testharness" ], "streams/readable-streams/general.any-expected.txt": [ - "6cc846a00e4c8154673595e380cb90416e9c0dd2", + "41a7590e863fd11382c6b13cf767968221a74ede", "support" ], "streams/readable-streams/general.any.js": [ - "f885ed6dbcdc6983ce1a52f60af492e875503d03", + "e9a107db1a36964044eb53a18ea53105140d0f42", "testharness" ], "streams/readable-streams/general.any.serviceworker-expected.txt": [ - "6cc846a00e4c8154673595e380cb90416e9c0dd2", + "41a7590e863fd11382c6b13cf767968221a74ede", "support" ], "streams/readable-streams/general.any.sharedworker-expected.txt": [ - "6cc846a00e4c8154673595e380cb90416e9c0dd2", + "41a7590e863fd11382c6b13cf767968221a74ede", "support" ], "streams/readable-streams/general.any.worker-expected.txt": [ - "6cc846a00e4c8154673595e380cb90416e9c0dd2", + "41a7590e863fd11382c6b13cf767968221a74ede", + "support" + ], + "streams/readable-streams/patched-global.any-expected.txt": [ + "95f34fb921ca5b3d8bd8b501e257c94d6844ca43", "support" ], "streams/readable-streams/patched-global.any.js": [ - "fa49249a9b5e78548892d6405460b88eb6e68361", + "500979f5b37ad1af106fcbb76ca531d4dc539129", "testharness" ], + "streams/readable-streams/patched-global.any.serviceworker-expected.txt": [ + "95f34fb921ca5b3d8bd8b501e257c94d6844ca43", + "support" + ], + "streams/readable-streams/patched-global.any.sharedworker-expected.txt": [ + "95f34fb921ca5b3d8bd8b501e257c94d6844ca43", + "support" + ], + "streams/readable-streams/patched-global.any.worker-expected.txt": [ + "95f34fb921ca5b3d8bd8b501e257c94d6844ca43", + "support" + ], "streams/readable-streams/reentrant-strategies.any.js": [ "7724ea63d3747e4fdf8dcd418889d3c2160d8036", "testharness"
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transitions/event-dispatch.tentative-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-transitions/event-dispatch.tentative-expected.txt index 9a36521e..4a1fd79 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transitions/event-dispatch.tentative-expected.txt +++ b/third_party/blink/web_tests/external/wpt/css/css-transitions/event-dispatch.tentative-expected.txt
@@ -3,15 +3,15 @@ PASS Idle -> Before PASS Idle or Pending -> Active PASS Idle or Pending -> After -FAIL Before -> Idle (display: none) assert_true: Timed out waiting for transitioncancel expected true got false +PASS Before -> Idle (display: none) FAIL Before -> Idle (Animation.timeline = null) promise_test: Unhandled rejection with value: object "TypeError: Cannot assign to read only property 'timeline' of object '#<Animation>'" PASS Before -> Active PASS Before -> After -FAIL Active -> Idle, no delay (display: none) assert_true: Timed out waiting for transitioncancel expected true got false +PASS Active -> Idle, no delay (display: none) FAIL Active -> Idle, no delay (Animation.timeline = null) promise_test: Unhandled rejection with value: object "TypeError: Cannot assign to read only property 'timeline' of object '#<Animation>'" -FAIL Active -> Idle, with positive delay (display: none) assert_true: Timed out waiting for transitioncancel expected true got false +PASS Active -> Idle, with positive delay (display: none) FAIL Active -> Idle, with positive delay (Animation.timeline = null) promise_test: Unhandled rejection with value: object "TypeError: Cannot assign to read only property 'timeline' of object '#<Animation>'" -FAIL Active -> Idle, with negative delay (display: none) assert_true: Timed out waiting for transitioncancel expected true got false +PASS Active -> Idle, with negative delay (display: none) FAIL Active -> Idle, with negative delay (Animation.timeline = null) promise_test: Unhandled rejection with value: object "TypeError: Cannot assign to read only property 'timeline' of object '#<Animation>'" PASS Active -> Before PASS Active -> After @@ -19,11 +19,11 @@ PASS After -> Active PASS Calculating the interval start and end time with negative start delay. FAIL Calculating the interval start and end time with negative end delay. assert_true: Timed out waiting for transitioncancel, transitionrun, transitionstart expected true got false -FAIL Call Animation.cancel after canceling transition. assert_true: Timed out waiting for transitioncancel expected true got false +PASS Call Animation.cancel after canceling transition. FAIL Restart transition after canceling transition immediately assert_true: Timed out waiting for transitioncancel, transitionrun expected true got false -FAIL Call Animation.cancel after restarting transition immediately assert_true: Timed out waiting for transitioncancel expected true got false +PASS Call Animation.cancel after restarting transition immediately FAIL Set timeline and play transition after clear the timeline promise_test: Unhandled rejection with value: object "TypeError: Cannot assign to read only property 'timeline' of object '#<Animation>'" -FAIL Set null target effect after canceling the transition assert_true: Timed out waiting for transitioncancel expected true got false +PASS Set null target effect after canceling the transition FAIL Cancel the transition after clearing the target effect assert_true: Timed out waiting for transitionend expected true got false Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transitions/transitioncancel-001-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-transitions/transitioncancel-001-expected.txt deleted file mode 100644 index d5f00951..0000000 --- a/third_party/blink/web_tests/external/wpt/css/css-transitions/transitioncancel-001-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This is a testharness.js-based test. -FAIL transitioncancel should be fired if the element is made display:none during the transition assert_true: transitioncancel event did fire expected true got false -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/css/mediaqueries/prefers-reduced-motion-expected.txt b/third_party/blink/web_tests/external/wpt/css/mediaqueries/prefers-reduced-motion-expected.txt deleted file mode 100644 index 00fbe2ce..0000000 --- a/third_party/blink/web_tests/external/wpt/css/mediaqueries/prefers-reduced-motion-expected.txt +++ /dev/null
@@ -1,22 +0,0 @@ -This is a testharness.js-based test. -FAIL Should be parseable in a CSS stylesheet: '(prefers-reduced-motion)' assert_true: expected true got false -FAIL Should be parseable in a CSS stylesheet: '(prefers-reduced-motion: no-preference)' assert_true: expected true got false -FAIL Should be parseable in a CSS stylesheet: '(prefers-reduced-motion: reduce)' assert_true: expected true got false -PASS Should not be parseable in a CSS stylesheet: '(prefers-reduced-motion: 0)' -PASS Should not be parseable in a CSS stylesheet: '(prefers-reduced-motion: none)' -PASS Should not be parseable in a CSS stylesheet: '(prefers-reduced-motion: 10px)' -PASS Should not be parseable in a CSS stylesheet: '(prefers-reduced-motion: no-preference reduce)' -PASS Should not be parseable in a CSS stylesheet: '(prefers-reduced-motion: reduced)' -PASS Should not be parseable in a CSS stylesheet: '(prefers-reduced-motion: no-preference/reduce)' -FAIL Should be parseable in JS: '(prefers-reduced-motion)' assert_true: expected true got false -FAIL Should be parseable in JS: '(prefers-reduced-motion: no-preference)' assert_true: expected true got false -FAIL Should be parseable in JS: '(prefers-reduced-motion: reduce)' assert_true: expected true got false -PASS Should not be parseable in JS: '(prefers-reduced-motion: 0)' -PASS Should not be parseable in JS: '(prefers-reduced-motion: none)' -PASS Should not be parseable in JS: '(prefers-reduced-motion: 10px)' -PASS Should not be parseable in JS: '(prefers-reduced-motion: no-preference reduce)' -PASS Should not be parseable in JS: '(prefers-reduced-motion: reduced)' -PASS Should not be parseable in JS: '(prefers-reduced-motion: no-preference/reduce)' -FAIL Check that no-preference evaluates to false in the boolean context assert_equals: expected true but got false -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/longtask-timing/supported-longtask-types.any.js b/third_party/blink/web_tests/external/wpt/longtask-timing/supported-longtask-types.window.js similarity index 100% rename from third_party/blink/web_tests/external/wpt/longtask-timing/supported-longtask-types.any.js rename to third_party/blink/web_tests/external/wpt/longtask-timing/supported-longtask-types.window.js
diff --git a/third_party/blink/web_tests/external/wpt/navigation-timing/supported_navigation_type.any.js b/third_party/blink/web_tests/external/wpt/navigation-timing/supported_navigation_type.window.js similarity index 100% rename from third_party/blink/web_tests/external/wpt/navigation-timing/supported_navigation_type.any.js rename to third_party/blink/web_tests/external/wpt/navigation-timing/supported_navigation_type.window.js
diff --git a/third_party/blink/web_tests/external/wpt/paint-timing/idlharness.window.js b/third_party/blink/web_tests/external/wpt/paint-timing/idlharness.window.js index 115af73..049f0f1 100644 --- a/third_party/blink/web_tests/external/wpt/paint-timing/idlharness.window.js +++ b/third_party/blink/web_tests/external/wpt/paint-timing/idlharness.window.js
@@ -19,6 +19,9 @@ resolve(); }); observer.observe({ entryTypes: ['paint'] }); + const div = document.createElement('div'); + div.innerHTML = 'Hello World'; + document.body.appendChild(div); }); const timeout = new Promise((_, reject) => { t.step_timeout(() => reject('Timed out waiting for paint event'), 3000);
diff --git a/third_party/blink/web_tests/external/wpt/paint-timing/supported-paint-type.any.js b/third_party/blink/web_tests/external/wpt/paint-timing/supported-paint-type.window.js similarity index 100% rename from third_party/blink/web_tests/external/wpt/paint-timing/supported-paint-type.any.js rename to third_party/blink/web_tests/external/wpt/paint-timing/supported-paint-type.window.js
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/async-iterator.any-expected.txt b/third_party/blink/web_tests/external/wpt/streams/readable-streams/async-iterator.any-expected.txt new file mode 100644 index 0000000..53fe193b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/async-iterator.any-expected.txt
@@ -0,0 +1,27 @@ +This is a testharness.js-based test. +PASS @@asyncIterator() method is === to getIterator() method +FAIL Async iterator instances should have the correct list of properties s.getIterator is not a function +FAIL Async-iterating a push source promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Async-iterating a pull source promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Async-iterating a pull source manually promise_test: Unhandled rejection with value: object "TypeError: s.getIterator is not a function" +FAIL Async-iterating an errored stream throws assert_equals: expected (string) "e" but got (object) object "TypeError: s is not async iterable" +FAIL Async-iterating a closed stream never executes the loop body, but works fine promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Async-iterating an empty but not closed/errored stream never executes the loop body and stalls the async function promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Async-iterating a partially consumed stream promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Cancellation behavior when throwing inside loop body; preventCancel = false assert_array_equals: cancel() should be called lengths differ, expected 3 got 0 +FAIL Cancellation behavior when throwing inside loop body; preventCancel = true assert_array_equals: cancel() should not be called lengths differ, expected 1 got 0 +FAIL Cancellation behavior when breaking inside loop body; preventCancel = false assert_array_equals: cancel() should be called lengths differ, expected 3 got 0 +FAIL Cancellation behavior when breaking inside loop body; preventCancel = true assert_array_equals: cancel() should not be called lengths differ, expected 1 got 0 +FAIL Cancellation behavior when returning inside loop body; preventCancel = false assert_array_equals: cancel() should be called lengths differ, expected 3 got 0 +FAIL Cancellation behavior when returning inside loop body; preventCancel = true assert_array_equals: cancel() should not be called lengths differ, expected 1 got 0 +FAIL Cancellation behavior when manually calling return(); preventCancel = false promise_test: Unhandled rejection with value: object "TypeError: s.getIterator is not a function" +FAIL Cancellation behavior when manually calling return(); preventCancel = true promise_test: Unhandled rejection with value: object "TypeError: s.getIterator is not a function" +FAIL Calling return() twice rejects promise_test: Unhandled rejection with value: object "TypeError: s[Symbol.asyncIterator] is not a function" +FAIL next()'s fulfillment value has the right shape promise_test: Unhandled rejection with value: object "TypeError: s[Symbol.asyncIterator] is not a function" +FAIL calling return() while there are pending reads rejects promise_test: Unhandled rejection with value: object "TypeError: s[Symbol.asyncIterator] is not a function" +FAIL getIterator() throws if there's already a lock s.getIterator is not a function +FAIL Acquiring a reader after exhaustively async-iterating a stream promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Acquiring a reader after partially async-iterating a stream promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Acquiring a reader and reading the remaining chunks after partially async-iterating a stream with preventCancel = true promise_test: Unhandled rejection with value: object "TypeError: s.getIterator(...) is not a function or its return value is not async iterable" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/async-iterator.any.js b/third_party/blink/web_tests/external/wpt/streams/readable-streams/async-iterator.any.js new file mode 100644 index 0000000..c59cbeb6 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/async-iterator.any.js
@@ -0,0 +1,340 @@ +// META: global=worker,jsshell +// META: script=../resources/rs-utils.js +// META: script=../resources/test-utils.js +// META: script=../resources/recording-streams.js +'use strict'; + +test(() => { + assert_equals(ReadableStream.prototype[Symbol.asyncIterator], ReadableStream.prototype.getIterator); +}, '@@asyncIterator() method is === to getIterator() method'); + +test(() => { + const s = new ReadableStream(); + const it = s.getIterator(); + const proto = Object.getPrototypeOf(it); + + const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}).prototype); + assert_equals(Object.getPrototypeOf(proto), AsyncIteratorPrototype, 'prototype should extend AsyncIteratorPrototype'); + + const methods = ['next', 'return'].sort(); + assert_array_equals(Object.getOwnPropertyNames(proto).sort(), methods, 'should have all the correct methods'); + + for (const m of methods) { + const propDesc = Object.getOwnPropertyDescriptor(proto, m); + assert_false(propDesc.enumerable, 'method should be non-enumerable'); + assert_true(propDesc.configurable, 'method should be configurable'); + assert_true(propDesc.writable, 'method should be writable'); + assert_equals(typeof it[m], 'function', 'method should be a function'); + assert_equals(it[m].name, m, 'method should have the correct name'); + } + + assert_equals(it.next.length, 0, 'next should have no parameters'); + assert_equals(it.return.length, 1, 'return should have 1 parameter'); + assert_equals(typeof it.throw, 'undefined', 'throw should not exist'); +}, 'Async iterator instances should have the correct list of properties'); + +promise_test(async () => { + const s = new ReadableStream({ + start(c) { + c.enqueue(1); + c.enqueue(2); + c.enqueue(3); + c.close(); + }, + }); + + const chunks = []; + for await (const chunk of s) { + chunks.push(chunk); + } + assert_array_equals(chunks, [1, 2, 3]); +}, 'Async-iterating a push source'); + +promise_test(async () => { + let i = 1; + const s = new ReadableStream({ + pull(c) { + c.enqueue(i); + if (i >= 3) { + c.close(); + } + i += 1; + }, + }); + + const chunks = []; + for await (const chunk of s) { + chunks.push(chunk); + } + assert_array_equals(chunks, [1, 2, 3]); +}, 'Async-iterating a pull source'); + +promise_test(async () => { + let i = 1; + const s = recordingReadableStream({ + pull(c) { + c.enqueue(i); + if (i >= 3) { + c.close(); + } + i += 1; + }, + }, new CountQueuingStrategy({ highWaterMark: 0 })); + + const it = s.getIterator(); + assert_array_equals(s.events, []); + + const read1 = await it.next(); + assert_equals(read1.done, false); + assert_equals(read1.value, 1); + assert_array_equals(s.events, ['pull']); + + const read2 = await it.next(); + assert_equals(read2.done, false); + assert_equals(read2.value, 2); + assert_array_equals(s.events, ['pull', 'pull']); + + const read3 = await it.next(); + assert_equals(read3.done, false); + assert_equals(read3.value, 3); + assert_array_equals(s.events, ['pull', 'pull', 'pull']); + + const read4 = await it.next(); + assert_equals(read4.done, true); + assert_equals(read4.value, undefined); + assert_array_equals(s.events, ['pull', 'pull', 'pull']); +}, 'Async-iterating a pull source manually'); + +promise_test(async () => { + const s = new ReadableStream({ + start(c) { + c.error('e'); + }, + }); + + try { + for await (const chunk of s) {} + assert_unreached(); + } catch (e) { + assert_equals(e, 'e'); + } +}, 'Async-iterating an errored stream throws'); + +promise_test(async () => { + const s = new ReadableStream({ + start(c) { + c.close(); + } + }); + + for await (const chunk of s) { + assert_unreached(); + } +}, 'Async-iterating a closed stream never executes the loop body, but works fine'); + +promise_test(async () => { + const s = new ReadableStream(); + + const loop = async () => { + for await (const chunk of s) { + assert_unreached(); + } + assert_unreached(); + }; + + await Promise.race([ + loop(), + flushAsyncEvents() + ]); +}, 'Async-iterating an empty but not closed/errored stream never executes the loop body and stalls the async function'); + +promise_test(async () => { + const s = new ReadableStream({ + start(c) { + c.enqueue(1); + c.enqueue(2); + c.enqueue(3); + c.close(); + }, + }); + + const reader = s.getReader(); + const readResult = await reader.read(); + assert_equals(readResult.done, false); + assert_equals(readResult.value, 1); + reader.releaseLock(); + + const chunks = []; + for await (const chunk of s) { + chunks.push(chunk); + } + assert_array_equals(chunks, [2, 3]); +}, 'Async-iterating a partially consumed stream'); + +for (const type of ['throw', 'break', 'return']) { + for (const preventCancel of [false, true]) { + promise_test(async () => { + const s = recordingReadableStream({ + start(c) { + c.enqueue(0); + } + }); + + // use a separate function for the loop body so return does not stop the test + const loop = async () => { + for await (const c of s.getIterator({ preventCancel })) { + if (type === 'throw') { + throw new Error(); + } else if (type === 'break') { + break; + } else if (type === 'return') { + return; + } + } + }; + + try { + await loop(); + } catch (e) {} + + if (preventCancel) { + assert_array_equals(s.events, ['pull'], `cancel() should not be called`); + } else { + assert_array_equals(s.events, ['pull', 'cancel', undefined], `cancel() should be called`); + } + }, `Cancellation behavior when ${type}ing inside loop body; preventCancel = ${preventCancel}`); + } +} + +for (const preventCancel of [false, true]) { + promise_test(async () => { + const s = recordingReadableStream({ + start(c) { + c.enqueue(0); + } + }); + + const it = s.getIterator({ preventCancel }); + await it.return(); + + if (preventCancel) { + assert_array_equals(s.events, [], `cancel() should not be called`); + } else { + assert_array_equals(s.events, ['cancel', undefined], `cancel() should be called`); + } + }, `Cancellation behavior when manually calling return(); preventCancel = ${preventCancel}`); +} + +promise_test(async () => { + const s = new ReadableStream(); + const it = s[Symbol.asyncIterator](); + await it.return(); + try { + await it.return(); + assert_unreached(); + } catch (e) {} +}, 'Calling return() twice rejects'); + +promise_test(async () => { + const s = new ReadableStream({ + start(c) { + c.enqueue(0); + c.close(); + }, + }); + const it = s[Symbol.asyncIterator](); + const next = await it.next(); + assert_equals(Object.getPrototypeOf(next), Object.prototype); + assert_array_equals(Object.getOwnPropertyNames(next).sort(), ['done', 'value']); +}, 'next()\'s fulfillment value has the right shape'); + +promise_test(async t => { + const s = recordingReadableStream(); + const it = s[Symbol.asyncIterator](); + it.next(); + + await promise_rejects(t, new TypeError(), it.return(), 'return() should reject'); + assert_array_equals(s.events, ['pull']); +}, 'calling return() while there are pending reads rejects'); + +test(() => { + const s = new ReadableStream({ + start(c) { + c.enqueue(0); + c.close(); + }, + }); + const it = s.getIterator(); + assert_throws(new TypeError(), () => s.getIterator(), 'getIterator() should throw'); +}, 'getIterator() throws if there\'s already a lock'); + +promise_test(async () => { + const s = new ReadableStream({ + start(c) { + c.enqueue(1); + c.enqueue(2); + c.enqueue(3); + c.close(); + }, + }); + + const chunks = []; + for await (const chunk of s) { + chunks.push(chunk); + } + assert_array_equals(chunks, [1, 2, 3]); + + const reader = s.getReader(); + await reader.closed; +}, 'Acquiring a reader after exhaustively async-iterating a stream'); + +promise_test(async () => { + const s = new ReadableStream({ + start(c) { + c.enqueue(1); + c.enqueue(2); + c.enqueue(3); + c.close(); + }, + }); + + // read the first two chunks, then cancel + const chunks = []; + for await (const chunk of s) { + chunks.push(chunk); + if (chunk >= 2) { + break; + } + } + assert_array_equals(chunks, [1, 2]); + + const reader = s.getReader(); + await reader.closed; +}, 'Acquiring a reader after partially async-iterating a stream'); + +promise_test(async () => { + const s = new ReadableStream({ + start(c) { + c.enqueue(1); + c.enqueue(2); + c.enqueue(3); + c.close(); + }, + }); + + // read the first two chunks, then release lock + const chunks = []; + for await (const chunk of s.getIterator({preventCancel: true})) { + chunks.push(chunk); + if (chunk >= 2) { + break; + } + } + assert_array_equals(chunks, [1, 2]); + + const reader = s.getReader(); + const readResult = await reader.read(); + assert_equals(readResult.done, false, 'should not be closed yet'); + assert_equals(readResult.value, 3, 'should read remaining chunk'); + await reader.closed; +}, 'Acquiring a reader and reading the remaining chunks after partially async-iterating a stream with preventCancel = true');
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/async-iterator.any.serviceworker-expected.txt b/third_party/blink/web_tests/external/wpt/streams/readable-streams/async-iterator.any.serviceworker-expected.txt new file mode 100644 index 0000000..53fe193b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/async-iterator.any.serviceworker-expected.txt
@@ -0,0 +1,27 @@ +This is a testharness.js-based test. +PASS @@asyncIterator() method is === to getIterator() method +FAIL Async iterator instances should have the correct list of properties s.getIterator is not a function +FAIL Async-iterating a push source promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Async-iterating a pull source promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Async-iterating a pull source manually promise_test: Unhandled rejection with value: object "TypeError: s.getIterator is not a function" +FAIL Async-iterating an errored stream throws assert_equals: expected (string) "e" but got (object) object "TypeError: s is not async iterable" +FAIL Async-iterating a closed stream never executes the loop body, but works fine promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Async-iterating an empty but not closed/errored stream never executes the loop body and stalls the async function promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Async-iterating a partially consumed stream promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Cancellation behavior when throwing inside loop body; preventCancel = false assert_array_equals: cancel() should be called lengths differ, expected 3 got 0 +FAIL Cancellation behavior when throwing inside loop body; preventCancel = true assert_array_equals: cancel() should not be called lengths differ, expected 1 got 0 +FAIL Cancellation behavior when breaking inside loop body; preventCancel = false assert_array_equals: cancel() should be called lengths differ, expected 3 got 0 +FAIL Cancellation behavior when breaking inside loop body; preventCancel = true assert_array_equals: cancel() should not be called lengths differ, expected 1 got 0 +FAIL Cancellation behavior when returning inside loop body; preventCancel = false assert_array_equals: cancel() should be called lengths differ, expected 3 got 0 +FAIL Cancellation behavior when returning inside loop body; preventCancel = true assert_array_equals: cancel() should not be called lengths differ, expected 1 got 0 +FAIL Cancellation behavior when manually calling return(); preventCancel = false promise_test: Unhandled rejection with value: object "TypeError: s.getIterator is not a function" +FAIL Cancellation behavior when manually calling return(); preventCancel = true promise_test: Unhandled rejection with value: object "TypeError: s.getIterator is not a function" +FAIL Calling return() twice rejects promise_test: Unhandled rejection with value: object "TypeError: s[Symbol.asyncIterator] is not a function" +FAIL next()'s fulfillment value has the right shape promise_test: Unhandled rejection with value: object "TypeError: s[Symbol.asyncIterator] is not a function" +FAIL calling return() while there are pending reads rejects promise_test: Unhandled rejection with value: object "TypeError: s[Symbol.asyncIterator] is not a function" +FAIL getIterator() throws if there's already a lock s.getIterator is not a function +FAIL Acquiring a reader after exhaustively async-iterating a stream promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Acquiring a reader after partially async-iterating a stream promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Acquiring a reader and reading the remaining chunks after partially async-iterating a stream with preventCancel = true promise_test: Unhandled rejection with value: object "TypeError: s.getIterator(...) is not a function or its return value is not async iterable" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/async-iterator.any.sharedworker-expected.txt b/third_party/blink/web_tests/external/wpt/streams/readable-streams/async-iterator.any.sharedworker-expected.txt new file mode 100644 index 0000000..53fe193b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/async-iterator.any.sharedworker-expected.txt
@@ -0,0 +1,27 @@ +This is a testharness.js-based test. +PASS @@asyncIterator() method is === to getIterator() method +FAIL Async iterator instances should have the correct list of properties s.getIterator is not a function +FAIL Async-iterating a push source promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Async-iterating a pull source promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Async-iterating a pull source manually promise_test: Unhandled rejection with value: object "TypeError: s.getIterator is not a function" +FAIL Async-iterating an errored stream throws assert_equals: expected (string) "e" but got (object) object "TypeError: s is not async iterable" +FAIL Async-iterating a closed stream never executes the loop body, but works fine promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Async-iterating an empty but not closed/errored stream never executes the loop body and stalls the async function promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Async-iterating a partially consumed stream promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Cancellation behavior when throwing inside loop body; preventCancel = false assert_array_equals: cancel() should be called lengths differ, expected 3 got 0 +FAIL Cancellation behavior when throwing inside loop body; preventCancel = true assert_array_equals: cancel() should not be called lengths differ, expected 1 got 0 +FAIL Cancellation behavior when breaking inside loop body; preventCancel = false assert_array_equals: cancel() should be called lengths differ, expected 3 got 0 +FAIL Cancellation behavior when breaking inside loop body; preventCancel = true assert_array_equals: cancel() should not be called lengths differ, expected 1 got 0 +FAIL Cancellation behavior when returning inside loop body; preventCancel = false assert_array_equals: cancel() should be called lengths differ, expected 3 got 0 +FAIL Cancellation behavior when returning inside loop body; preventCancel = true assert_array_equals: cancel() should not be called lengths differ, expected 1 got 0 +FAIL Cancellation behavior when manually calling return(); preventCancel = false promise_test: Unhandled rejection with value: object "TypeError: s.getIterator is not a function" +FAIL Cancellation behavior when manually calling return(); preventCancel = true promise_test: Unhandled rejection with value: object "TypeError: s.getIterator is not a function" +FAIL Calling return() twice rejects promise_test: Unhandled rejection with value: object "TypeError: s[Symbol.asyncIterator] is not a function" +FAIL next()'s fulfillment value has the right shape promise_test: Unhandled rejection with value: object "TypeError: s[Symbol.asyncIterator] is not a function" +FAIL calling return() while there are pending reads rejects promise_test: Unhandled rejection with value: object "TypeError: s[Symbol.asyncIterator] is not a function" +FAIL getIterator() throws if there's already a lock s.getIterator is not a function +FAIL Acquiring a reader after exhaustively async-iterating a stream promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Acquiring a reader after partially async-iterating a stream promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Acquiring a reader and reading the remaining chunks after partially async-iterating a stream with preventCancel = true promise_test: Unhandled rejection with value: object "TypeError: s.getIterator(...) is not a function or its return value is not async iterable" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/async-iterator.any.worker-expected.txt b/third_party/blink/web_tests/external/wpt/streams/readable-streams/async-iterator.any.worker-expected.txt new file mode 100644 index 0000000..53fe193b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/async-iterator.any.worker-expected.txt
@@ -0,0 +1,27 @@ +This is a testharness.js-based test. +PASS @@asyncIterator() method is === to getIterator() method +FAIL Async iterator instances should have the correct list of properties s.getIterator is not a function +FAIL Async-iterating a push source promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Async-iterating a pull source promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Async-iterating a pull source manually promise_test: Unhandled rejection with value: object "TypeError: s.getIterator is not a function" +FAIL Async-iterating an errored stream throws assert_equals: expected (string) "e" but got (object) object "TypeError: s is not async iterable" +FAIL Async-iterating a closed stream never executes the loop body, but works fine promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Async-iterating an empty but not closed/errored stream never executes the loop body and stalls the async function promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Async-iterating a partially consumed stream promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Cancellation behavior when throwing inside loop body; preventCancel = false assert_array_equals: cancel() should be called lengths differ, expected 3 got 0 +FAIL Cancellation behavior when throwing inside loop body; preventCancel = true assert_array_equals: cancel() should not be called lengths differ, expected 1 got 0 +FAIL Cancellation behavior when breaking inside loop body; preventCancel = false assert_array_equals: cancel() should be called lengths differ, expected 3 got 0 +FAIL Cancellation behavior when breaking inside loop body; preventCancel = true assert_array_equals: cancel() should not be called lengths differ, expected 1 got 0 +FAIL Cancellation behavior when returning inside loop body; preventCancel = false assert_array_equals: cancel() should be called lengths differ, expected 3 got 0 +FAIL Cancellation behavior when returning inside loop body; preventCancel = true assert_array_equals: cancel() should not be called lengths differ, expected 1 got 0 +FAIL Cancellation behavior when manually calling return(); preventCancel = false promise_test: Unhandled rejection with value: object "TypeError: s.getIterator is not a function" +FAIL Cancellation behavior when manually calling return(); preventCancel = true promise_test: Unhandled rejection with value: object "TypeError: s.getIterator is not a function" +FAIL Calling return() twice rejects promise_test: Unhandled rejection with value: object "TypeError: s[Symbol.asyncIterator] is not a function" +FAIL next()'s fulfillment value has the right shape promise_test: Unhandled rejection with value: object "TypeError: s[Symbol.asyncIterator] is not a function" +FAIL calling return() while there are pending reads rejects promise_test: Unhandled rejection with value: object "TypeError: s[Symbol.asyncIterator] is not a function" +FAIL getIterator() throws if there's already a lock s.getIterator is not a function +FAIL Acquiring a reader after exhaustively async-iterating a stream promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Acquiring a reader after partially async-iterating a stream promise_test: Unhandled rejection with value: object "TypeError: s is not async iterable" +FAIL Acquiring a reader and reading the remaining chunks after partially async-iterating a stream with preventCancel = true promise_test: Unhandled rejection with value: object "TypeError: s.getIterator(...) is not a function or its return value is not async iterable" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/brand-checks.any-expected.txt b/third_party/blink/web_tests/external/wpt/streams/readable-streams/brand-checks.any-expected.txt new file mode 100644 index 0000000..8c91f96b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/brand-checks.any-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +PASS Can get the ReadableStreamDefaultReader constructor indirectly +PASS Can get the ReadableStreamDefaultController constructor indirectly +FAIL Can get ReadableStreamAsyncIteratorPrototype object indirectly rs.getIterator is not a function +PASS ReadableStream.prototype.cancel enforces a brand check +PASS ReadableStream.prototype.getReader enforces a brand check +PASS ReadableStream.prototype.tee enforces a brand check +PASS ReadableStreamDefaultReader enforces a brand check on its argument +PASS ReadableStreamDefaultReader.prototype.closed enforces a brand check +PASS ReadableStreamDefaultReader.prototype.cancel enforces a brand check +PASS ReadableStreamDefaultReader.prototype.read enforces a brand check +PASS ReadableStreamDefaultReader.prototype.releaseLock enforces a brand check +PASS ReadableStreamDefaultController enforces a brand check on its argument +PASS ReadableStreamDefaultController can't be given a fully-constructed ReadableStream +PASS ReadableStreamDefaultController.prototype.close enforces a brand check +PASS ReadableStreamDefaultController.prototype.enqueue enforces a brand check +PASS ReadableStreamDefaultController.prototype.error enforces a brand check +FAIL ReadableStreamAsyncIteratorPrototype.next enforces a brand check Object prototype may only be an Object or null: undefined +FAIL ReadableStreamAsyncIteratorPrototype.return enforces a brand check Object prototype may only be an Object or null: undefined +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/brand-checks.any.js b/third_party/blink/web_tests/external/wpt/streams/readable-streams/brand-checks.any.js index 2906494b..521e436 100644 --- a/third_party/blink/web_tests/external/wpt/streams/readable-streams/brand-checks.any.js +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/brand-checks.any.js
@@ -4,6 +4,7 @@ let ReadableStreamDefaultReader; let ReadableStreamDefaultController; +let ReadableStreamAsyncIteratorPrototype; test(() => { @@ -23,6 +24,13 @@ }, 'Can get the ReadableStreamDefaultController constructor indirectly'); +test(() => { + + const rs = new ReadableStream(); + ReadableStreamAsyncIteratorPrototype = Object.getPrototypeOf(rs.getIterator()); + +}, 'Can get ReadableStreamAsyncIteratorPrototype object indirectly'); + function fakeRS() { return Object.setPrototypeOf({ cancel() { return Promise.resolve(); }, @@ -68,6 +76,13 @@ return controller; } +function fakeRSAsyncIterator() { + return Object.setPrototypeOf({ + next() { }, + return(value = undefined) { } + }, ReadableStreamAsyncIteratorPrototype); +} + promise_test(t => { return methodRejectsForAll(t, ReadableStream.prototype, 'cancel', @@ -157,3 +172,17 @@ [fakeRSDefaultController(), realRS(), realRSDefaultReader(), undefined, null]); }, 'ReadableStreamDefaultController.prototype.error enforces a brand check'); + +promise_test(t => { + + return methodRejectsForAll(t, ReadableStreamAsyncIteratorPrototype, 'next', + [fakeRSAsyncIterator(), realRS(), realRSDefaultReader(), undefined, null]); + +}, 'ReadableStreamAsyncIteratorPrototype.next enforces a brand check'); + +promise_test(t => { + + return methodRejectsForAll(t, ReadableStreamAsyncIteratorPrototype, 'return', + [fakeRSAsyncIterator(), realRS(), realRSDefaultReader(), undefined, null]); + +}, 'ReadableStreamAsyncIteratorPrototype.return enforces a brand check');
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/brand-checks.any.serviceworker-expected.txt b/third_party/blink/web_tests/external/wpt/streams/readable-streams/brand-checks.any.serviceworker-expected.txt new file mode 100644 index 0000000..8c91f96b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/brand-checks.any.serviceworker-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +PASS Can get the ReadableStreamDefaultReader constructor indirectly +PASS Can get the ReadableStreamDefaultController constructor indirectly +FAIL Can get ReadableStreamAsyncIteratorPrototype object indirectly rs.getIterator is not a function +PASS ReadableStream.prototype.cancel enforces a brand check +PASS ReadableStream.prototype.getReader enforces a brand check +PASS ReadableStream.prototype.tee enforces a brand check +PASS ReadableStreamDefaultReader enforces a brand check on its argument +PASS ReadableStreamDefaultReader.prototype.closed enforces a brand check +PASS ReadableStreamDefaultReader.prototype.cancel enforces a brand check +PASS ReadableStreamDefaultReader.prototype.read enforces a brand check +PASS ReadableStreamDefaultReader.prototype.releaseLock enforces a brand check +PASS ReadableStreamDefaultController enforces a brand check on its argument +PASS ReadableStreamDefaultController can't be given a fully-constructed ReadableStream +PASS ReadableStreamDefaultController.prototype.close enforces a brand check +PASS ReadableStreamDefaultController.prototype.enqueue enforces a brand check +PASS ReadableStreamDefaultController.prototype.error enforces a brand check +FAIL ReadableStreamAsyncIteratorPrototype.next enforces a brand check Object prototype may only be an Object or null: undefined +FAIL ReadableStreamAsyncIteratorPrototype.return enforces a brand check Object prototype may only be an Object or null: undefined +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/brand-checks.any.sharedworker-expected.txt b/third_party/blink/web_tests/external/wpt/streams/readable-streams/brand-checks.any.sharedworker-expected.txt new file mode 100644 index 0000000..8c91f96b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/brand-checks.any.sharedworker-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +PASS Can get the ReadableStreamDefaultReader constructor indirectly +PASS Can get the ReadableStreamDefaultController constructor indirectly +FAIL Can get ReadableStreamAsyncIteratorPrototype object indirectly rs.getIterator is not a function +PASS ReadableStream.prototype.cancel enforces a brand check +PASS ReadableStream.prototype.getReader enforces a brand check +PASS ReadableStream.prototype.tee enforces a brand check +PASS ReadableStreamDefaultReader enforces a brand check on its argument +PASS ReadableStreamDefaultReader.prototype.closed enforces a brand check +PASS ReadableStreamDefaultReader.prototype.cancel enforces a brand check +PASS ReadableStreamDefaultReader.prototype.read enforces a brand check +PASS ReadableStreamDefaultReader.prototype.releaseLock enforces a brand check +PASS ReadableStreamDefaultController enforces a brand check on its argument +PASS ReadableStreamDefaultController can't be given a fully-constructed ReadableStream +PASS ReadableStreamDefaultController.prototype.close enforces a brand check +PASS ReadableStreamDefaultController.prototype.enqueue enforces a brand check +PASS ReadableStreamDefaultController.prototype.error enforces a brand check +FAIL ReadableStreamAsyncIteratorPrototype.next enforces a brand check Object prototype may only be an Object or null: undefined +FAIL ReadableStreamAsyncIteratorPrototype.return enforces a brand check Object prototype may only be an Object or null: undefined +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/brand-checks.any.worker-expected.txt b/third_party/blink/web_tests/external/wpt/streams/readable-streams/brand-checks.any.worker-expected.txt new file mode 100644 index 0000000..8c91f96b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/brand-checks.any.worker-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +PASS Can get the ReadableStreamDefaultReader constructor indirectly +PASS Can get the ReadableStreamDefaultController constructor indirectly +FAIL Can get ReadableStreamAsyncIteratorPrototype object indirectly rs.getIterator is not a function +PASS ReadableStream.prototype.cancel enforces a brand check +PASS ReadableStream.prototype.getReader enforces a brand check +PASS ReadableStream.prototype.tee enforces a brand check +PASS ReadableStreamDefaultReader enforces a brand check on its argument +PASS ReadableStreamDefaultReader.prototype.closed enforces a brand check +PASS ReadableStreamDefaultReader.prototype.cancel enforces a brand check +PASS ReadableStreamDefaultReader.prototype.read enforces a brand check +PASS ReadableStreamDefaultReader.prototype.releaseLock enforces a brand check +PASS ReadableStreamDefaultController enforces a brand check on its argument +PASS ReadableStreamDefaultController can't be given a fully-constructed ReadableStream +PASS ReadableStreamDefaultController.prototype.close enforces a brand check +PASS ReadableStreamDefaultController.prototype.enqueue enforces a brand check +PASS ReadableStreamDefaultController.prototype.error enforces a brand check +FAIL ReadableStreamAsyncIteratorPrototype.next enforces a brand check Object prototype may only be an Object or null: undefined +FAIL ReadableStreamAsyncIteratorPrototype.return enforces a brand check Object prototype may only be an Object or null: undefined +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any-expected.txt b/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any-expected.txt index 6cc846a..41a7590 100644 --- a/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any-expected.txt +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any-expected.txt
@@ -2,7 +2,7 @@ PASS ReadableStream can be constructed with no errors PASS ReadableStream can't be constructed with garbage PASS ReadableStream can't be constructed with an invalid type -FAIL ReadableStream instances should have the correct list of properties assert_equals: cancel should have 1 parameter expected 1 but got 0 +FAIL ReadableStream instances should have the correct list of properties assert_array_equals: should have all the correct properties lengths differ, expected 8 got 7 PASS ReadableStream constructor should throw for non-function start arguments PASS ReadableStream constructor will not tolerate initial garbage as cancel argument PASS ReadableStream constructor will not tolerate initial garbage as pull argument
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any.js b/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any.js index f885ed6d..e9a107db 100644 --- a/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any.js +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any.js
@@ -39,13 +39,15 @@ test(() => { - const methods = ['cancel', 'constructor', 'getReader', 'pipeThrough', 'pipeTo', 'tee']; + const methods = ['cancel', 'constructor', 'getReader', 'pipeThrough', 'pipeTo', 'tee', 'getIterator']; const properties = methods.concat(['locked']).sort(); + const symbols = [Symbol.asyncIterator]; const rs = new ReadableStream(); const proto = Object.getPrototypeOf(rs); - assert_array_equals(Object.getOwnPropertyNames(proto).sort(), properties, 'should have all the correct methods'); + assert_array_equals(Object.getOwnPropertyNames(proto).sort(), properties, 'should have all the correct properties'); + assert_array_equals(Object.getOwnPropertySymbols(proto).sort(), symbols, 'should have all the correct symbols'); for (const m of methods) { const propDesc = Object.getOwnPropertyDescriptor(proto, m); @@ -70,6 +72,15 @@ assert_equals(rs.pipeThrough.length, 1, 'pipeThrough should have 1 parameters'); assert_equals(rs.pipeTo.length, 1, 'pipeTo should have 1 parameter'); assert_equals(rs.tee.length, 0, 'tee should have no parameters'); + assert_equals(rs.getIterator.length, 0, 'getIterator should have no required parameters'); + assert_equals(rs[Symbol.asyncIterator].length, 0, '@@asyncIterator should have no required parameters'); + + const asyncIteratorPropDesc = Object.getOwnPropertyDescriptor(proto, Symbol.asyncIterator); + assert_false(asyncIteratorPropDesc.enumerable, '@@asyncIterator should be non-enumerable'); + assert_true(asyncIteratorPropDesc.configurable, '@@asyncIterator should be configurable'); + assert_true(asyncIteratorPropDesc.writable, '@@asyncIterator should be writable'); + assert_equals(typeof rs[Symbol.asyncIterator], 'function', '@@asyncIterator should be a function'); + assert_equals(rs[Symbol.asyncIterator].name, 'getIterator', '@@asyncIterator should have the correct name'); }, 'ReadableStream instances should have the correct list of properties');
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any.serviceworker-expected.txt b/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any.serviceworker-expected.txt index 6cc846a..41a7590 100644 --- a/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any.serviceworker-expected.txt +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any.serviceworker-expected.txt
@@ -2,7 +2,7 @@ PASS ReadableStream can be constructed with no errors PASS ReadableStream can't be constructed with garbage PASS ReadableStream can't be constructed with an invalid type -FAIL ReadableStream instances should have the correct list of properties assert_equals: cancel should have 1 parameter expected 1 but got 0 +FAIL ReadableStream instances should have the correct list of properties assert_array_equals: should have all the correct properties lengths differ, expected 8 got 7 PASS ReadableStream constructor should throw for non-function start arguments PASS ReadableStream constructor will not tolerate initial garbage as cancel argument PASS ReadableStream constructor will not tolerate initial garbage as pull argument
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any.sharedworker-expected.txt b/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any.sharedworker-expected.txt index 6cc846a..41a7590 100644 --- a/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any.sharedworker-expected.txt +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any.sharedworker-expected.txt
@@ -2,7 +2,7 @@ PASS ReadableStream can be constructed with no errors PASS ReadableStream can't be constructed with garbage PASS ReadableStream can't be constructed with an invalid type -FAIL ReadableStream instances should have the correct list of properties assert_equals: cancel should have 1 parameter expected 1 but got 0 +FAIL ReadableStream instances should have the correct list of properties assert_array_equals: should have all the correct properties lengths differ, expected 8 got 7 PASS ReadableStream constructor should throw for non-function start arguments PASS ReadableStream constructor will not tolerate initial garbage as cancel argument PASS ReadableStream constructor will not tolerate initial garbage as pull argument
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any.worker-expected.txt b/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any.worker-expected.txt index 6cc846a..41a7590 100644 --- a/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any.worker-expected.txt +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/general.any.worker-expected.txt
@@ -2,7 +2,7 @@ PASS ReadableStream can be constructed with no errors PASS ReadableStream can't be constructed with garbage PASS ReadableStream can't be constructed with an invalid type -FAIL ReadableStream instances should have the correct list of properties assert_equals: cancel should have 1 parameter expected 1 but got 0 +FAIL ReadableStream instances should have the correct list of properties assert_array_equals: should have all the correct properties lengths differ, expected 8 got 7 PASS ReadableStream constructor should throw for non-function start arguments PASS ReadableStream constructor will not tolerate initial garbage as cancel argument PASS ReadableStream constructor will not tolerate initial garbage as pull argument
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/patched-global.any-expected.txt b/third_party/blink/web_tests/external/wpt/streams/readable-streams/patched-global.any-expected.txt new file mode 100644 index 0000000..95f34fb --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/patched-global.any-expected.txt
@@ -0,0 +1,6 @@ +This is a testharness.js-based test. +PASS ReadableStream tee() should not touch Object.prototype properties +PASS ReadableStream tee() should not call the global ReadableStream +FAIL ReadableStream getIterator() should use the original values of getReader() and ReadableStreamDefaultReader methods promise_test: Unhandled rejection with value: object "TypeError: rs is not async iterable" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/patched-global.any.js b/third_party/blink/web_tests/external/wpt/streams/readable-streams/patched-global.any.js index fa49249a..500979f 100644 --- a/third_party/blink/web_tests/external/wpt/streams/readable-streams/patched-global.any.js +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/patched-global.any.js
@@ -57,3 +57,53 @@ assert_true(isReadableStream(branch1), 'branch1 should be a ReadableStream'); assert_true(isReadableStream(branch2), 'branch2 should be a ReadableStream'); }, 'ReadableStream tee() should not call the global ReadableStream'); + +promise_test(async t => { + const rs = new ReadableStream({ + start(c) { + c.enqueue(1); + c.enqueue(2); + c.enqueue(3); + c.close(); + } + }); + + const oldReadableStreamGetReader = ReadableStream.prototype.getReader; + + const ReadableStreamDefaultReader = (new ReadableStream()).getReader().constructor; + const oldDefaultReaderRead = ReadableStreamDefaultReader.prototype.read; + const oldDefaultReaderCancel = ReadableStreamDefaultReader.prototype.cancel; + const oldDefaultReaderReleaseLock = ReadableStreamDefaultReader.prototype.releaseLock; + + self.ReadableStream.prototype.getReader = function() { + throw new Error('patched getReader() called'); + }; + + ReadableStreamDefaultReader.prototype.read = function() { + throw new Error('patched read() called'); + }; + ReadableStreamDefaultReader.prototype.cancel = function() { + throw new Error('patched cancel() called'); + }; + ReadableStreamDefaultReader.prototype.releaseLock = function() { + throw new Error('patched releaseLock() called'); + }; + + t.add_cleanup(() => { + self.ReadableStream.prototype.getReader = oldReadableStreamGetReader; + + ReadableStreamDefaultReader.prototype.read = oldDefaultReaderRead; + ReadableStreamDefaultReader.prototype.cancel = oldDefaultReaderCancel; + ReadableStreamDefaultReader.prototype.releaseLock = oldDefaultReaderReleaseLock; + }); + + // read the first chunk, then cancel + for await (const chunk of rs) { + break; + } + + // should be able to acquire a new reader + const reader = oldReadableStreamGetReader.call(rs); + // stream should be cancelled + await reader.closed; +}, 'ReadableStream getIterator() should use the original values of getReader() and ReadableStreamDefaultReader methods');
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/patched-global.any.serviceworker-expected.txt b/third_party/blink/web_tests/external/wpt/streams/readable-streams/patched-global.any.serviceworker-expected.txt new file mode 100644 index 0000000..95f34fb --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/patched-global.any.serviceworker-expected.txt
@@ -0,0 +1,6 @@ +This is a testharness.js-based test. +PASS ReadableStream tee() should not touch Object.prototype properties +PASS ReadableStream tee() should not call the global ReadableStream +FAIL ReadableStream getIterator() should use the original values of getReader() and ReadableStreamDefaultReader methods promise_test: Unhandled rejection with value: object "TypeError: rs is not async iterable" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/patched-global.any.sharedworker-expected.txt b/third_party/blink/web_tests/external/wpt/streams/readable-streams/patched-global.any.sharedworker-expected.txt new file mode 100644 index 0000000..95f34fb --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/patched-global.any.sharedworker-expected.txt
@@ -0,0 +1,6 @@ +This is a testharness.js-based test. +PASS ReadableStream tee() should not touch Object.prototype properties +PASS ReadableStream tee() should not call the global ReadableStream +FAIL ReadableStream getIterator() should use the original values of getReader() and ReadableStreamDefaultReader methods promise_test: Unhandled rejection with value: object "TypeError: rs is not async iterable" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/streams/readable-streams/patched-global.any.worker-expected.txt b/third_party/blink/web_tests/external/wpt/streams/readable-streams/patched-global.any.worker-expected.txt new file mode 100644 index 0000000..95f34fb --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/streams/readable-streams/patched-global.any.worker-expected.txt
@@ -0,0 +1,6 @@ +This is a testharness.js-based test. +PASS ReadableStream tee() should not touch Object.prototype properties +PASS ReadableStream tee() should not call the global ReadableStream +FAIL ReadableStream getIterator() should use the original values of getReader() and ReadableStreamDefaultReader methods promise_test: Unhandled rejection with value: object "TypeError: rs is not async iterable" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/webaudio/the-audio-api/the-audiobuffersourcenode-interface/sub-sample-buffer-stitching.html b/third_party/blink/web_tests/external/wpt/webaudio/the-audio-api/the-audiobuffersourcenode-interface/sub-sample-buffer-stitching.html new file mode 100644 index 0000000..b69cb0e8 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/webaudio/the-audio-api/the-audiobuffersourcenode-interface/sub-sample-buffer-stitching.html
@@ -0,0 +1,133 @@ +<!doctype html> +<html> + <head> + <title> + Test Sub-Sample Accurate Stitching of ABSNs + </title> + <script src="/resources/testharness.js"></script> + <script src="/resources/testharnessreport.js"></script> + <script src="/webaudio/resources/audit-util.js"></script> + <script src="/webaudio/resources/audit.js"></script> + </head> + <body> + <script> + let audit = Audit.createTaskRunner(); + + audit.define( + { + label: 'buffer-stitching-1', + description: 'Subsample buffer stitching, same rates' + }, + (task, should) => { + const sampleRate = 44100; + const bufferRate = 44100; + const bufferLength = 30; + + // Experimentally determined thresholds. DO NOT relax these values + // to far from these values to make the tests pass. + const errorThreshold = 9.0957e-5; + const snrThreshold = 85.586; + + // Informative message + should(sampleRate, 'Test 1: context.sampleRate') + .beEqualTo(sampleRate); + testBufferStitching(sampleRate, bufferRate, bufferLength) + .then(resultBuffer => { + const actual = resultBuffer.getChannelData(0); + const expected = resultBuffer.getChannelData(1); + should( + actual, + `Stitched sine-wave buffers at sample rate ${bufferRate}`) + .beCloseToArray( + expected, {absoluteThreshold: errorThreshold}); + const SNR = 10 * Math.log10(computeSNR(actual, expected)); + should(SNR, `SNR (${SNR} dB)`) + .beGreaterThanOrEqualTo(snrThreshold); + }) + .then(() => task.done()); + }); + + audit.define( + { + label: 'buffer-stitching-2', + description: 'Subsample buffer stitching, different rates' + }, + (task, should) => { + const sampleRate = 44100; + const bufferRate = 43800; + const bufferLength = 30; + + // Experimentally determined thresholds. DO NOT relax these values + // to far from these values to make the tests pass. + const errorThreshold = 3.8986e-3; + const snrThreshold = 65.737; + + // Informative message + should(sampleRate, 'Test 2: context.sampleRate') + .beEqualTo(sampleRate); + testBufferStitching(sampleRate, bufferRate, bufferLength) + .then(resultBuffer => { + const actual = resultBuffer.getChannelData(0); + const expected = resultBuffer.getChannelData(1); + should( + actual, + `Stitched sine-wave buffers at sample rate ${bufferRate}`) + .beCloseToArray( + expected, {absoluteThreshold: errorThreshold}); + const SNR = 10 * Math.log10(computeSNR(actual, expected)); + should(SNR, `SNR (${SNR} dB)`) + .beGreaterThanOrEqualTo(snrThreshold); + }) + .then(() => task.done()); + }); + + audit.run(); + + // Create graph to test stitching of consecutive ABSNs. The context rate + // is |sampleRate|, and the buffers have a fixed length of |bufferLength| + // and rate of |bufferRate|. The |bufferRate| should not be too different + // from |sampleRate| because of interpolation of the buffer to the context + // rate. + function testBufferStitching(sampleRate, bufferRate, bufferLength) { + // The context for testing. Channel 0 contains the output from + // stitching all the buffers together, and channel 1 contains the + // expected output. + const context = new OfflineAudioContext( + {numberOfChannels: 2, length: sampleRate, sampleRate: sampleRate}); + + const merger = new ChannelMergerNode( + context, {numberOfInputs: context.destination.channelCount}); + + merger.connect(context.destination); + + // The reference is a sine wave at 440 Hz. + const ref = new OscillatorNode(context, {frequency: 440, type: 'sine'}); + ref.connect(merger, 0, 1); + ref.start(); + + // The test signal is a bunch of short AudioBufferSources containing + // bits of a sine wave. + let waveSignal = new Float32Array(context.length); + const omega = 2 * Math.PI / bufferRate * ref.frequency.value; + for (let k = 0; k < context.length; ++k) { + waveSignal[k] = Math.sin(omega * k); + } + + // Slice the sine wave into many little buffers to be assigned to ABSNs + // that are started at the appropriate times to produce a final sine + // wave. + for (let k = 0; k < context.length; k += bufferLength) { + const buffer = + new AudioBuffer({length: bufferLength, sampleRate: bufferRate}); + buffer.copyToChannel(waveSignal.slice(k, k + bufferLength), 0); + + const src = new AudioBufferSourceNode(context, {buffer: buffer}); + src.connect(merger, 0, 0); + src.start(k / bufferRate); + } + + return context.startRendering(); + } + </script> + </body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/webaudio/the-audio-api/the-audiobuffersourcenode-interface/resources/sub-sample-scheduling.html b/third_party/blink/web_tests/external/wpt/webaudio/the-audio-api/the-audiobuffersourcenode-interface/sub-sample-scheduling.html similarity index 100% rename from third_party/blink/web_tests/external/wpt/webaudio/the-audio-api/the-audiobuffersourcenode-interface/resources/sub-sample-scheduling.html rename to third_party/blink/web_tests/external/wpt/webaudio/the-audio-api/the-audiobuffersourcenode-interface/sub-sample-scheduling.html
diff --git a/third_party/blink/web_tests/http/tests/devtools/tracing/timeline-misc/timeline-page-metrics-expected.txt b/third_party/blink/web_tests/http/tests/devtools/tracing/timeline-misc/timeline-page-metrics-expected.txt index 01b14ee0..5be01318 100644 --- a/third_party/blink/web_tests/http/tests/devtools/tracing/timeline-misc/timeline-page-metrics-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/tracing/timeline-misc/timeline-page-metrics-expected.txt
@@ -1,10 +1,12 @@ Test timeline page metrics. Entries: +101 NaN FP 101.2 NaN FCP 101.3 NaN FMP Markers: +101 1 First Paint 101.2 1.2000000000000028 First Contentful Paint 101.3 1.2999999999999972 First Meaningful Paint
diff --git a/third_party/blink/web_tests/http/tests/performance-timing/layout-jank/buffer-layout-jank.html b/third_party/blink/web_tests/http/tests/performance-timing/layout-jank/buffer-layout-jank.html new file mode 100644 index 0000000..c9cfd05 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/performance-timing/layout-jank/buffer-layout-jank.html
@@ -0,0 +1,39 @@ +<!DOCTYPE HTML> +<meta charset=utf-8> +<title>Layout Jank: query jank via the performance timeline</title> +<body> +<style> +#myDiv { position: relative; width: 300px; height: 100px; } +</style> +<div id='myDiv'></div> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<!-- Delay onload by inserting a slow image.--> +<img src="/resources/slow-image.php?name=notthere.png&mimeType=image&sleep=3000"> +<script> + async_test(function (t) { + // Modify the position of the div. + document.getElementById('myDiv').style = "top: 60px"; + function testBufferedEntry() { + if (performance.getEntriesByType('layoutJank').length === 0) { + t.step_timeout(testBufferedEntry, 0); + return; + } + assert_equals(performance.getEntriesByType('layoutJank').length, 1); + assert_equals(performance.getEntries().filter( + entry => entry.entryType === 'layoutJank').length, 1); + const entry = performance.getEntriesByType('layoutJank')[0]; + assert_equals(entry.entryType, "layoutJank"); + assert_equals(entry.name, ""); + assert_equals(entry.startTime, 0.0); + assert_equals(entry.duration, 0.0); + // The layout jank fraction should be: 300 * (100 + 60) / viewport size. + assert_equals(entry.fraction, 300 * (100 + 60) / + (document.documentElement.clientWidth * document.documentElement.clientHeight)); + t.done(); + } + t.step(testBufferedEntry); + }, 'LayoutJank before onload is buffered into the performance timeline.'); +</script> + +</body>
diff --git a/third_party/blink/web_tests/http/tests/performance-timing/layout-jank/observe-layoutjank.html b/third_party/blink/web_tests/http/tests/performance-timing/layout-jank/observe-layoutjank.html index 01079f0..1a0533ac 100644 --- a/third_party/blink/web_tests/http/tests/performance-timing/layout-jank/observe-layoutjank.html +++ b/third_party/blink/web_tests/http/tests/performance-timing/layout-jank/observe-layoutjank.html
@@ -28,7 +28,7 @@ // Modify the position of the div. document.getElementById('myDiv').style = "top: 60px"; }; - }, 'Element with elementtiming attribute is observable.'); + }, 'LayoutJank is observable via PerformanceObserver.'); </script> </body>
diff --git a/third_party/blink/web_tests/platform/linux/fast/text/font-format-support-color-cff2-expected.png b/third_party/blink/web_tests/platform/linux/fast/text/font-format-support-color-cff2-expected.png index a8d2552..a98ae940 100644 --- a/third_party/blink/web_tests/platform/linux/fast/text/font-format-support-color-cff2-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/text/font-format-support-color-cff2-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/text/font-format-support-color-cff2-vertical-expected.png b/third_party/blink/web_tests/platform/linux/fast/text/font-format-support-color-cff2-vertical-expected.png index e0fc138..e70e527 100644 --- a/third_party/blink/web_tests/platform/linux/fast/text/font-format-support-color-cff2-vertical-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/text/font-format-support-color-cff2-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/text/variable-fonts/cff2-variations-expected.png b/third_party/blink/web_tests/platform/linux/fast/text/variable-fonts/cff2-variations-expected.png index 4023648..108a029 100644 --- a/third_party/blink/web_tests/platform/linux/fast/text/variable-fonts/cff2-variations-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/text/variable-fonts/cff2-variations-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.10/fast/text/font-format-support-color-cff2-expected.png b/third_party/blink/web_tests/platform/mac-mac10.10/fast/text/font-format-support-color-cff2-expected.png index 3d9f430..45fc07a6 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.10/fast/text/font-format-support-color-cff2-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.10/fast/text/font-format-support-color-cff2-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.10/fast/text/font-format-support-color-cff2-vertical-expected.png b/third_party/blink/web_tests/platform/mac-mac10.10/fast/text/font-format-support-color-cff2-vertical-expected.png index 14114a63..37e4d008 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.10/fast/text/font-format-support-color-cff2-vertical-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.10/fast/text/font-format-support-color-cff2-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.10/fast/text/variable-fonts/cff2-variations-expected.png b/third_party/blink/web_tests/platform/mac-mac10.10/fast/text/variable-fonts/cff2-variations-expected.png index e5a52306..fed8edda 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.10/fast/text/variable-fonts/cff2-variations-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.10/fast/text/variable-fonts/cff2-variations-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.12/fast/text/font-format-support-color-cff2-expected.png b/third_party/blink/web_tests/platform/mac-mac10.12/fast/text/font-format-support-color-cff2-expected.png index c15779f..1ab524f 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.12/fast/text/font-format-support-color-cff2-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.12/fast/text/font-format-support-color-cff2-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.12/fast/text/font-format-support-color-cff2-vertical-expected.png b/third_party/blink/web_tests/platform/mac-mac10.12/fast/text/font-format-support-color-cff2-vertical-expected.png index 2540c06..68f72585 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.12/fast/text/font-format-support-color-cff2-vertical-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.12/fast/text/font-format-support-color-cff2-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.12/fast/text/variable-fonts/cff2-variations-expected.png b/third_party/blink/web_tests/platform/mac-mac10.12/fast/text/variable-fonts/cff2-variations-expected.png index 257f37b..40c68fb 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.12/fast/text/variable-fonts/cff2-variations-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.12/fast/text/variable-fonts/cff2-variations-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/text/font-format-support-color-cff2-expected.png b/third_party/blink/web_tests/platform/mac/fast/text/font-format-support-color-cff2-expected.png index 8f76d4e..10942a3 100644 --- a/third_party/blink/web_tests/platform/mac/fast/text/font-format-support-color-cff2-expected.png +++ b/third_party/blink/web_tests/platform/mac/fast/text/font-format-support-color-cff2-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/text/font-format-support-color-cff2-vertical-expected.png b/third_party/blink/web_tests/platform/mac/fast/text/font-format-support-color-cff2-vertical-expected.png index f26be29..aa3be0c 100644 --- a/third_party/blink/web_tests/platform/mac/fast/text/font-format-support-color-cff2-vertical-expected.png +++ b/third_party/blink/web_tests/platform/mac/fast/text/font-format-support-color-cff2-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/text/variable-fonts/cff2-variations-expected.png b/third_party/blink/web_tests/platform/mac/fast/text/variable-fonts/cff2-variations-expected.png index 3dbfecf..0d25503 100644 --- a/third_party/blink/web_tests/platform/mac/fast/text/variable-fonts/cff2-variations-expected.png +++ b/third_party/blink/web_tests/platform/mac/fast/text/variable-fonts/cff2-variations-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/text/font-format-support-color-cff2-expected.png b/third_party/blink/web_tests/platform/win/fast/text/font-format-support-color-cff2-expected.png index 5d9f3b2..da5949e2 100644 --- a/third_party/blink/web_tests/platform/win/fast/text/font-format-support-color-cff2-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/text/font-format-support-color-cff2-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/text/font-format-support-color-cff2-vertical-expected.png b/third_party/blink/web_tests/platform/win/fast/text/font-format-support-color-cff2-vertical-expected.png index f3bac6c..81e7782 100644 --- a/third_party/blink/web_tests/platform/win/fast/text/font-format-support-color-cff2-vertical-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/text/font-format-support-color-cff2-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/text/variable-fonts/cff2-variations-expected.png b/third_party/blink/web_tests/platform/win/fast/text/variable-fonts/cff2-variations-expected.png index 01b762e..0d9cf63 100644 --- a/third_party/blink/web_tests/platform/win/fast/text/variable-fonts/cff2-variations-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/text/variable-fonts/cff2-variations-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win7/fast/text/font-format-support-color-cff2-expected.png b/third_party/blink/web_tests/platform/win7/fast/text/font-format-support-color-cff2-expected.png index 287c942..9f7a787 100644 --- a/third_party/blink/web_tests/platform/win7/fast/text/font-format-support-color-cff2-expected.png +++ b/third_party/blink/web_tests/platform/win7/fast/text/font-format-support-color-cff2-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win7/fast/text/font-format-support-color-cff2-vertical-expected.png b/third_party/blink/web_tests/platform/win7/fast/text/font-format-support-color-cff2-vertical-expected.png index 16cd144..6ddb66c 100644 --- a/third_party/blink/web_tests/platform/win7/fast/text/font-format-support-color-cff2-vertical-expected.png +++ b/third_party/blink/web_tests/platform/win7/fast/text/font-format-support-color-cff2-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win7/fast/text/variable-fonts/cff2-variations-expected.png b/third_party/blink/web_tests/platform/win7/fast/text/variable-fonts/cff2-variations-expected.png index 5447a04..c2b6db8 100644 --- a/third_party/blink/web_tests/platform/win7/fast/text/variable-fonts/cff2-variations-expected.png +++ b/third_party/blink/web_tests/platform/win7/fast/text/variable-fonts/cff2-variations-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/shadow-dom/focus-flat-tree.html b/third_party/blink/web_tests/shadow-dom/focus-flat-tree.html new file mode 100644 index 0000000..41f8f70 --- /dev/null +++ b/third_party/blink/web_tests/shadow-dom/focus-flat-tree.html
@@ -0,0 +1,35 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script> +function clickOn(el) { + return new Promise(function(resolve, reject) { + chrome.gpuBenchmarking.pointerActionSequence([{ + source: 'mouse', + actions: [ + { name: 'pointerDown', + x: el.offsetLeft + 5, + y: el.offsetTop + 5 + }, + { name: 'pointerUp' } + ] + }], resolve); + }); +} +</script> +<body> + <div id='normalDiv' tabindex='0'><span id='normalSpan'>OK</span></div> + <div id='container'><span id='slottedSpan'>OK</span></div> +</body> +<script> +let sr = container.attachShadow({ mode: 'open' }); +sr.innerHTML = '<div id="shadowDiv" tabindex="0"><slot></slot></div>'; + +promise_test(async () => { + await clickOn(normalSpan); + assert_equals(document.activeElement, normalDiv); + await clickOn(slottedSpan); + assert_equals(sr.activeElement, sr.getElementById('shadowDiv')); +}, 'Clicking on non-focusable slot inside focusable button will make the flat-tree focusable ancestor get focused'); +</script>
diff --git a/third_party/blink/web_tests/virtual/paint-timing/external/wpt/paint-timing/idlharness.window-expected.txt b/third_party/blink/web_tests/virtual/paint-timing/external/wpt/paint-timing/idlharness.window-expected.txt deleted file mode 100644 index c3acfed..0000000 --- a/third_party/blink/web_tests/virtual/paint-timing/external/wpt/paint-timing/idlharness.window-expected.txt +++ /dev/null
@@ -1,12 +0,0 @@ -This is a testharness.js-based test. -FAIL idl_test setup promise_test: Unhandled rejection with value: "Timed out waiting for paint event" -PASS PerformancePaintTiming interface: existence and properties of interface object -PASS PerformancePaintTiming interface object length -PASS PerformancePaintTiming interface object name -PASS PerformancePaintTiming interface: existence and properties of interface prototype object -PASS PerformancePaintTiming interface: existence and properties of interface prototype object's "constructor" property -PASS PerformancePaintTiming interface: existence and properties of interface prototype object's @@unscopables property -FAIL PerformancePaintTiming must be primary interface of paintTiming assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: paintTiming is not defined" -FAIL Stringification of paintTiming assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: paintTiming is not defined" -Harness: the test ran to completion. -
diff --git a/third_party/boringssl/BUILD.generated.gni b/third_party/boringssl/BUILD.generated.gni index 4453b14..49ced59 100644 --- a/third_party/boringssl/BUILD.generated.gni +++ b/third_party/boringssl/BUILD.generated.gni
@@ -404,6 +404,7 @@ "ios-aarch64/crypto/fipsmodule/sha1-armv8.S", "ios-aarch64/crypto/fipsmodule/sha256-armv8.S", "ios-aarch64/crypto/fipsmodule/sha512-armv8.S", + "ios-aarch64/crypto/test/trampoline-armv8.S", ] crypto_sources_ios_arm = [ @@ -417,6 +418,7 @@ "ios-arm/crypto/fipsmodule/sha1-armv4-large.S", "ios-arm/crypto/fipsmodule/sha256-armv4.S", "ios-arm/crypto/fipsmodule/sha512-armv4.S", + "ios-arm/crypto/test/trampoline-armv4.S", ] crypto_sources_linux_aarch64 = [ @@ -427,6 +429,7 @@ "linux-aarch64/crypto/fipsmodule/sha1-armv8.S", "linux-aarch64/crypto/fipsmodule/sha256-armv8.S", "linux-aarch64/crypto/fipsmodule/sha512-armv8.S", + "linux-aarch64/crypto/test/trampoline-armv8.S", ] crypto_sources_linux_arm = [ @@ -440,6 +443,7 @@ "linux-arm/crypto/fipsmodule/sha1-armv4-large.S", "linux-arm/crypto/fipsmodule/sha256-armv4.S", "linux-arm/crypto/fipsmodule/sha512-armv4.S", + "linux-arm/crypto/test/trampoline-armv4.S", "src/crypto/curve25519/asm/x25519-asm-arm.S", "src/crypto/poly1305/poly1305_arm_asm.S", ]
diff --git a/third_party/boringssl/err_data.c b/third_party/boringssl/err_data.c index 46a7a86..f244bc7 100644 --- a/third_party/boringssl/err_data.c +++ b/third_party/boringssl/err_data.c
@@ -187,44 +187,44 @@ 0x28340c60, 0x283480ac, 0x283500ea, - 0x2c322eaf, + 0x2c322ec7, 0x2c3292bd, - 0x2c332ebd, - 0x2c33aecf, - 0x2c342ee3, - 0x2c34aef5, - 0x2c352f10, - 0x2c35af22, - 0x2c362f35, + 0x2c332ed5, + 0x2c33aee7, + 0x2c342efb, + 0x2c34af0d, + 0x2c352f28, + 0x2c35af3a, + 0x2c362f4d, 0x2c36832d, - 0x2c372f42, - 0x2c37af54, - 0x2c382f79, - 0x2c38af90, - 0x2c392f9e, - 0x2c39afae, - 0x2c3a2fc0, - 0x2c3aafd4, - 0x2c3b2fe5, - 0x2c3bb004, + 0x2c372f5a, + 0x2c37af6c, + 0x2c382f91, + 0x2c38afa8, + 0x2c392fb6, + 0x2c39afc6, + 0x2c3a2fd8, + 0x2c3aafec, + 0x2c3b2ffd, + 0x2c3bb01c, 0x2c3c12cf, 0x2c3c92e5, - 0x2c3d3018, + 0x2c3d3030, 0x2c3d92fe, - 0x2c3e3035, - 0x2c3eb043, - 0x2c3f305b, - 0x2c3fb073, - 0x2c40309d, + 0x2c3e304d, + 0x2c3eb05b, + 0x2c3f3073, + 0x2c3fb08b, + 0x2c4030b5, 0x2c4091d0, - 0x2c4130ae, - 0x2c41b0c1, + 0x2c4130c6, + 0x2c41b0d9, 0x2c421196, - 0x2c42b0d2, + 0x2c42b0ea, 0x2c430722, - 0x2c43aff6, - 0x2c442f67, - 0x2c44b080, + 0x2c43b00e, + 0x2c442f7f, + 0x2c44b098, 0x30320000, 0x30328015, 0x3033001f, @@ -421,177 +421,178 @@ 0x404f9f8f, 0x40501fe6, 0x40509ffa, - 0x40512015, - 0x40522025, - 0x4052a049, - 0x40532061, - 0x4053a074, - 0x40542089, - 0x4054a0ac, - 0x405520ba, - 0x4055a0f7, - 0x40562104, - 0x4056a11d, - 0x40572135, - 0x4057a148, - 0x4058215d, - 0x4058a184, - 0x405921b3, - 0x4059a1e0, - 0x405a21f4, - 0x405aa204, - 0x405b221c, - 0x405ba22d, - 0x405c2240, - 0x405ca27f, - 0x405d228c, - 0x405da2b1, - 0x405e22ef, + 0x4051202d, + 0x4052203d, + 0x4052a061, + 0x40532079, + 0x4053a08c, + 0x405420a1, + 0x4054a0c4, + 0x405520d2, + 0x4055a10f, + 0x4056211c, + 0x4056a135, + 0x4057214d, + 0x4057a160, + 0x40582175, + 0x4058a19c, + 0x405921cb, + 0x4059a1f8, + 0x405a220c, + 0x405aa21c, + 0x405b2234, + 0x405ba245, + 0x405c2258, + 0x405ca297, + 0x405d22a4, + 0x405da2c9, + 0x405e2307, 0x405e8ab3, - 0x405f2310, - 0x405fa31d, - 0x4060232b, - 0x4060a34d, - 0x406123ae, - 0x4061a3e6, - 0x406223fd, - 0x4062a40e, - 0x40632433, - 0x4063a448, - 0x4064245f, - 0x4064a48b, - 0x406524a6, - 0x4065a4bd, - 0x406624d5, - 0x4066a4ff, - 0x4067252a, - 0x4067a56f, - 0x406825b7, - 0x4068a5d8, - 0x4069260a, - 0x4069a638, - 0x406a2659, - 0x406aa679, - 0x406b2801, - 0x406ba824, - 0x406c283a, - 0x406caadd, - 0x406d2b0c, - 0x406dab34, - 0x406e2b62, - 0x406eabaf, - 0x406f2bea, - 0x406fac22, - 0x40702c35, - 0x4070ac52, + 0x405f2328, + 0x405fa335, + 0x40602343, + 0x4060a365, + 0x406123c6, + 0x4061a3fe, + 0x40622415, + 0x4062a426, + 0x4063244b, + 0x4063a460, + 0x40642477, + 0x4064a4a3, + 0x406524be, + 0x4065a4d5, + 0x406624ed, + 0x4066a517, + 0x40672542, + 0x4067a587, + 0x406825cf, + 0x4068a5f0, + 0x40692622, + 0x4069a650, + 0x406a2671, + 0x406aa691, + 0x406b2819, + 0x406ba83c, + 0x406c2852, + 0x406caaf5, + 0x406d2b24, + 0x406dab4c, + 0x406e2b7a, + 0x406eabc7, + 0x406f2c02, + 0x406fac3a, + 0x40702c4d, + 0x4070ac6a, 0x40710802, - 0x4071ac64, - 0x40722c77, - 0x4072acad, - 0x40732cc5, + 0x4071ac7c, + 0x40722c8f, + 0x4072acc5, + 0x40732cdd, 0x407394cf, - 0x40742cd9, - 0x4074acf3, - 0x40752d04, - 0x4075ad18, - 0x40762d26, + 0x40742cf1, + 0x4074ad0b, + 0x40752d1c, + 0x4075ad30, + 0x40762d3e, 0x40769293, - 0x40772d4b, - 0x4077ad6d, - 0x40782d88, - 0x4078adc1, - 0x40792dd8, - 0x4079adee, - 0x407a2e1a, - 0x407aae2d, - 0x407b2e42, - 0x407bae54, - 0x407c2e85, - 0x407cae8e, - 0x407d25f3, + 0x40772d63, + 0x4077ad85, + 0x40782da0, + 0x4078add9, + 0x40792df0, + 0x4079ae06, + 0x407a2e32, + 0x407aae45, + 0x407b2e5a, + 0x407bae6c, + 0x407c2e9d, + 0x407caea6, + 0x407d260b, 0x407d9f9f, - 0x407e2d9d, - 0x407ea194, + 0x407e2db5, + 0x407ea1ac, 0x407f1d2d, 0x407f9ad3, 0x40801f59, 0x40809d55, - 0x40812037, + 0x4081204f, 0x40819f33, - 0x40822b4d, + 0x40822b65, 0x40829ab9, - 0x4083216f, - 0x4083a470, + 0x40832187, + 0x4083a488, 0x40841d69, - 0x4084a1cc, - 0x40852251, - 0x4085a375, - 0x408622d1, + 0x4084a1e4, + 0x40852269, + 0x4085a38d, + 0x408622e9, 0x40869fb9, - 0x40872b93, - 0x4087a3c3, + 0x40872bab, + 0x4087a3db, 0x40881b1a, - 0x4088a582, + 0x4088a59a, 0x40891b69, 0x40899af6, - 0x408a2872, + 0x408a288a, 0x408a98e7, - 0x408b2e69, - 0x408babff, - 0x408c2261, + 0x408b2e81, + 0x408bac17, + 0x408c2279, 0x408c9903, 0x408d1dca, 0x408d9d9b, 0x408e1ee4, - 0x408ea0d7, - 0x408f2596, - 0x408fa391, - 0x4090254b, - 0x4090a2a3, - 0x4091285a, + 0x408ea0ef, + 0x408f25ae, + 0x408fa3a9, + 0x40902563, + 0x4090a2bb, + 0x40912872, 0x40919929, 0x40921bb6, - 0x4092abce, - 0x40932c90, + 0x4092abe6, + 0x40932ca8, 0x40939fca, 0x40941d7d, - 0x4094a88b, - 0x4095241f, - 0x4095adfa, - 0x40962b7a, + 0x4094a8a3, + 0x40952437, + 0x4095ae12, + 0x40962b92, 0x40969f72, - 0x41f4272c, - 0x41f927be, - 0x41fe26b1, - 0x41fea8ce, - 0x41ff29bf, - 0x42032745, - 0x42082767, - 0x4208a7a3, - 0x42092695, - 0x4209a7dd, - 0x420a26ec, - 0x420aa6cc, - 0x420b270c, - 0x420ba785, - 0x420c29db, - 0x420ca89b, - 0x420d28b5, - 0x420da8ec, - 0x42122906, - 0x421729a2, - 0x4217a948, - 0x421c296a, - 0x421f2925, - 0x422129f2, - 0x42262985, - 0x422b2ac1, - 0x422baa6f, - 0x422c2aa9, - 0x422caa2e, - 0x422d2a0d, - 0x422daa8e, - 0x422e2a54, + 0x40972015, + 0x41f42744, + 0x41f927d6, + 0x41fe26c9, + 0x41fea8e6, + 0x41ff29d7, + 0x4203275d, + 0x4208277f, + 0x4208a7bb, + 0x420926ad, + 0x4209a7f5, + 0x420a2704, + 0x420aa6e4, + 0x420b2724, + 0x420ba79d, + 0x420c29f3, + 0x420ca8b3, + 0x420d28cd, + 0x420da904, + 0x4212291e, + 0x421729ba, + 0x4217a960, + 0x421c2982, + 0x421f293d, + 0x42212a0a, + 0x4226299d, + 0x422b2ad9, + 0x422baa87, + 0x422c2ac1, + 0x422caa46, + 0x422d2a25, + 0x422daaa6, + 0x422e2a6c, 0x4432072d, 0x4432873c, 0x44330748, @@ -646,69 +647,69 @@ 0x4c41152c, 0x4c4193af, 0x4c421518, - 0x503230e4, - 0x5032b0f3, - 0x503330fe, - 0x5033b10e, - 0x50343127, - 0x5034b141, - 0x5035314f, - 0x5035b165, - 0x50363177, - 0x5036b18d, - 0x503731a6, - 0x5037b1b9, - 0x503831d1, - 0x5038b1e2, - 0x503931f7, - 0x5039b20b, - 0x503a322b, - 0x503ab241, - 0x503b3259, - 0x503bb26b, - 0x503c3287, - 0x503cb29e, - 0x503d32b7, - 0x503db2cd, - 0x503e32da, - 0x503eb2f0, - 0x503f3302, + 0x503230fc, + 0x5032b10b, + 0x50333116, + 0x5033b126, + 0x5034313f, + 0x5034b159, + 0x50353167, + 0x5035b17d, + 0x5036318f, + 0x5036b1a5, + 0x503731be, + 0x5037b1d1, + 0x503831e9, + 0x5038b1fa, + 0x5039320f, + 0x5039b223, + 0x503a3243, + 0x503ab259, + 0x503b3271, + 0x503bb283, + 0x503c329f, + 0x503cb2b6, + 0x503d32cf, + 0x503db2e5, + 0x503e32f2, + 0x503eb308, + 0x503f331a, 0x503f837b, - 0x50403315, - 0x5040b325, - 0x5041333f, - 0x5041b34e, - 0x50423368, - 0x5042b385, - 0x50433395, - 0x5043b3a5, - 0x504433b4, + 0x5040332d, + 0x5040b33d, + 0x50413357, + 0x5041b366, + 0x50423380, + 0x5042b39d, + 0x504333ad, + 0x5043b3bd, + 0x504433cc, 0x50448431, - 0x504533c8, - 0x5045b3e6, - 0x504633f9, - 0x5046b40f, - 0x50473421, - 0x5047b436, - 0x5048345c, - 0x5048b46a, - 0x5049347d, - 0x5049b492, - 0x504a34a8, - 0x504ab4b8, - 0x504b34d8, - 0x504bb4eb, - 0x504c350e, - 0x504cb53c, - 0x504d354e, - 0x504db56b, - 0x504e3586, - 0x504eb5a2, - 0x504f35b4, - 0x504fb5cb, - 0x505035da, + 0x504533e0, + 0x5045b3fe, + 0x50463411, + 0x5046b427, + 0x50473439, + 0x5047b44e, + 0x50483474, + 0x5048b482, + 0x50493495, + 0x5049b4aa, + 0x504a34c0, + 0x504ab4d0, + 0x504b34f0, + 0x504bb503, + 0x504c3526, + 0x504cb554, + 0x504d3566, + 0x504db583, + 0x504e359e, + 0x504eb5ba, + 0x504f35cc, + 0x504fb5e3, + 0x505035f2, 0x505086f1, - 0x505135ed, + 0x50513605, 0x58320f52, 0x68320f14, 0x68328c6c, @@ -1159,6 +1160,7 @@ "INVALID_SIGNATURE_ALGORITHM\0" "INVALID_SSL_SESSION\0" "INVALID_TICKET_KEYS_LENGTH\0" + "KEY_USAGE_BIT_INCORRECT\0" "LENGTH_MISMATCH\0" "MISSING_EXTENSION\0" "MISSING_KEY_SHARE\0"
diff --git a/third_party/boringssl/ios-aarch64/crypto/test/trampoline-armv8.S b/third_party/boringssl/ios-aarch64/crypto/test/trampoline-armv8.S new file mode 100644 index 0000000..95a41fe5 --- /dev/null +++ b/third_party/boringssl/ios-aarch64/crypto/test/trampoline-armv8.S
@@ -0,0 +1,684 @@ +// This file is generated from a similarly-named Perl script in the BoringSSL +// source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if !defined(OPENSSL_NO_ASM) +#if defined(BORINGSSL_PREFIX) +#include <boringssl_prefix_symbols_asm.h> +#endif +.text + +// abi_test_trampoline loads callee-saved registers from |state|, calls |func| +// with |argv|, then saves the callee-saved registers into |state|. It returns +// the result of |func|. The |unwind| argument is unused. +// uint64_t abi_test_trampoline(void (*func)(...), CallerState *state, +// const uint64_t *argv, size_t argc, +// uint64_t unwind); + +.globl _abi_test_trampoline +.private_extern _abi_test_trampoline +.align 4 +_abi_test_trampoline: +Labi_test_trampoline_begin: + // Stack layout (low to high addresses) + // x29,x30 (16 bytes) + // d8-d15 (64 bytes) + // x19-x28 (80 bytes) + // x1 (8 bytes) + // padding (8 bytes) + stp x29, x30, [sp, #-176]! + mov x29, sp + + // Saved callee-saved registers and |state|. + stp d8, d9, [sp, #16] + stp d10, d11, [sp, #32] + stp d12, d13, [sp, #48] + stp d14, d15, [sp, #64] + stp x19, x20, [sp, #80] + stp x21, x22, [sp, #96] + stp x23, x24, [sp, #112] + stp x25, x26, [sp, #128] + stp x27, x28, [sp, #144] + str x1, [sp, #160] + + // Load registers from |state|, with the exception of x29. x29 is the + // frame pointer and also callee-saved, but AAPCS64 allows platforms to + // mandate that x29 always point to a frame. iOS64 does so, which means + // we cannot fill x29 with entropy without violating ABI rules + // ourselves. x29 is tested separately below. + ldp d8, d9, [x1], #16 + ldp d10, d11, [x1], #16 + ldp d12, d13, [x1], #16 + ldp d14, d15, [x1], #16 + ldp x19, x20, [x1], #16 + ldp x21, x22, [x1], #16 + ldp x23, x24, [x1], #16 + ldp x25, x26, [x1], #16 + ldp x27, x28, [x1], #16 + + // Move parameters into temporary registers. + mov x9, x0 + mov x10, x2 + mov x11, x3 + + // Load parameters into registers. + cbz x11, Largs_done + ldr x0, [x10], #8 + subs x11, x11, #1 + b.eq Largs_done + ldr x1, [x10], #8 + subs x11, x11, #1 + b.eq Largs_done + ldr x2, [x10], #8 + subs x11, x11, #1 + b.eq Largs_done + ldr x3, [x10], #8 + subs x11, x11, #1 + b.eq Largs_done + ldr x4, [x10], #8 + subs x11, x11, #1 + b.eq Largs_done + ldr x5, [x10], #8 + subs x11, x11, #1 + b.eq Largs_done + ldr x6, [x10], #8 + subs x11, x11, #1 + b.eq Largs_done + ldr x7, [x10], #8 + +Largs_done: + blr x9 + + // Reload |state| and store registers. + ldr x1, [sp, #160] + stp d8, d9, [x1], #16 + stp d10, d11, [x1], #16 + stp d12, d13, [x1], #16 + stp d14, d15, [x1], #16 + stp x19, x20, [x1], #16 + stp x21, x22, [x1], #16 + stp x23, x24, [x1], #16 + stp x25, x26, [x1], #16 + stp x27, x28, [x1], #16 + + // |func| is required to preserve x29, the frame pointer. We cannot load + // random values into x29 (see comment above), so compare it against the + // expected value and zero the field of |state| if corrupted. + mov x9, sp + cmp x29, x9 + b.eq Lx29_ok + str xzr, [x1] + +Lx29_ok: + // Restore callee-saved registers. + ldp d8, d9, [sp, #16] + ldp d10, d11, [sp, #32] + ldp d12, d13, [sp, #48] + ldp d14, d15, [sp, #64] + ldp x19, x20, [sp, #80] + ldp x21, x22, [sp, #96] + ldp x23, x24, [sp, #112] + ldp x25, x26, [sp, #128] + ldp x27, x28, [sp, #144] + + ldp x29, x30, [sp], #176 + ret + + +.globl _abi_test_clobber_x0 +.private_extern _abi_test_clobber_x0 +.align 4 +_abi_test_clobber_x0: + mov x0, xzr + ret + + +.globl _abi_test_clobber_x1 +.private_extern _abi_test_clobber_x1 +.align 4 +_abi_test_clobber_x1: + mov x1, xzr + ret + + +.globl _abi_test_clobber_x2 +.private_extern _abi_test_clobber_x2 +.align 4 +_abi_test_clobber_x2: + mov x2, xzr + ret + + +.globl _abi_test_clobber_x3 +.private_extern _abi_test_clobber_x3 +.align 4 +_abi_test_clobber_x3: + mov x3, xzr + ret + + +.globl _abi_test_clobber_x4 +.private_extern _abi_test_clobber_x4 +.align 4 +_abi_test_clobber_x4: + mov x4, xzr + ret + + +.globl _abi_test_clobber_x5 +.private_extern _abi_test_clobber_x5 +.align 4 +_abi_test_clobber_x5: + mov x5, xzr + ret + + +.globl _abi_test_clobber_x6 +.private_extern _abi_test_clobber_x6 +.align 4 +_abi_test_clobber_x6: + mov x6, xzr + ret + + +.globl _abi_test_clobber_x7 +.private_extern _abi_test_clobber_x7 +.align 4 +_abi_test_clobber_x7: + mov x7, xzr + ret + + +.globl _abi_test_clobber_x8 +.private_extern _abi_test_clobber_x8 +.align 4 +_abi_test_clobber_x8: + mov x8, xzr + ret + + +.globl _abi_test_clobber_x9 +.private_extern _abi_test_clobber_x9 +.align 4 +_abi_test_clobber_x9: + mov x9, xzr + ret + + +.globl _abi_test_clobber_x10 +.private_extern _abi_test_clobber_x10 +.align 4 +_abi_test_clobber_x10: + mov x10, xzr + ret + + +.globl _abi_test_clobber_x11 +.private_extern _abi_test_clobber_x11 +.align 4 +_abi_test_clobber_x11: + mov x11, xzr + ret + + +.globl _abi_test_clobber_x12 +.private_extern _abi_test_clobber_x12 +.align 4 +_abi_test_clobber_x12: + mov x12, xzr + ret + + +.globl _abi_test_clobber_x13 +.private_extern _abi_test_clobber_x13 +.align 4 +_abi_test_clobber_x13: + mov x13, xzr + ret + + +.globl _abi_test_clobber_x14 +.private_extern _abi_test_clobber_x14 +.align 4 +_abi_test_clobber_x14: + mov x14, xzr + ret + + +.globl _abi_test_clobber_x15 +.private_extern _abi_test_clobber_x15 +.align 4 +_abi_test_clobber_x15: + mov x15, xzr + ret + + +.globl _abi_test_clobber_x16 +.private_extern _abi_test_clobber_x16 +.align 4 +_abi_test_clobber_x16: + mov x16, xzr + ret + + +.globl _abi_test_clobber_x17 +.private_extern _abi_test_clobber_x17 +.align 4 +_abi_test_clobber_x17: + mov x17, xzr + ret + + +.globl _abi_test_clobber_x19 +.private_extern _abi_test_clobber_x19 +.align 4 +_abi_test_clobber_x19: + mov x19, xzr + ret + + +.globl _abi_test_clobber_x20 +.private_extern _abi_test_clobber_x20 +.align 4 +_abi_test_clobber_x20: + mov x20, xzr + ret + + +.globl _abi_test_clobber_x21 +.private_extern _abi_test_clobber_x21 +.align 4 +_abi_test_clobber_x21: + mov x21, xzr + ret + + +.globl _abi_test_clobber_x22 +.private_extern _abi_test_clobber_x22 +.align 4 +_abi_test_clobber_x22: + mov x22, xzr + ret + + +.globl _abi_test_clobber_x23 +.private_extern _abi_test_clobber_x23 +.align 4 +_abi_test_clobber_x23: + mov x23, xzr + ret + + +.globl _abi_test_clobber_x24 +.private_extern _abi_test_clobber_x24 +.align 4 +_abi_test_clobber_x24: + mov x24, xzr + ret + + +.globl _abi_test_clobber_x25 +.private_extern _abi_test_clobber_x25 +.align 4 +_abi_test_clobber_x25: + mov x25, xzr + ret + + +.globl _abi_test_clobber_x26 +.private_extern _abi_test_clobber_x26 +.align 4 +_abi_test_clobber_x26: + mov x26, xzr + ret + + +.globl _abi_test_clobber_x27 +.private_extern _abi_test_clobber_x27 +.align 4 +_abi_test_clobber_x27: + mov x27, xzr + ret + + +.globl _abi_test_clobber_x28 +.private_extern _abi_test_clobber_x28 +.align 4 +_abi_test_clobber_x28: + mov x28, xzr + ret + + +.globl _abi_test_clobber_x29 +.private_extern _abi_test_clobber_x29 +.align 4 +_abi_test_clobber_x29: + mov x29, xzr + ret + + +.globl _abi_test_clobber_d0 +.private_extern _abi_test_clobber_d0 +.align 4 +_abi_test_clobber_d0: + fmov d0, xzr + ret + + +.globl _abi_test_clobber_d1 +.private_extern _abi_test_clobber_d1 +.align 4 +_abi_test_clobber_d1: + fmov d1, xzr + ret + + +.globl _abi_test_clobber_d2 +.private_extern _abi_test_clobber_d2 +.align 4 +_abi_test_clobber_d2: + fmov d2, xzr + ret + + +.globl _abi_test_clobber_d3 +.private_extern _abi_test_clobber_d3 +.align 4 +_abi_test_clobber_d3: + fmov d3, xzr + ret + + +.globl _abi_test_clobber_d4 +.private_extern _abi_test_clobber_d4 +.align 4 +_abi_test_clobber_d4: + fmov d4, xzr + ret + + +.globl _abi_test_clobber_d5 +.private_extern _abi_test_clobber_d5 +.align 4 +_abi_test_clobber_d5: + fmov d5, xzr + ret + + +.globl _abi_test_clobber_d6 +.private_extern _abi_test_clobber_d6 +.align 4 +_abi_test_clobber_d6: + fmov d6, xzr + ret + + +.globl _abi_test_clobber_d7 +.private_extern _abi_test_clobber_d7 +.align 4 +_abi_test_clobber_d7: + fmov d7, xzr + ret + + +.globl _abi_test_clobber_d8 +.private_extern _abi_test_clobber_d8 +.align 4 +_abi_test_clobber_d8: + fmov d8, xzr + ret + + +.globl _abi_test_clobber_d9 +.private_extern _abi_test_clobber_d9 +.align 4 +_abi_test_clobber_d9: + fmov d9, xzr + ret + + +.globl _abi_test_clobber_d10 +.private_extern _abi_test_clobber_d10 +.align 4 +_abi_test_clobber_d10: + fmov d10, xzr + ret + + +.globl _abi_test_clobber_d11 +.private_extern _abi_test_clobber_d11 +.align 4 +_abi_test_clobber_d11: + fmov d11, xzr + ret + + +.globl _abi_test_clobber_d12 +.private_extern _abi_test_clobber_d12 +.align 4 +_abi_test_clobber_d12: + fmov d12, xzr + ret + + +.globl _abi_test_clobber_d13 +.private_extern _abi_test_clobber_d13 +.align 4 +_abi_test_clobber_d13: + fmov d13, xzr + ret + + +.globl _abi_test_clobber_d14 +.private_extern _abi_test_clobber_d14 +.align 4 +_abi_test_clobber_d14: + fmov d14, xzr + ret + + +.globl _abi_test_clobber_d15 +.private_extern _abi_test_clobber_d15 +.align 4 +_abi_test_clobber_d15: + fmov d15, xzr + ret + + +.globl _abi_test_clobber_d16 +.private_extern _abi_test_clobber_d16 +.align 4 +_abi_test_clobber_d16: + fmov d16, xzr + ret + + +.globl _abi_test_clobber_d17 +.private_extern _abi_test_clobber_d17 +.align 4 +_abi_test_clobber_d17: + fmov d17, xzr + ret + + +.globl _abi_test_clobber_d18 +.private_extern _abi_test_clobber_d18 +.align 4 +_abi_test_clobber_d18: + fmov d18, xzr + ret + + +.globl _abi_test_clobber_d19 +.private_extern _abi_test_clobber_d19 +.align 4 +_abi_test_clobber_d19: + fmov d19, xzr + ret + + +.globl _abi_test_clobber_d20 +.private_extern _abi_test_clobber_d20 +.align 4 +_abi_test_clobber_d20: + fmov d20, xzr + ret + + +.globl _abi_test_clobber_d21 +.private_extern _abi_test_clobber_d21 +.align 4 +_abi_test_clobber_d21: + fmov d21, xzr + ret + + +.globl _abi_test_clobber_d22 +.private_extern _abi_test_clobber_d22 +.align 4 +_abi_test_clobber_d22: + fmov d22, xzr + ret + + +.globl _abi_test_clobber_d23 +.private_extern _abi_test_clobber_d23 +.align 4 +_abi_test_clobber_d23: + fmov d23, xzr + ret + + +.globl _abi_test_clobber_d24 +.private_extern _abi_test_clobber_d24 +.align 4 +_abi_test_clobber_d24: + fmov d24, xzr + ret + + +.globl _abi_test_clobber_d25 +.private_extern _abi_test_clobber_d25 +.align 4 +_abi_test_clobber_d25: + fmov d25, xzr + ret + + +.globl _abi_test_clobber_d26 +.private_extern _abi_test_clobber_d26 +.align 4 +_abi_test_clobber_d26: + fmov d26, xzr + ret + + +.globl _abi_test_clobber_d27 +.private_extern _abi_test_clobber_d27 +.align 4 +_abi_test_clobber_d27: + fmov d27, xzr + ret + + +.globl _abi_test_clobber_d28 +.private_extern _abi_test_clobber_d28 +.align 4 +_abi_test_clobber_d28: + fmov d28, xzr + ret + + +.globl _abi_test_clobber_d29 +.private_extern _abi_test_clobber_d29 +.align 4 +_abi_test_clobber_d29: + fmov d29, xzr + ret + + +.globl _abi_test_clobber_d30 +.private_extern _abi_test_clobber_d30 +.align 4 +_abi_test_clobber_d30: + fmov d30, xzr + ret + + +.globl _abi_test_clobber_d31 +.private_extern _abi_test_clobber_d31 +.align 4 +_abi_test_clobber_d31: + fmov d31, xzr + ret + + +.globl _abi_test_clobber_v8_upper +.private_extern _abi_test_clobber_v8_upper +.align 4 +_abi_test_clobber_v8_upper: + fmov v8.d[1], xzr + ret + + +.globl _abi_test_clobber_v9_upper +.private_extern _abi_test_clobber_v9_upper +.align 4 +_abi_test_clobber_v9_upper: + fmov v9.d[1], xzr + ret + + +.globl _abi_test_clobber_v10_upper +.private_extern _abi_test_clobber_v10_upper +.align 4 +_abi_test_clobber_v10_upper: + fmov v10.d[1], xzr + ret + + +.globl _abi_test_clobber_v11_upper +.private_extern _abi_test_clobber_v11_upper +.align 4 +_abi_test_clobber_v11_upper: + fmov v11.d[1], xzr + ret + + +.globl _abi_test_clobber_v12_upper +.private_extern _abi_test_clobber_v12_upper +.align 4 +_abi_test_clobber_v12_upper: + fmov v12.d[1], xzr + ret + + +.globl _abi_test_clobber_v13_upper +.private_extern _abi_test_clobber_v13_upper +.align 4 +_abi_test_clobber_v13_upper: + fmov v13.d[1], xzr + ret + + +.globl _abi_test_clobber_v14_upper +.private_extern _abi_test_clobber_v14_upper +.align 4 +_abi_test_clobber_v14_upper: + fmov v14.d[1], xzr + ret + + +.globl _abi_test_clobber_v15_upper +.private_extern _abi_test_clobber_v15_upper +.align 4 +_abi_test_clobber_v15_upper: + fmov v15.d[1], xzr + ret + +#endif // !OPENSSL_NO_ASM
diff --git a/third_party/boringssl/ios-arm/crypto/test/trampoline-armv4.S b/third_party/boringssl/ios-arm/crypto/test/trampoline-armv4.S new file mode 100644 index 0000000..894be8d --- /dev/null +++ b/third_party/boringssl/ios-arm/crypto/test/trampoline-armv4.S
@@ -0,0 +1,376 @@ +// This file is generated from a similarly-named Perl script in the BoringSSL +// source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if !defined(OPENSSL_NO_ASM) +#if defined(BORINGSSL_PREFIX) +#include <boringssl_prefix_symbols_asm.h> +#endif +.syntax unified + + + + +.text + +@ abi_test_trampoline loads callee-saved registers from |state|, calls |func| +@ with |argv|, then saves the callee-saved registers into |state|. It returns +@ the result of |func|. The |unwind| argument is unused. +@ uint32_t abi_test_trampoline(void (*func)(...), CallerState *state, +@ const uint32_t *argv, size_t argc, +@ int unwind); + +.globl _abi_test_trampoline +.private_extern _abi_test_trampoline +.align 4 +_abi_test_trampoline: +Labi_test_trampoline_begin: + @ Save parameters and all callee-saved registers. For convenience, we + @ save r9 on iOS even though it's volatile. + vstmdb sp!, {d8,d9,d10,d11,d12,d13,d14,d15} + stmdb sp!, {r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,lr} + + @ Reserve stack space for six (10-4) stack parameters, plus an extra 4 + @ bytes to keep it 8-byte-aligned (see APCS, section 5.3). + sub sp, sp, #28 + + @ Every register in APCS is either non-volatile or a parameter (except + @ r9 on iOS), so this code, by the actual call, loses all its scratch + @ registers. First fill in stack parameters while there are registers + @ to spare. + cmp r3, #4 + bls Lstack_args_done + mov r4, sp @ r4 is the output pointer. + add r5, r2, r3, lsl #2 @ Set r5 to the end of argv. + add r2, r2, #16 @ Skip four arguments. +Lstack_args_loop: + ldr r6, [r2], #4 + cmp r2, r5 + str r6, [r4], #4 + bne Lstack_args_loop + +Lstack_args_done: + @ Load registers from |r1|. + vldmia r1!, {d8,d9,d10,d11,d12,d13,d14,d15} +#if defined(__APPLE__) + @ r9 is not volatile on iOS. + ldmia r1!, {r4,r5,r6,r7,r8,r10-r11} +#else + ldmia r1!, {r4,r5,r6,r7,r8,r9,r10,r11} +#endif + + @ Load register parameters. This uses up our remaining registers, so we + @ repurpose lr as scratch space. + ldr r3, [sp, #40] @ Reload argc. + ldr lr, [sp, #36] @ Load argv into lr. + cmp r3, #3 + bhi Larg_r3 + beq Larg_r2 + cmp r3, #1 + bhi Larg_r1 + beq Larg_r0 + b Largs_done + +Larg_r3: + ldr r3, [lr, #12] @ argv[3] +Larg_r2: + ldr r2, [lr, #8] @ argv[2] +Larg_r1: + ldr r1, [lr, #4] @ argv[1] +Larg_r0: + ldr r0, [lr] @ argv[0] +Largs_done: + + @ With every other register in use, load the function pointer into lr + @ and call the function. + ldr lr, [sp, #28] + blx lr + + @ r1-r3 are free for use again. The trampoline only supports + @ single-return functions. Pass r4-r11 to the caller. + ldr r1, [sp, #32] + vstmia r1!, {d8,d9,d10,d11,d12,d13,d14,d15} +#if defined(__APPLE__) + @ r9 is not volatile on iOS. + stmia r1!, {r4,r5,r6,r7,r8,r10-r11} +#else + stmia r1!, {r4,r5,r6,r7,r8,r9,r10,r11} +#endif + + @ Unwind the stack and restore registers. + add sp, sp, #44 @ 44 = 28+16 + ldmia sp!, {r4,r5,r6,r7,r8,r9,r10,r11,lr} @ Skip r0-r3 (see +16 above). + vldmia sp!, {d8,d9,d10,d11,d12,d13,d14,d15} + + bx lr + + +.globl _abi_test_clobber_r0 +.private_extern _abi_test_clobber_r0 +.align 4 +_abi_test_clobber_r0: + mov r0, #0 + bx lr + + +.globl _abi_test_clobber_r1 +.private_extern _abi_test_clobber_r1 +.align 4 +_abi_test_clobber_r1: + mov r1, #0 + bx lr + + +.globl _abi_test_clobber_r2 +.private_extern _abi_test_clobber_r2 +.align 4 +_abi_test_clobber_r2: + mov r2, #0 + bx lr + + +.globl _abi_test_clobber_r3 +.private_extern _abi_test_clobber_r3 +.align 4 +_abi_test_clobber_r3: + mov r3, #0 + bx lr + + +.globl _abi_test_clobber_r4 +.private_extern _abi_test_clobber_r4 +.align 4 +_abi_test_clobber_r4: + mov r4, #0 + bx lr + + +.globl _abi_test_clobber_r5 +.private_extern _abi_test_clobber_r5 +.align 4 +_abi_test_clobber_r5: + mov r5, #0 + bx lr + + +.globl _abi_test_clobber_r6 +.private_extern _abi_test_clobber_r6 +.align 4 +_abi_test_clobber_r6: + mov r6, #0 + bx lr + + +.globl _abi_test_clobber_r7 +.private_extern _abi_test_clobber_r7 +.align 4 +_abi_test_clobber_r7: + mov r7, #0 + bx lr + + +.globl _abi_test_clobber_r8 +.private_extern _abi_test_clobber_r8 +.align 4 +_abi_test_clobber_r8: + mov r8, #0 + bx lr + + +.globl _abi_test_clobber_r9 +.private_extern _abi_test_clobber_r9 +.align 4 +_abi_test_clobber_r9: + mov r9, #0 + bx lr + + +.globl _abi_test_clobber_r10 +.private_extern _abi_test_clobber_r10 +.align 4 +_abi_test_clobber_r10: + mov r10, #0 + bx lr + + +.globl _abi_test_clobber_r11 +.private_extern _abi_test_clobber_r11 +.align 4 +_abi_test_clobber_r11: + mov r11, #0 + bx lr + + +.globl _abi_test_clobber_r12 +.private_extern _abi_test_clobber_r12 +.align 4 +_abi_test_clobber_r12: + mov r12, #0 + bx lr + + +.globl _abi_test_clobber_d0 +.private_extern _abi_test_clobber_d0 +.align 4 +_abi_test_clobber_d0: + mov r0, #0 + vmov s0, r0 + vmov s1, r0 + bx lr + + +.globl _abi_test_clobber_d1 +.private_extern _abi_test_clobber_d1 +.align 4 +_abi_test_clobber_d1: + mov r0, #0 + vmov s2, r0 + vmov s3, r0 + bx lr + + +.globl _abi_test_clobber_d2 +.private_extern _abi_test_clobber_d2 +.align 4 +_abi_test_clobber_d2: + mov r0, #0 + vmov s4, r0 + vmov s5, r0 + bx lr + + +.globl _abi_test_clobber_d3 +.private_extern _abi_test_clobber_d3 +.align 4 +_abi_test_clobber_d3: + mov r0, #0 + vmov s6, r0 + vmov s7, r0 + bx lr + + +.globl _abi_test_clobber_d4 +.private_extern _abi_test_clobber_d4 +.align 4 +_abi_test_clobber_d4: + mov r0, #0 + vmov s8, r0 + vmov s9, r0 + bx lr + + +.globl _abi_test_clobber_d5 +.private_extern _abi_test_clobber_d5 +.align 4 +_abi_test_clobber_d5: + mov r0, #0 + vmov s10, r0 + vmov s11, r0 + bx lr + + +.globl _abi_test_clobber_d6 +.private_extern _abi_test_clobber_d6 +.align 4 +_abi_test_clobber_d6: + mov r0, #0 + vmov s12, r0 + vmov s13, r0 + bx lr + + +.globl _abi_test_clobber_d7 +.private_extern _abi_test_clobber_d7 +.align 4 +_abi_test_clobber_d7: + mov r0, #0 + vmov s14, r0 + vmov s15, r0 + bx lr + + +.globl _abi_test_clobber_d8 +.private_extern _abi_test_clobber_d8 +.align 4 +_abi_test_clobber_d8: + mov r0, #0 + vmov s16, r0 + vmov s17, r0 + bx lr + + +.globl _abi_test_clobber_d9 +.private_extern _abi_test_clobber_d9 +.align 4 +_abi_test_clobber_d9: + mov r0, #0 + vmov s18, r0 + vmov s19, r0 + bx lr + + +.globl _abi_test_clobber_d10 +.private_extern _abi_test_clobber_d10 +.align 4 +_abi_test_clobber_d10: + mov r0, #0 + vmov s20, r0 + vmov s21, r0 + bx lr + + +.globl _abi_test_clobber_d11 +.private_extern _abi_test_clobber_d11 +.align 4 +_abi_test_clobber_d11: + mov r0, #0 + vmov s22, r0 + vmov s23, r0 + bx lr + + +.globl _abi_test_clobber_d12 +.private_extern _abi_test_clobber_d12 +.align 4 +_abi_test_clobber_d12: + mov r0, #0 + vmov s24, r0 + vmov s25, r0 + bx lr + + +.globl _abi_test_clobber_d13 +.private_extern _abi_test_clobber_d13 +.align 4 +_abi_test_clobber_d13: + mov r0, #0 + vmov s26, r0 + vmov s27, r0 + bx lr + + +.globl _abi_test_clobber_d14 +.private_extern _abi_test_clobber_d14 +.align 4 +_abi_test_clobber_d14: + mov r0, #0 + vmov s28, r0 + vmov s29, r0 + bx lr + + +.globl _abi_test_clobber_d15 +.private_extern _abi_test_clobber_d15 +.align 4 +_abi_test_clobber_d15: + mov r0, #0 + vmov s30, r0 + vmov s31, r0 + bx lr + +#endif // !OPENSSL_NO_ASM
diff --git a/third_party/boringssl/linux-aarch64/crypto/test/trampoline-armv8.S b/third_party/boringssl/linux-aarch64/crypto/test/trampoline-armv8.S new file mode 100644 index 0000000..56c79c43 --- /dev/null +++ b/third_party/boringssl/linux-aarch64/crypto/test/trampoline-armv8.S
@@ -0,0 +1,686 @@ +// This file is generated from a similarly-named Perl script in the BoringSSL +// source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if !defined(OPENSSL_NO_ASM) +#if defined(__aarch64__) +#if defined(BORINGSSL_PREFIX) +#include <boringssl_prefix_symbols_asm.h> +#endif +.text + +// abi_test_trampoline loads callee-saved registers from |state|, calls |func| +// with |argv|, then saves the callee-saved registers into |state|. It returns +// the result of |func|. The |unwind| argument is unused. +// uint64_t abi_test_trampoline(void (*func)(...), CallerState *state, +// const uint64_t *argv, size_t argc, +// uint64_t unwind); +.type abi_test_trampoline, %function +.globl abi_test_trampoline +.hidden abi_test_trampoline +.align 4 +abi_test_trampoline: +.Labi_test_trampoline_begin: + // Stack layout (low to high addresses) + // x29,x30 (16 bytes) + // d8-d15 (64 bytes) + // x19-x28 (80 bytes) + // x1 (8 bytes) + // padding (8 bytes) + stp x29, x30, [sp, #-176]! + mov x29, sp + + // Saved callee-saved registers and |state|. + stp d8, d9, [sp, #16] + stp d10, d11, [sp, #32] + stp d12, d13, [sp, #48] + stp d14, d15, [sp, #64] + stp x19, x20, [sp, #80] + stp x21, x22, [sp, #96] + stp x23, x24, [sp, #112] + stp x25, x26, [sp, #128] + stp x27, x28, [sp, #144] + str x1, [sp, #160] + + // Load registers from |state|, with the exception of x29. x29 is the + // frame pointer and also callee-saved, but AAPCS64 allows platforms to + // mandate that x29 always point to a frame. iOS64 does so, which means + // we cannot fill x29 with entropy without violating ABI rules + // ourselves. x29 is tested separately below. + ldp d8, d9, [x1], #16 + ldp d10, d11, [x1], #16 + ldp d12, d13, [x1], #16 + ldp d14, d15, [x1], #16 + ldp x19, x20, [x1], #16 + ldp x21, x22, [x1], #16 + ldp x23, x24, [x1], #16 + ldp x25, x26, [x1], #16 + ldp x27, x28, [x1], #16 + + // Move parameters into temporary registers. + mov x9, x0 + mov x10, x2 + mov x11, x3 + + // Load parameters into registers. + cbz x11, .Largs_done + ldr x0, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x1, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x2, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x3, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x4, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x5, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x6, [x10], #8 + subs x11, x11, #1 + b.eq .Largs_done + ldr x7, [x10], #8 + +.Largs_done: + blr x9 + + // Reload |state| and store registers. + ldr x1, [sp, #160] + stp d8, d9, [x1], #16 + stp d10, d11, [x1], #16 + stp d12, d13, [x1], #16 + stp d14, d15, [x1], #16 + stp x19, x20, [x1], #16 + stp x21, x22, [x1], #16 + stp x23, x24, [x1], #16 + stp x25, x26, [x1], #16 + stp x27, x28, [x1], #16 + + // |func| is required to preserve x29, the frame pointer. We cannot load + // random values into x29 (see comment above), so compare it against the + // expected value and zero the field of |state| if corrupted. + mov x9, sp + cmp x29, x9 + b.eq .Lx29_ok + str xzr, [x1] + +.Lx29_ok: + // Restore callee-saved registers. + ldp d8, d9, [sp, #16] + ldp d10, d11, [sp, #32] + ldp d12, d13, [sp, #48] + ldp d14, d15, [sp, #64] + ldp x19, x20, [sp, #80] + ldp x21, x22, [sp, #96] + ldp x23, x24, [sp, #112] + ldp x25, x26, [sp, #128] + ldp x27, x28, [sp, #144] + + ldp x29, x30, [sp], #176 + ret +.size abi_test_trampoline,.-abi_test_trampoline +.type abi_test_clobber_x0, %function +.globl abi_test_clobber_x0 +.hidden abi_test_clobber_x0 +.align 4 +abi_test_clobber_x0: + mov x0, xzr + ret +.size abi_test_clobber_x0,.-abi_test_clobber_x0 +.type abi_test_clobber_x1, %function +.globl abi_test_clobber_x1 +.hidden abi_test_clobber_x1 +.align 4 +abi_test_clobber_x1: + mov x1, xzr + ret +.size abi_test_clobber_x1,.-abi_test_clobber_x1 +.type abi_test_clobber_x2, %function +.globl abi_test_clobber_x2 +.hidden abi_test_clobber_x2 +.align 4 +abi_test_clobber_x2: + mov x2, xzr + ret +.size abi_test_clobber_x2,.-abi_test_clobber_x2 +.type abi_test_clobber_x3, %function +.globl abi_test_clobber_x3 +.hidden abi_test_clobber_x3 +.align 4 +abi_test_clobber_x3: + mov x3, xzr + ret +.size abi_test_clobber_x3,.-abi_test_clobber_x3 +.type abi_test_clobber_x4, %function +.globl abi_test_clobber_x4 +.hidden abi_test_clobber_x4 +.align 4 +abi_test_clobber_x4: + mov x4, xzr + ret +.size abi_test_clobber_x4,.-abi_test_clobber_x4 +.type abi_test_clobber_x5, %function +.globl abi_test_clobber_x5 +.hidden abi_test_clobber_x5 +.align 4 +abi_test_clobber_x5: + mov x5, xzr + ret +.size abi_test_clobber_x5,.-abi_test_clobber_x5 +.type abi_test_clobber_x6, %function +.globl abi_test_clobber_x6 +.hidden abi_test_clobber_x6 +.align 4 +abi_test_clobber_x6: + mov x6, xzr + ret +.size abi_test_clobber_x6,.-abi_test_clobber_x6 +.type abi_test_clobber_x7, %function +.globl abi_test_clobber_x7 +.hidden abi_test_clobber_x7 +.align 4 +abi_test_clobber_x7: + mov x7, xzr + ret +.size abi_test_clobber_x7,.-abi_test_clobber_x7 +.type abi_test_clobber_x8, %function +.globl abi_test_clobber_x8 +.hidden abi_test_clobber_x8 +.align 4 +abi_test_clobber_x8: + mov x8, xzr + ret +.size abi_test_clobber_x8,.-abi_test_clobber_x8 +.type abi_test_clobber_x9, %function +.globl abi_test_clobber_x9 +.hidden abi_test_clobber_x9 +.align 4 +abi_test_clobber_x9: + mov x9, xzr + ret +.size abi_test_clobber_x9,.-abi_test_clobber_x9 +.type abi_test_clobber_x10, %function +.globl abi_test_clobber_x10 +.hidden abi_test_clobber_x10 +.align 4 +abi_test_clobber_x10: + mov x10, xzr + ret +.size abi_test_clobber_x10,.-abi_test_clobber_x10 +.type abi_test_clobber_x11, %function +.globl abi_test_clobber_x11 +.hidden abi_test_clobber_x11 +.align 4 +abi_test_clobber_x11: + mov x11, xzr + ret +.size abi_test_clobber_x11,.-abi_test_clobber_x11 +.type abi_test_clobber_x12, %function +.globl abi_test_clobber_x12 +.hidden abi_test_clobber_x12 +.align 4 +abi_test_clobber_x12: + mov x12, xzr + ret +.size abi_test_clobber_x12,.-abi_test_clobber_x12 +.type abi_test_clobber_x13, %function +.globl abi_test_clobber_x13 +.hidden abi_test_clobber_x13 +.align 4 +abi_test_clobber_x13: + mov x13, xzr + ret +.size abi_test_clobber_x13,.-abi_test_clobber_x13 +.type abi_test_clobber_x14, %function +.globl abi_test_clobber_x14 +.hidden abi_test_clobber_x14 +.align 4 +abi_test_clobber_x14: + mov x14, xzr + ret +.size abi_test_clobber_x14,.-abi_test_clobber_x14 +.type abi_test_clobber_x15, %function +.globl abi_test_clobber_x15 +.hidden abi_test_clobber_x15 +.align 4 +abi_test_clobber_x15: + mov x15, xzr + ret +.size abi_test_clobber_x15,.-abi_test_clobber_x15 +.type abi_test_clobber_x16, %function +.globl abi_test_clobber_x16 +.hidden abi_test_clobber_x16 +.align 4 +abi_test_clobber_x16: + mov x16, xzr + ret +.size abi_test_clobber_x16,.-abi_test_clobber_x16 +.type abi_test_clobber_x17, %function +.globl abi_test_clobber_x17 +.hidden abi_test_clobber_x17 +.align 4 +abi_test_clobber_x17: + mov x17, xzr + ret +.size abi_test_clobber_x17,.-abi_test_clobber_x17 +.type abi_test_clobber_x19, %function +.globl abi_test_clobber_x19 +.hidden abi_test_clobber_x19 +.align 4 +abi_test_clobber_x19: + mov x19, xzr + ret +.size abi_test_clobber_x19,.-abi_test_clobber_x19 +.type abi_test_clobber_x20, %function +.globl abi_test_clobber_x20 +.hidden abi_test_clobber_x20 +.align 4 +abi_test_clobber_x20: + mov x20, xzr + ret +.size abi_test_clobber_x20,.-abi_test_clobber_x20 +.type abi_test_clobber_x21, %function +.globl abi_test_clobber_x21 +.hidden abi_test_clobber_x21 +.align 4 +abi_test_clobber_x21: + mov x21, xzr + ret +.size abi_test_clobber_x21,.-abi_test_clobber_x21 +.type abi_test_clobber_x22, %function +.globl abi_test_clobber_x22 +.hidden abi_test_clobber_x22 +.align 4 +abi_test_clobber_x22: + mov x22, xzr + ret +.size abi_test_clobber_x22,.-abi_test_clobber_x22 +.type abi_test_clobber_x23, %function +.globl abi_test_clobber_x23 +.hidden abi_test_clobber_x23 +.align 4 +abi_test_clobber_x23: + mov x23, xzr + ret +.size abi_test_clobber_x23,.-abi_test_clobber_x23 +.type abi_test_clobber_x24, %function +.globl abi_test_clobber_x24 +.hidden abi_test_clobber_x24 +.align 4 +abi_test_clobber_x24: + mov x24, xzr + ret +.size abi_test_clobber_x24,.-abi_test_clobber_x24 +.type abi_test_clobber_x25, %function +.globl abi_test_clobber_x25 +.hidden abi_test_clobber_x25 +.align 4 +abi_test_clobber_x25: + mov x25, xzr + ret +.size abi_test_clobber_x25,.-abi_test_clobber_x25 +.type abi_test_clobber_x26, %function +.globl abi_test_clobber_x26 +.hidden abi_test_clobber_x26 +.align 4 +abi_test_clobber_x26: + mov x26, xzr + ret +.size abi_test_clobber_x26,.-abi_test_clobber_x26 +.type abi_test_clobber_x27, %function +.globl abi_test_clobber_x27 +.hidden abi_test_clobber_x27 +.align 4 +abi_test_clobber_x27: + mov x27, xzr + ret +.size abi_test_clobber_x27,.-abi_test_clobber_x27 +.type abi_test_clobber_x28, %function +.globl abi_test_clobber_x28 +.hidden abi_test_clobber_x28 +.align 4 +abi_test_clobber_x28: + mov x28, xzr + ret +.size abi_test_clobber_x28,.-abi_test_clobber_x28 +.type abi_test_clobber_x29, %function +.globl abi_test_clobber_x29 +.hidden abi_test_clobber_x29 +.align 4 +abi_test_clobber_x29: + mov x29, xzr + ret +.size abi_test_clobber_x29,.-abi_test_clobber_x29 +.type abi_test_clobber_d0, %function +.globl abi_test_clobber_d0 +.hidden abi_test_clobber_d0 +.align 4 +abi_test_clobber_d0: + fmov d0, xzr + ret +.size abi_test_clobber_d0,.-abi_test_clobber_d0 +.type abi_test_clobber_d1, %function +.globl abi_test_clobber_d1 +.hidden abi_test_clobber_d1 +.align 4 +abi_test_clobber_d1: + fmov d1, xzr + ret +.size abi_test_clobber_d1,.-abi_test_clobber_d1 +.type abi_test_clobber_d2, %function +.globl abi_test_clobber_d2 +.hidden abi_test_clobber_d2 +.align 4 +abi_test_clobber_d2: + fmov d2, xzr + ret +.size abi_test_clobber_d2,.-abi_test_clobber_d2 +.type abi_test_clobber_d3, %function +.globl abi_test_clobber_d3 +.hidden abi_test_clobber_d3 +.align 4 +abi_test_clobber_d3: + fmov d3, xzr + ret +.size abi_test_clobber_d3,.-abi_test_clobber_d3 +.type abi_test_clobber_d4, %function +.globl abi_test_clobber_d4 +.hidden abi_test_clobber_d4 +.align 4 +abi_test_clobber_d4: + fmov d4, xzr + ret +.size abi_test_clobber_d4,.-abi_test_clobber_d4 +.type abi_test_clobber_d5, %function +.globl abi_test_clobber_d5 +.hidden abi_test_clobber_d5 +.align 4 +abi_test_clobber_d5: + fmov d5, xzr + ret +.size abi_test_clobber_d5,.-abi_test_clobber_d5 +.type abi_test_clobber_d6, %function +.globl abi_test_clobber_d6 +.hidden abi_test_clobber_d6 +.align 4 +abi_test_clobber_d6: + fmov d6, xzr + ret +.size abi_test_clobber_d6,.-abi_test_clobber_d6 +.type abi_test_clobber_d7, %function +.globl abi_test_clobber_d7 +.hidden abi_test_clobber_d7 +.align 4 +abi_test_clobber_d7: + fmov d7, xzr + ret +.size abi_test_clobber_d7,.-abi_test_clobber_d7 +.type abi_test_clobber_d8, %function +.globl abi_test_clobber_d8 +.hidden abi_test_clobber_d8 +.align 4 +abi_test_clobber_d8: + fmov d8, xzr + ret +.size abi_test_clobber_d8,.-abi_test_clobber_d8 +.type abi_test_clobber_d9, %function +.globl abi_test_clobber_d9 +.hidden abi_test_clobber_d9 +.align 4 +abi_test_clobber_d9: + fmov d9, xzr + ret +.size abi_test_clobber_d9,.-abi_test_clobber_d9 +.type abi_test_clobber_d10, %function +.globl abi_test_clobber_d10 +.hidden abi_test_clobber_d10 +.align 4 +abi_test_clobber_d10: + fmov d10, xzr + ret +.size abi_test_clobber_d10,.-abi_test_clobber_d10 +.type abi_test_clobber_d11, %function +.globl abi_test_clobber_d11 +.hidden abi_test_clobber_d11 +.align 4 +abi_test_clobber_d11: + fmov d11, xzr + ret +.size abi_test_clobber_d11,.-abi_test_clobber_d11 +.type abi_test_clobber_d12, %function +.globl abi_test_clobber_d12 +.hidden abi_test_clobber_d12 +.align 4 +abi_test_clobber_d12: + fmov d12, xzr + ret +.size abi_test_clobber_d12,.-abi_test_clobber_d12 +.type abi_test_clobber_d13, %function +.globl abi_test_clobber_d13 +.hidden abi_test_clobber_d13 +.align 4 +abi_test_clobber_d13: + fmov d13, xzr + ret +.size abi_test_clobber_d13,.-abi_test_clobber_d13 +.type abi_test_clobber_d14, %function +.globl abi_test_clobber_d14 +.hidden abi_test_clobber_d14 +.align 4 +abi_test_clobber_d14: + fmov d14, xzr + ret +.size abi_test_clobber_d14,.-abi_test_clobber_d14 +.type abi_test_clobber_d15, %function +.globl abi_test_clobber_d15 +.hidden abi_test_clobber_d15 +.align 4 +abi_test_clobber_d15: + fmov d15, xzr + ret +.size abi_test_clobber_d15,.-abi_test_clobber_d15 +.type abi_test_clobber_d16, %function +.globl abi_test_clobber_d16 +.hidden abi_test_clobber_d16 +.align 4 +abi_test_clobber_d16: + fmov d16, xzr + ret +.size abi_test_clobber_d16,.-abi_test_clobber_d16 +.type abi_test_clobber_d17, %function +.globl abi_test_clobber_d17 +.hidden abi_test_clobber_d17 +.align 4 +abi_test_clobber_d17: + fmov d17, xzr + ret +.size abi_test_clobber_d17,.-abi_test_clobber_d17 +.type abi_test_clobber_d18, %function +.globl abi_test_clobber_d18 +.hidden abi_test_clobber_d18 +.align 4 +abi_test_clobber_d18: + fmov d18, xzr + ret +.size abi_test_clobber_d18,.-abi_test_clobber_d18 +.type abi_test_clobber_d19, %function +.globl abi_test_clobber_d19 +.hidden abi_test_clobber_d19 +.align 4 +abi_test_clobber_d19: + fmov d19, xzr + ret +.size abi_test_clobber_d19,.-abi_test_clobber_d19 +.type abi_test_clobber_d20, %function +.globl abi_test_clobber_d20 +.hidden abi_test_clobber_d20 +.align 4 +abi_test_clobber_d20: + fmov d20, xzr + ret +.size abi_test_clobber_d20,.-abi_test_clobber_d20 +.type abi_test_clobber_d21, %function +.globl abi_test_clobber_d21 +.hidden abi_test_clobber_d21 +.align 4 +abi_test_clobber_d21: + fmov d21, xzr + ret +.size abi_test_clobber_d21,.-abi_test_clobber_d21 +.type abi_test_clobber_d22, %function +.globl abi_test_clobber_d22 +.hidden abi_test_clobber_d22 +.align 4 +abi_test_clobber_d22: + fmov d22, xzr + ret +.size abi_test_clobber_d22,.-abi_test_clobber_d22 +.type abi_test_clobber_d23, %function +.globl abi_test_clobber_d23 +.hidden abi_test_clobber_d23 +.align 4 +abi_test_clobber_d23: + fmov d23, xzr + ret +.size abi_test_clobber_d23,.-abi_test_clobber_d23 +.type abi_test_clobber_d24, %function +.globl abi_test_clobber_d24 +.hidden abi_test_clobber_d24 +.align 4 +abi_test_clobber_d24: + fmov d24, xzr + ret +.size abi_test_clobber_d24,.-abi_test_clobber_d24 +.type abi_test_clobber_d25, %function +.globl abi_test_clobber_d25 +.hidden abi_test_clobber_d25 +.align 4 +abi_test_clobber_d25: + fmov d25, xzr + ret +.size abi_test_clobber_d25,.-abi_test_clobber_d25 +.type abi_test_clobber_d26, %function +.globl abi_test_clobber_d26 +.hidden abi_test_clobber_d26 +.align 4 +abi_test_clobber_d26: + fmov d26, xzr + ret +.size abi_test_clobber_d26,.-abi_test_clobber_d26 +.type abi_test_clobber_d27, %function +.globl abi_test_clobber_d27 +.hidden abi_test_clobber_d27 +.align 4 +abi_test_clobber_d27: + fmov d27, xzr + ret +.size abi_test_clobber_d27,.-abi_test_clobber_d27 +.type abi_test_clobber_d28, %function +.globl abi_test_clobber_d28 +.hidden abi_test_clobber_d28 +.align 4 +abi_test_clobber_d28: + fmov d28, xzr + ret +.size abi_test_clobber_d28,.-abi_test_clobber_d28 +.type abi_test_clobber_d29, %function +.globl abi_test_clobber_d29 +.hidden abi_test_clobber_d29 +.align 4 +abi_test_clobber_d29: + fmov d29, xzr + ret +.size abi_test_clobber_d29,.-abi_test_clobber_d29 +.type abi_test_clobber_d30, %function +.globl abi_test_clobber_d30 +.hidden abi_test_clobber_d30 +.align 4 +abi_test_clobber_d30: + fmov d30, xzr + ret +.size abi_test_clobber_d30,.-abi_test_clobber_d30 +.type abi_test_clobber_d31, %function +.globl abi_test_clobber_d31 +.hidden abi_test_clobber_d31 +.align 4 +abi_test_clobber_d31: + fmov d31, xzr + ret +.size abi_test_clobber_d31,.-abi_test_clobber_d31 +.type abi_test_clobber_v8_upper, %function +.globl abi_test_clobber_v8_upper +.hidden abi_test_clobber_v8_upper +.align 4 +abi_test_clobber_v8_upper: + fmov v8.d[1], xzr + ret +.size abi_test_clobber_v8_upper,.-abi_test_clobber_v8_upper +.type abi_test_clobber_v9_upper, %function +.globl abi_test_clobber_v9_upper +.hidden abi_test_clobber_v9_upper +.align 4 +abi_test_clobber_v9_upper: + fmov v9.d[1], xzr + ret +.size abi_test_clobber_v9_upper,.-abi_test_clobber_v9_upper +.type abi_test_clobber_v10_upper, %function +.globl abi_test_clobber_v10_upper +.hidden abi_test_clobber_v10_upper +.align 4 +abi_test_clobber_v10_upper: + fmov v10.d[1], xzr + ret +.size abi_test_clobber_v10_upper,.-abi_test_clobber_v10_upper +.type abi_test_clobber_v11_upper, %function +.globl abi_test_clobber_v11_upper +.hidden abi_test_clobber_v11_upper +.align 4 +abi_test_clobber_v11_upper: + fmov v11.d[1], xzr + ret +.size abi_test_clobber_v11_upper,.-abi_test_clobber_v11_upper +.type abi_test_clobber_v12_upper, %function +.globl abi_test_clobber_v12_upper +.hidden abi_test_clobber_v12_upper +.align 4 +abi_test_clobber_v12_upper: + fmov v12.d[1], xzr + ret +.size abi_test_clobber_v12_upper,.-abi_test_clobber_v12_upper +.type abi_test_clobber_v13_upper, %function +.globl abi_test_clobber_v13_upper +.hidden abi_test_clobber_v13_upper +.align 4 +abi_test_clobber_v13_upper: + fmov v13.d[1], xzr + ret +.size abi_test_clobber_v13_upper,.-abi_test_clobber_v13_upper +.type abi_test_clobber_v14_upper, %function +.globl abi_test_clobber_v14_upper +.hidden abi_test_clobber_v14_upper +.align 4 +abi_test_clobber_v14_upper: + fmov v14.d[1], xzr + ret +.size abi_test_clobber_v14_upper,.-abi_test_clobber_v14_upper +.type abi_test_clobber_v15_upper, %function +.globl abi_test_clobber_v15_upper +.hidden abi_test_clobber_v15_upper +.align 4 +abi_test_clobber_v15_upper: + fmov v15.d[1], xzr + ret +.size abi_test_clobber_v15_upper,.-abi_test_clobber_v15_upper +#endif +#endif // !OPENSSL_NO_ASM
diff --git a/third_party/boringssl/linux-arm/crypto/test/trampoline-armv4.S b/third_party/boringssl/linux-arm/crypto/test/trampoline-armv4.S new file mode 100644 index 0000000..2779a231 --- /dev/null +++ b/third_party/boringssl/linux-arm/crypto/test/trampoline-armv4.S
@@ -0,0 +1,378 @@ +// This file is generated from a similarly-named Perl script in the BoringSSL +// source tree. Do not edit by hand. + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM) +#define OPENSSL_NO_ASM +#endif +#endif + +#if !defined(OPENSSL_NO_ASM) +#if defined(__arm__) +#if defined(BORINGSSL_PREFIX) +#include <boringssl_prefix_symbols_asm.h> +#endif +.syntax unified + +.arch armv7-a +.fpu vfp + +.text + +@ abi_test_trampoline loads callee-saved registers from |state|, calls |func| +@ with |argv|, then saves the callee-saved registers into |state|. It returns +@ the result of |func|. The |unwind| argument is unused. +@ uint32_t abi_test_trampoline(void (*func)(...), CallerState *state, +@ const uint32_t *argv, size_t argc, +@ int unwind); +.type abi_test_trampoline, %function +.globl abi_test_trampoline +.hidden abi_test_trampoline +.align 4 +abi_test_trampoline: +.Labi_test_trampoline_begin: + @ Save parameters and all callee-saved registers. For convenience, we + @ save r9 on iOS even though it's volatile. + vstmdb sp!, {d8,d9,d10,d11,d12,d13,d14,d15} + stmdb sp!, {r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,lr} + + @ Reserve stack space for six (10-4) stack parameters, plus an extra 4 + @ bytes to keep it 8-byte-aligned (see APCS, section 5.3). + sub sp, sp, #28 + + @ Every register in APCS is either non-volatile or a parameter (except + @ r9 on iOS), so this code, by the actual call, loses all its scratch + @ registers. First fill in stack parameters while there are registers + @ to spare. + cmp r3, #4 + bls .Lstack_args_done + mov r4, sp @ r4 is the output pointer. + add r5, r2, r3, lsl #2 @ Set r5 to the end of argv. + add r2, r2, #16 @ Skip four arguments. +.Lstack_args_loop: + ldr r6, [r2], #4 + cmp r2, r5 + str r6, [r4], #4 + bne .Lstack_args_loop + +.Lstack_args_done: + @ Load registers from |r1|. + vldmia r1!, {d8,d9,d10,d11,d12,d13,d14,d15} +#if defined(__APPLE__) + @ r9 is not volatile on iOS. + ldmia r1!, {r4,r5,r6,r7,r8,r10-r11} +#else + ldmia r1!, {r4,r5,r6,r7,r8,r9,r10,r11} +#endif + + @ Load register parameters. This uses up our remaining registers, so we + @ repurpose lr as scratch space. + ldr r3, [sp, #40] @ Reload argc. + ldr lr, [sp, #36] @ .Load argv into lr. + cmp r3, #3 + bhi .Larg_r3 + beq .Larg_r2 + cmp r3, #1 + bhi .Larg_r1 + beq .Larg_r0 + b .Largs_done + +.Larg_r3: + ldr r3, [lr, #12] @ argv[3] +.Larg_r2: + ldr r2, [lr, #8] @ argv[2] +.Larg_r1: + ldr r1, [lr, #4] @ argv[1] +.Larg_r0: + ldr r0, [lr] @ argv[0] +.Largs_done: + + @ With every other register in use, load the function pointer into lr + @ and call the function. + ldr lr, [sp, #28] + blx lr + + @ r1-r3 are free for use again. The trampoline only supports + @ single-return functions. Pass r4-r11 to the caller. + ldr r1, [sp, #32] + vstmia r1!, {d8,d9,d10,d11,d12,d13,d14,d15} +#if defined(__APPLE__) + @ r9 is not volatile on iOS. + stmia r1!, {r4,r5,r6,r7,r8,r10-r11} +#else + stmia r1!, {r4,r5,r6,r7,r8,r9,r10,r11} +#endif + + @ Unwind the stack and restore registers. + add sp, sp, #44 @ 44 = 28+16 + ldmia sp!, {r4,r5,r6,r7,r8,r9,r10,r11,lr} @ Skip r0-r3 (see +16 above). + vldmia sp!, {d8,d9,d10,d11,d12,d13,d14,d15} + + bx lr +.size abi_test_trampoline,.-abi_test_trampoline +.type abi_test_clobber_r0, %function +.globl abi_test_clobber_r0 +.hidden abi_test_clobber_r0 +.align 4 +abi_test_clobber_r0: + mov r0, #0 + bx lr +.size abi_test_clobber_r0,.-abi_test_clobber_r0 +.type abi_test_clobber_r1, %function +.globl abi_test_clobber_r1 +.hidden abi_test_clobber_r1 +.align 4 +abi_test_clobber_r1: + mov r1, #0 + bx lr +.size abi_test_clobber_r1,.-abi_test_clobber_r1 +.type abi_test_clobber_r2, %function +.globl abi_test_clobber_r2 +.hidden abi_test_clobber_r2 +.align 4 +abi_test_clobber_r2: + mov r2, #0 + bx lr +.size abi_test_clobber_r2,.-abi_test_clobber_r2 +.type abi_test_clobber_r3, %function +.globl abi_test_clobber_r3 +.hidden abi_test_clobber_r3 +.align 4 +abi_test_clobber_r3: + mov r3, #0 + bx lr +.size abi_test_clobber_r3,.-abi_test_clobber_r3 +.type abi_test_clobber_r4, %function +.globl abi_test_clobber_r4 +.hidden abi_test_clobber_r4 +.align 4 +abi_test_clobber_r4: + mov r4, #0 + bx lr +.size abi_test_clobber_r4,.-abi_test_clobber_r4 +.type abi_test_clobber_r5, %function +.globl abi_test_clobber_r5 +.hidden abi_test_clobber_r5 +.align 4 +abi_test_clobber_r5: + mov r5, #0 + bx lr +.size abi_test_clobber_r5,.-abi_test_clobber_r5 +.type abi_test_clobber_r6, %function +.globl abi_test_clobber_r6 +.hidden abi_test_clobber_r6 +.align 4 +abi_test_clobber_r6: + mov r6, #0 + bx lr +.size abi_test_clobber_r6,.-abi_test_clobber_r6 +.type abi_test_clobber_r7, %function +.globl abi_test_clobber_r7 +.hidden abi_test_clobber_r7 +.align 4 +abi_test_clobber_r7: + mov r7, #0 + bx lr +.size abi_test_clobber_r7,.-abi_test_clobber_r7 +.type abi_test_clobber_r8, %function +.globl abi_test_clobber_r8 +.hidden abi_test_clobber_r8 +.align 4 +abi_test_clobber_r8: + mov r8, #0 + bx lr +.size abi_test_clobber_r8,.-abi_test_clobber_r8 +.type abi_test_clobber_r9, %function +.globl abi_test_clobber_r9 +.hidden abi_test_clobber_r9 +.align 4 +abi_test_clobber_r9: + mov r9, #0 + bx lr +.size abi_test_clobber_r9,.-abi_test_clobber_r9 +.type abi_test_clobber_r10, %function +.globl abi_test_clobber_r10 +.hidden abi_test_clobber_r10 +.align 4 +abi_test_clobber_r10: + mov r10, #0 + bx lr +.size abi_test_clobber_r10,.-abi_test_clobber_r10 +.type abi_test_clobber_r11, %function +.globl abi_test_clobber_r11 +.hidden abi_test_clobber_r11 +.align 4 +abi_test_clobber_r11: + mov r11, #0 + bx lr +.size abi_test_clobber_r11,.-abi_test_clobber_r11 +.type abi_test_clobber_r12, %function +.globl abi_test_clobber_r12 +.hidden abi_test_clobber_r12 +.align 4 +abi_test_clobber_r12: + mov r12, #0 + bx lr +.size abi_test_clobber_r12,.-abi_test_clobber_r12 +.type abi_test_clobber_d0, %function +.globl abi_test_clobber_d0 +.hidden abi_test_clobber_d0 +.align 4 +abi_test_clobber_d0: + mov r0, #0 + vmov s0, r0 + vmov s1, r0 + bx lr +.size abi_test_clobber_d0,.-abi_test_clobber_d0 +.type abi_test_clobber_d1, %function +.globl abi_test_clobber_d1 +.hidden abi_test_clobber_d1 +.align 4 +abi_test_clobber_d1: + mov r0, #0 + vmov s2, r0 + vmov s3, r0 + bx lr +.size abi_test_clobber_d1,.-abi_test_clobber_d1 +.type abi_test_clobber_d2, %function +.globl abi_test_clobber_d2 +.hidden abi_test_clobber_d2 +.align 4 +abi_test_clobber_d2: + mov r0, #0 + vmov s4, r0 + vmov s5, r0 + bx lr +.size abi_test_clobber_d2,.-abi_test_clobber_d2 +.type abi_test_clobber_d3, %function +.globl abi_test_clobber_d3 +.hidden abi_test_clobber_d3 +.align 4 +abi_test_clobber_d3: + mov r0, #0 + vmov s6, r0 + vmov s7, r0 + bx lr +.size abi_test_clobber_d3,.-abi_test_clobber_d3 +.type abi_test_clobber_d4, %function +.globl abi_test_clobber_d4 +.hidden abi_test_clobber_d4 +.align 4 +abi_test_clobber_d4: + mov r0, #0 + vmov s8, r0 + vmov s9, r0 + bx lr +.size abi_test_clobber_d4,.-abi_test_clobber_d4 +.type abi_test_clobber_d5, %function +.globl abi_test_clobber_d5 +.hidden abi_test_clobber_d5 +.align 4 +abi_test_clobber_d5: + mov r0, #0 + vmov s10, r0 + vmov s11, r0 + bx lr +.size abi_test_clobber_d5,.-abi_test_clobber_d5 +.type abi_test_clobber_d6, %function +.globl abi_test_clobber_d6 +.hidden abi_test_clobber_d6 +.align 4 +abi_test_clobber_d6: + mov r0, #0 + vmov s12, r0 + vmov s13, r0 + bx lr +.size abi_test_clobber_d6,.-abi_test_clobber_d6 +.type abi_test_clobber_d7, %function +.globl abi_test_clobber_d7 +.hidden abi_test_clobber_d7 +.align 4 +abi_test_clobber_d7: + mov r0, #0 + vmov s14, r0 + vmov s15, r0 + bx lr +.size abi_test_clobber_d7,.-abi_test_clobber_d7 +.type abi_test_clobber_d8, %function +.globl abi_test_clobber_d8 +.hidden abi_test_clobber_d8 +.align 4 +abi_test_clobber_d8: + mov r0, #0 + vmov s16, r0 + vmov s17, r0 + bx lr +.size abi_test_clobber_d8,.-abi_test_clobber_d8 +.type abi_test_clobber_d9, %function +.globl abi_test_clobber_d9 +.hidden abi_test_clobber_d9 +.align 4 +abi_test_clobber_d9: + mov r0, #0 + vmov s18, r0 + vmov s19, r0 + bx lr +.size abi_test_clobber_d9,.-abi_test_clobber_d9 +.type abi_test_clobber_d10, %function +.globl abi_test_clobber_d10 +.hidden abi_test_clobber_d10 +.align 4 +abi_test_clobber_d10: + mov r0, #0 + vmov s20, r0 + vmov s21, r0 + bx lr +.size abi_test_clobber_d10,.-abi_test_clobber_d10 +.type abi_test_clobber_d11, %function +.globl abi_test_clobber_d11 +.hidden abi_test_clobber_d11 +.align 4 +abi_test_clobber_d11: + mov r0, #0 + vmov s22, r0 + vmov s23, r0 + bx lr +.size abi_test_clobber_d11,.-abi_test_clobber_d11 +.type abi_test_clobber_d12, %function +.globl abi_test_clobber_d12 +.hidden abi_test_clobber_d12 +.align 4 +abi_test_clobber_d12: + mov r0, #0 + vmov s24, r0 + vmov s25, r0 + bx lr +.size abi_test_clobber_d12,.-abi_test_clobber_d12 +.type abi_test_clobber_d13, %function +.globl abi_test_clobber_d13 +.hidden abi_test_clobber_d13 +.align 4 +abi_test_clobber_d13: + mov r0, #0 + vmov s26, r0 + vmov s27, r0 + bx lr +.size abi_test_clobber_d13,.-abi_test_clobber_d13 +.type abi_test_clobber_d14, %function +.globl abi_test_clobber_d14 +.hidden abi_test_clobber_d14 +.align 4 +abi_test_clobber_d14: + mov r0, #0 + vmov s28, r0 + vmov s29, r0 + bx lr +.size abi_test_clobber_d14,.-abi_test_clobber_d14 +.type abi_test_clobber_d15, %function +.globl abi_test_clobber_d15 +.hidden abi_test_clobber_d15 +.align 4 +abi_test_clobber_d15: + mov r0, #0 + vmov s30, r0 + vmov s31, r0 + bx lr +.size abi_test_clobber_d15,.-abi_test_clobber_d15 +#endif +#endif // !OPENSSL_NO_ASM
diff --git a/third_party/boringssl/linux-x86_64/crypto/test/trampoline-x86_64.S b/third_party/boringssl/linux-x86_64/crypto/test/trampoline-x86_64.S index 666ac40..91a13f3 100644 --- a/third_party/boringssl/linux-x86_64/crypto/test/trampoline-x86_64.S +++ b/third_party/boringssl/linux-x86_64/crypto/test/trampoline-x86_64.S
@@ -25,7 +25,7 @@ .hidden abi_test_trampoline .align 16 abi_test_trampoline: -.Labi_test_trampoline_begin: +.Labi_test_trampoline_seh_begin: .cfi_startproc @@ -38,27 +38,27 @@ subq $120,%rsp .cfi_adjust_cfa_offset 120 -.Labi_test_trampoline_prolog_alloc: +.Labi_test_trampoline_seh_prolog_alloc: movq %r8,48(%rsp) movq %rbx,64(%rsp) .cfi_offset rbx, -64 -.Labi_test_trampoline_prolog_rbx: +.Labi_test_trampoline_seh_prolog_rbx: movq %rbp,72(%rsp) .cfi_offset rbp, -56 -.Labi_test_trampoline_prolog_rbp: +.Labi_test_trampoline_seh_prolog_rbp: movq %r12,80(%rsp) .cfi_offset r12, -48 -.Labi_test_trampoline_prolog_r12: +.Labi_test_trampoline_seh_prolog_r12: movq %r13,88(%rsp) .cfi_offset r13, -40 -.Labi_test_trampoline_prolog_r13: +.Labi_test_trampoline_seh_prolog_r13: movq %r14,96(%rsp) .cfi_offset r14, -32 -.Labi_test_trampoline_prolog_r14: +.Labi_test_trampoline_seh_prolog_r14: movq %r15,104(%rsp) .cfi_offset r15, -24 -.Labi_test_trampoline_prolog_r15: -.Labi_test_trampoline_prolog_end: +.Labi_test_trampoline_seh_prolog_r15: +.Labi_test_trampoline_seh_prolog_end: movq 0(%rsi),%rbx movq 8(%rsi),%rbp movq 16(%rsi),%r12 @@ -182,7 +182,7 @@ .byte 0xf3,0xc3 .cfi_endproc -.Labi_test_trampoline_end: +.Labi_test_trampoline_seh_end: .size abi_test_trampoline,.-abi_test_trampoline .type abi_test_clobber_rax, @function .globl abi_test_clobber_rax @@ -441,13 +441,20 @@ .align 16 abi_test_bad_unwind_wrong_register: .cfi_startproc +.Labi_test_bad_unwind_wrong_register_seh_begin: pushq %r12 .cfi_adjust_cfa_offset 8 .cfi_offset %r13,-16 +.Labi_test_bad_unwind_wrong_register_seh_push_r13: + + + + nop popq %r12 .cfi_adjust_cfa_offset -8 .cfi_restore %r12 .byte 0xf3,0xc3 +.Labi_test_bad_unwind_wrong_register_seh_end: .cfi_endproc .size abi_test_bad_unwind_wrong_register,.-abi_test_bad_unwind_wrong_register @@ -460,15 +467,18 @@ .align 16 abi_test_bad_unwind_temporary: .cfi_startproc +.Labi_test_bad_unwind_temporary_seh_begin: pushq %r12 .cfi_adjust_cfa_offset 8 .cfi_offset %r12,-16 +.Labi_test_bad_unwind_temporary_seh_push_r12: - incq %r12 - movq %r12,(%rsp) + movq %r12,%rax + incq %rax + movq %rax,(%rsp) - decq %r12 + movq %r12,(%rsp) @@ -476,6 +486,7 @@ .cfi_adjust_cfa_offset -8 .cfi_restore %r12 .byte 0xf3,0xc3 +.Labi_test_bad_unwind_temporary_seh_end: .cfi_endproc .size abi_test_bad_unwind_temporary,.-abi_test_bad_unwind_temporary
diff --git a/third_party/boringssl/mac-x86_64/crypto/test/trampoline-x86_64.S b/third_party/boringssl/mac-x86_64/crypto/test/trampoline-x86_64.S index 707460f..863e6b04 100644 --- a/third_party/boringssl/mac-x86_64/crypto/test/trampoline-x86_64.S +++ b/third_party/boringssl/mac-x86_64/crypto/test/trampoline-x86_64.S
@@ -25,7 +25,7 @@ .private_extern _abi_test_trampoline .p2align 4 _abi_test_trampoline: -L$abi_test_trampoline_begin: +L$abi_test_trampoline_seh_begin: @@ -38,27 +38,27 @@ subq $120,%rsp -L$abi_test_trampoline_prolog_alloc: +L$abi_test_trampoline_seh_prolog_alloc: movq %r8,48(%rsp) movq %rbx,64(%rsp) -L$abi_test_trampoline_prolog_rbx: +L$abi_test_trampoline_seh_prolog_rbx: movq %rbp,72(%rsp) -L$abi_test_trampoline_prolog_rbp: +L$abi_test_trampoline_seh_prolog_rbp: movq %r12,80(%rsp) -L$abi_test_trampoline_prolog_r12: +L$abi_test_trampoline_seh_prolog_r12: movq %r13,88(%rsp) -L$abi_test_trampoline_prolog_r13: +L$abi_test_trampoline_seh_prolog_r13: movq %r14,96(%rsp) -L$abi_test_trampoline_prolog_r14: +L$abi_test_trampoline_seh_prolog_r14: movq %r15,104(%rsp) -L$abi_test_trampoline_prolog_r15: -L$abi_test_trampoline_prolog_end: +L$abi_test_trampoline_seh_prolog_r15: +L$abi_test_trampoline_seh_prolog_end: movq 0(%rsi),%rbx movq 8(%rsi),%rbp movq 16(%rsi),%r12 @@ -182,7 +182,7 @@ .byte 0xf3,0xc3 -L$abi_test_trampoline_end: +L$abi_test_trampoline_seh_end: .globl _abi_test_clobber_rax @@ -441,11 +441,18 @@ .p2align 4 _abi_test_bad_unwind_wrong_register: +L$abi_test_bad_unwind_wrong_register_seh_begin: pushq %r12 +L$abi_test_bad_unwind_wrong_register_seh_push_r13: + + + + nop popq %r12 .byte 0xf3,0xc3 +L$abi_test_bad_unwind_wrong_register_seh_end: @@ -458,20 +465,24 @@ .p2align 4 _abi_test_bad_unwind_temporary: +L$abi_test_bad_unwind_temporary_seh_begin: pushq %r12 +L$abi_test_bad_unwind_temporary_seh_push_r12: - incq %r12 - movq %r12,(%rsp) + movq %r12,%rax + incq %rax + movq %rax,(%rsp) - decq %r12 + movq %r12,(%rsp) popq %r12 .byte 0xf3,0xc3 +L$abi_test_bad_unwind_temporary_seh_end:
diff --git a/third_party/boringssl/win-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.asm b/third_party/boringssl/win-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.asm index d54df7b..434ba10e 100644 --- a/third_party/boringssl/win-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.asm +++ b/third_party/boringssl/win-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.asm
@@ -461,16 +461,16 @@ DB 5 DB 0 -DB $L$gmult_seh_allocstack-$L$gmult_seh_begin -DB 66 +DB $L$gmult_seh_save_xmm10-$L$gmult_seh_begin +DB 168 + DW 1 DB $L$gmult_seh_save_xmm6-$L$gmult_seh_begin DB 104 DW 0 -DB $L$gmult_seh_save_xmm10-$L$gmult_seh_begin -DB 168 - DW 1 +DB $L$gmult_seh_allocstack-$L$gmult_seh_begin +DB 66 ALIGN 8 $L$ghash_seh_info: @@ -479,17 +479,17 @@ DB 7 DB 0 -DB $L$ghash_seh_allocstack-$L$ghash_seh_begin -DB 98 - -DB $L$ghash_seh_save_xmm6-$L$ghash_seh_begin -DB 104 - DW 0 +DB $L$ghash_seh_save_xmm11-$L$ghash_seh_begin +DB 184 + DW 2 DB $L$ghash_seh_save_xmm10-$L$ghash_seh_begin DB 168 DW 1 -DB $L$ghash_seh_save_xmm11-$L$ghash_seh_begin -DB 184 - DW 2 +DB $L$ghash_seh_save_xmm6-$L$ghash_seh_begin +DB 104 + DW 0 + +DB $L$ghash_seh_allocstack-$L$ghash_seh_begin +DB 98
diff --git a/third_party/boringssl/win-x86_64/crypto/test/trampoline-x86_64.asm b/third_party/boringssl/win-x86_64/crypto/test/trampoline-x86_64.asm index 25b1af13..9900669 100644 --- a/third_party/boringssl/win-x86_64/crypto/test/trampoline-x86_64.asm +++ b/third_party/boringssl/win-x86_64/crypto/test/trampoline-x86_64.asm
@@ -23,7 +23,7 @@ global abi_test_trampoline ALIGN 16 abi_test_trampoline: -$L$abi_test_trampoline_begin: +$L$abi_test_trampoline_seh_begin: @@ -36,62 +36,62 @@ sub rsp,344 -$L$abi_test_trampoline_prolog_alloc: +$L$abi_test_trampoline_seh_prolog_alloc: mov QWORD[112+rsp],rbx -$L$abi_test_trampoline_prolog_rbx: +$L$abi_test_trampoline_seh_prolog_rbx: mov QWORD[120+rsp],rbp -$L$abi_test_trampoline_prolog_rbp: +$L$abi_test_trampoline_seh_prolog_rbp: mov QWORD[128+rsp],rdi -$L$abi_test_trampoline_prolog_rdi: +$L$abi_test_trampoline_seh_prolog_rdi: mov QWORD[136+rsp],rsi -$L$abi_test_trampoline_prolog_rsi: +$L$abi_test_trampoline_seh_prolog_rsi: mov QWORD[144+rsp],r12 -$L$abi_test_trampoline_prolog_r12: +$L$abi_test_trampoline_seh_prolog_r12: mov QWORD[152+rsp],r13 -$L$abi_test_trampoline_prolog_r13: +$L$abi_test_trampoline_seh_prolog_r13: mov QWORD[160+rsp],r14 -$L$abi_test_trampoline_prolog_r14: +$L$abi_test_trampoline_seh_prolog_r14: mov QWORD[168+rsp],r15 -$L$abi_test_trampoline_prolog_r15: +$L$abi_test_trampoline_seh_prolog_r15: movdqa XMMWORD[176+rsp],xmm6 -$L$abi_test_trampoline_prolog_xmm6: +$L$abi_test_trampoline_seh_prolog_xmm6: movdqa XMMWORD[192+rsp],xmm7 -$L$abi_test_trampoline_prolog_xmm7: +$L$abi_test_trampoline_seh_prolog_xmm7: movdqa XMMWORD[208+rsp],xmm8 -$L$abi_test_trampoline_prolog_xmm8: +$L$abi_test_trampoline_seh_prolog_xmm8: movdqa XMMWORD[224+rsp],xmm9 -$L$abi_test_trampoline_prolog_xmm9: +$L$abi_test_trampoline_seh_prolog_xmm9: movdqa XMMWORD[240+rsp],xmm10 -$L$abi_test_trampoline_prolog_xmm10: +$L$abi_test_trampoline_seh_prolog_xmm10: movdqa XMMWORD[256+rsp],xmm11 -$L$abi_test_trampoline_prolog_xmm11: +$L$abi_test_trampoline_seh_prolog_xmm11: movdqa XMMWORD[272+rsp],xmm12 -$L$abi_test_trampoline_prolog_xmm12: +$L$abi_test_trampoline_seh_prolog_xmm12: movdqa XMMWORD[288+rsp],xmm13 -$L$abi_test_trampoline_prolog_xmm13: +$L$abi_test_trampoline_seh_prolog_xmm13: movdqa XMMWORD[304+rsp],xmm14 -$L$abi_test_trampoline_prolog_xmm14: +$L$abi_test_trampoline_seh_prolog_xmm14: movdqa XMMWORD[320+rsp],xmm15 -$L$abi_test_trampoline_prolog_xmm15: -$L$abi_test_trampoline_prolog_end: +$L$abi_test_trampoline_seh_prolog_xmm15: +$L$abi_test_trampoline_seh_prolog_end: mov rbx,QWORD[rdx] mov rbp,QWORD[8+rdx] mov rdi,QWORD[16+rdx] @@ -252,7 +252,7 @@ DB 0F3h,0C3h ;repret -$L$abi_test_trampoline_end: +$L$abi_test_trampoline_seh_end: global abi_test_clobber_rax @@ -479,11 +479,18 @@ ALIGN 16 abi_test_bad_unwind_wrong_register: +$L$abi_test_bad_unwind_wrong_register_seh_begin: push r12 +$L$abi_test_bad_unwind_wrong_register_seh_push_r13: + + + + nop pop r12 DB 0F3h,0C3h ;repret +$L$abi_test_bad_unwind_wrong_register_seh_end: @@ -495,20 +502,24 @@ ALIGN 16 abi_test_bad_unwind_temporary: +$L$abi_test_bad_unwind_temporary_seh_begin: push r12 +$L$abi_test_bad_unwind_temporary_seh_push_r12: - inc r12 - mov QWORD[rsp],r12 + mov rax,r12 + inc rax + mov QWORD[rsp],rax - dec r12 + mov QWORD[rsp],r12 pop r12 DB 0F3h,0C3h ;repret +$L$abi_test_bad_unwind_temporary_seh_end: @@ -534,76 +545,138 @@ std DB 0F3h,0C3h ;repret + + + + + +global abi_test_bad_unwind_epilog +ALIGN 16 +abi_test_bad_unwind_epilog: +$L$abi_test_bad_unwind_epilog_seh_begin: + push r12 +$L$abi_test_bad_unwind_epilog_seh_push_r12: + + nop + + + pop r12 + nop + DB 0F3h,0C3h ;repret +$L$abi_test_bad_unwind_epilog_seh_end: + section .pdata rdata align=4 ALIGN 4 - DD $L$abi_test_trampoline_begin wrt ..imagebase - DD $L$abi_test_trampoline_end wrt ..imagebase - DD $L$abi_test_trampoline_info wrt ..imagebase + DD $L$abi_test_trampoline_seh_begin wrt ..imagebase + DD $L$abi_test_trampoline_seh_end wrt ..imagebase + DD $L$abi_test_trampoline_seh_info wrt ..imagebase + + DD $L$abi_test_bad_unwind_wrong_register_seh_begin wrt ..imagebase + DD $L$abi_test_bad_unwind_wrong_register_seh_end wrt ..imagebase + DD $L$abi_test_bad_unwind_wrong_register_seh_info wrt ..imagebase + + DD $L$abi_test_bad_unwind_temporary_seh_begin wrt ..imagebase + DD $L$abi_test_bad_unwind_temporary_seh_end wrt ..imagebase + DD $L$abi_test_bad_unwind_temporary_seh_info wrt ..imagebase + + DD $L$abi_test_bad_unwind_epilog_seh_begin wrt ..imagebase + DD $L$abi_test_bad_unwind_epilog_seh_end wrt ..imagebase + DD $L$abi_test_bad_unwind_epilog_seh_info wrt ..imagebase section .xdata rdata align=8 ALIGN 8 -$L$abi_test_trampoline_info: +$L$abi_test_trampoline_seh_info: DB 1 -DB $L$abi_test_trampoline_prolog_end-$L$abi_test_trampoline_begin +DB $L$abi_test_trampoline_seh_prolog_end-$L$abi_test_trampoline_seh_begin DB 38 DB 0 -DB $L$abi_test_trampoline_prolog_alloc-$L$abi_test_trampoline_begin -DB 1 - DW 43 -DB $L$abi_test_trampoline_prolog_rbx-$L$abi_test_trampoline_begin -DB 52 - DW 14 -DB $L$abi_test_trampoline_prolog_rbp-$L$abi_test_trampoline_begin -DB 84 - DW 15 -DB $L$abi_test_trampoline_prolog_rdi-$L$abi_test_trampoline_begin -DB 116 - DW 16 -DB $L$abi_test_trampoline_prolog_rsi-$L$abi_test_trampoline_begin -DB 100 - DW 17 -DB $L$abi_test_trampoline_prolog_r12-$L$abi_test_trampoline_begin -DB 196 - DW 18 -DB $L$abi_test_trampoline_prolog_r13-$L$abi_test_trampoline_begin -DB 212 - DW 19 -DB $L$abi_test_trampoline_prolog_r14-$L$abi_test_trampoline_begin -DB 228 - DW 20 -DB $L$abi_test_trampoline_prolog_r15-$L$abi_test_trampoline_begin -DB 244 - DW 21 -DB $L$abi_test_trampoline_prolog_xmm6-$L$abi_test_trampoline_begin -DB 104 - DW 11 -DB $L$abi_test_trampoline_prolog_xmm7-$L$abi_test_trampoline_begin -DB 120 - DW 12 -DB $L$abi_test_trampoline_prolog_xmm8-$L$abi_test_trampoline_begin -DB 136 - DW 13 -DB $L$abi_test_trampoline_prolog_xmm9-$L$abi_test_trampoline_begin -DB 152 - DW 14 -DB $L$abi_test_trampoline_prolog_xmm10-$L$abi_test_trampoline_begin -DB 168 - DW 15 -DB $L$abi_test_trampoline_prolog_xmm11-$L$abi_test_trampoline_begin -DB 184 - DW 16 -DB $L$abi_test_trampoline_prolog_xmm12-$L$abi_test_trampoline_begin -DB 200 - DW 17 -DB $L$abi_test_trampoline_prolog_xmm13-$L$abi_test_trampoline_begin -DB 216 - DW 18 -DB $L$abi_test_trampoline_prolog_xmm14-$L$abi_test_trampoline_begin -DB 232 - DW 19 -DB $L$abi_test_trampoline_prolog_xmm15-$L$abi_test_trampoline_begin +DB $L$abi_test_trampoline_seh_prolog_xmm15-$L$abi_test_trampoline_seh_begin DB 248 DW 20 +DB $L$abi_test_trampoline_seh_prolog_xmm14-$L$abi_test_trampoline_seh_begin +DB 232 + DW 19 +DB $L$abi_test_trampoline_seh_prolog_xmm13-$L$abi_test_trampoline_seh_begin +DB 216 + DW 18 +DB $L$abi_test_trampoline_seh_prolog_xmm12-$L$abi_test_trampoline_seh_begin +DB 200 + DW 17 +DB $L$abi_test_trampoline_seh_prolog_xmm11-$L$abi_test_trampoline_seh_begin +DB 184 + DW 16 +DB $L$abi_test_trampoline_seh_prolog_xmm10-$L$abi_test_trampoline_seh_begin +DB 168 + DW 15 +DB $L$abi_test_trampoline_seh_prolog_xmm9-$L$abi_test_trampoline_seh_begin +DB 152 + DW 14 +DB $L$abi_test_trampoline_seh_prolog_xmm8-$L$abi_test_trampoline_seh_begin +DB 136 + DW 13 +DB $L$abi_test_trampoline_seh_prolog_xmm7-$L$abi_test_trampoline_seh_begin +DB 120 + DW 12 +DB $L$abi_test_trampoline_seh_prolog_xmm6-$L$abi_test_trampoline_seh_begin +DB 104 + DW 11 +DB $L$abi_test_trampoline_seh_prolog_r15-$L$abi_test_trampoline_seh_begin +DB 244 + DW 21 +DB $L$abi_test_trampoline_seh_prolog_r14-$L$abi_test_trampoline_seh_begin +DB 228 + DW 20 +DB $L$abi_test_trampoline_seh_prolog_r13-$L$abi_test_trampoline_seh_begin +DB 212 + DW 19 +DB $L$abi_test_trampoline_seh_prolog_r12-$L$abi_test_trampoline_seh_begin +DB 196 + DW 18 +DB $L$abi_test_trampoline_seh_prolog_rsi-$L$abi_test_trampoline_seh_begin +DB 100 + DW 17 +DB $L$abi_test_trampoline_seh_prolog_rdi-$L$abi_test_trampoline_seh_begin +DB 116 + DW 16 +DB $L$abi_test_trampoline_seh_prolog_rbp-$L$abi_test_trampoline_seh_begin +DB 84 + DW 15 +DB $L$abi_test_trampoline_seh_prolog_rbx-$L$abi_test_trampoline_seh_begin +DB 52 + DW 14 +DB $L$abi_test_trampoline_seh_prolog_alloc-$L$abi_test_trampoline_seh_begin +DB 1 + DW 43 + +ALIGN 8 +$L$abi_test_bad_unwind_wrong_register_seh_info: +DB 1 +DB $L$abi_test_bad_unwind_wrong_register_seh_push_r13-$L$abi_test_bad_unwind_wrong_register_seh_begin +DB 1 +DB 0 + +DB $L$abi_test_bad_unwind_wrong_register_seh_push_r13-$L$abi_test_bad_unwind_wrong_register_seh_begin +DB 208 + +ALIGN 8 +$L$abi_test_bad_unwind_temporary_seh_info: +DB 1 +DB $L$abi_test_bad_unwind_temporary_seh_push_r12-$L$abi_test_bad_unwind_temporary_seh_begin +DB 1 +DB 0 + +DB $L$abi_test_bad_unwind_temporary_seh_push_r12-$L$abi_test_bad_unwind_temporary_seh_begin +DB 192 + +ALIGN 8 +$L$abi_test_bad_unwind_epilog_seh_info: +DB 1 +DB $L$abi_test_bad_unwind_epilog_seh_push_r12-$L$abi_test_bad_unwind_epilog_seh_begin +DB 1 +DB 0 + +DB $L$abi_test_bad_unwind_epilog_seh_push_r12-$L$abi_test_bad_unwind_epilog_seh_begin +DB 192
diff --git a/third_party/freetype/README.chromium b/third_party/freetype/README.chromium index 5dd1cc12..eb10801 100644 --- a/third_party/freetype/README.chromium +++ b/third_party/freetype/README.chromium
@@ -1,7 +1,7 @@ Name: FreeType URL: http://www.freetype.org/ -Version: VER-2-9-1-329 -Revision: 1e7a8f30c231bace001c617099e78f78743dd3b4 +Version: VER-2-9-1-333 +Revision: a6feefdfefd6eb8e62728f40638241bb1d8c993e License: Custom license "inspired by the BSD, Artistic, and IJG (Independent JPEG Group) licenses" License File: src/docs/FTL.TXT
diff --git a/third_party/freetype/include/freetype-custom-config/ftconfig.h b/third_party/freetype/include/freetype-custom-config/ftconfig.h index 1b24a24..b3337fa 100644 --- a/third_party/freetype/include/freetype-custom-config/ftconfig.h +++ b/third_party/freetype/include/freetype-custom-config/ftconfig.h
@@ -4,7 +4,7 @@ * * ANSI-specific configuration file (specification only). * - * Copyright 1996-2018 by + * Copyright 1996-2019 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used,
diff --git a/third_party/freetype/include/freetype-custom-config/ftoption.h b/third_party/freetype/include/freetype-custom-config/ftoption.h index c2edaea..e7bc45a9 100644 --- a/third_party/freetype/include/freetype-custom-config/ftoption.h +++ b/third_party/freetype/include/freetype-custom-config/ftoption.h
@@ -4,7 +4,7 @@ * * User-selectable configuration macros (specification only). * - * Copyright 1996-2018 by + * Copyright 1996-2019 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used,
diff --git a/third_party/metrics_proto/README.chromium b/third_party/metrics_proto/README.chromium index 5c7c566..02d8908 100644 --- a/third_party/metrics_proto/README.chromium +++ b/third_party/metrics_proto/README.chromium
@@ -1,8 +1,8 @@ Name: Metrics Protos Short Name: metrics_proto URL: This is the canonical public repository -Version: 229533285 -Date: 2019/01/16 UTC +Version: 232558611 +Date: 2019/02/05 UTC License: BSD Security Critical: Yes
diff --git a/third_party/metrics_proto/cast_logs.proto b/third_party/metrics_proto/cast_logs.proto index 2a9e37c..9d43c077 100644 --- a/third_party/metrics_proto/cast_logs.proto +++ b/third_party/metrics_proto/cast_logs.proto
@@ -240,7 +240,7 @@ // Next tag: 9 message CastDeviceMutableInfo { // This is the last type of reboot the device encountered - // Next tag: 11 + // Next tag: 12 enum RebootType { REBOOT_TYPE_UNKNOWN = 0; // Fail to get reboot type from system property REBOOT_TYPE_FORCED = 1; // Power removed from device @@ -253,6 +253,7 @@ REBOOT_TYPE_FDR = 8; REBOOT_TYPE_HW_WATCHDOG = 9; REBOOT_TYPE_SW_OTHER = 10; + REBOOT_TYPE_OVERHEAT = 11; } optional RebootType last_reboot_type = 1;
diff --git a/tools/clang/scripts/update.py b/tools/clang/scripts/update.py index 2734950..3da852d 100755 --- a/tools/clang/scripts/update.py +++ b/tools/clang/scripts/update.py
@@ -27,7 +27,7 @@ # Do NOT CHANGE this if you don't know what you're doing -- see # https://chromium.googlesource.com/chromium/src/+/master/docs/updating_clang.md # Reverting problematic clang rolls is safe, though. -CLANG_REVISION = '353069' +CLANG_REVISION = '353250' use_head_revision = bool(os.environ.get('LLVM_FORCE_HEAD_REVISION', '0') in ('1', 'YES')) @@ -35,7 +35,7 @@ CLANG_REVISION = 'HEAD' # This is incremented when pushing a new build of Clang at the same revision. -CLANG_SUB_REVISION=2 +CLANG_SUB_REVISION=1 PACKAGE_VERSION = "%s-%s" % (CLANG_REVISION, CLANG_SUB_REVISION)
diff --git a/tools/imagediff/BUILD.gn b/tools/imagediff/BUILD.gn index cdc204ef..6676d03f 100644 --- a/tools/imagediff/BUILD.gn +++ b/tools/imagediff/BUILD.gn
@@ -6,7 +6,7 @@ if (current_toolchain == host_toolchain) { executable("imagediff") { - output_name = "image_diff" # Different than dir nam for historical reasons. + output_name = "image_diff" # Different than dir name for historical reasons. sources = [ "image_diff.cc", "image_diff_png.cc", @@ -23,9 +23,13 @@ ] } } else { - # Aliases for compatibility with GYP. binary_symlink("imagediff") { binary_label = ":$target_name($host_toolchain)" binary_output_name = "image_diff" + + # The 'executable' target does this automatically. + if (is_win) { + binary_output_name += ".exe" + } } }
diff --git a/tools/json_schema_compiler/idl_schema.py b/tools/json_schema_compiler/idl_schema.py index f68ba0a8..f9f73442 100755 --- a/tools/json_schema_compiler/idl_schema.py +++ b/tools/json_schema_compiler/idl_schema.py
@@ -516,6 +516,8 @@ compiler_options['implemented_in'] = node.value elif node.name == 'camel_case_enum_to_string': compiler_options['camel_case_enum_to_string'] = node.value + elif node.name == 'generate_error_messages': + compiler_options['generate_error_messages'] = True elif node.name == 'deprecated': deprecated = str(node.value) elif node.name == 'documentation_title':
diff --git a/tools/json_schema_compiler/idl_schema_test.py b/tools/json_schema_compiler/idl_schema_test.py index dd05571..8d4e8b9 100755 --- a/tools/json_schema_compiler/idl_schema_test.py +++ b/tools/json_schema_compiler/idl_schema_test.py
@@ -199,6 +199,17 @@ expected = None self.assertEquals(expected, schema['platforms']) + def testGenerateErrorMessages(self): + schema = idl_schema.Load('test/idl_generate_error_messages.idl')[0] + self.assertEquals('idl_generate_error_messages', schema['namespace']) + self.assertTrue(schema['compiler_options'].get('generate_error_messages', + False)) + + schema = idl_schema.Load('test/idl_basics.idl')[0] + self.assertEquals('idl_basics', schema['namespace']) + self.assertFalse(schema['compiler_options'].get('generate_error_messages', + False)) + def testSpecificImplementNamespace(self): schema = idl_schema.Load('test/idl_namespace_specific_implement.idl')[0] self.assertEquals('idl_namespace_specific_implement',
diff --git a/tools/json_schema_compiler/test/idl_generate_error_messages.idl b/tools/json_schema_compiler/test/idl_generate_error_messages.idl new file mode 100644 index 0000000..2af6f89 --- /dev/null +++ b/tools/json_schema_compiler/test/idl_generate_error_messages.idl
@@ -0,0 +1,10 @@ +// 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. + +// Tests the case of a namespace with error generation enabled. + +[generate_error_messages] +namespace idl_generate_error_messages { + +};
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index 225788fe..ab9660a8 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -131,6 +131,7 @@ 'ToTAndroidOfficial': 'android_clang_tot_release_minimal_symbols_official_optimize', 'ToTAndroid64': 'android_clang_tot_release_arm64', 'ToTAndroid x64': 'android_clang_tot_x64', + 'ToTLinuxOfficial': 'clang_tot_linux_official', 'ToTLinux': 'clang_tot_linux_full_symbols_shared_release', 'ToTLinuxCoverage': 'clang_tot_coverage_minimal_symbols_shared_release_with_libfuzzer', 'ToTLinux (dbg)': 'clang_tot_shared_debug', @@ -213,7 +214,6 @@ 'Linux x64 Goma Latest Client LocalOutputCache': 'release_bot', 'mac-hermetic-upgrade-rel': 'release_bot', - 'mac-views-rel': 'mac_views_browser_release_bot', 'Chromium Mac 10.13': 'release_bot', 'Mac Builder (dbg) Goma Canary (clobber)': 'debug_bot', @@ -748,7 +748,6 @@ 'mac_optional_gpu_tests_rel': 'gpu_fyi_tests_release_trybot', 'mac_upload_clang': 'release_bot', 'mac-rel': 'gpu_tests_release_trybot', - 'mac-views-rel': 'mac_views_browser_release_trybot', }, 'tryserver.chromium.perf': { @@ -1208,6 +1207,10 @@ 'clang_tot', 'full_symbols', 'shared', 'release', ], + 'clang_tot_linux_official': [ + 'clang_tot', 'official', + ], + 'clang_tot_msan_release': [ 'clang_tot', 'msan', 'release', ], @@ -1611,14 +1614,6 @@ 'analysis' ], - 'mac_views_browser_release_bot': [ - 'mac_views_browser', 'release_bot', - ], - - 'mac_views_browser_release_trybot': [ - 'mac_views_browser', 'release_trybot', - ], - 'msan_edge_release_bot': [ 'msan', 'edge', 'release_bot', ], @@ -2145,10 +2140,6 @@ 'gn_args': 'enable_stripping=true', }, - 'mac_views_browser': { - 'gn_args': 'mac_views_browser=true', - }, - 'minimal_symbols': { 'gn_args': 'symbol_level=1', },
diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index 7ac9633..3d67c80a 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml
@@ -19892,8 +19892,11 @@ </action> <action name="Tab.Screenshot.WithoutStoragePermission"> - <owner>Please list the metric's owners. Add more owner tags as needed.</owner> - <description>Please enter the description of the metric.</description> + <owner>sebsg@chromium.org</owner> + <description> + Recorded when the user takes a screenshot of a chrome tab when chrome + doesn't have storage permissions. + </description> </action> <action name="Tab_DropURLBetweenTabs">
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index f7f63e2..ef64b53 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -15386,6 +15386,7 @@ <int value="516" label="ExtensionAllowInsecureUpdates"/> <int value="517" label="BrowserSwitcherEnabled"/> <int value="518" label="CertificateManagementAllowed"/> + <int value="519" label="BrowserSwitcherKeepLastChromeTab"/> </enum> <enum name="EnterprisePolicyInvalidations"> @@ -21519,6 +21520,7 @@ <int value="2779" label="V8HTMLMediaElement_Remote_AttributeGetter"/> <int value="2780" label="V8RemotePlayback_WatchAvailability_Method"/> <int value="2781" label="V8RemotePlayback_Prompt_Method"/> + <int value="2782" label="LayoutJankExplicitlyRequested"/> </enum> <enum name="FeaturePolicyFeature"> @@ -30795,6 +30797,7 @@ <int value="-1772172557" label="enable-osk-overscroll"/> <int value="-1768672408" label="ChromeDuplex:disabled"/> <int value="-1767470652" label="out-of-process-pdf"/> + <int value="-1766129470" label="DataSaverLiteModeRebranding:disabled"/> <int value="-1758468685" label="DownloadHomeV2:disabled"/> <int value="-1755301960" label="ClearOldBrowsingData:enabled"/> <int value="-1753458842" label="OfflinePagesLivePageSharing:disabled"/> @@ -31101,6 +31104,7 @@ <int value="-1276912933" label="enable-quick-unlock-pin"/> <int value="-1272593346" label="NewTabLoadingAnimation:disabled"/> <int value="-1271563519" label="enable-appcontainer"/> + <int value="-1269962982" label="SyncUSSPasswords:disabled"/> <int value="-1269093329" label="AndroidOmniboxPreviewsBadge:disabled"/> <int value="-1269084216" label="ash-md"/> <int value="-1268836676" label="disable-out-of-process-pdf"/> @@ -31532,6 +31536,7 @@ <int value="-516845951" label="enable-embedded-extension-options"/> <int value="-513967943" label="CryptAuthV2Enrollment:disabled"/> <int value="-513305102" label="LanguagesPreference:enabled"/> + <int value="-513066193" label="SyncUSSPasswords:enabled"/> <int value="-512971943" label="disable-one-copy"/> <int value="-510488450" label="disable-pnacl"/> <int value="-508250572" label="ServiceWorkerLongRunningMessage:disabled"/> @@ -32738,6 +32743,7 @@ <int value="1612446645" label="enable-weak-memorycache"/> <int value="1612871297" label="WebPayments:disabled"/> <int value="1612974229" label="allow-insecure-localhost"/> + <int value="1614309501" label="DataSaverLiteModeRebranding:enabled"/> <int value="1614596813" label="CloseButtonsInactiveTabs:disabled"/> <int value="1615988672" label="GrantNotificationsToDSE:enabled"/> <int value="1617187093" label="enable-improved-a2hs"/> @@ -43683,6 +43689,9 @@ <int value="6" label="User opted out of this preview (pre-s13n only)"/> <int value="7" label="The user has blocked cookies for the original page"/> <int value="8" label="ECT Unknown"/> + <int value="9" + label="Exceeded maximum number of navigation restarts or a redirect + loop was detected"/> </enum> <enum name="PreviewsServerLitePageServerResponse"> @@ -44993,6 +45002,7 @@ <int value="118" label="QUIC_STREAM_ID_BLOCKED_ERROR"/> <int value="119" label="QUIC_MAX_STREAM_ID_ERROR"/> <int value="120" label="QUIC_HTTP_DECODER_ERROR"/> + <int value="121" label="QUIC_STALE_CONNECTION_CANCELLED"/> </enum> <enum name="QuicHandshakeFailureReason">
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index e6a1ed22..6d68d2c1 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -3832,7 +3832,9 @@ <owner>tapted@chromium.org</owner> <summary> The type of app list search result that was opened by the user. This is - gathered per SearchResult opened. + gathered per SearchResult opened. Entries for milestone 62 are not accurate + and should be filtered out when viewing this histogram + (https://crbug.com/919550). </summary> </histogram> @@ -136651,6 +136653,8 @@ <histogram_suffixes name="MediaPipelineStatusForStreams" separator="."> <suffix name="AudioOnly" label="PipelineStatus for Audio-only streams."/> + <suffix name="AudioVideo.AV1.SW" + label="PipelineStatus for AV streams with AV1 software decoder."/> <suffix name="AudioVideo.H264.DDS.HW" label="PipelineStatus for AV streams with H264 hardware decoder and that go through the DecryptingDemuxerStream (DDS)."/> @@ -144322,11 +144326,7 @@ <histogram_suffixes name="TaskSchedulerWorkerPool" separator="."> <suffix name="BackgroundBlockingPool" - label="Applies to the BackgroundBlocking worker pool."> - <obsolete> - Deprecated January 2019 as the pool no longer exists. - </obsolete> - </suffix> + label="Applies to the BackgroundBlocking worker pool."/> <suffix name="BackgroundFileIOPool" label="Applies to the BackgroundFileIO worker pool."> <obsolete> @@ -144335,11 +144335,7 @@ </suffix> <suffix name="BackgroundPool" label="Applies to the Background worker pool."/> <suffix name="ForegroundBlockingPool" - label="Applies to the ForegroundBlocking worker pool."> - <obsolete> - Deprecated January 2019 as the pool no longer exists. - </obsolete> - </suffix> + label="Applies to the ForegroundBlocking worker pool."/> <suffix name="ForegroundFileIOPool" label="Applies to the ForegroundFileIO worker pool."> <obsolete>
diff --git a/tools/perf/contrib/network_service/loading.py b/tools/perf/contrib/network_service/loading.py index 538c568..2b17f08 100644 --- a/tools/perf/contrib/network_service/loading.py +++ b/tools/perf/contrib/network_service/loading.py
@@ -15,6 +15,8 @@ from telemetry.value import none_values from telemetry.value.list_of_scalar_values import StandardDeviation +from tracing.value import convert_chart_json + def _ListSubtraction(diff_list, control_list): """Subtract |control_list|'s elements from the corresponding elements in |diff_list|, and store the results in |diff_list|. @@ -157,10 +159,12 @@ def Run(self, finder_options): """We shouldn't be overriding this according to telemetry.benchmark.Benchmark""" - assert 'chartjson' in finder_options.output_formats, ( - 'loading.desktop.network_service requires --output-format=chartjson. ' - 'Please contact owner to rewrite the benchmark if chartjson is going ' - 'away.') + assert 'histograms' in finder_options.output_formats, ( + 'loading.desktop.network_service requires --output-format=histograms.') + + # feed the story_runner with 'chartjson' output formats. + finder_options.output_formats = ['chartjson'] + assert finder_options.output_dir output_dir = finder_options.output_dir temp_file_path = os.path.join(output_dir, 'results-chart.json') @@ -198,6 +202,17 @@ with open(temp_file_path, 'w') as f: json.dump(enabled_chart_json, f, indent=2, separators=(',', ': ')) f.write('\n') + logging.info('Converting chartjsons to histograms') + histogram_result = convert_chart_json.ConvertChartJson(temp_file_path) + if histogram_result.returncode != 0: + logging.error('Error converting chart json to Histograms:\n' + + histogram_result.stdout) + return 1 + + temp_file_path = os.path.join(output_dir, 'histograms.json') + with open(temp_file_path, 'w') as f: + f.write(histogram_result.stdout) + return 0 def SetExtraBrowserOptions(self, options):
diff --git a/ui/android/BUILD.gn b/ui/android/BUILD.gn index bb5c67c5..bd312d3 100644 --- a/ui/android/BUILD.gn +++ b/ui/android/BUILD.gn
@@ -131,22 +131,24 @@ java_strings_grd("ui_strings_grd") { grd_file = "java/strings/android_ui_strings.grd" outputs = [ + "values/android_ui_strings.xml", "values-am/android_ui_strings.xml", "values-ar/android_ui_strings.xml", "values-bg/android_ui_strings.xml", + "values-bn/android_ui_strings.xml", "values-ca/android_ui_strings.xml", "values-cs/android_ui_strings.xml", "values-da/android_ui_strings.xml", "values-de/android_ui_strings.xml", "values-el/android_ui_strings.xml", - "values/android_ui_strings.xml", "values-en-rGB/android_ui_strings.xml", "values-es/android_ui_strings.xml", "values-es-rUS/android_ui_strings.xml", + "values-et/android_ui_strings.xml", "values-fa/android_ui_strings.xml", "values-fi/android_ui_strings.xml", - "values-tl/android_ui_strings.xml", "values-fr/android_ui_strings.xml", + "values-gu/android_ui_strings.xml", "values-hi/android_ui_strings.xml", "values-hr/android_ui_strings.xml", "values-hu/android_ui_strings.xml", @@ -154,11 +156,15 @@ "values-it/android_ui_strings.xml", "values-iw/android_ui_strings.xml", "values-ja/android_ui_strings.xml", + "values-kn/android_ui_strings.xml", "values-ko/android_ui_strings.xml", "values-lt/android_ui_strings.xml", "values-lv/android_ui_strings.xml", - "values-nl/android_ui_strings.xml", + "values-ml/android_ui_strings.xml", + "values-mr/android_ui_strings.xml", + "values-ms/android_ui_strings.xml", "values-nb/android_ui_strings.xml", + "values-nl/android_ui_strings.xml", "values-pl/android_ui_strings.xml", "values-pt-rBR/android_ui_strings.xml", "values-pt-rPT/android_ui_strings.xml", @@ -169,7 +175,10 @@ "values-sr/android_ui_strings.xml", "values-sv/android_ui_strings.xml", "values-sw/android_ui_strings.xml", + "values-ta/android_ui_strings.xml", + "values-te/android_ui_strings.xml", "values-th/android_ui_strings.xml", + "values-tl/android_ui_strings.xml", "values-tr/android_ui_strings.xml", "values-uk/android_ui_strings.xml", "values-vi/android_ui_strings.xml", @@ -216,10 +225,7 @@ } generate_ui_locale_resources("ui_locale_string_resources") { - # NOTE: It is not possible to pass just |locales| here, otherwise - # the lint step will later complain that 3 strings in android_ui_strings.grd - # are not localized to the omitted locales! - ui_locales = locales - android_chrome_omitted_locales + ui_locales = locales } android_resources("ui_java_resources") {
diff --git a/ui/android/java/strings/android_ui_strings.grd b/ui/android/java/strings/android_ui_strings.grd index f2abb79..ecd0010 100644 --- a/ui/android/java/strings/android_ui_strings.grd +++ b/ui/android/java/strings/android_ui_strings.grd
@@ -4,6 +4,7 @@ <output filename="values-am/android_ui_strings.xml" lang="am" type="android" /> <output filename="values-ar/android_ui_strings.xml" lang="ar" type="android" /> <output filename="values-bg/android_ui_strings.xml" lang="bg" type="android" /> + <output filename="values-bn/android_ui_strings.xml" lang="bn" type="android" /> <output filename="values-ca/android_ui_strings.xml" lang="ca" type="android" /> <output filename="values-cs/android_ui_strings.xml" lang="cs" type="android" /> <output filename="values-da/android_ui_strings.xml" lang="da" type="android" /> @@ -13,10 +14,12 @@ <output filename="values-en-rGB/android_ui_strings.xml" lang="en-GB" type="android" /> <output filename="values-es/android_ui_strings.xml" lang="es" type="android" /> <output filename="values-es-rUS/android_ui_strings.xml" lang="es-419" type="android" /> + <output filename="values-et/android_ui_strings.xml" lang="et" type="android" /> <output filename="values-fa/android_ui_strings.xml" lang="fa" type="android" /> <output filename="values-fi/android_ui_strings.xml" lang="fi" type="android" /> <output filename="values-tl/android_ui_strings.xml" lang="fil" type="android" /> <output filename="values-fr/android_ui_strings.xml" lang="fr" type="android" /> + <output filename="values-gu/android_ui_strings.xml" lang="gu" type="android" /> <output filename="values-hi/android_ui_strings.xml" lang="hi" type="android" /> <output filename="values-hr/android_ui_strings.xml" lang="hr" type="android" /> <output filename="values-hu/android_ui_strings.xml" lang="hu" type="android" /> @@ -24,9 +27,13 @@ <output filename="values-it/android_ui_strings.xml" lang="it" type="android" /> <output filename="values-iw/android_ui_strings.xml" lang="iw" type="android" /> <output filename="values-ja/android_ui_strings.xml" lang="ja" type="android" /> + <output filename="values-kn/android_ui_strings.xml" lang="kn" type="android" /> <output filename="values-ko/android_ui_strings.xml" lang="ko" type="android" /> <output filename="values-lt/android_ui_strings.xml" lang="lt" type="android" /> <output filename="values-lv/android_ui_strings.xml" lang="lv" type="android" /> + <output filename="values-ml/android_ui_strings.xml" lang="ml" type="android" /> + <output filename="values-mr/android_ui_strings.xml" lang="mr" type="android" /> + <output filename="values-ms/android_ui_strings.xml" lang="ms" type="android" /> <output filename="values-nl/android_ui_strings.xml" lang="nl" type="android" /> <output filename="values-nb/android_ui_strings.xml" lang="no" type="android" /> <output filename="values-pl/android_ui_strings.xml" lang="pl" type="android" /> @@ -39,6 +46,8 @@ <output filename="values-sr/android_ui_strings.xml" lang="sr" type="android" /> <output filename="values-sv/android_ui_strings.xml" lang="sv" type="android" /> <output filename="values-sw/android_ui_strings.xml" lang="sw" type="android" /> + <output filename="values-ta/android_ui_strings.xml" lang="ta" type="android" /> + <output filename="values-te/android_ui_strings.xml" lang="te" type="android" /> <output filename="values-th/android_ui_strings.xml" lang="th" type="android" /> <output filename="values-tr/android_ui_strings.xml" lang="tr" type="android" /> <output filename="values-uk/android_ui_strings.xml" lang="uk" type="android" />
diff --git a/ui/aura/mus/window_tree_client.cc b/ui/aura/mus/window_tree_client.cc index fc635f48..57643670 100644 --- a/ui/aura/mus/window_tree_client.cc +++ b/ui/aura/mus/window_tree_client.cc
@@ -229,6 +229,12 @@ return it != windows_.end() ? it->second : nullptr; } +void WindowTreeClient::SetCanFocus(Window* window, bool can_focus) { + DCHECK(tree_); + DCHECK(window); + tree_->SetCanFocus(WindowMus::Get(window)->server_id(), can_focus); +} + void WindowTreeClient::SetCursor(WindowMus* window, const ui::Cursor& old_cursor, const ui::Cursor& new_cursor) {
diff --git a/ui/aura/mus/window_tree_client.h b/ui/aura/mus/window_tree_client.h index 6e2b375..5cb9f38 100644 --- a/ui/aura/mus/window_tree_client.h +++ b/ui/aura/mus/window_tree_client.h
@@ -132,6 +132,7 @@ WindowMus* GetWindowByServerId(ws::Id id); + void SetCanFocus(Window* window, bool can_focus); void SetCanAcceptDrops(WindowMus* window, bool can_accept_drops); void SetEventTargetingPolicy(WindowMus* window, ws::mojom::EventTargetingPolicy policy);
diff --git a/ui/aura/test/mus/test_window_tree.cc b/ui/aura/test/mus/test_window_tree.cc index c789a14..98bf5a3f 100644 --- a/ui/aura/test/mus/test_window_tree.cc +++ b/ui/aura/test/mus/test_window_tree.cc
@@ -332,6 +332,8 @@ OnChangeReceived(change_id, WindowTreeChangeType::FOCUS); } +void TestWindowTree::SetCanFocus(ws::Id window_id, bool can_focus) {} + void TestWindowTree::SetEventTargetingPolicy( ws::Id window_id, ws::mojom::EventTargetingPolicy policy) {}
diff --git a/ui/aura/test/mus/test_window_tree.h b/ui/aura/test/mus/test_window_tree.h index 0863c99..142c259 100644 --- a/ui/aura/test/mus/test_window_tree.h +++ b/ui/aura/test/mus/test_window_tree.h
@@ -246,6 +246,7 @@ const viz::FrameSinkId& frame_sink_id) override; void UnattachFrameSinkId(uint64_t window_id) override; void SetFocus(uint32_t change_id, ws::Id window_id) override; + void SetCanFocus(ws::Id window_id, bool can_focus) override; void SetEventTargetingPolicy(ws::Id window_id, ws::mojom::EventTargetingPolicy policy) override; void SetCursor(uint32_t change_id,
diff --git a/ui/base/ui_base_features.cc b/ui/base/ui_base_features.cc index 70cb362..e1f8d01 100644 --- a/ui/base/ui_base_features.cc +++ b/ui/base/ui_base_features.cc
@@ -100,6 +100,11 @@ // Enables DirectManipulation API for processing Precision Touchpad events. const base::Feature kPrecisionTouchpad{"PrecisionTouchpad", base::FEATURE_ENABLED_BY_DEFAULT}; + +// Enables Logging for DirectManipulation. +const base::Feature kPrecisionTouchpadLogging{ + "PrecisionTouchpadLogging", base::FEATURE_DISABLED_BY_DEFAULT}; + // Enables Swipe left/right to navigation back/forward API for processing // Precision Touchpad events. const base::Feature kPrecisionTouchpadScrollPhase{
diff --git a/ui/base/ui_base_features.h b/ui/base/ui_base_features.h index 614dc06..e719644 100644 --- a/ui/base/ui_base_features.h +++ b/ui/base/ui_base_features.h
@@ -35,6 +35,7 @@ UI_BASE_EXPORT extern const base::Feature kInputPaneOnScreenKeyboard; UI_BASE_EXPORT extern const base::Feature kPointerEventsForTouch; UI_BASE_EXPORT extern const base::Feature kPrecisionTouchpad; +UI_BASE_EXPORT extern const base::Feature kPrecisionTouchpadLogging; UI_BASE_EXPORT extern const base::Feature kPrecisionTouchpadScrollPhase; UI_BASE_EXPORT extern const base::Feature kTSFImeSupport;
diff --git a/ui/base/win/direct_manipulation.cc b/ui/base/win/direct_manipulation.cc index 65b5dcb0..f1317f08 100644 --- a/ui/base/win/direct_manipulation.cc +++ b/ui/base/win/direct_manipulation.cc
@@ -7,7 +7,9 @@ #include <objbase.h> #include <cmath> +#include "base/logging.h" #include "base/memory/ptr_util.h" +#include "base/optional.h" #include "base/threading/thread_task_runner_handle.h" #include "base/win/windows_version.h" #include "ui/base/ui_base_features.h" @@ -17,6 +19,30 @@ namespace ui { namespace win { +namespace { +base::Optional<bool> logging_enabled; + +bool LoggingEnabled() { + if (!logging_enabled.has_value()) { + logging_enabled = + base::FeatureList::IsEnabled(features::kPrecisionTouchpadLogging); + } + + return logging_enabled.value(); +} + +// TODO(crbug.com/914914) This is added for help us getting debug log on +// machine with scrolling issue on Windows Precision Touchpad. We will remove it +// after Windows Precision Touchpad scrolling issue fixed. +void DebugLogging(const std::string& s, HRESULT hr) { + if (!LoggingEnabled()) + return; + + LOG(ERROR) << "Windows PTP: " << s << " " << hr; +} + +} // namespace + // static std::unique_ptr<DirectManipulationHelper> DirectManipulationHelper::CreateInstance(HWND window, @@ -79,18 +105,24 @@ HRESULT hr = ::CoCreateInstance(CLSID_DirectManipulationManager, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&manager_)); - if (!SUCCEEDED(hr)) + if (!SUCCEEDED(hr)) { + DebugLogging("DirectManipulationManager create failed.", hr); return false; + } // Since we want to use fake viewport, we need UpdateManager to tell a fake // fake render frame. hr = manager_->GetUpdateManager(IID_PPV_ARGS(&update_manager_)); - if (!SUCCEEDED(hr)) + if (!SUCCEEDED(hr)) { + DebugLogging("Get UpdateManager failed.", hr); return false; + } hr = manager_->CreateViewport(nullptr, window_, IID_PPV_ARGS(&viewport_)); - if (!SUCCEEDED(hr)) + if (!SUCCEEDED(hr)) { + DebugLogging("Viewport create failed.", hr); return false; + } DIRECTMANIPULATION_CONFIGURATION configuration = DIRECTMANIPULATION_CONFIGURATION_INTERACTION | @@ -102,15 +134,19 @@ DIRECTMANIPULATION_CONFIGURATION_SCALING; hr = viewport_->ActivateConfiguration(configuration); - if (!SUCCEEDED(hr)) + if (!SUCCEEDED(hr)) { + DebugLogging("Viewport set ActivateConfiguration failed.", hr); return false; + } // Since we are using fake viewport and only want to use Direct Manipulation // for touchpad, we need to use MANUALUPDATE option. hr = viewport_->SetViewportOptions( DIRECTMANIPULATION_VIEWPORT_OPTIONS_MANUALUPDATE); - if (!SUCCEEDED(hr)) + if (!SUCCEEDED(hr)) { + DebugLogging("Viewport set ViewportOptions failed.", hr); return false; + } event_handler_ = Microsoft::WRL::Make<DirectManipulationHandler>(this, event_target); @@ -119,50 +155,81 @@ // IDirectManipulationViewportEventHandler. hr = viewport_->AddEventHandler(window_, event_handler_.Get(), &view_port_handler_cookie_); - if (!SUCCEEDED(hr)) + if (!SUCCEEDED(hr)) { + DebugLogging("Viewport add EventHandler failed.", hr); return false; + } // Set default rect for viewport before activate. viewport_size_ = {1000, 1000}; RECT rect = gfx::Rect(viewport_size_).ToRECT(); hr = viewport_->SetViewportRect(&rect); - if (!SUCCEEDED(hr)) + if (!SUCCEEDED(hr)) { + DebugLogging("Viewport set rect failed.", hr); return false; + } hr = manager_->Activate(window_); - if (!SUCCEEDED(hr)) + if (!SUCCEEDED(hr)) { + DebugLogging("DirectManipulationManager activate failed.", hr); return false; + } hr = viewport_->Enable(); - if (!SUCCEEDED(hr)) + if (!SUCCEEDED(hr)) { + DebugLogging("Viewport enable failed.", hr); return false; + } hr = update_manager_->Update(nullptr); - if (!SUCCEEDED(hr)) + if (!SUCCEEDED(hr)) { + DebugLogging("UpdateManager update failed.", hr); return false; + } + DebugLogging("DirectManipulation initialization complete", S_OK); return true; } void DirectManipulationHelper::Activate() { - viewport_->Stop(); - manager_->Activate(window_); + HRESULT hr = viewport_->Stop(); + if (!SUCCEEDED(hr)) { + DebugLogging("Viewport stop failed.", hr); + return; + } + + hr = manager_->Activate(window_); + if (!SUCCEEDED(hr)) + DebugLogging("DirectManipulationManager activate failed.", hr); } void DirectManipulationHelper::Deactivate() { - viewport_->Stop(); - manager_->Deactivate(window_); + HRESULT hr = viewport_->Stop(); + if (!SUCCEEDED(hr)) { + DebugLogging("Viewport stop failed.", hr); + return; + } + + hr = manager_->Deactivate(window_); + if (!SUCCEEDED(hr)) + DebugLogging("DirectManipulationManager deactivate failed.", hr); } void DirectManipulationHelper::SetSize(const gfx::Size& size) { if (viewport_size_ == size) return; - viewport_->Stop(); + HRESULT hr = viewport_->Stop(); + if (!SUCCEEDED(hr)) { + DebugLogging("Viewport stop failed.", hr); + return; + } viewport_size_ = size; RECT rect = gfx::Rect(viewport_size_).ToRECT(); - viewport_->SetViewportRect(&rect); + hr = viewport_->SetViewportRect(&rect); + if (!SUCCEEDED(hr)) + DebugLogging("Viewport set rect failed.", hr); } bool DirectManipulationHelper::OnPointerHitTest( @@ -187,7 +254,12 @@ GetProcAddress(GetModuleHandleA("user32.dll"), "GetPointerType")); if (get_pointer_type && get_pointer_type(pointer_id, &pointer_type) && pointer_type == PT_TOUCHPAD && event_target) { - viewport_->SetContact(pointer_id); + HRESULT hr = viewport_->SetContact(pointer_id); + if (!SUCCEEDED(hr)) { + DebugLogging("Viewport set contact failed.", hr); + return false; + } + // Request begin frame for fake viewport. need_poll_events_ = true; } @@ -201,8 +273,10 @@ viewport_->ZoomToRect(static_cast<float>(0), static_cast<float>(0), static_cast<float>(viewport_size_.width()), static_cast<float>(viewport_size_.height()), FALSE); - if (!SUCCEEDED(hr)) + if (!SUCCEEDED(hr)) { + DebugLogging("Viewport zoom to rect failed.", hr); return hr; + } need_poll_events_ = need_poll_events; return S_OK; @@ -210,7 +284,9 @@ bool DirectManipulationHelper::PollForNextEvent() { // Simulate 1 frame in update_manager_. - update_manager_->Update(nullptr); + HRESULT hr = update_manager_->Update(nullptr); + if (!SUCCEEDED(hr)) + DebugLogging("UpdateManager update failed.", hr); return need_poll_events_; } @@ -234,6 +310,13 @@ if (gesture_state_ == new_gesture_state) return; + if (LoggingEnabled()) { + std::string s = "TransitionToState " + + std::to_string(static_cast<int>(gesture_state_)) + " -> " + + std::to_string(static_cast<int>(new_gesture_state)); + DebugLogging(s, S_OK); + } + Gesture previous_gesture_state = gesture_state_; gesture_state_ = new_gesture_state; @@ -303,6 +386,12 @@ // testing. DCHECK(viewport); + if (LoggingEnabled()) { + std::string s = "ViewportStatusChanged " + std::to_string(previous) + + " -> " + std::to_string(current); + DebugLogging(s, S_OK); + } + // The state of our viewport has changed! We'l be in one of three states: // - ENABLED: initial state // - READY: the previous gesture has been completed @@ -397,8 +486,10 @@ float xform[6]; hr = content->GetContentTransform(xform, ARRAYSIZE(xform)); - if (!SUCCEEDED(hr)) + if (!SUCCEEDED(hr)) { + DebugLogging("DirectManipulationContent get transform failed.", hr); return hr; + } float scale = xform[0]; int x_offset = xform[4] / device_scale_factor_;
diff --git a/ui/gl/BUILD.gn b/ui/gl/BUILD.gn index 77750dc..cb976c1 100644 --- a/ui/gl/BUILD.gn +++ b/ui/gl/BUILD.gn
@@ -562,6 +562,7 @@ generate_jar_jni("surface_jni_headers") { jni_package = "ui/gl" classes = [ "android/view/Surface.class" ] + always_mangle = true } generate_jni("gl_jni_headers") {
diff --git a/ui/gl/android/scoped_java_surface.cc b/ui/gl/android/scoped_java_surface.cc index 26f97e5..b88669c2 100644 --- a/ui/gl/android/scoped_java_surface.cc +++ b/ui/gl/android/scoped_java_surface.cc
@@ -24,7 +24,7 @@ ScopedJavaSurface::ScopedJavaSurface(const SurfaceTexture* surface_texture) { JNIEnv* env = base::android::AttachCurrentThread(); - ScopedJavaLocalRef<jobject> tmp(JNI_Surface::Java_Surface_Constructor( + ScopedJavaLocalRef<jobject> tmp(JNI_Surface::Java_Surface_ConstructorAVS_AGST( env, surface_texture->j_surface_texture())); DCHECK(!tmp.is_null()); j_surface_.Reset(tmp); @@ -46,7 +46,7 @@ void ScopedJavaSurface::ReleaseSurfaceIfNeeded() { if (auto_release_ && !j_surface_.is_null()) { JNIEnv* env = base::android::AttachCurrentThread(); - JNI_Surface::Java_Surface_release(env, j_surface_); + JNI_Surface::Java_Surface_releaseV(env, j_surface_); } } @@ -64,7 +64,7 @@ bool ScopedJavaSurface::IsValid() const { JNIEnv* env = base::android::AttachCurrentThread(); - return !IsEmpty() && JNI_Surface::Java_Surface_isValid(env, j_surface_); + return !IsEmpty() && JNI_Surface::Java_Surface_isValidZ(env, j_surface_); } // static
diff --git a/ui/gl/gl_bindings_autogen_gl.cc b/ui/gl/gl_bindings_autogen_gl.cc index 552fdcf..a8b45cfe 100644 --- a/ui/gl/gl_bindings_autogen_gl.cc +++ b/ui/gl/gl_bindings_autogen_gl.cc
@@ -304,6 +304,8 @@ gfx::HasExtension(extensions, "GL_ARB_draw_buffers"); ext.b_GL_ARB_draw_instanced = gfx::HasExtension(extensions, "GL_ARB_draw_instanced"); + ext.b_GL_ARB_ES2_compatibility = + gfx::HasExtension(extensions, "GL_ARB_ES2_compatibility"); ext.b_GL_ARB_framebuffer_object = gfx::HasExtension(extensions, "GL_ARB_framebuffer_object"); ext.b_GL_ARB_get_program_binary = @@ -1406,7 +1408,8 @@ GetGLProcAddress("glGetProgramResourceiv")); } - if (ver->IsAtLeastGL(4u, 3u) || ver->IsAtLeastGLES(3u, 1u)) { + if (ver->IsAtLeastGL(4u, 3u) || ver->IsAtLeastGLES(3u, 1u) || + ext.b_GL_ARB_program_interface_query) { fn.glGetProgramResourceLocationFn = reinterpret_cast<glGetProgramResourceLocationProc>( GetGLProcAddress("glGetProgramResourceLocation")); @@ -1560,7 +1563,8 @@ GetGLProcAddress("glGetShaderivRobustANGLE")); } - if (ver->IsAtLeastGL(4u, 1u) || ver->is_es) { + if (ver->IsAtLeastGL(4u, 1u) || ver->is_es || + ext.b_GL_ARB_ES2_compatibility) { fn.glGetShaderPrecisionFormatFn = reinterpret_cast<glGetShaderPrecisionFormatProc>( GetGLProcAddress("glGetShaderPrecisionFormat"));
diff --git a/ui/gl/gl_bindings_autogen_gl.h b/ui/gl/gl_bindings_autogen_gl.h index a91d0c9..3af0694 100644 --- a/ui/gl/gl_bindings_autogen_gl.h +++ b/ui/gl/gl_bindings_autogen_gl.h
@@ -1783,6 +1783,7 @@ bool b_GL_ARB_blend_func_extended; bool b_GL_ARB_draw_buffers; bool b_GL_ARB_draw_instanced; + bool b_GL_ARB_ES2_compatibility; bool b_GL_ARB_framebuffer_object; bool b_GL_ARB_get_program_binary; bool b_GL_ARB_instanced_arrays;
diff --git a/ui/latency/latency_tracker.cc b/ui/latency/latency_tracker.cc index 88d8346..d98a8e0 100644 --- a/ui/latency/latency_tracker.cc +++ b/ui/latency/latency_tracker.cc
@@ -369,7 +369,7 @@ // creation time and gpu swap begin time. pending_finished_lag_report_->lag = (gpu_swap_begin_timestamp - event_timestamp).InMillisecondsF() * - latency.scroll_update_delta(); + std::abs(latency.scroll_update_delta()); // The next report time should be a least 1 second away from current report // time. next_report_time_ = pending_finished_lag_report_->report_time + @@ -386,14 +386,14 @@ // average delta(current delta/2). float pending_finger_move_lag = (event_timestamp - last_event_timestamp_).InMillisecondsF() * - latency.scroll_update_delta() / 2; + std::abs(latency.scroll_update_delta() / 2); // |event_dispatch_lag| is the area between the current event creation time // (i.e. last coalesced event of current event creation time) and gpu swap // begin time of this event. float event_dispatch_lag = (gpu_swap_begin_timestamp - event_timestamp).InMillisecondsF() * - latency.scroll_update_delta(); + std::abs(latency.scroll_update_delta()); if (pending_finished_lag_report_) { if (event_timestamp >= pending_finished_lag_report_->report_time) { @@ -421,7 +421,7 @@ (gpu_swap_begin_timestamp - pending_finished_lag_report_->report_time) .InMillisecondsF() * - latency.scroll_update_delta(); + std::abs(latency.scroll_update_delta()); pending_finished_lag_report_->lag += pending_finger_move_lag + event_dispatch_lag - lag_after_report_time; @@ -460,9 +460,10 @@ void LatencyTracker::ReportAverageLagUma(std::unique_ptr<LagData> report) { if (report) { DCHECK(!report->report_time.is_null()); + DCHECK(report->lag >= 0.f); base::UmaHistogramCounts1000( "Event.Latency." + report->scroll_name + ".Touch.AverageLag", - std::abs(report->lag) / + report->lag / (report->report_time - last_reported_time_).InMillisecondsF()); last_reported_time_ = report->report_time;
diff --git a/ui/native_theme/common_theme.cc b/ui/native_theme/common_theme.cc index 4206342..2017e90c 100644 --- a/ui/native_theme/common_theme.cc +++ b/ui/native_theme/common_theme.cc
@@ -44,6 +44,7 @@ switch (color_id) { case NativeTheme::kColorId_LabelEnabledColor: case NativeTheme::kColorId_TextfieldDefaultColor: + case NativeTheme::kColorId_EnabledMenuItemForegroundColor: case NativeTheme::kColorId_SelectedMenuItemForegroundColor: case NativeTheme::kColorId_HighlightedMenuItemForegroundColor: return gfx::kGoogleGrey200;
diff --git a/ui/native_theme/native_theme_win.cc b/ui/native_theme/native_theme_win.cc index 932abb6b..08d5bc5 100644 --- a/ui/native_theme/native_theme_win.cc +++ b/ui/native_theme/native_theme_win.cc
@@ -432,6 +432,14 @@ } SkColor NativeThemeWin::GetSystemColor(ColorId color_id) const { + // Win32 system colors currently don't support Dark Mode. As a result, + // fallback on the Aura colors. Inverted color schemes can be ignored here + // as it's only true when Chrome is running on a high-contrast AND when the + // relative luminance of COLOR_WINDOWTEXT is greater than COLOR_WINDOW (e.g. + // white on black), which is basically like dark mode. + if (SystemDarkModeEnabled()) + return GetAuraColor(color_id, this); + // TODO: Obtain the correct colors for these using GetSysColor. // Button: constexpr SkColor kButtonHoverColor = SkColorSetRGB(6, 45, 117);
diff --git a/ui/ozone/platform/wayland/BUILD.gn b/ui/ozone/platform/wayland/BUILD.gn index 1644e69..ddbcee3c 100644 --- a/ui/ozone/platform/wayland/BUILD.gn +++ b/ui/ozone/platform/wayland/BUILD.gn
@@ -5,6 +5,7 @@ visibility = [ "//ui/ozone/*" ] import("//build/config/linux/pkg_config.gni") +import("//testing/libfuzzer/fuzzer_test.gni") import("//ui/ozone/platform/wayland/wayland.gni") pkg_config("wayland-egl") { @@ -206,6 +207,10 @@ deps = [ "//base:base", + "//ui/ozone:platform", + ] + + public_deps = [ "//skia", "//testing/gmock", "//third_party/wayland:wayland_server", @@ -262,3 +267,18 @@ defines += [ "WAYLAND_GBM" ] } } + +fuzzer_test("wayland_buffer_fuzzer") { + defines = [ "WL_HIDE_DEPRECATED" ] + sources = [ + "wayland_buffer_fuzzer.cc", + ] + deps = [ + ":test_support", + ":wayland", + "//base/test:test_support", + "//build/config/linux/libdrm", + "//ui/gfx:test_support", + "//ui/platform_window:platform_window", + ] +}
diff --git a/ui/ozone/platform/wayland/test/mock_buffer.cc b/ui/ozone/platform/wayland/test/mock_buffer.cc index b31f928..11af912 100644 --- a/ui/ozone/platform/wayland/test/mock_buffer.cc +++ b/ui/ozone/platform/wayland/test/mock_buffer.cc
@@ -11,11 +11,6 @@ MockBuffer::MockBuffer(wl_resource* resource, std::vector<base::ScopedFD>&& fds) : ServerObject(resource), fds_(std::move(fds)) {} -MockBuffer::~MockBuffer() { - for (auto& fd : fds_) { - LOG(WARNING) << "Will close FD: " << fd.get(); - fd.reset(); - } -} +MockBuffer::~MockBuffer() {} } // namespace wl
diff --git a/ui/ozone/platform/wayland/test/mock_buffer.h b/ui/ozone/platform/wayland/test/mock_buffer.h index 94f565f6..1b0eee3 100644 --- a/ui/ozone/platform/wayland/test/mock_buffer.h +++ b/ui/ozone/platform/wayland/test/mock_buffer.h
@@ -12,7 +12,6 @@ #include "testing/gmock/include/gmock/gmock.h" #include "ui/ozone/platform/wayland/test/server_object.h" -struct wl_client; struct wl_resource; namespace wl { @@ -25,8 +24,6 @@ MockBuffer(wl_resource* resource, std::vector<base::ScopedFD>&& fds); ~MockBuffer() override; - MOCK_METHOD2(Destroy, void(wl_client* client, wl_resource* resource)); - private: std::vector<base::ScopedFD> fds_;
diff --git a/ui/ozone/platform/wayland/test/mock_zwp_linux_buffer_params.cc b/ui/ozone/platform/wayland/test/mock_zwp_linux_buffer_params.cc index 4e48727..ca7fa6a 100644 --- a/ui/ozone/platform/wayland/test/mock_zwp_linux_buffer_params.cc +++ b/ui/ozone/platform/wayland/test/mock_zwp_linux_buffer_params.cc
@@ -34,9 +34,10 @@ auto* buffer_params = GetUserDataAs<MockZwpLinuxBufferParamsV1>(buffer_params_resource); - wl_resource* buffer_resource = CreateResourceWithImpl<MockBuffer>( - client, &wl_buffer_interface, 1, &kMockWlBufferImpl, 0, - std::move(buffer_params->fds_)); + wl_resource* buffer_resource = + CreateResourceWithImpl<::testing::NiceMock<MockBuffer>>( + client, &wl_buffer_interface, 1, &kMockWlBufferImpl, 0, + std::move(buffer_params->fds_)); zwp_linux_buffer_params_v1_send_created(buffer_params_resource, buffer_resource);
diff --git a/ui/ozone/platform/wayland/test/mock_zwp_linux_dmabuf.cc b/ui/ozone/platform/wayland/test/mock_zwp_linux_dmabuf.cc index b82975d3..c44d41a4 100644 --- a/ui/ozone/platform/wayland/test/mock_zwp_linux_dmabuf.cc +++ b/ui/ozone/platform/wayland/test/mock_zwp_linux_dmabuf.cc
@@ -17,7 +17,7 @@ constexpr uint32_t kLinuxDmabufVersion = 1; void CreateParams(wl_client* client, wl_resource* resource, uint32_t id) { - CreateResourceWithImpl<MockZwpLinuxBufferParamsV1>( + CreateResourceWithImpl<::testing::NiceMock<MockZwpLinuxBufferParamsV1>>( client, &zwp_linux_buffer_params_v1_interface, wl_resource_get_version(resource), &kMockZwpLinuxBufferParamsV1Impl, id);
diff --git a/ui/ozone/platform/wayland/test/test_compositor.cc b/ui/ozone/platform/wayland/test/test_compositor.cc index 6345232d..8883302 100644 --- a/ui/ozone/platform/wayland/test/test_compositor.cc +++ b/ui/ozone/platform/wayland/test/test_compositor.cc
@@ -20,9 +20,10 @@ void CreateSurface(wl_client* client, wl_resource* compositor_resource, uint32_t id) { - wl_resource* resource = CreateResourceWithImpl<MockSurface>( - client, &wl_surface_interface, - wl_resource_get_version(compositor_resource), &kMockSurfaceImpl, id); + wl_resource* resource = + CreateResourceWithImpl<::testing::NiceMock<MockSurface>>( + client, &wl_surface_interface, + wl_resource_get_version(compositor_resource), &kMockSurfaceImpl, id); GetUserDataAs<TestCompositor>(compositor_resource) ->AddSurface(GetUserDataAs<MockSurface>(resource)); }
diff --git a/ui/ozone/platform/wayland/test/test_wayland_server_thread.cc b/ui/ozone/platform/wayland/test/test_wayland_server_thread.cc index fa008a00..e92e077 100644 --- a/ui/ozone/platform/wayland/test/test_wayland_server_thread.cc +++ b/ui/ozone/platform/wayland/test/test_wayland_server_thread.cc
@@ -30,6 +30,9 @@ controller_(FROM_HERE) {} TestWaylandServerThread::~TestWaylandServerThread() { + if (client_) + wl_client_destroy(client_); + Resume(); Stop(); }
diff --git a/ui/ozone/platform/wayland/wayland_buffer_fuzzer.cc b/ui/ozone/platform/wayland/wayland_buffer_fuzzer.cc new file mode 100644 index 0000000..84395c4 --- /dev/null +++ b/ui/ozone/platform/wayland/wayland_buffer_fuzzer.cc
@@ -0,0 +1,141 @@ +// 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. + +// This fuzzer tests browser-side implementation of +// ozone::mojom::WaylandConnection. + +#include <drm_fourcc.h> +#include <stddef.h> +#include <stdint.h> + +#include <memory> +#include <vector> + +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/message_loop/message_loop.h" +#include "base/test/fuzzed_data_provider.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/ozone/platform/wayland/test/test_wayland_server_thread.h" +#include "ui/ozone/platform/wayland/wayland_connection.h" +#include "ui/ozone/platform/wayland/wayland_window.h" +#include "ui/platform_window/platform_window_delegate.h" +#include "ui/platform_window/platform_window_init_properties.h" + +using testing::_; + +namespace { + +// Off-class equivalent of WaylandTest::Sync. +void Sync(wl::TestWaylandServerThread* server) { + DCHECK(server); + + server->Resume(); + base::RunLoop().RunUntilIdle(); + server->Pause(); +} + +// Copied from ui/ozone/test/mock_platform_window_delegate.h to avoid +// dependency from the whole library (it causes link problems). +class MockPlatformWindowDelegate : public ui::PlatformWindowDelegate { + public: + MockPlatformWindowDelegate() = default; + ~MockPlatformWindowDelegate() = default; + + MOCK_METHOD1(OnBoundsChanged, void(const gfx::Rect& new_bounds)); + MOCK_METHOD1(OnDamageRect, void(const gfx::Rect& damaged_region)); + MOCK_METHOD1(DispatchEvent, void(ui::Event* event)); + MOCK_METHOD0(OnCloseRequest, void()); + MOCK_METHOD0(OnClosed, void()); + MOCK_METHOD1(OnWindowStateChanged, void(ui::PlatformWindowState new_state)); + MOCK_METHOD0(OnLostCapture, void()); + MOCK_METHOD1(OnAcceleratedWidgetAvailable, + void(gfx::AcceleratedWidget widget)); + MOCK_METHOD0(OnAcceleratedWidgetDestroyed, void()); + MOCK_METHOD1(OnActivationChanged, void(bool active)); + + private: + DISALLOW_COPY_AND_ASSIGN(MockPlatformWindowDelegate); +}; + +} // namespace + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + base::FuzzedDataProvider data_provider(data, size); + + std::vector<uint32_t> known_fourccs{ + DRM_FORMAT_R8, DRM_FORMAT_GR88, DRM_FORMAT_ABGR8888, + DRM_FORMAT_XBGR8888, DRM_FORMAT_ARGB8888, DRM_FORMAT_XRGB8888, + DRM_FORMAT_XRGB2101010, DRM_FORMAT_XBGR2101010, DRM_FORMAT_RGB565, + DRM_FORMAT_UYVY, DRM_FORMAT_NV12, DRM_FORMAT_YVU420}; + + base::MessageLoopForUI message_loop; + + MockPlatformWindowDelegate delegate; + std::unique_ptr<ui::WaylandConnection> connection = + std::make_unique<ui::WaylandConnection>(); + std::unique_ptr<ui::WaylandWindow> window = + std::make_unique<ui::WaylandWindow>(&delegate, connection.get()); + gfx::AcceleratedWidget widget = gfx::kNullAcceleratedWidget; + + wl::TestWaylandServerThread server; + CHECK(server.Start(6)); + CHECK(connection->Initialize()); + + EXPECT_CALL(delegate, OnAcceleratedWidgetAvailable(_)) + .WillOnce(testing::SaveArg<0>(&widget)); + ui::PlatformWindowInitProperties properties; + properties.bounds = gfx::Rect(0, 0, 800, 600); + properties.type = ui::PlatformWindowType::kWindow; + CHECK(window->Initialize(std::move(properties))); + CHECK_NE(widget, gfx::kNullAcceleratedWidget); + + base::RunLoop().RunUntilIdle(); + server.Pause(); + + base::FilePath temp_path; + EXPECT_TRUE(base::CreateTemporaryFile(&temp_path)); + base::File temp(temp_path, + base::File::FLAG_WRITE | base::File::FLAG_CREATE_ALWAYS); + + // 10K screens are reality these days. + const uint32_t kWidth = data_provider.ConsumeIntegralInRange(1U, 20000U); + const uint32_t kHeight = data_provider.ConsumeIntegralInRange(1U, 20000U); + // The buffer manager opens a file descriptor for each plane so |plane_count| + // cannot be really large. Technically, the maximum is |ulimit| minus number + // of file descriptors opened by this process already (which is 17 at the time + // of writing) but there is little sense in having more than a few planes in a + // real system so here is a hard limit of 500. + const uint32_t kPlaneCount = data_provider.ConsumeIntegralInRange(1U, 500U); + const uint32_t kFormat = known_fourccs[data_provider.ConsumeIntegralInRange( + 0UL, known_fourccs.size() - 1)]; + + std::vector<uint32_t> strides(kPlaneCount); + std::vector<uint32_t> offsets(kPlaneCount); + std::vector<uint64_t> modifiers(kPlaneCount); + for (uint32_t i = 0; i < kPlaneCount; ++i) { + strides[i] = data_provider.ConsumeIntegralInRange(1U, UINT_MAX); + offsets[i] = data_provider.ConsumeIntegralInRange(0U, UINT_MAX); + modifiers[i] = + data_provider.ConsumeIntegralInRange(uint64_t(0), UINT64_MAX); + } + + const uint32_t kBufferId = 1; + + EXPECT_CALL(*server.zwp_linux_dmabuf_v1(), CreateParams(_, _, _)); + + connection->CreateZwpLinuxDmabuf(std::move(temp), kWidth, kHeight, strides, + offsets, kFormat, modifiers, kPlaneCount, + kBufferId); + + Sync(&server); + Sync(&server); + + connection->DestroyZwpLinuxDmabuf(kBufferId); + + Sync(&server); + + return 0; +}
diff --git a/ui/ozone/platform/wayland/wayland_buffer_manager.cc b/ui/ozone/platform/wayland/wayland_buffer_manager.cc index 8f165e04..213605e1 100644 --- a/ui/ozone/platform/wayland/wayland_buffer_manager.cc +++ b/ui/ozone/platform/wayland/wayland_buffer_manager.cc
@@ -54,7 +54,8 @@ WaylandConnection* connection) : zwp_linux_dmabuf_(zwp_linux_dmabuf), connection_(connection) { static const zwp_linux_dmabuf_v1_listener dmabuf_listener = { - &WaylandBufferManager::Format, &WaylandBufferManager::Modifiers, + &WaylandBufferManager::Format, + &WaylandBufferManager::Modifiers, }; zwp_linux_dmabuf_v1_add_listener(zwp_linux_dmabuf_.get(), &dmabuf_listener, this); @@ -87,23 +88,22 @@ modifiers, planes_count, buffer_id)) { // base::File::Close() has an assertion that checks if blocking operations // are allowed. Thus, manually close the fd here. - base::ScopedFD fd(file.TakePlatformFile()); - fd.reset(); + base::ScopedFD deleter(file.TakePlatformFile()); return false; } + base::ScopedFD fd(file.TakePlatformFile()); + // Store |params| connected to |buffer_id| to track buffer creation and // identify, which buffer a client wants to use. DCHECK(zwp_linux_dmabuf_); struct zwp_linux_buffer_params_v1* params = zwp_linux_dmabuf_v1_create_params(zwp_linux_dmabuf_.get()); - std::unique_ptr<Buffer> buffer = - std::make_unique<Buffer>(buffer_id, params, gfx::Size(width, height)); buffers_.insert(std::pair<uint32_t, std::unique_ptr<Buffer>>( - buffer_id, std::move(buffer))); + buffer_id, + std::make_unique<Buffer>(buffer_id, params, gfx::Size(width, height)))); - uint32_t fd = file.TakePlatformFile(); for (size_t i = 0; i < planes_count; i++) { uint32_t modifier_lo = 0; uint32_t modifier_hi = 0; @@ -114,8 +114,9 @@ DCHECK_EQ(planes_count, 1u) << "Invalid modifier may be passed only in " "case of single plane format being used"; } - zwp_linux_buffer_params_v1_add(params, fd, i /* plane id */, offsets[i], - strides[i], modifier_hi, modifier_lo); + zwp_linux_buffer_params_v1_add(params, fd.get(), i /* plane id */, + offsets[i], strides[i], modifier_hi, + modifier_lo); } zwp_linux_buffer_params_v1_add_listener(params, ¶ms_listener, this); zwp_linux_buffer_params_v1_create(params, width, height, format, 0);
diff --git a/ui/ozone/platform/wayland/wayland_connection.cc b/ui/ozone/platform/wayland/wayland_connection.cc index e963c49..1a7882b 100644 --- a/ui/ozone/platform/wayland/wayland_connection.cc +++ b/ui/ozone/platform/wayland/wayland_connection.cc
@@ -52,7 +52,8 @@ bool WaylandConnection::Initialize() { static const wl_registry_listener registry_listener = { - &WaylandConnection::Global, &WaylandConnection::GlobalRemove, + &WaylandConnection::Global, + &WaylandConnection::GlobalRemove, }; display_.reset(wl_display_connect(nullptr)); @@ -364,7 +365,8 @@ const char* interface, uint32_t version) { static const wl_seat_listener seat_listener = { - &WaylandConnection::Capabilities, &WaylandConnection::Name, + &WaylandConnection::Capabilities, + &WaylandConnection::Name, }; static const xdg_shell_listener shell_listener = { &WaylandConnection::Ping,
diff --git a/ui/views/BUILD.gn b/ui/views/BUILD.gn index 35e0140e..e38d23a 100644 --- a/ui/views/BUILD.gn +++ b/ui/views/BUILD.gn
@@ -131,7 +131,6 @@ "controls/menu/menu_image_util.h", "controls/menu/menu_insertion_delegate_win.h", "controls/menu/menu_item_view.h", - "controls/menu/menu_listener.h", "controls/menu/menu_model_adapter.h", "controls/menu/menu_runner.h", "controls/menu/menu_runner_handler.h", @@ -338,7 +337,6 @@ "controls/menu/menu_host_root_view.cc", "controls/menu/menu_image_util.cc", "controls/menu/menu_item_view.cc", - "controls/menu/menu_listener.cc", "controls/menu/menu_model_adapter.cc", "controls/menu/menu_runner.cc", "controls/menu/menu_runner_impl.cc",
diff --git a/ui/views/controls/menu/menu_listener.cc b/ui/views/controls/menu/menu_listener.cc deleted file mode 100644 index 4b86833..0000000 --- a/ui/views/controls/menu/menu_listener.cc +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_listener.h" - -namespace views { - -MenuListener::MenuListener() { -} - -MenuListener::~MenuListener() { -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_listener.h b/ui/views/controls/menu/menu_listener.h deleted file mode 100644 index 19cfb68..0000000 --- a/ui/views/controls/menu/menu_listener.h +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_LISTENER_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_LISTENER_H_ - -#include "ui/views/views_export.h" - -namespace views { - -// An interface for clients that want a notification when a menu is opened. -class VIEWS_EXPORT MenuListener { - public: - MenuListener(); - - // This will be called after the menu has actually opened. - virtual void OnMenuOpened() = 0; - - protected: - virtual ~MenuListener(); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_LISTENER_H_