diff --git a/.gitignore b/.gitignore index 08a05ccf..f9e53d7 100644 --- a/.gitignore +++ b/.gitignore
@@ -131,6 +131,7 @@ /chrome/test/chromeos/autotest/files/client/deps/perf_data_dep/test_src/ /chrome/test/chromeos/autotest/files/client/deps/pyauto_dep/test_src/ /chrome/test/chromeos/autotest/files/client/deps/telemetry_dep/test_src/ +/chrome/test/data/autofill/captured_sites /chrome/test/data/extensions/api_test/permissions/nacl_enabled/bin /chrome/test/data/firefox2_profile/searchplugins /chrome/test/data/firefox2_searchplugins
diff --git a/AUTHORS b/AUTHORS index d07d2e39..e7b6183 100644 --- a/AUTHORS +++ b/AUTHORS
@@ -51,7 +51,7 @@ Alexis Menard <alexis.menard@intel.com> Alfredo Hernandez <ahernandez.miralles@gmail.com> Ali Vathi <ali.akbar@gmail.com> -Allan Sandfeld Jensen <allan.jensen@theqtcompany.com> +Allan Sandfeld Jensen <allan.jensen@qt.io> Alper Çakan <alpercakan98@gmail.com> Ambarish Rapte <ambarish.r@samsung.com> Amey Jahagirdar <jahagird@amazon.com>
diff --git a/BUILD.gn b/BUILD.gn index b722743..99b74571 100644 --- a/BUILD.gn +++ b/BUILD.gn
@@ -940,13 +940,14 @@ group("webdriver_wpt_tests") { testonly = true data = [ - "//third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/webdriver/", + "//third_party/blink/tools/blinkpy/", "//third_party/blink/web_tests/external/wpt/webdriver/", "//chrome/test/chromedriver/test/run_webdriver_tests.py", "//chrome/test/chromedriver/server/server.py", "//chrome/test/chromedriver/util.py", "//chrome/test/chromedriver/chrome_paths.py", "//testing/xvfb.py", + "//third_party/pywebsocket/src/mod_pywebsocket/", ] data_deps = [ "//chrome:chrome",
diff --git a/DEPS b/DEPS index 834e405..979027ee 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': '7a74c7cb6da0809e2ea2121932b889844e249157', + 'skia_revision': '28bafb01c90c0ba1a281f322325f542f0e97e4b6', # 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': 'ad16165cca87b0bdaf39feb026844252fd3c724c', + 'v8_revision': 'b23ca2a5814cc9e54d7fd840a0c3a2c5161ecc77', # 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. @@ -189,7 +189,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': '309c28a6328bf11bb2863afab0b28691a783941f', + 'catapult_revision': '798bb03c8950ab6a87d5e9c9a1c0f1d101d2d335', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -253,7 +253,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': '108bcbd5c9b83c545e6466d787035527a35f909f', + 'dawn_revision': 'e1f0d4e639f64d598de410e3b03813427ceaf5c5', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -274,6 +274,10 @@ # the commit queue can handle CLs rolling libunwind # and whatever else without interference from each other. "libunwind_revision": "69d9b84cca8354117b9fe9705a4430d789ee599b", + # Three lines of non-changing comments so that + # the commit queue can handle CLs rolling ios_webkit + # and whatever else without interference from each other. + "ios_webkit_revision": "59e9de61b7b36507836fa8b098e8839d7d995b13", } # Only these hosts are allowed for dependencies in this DEPS file. @@ -452,7 +456,8 @@ }, 'src/ios/third_party/webkit/src': { - 'url': Var('chromium_git') + '/external/github.com/WebKit/webkit.git' + '@' + 'c56dd8a91c62afcfd0de4a5fe6dbb46484ea1fb5', + 'url': Var('chromium_git') + '/external/github.com/WebKit/webkit.git' + + '@' + Var('ios_webkit_revision'), 'condition': 'checkout_ios and checkout_ios_webkit' }, @@ -732,7 +737,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'd70d87c663f37683f805eb5d8ffe5679d48acb72', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '685ea8d6f03c3ad6d835efe7f4a835a8f4702458', 'condition': 'checkout_linux', }, @@ -1092,7 +1097,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'ee4db4b3e9e39c2f948ff199a9e7f98ed0767256', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '5e577f20fc7c1a2cc8b011e200db79bac2529e72', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + 'ac0d98b5cee6c024b0cffeb4f8f45b6fc5ccdb78', @@ -1255,7 +1260,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'a0f51b2e123f39c9ff12e621b0b47dd28dd64424', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '397c06fe9db8512e18ffa401ead1dd7cf4e725d0', + Var('webrtc_git') + '/src.git' + '@' + '106d92d4c930088d2e7ae6ca74fa863a5edb9db8', 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -1296,7 +1301,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@211efe6b022c41e74d7c740e11e635eee36e861d', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@0613361e6c4ff5f3563633ea70dc0bb92aa6bb0f', 'condition': 'checkout_src_internal', },
diff --git a/android_webview/BUILD.gn b/android_webview/BUILD.gn index fd156f2..b18cac9f 100644 --- a/android_webview/BUILD.gn +++ b/android_webview/BUILD.gn
@@ -664,6 +664,8 @@ "browser/net_helpers.h", "browser/net_network_service/android_stream_reader_url_loader.cc", "browser/net_network_service/android_stream_reader_url_loader.h", + "browser/net_network_service/aw_cookie_manager_wrapper.cc", + "browser/net_network_service/aw_cookie_manager_wrapper.h", "browser/parent_compositor_draw_constraints.cc", "browser/parent_compositor_draw_constraints.h", "browser/parent_output_surface.cc",
diff --git a/android_webview/browser/aw_content_browser_client.cc b/android_webview/browser/aw_content_browser_client.cc index 8ea23ec..3502eaa 100644 --- a/android_webview/browser/aw_content_browser_client.cc +++ b/android_webview/browser/aw_content_browser_client.cc
@@ -28,8 +28,10 @@ #include "android_webview/browser/aw_url_checker_delegate_impl.h" #include "android_webview/browser/aw_url_loader_throttle.h" #include "android_webview/browser/aw_web_contents_view_delegate.h" +#include "android_webview/browser/cookie_manager.h" #include "android_webview/browser/net/aw_url_request_context_getter.h" #include "android_webview/browser/net_helpers.h" +#include "android_webview/browser/net_network_service/aw_cookie_manager_wrapper.h" #include "android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.h" #include "android_webview/browser/tracing/aw_tracing_delegate.h" #include "android_webview/common/aw_content_client.h" @@ -89,6 +91,7 @@ #include "services/network/network_service.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/resource_request.h" +#include "services/network/public/mojom/cookie_manager.mojom-forward.h" #include "services/service_manager/public/cpp/binder_registry.h" #include "storage/browser/quota/quota_settings.h" #include "ui/base/resource/resource_bundle.h" @@ -213,6 +216,21 @@ false /*safebrowsing_hit*/); } +void PassCookieManagerToCookieManagerWrapper( + const network::mojom::NetworkContextPtr& network_context) { + // Get the CookieManager from the NetworkContext. + network::mojom::CookieManagerPtrInfo cookie_manager_info; + network_context->GetCookieManager(mojo::MakeRequest(&cookie_manager_info)); + + // Pass the CookieManagerPtrInfo to AwCookieManagerWrapper, so it can use that + // CookieManager to implement its APIs on the correct thread. + CookieManager* aw_cookie_manager = CookieManager::GetInstance(); + aw_cookie_manager->GetCookieStoreTaskRunner()->PostTask( + FROM_HERE, base::BindOnce(&CookieManager::SetMojoCookieManager, + base::Unretained(aw_cookie_manager), + std::move(cookie_manager_info))); +} + } // anonymous namespace std::string GetProduct() { @@ -287,6 +305,10 @@ // Quic is not currently supported in WebView (http://crbug.com/763187). content::GetNetworkService()->DisableQuic(); + // Pass a CookieManager to the code supporting AwCookieManager.java (i.e., the + // Cookies APIs). + PassCookieManagerToCookieManagerWrapper(network_context); + return network_context; }
diff --git a/android_webview/browser/cookie_manager.cc b/android_webview/browser/cookie_manager.cc index deac5d3..cd5de81 100644 --- a/android_webview/browser/cookie_manager.cc +++ b/android_webview/browser/cookie_manager.cc
@@ -12,10 +12,12 @@ #include "android_webview/browser/aw_cookie_access_policy.h" #include "android_webview/browser/net/init_native_callback.h" +#include "android_webview/browser/net_network_service/aw_cookie_manager_wrapper.h" #include "base/android/jni_string.h" #include "base/android/path_utils.h" #include "base/bind.h" #include "base/bind_helpers.h" +#include "base/feature_list.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/lazy_instance.h" @@ -38,6 +40,9 @@ #include "net/cookies/parsed_cookie.h" #include "net/extras/sqlite/cookie_crypto_delegate.h" #include "net/url_request/url_request_context.h" +#include "services/network/network_service.h" +#include "services/network/public/cpp/features.h" +#include "services/network/public/mojom/cookie_manager.mojom-forward.h" #include "url/url_constants.h" using base::FilePath; @@ -243,6 +248,21 @@ return cookie_store_.get(); } +AwCookieManagerWrapper* CookieManager::GetCookieManagerWrapper() { + DCHECK(base::FeatureList::IsEnabled(network::features::kNetworkService)); + DCHECK(cookie_store_task_runner_->RunsTasksInCurrentSequence()); + if (!cookie_manager_wrapper_) { + cookie_manager_wrapper_ = std::make_unique<AwCookieManagerWrapper>(); + } + return cookie_manager_wrapper_.get(); +} + +void CookieManager::SetMojoCookieManager( + network::mojom::CookieManagerPtrInfo cookie_manager_info) { + GetCookieManagerWrapper()->SetMojoCookieManager( + std::move(cookie_manager_info)); +} + void CookieManager::SetShouldAcceptCookies(bool accept) { AwCookieAccessPolicy::GetInstance()->SetShouldAcceptCookies(accept); } @@ -313,10 +333,17 @@ options.set_same_site_cookie_mode( net::CookieOptions::SameSiteCookieMode::INCLUDE_STRICT_AND_LAX); - GetCookieStore()->GetCookieListWithOptionsAsync( - host, options, - base::BindOnce(&CookieManager::GetCookieListCompleted, - base::Unretained(this), std::move(complete), result)); + if (base::FeatureList::IsEnabled(network::features::kNetworkService)) { + GetCookieManagerWrapper()->GetCookieList( + host, options, + base::BindOnce(&CookieManager::GetCookieListCompleted2, + base::Unretained(this), std::move(complete), result)); + } else { + GetCookieStore()->GetCookieListWithOptionsAsync( + host, options, + base::BindOnce(&CookieManager::GetCookieListCompleted, + base::Unretained(this), std::move(complete), result)); + } } void CookieManager::GetCookieListCompleted( @@ -328,6 +355,13 @@ std::move(complete).Run(); } +void CookieManager::GetCookieListCompleted2(base::OnceClosure complete, + net::CookieList* result, + const net::CookieList& value) { + *result = value; + std::move(complete).Run(); +} + void CookieManager::RemoveSessionCookies( std::unique_ptr<BoolCookieCallbackHolder> callback_holder) { base::RepeatingCallback<void(bool)> callback =
diff --git a/android_webview/browser/cookie_manager.h b/android_webview/browser/cookie_manager.h index 72ca699..5e4a2fbe 100644 --- a/android_webview/browser/cookie_manager.h +++ b/android_webview/browser/cookie_manager.h
@@ -11,6 +11,7 @@ #include "base/lazy_instance.h" #include "base/threading/thread.h" #include "net/cookies/canonical_cookie.h" +#include "services/network/public/mojom/cookie_manager.mojom-forward.h" class GURL; @@ -24,6 +25,7 @@ namespace android_webview { +class AwCookieManagerWrapper; class BoolCookieCallbackHolder; // CookieManager creates and owns Webview's CookieStore, in addition to handling @@ -41,6 +43,11 @@ // Returns the CookieStore, creating it if necessary. This must only be called // on the CookieStore TaskRunner. net::CookieStore* GetCookieStore(); + // Passes a |cookie_manager_info| to |cookie_manager_wrapper_|. This may + // create an AwCookieManagerWrapper to assign to |cookie_manager_wrapper_|, if + // none already exists. + void SetMojoCookieManager( + network::mojom::CookieManagerPtrInfo cookie_manager_info); void SetShouldAcceptCookies(bool accept); bool GetShouldAcceptCookies(); @@ -65,6 +72,12 @@ CookieManager(); ~CookieManager(); + // Returns an AwCookieManagerWrapper, creating it if necessary. This must only + // be called on the CookieStore TaskRunner. Must only be called when the + // NetworkService is enabled, although this may be called before content layer + // is initialized. + AwCookieManagerWrapper* GetCookieManagerWrapper(); + void ExecCookieTaskSync( base::OnceCallback<void(base::RepeatingCallback<void(bool)>)> task); void ExecCookieTaskSync( @@ -84,6 +97,9 @@ net::CookieList* result, const net::CookieList& value, const net::CookieStatusList& excluded_cookies); + void GetCookieListCompleted2(base::OnceClosure complete, + net::CookieList* result, + const net::CookieList& value); void RemoveSessionCookiesHelper(base::RepeatingCallback<void(bool)> callback); void RemoveAllCookiesHelper(base::RepeatingCallback<void(bool)> callback); @@ -112,6 +128,7 @@ scoped_refptr<base::SingleThreadTaskRunner> cookie_store_task_runner_; std::unique_ptr<net::CookieStore> cookie_store_; + std::unique_ptr<AwCookieManagerWrapper> cookie_manager_wrapper_; DISALLOW_COPY_AND_ASSIGN(CookieManager); };
diff --git a/android_webview/browser/net_network_service/aw_cookie_manager_wrapper.cc b/android_webview/browser/net_network_service/aw_cookie_manager_wrapper.cc new file mode 100644 index 0000000..3328c13 --- /dev/null +++ b/android_webview/browser/net_network_service/aw_cookie_manager_wrapper.cc
@@ -0,0 +1,33 @@ +// 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 "android_webview/browser/net_network_service/aw_cookie_manager_wrapper.h" + +#include "base/feature_list.h" +#include "services/network/public/cpp/features.h" + +namespace android_webview { + +AwCookieManagerWrapper::AwCookieManagerWrapper() { + DCHECK(base::FeatureList::IsEnabled(network::features::kNetworkService)); +} + +AwCookieManagerWrapper::~AwCookieManagerWrapper() {} + +void AwCookieManagerWrapper::SetMojoCookieManager( + network::mojom::CookieManagerPtrInfo cookie_manager_info) { + DCHECK(!cookie_manager_.is_bound()); + cookie_manager_.Bind(std::move(cookie_manager_info)); +} + +void AwCookieManagerWrapper::GetCookieList( + const GURL& url, + const net::CookieOptions& cookie_options, + GetCookieListCallback callback) { + // TODO(ntfschr): handle the case where content layer isn't initialized yet + // (http://crbug.com/902641). + cookie_manager_->GetCookieList(url, cookie_options, std::move(callback)); +} + +} // namespace android_webview
diff --git a/android_webview/browser/net_network_service/aw_cookie_manager_wrapper.h b/android_webview/browser/net_network_service/aw_cookie_manager_wrapper.h new file mode 100644 index 0000000..e1dbd2c --- /dev/null +++ b/android_webview/browser/net_network_service/aw_cookie_manager_wrapper.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. + +#ifndef ANDROID_WEBVIEW_BROWSER_NET_NETWORK_SERVICE_AW_COOKIE_MANAGER_WRAPPER_H_ +#define ANDROID_WEBVIEW_BROWSER_NET_NETWORK_SERVICE_AW_COOKIE_MANAGER_WRAPPER_H_ + +#include "base/callback.h" +#include "net/cookies/cookie_store.h" +#include "services/network/public/mojom/cookie_manager.mojom.h" + +namespace android_webview { + +using GetCookieListCallback = + base::OnceCallback<void(const std::vector<net::CanonicalCookie>&)>; + +// AwCookieManagerWrapper is a thin wrapper around +// network::mojom::CookieManager. This lives on the CookieStore TaskRunner. This +// class's main responsibility is to support the CookieManager APIs before it +// receives a CookieManager from the NetworkContext, at which point it will +// switch to that CookieManager. +class AwCookieManagerWrapper { + public: + AwCookieManagerWrapper(); + ~AwCookieManagerWrapper(); + + // Called when content layer starts up, to pass in a NetworkContextPtr for us + // to use for Cookies APIs. + void SetMojoCookieManager( + network::mojom::CookieManagerPtrInfo cookie_manager_info); + + // Thin wrappers around network::mojom::CookieManager APIs. + // TODO(ntfschr): implement the other APIs we need (http://crbug.com/902641). + void GetCookieList(const GURL& url, + const net::CookieOptions& cookie_options, + GetCookieListCallback callback); + + private: + // A CookieManagerPtr which is cloned from the NetworkContext's + // CookieManagerPtr (but, lives on this thread). + network::mojom::CookieManagerPtr cookie_manager_; + + DISALLOW_COPY_AND_ASSIGN(AwCookieManagerWrapper); +}; + +} // namespace android_webview + +#endif // ANDROID_WEBVIEW_BROWSER_NET_NETWORK_SERVICE_AW_COOKIE_MANAGER_WRAPPER_H_
diff --git a/android_webview/support_library/java/src/org/chromium/support_lib_glue/SupportLibWebViewChromiumFactory.java b/android_webview/support_library/java/src/org/chromium/support_lib_glue/SupportLibWebViewChromiumFactory.java index c58f4dee..d35e8bde 100644 --- a/android_webview/support_library/java/src/org/chromium/support_lib_glue/SupportLibWebViewChromiumFactory.java +++ b/android_webview/support_library/java/src/org/chromium/support_lib_glue/SupportLibWebViewChromiumFactory.java
@@ -64,7 +64,7 @@ Features.WEB_MESSAGE_CALLBACK_ON_MESSAGE, Features.GET_WEB_VIEW_CLIENT, Features.GET_WEB_CHROME_CLIENT, - Features.PROXY_OVERRIDE + Features.DEV_SUFFIX, + Features.PROXY_OVERRIDE, Features.SUPPRESS_ERROR_PAGE + Features.DEV_SUFFIX, Features.GET_WEB_VIEW_RENDERER, Features.WEB_VIEW_RENDERER_TERMINATE,
diff --git a/android_webview/tools/run_cts.py b/android_webview/tools/run_cts.py index 11f26bef..09340623 100755 --- a/android_webview/tools/run_cts.py +++ b/android_webview/tools/run_cts.py
@@ -23,6 +23,7 @@ from devil.android.sdk import version_codes # pylint: disable=import-error from devil.android.tools import script_common # pylint: disable=import-error from devil.utils import cmd_helper # pylint: disable=import-error +from devil.utils import logging_common # pylint: disable=import-error from pylib.utils import test_filter # pylint: disable=import-error # cts test archives for all platforms are stored in this bucket @@ -330,8 +331,10 @@ test_filter.AddFilterOptions(parser) script_common.AddDeviceArguments(parser) + logging_common.AddLoggingArguments(parser) args, test_runner_args = parser.parse_known_args() + logging_common.InitializeLogging(args) devil_chromium.Initialize() devices = script_common.GetDevices(args.devices, args.blacklist_file)
diff --git a/ash/contained_shell/contained_shell_controller.cc b/ash/contained_shell/contained_shell_controller.cc index 03255da..b4bcf99 100644 --- a/ash/contained_shell/contained_shell_controller.cc +++ b/ash/contained_shell/contained_shell_controller.cc
@@ -3,9 +3,11 @@ // found in the LICENSE file. #include "ash/contained_shell/contained_shell_controller.h" +#include "ash/public/cpp/ash_pref_names.h" #include "ash/session/session_controller.h" #include "ash/shell.h" #include "components/account_id/account_id.h" +#include "components/prefs/pref_registry_simple.h" #include <utility> @@ -20,6 +22,13 @@ bindings_.AddBinding(this, std::move(request)); } +// static +void ContainedShellController::RegisterProfilePrefs( + PrefRegistrySimple* registry) { + registry->RegisterBooleanPref(prefs::kContainedShellEnabled, false, + PrefRegistry::PUBLIC); +} + void ContainedShellController::LaunchContainedShell() { contained_shell_client_->LaunchContainedShell(Shell::Get() ->session_controller()
diff --git a/ash/contained_shell/contained_shell_controller.h b/ash/contained_shell/contained_shell_controller.h index 4d379230..fdccbaf 100644 --- a/ash/contained_shell/contained_shell_controller.h +++ b/ash/contained_shell/contained_shell_controller.h
@@ -10,6 +10,8 @@ #include "base/macros.h" #include "mojo/public/cpp/bindings/binding_set.h" +class PrefRegistrySimple; + namespace ash { // ContainedShellController allows a consumer of ash to provide a @@ -22,6 +24,9 @@ ContainedShellController(); ~ContainedShellController() override; + // Register prefs related to the Contained Shell. + static void RegisterProfilePrefs(PrefRegistrySimple* registry); + // Binds the mojom::ContainedShellController interface to this object. void BindRequest(mojom::ContainedShellControllerRequest request);
diff --git a/ash/public/cpp/ash_pref_names.cc b/ash/public/cpp/ash_pref_names.cc index 91f6ee8..483d5d45 100644 --- a/ash/public/cpp/ash_pref_names.cc +++ b/ash/public/cpp/ash_pref_names.cc
@@ -81,6 +81,10 @@ // regardless of the state of a11y features. const char kShouldAlwaysShowAccessibilityMenu[] = "settings.a11y.enable_menu"; +// A boolean pref that stores whether the Contained Shell is enabled. When it +// is, use the contained shell after sign in. +const char kContainedShellEnabled[] = "ash.contained_shell.enabled"; + // A boolean pref storing the enabled status of the Docked Magnifier feature. const char kDockedMagnifierEnabled[] = "ash.docked_magnifier.enabled"; // A double pref storing the scale value of the Docked Magnifier feature by
diff --git a/ash/public/cpp/ash_pref_names.h b/ash/public/cpp/ash_pref_names.h index c1bae25..8378554 100644 --- a/ash/public/cpp/ash_pref_names.h +++ b/ash/public/cpp/ash_pref_names.h
@@ -34,6 +34,8 @@ ASH_PUBLIC_EXPORT extern const char kAccessibilityDictationEnabled[]; ASH_PUBLIC_EXPORT extern const char kShouldAlwaysShowAccessibilityMenu[]; +ASH_PUBLIC_EXPORT extern const char kContainedShellEnabled[]; + ASH_PUBLIC_EXPORT extern const char kDockedMagnifierEnabled[]; ASH_PUBLIC_EXPORT extern const char kDockedMagnifierScale[]; ASH_PUBLIC_EXPORT extern const char
diff --git a/ash/shelf/shelf_app_button.cc b/ash/shelf/shelf_app_button.cc index d402b10..29f04bef 100644 --- a/ash/shelf/shelf_app_button.cc +++ b/ash/shelf/shelf_app_button.cc
@@ -12,7 +12,6 @@ #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_constants.h" #include "ash/shelf/shelf_view.h" -#include "ash/system/tray/tray_popup_utils.h" #include "base/bind.h" #include "base/metrics/histogram_macros.h" #include "base/stl_util.h" @@ -332,8 +331,6 @@ notification_indicator_->SetVisible(false); AddChildView(notification_indicator_); } - - SetFocusPainter(TrayPopupUtils::CreateFocusPainter()); } ShelfAppButton::~ShelfAppButton() {
diff --git a/ash/shelf/shelf_button.cc b/ash/shelf/shelf_button.cc index 5427a844..0c8527a 100644 --- a/ash/shelf/shelf_button.cc +++ b/ash/shelf/shelf_button.cc
@@ -7,6 +7,7 @@ #include "ash/shelf/ink_drop_button_listener.h" #include "ash/shelf/shelf_constants.h" #include "ash/shelf/shelf_view.h" +#include "ash/system/tray/tray_popup_utils.h" #include "ui/accessibility/ax_node_data.h" #include "ui/views/animation/ink_drop_impl.h" @@ -20,6 +21,7 @@ set_ink_drop_visible_opacity(kShelfInkDropVisibleOpacity); SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY); SetInkDropMode(InkDropMode::ON_NO_GESTURE_HANDLER); + SetFocusPainter(TrayPopupUtils::CreateFocusPainter()); } ShelfButton::~ShelfButton() = default; @@ -52,6 +54,13 @@ return true; } +// Do not remove this function to avoid unnecessary ChromeVox announcement +// triggered by Button::GetAccessibleNodeData. (See https://crbug.com/932200) +void ShelfButton::GetAccessibleNodeData(ui::AXNodeData* node_data) { + node_data->role = ax::mojom::Role::kButton; + node_data->SetName(GetAccessibleName()); +} + bool ShelfButton::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const { // Copy the proper tooltip text, but return false because we do not want to
diff --git a/ash/shelf/shelf_button.h b/ash/shelf/shelf_button.h index e2d56d8..fd1963b 100644 --- a/ash/shelf/shelf_button.h +++ b/ash/shelf/shelf_button.h
@@ -23,6 +23,7 @@ void OnMouseReleased(const ui::MouseEvent& event) override; void OnMouseCaptureLost() override; bool OnMouseDragged(const ui::MouseEvent& event) override; + void GetAccessibleNodeData(ui::AXNodeData* node_data) override; bool GetTooltipText(const gfx::Point& p, base::string16* tooltip) const override;
diff --git a/ash/shell.cc b/ash/shell.cc index 7c61054..c4d98df1 100644 --- a/ash/shell.cc +++ b/ash/shell.cc
@@ -248,6 +248,7 @@ AccessibilityController::RegisterProfilePrefs(registry, for_test); AssistantController::RegisterProfilePrefs(registry); BluetoothPowerController::RegisterProfilePrefs(registry); + ContainedShellController::RegisterProfilePrefs(registry); DockedMagnifierController::RegisterProfilePrefs(registry, for_test); LoginScreenController::RegisterProfilePrefs(registry, for_test); LogoutButtonTray::RegisterProfilePrefs(registry);
diff --git a/ash/wm/overview/overview_session_unittest.cc b/ash/wm/overview/overview_session_unittest.cc index 54aa268..95d91f4 100644 --- a/ash/wm/overview/overview_session_unittest.cc +++ b/ash/wm/overview/overview_session_unittest.cc
@@ -130,7 +130,7 @@ void SetUp() override { AshTestBase::SetUp(); - + Shell::Get()->aura_env()->set_throttle_input_on_resize_for_testing(false); shelf_view_test_api_ = std::make_unique<ShelfViewTestAPI>( GetPrimaryShelf()->GetShelfViewForTesting()); shelf_view_test_api_->SetAnimationDuration(1);
diff --git a/ash/ws/window_service_delegate_impl_unittest.cc b/ash/ws/window_service_delegate_impl_unittest.cc index 54c1f10d..78c88b3 100644 --- a/ash/ws/window_service_delegate_impl_unittest.cc +++ b/ash/ws/window_service_delegate_impl_unittest.cc
@@ -92,6 +92,7 @@ // AshTestBase: void SetUp() override { AshTestBase::SetUp(); + Shell::Get()->aura_env()->set_throttle_input_on_resize_for_testing(false); NonClientFrameViewAsh::use_empty_minimum_size_for_test_ = true; top_level_ = CreateTestWindow(gfx::Rect(100, 100, 100, 100)); ASSERT_TRUE(top_level_);
diff --git a/base/BUILD.gn b/base/BUILD.gn index 639480e..59c33fc 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -1954,7 +1954,8 @@ buildflag_header("anchor_functions_buildflags") { header = "anchor_functions_buildflags.h" header_dir = "base/android/library_loader" - _supports_code_ordering = current_cpu == "arm" || current_cpu == "arm64" + _supports_code_ordering = + is_android && (current_cpu == "arm" || current_cpu == "arm64") flags = [ "USE_LLD=$use_lld",
diff --git a/base/allocator/allocator_interception_mac.mm b/base/allocator/allocator_interception_mac.mm index f0d7200..0f5f8608 100644 --- a/base/allocator/allocator_interception_mac.mm +++ b/base/allocator/allocator_interception_mac.mm
@@ -500,7 +500,7 @@ base::TimeDelta next_delay = delay * 2; SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&ShimNewMallocZonesAndReschedule, end_time, next_delay), + base::BindOnce(&ShimNewMallocZonesAndReschedule, end_time, next_delay), delay); }
diff --git a/base/android/application_status_listener_unittest.cc b/base/android/application_status_listener_unittest.cc index f904dd0..31e1cde3 100644 --- a/base/android/application_status_listener_unittest.cc +++ b/base/android/application_status_listener_unittest.cc
@@ -51,8 +51,8 @@ // Start the thread and tell it to register for events. thread_.Start(); thread_.task_runner()->PostTask( - FROM_HERE, base::Bind(&MultiThreadedTest::RegisterThreadForEvents, - base::Unretained(this))); + FROM_HERE, base::BindOnce(&MultiThreadedTest::RegisterThreadForEvents, + base::Unretained(this))); // Wait for its completion. event_.Wait();
diff --git a/base/message_loop/message_loop_io_posix_unittest.cc b/base/message_loop/message_loop_io_posix_unittest.cc index 4dd5f28..d988600 100644 --- a/base/message_loop/message_loop_io_posix_unittest.cc +++ b/base/message_loop/message_loop_io_posix_unittest.cc
@@ -4,6 +4,8 @@ #include "base/message_loop/message_loop.h" +#include <sys/socket.h> + #include "base/bind.h" #include "base/compiler_specific.h" #include "base/files/file_util.h" @@ -98,7 +100,7 @@ write_closure_ = std::move(write_closure); } - // base:MessagePumpFuchsia::Watcher interface. + // base::WatchableIOMessagePumpPosix::FdWatcher: void OnFileCanReadWithoutBlocking(int fd) override { // Empty the pipe buffer to reset the event. Otherwise libevent // implementation of MessageLoop may call the event handler again even if @@ -177,6 +179,151 @@ RunLoop().Run(); } +// A watcher that owns its controller and will either delete itself or stop +// watching the FD after observing the specified event type. +class ReaderWriterHandler : public MessagePumpForIO::FdWatcher { + public: + enum Action { + // Just call StopWatchingFileDescriptor(). + kStopWatching, + // Delete |this| and its owned controller. + kDelete, + }; + enum ActWhen { + // Take the Action after observing a read event. + kOnReadEvent, + // Take the Action after observing a write event. + kOnWriteEvent, + }; + + ReaderWriterHandler(Action action, + ActWhen when, + OnceClosure idle_quit_closure) + : action_(action), + when_(when), + controller_(FROM_HERE), + idle_quit_closure_(std::move(idle_quit_closure)) {} + + // base::WatchableIOMessagePumpPosix::FdWatcher: + void OnFileCanReadWithoutBlocking(int fd) override { + if (when_ == kOnReadEvent) { + DoAction(); + } else { + char c; + EXPECT_EQ(1, HANDLE_EINTR(read(fd, &c, 1))); + } + } + + void OnFileCanWriteWithoutBlocking(int fd) override { + if (when_ == kOnWriteEvent) { + DoAction(); + } else { + char c = '\0'; + EXPECT_EQ(1, HANDLE_EINTR(write(fd, &c, 1))); + } + } + + MessagePumpForIO::FdWatchController* controller() { return &controller_; } + + private: + void DoAction() { + OnceClosure idle_quit_closure = std::move(idle_quit_closure_); + if (action_ == kDelete) { + delete this; + } else if (action_ == kStopWatching) { + controller_.StopWatchingFileDescriptor(); + } + std::move(idle_quit_closure).Run(); + } + + Action action_; + ActWhen when_; + MessagePumpForIO::FdWatchController controller_; + OnceClosure idle_quit_closure_; + + DISALLOW_COPY_AND_ASSIGN(ReaderWriterHandler); +}; + +class MessageLoopForIoPosixReadAndWriteTest + : public testing::TestWithParam<ReaderWriterHandler::Action> { + protected: + bool CreateSocketPair(ScopedFD* one, ScopedFD* two) { + int fds[2]; + if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == -1) + return false; + one->reset(fds[0]); + two->reset(fds[1]); + return true; + } +}; + +INSTANTIATE_TEST_SUITE_P(StopWatchingOrDelete, + MessageLoopForIoPosixReadAndWriteTest, + testing::Values(ReaderWriterHandler::kStopWatching, + ReaderWriterHandler::kDelete)); + +// Test deleting or stopping watch after a read event for a watcher that is +// registered for both read and write. +TEST_P(MessageLoopForIoPosixReadAndWriteTest, AfterRead) { + MessageLoopForIO message_loop; + ScopedFD one, two; + ASSERT_TRUE(CreateSocketPair(&one, &two)); + + RunLoop run_loop; + ReaderWriterHandler* handler = + new ReaderWriterHandler(GetParam(), ReaderWriterHandler::kOnReadEvent, + run_loop.QuitWhenIdleClosure()); + + // Trigger a read event on |one| by writing to |two|. + char c = '\0'; + EXPECT_EQ(1, HANDLE_EINTR(write(two.get(), &c, 1))); + + // The triggered read will cause the watcher action to run. |one| would + // also be immediately available for writing, so this should not cause a + // use-after-free on the |handler|. + MessageLoopCurrentForIO::Get()->WatchFileDescriptor( + one.get(), true, MessagePumpForIO::WATCH_READ_WRITE, + handler->controller(), handler); + run_loop.Run(); + + if (GetParam() == ReaderWriterHandler::kStopWatching) { + delete handler; + } +} + +// Test deleting or stopping watch after a write event for a watcher that is +// registered for both read and write. +TEST_P(MessageLoopForIoPosixReadAndWriteTest, AfterWrite) { + MessageLoopForIO message_loop; + ScopedFD one, two; + ASSERT_TRUE(CreateSocketPair(&one, &two)); + + RunLoop run_loop; + ReaderWriterHandler* handler = + new ReaderWriterHandler(GetParam(), ReaderWriterHandler::kOnWriteEvent, + run_loop.QuitWhenIdleClosure()); + + // Trigger two read events on |one| by writing to |two|. Because each read + // event only reads one char, |one| will be available for reading again after + // the first read event is handled. + char c = '\0'; + EXPECT_EQ(1, HANDLE_EINTR(write(two.get(), &c, 1))); + EXPECT_EQ(1, HANDLE_EINTR(write(two.get(), &c, 1))); + + // The triggered read and the immediate availability of |one| for writing + // should cause both the read and write watchers to be triggered. The + // |handler| will do its action in response to the write event, which should + // not trigger a use-after-free for the second read that was queued. + MessageLoopCurrentForIO::Get()->WatchFileDescriptor( + one.get(), true, MessagePumpForIO::WATCH_READ_WRITE, + handler->controller(), handler); + run_loop.Run(); + + if (GetParam() == ReaderWriterHandler::kStopWatching) { + delete handler; + } +} + // Verify that basic readable notification works. TEST_F(MessageLoopForIoPosixTest, WatchReadable) { MessageLoopForIO message_loop;
diff --git a/base/task/sequence_manager/sequence_manager_impl_unittest.cc b/base/task/sequence_manager/sequence_manager_impl_unittest.cc index 795ce042..3664f44 100644 --- a/base/task/sequence_manager/sequence_manager_impl_unittest.cc +++ b/base/task/sequence_manager/sequence_manager_impl_unittest.cc
@@ -66,7 +66,6 @@ namespace sequence_manager_impl_unittest { enum class TestType { - kCustom, kMockTaskRunner, kMessageLoop, kMessagePump, @@ -80,8 +79,6 @@ return "kMessagePump"; case TestType::kMessageLoop: return "kMessageLoop"; - case TestType::kCustom: - return "kCustom"; } } @@ -113,6 +110,29 @@ virtual void RunDoWorkOnce() = 0; virtual SequenceManagerForTest* sequence_manager() const = 0; virtual void DestroySequenceManager() = 0; + virtual int GetNowTicksCallCount() = 0; +}; + +class CallCountingTickClock : public TickClock { + public: + explicit CallCountingTickClock(RepeatingCallback<TimeTicks()> now_callback) + : now_callback_(std::move(now_callback)) {} + explicit CallCountingTickClock(TickClock* clock) + : CallCountingTickClock( + BindLambdaForTesting([clock]() { return clock->NowTicks(); })) {} + + ~CallCountingTickClock() override = default; + + TimeTicks NowTicks() const override { + ++now_call_count_; + return now_callback_.Run(); + } + + int now_call_count() const { return now_call_count_; } + + private: + const RepeatingCallback<TimeTicks()> now_callback_; + mutable std::atomic<int> now_call_count_{0}; }; class FixtureWithMockTaskRunner final : public Fixture { @@ -120,6 +140,8 @@ FixtureWithMockTaskRunner() : test_task_runner_(MakeRefCounted<TestMockTimeTaskRunner>( TestMockTimeTaskRunner::Type::kBoundToThread)), + call_counting_clock_( + Bind(&TestMockTimeTaskRunner::NowTicks, test_task_runner_)), sequence_manager_(SequenceManagerForTest::Create( nullptr, ThreadTaskRunnerHandle::Get(), @@ -134,7 +156,7 @@ } const TickClock* mock_tick_clock() const override { - return test_task_runner_->GetMockTickClock(); + return &call_counting_clock_; } TimeDelta NextPendingTaskDelay() const override { @@ -168,22 +190,27 @@ void DestroySequenceManager() override { sequence_manager_.reset(); } + int GetNowTicksCallCount() override { + return call_counting_clock_.now_call_count(); + }; + private: scoped_refptr<TestMockTimeTaskRunner> test_task_runner_; + CallCountingTickClock call_counting_clock_; std::unique_ptr<SequenceManagerForTest> sequence_manager_; }; class FixtureWithMockMessagePump : public Fixture { public: - FixtureWithMockMessagePump() { + FixtureWithMockMessagePump() : call_counting_clock_(&mock_clock_) { // 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_), + std::make_unique<ThreadControllerWithMessagePumpImpl>( + std::move(pump), mock_tick_clock()), SequenceManager::Settings{.randomised_sampling_enabled = false}); sequence_manager_->SetDefaultTaskRunner(MakeRefCounted<NullTaskRunner>()); } @@ -192,14 +219,17 @@ mock_clock_.Advance(delta); } - const TickClock* mock_tick_clock() const override { return &mock_clock_; } + const TickClock* mock_tick_clock() const override { + return &call_counting_clock_; + } TimeDelta NextPendingTaskDelay() const override { - return pump_->next_wake_up_time() - mock_clock_.NowTicks(); + return pump_->next_wake_up_time() - mock_tick_clock()->NowTicks(); } void FastForwardBy(TimeDelta delta) override { - pump_->SetAllowTimeToAutoAdvanceUntil(mock_clock_.NowTicks() + delta); + pump_->SetAllowTimeToAutoAdvanceUntil(mock_tick_clock()->NowTicks() + + delta); pump_->SetStopWhenMessagePumpIsIdle(true); RunLoop().Run(); pump_->SetStopWhenMessagePumpIsIdle(false); @@ -210,7 +240,7 @@ pump_->SetStopWhenMessagePumpIsIdle(true); RunLoop().Run(); pump_->SetStopWhenMessagePumpIsIdle(false); - pump_->SetAllowTimeToAutoAdvanceUntil(mock_clock_.NowTicks()); + pump_->SetAllowTimeToAutoAdvanceUntil(mock_tick_clock()->NowTicks()); } void RunDoWorkOnce() override { @@ -228,16 +258,22 @@ sequence_manager_.reset(); } + int GetNowTicksCallCount() override { + return call_counting_clock_.now_call_count(); + }; + private: MockTimeMessagePump* pump_ = nullptr; SimpleTestTickClock mock_clock_; + CallCountingTickClock call_counting_clock_; std::unique_ptr<SequenceManagerForTest> sequence_manager_; }; class FixtureWithMessageLoop : public Fixture { public: FixtureWithMessageLoop() - : auto_reset_global_clock_(&global_clock_, &mock_clock_) { + : call_counting_clock_(&mock_clock_), + auto_reset_global_clock_(&global_clock_, &call_counting_clock_) { // A null clock triggers some assertions. mock_clock_.Advance(TimeDelta::FromMilliseconds(1)); scoped_clock_override_ = @@ -250,7 +286,7 @@ sequence_manager_ = SequenceManagerForTest::Create( message_loop_->GetMessageLoopBase(), ThreadTaskRunnerHandle::Get(), - &mock_clock_, + mock_tick_clock(), SequenceManager::Settings{.randomised_sampling_enabled = false}); } @@ -258,14 +294,17 @@ mock_clock_.Advance(delta); } - const TickClock* mock_tick_clock() const override { return &mock_clock_; } + const TickClock* mock_tick_clock() const override { + return &call_counting_clock_; + } TimeDelta NextPendingTaskDelay() const override { - return pump_->next_wake_up_time() - mock_clock_.NowTicks(); + return pump_->next_wake_up_time() - mock_tick_clock()->NowTicks(); } void FastForwardBy(TimeDelta delta) override { - pump_->SetAllowTimeToAutoAdvanceUntil(mock_clock_.NowTicks() + delta); + pump_->SetAllowTimeToAutoAdvanceUntil(mock_tick_clock()->NowTicks() + + delta); pump_->SetStopWhenMessagePumpIsIdle(true); RunLoop().Run(); pump_->SetStopWhenMessagePumpIsIdle(false); @@ -276,7 +315,7 @@ pump_->SetStopWhenMessagePumpIsIdle(true); RunLoop().Run(); pump_->SetStopWhenMessagePumpIsIdle(false); - pump_->SetAllowTimeToAutoAdvanceUntil(mock_clock_.NowTicks()); + pump_->SetAllowTimeToAutoAdvanceUntil(mock_tick_clock()->NowTicks()); } void RunDoWorkOnce() override { @@ -294,10 +333,15 @@ sequence_manager_.reset(); } + int GetNowTicksCallCount() override { + return call_counting_clock_.now_call_count(); + }; + private: static TickClock* global_clock_; static TimeTicks TicksNowOverride() { return global_clock_->NowTicks(); } SimpleTestTickClock mock_clock_; + CallCountingTickClock call_counting_clock_; AutoReset<TickClock*> auto_reset_global_clock_; std::unique_ptr<base::subtle::ScopedTimeClockOverrides> scoped_clock_override_; @@ -308,11 +352,9 @@ TickClock* FixtureWithMessageLoop::global_clock_; -// SequenceManagerImpl uses TestMockTimeTaskRunner which controls -// both task execution and mock clock. -// TODO(kraynov): Make this class to support all TestTypes. -// It will allow us to re-run tests in various environments before we'll -// eventually move to MessagePump and remove current ThreadControllerImpl. +// Convenience wrapper around the fixtures so that we can use parametrized tests +// instead of templated ones. The latter would be more verbose as all method +// calls to the fixture would need to be like this->method() class SequenceManagerTest : public testing::TestWithParam<TestType>, public Fixture { public: @@ -392,56 +434,14 @@ void DestroySequenceManager() override { fixture_->DestroySequenceManager(); } + int GetNowTicksCallCount() override { + return fixture_->GetNowTicksCallCount(); + } + private: std::unique_ptr<Fixture> fixture_; }; -// TODO(carlscab): Remove once the classes below have been migrated to -// SequenceManagerTest -class SequenceManagerTestBase : public testing::TestWithParam<TestType> { - protected: - void TearDown() override { - // SequenceManager should be deleted before an underlying task runner. - manager_.reset(); - } - - scoped_refptr<TestTaskQueue> CreateTaskQueue( - TaskQueue::Spec spec = TaskQueue::Spec("test")) { - return manager_->CreateTaskQueueWithType<TestTaskQueue>(spec); - } - - std::vector<scoped_refptr<TestTaskQueue>> CreateTaskQueues( - size_t num_queues) { - std::vector<scoped_refptr<TestTaskQueue>> queues; - for (size_t i = 0; i < num_queues; i++) - queues.push_back(CreateTaskQueue()); - return queues; - } - - std::unique_ptr<SequenceManagerForTest> manager_; - - TimeTicks start_time_; - TestTaskTimeObserver test_task_time_observer_; -}; - -// SequenceManagerImpl is being initialized with real MessageLoop -// at cost of less control over a task runner. -// It also runs a version with experimental MessagePump support. -// TODO(kraynov): Generalize as many tests as possible to run it -// in all supported environments. -// TODO(carlscab): Migrate to SequenceManagerTest and remove -class SequenceManagerTestWithCustomInitialization - : public SequenceManagerTestBase { - protected: - void SetUp() override { ASSERT_EQ(GetParam(), TestType::kCustom); } - - const TickClock* GetTickClock() { return &mock_clock_; } - - scoped_refptr<TestTaskQueue> default_task_queue_; - std::unique_ptr<MessageLoop> message_loop_; - SimpleTestTickClock mock_clock_; -}; - INSTANTIATE_TEST_SUITE_P(, SequenceManagerTest, testing::Values(TestType::kMockTaskRunner, @@ -449,10 +449,6 @@ TestType::kMessagePump), GetTestNameSuffix); -INSTANTIATE_TEST_SUITE_P(, - SequenceManagerTestWithCustomInitialization, - testing::Values(TestType::kCustom)); - void PostFromNestedRunloop(scoped_refptr<TestTaskQueue> runner, std::vector<std::pair<OnceClosure, bool>>* tasks) { for (std::pair<OnceClosure, bool>& pair : *tasks) { @@ -487,14 +483,8 @@ DISALLOW_COPY_AND_ASSIGN(TestCountUsesTimeSource); }; -TEST_P(SequenceManagerTestWithCustomInitialization, NowNotCalledIfUnneeded) { - message_loop_.reset(new MessageLoop()); - TestCountUsesTimeSource test_count_uses_time_source; - - manager_ = SequenceManagerForTest::Create( - nullptr, ThreadTaskRunnerHandle::Get(), &test_count_uses_time_source, - SequenceManager::Settings{.randomised_sampling_enabled = false}); - manager_->SetWorkBatchSize(6); +TEST_P(SequenceManagerTest, NowNotCalledIfUnneeded) { + sequence_manager()->SetWorkBatchSize(6); auto queues = CreateTaskQueues(3u); @@ -507,19 +497,14 @@ RunLoop().RunUntilIdle(); - EXPECT_EQ(0, test_count_uses_time_source.now_calls_count()); + EXPECT_EQ(0, GetNowTicksCallCount()); } -TEST_P(SequenceManagerTestWithCustomInitialization, +TEST_P(SequenceManagerTest, NowCalledMinimumNumberOfTimesToComputeTaskDurations) { - message_loop_.reset(new MessageLoop()); - TestCountUsesTimeSource test_count_uses_time_source; - - manager_ = SequenceManagerForTest::Create( - nullptr, ThreadTaskRunnerHandle::Get(), &test_count_uses_time_source, - SequenceManager::Settings{.randomised_sampling_enabled = false}); - manager_->SetWorkBatchSize(6); - manager_->AddTaskTimeObserver(&test_task_time_observer_); + TestTaskTimeObserver time_observer; + sequence_manager()->SetWorkBatchSize(6); + sequence_manager()->AddTaskTimeObserver(&time_observer); auto queues = CreateTaskQueues(3u); @@ -533,19 +518,14 @@ RunLoop().RunUntilIdle(); // Now is called when each task starts running and when its completed. // 6 * 2 = 12 calls. - EXPECT_EQ(12, test_count_uses_time_source.now_calls_count()); + EXPECT_EQ(12, GetNowTicksCallCount()); } -TEST_P(SequenceManagerTestWithCustomInitialization, +TEST_P(SequenceManagerTest, NowCalledMinimumNumberOfTimesToComputeTaskDurationsDelayedFenceAllowed) { - message_loop_.reset(new MessageLoop()); - TestCountUsesTimeSource test_count_uses_time_source; - - manager_ = SequenceManagerForTest::Create( - nullptr, ThreadTaskRunnerHandle::Get(), &test_count_uses_time_source, - SequenceManager::Settings{.randomised_sampling_enabled = false}); - manager_->SetWorkBatchSize(6); - manager_->AddTaskTimeObserver(&test_task_time_observer_); + TestTaskTimeObserver time_observer; + sequence_manager()->SetWorkBatchSize(6); + sequence_manager()->AddTaskTimeObserver(&time_observer); std::vector<scoped_refptr<TestTaskQueue>> queues; for (size_t i = 0; i < 3; i++) { @@ -563,7 +543,7 @@ RunLoop().RunUntilIdle(); // Now is called each time a task is queued, when first task is started // running, and when a task is completed. 6 * 3 = 18 calls. - EXPECT_EQ(18, test_count_uses_time_source.now_calls_count()); + EXPECT_EQ(18, GetNowTicksCallCount()); } void NullTask() {} @@ -3738,7 +3718,7 @@ EXPECT_FALSE(counter.HasReferences()); } -TEST_P(SequenceManagerTestWithCustomInitialization, DefaultTaskRunnerSupport) { +TEST(SequenceManagerBasicTest, DefaultTaskRunnerSupport) { MessageLoop message_loop; scoped_refptr<SingleThreadTaskRunner> original_task_runner = message_loop.task_runner(); @@ -3940,8 +3920,7 @@ EXPECT_TRUE(run); } -TEST_P(SequenceManagerTestWithCustomInitialization, - CreateUnboundSequenceManagerWhichIsNeverBound) { +TEST_P(SequenceManagerTest, CreateUnboundSequenceManagerWhichIsNeverBound) { // This should not crash. CreateUnboundSequenceManager(); }
diff --git a/base/test/test_mock_time_task_runner_unittest.cc b/base/test/test_mock_time_task_runner_unittest.cc index 8eb2780f..e8227dd 100644 --- a/base/test/test_mock_time_task_runner_unittest.cc +++ b/base/test/test_mock_time_task_runner_unittest.cc
@@ -33,28 +33,30 @@ int counter = 0; mock_time_task_runner->PostTask( - FROM_HERE, - base::Bind([](int* counter) { *counter += 1; }, Unretained(&counter))); + FROM_HERE, base::BindOnce([](int* counter) { *counter += 1; }, + Unretained(&counter))); mock_time_task_runner->PostTask( - FROM_HERE, - base::Bind([](int* counter) { *counter += 32; }, Unretained(&counter))); + FROM_HERE, base::BindOnce([](int* counter) { *counter += 32; }, + Unretained(&counter))); mock_time_task_runner->PostDelayedTask( FROM_HERE, - base::Bind([](int* counter) { *counter += 256; }, Unretained(&counter)), + base::BindOnce([](int* counter) { *counter += 256; }, + Unretained(&counter)), TimeDelta::FromSeconds(3)); mock_time_task_runner->PostDelayedTask( FROM_HERE, - base::Bind([](int* counter) { *counter += 64; }, Unretained(&counter)), + base::BindOnce([](int* counter) { *counter += 64; }, + Unretained(&counter)), TimeDelta::FromSeconds(1)); mock_time_task_runner->PostDelayedTask( FROM_HERE, - base::Bind([](int* counter) { *counter += 1024; }, - Unretained(&counter)), + base::BindOnce([](int* counter) { *counter += 1024; }, + Unretained(&counter)), TimeDelta::FromMinutes(20)); mock_time_task_runner->PostDelayedTask( FROM_HERE, - base::Bind([](int* counter) { *counter += 4096; }, - Unretained(&counter)), + base::BindOnce([](int* counter) { *counter += 4096; }, + Unretained(&counter)), TimeDelta::FromDays(20)); int expected_value = 0; @@ -96,26 +98,30 @@ int counter = 0; ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind([](int* counter) { *counter += 1; }, Unretained(&counter))); + FROM_HERE, base::BindOnce([](int* counter) { *counter += 1; }, + Unretained(&counter))); ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind([](int* counter) { *counter += 32; }, Unretained(&counter))); + FROM_HERE, base::BindOnce([](int* counter) { *counter += 32; }, + Unretained(&counter))); ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind([](int* counter) { *counter += 256; }, Unretained(&counter)), + base::BindOnce([](int* counter) { *counter += 256; }, + Unretained(&counter)), TimeDelta::FromSeconds(3)); ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind([](int* counter) { *counter += 64; }, Unretained(&counter)), + base::BindOnce([](int* counter) { *counter += 64; }, + Unretained(&counter)), TimeDelta::FromSeconds(1)); ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind([](int* counter) { *counter += 1024; }, Unretained(&counter)), + base::BindOnce([](int* counter) { *counter += 1024; }, + Unretained(&counter)), TimeDelta::FromMinutes(20)); ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind([](int* counter) { *counter += 4096; }, Unretained(&counter)), + base::BindOnce([](int* counter) { *counter += 4096; }, + Unretained(&counter)), TimeDelta::FromDays(20)); int expected_value = 0; @@ -134,8 +140,8 @@ FROM_HERE, run_loop.QuitClosure(), TimeDelta::FromSeconds(1)); ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind([](int* counter) { *counter += 8192; }, - Unretained(&counter)), + base::BindOnce([](int* counter) { *counter += 8192; }, + Unretained(&counter)), TimeDelta::FromSeconds(1)); // The QuitClosure() should be ordered between the 64 and the 8192 @@ -157,8 +163,8 @@ FROM_HERE, run_loop.QuitWhenIdleClosure(), TimeDelta::FromSeconds(5)); ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind([](int* counter) { *counter += 16384; }, - Unretained(&counter)), + base::BindOnce([](int* counter) { *counter += 16384; }, + Unretained(&counter)), TimeDelta::FromSeconds(5)); // The QuitWhenIdleClosure() shouldn't preempt equally delayed tasks and as
diff --git a/base/threading/thread_restrictions.cc b/base/threading/thread_restrictions.cc index 4541b22..3b21886a 100644 --- a/base/threading/thread_restrictions.cc +++ b/base/threading/thread_restrictions.cc
@@ -41,10 +41,6 @@ } // namespace internal -void AssertBlockingAllowedDeprecated() { - internal::AssertBlockingAllowed(); -} - void DisallowBlocking() { g_blocking_disallowed.Get().Set(true); }
diff --git a/base/threading/thread_restrictions.h b/base/threading/thread_restrictions.h index 3b4def4..c2f767d 100644 --- a/base/threading/thread_restrictions.h +++ b/base/threading/thread_restrictions.h
@@ -291,14 +291,6 @@ } // namespace internal -// Asserts that blocking calls are allowed in the current scope. -// -// DEPRECATED: Use ScopedBlockingCall, which serves as a precise annotation of -// the scope that may/will block. -// TODO(etiennep): Complete migration and delete this method. -INLINE_IF_DCHECK_IS_OFF void AssertBlockingAllowedDeprecated() - EMPTY_BODY_IF_DCHECK_IS_OFF; - // Disallows blocking on the current thread. INLINE_IF_DCHECK_IS_OFF void DisallowBlocking() EMPTY_BODY_IF_DCHECK_IS_OFF;
diff --git a/base/trace_event/trace_event_android.cc b/base/trace_event/trace_event_android.cc index 3394ca6..c699334 100644 --- a/base/trace_event/trace_event_android.cc +++ b/base/trace_event/trace_event_android.cc
@@ -127,8 +127,8 @@ WaitableEvent::InitialState::NOT_SIGNALED); end_chrome_tracing_thread.Start(); end_chrome_tracing_thread.task_runner()->PostTask( - FROM_HERE, base::Bind(&EndChromeTracing, Unretained(this), - Unretained(&complete_event))); + FROM_HERE, base::BindOnce(&EndChromeTracing, Unretained(this), + Unretained(&complete_event))); complete_event.Wait(); }
diff --git a/build/android/list_class_verification_failures.py b/build/android/list_class_verification_failures.py index 5240c62..2206f4b 100755 --- a/build/android/list_class_verification_failures.py +++ b/build/android/list_class_verification_failures.py
@@ -16,7 +16,6 @@ import logging import os import re -import sys import devil_chromium from devil.android import device_errors @@ -25,6 +24,7 @@ from devil.android.ndk import abis from devil.android.sdk import version_codes from devil.android.tools import script_common +from devil.utils import logging_common from py_utils import tempfile_ext STATUSES = [ @@ -258,18 +258,11 @@ script_common.AddEnvironmentArguments(parser) script_common.AddDeviceArguments(parser) + logging_common.AddLoggingArguments(parser) - parser.add_argument('--verbose', '-v', default=False, action='store_true') - parser.add_argument('--quiet', '-q', default=False, action='store_true') args = parser.parse_args() script_common.InitializeEnvironment(args) - - if args.verbose: - logging.basicConfig(stream=sys.stderr, level=logging.INFO) - elif args.quiet: - logging.basicConfig(stream=sys.stderr, level=logging.ERROR) - else: - logging.basicConfig(stream=sys.stderr, level=logging.WARN) + logging_common.InitializeLogging(args) if args.workdir: if not os.path.isdir(args.workdir):
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index 936b1bb..45dc192 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -3b01f76cec3e1be290b0cff261ebd1bcb429e61d \ No newline at end of file +aca22aec66780aac24fecb9d9bb8a77c80b8aa2d \ No newline at end of file
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index 03c66092..0512955 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -2f2a8092ed00985040b8635d51324ef19791f342 \ No newline at end of file +631bd6065a518a7b2da0417e36fb0306936184f6 \ No newline at end of file
diff --git a/cc/animation/README.md b/cc/animation/README.md index 12359aa..a3eb4c4 100644 --- a/cc/animation/README.md +++ b/cc/animation/README.md
@@ -130,12 +130,70 @@ ### Interaction between cc/animation and Blink -Blink is able to move compatible animations off the main thread, by promoting -the animating element into a layer. This section gives an overview of the -machinery to move animations to the compositor from Blink. It does not go into -details on the Blink-side of animations. +Blink is able to move compatible animations off the main thread by promoting +the animating element into a layer. The Blink +[Lifetime of a compositor animation](../../third_party/blink/renderer/core/animation/README.md#lifetime-of-a-compositor-animation) +document describes how composited animations are created in blink. Once a +compositor animation is created it is pushed through the commit cycle. -`TODO(smcgruer): Write this.` +The lifetime of a newly started cc::Animation is roughly the following: + +1. [blink::DocumentAnimations::UpdateAnimations][] calls [blink::Animation::PreCommit][] + on each pending blink::Animation constructing the corresponding + cc::Animation via [blink::Animation::CreateCompositorAnimation][] (attaching + the animation to the cc::AnimationTimeline resulting in it being later pushed). + The KeyframeEffects are constructed via [blink::Animation::StartAnimationOnCompositor][]. +1. [AnimationHost::RegisterKeyframeEffectForElement][] creates a + cc::ElementAnimations for the target `element_id` if one does not already + exist. This ElementAnimations instance is shared by all animations with + the same target and tracks the existence of the target. +1. During the commit, [cc::ElementAnimations::ElementRegistered][] is called on the + main thread's AnimationHost either: + - Before BlinkGenPropertyTrees, when a layer with the target `element_id` is + registered. + - After BlinkGenPropertyTrees, after a property tree node with the target + `element_id` is created on the main thread LayerTreeHost's `property_trees_`. + This begins ticking the attached KeyframeEffects and tracks that the element + exists in the active layer / property tree. +1. [cc::LayerTreeHost::FinishCommitOnImplThread][] calls + [cc::AnimationHost::PushPropertiesTo][] which results in + [cc::AnimationTimeline::PushAttachedAnimationsToImplThread][] creating a + cc::Animation on the compositor thread's AnimationTimeline for each animation + missing from the compositor thread. +1. [cc::Animation::PushPropertiesTo][] is called on every animation on the timeline. + When the `element_id` is pushed by [cc::KeyframeEffect::PushPropertiesTo][] + [cc::Animation::AttachElementForKeyframeEffect][] creates a compositor side + cc::ElementAnimations instance to track the existence of the element on the + compositor. Since animations are pushed after the layer and property trees, + the element should already exist on the pending tree. This will result in the + animation being added to the ticking animations list. +1. Now the animation is ticking, meaning that [cc::Animation::Tick][] will be called + every frame and update the pending property tree nodes. +1. When the pending tree is activated, + [cc::AnimationHost::ActivateAnimations][] updates the keyframe effects and + [cc::ElementAnimations::ElementRegistered][] + is called for the newly added element id on the active tree, setting + `has_element_in_active_list_`. +1. Subsequent animation ticks will now update the property nodes on the active + tree. + +[blink::DocumentAnimations::UpdateAnimations]: https://cs.chromium.org/search?q=function:blink::DocumentAnimations::UpdateAnimations+GetPendingAnimations +[blink::Animation::PreCommit]: https://cs.chromium.org/search?q=function:blink::PendingAnimations::Update+%5C-%5C>PreCommit%5C(&g=0&l=57 +[blink::Animation::CreateCompositorAnimation]: https://cs.chromium.org/search?q=function:blink::Animation::CreateCompositorAnimation+%5E%5B+%5D*AttachCompositorTimeline +[blink::Animation::StartAnimationOnCompositor]: https://cs.chromium.org/search?q=function:blink::Animation::StartAnimationOnCompositor+%5C-%5C>StartAnimationOnCompositor +[AnimationHost::RegisterKeyframeEffectForElement]: https://cs.chromium.org/search?q=function:cc::AnimationHost::RegisterKeyframeEffectForElement+ElementAnimations::Create +[cc::ElementAnimations::ElementRegistered]: https://cs.chromium.org/search?q=function:cc::ElementAnimations::ElementRegistered+%5C!has_element_in_any_list +[cc::LayerTreeHost::FinishCommitOnImplThread]: https://cs.chromium.org/search?q=cc::LayerTreeHost::FinishCommitOnImplThread+file:%5C.cc +[cc::AnimationHost::PushPropertiesTo]: https://cs.chromium.org/search/?q=function:cc::LayerTreeHost::FinishCommitOnImplThread+%5C-%5C>PushPropertiesTo +[cc::AnimationTimeline::PushAttachedAnimationsToImplThread]: https://cs.chromium.org/search?q=function:cc::AnimationTimeline::PushAttachedAnimationsToImplThread+animation%5C-%5C>CreateImplInstance +[cc::Animation::PushPropertiesTo]: https://cs.chromium.org/search?q=cc::Animation::PushPropertiesTo+file:%5C.cc +[cc::KeyframeEffect::PushPropertiesTo]: https://cs.chromium.org/search?q=cc::KeyframeEffect::PushPropertiesTo+file:%5C.cc +[cc::Animation::AttachElementForKeyframeEffect]: https://cs.chromium.org/search?q=cc::Animation::AttachElementForKeyframeEffect+file:%5C.cc +[cc::Animation::Tick]: https://cs.chromium.org/search?q=cc::Animation::Tick+file:%5C.cc +[cc::AnimationHost::ActivateAnimations]: https://cs.chromium.org/search?q=cc::AnimationHost::ActivateAnimations+ActivateKeyframeEffects +[cc::ElementAnimations::ElementRegistered]: https://cs.chromium.org/search?q=cc::ElementAnimations::ElementRegistered+file:%5C.cc + +`TODO(flackr): Document finishing / cancel / abort.` ### Interaction between cc/animation and ui/
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/compositor/OWNERS index 372e007f..487efe8 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/OWNERS +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/OWNERS
@@ -1,4 +1,3 @@ -changwan@chromium.org dtrainor@chromium.org mdjones@chromium.org
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/OWNERS index f7bddc9..0484637 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/OWNERS +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/OWNERS
@@ -1,4 +1,3 @@ -changwan@chromium.org dtrainor@chromium.org twellington@chromium.org
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java index 120930ab..0f15f49 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java
@@ -251,6 +251,8 @@ @Nullable private NavigationController getNavigationController() { + if (getActivityTab() == null) return null; + WebContents webContents = getActivityTab().getWebContents(); return webContents == null ? null : webContents.getNavigationController(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java index 3debaed..ee7fbfb6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java
@@ -128,6 +128,12 @@ private static final long INVALID_TIMESTAMP = -1; + /** + * The required page load percentage for the page to be considered ready assuming the + * TextureView is also ready. + */ + private static final int CONSIDERED_READY_LOAD_PERCENTAGE = 100; + /** Used for logging. */ private static final String TAG = "Tab"; @@ -832,6 +838,15 @@ } } + /** + * @return Whether or not the loading and rendering of the page is done. + * TODO(jinsukkim): Delete this method once the refactoring is finished. + */ + @VisibleForTesting + public boolean isLoadingAndRenderingDone() { + return isReady() && getProgress() >= CONSIDERED_READY_LOAD_PERCENTAGE; + } + /** Stop the current navigation. */ public void stopLoading() { if (isLoading()) { @@ -936,6 +951,7 @@ */ public boolean isPreview() { return getWebContents() != null && !isNativePage() && !isShowingInterstitialPage() + && getSecurityLevel() != ConnectionSecurityLevel.DANGEROUS && PreviewsAndroidBridge.getInstance().shouldShowPreviewUI(getWebContents()); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/webapps/OWNERS index 6a60ce47..d5bee6b2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/OWNERS +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/OWNERS
@@ -1,5 +1,4 @@ dominickn@chromium.org mlamouri@chromium.org -changwan@chromium.org # COMPONENT: Content>WebApps
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/compositor/OWNERS b/chrome/android/javatests/src/org/chromium/chrome/browser/compositor/OWNERS index 68c59f8..6f92e868 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/compositor/OWNERS +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/compositor/OWNERS
@@ -1,4 +1,3 @@ -changwan@chromium.org dtrainor@chromium.org # COMPONENT: UI>Browser>Mobile>CompositedUI
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contacts_picker/ContactsPickerDialogTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contacts_picker/ContactsPickerDialogTest.java index 08ce706..9831abb 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contacts_picker/ContactsPickerDialogTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contacts_picker/ContactsPickerDialogTest.java
@@ -12,7 +12,6 @@ import android.support.test.InstrumentationRegistry; import android.support.test.filters.LargeTest; import android.support.v7.widget.RecyclerView; -import android.util.JsonWriter; import android.view.View; import android.widget.Button; import android.widget.TextView; @@ -37,7 +36,6 @@ import org.chromium.content_public.browser.test.util.TestTouchUtils; import org.chromium.ui.ContactsPickerListener; -import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; @@ -65,13 +63,13 @@ // The selection delegate for the dialog. private SelectionDelegate<ContactDetails> mSelectionDelegate; - // The last action recorded in the dialog (e.g. photo selected). + // The last action recorded in the dialog (e.g. contacts selected). private @ContactsPickerAction int mLastActionRecorded; - // The final set of contacts picked by the dialog (json string). - private String mLastSelectedContacts; + // The final set of contacts picked by the dialog. + private List<ContactsPickerListener.Contact> mLastSelectedContacts; - // The list of currently selected photos (built piecemeal). + // The list of currently selected contacts (built piecemeal). private List<ContactDetails> mCurrentContactSelection; // A callback that fires when something is selected in the dialog. @@ -104,15 +102,15 @@ public void onContactsPickerUserAction(@ContactsPickerAction int action, String contactsJson, List<ContactsPickerListener.Contact> contacts) { mLastActionRecorded = action; - mLastSelectedContacts = contactsJson; + mLastSelectedContacts = (contacts != null) ? new ArrayList<>(contacts) : null; onActionCallback.notifyCalled(); } // SelectionObserver: @Override - public void onSelectionStateChange(List<ContactDetails> photosSelected) { - mCurrentContactSelection = photosSelected; + public void onSelectionStateChange(List<ContactDetails> contactsSelected) { + mCurrentContactSelection = contactsSelected; onSelectionCallback.notifyCalled(); } @@ -225,19 +223,6 @@ }); } - private void addContact(JsonWriter writer, String displayName) throws Throwable { - writer.beginObject(); - writer.name("name"); - writer.value(displayName); - writer.name("emails"); - writer.beginArray(); - writer.endArray(); - writer.name("phoneNumbers"); - writer.beginArray(); - writer.endArray(); - writer.endObject(); - } - @Test @LargeTest public void testOriginString() throws Throwable { @@ -273,7 +258,7 @@ clickView(0, expectedSelectionCount, /* expectSelection = */ true); clickCancel(); - Assert.assertNull(mLastSelectedContacts); + Assert.assertEquals(null, mLastSelectedContacts); Assert.assertEquals(ContactsPickerAction.CANCEL, mLastActionRecorded); dismissDialog(); @@ -293,14 +278,10 @@ clickView(1, expectedSelectionCount, /* expectSelection = */ true); clickDone(); - StringWriter out = new StringWriter(); - final JsonWriter writer = new JsonWriter(out); - writer.beginArray(); - addContact(writer, mTestContacts.get(1).getDisplayName()); - writer.endArray(); - Assert.assertEquals(ContactsPickerAction.CONTACTS_SELECTED, mLastActionRecorded); - Assert.assertEquals(out.toString(), mLastSelectedContacts); + Assert.assertEquals(1, mLastSelectedContacts.size()); + Assert.assertEquals( + mTestContacts.get(1).getDisplayName(), mLastSelectedContacts.get(0).names.get(0)); dismissDialog(); } @@ -321,15 +302,13 @@ clickDone(); Assert.assertEquals(ContactsPickerAction.CONTACTS_SELECTED, mLastActionRecorded); - - StringWriter out = new StringWriter(); - final JsonWriter writer = new JsonWriter(out); - writer.beginArray(); - addContact(writer, mTestContacts.get(4).getDisplayName()); - addContact(writer, mTestContacts.get(2).getDisplayName()); - addContact(writer, mTestContacts.get(0).getDisplayName()); - writer.endArray(); - Assert.assertEquals(out.toString(), mLastSelectedContacts); + Assert.assertEquals(3, mLastSelectedContacts.size()); + Assert.assertEquals( + mTestContacts.get(4).getDisplayName(), mLastSelectedContacts.get(0).names.get(0)); + Assert.assertEquals( + mTestContacts.get(2).getDisplayName(), mLastSelectedContacts.get(1).names.get(0)); + Assert.assertEquals( + mTestContacts.get(0).getDisplayName(), mLastSelectedContacts.get(2).names.get(0)); dismissDialog(); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/OWNERS b/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/OWNERS index b0c7727..a1fd00c4 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/OWNERS +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/OWNERS
@@ -1,5 +1,4 @@ dominickn@chromium.org -changwan@chromium.org hanxi@chromium.org mlamouri@chromium.org pkotwicz@chromium.org
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/compositor/OWNERS b/chrome/android/junit/src/org/chromium/chrome/browser/compositor/OWNERS index 68c59f8..6f92e868 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/compositor/OWNERS +++ b/chrome/android/junit/src/org/chromium/chrome/browser/compositor/OWNERS
@@ -1,4 +1,3 @@ -changwan@chromium.org dtrainor@chromium.org # COMPONENT: UI>Browser>Mobile>CompositedUI
diff --git a/chrome/app_shim/chrome_main_app_mode_mac.mm b/chrome/app_shim/chrome_main_app_mode_mac.mm index 026678d..a770ab4 100644 --- a/chrome/app_shim/chrome_main_app_mode_mac.mm +++ b/chrome/app_shim/chrome_main_app_mode_mac.mm
@@ -318,8 +318,9 @@ [ReplyEventHandler pingProcessAndCall:on_ping_chrome_reply]; main_message_loop.task_runner()->PostDelayedTask( - FROM_HERE, base::Bind(&AppShimController::OnPingChromeTimeout, - base::Unretained(&controller)), + FROM_HERE, + base::BindOnce(&AppShimController::OnPingChromeTimeout, + base::Unretained(&controller)), base::TimeDelta::FromSeconds(kPingChromeTimeoutSeconds)); } else { // Chrome already running. Proceed to init. This could still fail if Chrome
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 99203c7..60e342c 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -3321,6 +3321,8 @@ "metrics/perf/collection_params.h", "metrics/perf/cpu_identity.cc", "metrics/perf/cpu_identity.h", + "metrics/perf/heap_collector.cc", + "metrics/perf/heap_collector.h", "metrics/perf/metric_collector.cc", "metrics/perf/metric_collector.h", "metrics/perf/perf_events_collector.cc",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 9f460eeb..6e84d55f 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -2506,9 +2506,6 @@ {"enable-bulk-printers", flag_descriptions::kBulkPrintersName, flag_descriptions::kBulkPrintersDescription, kOsCrOS, FEATURE_VALUE_TYPE(features::kBulkPrinters)}, - {"disable-cros-component", flag_descriptions::kCrOSComponentName, - flag_descriptions::kCrOSComponentDescription, kOsCrOS, - FEATURE_VALUE_TYPE(features::kCrOSComponent)}, {"enable-encryption-migration", flag_descriptions::kEnableEncryptionMigrationName, flag_descriptions::kEnableEncryptionMigrationDescription, kOsCrOS, @@ -2576,54 +2573,11 @@ flag_descriptions::kFramebustingName, flag_descriptions::kFramebustingDescription, kOsAll, FEATURE_VALUE_TYPE(features::kFramebustingNeedsSameOriginOrUserGesture)}, - {"web-payments", flag_descriptions::kWebPaymentsName, - flag_descriptions::kWebPaymentsDescription, kOsDesktop, - FEATURE_VALUE_TYPE(features::kWebPayments)}, - {"web-payments-modifiers", flag_descriptions::kWebPaymentsModifiersName, - flag_descriptions::kWebPaymentsModifiersDescription, - kOsAndroid | kOsDesktop, - FEATURE_VALUE_TYPE(payments::features::kWebPaymentsModifiers)}, - {"service-worker-payment-apps", - flag_descriptions::kServiceWorkerPaymentAppsName, - flag_descriptions::kServiceWorkerPaymentAppsDescription, - kOsAndroid | kOsDesktop, - FEATURE_VALUE_TYPE(features::kServiceWorkerPaymentApps)}, - {"enable-web-payments-single-app-ui-skip", - flag_descriptions::kEnableWebPaymentsSingleAppUiSkipName, - flag_descriptions::kEnableWebPaymentsSingleAppUiSkipDescription, - kOsAndroid | kOsDesktop, - FEATURE_VALUE_TYPE(payments::features::kWebPaymentsSingleAppUiSkip)}, - {"just-in-time-service-worker-payment-app", - flag_descriptions::kJustInTimeServiceWorkerPaymentAppName, - flag_descriptions::kJustInTimeServiceWorkerPaymentAppDescription, - kOsAndroid | kOsDesktop, - FEATURE_VALUE_TYPE(payments::features::kWebPaymentsJustInTimePaymentApp)}, {"per-method-can-make-payment-quota", flag_descriptions::kPerMethodCanMakePaymentQuotaName, flag_descriptions::kPerMethodCanMakePaymentQuotaDescription, kOsAll, FEATURE_VALUE_TYPE( payments::features::kWebPaymentsPerMethodCanMakePaymentQuota)}, -#if defined(OS_ANDROID) - {"enable-android-pay-integration-v1", - flag_descriptions::kEnableAndroidPayIntegrationV1Name, - flag_descriptions::kEnableAndroidPayIntegrationV1Description, kOsAndroid, - FEATURE_VALUE_TYPE(chrome::android::kAndroidPayIntegrationV1)}, - {"enable-android-pay-integration-v2", - flag_descriptions::kEnableAndroidPayIntegrationV2Name, - flag_descriptions::kEnableAndroidPayIntegrationV2Description, kOsAndroid, - FEATURE_VALUE_TYPE(chrome::android::kAndroidPayIntegrationV2)}, - {"enable-web-payments-method-section-order-v2", - flag_descriptions::kEnableWebPaymentsMethodSectionOrderV2Name, - flag_descriptions::kEnableWebPaymentsMethodSectionOrderV2Description, - kOsAndroid, - FEATURE_VALUE_TYPE(payments::features::kWebPaymentsMethodSectionOrderV2)}, - {"android-payment-apps", flag_descriptions::kAndroidPaymentAppsName, - flag_descriptions::kAndroidPaymentAppsDescription, kOsAndroid, - FEATURE_VALUE_TYPE(chrome::android::kAndroidPaymentApps)}, - {"pay-with-google-v1", flag_descriptions::kPayWithGoogleV1Name, - flag_descriptions::kPayWithGoogleV1Description, kOsAndroid, - FEATURE_VALUE_TYPE(chrome::android::kPayWithGoogleV1)}, -#endif // OS_ANDROID #if defined(OS_CHROMEOS) {"disable-eol-notification", flag_descriptions::kEolNotificationName, flag_descriptions::kEolNotificationDescription, kOsCrOS,
diff --git a/chrome/browser/android/chrome_feature_list.cc b/chrome/browser/android/chrome_feature_list.cc index 9a4d492..bf300117 100644 --- a/chrome/browser/android/chrome_feature_list.cc +++ b/chrome/browser/android/chrome_feature_list.cc
@@ -215,6 +215,7 @@ const base::Feature kAndroidNightMode{"AndroidNightMode", base::FEATURE_DISABLED_BY_DEFAULT}; +// TODO(rouslan): Remove this. const base::Feature kAndroidPayIntegrationV1{"AndroidPayIntegrationV1", base::FEATURE_ENABLED_BY_DEFAULT}; @@ -224,9 +225,11 @@ const base::Feature kAllowRemoteContextForNotifications{ "AllowRemoteContextForNotifications", base::FEATURE_ENABLED_BY_DEFAULT}; +// TODO(rouslan): Remove this. const base::Feature kAndroidPayIntegrationV2{"AndroidPayIntegrationV2", base::FEATURE_ENABLED_BY_DEFAULT}; +// TODO(rouslan): Remove this. const base::Feature kAndroidPaymentApps{"AndroidPaymentApps", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kAndroidSiteSettingsUIRefresh{ @@ -400,6 +403,7 @@ const base::Feature kOmniboxVoiceSearchAlwaysVisible{ "OmniboxVoiceSearchAlwaysVisible", base::FEATURE_DISABLED_BY_DEFAULT}; +// TODO(rouslan): Remove this. const base::Feature kPayWithGoogleV1{"PayWithGoogleV1", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/chrome/browser/android/compositor/OWNERS b/chrome/browser/android/compositor/OWNERS index aa2f428..8d8ce64 100644 --- a/chrome/browser/android/compositor/OWNERS +++ b/chrome/browser/android/compositor/OWNERS
@@ -1,4 +1,3 @@ -changwan@chromium.org dtrainor@chromium.org mdjones@chromium.org
diff --git a/chrome/browser/android/download/download_manager_service.cc b/chrome/browser/android/download/download_manager_service.cc index e501b0e..08a81c7 100644 --- a/chrome/browser/android/download/download_manager_service.cc +++ b/chrome/browser/android/download/download_manager_service.cc
@@ -621,8 +621,9 @@ void DownloadManagerService::OnResumptionFailed( const std::string& download_guid) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&DownloadManagerService::OnResumptionFailedInternal, - base::Unretained(this), download_guid)); + FROM_HERE, + base::BindOnce(&DownloadManagerService::OnResumptionFailedInternal, + base::Unretained(this), download_guid)); DownloadController::RecordDownloadCancelReason( DownloadController::CANCEL_REASON_NOT_CANCELED); }
diff --git a/chrome/browser/android/feedback/connectivity_checker.cc b/chrome/browser/android/feedback/connectivity_checker.cc index 76aa789..76039a5 100644 --- a/chrome/browser/android/feedback/connectivity_checker.cc +++ b/chrome/browser/android/feedback/connectivity_checker.cc
@@ -54,9 +54,9 @@ ConnectivityCheckResult result) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&ExecuteCallback, - base::android::ScopedJavaGlobalRef<jobject>(j_callback), - result)); + base::BindOnce(&ExecuteCallback, + base::android::ScopedJavaGlobalRef<jobject>(j_callback), + result)); } // A utility class for checking if the device is currently connected to the
diff --git a/chrome/browser/android/history_report/delta_file_service.cc b/chrome/browser/android/history_report/delta_file_service.cc index 526c106..ce51a73 100644 --- a/chrome/browser/android/history_report/delta_file_service.cc +++ b/chrome/browser/android/history_report/delta_file_service.cc
@@ -96,14 +96,16 @@ void DeltaFileService::PageAdded(const GURL& url) { task_runner_->PostTask( - FROM_HERE, base::Bind(&DeltaFileServiceDoAddPage, - base::Unretained(delta_file_backend_.get()), url)); + FROM_HERE, + base::BindOnce(&DeltaFileServiceDoAddPage, + base::Unretained(delta_file_backend_.get()), url)); } void DeltaFileService::PageDeleted(const GURL& url) { task_runner_->PostTask( - FROM_HERE, base::Bind(&DeltaFileServiceDoDeletePage, - base::Unretained(delta_file_backend_.get()), url)); + FROM_HERE, + base::BindOnce(&DeltaFileServiceDoDeletePage, + base::Unretained(delta_file_backend_.get()), url)); } int64_t DeltaFileService::Trim(int64_t lower_bound) { @@ -112,9 +114,9 @@ base::WaitableEvent::InitialState::NOT_SIGNALED); task_runner_->PostTask( FROM_HERE, - base::Bind(&DeltaFileServiceDoTrim, - base::Unretained(delta_file_backend_.get()), lower_bound, - base::Unretained(&finished), base::Unretained(&result))); + base::BindOnce(&DeltaFileServiceDoTrim, + base::Unretained(delta_file_backend_.get()), lower_bound, + base::Unretained(&finished), base::Unretained(&result))); finished.Wait(); return result; } @@ -126,10 +128,10 @@ base::WaitableEvent finished(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); task_runner_->PostTask( - FROM_HERE, base::Bind(&DeltaFileServiceDoQuery, - base::Unretained(delta_file_backend_.get()), - last_seq_no, limit, base::Unretained(&finished), - base::Unretained(&result))); + FROM_HERE, base::BindOnce(&DeltaFileServiceDoQuery, + base::Unretained(delta_file_backend_.get()), + last_seq_no, limit, base::Unretained(&finished), + base::Unretained(&result))); finished.Wait(); return result; } @@ -140,17 +142,17 @@ base::WaitableEvent::InitialState::NOT_SIGNALED); task_runner_->PostTask( FROM_HERE, - base::Bind(&DeltaFileServiceDoRecreate, - base::Unretained(delta_file_backend_.get()), urls, - base::Unretained(&finished), base::Unretained(&result))); + base::BindOnce(&DeltaFileServiceDoRecreate, + base::Unretained(delta_file_backend_.get()), urls, + base::Unretained(&finished), base::Unretained(&result))); finished.Wait(); return result; } void DeltaFileService::Clear() { task_runner_->PostTask( - FROM_HERE, base::Bind(&DeltaFileServiceDoClear, - base::Unretained(delta_file_backend_.get()))); + FROM_HERE, base::BindOnce(&DeltaFileServiceDoClear, + base::Unretained(delta_file_backend_.get()))); } std::string DeltaFileService::Dump() { @@ -159,9 +161,9 @@ base::WaitableEvent::InitialState::NOT_SIGNALED); task_runner_->PostTask( FROM_HERE, - base::Bind(&DeltaFileServiceDoDump, - base::Unretained(delta_file_backend_.get()), - base::Unretained(&finished), base::Unretained(&dump))); + base::BindOnce(&DeltaFileServiceDoDump, + base::Unretained(delta_file_backend_.get()), + base::Unretained(&finished), base::Unretained(&dump))); finished.Wait(); return dump; }
diff --git a/chrome/browser/android/history_report/usage_reports_buffer_service.cc b/chrome/browser/android/history_report/usage_reports_buffer_service.cc index 0a3276b..111442c6 100644 --- a/chrome/browser/android/history_report/usage_reports_buffer_service.cc +++ b/chrome/browser/android/history_report/usage_reports_buffer_service.cc
@@ -90,17 +90,17 @@ void UsageReportsBufferService::Init() { task_runner_->PostTask(FROM_HERE, - base::Bind(&UsageReportsBufferServiceDoInit, - base::Unretained(backend_.get()))); + base::BindOnce(&UsageReportsBufferServiceDoInit, + base::Unretained(backend_.get()))); } void UsageReportsBufferService::AddVisit(const std::string& id, int64_t timestamp_ms, bool typed_visit) { - task_runner_->PostTask( - FROM_HERE, base::Bind(&UsageReportsBufferServiceDoAddVisit, - base::Unretained(backend_.get()), id, timestamp_ms, - typed_visit)); + task_runner_->PostTask(FROM_HERE, + base::BindOnce(&UsageReportsBufferServiceDoAddVisit, + base::Unretained(backend_.get()), id, + timestamp_ms, typed_visit)); } std::unique_ptr<std::vector<UsageReport>> @@ -112,9 +112,9 @@ // call. task_runner_->PostTask( FROM_HERE, - base::Bind(&UsageReportsBufferServiceDoGetUsageReportsBatch, - base::Unretained(backend_.get()), batch_size, - base::Unretained(&finished), base::Unretained(&result))); + base::BindOnce(&UsageReportsBufferServiceDoGetUsageReportsBatch, + base::Unretained(backend_.get()), batch_size, + base::Unretained(&finished), base::Unretained(&result))); finished.Wait(); return result; } @@ -125,11 +125,11 @@ base::WaitableEvent::InitialState::NOT_SIGNALED); // It's ok to pass unretained pointers here because this is a synchronous // call. - task_runner_->PostTask( - FROM_HERE, - base::Bind(&UsageReportsBufferServiceDoRemove, - base::Unretained(backend_.get()), - base::Unretained(&report_ids), base::Unretained(&finished))); + task_runner_->PostTask(FROM_HERE, + base::BindOnce(&UsageReportsBufferServiceDoRemove, + base::Unretained(backend_.get()), + base::Unretained(&report_ids), + base::Unretained(&finished))); finished.Wait(); } @@ -139,9 +139,9 @@ // It's ok to pass unretained pointers here because this is a synchronous // call. task_runner_->PostTask(FROM_HERE, - base::Bind(&UsageReportsBufferServiceDoClear, - base::Unretained(backend_.get()), - base::Unretained(&finished))); + base::BindOnce(&UsageReportsBufferServiceDoClear, + base::Unretained(backend_.get()), + base::Unretained(&finished))); finished.Wait(); } @@ -151,10 +151,11 @@ base::WaitableEvent::InitialState::NOT_SIGNALED); // It's ok to pass unretained pointers here because this is a synchronous // call. - task_runner_->PostTask(FROM_HERE, base::Bind(&UsageReportsBufferServiceDoDump, - base::Unretained(backend_.get()), - base::Unretained(&finished), - base::Unretained(&dump))); + task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&UsageReportsBufferServiceDoDump, + base::Unretained(backend_.get()), + base::Unretained(&finished), base::Unretained(&dump))); finished.Wait(); return dump; }
diff --git a/chrome/browser/android/metrics/uma_session_stats.cc b/chrome/browser/android/metrics/uma_session_stats.cc index 93fd733..8869765 100644 --- a/chrome/browser/android/metrics/uma_session_stats.cc +++ b/chrome/browser/android/metrics/uma_session_stats.cc
@@ -135,9 +135,10 @@ // will ensure that the consent file contains the ClientID. The ID is passed // to the renderer for crash reporting when things go wrong. GoogleUpdateSettings::CollectStatsConsentTaskRunner()->PostTask( - FROM_HERE, base::Bind(base::IgnoreResult( - GoogleUpdateSettings::SetCollectStatsConsent), - consent)); + FROM_HERE, + base::BindOnce( + base::IgnoreResult(GoogleUpdateSettings::SetCollectStatsConsent), + consent)); } // Initialize the local consent bool variable to false. Used only for testing.
diff --git a/chrome/browser/android/resource_id.h b/chrome/browser/android/resource_id.h index 0b84d6e6..df8f80e4 100644 --- a/chrome/browser/android/resource_id.h +++ b/chrome/browser/android/resource_id.h
@@ -39,6 +39,7 @@ DECLARE_RESOURCE_ID(IDR_ANDROID_INFOBAR_FROZEN_TAB, R.drawable.infobar_restore) DECLARE_RESOURCE_ID(IDR_ANDROID_INFOBAR_GEOLOCATION, R.drawable.infobar_geolocation) +DECLARE_RESOURCE_ID(IDR_ANDROID_INFOBAR_LITE_MODE, R.drawable.preview_pin_round) DECLARE_RESOURCE_ID(IDR_ANDROID_INFOBAR_MEDIA_STREAM_CAMERA, R.drawable.infobar_camera) DECLARE_RESOURCE_ID(IDR_ANDROID_INFOBAR_MEDIA_STREAM_MIC,
diff --git a/chrome/browser/android/thumbnail/thumbnail.cc b/chrome/browser/android/thumbnail/thumbnail.cc index d43209a..d8cd3d6 100644 --- a/chrome/browser/android/thumbnail/thumbnail.cc +++ b/chrome/browser/android/thumbnail/thumbnail.cc
@@ -94,7 +94,7 @@ // to avoid reentry there. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&Thumbnail::DoInvalidate, weak_factory_.GetWeakPtr())); + base::BindOnce(&Thumbnail::DoInvalidate, weak_factory_.GetWeakPtr())); return bitmap_; }
diff --git a/chrome/browser/android/usage_stats/usage_stats_database.cc b/chrome/browser/android/usage_stats/usage_stats_database.cc index 4d3edaef..dcf85a05 100644 --- a/chrome/browser/android/usage_stats/usage_stats_database.cc +++ b/chrome/browser/android/usage_stats/usage_stats_database.cc
@@ -10,7 +10,6 @@ #include "base/strings/safe_sprintf.h" #include "base/strings/strcat.h" #include "base/task/post_task.h" -#include "chrome/browser/android/usage_stats/website_event.pb.h" #include "components/leveldb_proto/content/proto_database_provider_factory.h" #include "components/leveldb_proto/public/proto_database_provider.h" @@ -19,7 +18,7 @@ using leveldb_proto::ProtoDatabaseProvider; using leveldb_proto::ProtoDatabaseProviderFactory; -const char kNamespace[] = "usage_stats"; +const char kNamespace[] = "UsageStats"; const char kKeySeparator[] = "_"; @@ -33,10 +32,12 @@ const char kUnixTimeFormat[] = "%011d"; UsageStatsDatabase::UsageStatsDatabase(Profile* profile) - : weak_ptr_factory_(this) { + : website_event_db_initialized_(false), + suspension_db_initialized_(false), + token_mapping_db_initialized_(false), + weak_ptr_factory_(this) { ProtoDatabaseProvider* db_provider = - ProtoDatabaseProviderFactory::GetInstance()->GetForBrowserContext( - profile); + ProtoDatabaseProviderFactory::GetForBrowserContext(profile); base::FilePath usage_stats_dir = profile->GetPath().Append(kNamespace); @@ -52,6 +53,8 @@ token_mapping_db_ = db_provider->GetDB<TokenMapping>( kNamespace, kTokenMappingPrefix, usage_stats_dir, db_task_runner); + + InitializeDBs(); } // Used for testing. @@ -62,7 +65,12 @@ : website_event_db_(std::move(website_event_db)), suspension_db_(std::move(suspension_db)), token_mapping_db_(std::move(token_mapping_db)), - weak_ptr_factory_(this) {} + website_event_db_initialized_(false), + suspension_db_initialized_(false), + token_mapping_db_initialized_(false), + weak_ptr_factory_(this) { + InitializeDBs(); +} UsageStatsDatabase::~UsageStatsDatabase() = default; @@ -97,7 +105,30 @@ } // namespace +void UsageStatsDatabase::InitializeDBs() { + // Asynchronously initialize databases. + website_event_db_->Init( + kNamespace, base::BindOnce(&UsageStatsDatabase::OnWebsiteEventInitDone, + weak_ptr_factory_.GetWeakPtr(), true)); + + suspension_db_->Init(kNamespace, + base::BindOnce(&UsageStatsDatabase::OnSuspensionInitDone, + weak_ptr_factory_.GetWeakPtr(), true)); + + token_mapping_db_->Init( + kNamespace, base::BindOnce(&UsageStatsDatabase::OnTokenMappingInitDone, + weak_ptr_factory_.GetWeakPtr(), true)); +} + void UsageStatsDatabase::GetAllEvents(EventsCallback callback) { + // Defer execution if database is uninitialized. + if (!website_event_db_initialized_) { + website_event_db_callbacks_.emplace( + base::BindOnce(&UsageStatsDatabase::GetAllEvents, + weak_ptr_factory_.GetWeakPtr(), std::move(callback))); + return; + } + // Load all WebsiteEvents. website_event_db_->LoadEntries( base::BindOnce(&UsageStatsDatabase::OnLoadEntriesForGetAllEvents, @@ -107,6 +138,14 @@ void UsageStatsDatabase::QueryEventsInRange(int64_t start, int64_t end, EventsCallback callback) { + // Defer execution if database is uninitialized. + if (!website_event_db_initialized_) { + website_event_db_callbacks_.emplace(base::BindOnce( + &UsageStatsDatabase::QueryEventsInRange, weak_ptr_factory_.GetWeakPtr(), + start, end, std::move(callback))); + return; + } + // Load all WebsiteEvents where the timestamp is // in the specified range. Function accepts a half-open range [start, end) as // input, but the database operates on fully-closed ranges. Because the @@ -120,6 +159,14 @@ void UsageStatsDatabase::AddEvents(std::vector<WebsiteEvent> events, StatusCallback callback) { + // Defer execution if database is uninitialized. + if (!website_event_db_initialized_) { + website_event_db_callbacks_.emplace(base::BindOnce( + &UsageStatsDatabase::AddEvents, weak_ptr_factory_.GetWeakPtr(), + std::move(events), std::move(callback))); + return; + } + auto entries = std::make_unique<ProtoDatabase<WebsiteEvent>::KeyEntryVector>(); entries->reserve(events.size()); @@ -139,6 +186,14 @@ } void UsageStatsDatabase::DeleteAllEvents(StatusCallback callback) { + // Defer execution if database is uninitialized. + if (!website_event_db_initialized_) { + website_event_db_callbacks_.emplace( + base::BindOnce(&UsageStatsDatabase::DeleteAllEvents, + weak_ptr_factory_.GetWeakPtr(), std::move(callback))); + return; + } + // Remove all WebsiteEvent entries. website_event_db_->UpdateEntriesWithRemoveFilter( std::make_unique<ProtoDatabase<WebsiteEvent>::KeyEntryVector>(), @@ -149,6 +204,14 @@ void UsageStatsDatabase::DeleteEventsInRange(int64_t start, int64_t end, StatusCallback callback) { + // Defer execution if database is uninitialized. + if (!website_event_db_initialized_) { + website_event_db_callbacks_.emplace(base::BindOnce( + &UsageStatsDatabase::DeleteEventsInRange, + weak_ptr_factory_.GetWeakPtr(), start, end, std::move(callback))); + return; + } + // TODO(crbug/927655): If/when leveldb_proto adds an UpdateEntriesInRange // function, we should consolidate these two proto_db_ calls into a single // call. @@ -167,6 +230,15 @@ void UsageStatsDatabase::DeleteEventsWithMatchingDomains( base::flat_set<std::string> domains, StatusCallback callback) { + // Defer execution if database is uninitialized. + if (!website_event_db_initialized_) { + website_event_db_callbacks_.emplace( + base::BindOnce(&UsageStatsDatabase::DeleteEventsWithMatchingDomains, + weak_ptr_factory_.GetWeakPtr(), std::move(domains), + std::move(callback))); + return; + } + // Remove all events with domains in the given set. website_event_db_->UpdateEntriesWithRemoveFilter( std::make_unique<ProtoDatabase<WebsiteEvent>::KeyEntryVector>(), @@ -176,6 +248,14 @@ } void UsageStatsDatabase::GetAllSuspensions(SuspensionsCallback callback) { + if (!suspension_db_initialized_) { + // Defer execution if database is uninitialized. + suspension_db_callbacks_.emplace( + base::BindOnce(&UsageStatsDatabase::GetAllSuspensions, + weak_ptr_factory_.GetWeakPtr(), std::move(callback))); + return; + } + // Load all Suspensions. suspension_db_->LoadEntries( base::BindOnce(&UsageStatsDatabase::OnLoadEntriesForGetAllSuspensions, @@ -184,6 +264,14 @@ void UsageStatsDatabase::SetSuspensions(base::flat_set<std::string> domains, StatusCallback callback) { + // Defer execution if database is uninitialized. + if (!suspension_db_initialized_) { + suspension_db_callbacks_.emplace(base::BindOnce( + &UsageStatsDatabase::SetSuspensions, weak_ptr_factory_.GetWeakPtr(), + std::move(domains), std::move(callback))); + return; + } + auto entries = std::make_unique<ProtoDatabase<Suspension>::KeyEntryVector>(); for (std::string domain : domains) { @@ -202,6 +290,14 @@ } void UsageStatsDatabase::GetAllTokenMappings(TokenMappingsCallback callback) { + // Defer execution if database is uninitialized. + if (!token_mapping_db_initialized_) { + token_mapping_db_callbacks_.emplace( + base::BindOnce(&UsageStatsDatabase::GetAllTokenMappings, + weak_ptr_factory_.GetWeakPtr(), std::move(callback))); + return; + } + // Load all TokenMappings. token_mapping_db_->LoadEntries( base::BindOnce(&UsageStatsDatabase::OnLoadEntriesForGetAllTokenMappings, @@ -210,6 +306,14 @@ void UsageStatsDatabase::SetTokenMappings(TokenMap mappings, StatusCallback callback) { + // Defer execution if database is uninitialized. + if (!token_mapping_db_initialized_) { + token_mapping_db_callbacks_.emplace(base::BindOnce( + &UsageStatsDatabase::SetTokenMappings, weak_ptr_factory_.GetWeakPtr(), + std::move(mappings), std::move(callback))); + return; + } + std::vector<std::string> keys; keys.reserve(mappings.size()); @@ -239,6 +343,76 @@ weak_ptr_factory_.GetWeakPtr(), std::move(callback))); } +void UsageStatsDatabase::OnWebsiteEventInitDone( + bool retry, + leveldb_proto::Enums::InitStatus status) { + website_event_db_initialized_ = + status == leveldb_proto::Enums::InitStatus::kOK; + + if (!website_event_db_initialized_) { + if (retry) { + // Retry unsuccessful initialization. + website_event_db_->Init( + kNamespace, + base::BindOnce(&UsageStatsDatabase::OnWebsiteEventInitDone, + weak_ptr_factory_.GetWeakPtr(), false)); + } + return; + } + + // Execute deferred operations on sucessfully initialized database. + while (!website_event_db_callbacks_.empty()) { + std::move(website_event_db_callbacks_.front()).Run(); + website_event_db_callbacks_.pop(); + } +} + +void UsageStatsDatabase::OnSuspensionInitDone( + bool retry, + leveldb_proto::Enums::InitStatus status) { + suspension_db_initialized_ = status == leveldb_proto::Enums::InitStatus::kOK; + + if (!suspension_db_initialized_) { + if (retry) { + // Retry unsuccessful initialization. + suspension_db_->Init( + kNamespace, base::BindOnce(&UsageStatsDatabase::OnSuspensionInitDone, + weak_ptr_factory_.GetWeakPtr(), false)); + } + return; + } + + // Execute deferred operations on sucessfully initialized database. + while (!suspension_db_callbacks_.empty()) { + std::move(suspension_db_callbacks_.front()).Run(); + suspension_db_callbacks_.pop(); + } +} + +void UsageStatsDatabase::OnTokenMappingInitDone( + bool retry, + leveldb_proto::Enums::InitStatus status) { + token_mapping_db_initialized_ = + status == leveldb_proto::Enums::InitStatus::kOK; + + if (!token_mapping_db_initialized_) { + if (retry) { + // Retry unsuccessful initialization. + token_mapping_db_->Init( + kNamespace, + base::BindOnce(&UsageStatsDatabase::OnTokenMappingInitDone, + weak_ptr_factory_.GetWeakPtr(), false)); + } + return; + } + + // Execute deferred operations on sucessfully initialized database. + while (!token_mapping_db_callbacks_.empty()) { + std::move(token_mapping_db_callbacks_.front()).Run(); + token_mapping_db_callbacks_.pop(); + } +} + void UsageStatsDatabase::OnUpdateEntries(StatusCallback callback, bool isSuccess) { std::move(callback).Run(ToError(isSuccess));
diff --git a/chrome/browser/android/usage_stats/usage_stats_database.h b/chrome/browser/android/usage_stats/usage_stats_database.h index 995bf09a..a6db1688 100644 --- a/chrome/browser/android/usage_stats/usage_stats_database.h +++ b/chrome/browser/android/usage_stats/usage_stats_database.h
@@ -10,9 +10,12 @@ #include <string> #include <vector> +#include "base/callback.h" #include "base/containers/flat_set.h" +#include "base/containers/queue.h" #include "base/files/file_path.h" #include "base/macros.h" +#include "base/memory/weak_ptr.h" #include "chrome/browser/android/usage_stats/website_event.pb.h" #include "chrome/browser/profiles/profile.h" #include "components/leveldb_proto/public/proto_database.h" @@ -81,6 +84,17 @@ void SetTokenMappings(TokenMap mappings, StatusCallback callback); private: + void InitializeDBs(); + + void OnWebsiteEventInitDone(bool retry, + leveldb_proto::Enums::InitStatus status); + + void OnSuspensionInitDone(bool retry, + leveldb_proto::Enums::InitStatus status); + + void OnTokenMappingInitDone(bool retry, + leveldb_proto::Enums::InitStatus status); + void OnUpdateEntries(StatusCallback callback, bool isSuccess); void OnLoadEntriesForGetAllEvents( @@ -112,6 +126,16 @@ std::unique_ptr<ProtoDatabase<Suspension>> suspension_db_; std::unique_ptr<ProtoDatabase<TokenMapping>> token_mapping_db_; + // Track initialization state of proto databases. + bool website_event_db_initialized_; + bool suspension_db_initialized_; + bool token_mapping_db_initialized_; + + // Store callbacks for delayed execution once database is initialized. + base::queue<base::OnceClosure> website_event_db_callbacks_; + base::queue<base::OnceClosure> suspension_db_callbacks_; + base::queue<base::OnceClosure> token_mapping_db_callbacks_; + base::WeakPtrFactory<UsageStatsDatabase> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(UsageStatsDatabase);
diff --git a/chrome/browser/android/usage_stats/usage_stats_database_unittest.cc b/chrome/browser/android/usage_stats/usage_stats_database_unittest.cc index 8a53e68..83d96d1 100644 --- a/chrome/browser/android/usage_stats/usage_stats_database_unittest.cc +++ b/chrome/browser/android/usage_stats/usage_stats_database_unittest.cc
@@ -81,9 +81,9 @@ MOCK_METHOD1(OnUpdateDone, void(UsageStatsDatabase::Error)); MOCK_METHOD2(OnGetEventsDone, void(UsageStatsDatabase::Error, std::vector<WebsiteEvent>)); - MOCK_METHOD2(OnGetAllSuspensionsDone, + MOCK_METHOD2(OnGetSuspensionsDone, void(UsageStatsDatabase::Error, std::vector<std::string>)); - MOCK_METHOD2(OnGetAllTokenMappingsDone, + MOCK_METHOD2(OnGetTokenMappingsDone, void(UsageStatsDatabase::Error, UsageStatsDatabase::TokenMap)); private: @@ -105,66 +105,90 @@ ASSERT_NE(nullptr, fake_website_event_db()); ASSERT_NE(nullptr, fake_suspension_db()); ASSERT_NE(nullptr, fake_token_mapping_db()); + + // Expect that Init has been called on all ProtoDatabases. If it hasn't, then + // InitStatusCallback will cause the test to crash. + fake_website_event_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + fake_suspension_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + fake_token_mapping_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); } // Website Event Tests TEST_F(UsageStatsDatabaseTest, GetAllEventsSuccess) { - EXPECT_CALL(*this, OnGetEventsDone(UsageStatsDatabase::Error::kNoError, - ElementsAre())); + fake_website_event_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); usage_stats_database()->GetAllEvents(base::BindOnce( &UsageStatsDatabaseTest::OnGetEventsDone, base::Unretained(this))); + EXPECT_CALL(*this, OnGetEventsDone(UsageStatsDatabase::Error::kNoError, + ElementsAre())); + fake_website_event_db()->LoadCallback(true); } TEST_F(UsageStatsDatabaseTest, GetAllEventsFailure) { - EXPECT_CALL(*this, OnGetEventsDone(UsageStatsDatabase::Error::kUnknownError, - ElementsAre())); + fake_website_event_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); usage_stats_database()->GetAllEvents(base::BindOnce( &UsageStatsDatabaseTest::OnGetEventsDone, base::Unretained(this))); + EXPECT_CALL(*this, OnGetEventsDone(UsageStatsDatabase::Error::kUnknownError, + ElementsAre())); + fake_website_event_db()->LoadCallback(false); } TEST_F(UsageStatsDatabaseTest, AddEventsEmpty) { - std::vector<WebsiteEvent> events; + fake_website_event_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + std::vector<WebsiteEvent> events; usage_stats_database()->AddEvents( events, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_website_event_db()->UpdateCallback(true); } TEST_F(UsageStatsDatabaseTest, AddAndGetOneEvent) { + fake_website_event_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + // Add 1 event. WebsiteEvent event1 = CreateWebsiteEvent(kFqdn1, 1, WebsiteEvent::START_BROWSING); std::vector<WebsiteEvent> events({event1}); - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); - usage_stats_database()->AddEvents( events, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_website_event_db()->UpdateCallback(true); // Get 1 event. - EXPECT_CALL(*this, OnGetEventsDone(UsageStatsDatabase::Error::kNoError, - ElementsAre(EqualsWebsiteEvent(event1)))); - usage_stats_database()->GetAllEvents(base::BindOnce( &UsageStatsDatabaseTest::OnGetEventsDone, base::Unretained(this))); + EXPECT_CALL(*this, OnGetEventsDone(UsageStatsDatabase::Error::kNoError, + ElementsAre(EqualsWebsiteEvent(event1)))); + fake_website_event_db()->LoadCallback(true); } TEST_F(UsageStatsDatabaseTest, AddAndQueryEventsInRange) { + fake_website_event_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + // Add 2 events at time 5 and 10. WebsiteEvent event1 = CreateWebsiteEvent(kFqdn1, 5, WebsiteEvent::START_BROWSING); @@ -172,61 +196,67 @@ CreateWebsiteEvent(kFqdn2, 10, WebsiteEvent::STOP_BROWSING); std::vector<WebsiteEvent> events({event1, event2}); - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); - usage_stats_database()->AddEvents( events, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_website_event_db()->UpdateCallback(true); // Get events between time 0 (inclusive) and 9 (exclusive). // This test validates the correct lexicographic ordering of timestamps such // that key(0) <= key(5) < key(9) <= key(10). - EXPECT_CALL(*this, OnGetEventsDone(UsageStatsDatabase::Error::kNoError, - ElementsAre(EqualsWebsiteEvent(event1)))); - usage_stats_database()->QueryEventsInRange( 0, 9, base::BindOnce(&UsageStatsDatabaseTest::OnGetEventsDone, base::Unretained(this))); + EXPECT_CALL(*this, OnGetEventsDone(UsageStatsDatabase::Error::kNoError, + ElementsAre(EqualsWebsiteEvent(event1)))); + fake_website_event_db()->LoadCallback(true); } TEST_F(UsageStatsDatabaseTest, AddAndDeleteAllEvents) { + fake_website_event_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + // Add 1 event. WebsiteEvent event1 = CreateWebsiteEvent(kFqdn1, 1, WebsiteEvent::START_BROWSING); std::vector<WebsiteEvent> events({event1}); - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); - usage_stats_database()->AddEvents( events, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_website_event_db()->UpdateCallback(true); // Delete all events. - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); - usage_stats_database()->DeleteAllEvents(base::BindOnce( &UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_website_event_db()->UpdateCallback(true); // Get all events (expecting none). - EXPECT_CALL(*this, OnGetEventsDone(UsageStatsDatabase::Error::kNoError, - ElementsAre())); - usage_stats_database()->GetAllEvents(base::BindOnce( &UsageStatsDatabaseTest::OnGetEventsDone, base::Unretained(this))); + EXPECT_CALL(*this, OnGetEventsDone(UsageStatsDatabase::Error::kNoError, + ElementsAre())); + fake_website_event_db()->LoadCallback(true); } TEST_F(UsageStatsDatabaseTest, AddAndDeleteEventsInRange) { + fake_website_event_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + // Add 3 events. WebsiteEvent event1 = CreateWebsiteEvent(kFqdn1, 1, WebsiteEvent::START_BROWSING); @@ -236,36 +266,39 @@ CreateWebsiteEvent(kFqdn1, 10, WebsiteEvent::START_BROWSING); std::vector<WebsiteEvent> events({event1, event2, event3}); - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); - usage_stats_database()->AddEvents( events, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_website_event_db()->UpdateCallback(true); // Delete events between time 1 (inclusive) and 10 (exclusive). - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); - usage_stats_database()->DeleteEventsInRange( 1, 10, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_website_event_db()->LoadCallback(true); fake_website_event_db()->UpdateCallback(true); // Get 1 remaining event outside range (at time 10). - EXPECT_CALL(*this, OnGetEventsDone(UsageStatsDatabase::Error::kNoError, - ElementsAre(EqualsWebsiteEvent(event3)))); - usage_stats_database()->GetAllEvents(base::BindOnce( &UsageStatsDatabaseTest::OnGetEventsDone, base::Unretained(this))); + EXPECT_CALL(*this, OnGetEventsDone(UsageStatsDatabase::Error::kNoError, + ElementsAre(EqualsWebsiteEvent(event3)))); + fake_website_event_db()->LoadCallback(true); } TEST_F(UsageStatsDatabaseTest, AddAndDeleteEventsMatchingDomain) { + fake_website_event_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + // Add 3 events. WebsiteEvent event1 = CreateWebsiteEvent(kFqdn1, 1, WebsiteEvent::START_BROWSING); @@ -275,253 +308,347 @@ CreateWebsiteEvent(kFqdn2, 1, WebsiteEvent::START_BROWSING); std::vector<WebsiteEvent> events({event1, event2, event3}); - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); - usage_stats_database()->AddEvents( events, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_website_event_db()->UpdateCallback(true); // Delete 2 events by FQDN. base::flat_set<std::string> domains({kFqdn1}); - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); usage_stats_database()->DeleteEventsWithMatchingDomains( domains, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_website_event_db()->UpdateCallback(true); // Get 1 remaining event with non-matching FQDN. + usage_stats_database()->GetAllEvents(base::BindOnce( + &UsageStatsDatabaseTest::OnGetEventsDone, base::Unretained(this))); + EXPECT_CALL(*this, OnGetEventsDone(UsageStatsDatabase::Error::kNoError, ElementsAre(EqualsWebsiteEvent(event3)))); + fake_website_event_db()->LoadCallback(true); +} + +TEST_F(UsageStatsDatabaseTest, GetAllEventsDeferred) { + // Don't complete the database initialization yet. + + // Make request to database. usage_stats_database()->GetAllEvents(base::BindOnce( &UsageStatsDatabaseTest::OnGetEventsDone, base::Unretained(this))); + // Expect callback to be run after initialization succeeds. + EXPECT_CALL(*this, OnGetEventsDone(UsageStatsDatabase::Error::kNoError, + ElementsAre())); + + fake_website_event_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + fake_website_event_db()->LoadCallback(true); } // Suspension Tests TEST_F(UsageStatsDatabaseTest, SetSuspensionsSuccess) { - base::flat_set<std::string> domains({kFqdn1, kFqdn2}); + fake_suspension_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + base::flat_set<std::string> domains({kFqdn1, kFqdn2}); usage_stats_database()->SetSuspensions( domains, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_suspension_db()->UpdateCallback(true); } TEST_F(UsageStatsDatabaseTest, SetSuspensionsFailure) { - base::flat_set<std::string> domains({kFqdn1, kFqdn2}); + fake_suspension_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kUnknownError)); + base::flat_set<std::string> domains({kFqdn1, kFqdn2}); usage_stats_database()->SetSuspensions( domains, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kUnknownError)); + fake_suspension_db()->UpdateCallback(false); } TEST_F(UsageStatsDatabaseTest, GetAllSuspensionsSuccess) { + fake_suspension_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + std::vector<std::string> expected; - EXPECT_CALL(*this, OnGetAllSuspensionsDone( - UsageStatsDatabase::Error::kNoError, expected)); + usage_stats_database()->GetAllSuspensions(base::BindOnce( + &UsageStatsDatabaseTest::OnGetSuspensionsDone, base::Unretained(this))); - usage_stats_database()->GetAllSuspensions( - base::BindOnce(&UsageStatsDatabaseTest::OnGetAllSuspensionsDone, - base::Unretained(this))); + EXPECT_CALL(*this, OnGetSuspensionsDone(UsageStatsDatabase::Error::kNoError, + expected)); fake_suspension_db()->LoadCallback(true); } TEST_F(UsageStatsDatabaseTest, GetAllSuspensionsFailure) { + fake_suspension_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + std::vector<std::string> expected; - EXPECT_CALL(*this, OnGetAllSuspensionsDone( - UsageStatsDatabase::Error::kUnknownError, expected)); + usage_stats_database()->GetAllSuspensions(base::BindOnce( + &UsageStatsDatabaseTest::OnGetSuspensionsDone, base::Unretained(this))); - usage_stats_database()->GetAllSuspensions( - base::BindOnce(&UsageStatsDatabaseTest::OnGetAllSuspensionsDone, - base::Unretained(this))); + EXPECT_CALL(*this, OnGetSuspensionsDone( + UsageStatsDatabase::Error::kUnknownError, expected)); fake_suspension_db()->LoadCallback(false); } TEST_F(UsageStatsDatabaseTest, SetAndGetSuspension) { + fake_suspension_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + // Insert 1 suspension. base::flat_set<std::string> domains({kFqdn1}); - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); - usage_stats_database()->SetSuspensions( domains, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_suspension_db()->UpdateCallback(true); // Get 1 suspension. std::vector<std::string> expected({kFqdn1}); - EXPECT_CALL(*this, OnGetAllSuspensionsDone( - UsageStatsDatabase::Error::kNoError, expected)); + usage_stats_database()->GetAllSuspensions(base::BindOnce( + &UsageStatsDatabaseTest::OnGetSuspensionsDone, base::Unretained(this))); - usage_stats_database()->GetAllSuspensions( - base::BindOnce(&UsageStatsDatabaseTest::OnGetAllSuspensionsDone, - base::Unretained(this))); + EXPECT_CALL(*this, OnGetSuspensionsDone(UsageStatsDatabase::Error::kNoError, + expected)); fake_suspension_db()->LoadCallback(true); } TEST_F(UsageStatsDatabaseTest, SetRemoveAndGetSuspension) { + fake_suspension_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + // Insert 2 suspensions. base::flat_set<std::string> domains1({kFqdn1, kFqdn2}); - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); - usage_stats_database()->SetSuspensions( domains1, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_suspension_db()->UpdateCallback(true); // Insert 1 suspension, and remove the other. base::flat_set<std::string> domains2({kFqdn1}); - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); - usage_stats_database()->SetSuspensions( domains2, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_suspension_db()->UpdateCallback(true); // Get 1 suspension. std::vector<std::string> expected({kFqdn1}); - EXPECT_CALL(*this, OnGetAllSuspensionsDone( - UsageStatsDatabase::Error::kNoError, expected)); + usage_stats_database()->GetAllSuspensions(base::BindOnce( + &UsageStatsDatabaseTest::OnGetSuspensionsDone, base::Unretained(this))); - usage_stats_database()->GetAllSuspensions( - base::BindOnce(&UsageStatsDatabaseTest::OnGetAllSuspensionsDone, - base::Unretained(this))); + EXPECT_CALL(*this, OnGetSuspensionsDone(UsageStatsDatabase::Error::kNoError, + expected)); + + fake_suspension_db()->LoadCallback(true); +} + +TEST_F(UsageStatsDatabaseTest, SetAndGetSuspensionDeferred) { + // Fail to initialize the database. + fake_suspension_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kError); + + // Insert 1 suspension. + base::flat_set<std::string> domains({kFqdn1}); + + usage_stats_database()->SetSuspensions( + domains, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, + base::Unretained(this))); + + // Get 1 suspension. + std::vector<std::string> expected({kFqdn1}); + + usage_stats_database()->GetAllSuspensions(base::BindOnce( + &UsageStatsDatabaseTest::OnGetSuspensionsDone, base::Unretained(this))); + + // Now successfully initialize database, and expect previous callbacks to be + // run. + fake_suspension_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + + fake_suspension_db()->UpdateCallback(true); + + EXPECT_CALL(*this, OnGetSuspensionsDone(UsageStatsDatabase::Error::kNoError, + expected)); fake_suspension_db()->LoadCallback(true); } // Token Mapping Tests - TEST_F(UsageStatsDatabaseTest, SetTokenMappingsSuccess) { - UsageStatsDatabase::TokenMap mappings({{kToken1, kFqdn1}, {kToken2, kFqdn2}}); + fake_token_mapping_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + UsageStatsDatabase::TokenMap mappings({{kToken1, kFqdn1}, {kToken2, kFqdn2}}); usage_stats_database()->SetTokenMappings( mappings, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_token_mapping_db()->UpdateCallback(true); } TEST_F(UsageStatsDatabaseTest, SetTokenMappingsFailure) { - UsageStatsDatabase::TokenMap mappings({{kToken1, kFqdn1}, {kToken2, kFqdn2}}); + fake_token_mapping_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kUnknownError)); + UsageStatsDatabase::TokenMap mappings({{kToken1, kFqdn1}, {kToken2, kFqdn2}}); usage_stats_database()->SetTokenMappings( mappings, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kUnknownError)); + fake_token_mapping_db()->UpdateCallback(false); } TEST_F(UsageStatsDatabaseTest, GetAllTokenMappingsSuccess) { + fake_token_mapping_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + UsageStatsDatabase::TokenMap expected; - EXPECT_CALL(*this, OnGetAllTokenMappingsDone( - UsageStatsDatabase::Error::kNoError, expected)); + usage_stats_database()->GetAllTokenMappings(base::BindOnce( + &UsageStatsDatabaseTest::OnGetTokenMappingsDone, base::Unretained(this))); - usage_stats_database()->GetAllTokenMappings( - base::BindOnce(&UsageStatsDatabaseTest::OnGetAllTokenMappingsDone, - base::Unretained(this))); + EXPECT_CALL(*this, OnGetTokenMappingsDone(UsageStatsDatabase::Error::kNoError, + expected)); fake_token_mapping_db()->LoadCallback(true); } TEST_F(UsageStatsDatabaseTest, GetAllTokenMappingsFailure) { + fake_token_mapping_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + UsageStatsDatabase::TokenMap expected; - EXPECT_CALL(*this, OnGetAllTokenMappingsDone( - UsageStatsDatabase::Error::kUnknownError, expected)); + usage_stats_database()->GetAllTokenMappings(base::BindOnce( + &UsageStatsDatabaseTest::OnGetTokenMappingsDone, base::Unretained(this))); - usage_stats_database()->GetAllTokenMappings( - base::BindOnce(&UsageStatsDatabaseTest::OnGetAllTokenMappingsDone, - base::Unretained(this))); + EXPECT_CALL(*this, OnGetTokenMappingsDone( + UsageStatsDatabase::Error::kUnknownError, expected)); fake_token_mapping_db()->LoadCallback(false); } TEST_F(UsageStatsDatabaseTest, SetAndGetTokenMapping) { + fake_token_mapping_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + UsageStatsDatabase::TokenMap mapping({{kToken1, kFqdn1}}); // Insert 1 token mapping. - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); - usage_stats_database()->SetTokenMappings( mapping, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_token_mapping_db()->UpdateCallback(true); // Get 1 token mapping. - EXPECT_CALL(*this, OnGetAllTokenMappingsDone( - UsageStatsDatabase::Error::kNoError, mapping)); + usage_stats_database()->GetAllTokenMappings(base::BindOnce( + &UsageStatsDatabaseTest::OnGetTokenMappingsDone, base::Unretained(this))); - usage_stats_database()->GetAllTokenMappings( - base::BindOnce(&UsageStatsDatabaseTest::OnGetAllTokenMappingsDone, - base::Unretained(this))); + EXPECT_CALL(*this, OnGetTokenMappingsDone(UsageStatsDatabase::Error::kNoError, + mapping)); fake_token_mapping_db()->LoadCallback(true); } TEST_F(UsageStatsDatabaseTest, SetRemoveAndGetTokenMapping) { + fake_token_mapping_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kOK); + // Insert 2 token mappings. UsageStatsDatabase::TokenMap mappings1( {{kToken1, kFqdn1}, {kToken2, kFqdn2}}); - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); - usage_stats_database()->SetTokenMappings( mappings1, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_token_mapping_db()->UpdateCallback(true); // Re-insert 1 token mapping, and remove the other.apping) { UsageStatsDatabase::TokenMap mappings2({{kToken1, kFqdn1}}); - EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); - usage_stats_database()->SetTokenMappings( mappings2, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, base::Unretained(this))); + EXPECT_CALL(*this, OnUpdateDone(UsageStatsDatabase::Error::kNoError)); + fake_token_mapping_db()->UpdateCallback(true); // Get 1 remaining token mapping. - EXPECT_CALL(*this, OnGetAllTokenMappingsDone( - UsageStatsDatabase::Error::kNoError, mappings2)); + usage_stats_database()->GetAllTokenMappings(base::BindOnce( + &UsageStatsDatabaseTest::OnGetTokenMappingsDone, base::Unretained(this))); - usage_stats_database()->GetAllTokenMappings( - base::BindOnce(&UsageStatsDatabaseTest::OnGetAllTokenMappingsDone, - base::Unretained(this))); + EXPECT_CALL(*this, OnGetTokenMappingsDone(UsageStatsDatabase::Error::kNoError, + mappings2)); fake_token_mapping_db()->LoadCallback(true); } + +TEST_F(UsageStatsDatabaseTest, SetTokenMappingsUninitialized) { + // Fail to initialize database. + fake_token_mapping_db()->InitStatusCallback( + leveldb_proto::Enums::InitStatus::kError); + + UsageStatsDatabase::TokenMap mappings({{kToken1, kFqdn1}, {kToken2, kFqdn2}}); + + // Expect callback will not be run. + EXPECT_CALL(*this, OnUpdateDone).Times(0); + + usage_stats_database()->SetTokenMappings( + mappings, base::BindOnce(&UsageStatsDatabaseTest::OnUpdateDone, + base::Unretained(this))); +} + } // namespace usage_stats
diff --git a/chrome/browser/android/webapk/webapk_icon_hasher.cc b/chrome/browser/android/webapk/webapk_icon_hasher.cc index 85483b81..0ead7442 100644 --- a/chrome/browser/android/webapk/webapk_icon_hasher.cc +++ b/chrome/browser/android/webapk/webapk_icon_hasher.cc
@@ -52,7 +52,7 @@ const Murmur2HashCallback& callback) { if (!icon_url.is_valid()) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, - base::Bind(callback, "")); + base::BindOnce(callback, "")); return; } @@ -63,8 +63,8 @@ !data.empty()) { hash = ComputeMurmur2Hash(data); } - base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, - base::Bind(callback, hash)); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(callback, hash)); return; }
diff --git a/chrome/browser/android/webapk/webapk_installer_unittest.cc b/chrome/browser/android/webapk/webapk_installer_unittest.cc index 776d530..a679e32 100644 --- a/chrome/browser/android/webapk/webapk_installer_unittest.cc +++ b/chrome/browser/android/webapk/webapk_installer_unittest.cc
@@ -75,8 +75,8 @@ void PostTaskToRunSuccessCallback() { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&TestWebApkInstaller::OnResult, base::Unretained(this), - WebApkInstallResult::SUCCESS)); + base::BindOnce(&TestWebApkInstaller::OnResult, base::Unretained(this), + WebApkInstallResult::SUCCESS)); } private:
diff --git a/chrome/browser/android/webapk/webapk_update_manager.cc b/chrome/browser/android/webapk/webapk_update_manager.cc index 96da1fd..cbbf307 100644 --- a/chrome/browser/android/webapk/webapk_update_manager.cc +++ b/chrome/browser/android/webapk/webapk_update_manager.cc
@@ -155,8 +155,8 @@ if (profile == nullptr) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&OnUpdated, callback_ref, WebApkInstallResult::FAILURE, - false /* relax_updates */, "" /* webapk_package */)); + base::BindOnce(&OnUpdated, callback_ref, WebApkInstallResult::FAILURE, + false /* relax_updates */, "" /* webapk_package */)); return; }
diff --git a/chrome/browser/apps/app_shim/app_shim_handler_mac.cc b/chrome/browser/apps/app_shim/app_shim_handler_mac.cc index 7a279c5..8263894 100644 --- a/chrome/browser/apps/app_shim/app_shim_handler_mac.cc +++ b/chrome/browser/apps/app_shim/app_shim_handler_mac.cc
@@ -69,7 +69,7 @@ // Post this to give AppWindows a chance to remove themselves from the // registry. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&TerminateIfNoAppWindows)); + FROM_HERE, base::BindOnce(&TerminateIfNoAppWindows)); } }
diff --git a/chrome/browser/apps/app_shim/app_shim_host_manager_mac.mm b/chrome/browser/apps/app_shim/app_shim_host_manager_mac.mm index e9a0e6c..7412671 100644 --- a/chrome/browser/apps/app_shim/app_shim_host_manager_mac.mm +++ b/chrome/browser/apps/app_shim/app_shim_host_manager_mac.mm
@@ -141,7 +141,7 @@ base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO}) ->PostTask(FROM_HERE, - base::Bind(&AppShimHostManager::ListenOnIOThread, this)); + base::BindOnce(&AppShimHostManager::ListenOnIOThread, this)); } void AppShimHostManager::ListenOnIOThread() { @@ -149,7 +149,7 @@ if (!acceptor_->Listen()) { base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::UI}) ->PostTask(FROM_HERE, - base::Bind(&AppShimHostManager::OnListenError, this)); + base::BindOnce(&AppShimHostManager::OnListenError, this)); } }
diff --git a/chrome/browser/background/background_contents_service_unittest.cc b/chrome/browser/background/background_contents_service_unittest.cc index 0f93b24..8ebc2aa 100644 --- a/chrome/browser/background/background_contents_service_unittest.cc +++ b/chrome/browser/background/background_contents_service_unittest.cc
@@ -168,8 +168,7 @@ TEST_F(BackgroundContentsServiceTest, BackgroundContentsUrlAdded) { TestingProfile profile; BackgroundContentsService service(&profile, command_line_.get()); - BackgroundContentsServiceFactory::GetInstance() - ->RegisterUserPrefsOnBrowserContextForTest(&profile); + GURL orig_url; GURL url("http://a/"); GURL url2("http://a/"); @@ -195,8 +194,6 @@ TEST_F(BackgroundContentsServiceTest, BackgroundContentsUrlAddedAndClosed) { TestingProfile profile; BackgroundContentsService service(&profile, command_line_.get()); - BackgroundContentsServiceFactory::GetInstance() - ->RegisterUserPrefsOnBrowserContextForTest(&profile); GURL url("http://a/"); MockBackgroundContents* contents = new MockBackgroundContents(&profile); @@ -216,8 +213,6 @@ TEST_F(BackgroundContentsServiceTest, RestartBackgroundContents) { TestingProfile profile; BackgroundContentsService service(&profile, command_line_.get()); - BackgroundContentsServiceFactory::GetInstance() - ->RegisterUserPrefsOnBrowserContextForTest(&profile); GURL url("http://a/"); { @@ -248,8 +243,6 @@ TEST_F(BackgroundContentsServiceTest, TestApplicationIDLinkage) { TestingProfile profile; BackgroundContentsService service(&profile, command_line_.get()); - BackgroundContentsServiceFactory::GetInstance() - ->RegisterUserPrefsOnBrowserContextForTest(&profile); EXPECT_EQ(NULL, service.GetAppBackgroundContents("appid")); MockBackgroundContents* contents =
diff --git a/chrome/browser/background/background_mode_manager_mac.mm b/chrome/browser/background/background_mode_manager_mac.mm index da5ef40..6765e10 100644 --- a/chrome/browser/background/background_mode_manager_mac.mm +++ b/chrome/browser/background/background_mode_manager_mac.mm
@@ -119,14 +119,15 @@ // a new one - just check to see if the user removed it so we don't // ever create another one. task_runner_->PostTask( - FROM_HERE, base::Bind(CheckForUserRemovedLoginItemOnWorkerThread)); + FROM_HERE, + base::BindOnce(CheckForUserRemovedLoginItemOnWorkerThread)); } else { bool need_migration = !service->GetBoolean( prefs::kMigratedLoginItemPref); service->SetBoolean(prefs::kMigratedLoginItemPref, true); task_runner_->PostTask( FROM_HERE, - base::Bind(EnableLaunchOnStartupOnWorkerThread, need_migration)); + base::BindOnce(EnableLaunchOnStartupOnWorkerThread, need_migration)); } } else { PrefService* service = g_browser_process->local_state(); @@ -140,12 +141,12 @@ // If the user removed our login item, note this so we don't ever create // another one. task_runner_->PostTask( - FROM_HERE, base::Bind(CheckForUserRemovedLoginItemOnWorkerThread)); + FROM_HERE, base::BindOnce(CheckForUserRemovedLoginItemOnWorkerThread)); // Call to the File thread to remove the login item since it requires // accessing the disk. - task_runner_->PostTask(FROM_HERE, - base::Bind(DisableLaunchOnStartupOnWorkerThread)); + task_runner_->PostTask( + FROM_HERE, base::BindOnce(DisableLaunchOnStartupOnWorkerThread)); } }
diff --git a/chrome/browser/browser_process_impl.cc b/chrome/browser/browser_process_impl.cc index 3123425..27092f63 100644 --- a/chrome/browser/browser_process_impl.cc +++ b/chrome/browser/browser_process_impl.cc
@@ -1458,7 +1458,8 @@ #if defined(OS_MACOSX) base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop)); + FROM_HERE, + base::BindOnce(ChromeBrowserMainPartsMac::DidEndMainMessageLoop)); #endif #if !defined(OS_ANDROID)
diff --git a/chrome/browser/chromeos/certificate_provider/certificate_provider_service.cc b/chrome/browser/chromeos/certificate_provider/certificate_provider_service.cc index 9c38dc4..03c2d0f 100644 --- a/chrome/browser/chromeos/certificate_provider/certificate_provider_service.cc +++ b/chrome/browser/chromeos/certificate_provider/certificate_provider_service.cc
@@ -201,8 +201,8 @@ base::Bind(&PostIdentitiesToTaskRunner, source_task_runner, callback); service_task_runner_->PostTask( - FROM_HERE, base::Bind(&GetCertificatesOnServiceThread, service_, - callback_from_service_thread)); + FROM_HERE, base::BindOnce(&GetCertificatesOnServiceThread, service_, + callback_from_service_thread)); } std::unique_ptr<CertificateProvider>
diff --git a/chrome/browser/chromeos/fileapi/external_file_url_request_job.cc b/chrome/browser/chromeos/fileapi/external_file_url_request_job.cc index 392a10d..9eff600 100644 --- a/chrome/browser/chromeos/fileapi/external_file_url_request_job.cc +++ b/chrome/browser/chromeos/fileapi/external_file_url_request_job.cc
@@ -35,8 +35,8 @@ // delegate, because NotifyStartError is not legal to call synchronously in // Start(). base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&ExternalFileURLRequestJob::StartAsync, - weak_ptr_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&ExternalFileURLRequestJob::StartAsync, + weak_ptr_factory_.GetWeakPtr())); } void ExternalFileURLRequestJob::StartAsync() {
diff --git a/chrome/browser/chromeos/first_run/drive_first_run_controller.cc b/chrome/browser/chromeos/first_run/drive_first_run_controller.cc index bcf65ed..855caba9 100644 --- a/chrome/browser/chromeos/first_run/drive_first_run_controller.cc +++ b/chrome/browser/chromeos/first_run/drive_first_run_controller.cc
@@ -204,8 +204,8 @@ // of a call stack for some routine of the contained WebContents. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&DriveWebContentsManager::RunCompletionCallback, - weak_ptr_factory_.GetWeakPtr(), success, outcome)); + base::BindOnce(&DriveWebContentsManager::RunCompletionCallback, + weak_ptr_factory_.GetWeakPtr(), success, outcome)); StopLoad(); } }
diff --git a/chrome/browser/chromeos/first_run/goodies_displayer.cc b/chrome/browser/chromeos/first_run/goodies_displayer.cc index 181e8e8..79425c0 100644 --- a/chrome/browser/chromeos/first_run/goodies_displayer.cc +++ b/chrome/browser/chromeos/first_run/goodies_displayer.cc
@@ -140,7 +140,8 @@ } // Regardless of how we got here, we don't henceforth need to show Goodies. - base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(&Delete)); + base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, + base::BindOnce(&Delete)); } GoodiesDisplayerTestInfo::GoodiesDisplayerTestInfo()
diff --git a/chrome/browser/chromeos/lock_screen_apps/app_manager_impl.cc b/chrome/browser/chromeos/lock_screen_apps/app_manager_impl.cc index 2c4174b9..ff1205e 100644 --- a/chrome/browser/chromeos/lock_screen_apps/app_manager_impl.cc +++ b/chrome/browser/chromeos/lock_screen_apps/app_manager_impl.cc
@@ -95,7 +95,7 @@ const ExtensionCallback& callback, const scoped_refptr<base::SequencedTaskRunner>& task_runner, const scoped_refptr<const extensions::Extension>& extension) { - task_runner->PostTask(FROM_HERE, base::Bind(callback, extension)); + task_runner->PostTask(FROM_HERE, base::BindOnce(callback, extension)); } // Loads extension with the provided |extension_id|, |location|, and @@ -426,7 +426,7 @@ extensions::GetExtensionFileTaskRunner()->PostTask( FROM_HERE, - base::Bind( + base::BindOnce( &InstallExtensionCopy, lock_profile_app, app->path(), lock_screen_service->install_directory(), lock_screen_profile_, base::Bind(&InvokeCallbackOnTaskRunner,
diff --git a/chrome/browser/chromeos/lock_screen_apps/first_app_run_toast_manager.cc b/chrome/browser/chromeos/lock_screen_apps/first_app_run_toast_manager.cc index 0824c4a3..7ea1c632 100644 --- a/chrome/browser/chromeos/lock_screen_apps/first_app_run_toast_manager.cc +++ b/chrome/browser/chromeos/lock_screen_apps/first_app_run_toast_manager.cc
@@ -130,8 +130,8 @@ // activation completes. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&FirstAppRunToastManager::CreateAndShowToastDialog, - weak_ptr_factory_.GetWeakPtr())); + base::BindOnce(&FirstAppRunToastManager::CreateAndShowToastDialog, + weak_ptr_factory_.GetWeakPtr())); } }
diff --git a/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc b/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc index 0be14eb..9398291 100644 --- a/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc +++ b/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc
@@ -125,7 +125,7 @@ base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); task_runner->PostTask( FROM_HERE, - base::Bind( + base::BindOnce( &LoadPrivateKeyByPublicKeyOnWorkerThread, owner_key_util, base::Passed(crypto::GetPublicSlotForChromeOSUser(username_hash)), base::Passed(std::move(private_slot)), callback));
diff --git a/chrome/browser/chromeos/power/freezer_cgroup_process_manager.cc b/chrome/browser/chromeos/power/freezer_cgroup_process_manager.cc index 69cf8a6..cbf3c8c 100644 --- a/chrome/browser/chromeos/power/freezer_cgroup_process_manager.cc +++ b/chrome/browser/chromeos/power/freezer_cgroup_process_manager.cc
@@ -112,13 +112,13 @@ if (!result && !froze_successfully_) result = true; - ui_thread_->PostTask(FROM_HERE, base::Bind(callback, result)); + ui_thread_->PostTask(FROM_HERE, base::BindOnce(callback, result)); } void CheckCanFreezeRenderers(ResultCallback callback) { DCHECK(file_thread_->RunsTasksInCurrentSequence()); - ui_thread_->PostTask(FROM_HERE, base::Bind(callback, enabled_)); + ui_thread_->PostTask(FROM_HERE, base::BindOnce(callback, enabled_)); } private: @@ -160,9 +160,9 @@ : file_thread_(base::CreateSequencedTaskRunnerWithTraits( {base::TaskPriority::BEST_EFFORT, base::MayBlock()})), file_worker_(new FileWorker(file_thread_)) { - file_thread_->PostTask(FROM_HERE, - base::Bind(&FileWorker::Start, - base::Unretained(file_worker_.get()))); + file_thread_->PostTask( + FROM_HERE, + base::BindOnce(&FileWorker::Start, base::Unretained(file_worker_.get()))); } FreezerCgroupProcessManager::~FreezerCgroupProcessManager() { @@ -172,31 +172,31 @@ void FreezerCgroupProcessManager::SetShouldFreezeRenderer( base::ProcessHandle handle, bool frozen) { - file_thread_->PostTask(FROM_HERE, - base::Bind(&FileWorker::SetShouldFreezeRenderer, - base::Unretained(file_worker_.get()), - handle, frozen)); + file_thread_->PostTask( + FROM_HERE, + base::BindOnce(&FileWorker::SetShouldFreezeRenderer, + base::Unretained(file_worker_.get()), handle, frozen)); } void FreezerCgroupProcessManager::FreezeRenderers() { file_thread_->PostTask(FROM_HERE, - base::Bind(&FileWorker::FreezeRenderers, - base::Unretained(file_worker_.get()))); + base::BindOnce(&FileWorker::FreezeRenderers, + base::Unretained(file_worker_.get()))); } void FreezerCgroupProcessManager::ThawRenderers(ResultCallback callback) { - file_thread_->PostTask(FROM_HERE, - base::Bind(&FileWorker::ThawRenderers, - base::Unretained(file_worker_.get()), - callback)); + file_thread_->PostTask( + FROM_HERE, + base::BindOnce(&FileWorker::ThawRenderers, + base::Unretained(file_worker_.get()), callback)); } void FreezerCgroupProcessManager::CheckCanFreezeRenderers( ResultCallback callback) { - file_thread_->PostTask(FROM_HERE, - base::Bind(&FileWorker::CheckCanFreezeRenderers, - base::Unretained(file_worker_.get()), - callback)); + file_thread_->PostTask( + FROM_HERE, + base::BindOnce(&FileWorker::CheckCanFreezeRenderers, + base::Unretained(file_worker_.get()), callback)); } } // namespace chromeos
diff --git a/chrome/browser/chromeos/printing/cups_print_job_manager_impl.cc b/chrome/browser/chromeos/printing/cups_print_job_manager_impl.cc index bbb7c03..e4908e3 100644 --- a/chrome/browser/chromeos/printing/cups_print_job_manager_impl.cc +++ b/chrome/browser/chromeos/printing/cups_print_job_manager_impl.cc
@@ -350,8 +350,9 @@ // Run a query now. base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::UI}) - ->PostTask(FROM_HERE, base::Bind(&CupsPrintJobManagerImpl::PostQuery, - weak_ptr_factory_.GetWeakPtr())); + ->PostTask(FROM_HERE, + base::BindOnce(&CupsPrintJobManagerImpl::PostQuery, + weak_ptr_factory_.GetWeakPtr())); // Start the timer for ongoing queries. ScheduleQuery();
diff --git a/chrome/browser/chromeos/printing/printer_configurer.cc b/chrome/browser/chromeos/printing/printer_configurer.cc index 598f23b..41821ea 100644 --- a/chrome/browser/chromeos/printing/printer_configurer.cc +++ b/chrome/browser/chromeos/printing/printer_configurer.cc
@@ -230,33 +230,31 @@ PrinterSetupCallback cb, const std::string& ppd_contents, const std::vector<std::string>& ppd_filters) { - if (base::FeatureList::IsEnabled(features::kCrOSComponent)) { - std::set<std::string> components_requested; - for (const auto& ppd_filter : ppd_filters) { - for (const auto& component : GetComponentizedFilters()) { - if (component.first == ppd_filter) { - components_requested.insert(component.second); - } + std::set<std::string> components_requested; + for (const auto& ppd_filter : ppd_filters) { + for (const auto& component : GetComponentizedFilters()) { + if (component.first == ppd_filter) { + components_requested.insert(component.second); } } - if (components_requested.size() == 1) { - // Only allow one filter request in ppd file. - auto& component_name = *components_requested.begin(); - g_browser_process->platform_part()->cros_component_manager()->Load( - component_name, - component_updater::CrOSComponentManager::MountPolicy::kMount, - component_updater::CrOSComponentManager::UpdatePolicy::kDontForce, - base::BindOnce(&PrinterConfigurerImpl::OnComponentLoad, - weak_factory_.GetWeakPtr(), printer, ppd_contents, - std::move(cb))); - return; - } - if (components_requested.size() > 1) { - PRINTER_LOG(ERROR) << printer.make_and_model() - << " More than one filter component is requested."; - std::move(cb).Run(PrinterSetupResult::kFatalError); - return; - } + } + if (components_requested.size() == 1) { + // Only allow one filter request in ppd file. + auto& component_name = *components_requested.begin(); + g_browser_process->platform_part()->cros_component_manager()->Load( + component_name, + component_updater::CrOSComponentManager::MountPolicy::kMount, + component_updater::CrOSComponentManager::UpdatePolicy::kDontForce, + base::BindOnce(&PrinterConfigurerImpl::OnComponentLoad, + weak_factory_.GetWeakPtr(), printer, ppd_contents, + std::move(cb))); + return; + } + if (components_requested.size() > 1) { + PRINTER_LOG(ERROR) << printer.make_and_model() + << " More than one filter component is requested."; + std::move(cb).Run(PrinterSetupResult::kFatalError); + return; } AddPrinter(printer, ppd_contents, std::move(cb)); }
diff --git a/chrome/browser/chromeos/resource_reporter/resource_reporter.cc b/chrome/browser/chromeos/resource_reporter/resource_reporter.cc index 1579942..cb5c0f0 100644 --- a/chrome/browser/chromeos/resource_reporter/resource_reporter.cc +++ b/chrome/browser/chromeos/resource_reporter/resource_reporter.cc
@@ -192,7 +192,7 @@ // Schedule reporting the samples. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&ResourceReporter::ReportSamples, base::Unretained(this))); + base::BindOnce(&ResourceReporter::ReportSamples, base::Unretained(this))); } ResourceReporter::ResourceReporter()
diff --git a/chrome/browser/chromeos/settings/device_settings_service.cc b/chrome/browser/chromeos/settings/device_settings_service.cc index a6f9795..a62580a 100644 --- a/chrome/browser/chromeos/settings/device_settings_service.cc +++ b/chrome/browser/chromeos/settings/device_settings_service.cc
@@ -182,7 +182,7 @@ if (GetOwnershipStatus() != OWNERSHIP_UNKNOWN) { // Report status immediately. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, GetOwnershipStatus())); + FROM_HERE, base::BindOnce(callback, GetOwnershipStatus())); } else { // If the key hasn't been loaded yet, enqueue the callback to be fired when // the next SessionManagerOperation completes. If no operation is pending,
diff --git a/chrome/browser/chromeos/shutdown_policy_browsertest.cc b/chrome/browser/chromeos/shutdown_policy_browsertest.cc index 132a46c..a9610fbd 100644 --- a/chrome/browser/chromeos/shutdown_policy_browsertest.cc +++ b/chrome/browser/chromeos/shutdown_policy_browsertest.cc
@@ -297,7 +297,7 @@ // If the login display is still showing, exit gracefully. if (LoginDisplayHost::default_host()) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&chrome::AttemptExit)); + FROM_HERE, base::BindOnce(&chrome::AttemptExit)); RunUntilBrowserProcessQuits(); } }
diff --git a/chrome/browser/conflicts/module_database_win.cc b/chrome/browser/conflicts/module_database_win.cc index ba3560c..8e859d8 100644 --- a/chrome/browser/conflicts/module_database_win.cc +++ b/chrome/browser/conflicts/module_database_win.cc
@@ -172,9 +172,10 @@ // is never freed. if (!task_runner_->RunsTasksInCurrentSequence()) { task_runner_->PostTask( - FROM_HERE, base::Bind(&ModuleDatabase::OnModuleLoad, - base::Unretained(this), process_type, module_path, - module_size, module_time_date_stamp)); + FROM_HERE, + base::BindOnce(&ModuleDatabase::OnModuleLoad, base::Unretained(this), + process_type, module_path, module_size, + module_time_date_stamp)); return; }
diff --git a/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc b/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc index 1dd91fe..42db890 100644 --- a/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc +++ b/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc
@@ -154,9 +154,9 @@ // the result with a task to the current thread. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(registry->GetDefaultWebClientCallback(protocol), - force_os_failure_ ? shell_integration::NOT_DEFAULT - : shell_integration::IS_DEFAULT)); + base::BindOnce(registry->GetDefaultWebClientCallback(protocol), + force_os_failure_ ? shell_integration::NOT_DEFAULT + : shell_integration::IS_DEFAULT)); if (!force_os_failure_) os_registered_protocols_.insert(protocol);
diff --git a/chrome/browser/devtools/global_confirm_info_bar.cc b/chrome/browser/devtools/global_confirm_info_bar.cc index 9253e50..9299c90 100644 --- a/chrome/browser/devtools/global_confirm_info_bar.cc +++ b/chrome/browser/devtools/global_confirm_info_bar.cc
@@ -239,8 +239,8 @@ is_closing_ = true; base::SequencedTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&GlobalConfirmInfoBar::Close, weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&GlobalConfirmInfoBar::Close, + weak_factory_.GetWeakPtr())); } return; }
diff --git a/chrome/browser/extensions/extension_assets_manager_chromeos.cc b/chrome/browser/extensions/extension_assets_manager_chromeos.cc index f134ff8d..3dedb626 100644 --- a/chrome/browser/extensions/extension_assets_manager_chromeos.cc +++ b/chrome/browser/extensions/extension_assets_manager_chromeos.cc
@@ -291,9 +291,9 @@ // user types. GetExtensionFileTaskRunner()->PostTask( FROM_HERE, - base::Bind(&ExtensionAssetsManagerChromeOS::InstallLocalExtension, id, - version, unpacked_extension_root, local_install_dir, - callback)); + base::BindOnce(&ExtensionAssetsManagerChromeOS::InstallLocalExtension, + id, version, unpacked_extension_root, local_install_dir, + callback)); return; } @@ -324,7 +324,7 @@ // unpacked_extension_root will be deleted by CrxInstaller. GetExtensionFileTaskRunner()->PostTask( - FROM_HERE, base::Bind(callback, base::FilePath(shared_path))); + FROM_HERE, base::BindOnce(callback, base::FilePath(shared_path))); } else { // Desired version is not found in shared location. ExtensionAssetsManagerHelper* helper = @@ -334,8 +334,9 @@ // There is no install in progress for given <id, version> so run install. GetExtensionFileTaskRunner()->PostTask( FROM_HERE, - base::Bind(&ExtensionAssetsManagerChromeOS::InstallSharedExtension, - id, version, unpacked_extension_root)); + base::BindOnce( + &ExtensionAssetsManagerChromeOS::InstallSharedExtension, id, + version, unpacked_extension_root)); } } } @@ -374,9 +375,9 @@ pending_installs[i]; GetExtensionFileTaskRunner()->PostTask( FROM_HERE, - base::Bind(&ExtensionAssetsManagerChromeOS::InstallLocalExtension, id, - version, info.unpacked_extension_root, - info.local_install_dir, info.callback)); + base::BindOnce(&ExtensionAssetsManagerChromeOS::InstallLocalExtension, + id, version, info.unpacked_extension_root, + info.local_install_dir, info.callback)); } return; } @@ -401,7 +402,7 @@ users->AppendString(info.profile->GetProfileUserName()); GetExtensionFileTaskRunner()->PostTask( - FROM_HERE, base::Bind(info.callback, shared_version_dir)); + FROM_HERE, base::BindOnce(info.callback, shared_version_dir)); } version_info->Set(kSharedExtensionUsers, std::move(users)); extension_info_weak->SetWithoutPathExpansion(version, @@ -463,8 +464,8 @@ } GetExtensionFileTaskRunner()->PostTask( FROM_HERE, - base::Bind(&ExtensionAssetsManagerChromeOS::DeleteSharedVersion, - base::FilePath(shared_path))); + base::BindOnce(&ExtensionAssetsManagerChromeOS::DeleteSharedVersion, + base::FilePath(shared_path))); extension_info->RemoveWithoutPathExpansion(*it, NULL); } }
diff --git a/chrome/browser/extensions/extension_garbage_collector_chromeos.cc b/chrome/browser/extensions/extension_garbage_collector_chromeos.cc index eaef677..8bad3cbc 100644 --- a/chrome/browser/extensions/extension_garbage_collector_chromeos.cc +++ b/chrome/browser/extensions/extension_garbage_collector_chromeos.cc
@@ -79,9 +79,10 @@ if (ExtensionAssetsManagerChromeOS::CleanUpSharedExtensions(&paths)) { if (!GetExtensionFileTaskRunner()->PostTask( FROM_HERE, - base::Bind(&GarbageCollectExtensionsOnFileThread, - ExtensionAssetsManagerChromeOS::GetSharedInstallDir(), - paths))) { + base::BindOnce( + &GarbageCollectExtensionsOnFileThread, + ExtensionAssetsManagerChromeOS::GetSharedInstallDir(), + paths))) { NOTREACHED(); } }
diff --git a/chrome/browser/extensions/updater/local_extension_cache.cc b/chrome/browser/extensions/updater/local_extension_cache.cc index a70b012..bc56766 100644 --- a/chrome/browser/extensions/updater/local_extension_cache.cc +++ b/chrome/browser/extensions/updater/local_extension_cache.cc
@@ -106,9 +106,9 @@ // If caller is not interested in file_path, extension is not used. base::Time now = base::Time::Now(); - backend_task_runner_->PostTask(FROM_HERE, - base::Bind(&LocalExtensionCache::BackendMarkFileUsed, - it->second.file_path, now)); + backend_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&LocalExtensionCache::BackendMarkFileUsed, + it->second.file_path, now)); it->second.last_used = now; } @@ -178,9 +178,9 @@ } backend_task_runner_->PostTask( - FROM_HERE, base::Bind(&LocalExtensionCache::BackendInstallCacheEntry, - weak_ptr_factory_.GetWeakPtr(), cache_dir_, id, - expected_hash, file_path, version, callback)); + FROM_HERE, base::BindOnce(&LocalExtensionCache::BackendInstallCacheEntry, + weak_ptr_factory_.GetWeakPtr(), cache_dir_, id, + expected_hash, file_path, version, callback)); } bool LocalExtensionCache::RemoveExtensionAt(const CacheMap::iterator& it, @@ -189,8 +189,8 @@ return false; std::string hash = match_hash ? it->second.expected_hash : std::string(); backend_task_runner_->PostTask( - FROM_HERE, base::Bind(&LocalExtensionCache::BackendRemoveCacheEntry, - cache_dir_, it->first, hash)); + FROM_HERE, base::BindOnce(&LocalExtensionCache::BackendRemoveCacheEntry, + cache_dir_, it->first, hash)); cached_extensions_.erase(it); return true; } @@ -244,10 +244,8 @@ backend_task_runner_->PostTask( FROM_HERE, - base::Bind(&LocalExtensionCache::BackendCheckCacheStatus, - weak_ptr_factory_.GetWeakPtr(), - cache_dir_, - callback)); + base::BindOnce(&LocalExtensionCache::BackendCheckCacheStatus, + weak_ptr_factory_.GetWeakPtr(), cache_dir_, callback)); } // static @@ -307,10 +305,8 @@ DCHECK_EQ(state_, kWaitInitialization); backend_task_runner_->PostTask( FROM_HERE, - base::Bind(&LocalExtensionCache::BackendCheckCacheContents, - weak_ptr_factory_.GetWeakPtr(), - cache_dir_, - callback)); + base::BindOnce(&LocalExtensionCache::BackendCheckCacheContents, + weak_ptr_factory_.GetWeakPtr(), cache_dir_, callback)); } // static
diff --git a/chrome/browser/first_run/first_run_internal_posix_browsertest.cc b/chrome/browser/first_run/first_run_internal_posix_browsertest.cc index 58d1ed89..34563ae 100644 --- a/chrome/browser/first_run/first_run_internal_posix_browsertest.cc +++ b/chrome/browser/first_run/first_run_internal_posix_browsertest.cc
@@ -55,8 +55,8 @@ void SetupNestedTask() { EXPECT_TRUE(base::SequencedTaskRunnerHandle::Get()); base::SequencedTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&FirstRunInternalPosixTest::InspectState, - base::Unretained(this))); + FROM_HERE, base::BindOnce(&FirstRunInternalPosixTest::InspectState, + base::Unretained(this))); } // A task queued up to run once the first-run dialog starts pumping messages
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 45cb427..4876b35b 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -98,11 +98,6 @@ "expiry_milestone": 76 }, { - "name": "android-payment-apps", - // "owners": [ "your-team" ], - "expiry_milestone": 76 - }, - { "name": "android-site-settings-ui-refresh", "owners": [ "hkamila" ], "expiry_milestone": 76 @@ -323,7 +318,7 @@ }, { "name": "calculate-native-win-occlusion", - // "owners": [ "your-team" ], + "owners": [ "davidbienvenu", "fdoray" ], "expiry_milestone": 76 }, { @@ -548,11 +543,6 @@ "expiry_milestone": 76 }, { - "name": "disable-cros-component", - // "owners": [ "your-team" ], - "expiry_milestone": 76 - }, - { "name": "disable-eol-notification", // "owners": [ "your-team" ], "expiry_milestone": 76 @@ -738,16 +728,6 @@ "expiry_milestone": 76 }, { - "name": "enable-android-pay-integration-v1", - // "owners": [ "your-team" ], - "expiry_milestone": 76 - }, - { - "name": "enable-android-pay-integration-v2", - // "owners": [ "your-team" ], - "expiry_milestone": 76 - }, - { "name": "enable-android-spellchecker", "owners": [ "timvolodine" ], "expiry_milestone": 76 @@ -1484,12 +1464,12 @@ }, { "name": "enable-ntp-asset-download-suggestions", - // "owners": [ "your-team" ], + "owners": [ "fgorski" ], "expiry_milestone": 76 }, { "name": "enable-ntp-bookmark-suggestions", - // "owners": [ "your-team" ], + "owners": [ "fgorski" ], "expiry_milestone": 76 }, { @@ -1499,22 +1479,22 @@ }, { "name": "enable-ntp-offline-page-download-suggestions", - // "owners": [ "your-team" ], + "owners": [ "fgorski" ], "expiry_milestone": 76 }, { "name": "enable-ntp-remote-suggestions", - // "owners": [ "your-team" ], + "owners": [ "fgorski" ], "expiry_milestone": 76 }, { "name": "enable-ntp-snippets-increased-visibility", - // "owners": [ "your-team" ], + "owners": [ "fgorski" ], "expiry_milestone": 76 }, { "name": "enable-ntp-suggestions-notifications", - // "owners": [ "your-team" ], + "owners": [ "fgorski" ], "expiry_milestone": 76 }, { @@ -1952,16 +1932,6 @@ "expiry_milestone": -1 }, { - "name": "enable-web-payments-method-section-order-v2", - // "owners": [ "your-team" ], - "expiry_milestone": 76 - }, - { - "name": "enable-web-payments-single-app-ui-skip", - // "owners": [ "your-team" ], - "expiry_milestone": 76 - }, - { "name": "enable-webassembly", "owners": [ "titzer", "wasm-team@google.com" ], "expiry_milestone": 72 @@ -2292,11 +2262,6 @@ "expiry_milestone": 74 }, { - "name": "just-in-time-service-worker-payment-app", - // "owners": [ "your-team" ], - "expiry_milestone": 76 - }, - { "name": "keep-prefetched-content-suggestions", // "owners": [ "your-team" ], "expiry_milestone": 76 @@ -2702,11 +2667,6 @@ "expiry_milestone": 76 }, { - "name": "pay-with-google-v1", - // "owners": [ "your-team" ], - "expiry_milestone": 76 - }, - { "name": "pdf-annotations", "owners": [ "dstockwell@google.com" ], "expiry_milestone": 76 @@ -2783,8 +2743,8 @@ }, { "name": "reduced-referrer-granularity", - // "owners": [ "your-team" ], - "expiry_milestone": 76 + "owners": [ "jochen", "mkwst" ], + "expiry_milestone": 78 }, { "name": "remove-ntp-fakebox", @@ -2837,11 +2797,6 @@ "expiry_milestone": 74 }, { - "name": "service-worker-payment-apps", - // "owners": [ "your-team" ], - "expiry_milestone": 76 - }, - { "name": "session-restore-prioritizes-background-use-cases", "owners": [ "chrisha" ], "expiry_milestone": 76 @@ -3199,21 +3154,11 @@ "expiry_milestone": 76 }, { - "name": "web-payments", - // "owners": [ "your-team" ], - "expiry_milestone": 76 - }, - { "name": "web-contents-occlusion", "owners": [ "davidbienvenu" ], "expiry_milestone": 77 }, { - "name": "web-payments-modifiers", - // "owners": [ "your-team" ], - "expiry_milestone": 76 - }, - { "name": "webrtc-unified-plan-by-default", // "owners": [ "your-team" ], "expiry_milestone": 76
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index d2853aa..0de0baf 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -376,12 +376,6 @@ "Enables enforcement of a single media session having audio focus at " "any one time. Requires #enable-media-session-service to be enabled too."; -const char kEnableWebPaymentsSingleAppUiSkipName[] = - "Enable Web Payments single app UI skip"; -const char kEnableWebPaymentsSingleAppUiSkipDescription[] = - "Enable Web Payments to skip showing its UI if the developer specifies a " - "single app."; - const char kEnableAutocompleteDataRetentionPolicyName[] = "Enable automatic cleanup of expired Autocomplete entries."; const char kEnableAutocompleteDataRetentionPolicyDescription[] = @@ -1211,12 +1205,6 @@ "conflict with the latest JavaScript features. This flag allows disabling " "support of those features for compatibility with such pages."; -const char kJustInTimeServiceWorkerPaymentAppName[] = - "Just-in-time service worker payment app"; -const char kJustInTimeServiceWorkerPaymentAppDescription[] = - "Allow crawling just-in-time service worker payment app when there is no " - "installed service worker payment app for a payment request."; - const char kKeepAliveRendererForKeepaliveRequestsName[] = "Keep a renderer alive for keepalive fetch requests"; const char kKeepAliveRendererForKeepaliveRequestsDescription[] = @@ -1691,10 +1679,6 @@ "Allows users to push tabs from Android devices to other synced " "devices, in order to easily transition those tabs to the new device "; -const char kServiceWorkerPaymentAppsName[] = "Service Worker payment apps"; -const char kServiceWorkerPaymentAppsDescription[] = - "Enable Service Worker applications to integrate as payment apps"; - const char kServiceWorkerImportedScriptUpdateCheckName[] = "Enable update check for service worker importScripts() resources"; const char kServiceWorkerImportedScriptUpdateCheckDescription[] = @@ -2055,17 +2039,6 @@ const char kWebMidiName[] = "Web MIDI API"; const char kWebMidiDescription[] = "Enable Web MIDI API experimental support."; -const char kWebPaymentsName[] = "Web Payments"; -const char kWebPaymentsDescription[] = - "Enable Web Payments API integration, a JavaScript API for merchants."; - -const char kWebPaymentsModifiersName[] = "Enable web payment modifiers"; -const char kWebPaymentsModifiersDescription[] = - "If the website provides modifiers in the payment request, show the custom " - "total for each payment instrument, update the shopping cart when " - "instruments are switched, and send modified payment method specific data " - "to the payment app."; - const char kWebrtcEchoCanceller3Name[] = "WebRTC Echo Canceller 3."; const char kWebrtcEchoCanceller3Description[] = "Experimental WebRTC echo canceller (AEC3)."; @@ -2210,10 +2183,6 @@ "Enables messaging in site permissions UI informing user when " "notifications are disabled for the entire app."; -const char kAndroidPaymentAppsName[] = "Android payment apps"; -const char kAndroidPaymentAppsDescription[] = - "Enable third party Android apps to integrate as payment apps"; - const char kAsyncDnsName[] = "Async DNS resolver"; const char kAsyncDnsDescription[] = "Enables the built-in DNS resolver."; @@ -2345,14 +2314,6 @@ const char kDownloadHomeV2Description[] = "Enables the new UI for download home"; -const char kEnableAndroidPayIntegrationV1Name[] = "Enable Android Pay v1"; -const char kEnableAndroidPayIntegrationV1Description[] = - "Enable integration with Android Pay using the first version of the API"; - -const char kEnableAndroidPayIntegrationV2Name[] = "Enable Android Pay v2"; -const char kEnableAndroidPayIntegrationV2Description[] = - "Enable integration with Android Pay using the second version of the API"; - const char kAutofillManualFallbackAndroidName[] = "Enable Autofill manual fallback for Addresses and Payments (Android)"; const char kAutofillManualFallbackAndroidDescription[] = @@ -2453,12 +2414,6 @@ const char kEnableWebNfcName[] = "WebNFC"; const char kEnableWebNfcDescription[] = "Enable WebNFC support."; -const char kEnableWebPaymentsMethodSectionOrderV2Name[] = - "Enable Web Payments method section order V2."; -const char kEnableWebPaymentsMethodSectionOrderV2Description[] = - "Enable this option to display payment method section above address " - "section instead of below it."; - const char kEphemeralTabName[] = "An Ephemeral Tab in an Overlay Panel"; const char kEphemeralTabDescription[] = "Enable a 'Preview page/image' at a linked page into an overlay."; @@ -2647,11 +2602,6 @@ "Enable storing recently visited pages locally for offline use. Requires " "Offline Pages to be enabled."; -const char kPayWithGoogleV1Name[] = "Pay with Google v1"; -const char kPayWithGoogleV1Description[] = - "Enable Pay with Google integration into Web Payments with API version " - "'1'."; - const char kProgressBarThrottleName[] = "Android progress update throttling."; const char kProgressBarThrottleDescription[] = "Limit the maximum progress update to make progress appear smoother."; @@ -3136,10 +3086,6 @@ "different captive portals. This enables opening captive portal " "authorization dialog in a separate window, which ignores proxy settings."; -const char kCrOSComponentName[] = "Chrome OS Component"; -const char kCrOSComponentDescription[] = - "Disable the use of componentized escpr CUPS filter."; - const char kCrOSContainerName[] = "Chrome OS Container"; const char kCrOSContainerDescription[] = "Enable the use of Chrome OS Container utility.";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 2587f718..f92ca09 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -575,9 +575,6 @@ extern const char kEnableWebAuthenticationCableSupportName[]; extern const char kEnableWebAuthenticationCableSupportDescription[]; -extern const char kEnableWebPaymentsSingleAppUiSkipName[]; -extern const char kEnableWebPaymentsSingleAppUiSkipDescription[]; - extern const char kEnableWebUsbName[]; extern const char kEnableWebUsbDescription[]; @@ -731,9 +728,6 @@ extern const char kJavascriptHarmonyShippingName[]; extern const char kJavascriptHarmonyShippingDescription[]; -extern const char kJustInTimeServiceWorkerPaymentAppName[]; -extern const char kJustInTimeServiceWorkerPaymentAppDescription[]; - extern const char kKeepAliveRendererForKeepaliveRequestsName[]; extern const char kKeepAliveRendererForKeepaliveRequestsDescription[]; @@ -1007,9 +1001,6 @@ extern const char kSendTabToSelfName[]; extern const char kSendTabToSelfDescription[]; -extern const char kServiceWorkerPaymentAppsName[]; -extern const char kServiceWorkerPaymentAppsDescription[]; - extern const char kServiceWorkerImportedScriptUpdateCheckName[]; extern const char kServiceWorkerImportedScriptUpdateCheckDescription[]; @@ -1221,12 +1212,6 @@ extern const char kWebMidiName[]; extern const char kWebMidiDescription[]; -extern const char kWebPaymentsName[]; -extern const char kWebPaymentsDescription[]; - -extern const char kWebPaymentsModifiersName[]; -extern const char kWebPaymentsModifiersDescription[]; - extern const char kWebrtcEchoCanceller3Name[]; extern const char kWebrtcEchoCanceller3Description[]; @@ -1305,9 +1290,6 @@ extern const char kAndroidAutofillAccessibilityName[]; extern const char kAndroidAutofillAccessibilityDescription[]; -extern const char kAndroidPaymentAppsName[]; -extern const char kAndroidPaymentAppsDescription[]; - extern const char kAndroidSurfaceControl[]; extern const char kAndroidSurfaceControlDescription[]; @@ -1392,12 +1374,6 @@ extern const char kDownloadHomeV2Name[]; extern const char kDownloadHomeV2Description[]; -extern const char kEnableAndroidPayIntegrationV1Name[]; -extern const char kEnableAndroidPayIntegrationV1Description[]; - -extern const char kEnableAndroidPayIntegrationV2Name[]; -extern const char kEnableAndroidPayIntegrationV2Description[]; - extern const char kAutofillManualFallbackAndroidName[]; extern const char kAutofillManualFallbackAndroidDescription[]; @@ -1452,9 +1428,6 @@ extern const char kEnableWebNfcName[]; extern const char kEnableWebNfcDescription[]; -extern const char kEnableWebPaymentsMethodSectionOrderV2Name[]; -extern const char kEnableWebPaymentsMethodSectionOrderV2Description[]; - extern const char kEphemeralTabName[]; extern const char kEphemeralTabDescription[]; @@ -1563,9 +1536,6 @@ extern const char kOffliningRecentPagesName[]; extern const char kOffliningRecentPagesDescription[]; -extern const char kPayWithGoogleV1Name[]; -extern const char kPayWithGoogleV1Description[]; - extern const char kProgressBarThrottleName[]; extern const char kProgressBarThrottleDescription[]; @@ -1876,9 +1846,6 @@ extern const char kCaptivePortalBypassProxyName[]; extern const char kCaptivePortalBypassProxyDescription[]; -extern const char kCrOSComponentName[]; -extern const char kCrOSComponentDescription[]; - extern const char kCrOSContainerName[]; extern const char kCrOSContainerDescription[];
diff --git a/chrome/browser/google/google_update_win.cc b/chrome/browser/google/google_update_win.cc index 6611ed9..dd2ff72b 100644 --- a/chrome/browser/google/google_update_win.cc +++ b/chrome/browser/google/google_update_win.cc
@@ -374,8 +374,8 @@ driver_ = new UpdateCheckDriver(locale, install_update_if_possible, elevation_window, delegate); driver_->task_runner_->PostTask( - FROM_HERE, base::Bind(&UpdateCheckDriver::BeginUpdateCheck, - base::Unretained(driver_))); + FROM_HERE, base::BindOnce(&UpdateCheckDriver::BeginUpdateCheck, + base::Unretained(driver_))); } else { driver_->AddDelegate(delegate); } @@ -462,8 +462,8 @@ if (SUCCEEDED(hresult)) { // Start polling. task_runner_->PostTask(FROM_HERE, - base::Bind(&UpdateCheckDriver::PollGoogleUpdate, - base::Unretained(this))); + base::BindOnce(&UpdateCheckDriver::PollGoogleUpdate, + base::Unretained(this))); return; } if (hresult == GOOPDATE_E_APP_USING_EXTERNAL_UPDATER) { @@ -471,8 +471,9 @@ if (allowed_retries_) { --allowed_retries_; task_runner_->PostDelayedTask( - FROM_HERE, base::Bind(&UpdateCheckDriver::BeginUpdateCheck, - base::Unretained(this)), + FROM_HERE, + base::BindOnce(&UpdateCheckDriver::BeginUpdateCheck, + base::Unretained(this)), base::TimeDelta::FromSeconds(kGoogleRetryIntervalSeconds)); return; } @@ -796,15 +797,16 @@ // It is safe to post this task with an unretained pointer since the task // is guaranteed to run before a subsequent DeleteSoon is handled. result_runner_->PostTask( - FROM_HERE, base::Bind(&UpdateCheckDriver::NotifyUpgradeProgress, - base::Unretained(this), last_reported_progress_, - new_version_)); + FROM_HERE, base::BindOnce(&UpdateCheckDriver::NotifyUpgradeProgress, + base::Unretained(this), + last_reported_progress_, new_version_)); } // Schedule the next check. task_runner_->PostDelayedTask( - FROM_HERE, base::Bind(&UpdateCheckDriver::PollGoogleUpdate, - base::Unretained(this)), + FROM_HERE, + base::BindOnce(&UpdateCheckDriver::PollGoogleUpdate, + base::Unretained(this)), base::TimeDelta::FromMilliseconds(kGoogleUpdatePollIntervalMs)); // Early return for this non-terminal state. return;
diff --git a/chrome/browser/history/android/android_provider_backend_unittest.cc b/chrome/browser/history/android/android_provider_backend_unittest.cc index 548a752..23852bd6 100644 --- a/chrome/browser/history/android/android_provider_backend_unittest.cc +++ b/chrome/browser/history/android/android_provider_backend_unittest.cc
@@ -301,9 +301,10 @@ // HistoryBackend will shutdown after that. { scoped_refptr<HistoryBackend> history_backend; - history_backend = new HistoryBackend(new AndroidProviderBackendDelegate(), - history_client_->CreateBackendClient(), - base::ThreadTaskRunnerHandle::Get()); + history_backend = base::MakeRefCounted<HistoryBackend>( + std::make_unique<AndroidProviderBackendDelegate>(), + history_client_->CreateBackendClient(), + base::ThreadTaskRunnerHandle::Get()); history_backend->Init(false, TestHistoryDatabaseParamsForPath(temp_dir_.GetPath())); history_backend->AddVisits(url1, visits1, history::SOURCE_SYNCED); @@ -438,9 +439,10 @@ // HistoryBackend will shutdown after that. { scoped_refptr<HistoryBackend> history_backend; - history_backend = new HistoryBackend(new AndroidProviderBackendDelegate(), - history_client_->CreateBackendClient(), - base::ThreadTaskRunnerHandle::Get()); + history_backend = base::MakeRefCounted<HistoryBackend>( + std::make_unique<AndroidProviderBackendDelegate>(), + history_client_->CreateBackendClient(), + base::ThreadTaskRunnerHandle::Get()); history_backend->Init(false, TestHistoryDatabaseParamsForPath(temp_dir_.GetPath())); history_backend->AddVisits(url1, visits1, history::SOURCE_SYNCED); @@ -1827,9 +1829,10 @@ // HistoryBackend will shutdown after that. { scoped_refptr<HistoryBackend> history_backend; - history_backend = new HistoryBackend(new AndroidProviderBackendDelegate(), - history_client_->CreateBackendClient(), - base::ThreadTaskRunnerHandle::Get()); + history_backend = base::MakeRefCounted<HistoryBackend>( + std::make_unique<AndroidProviderBackendDelegate>(), + history_client_->CreateBackendClient(), + base::ThreadTaskRunnerHandle::Get()); history_backend->Init(false, TestHistoryDatabaseParamsForPath(temp_dir_.GetPath())); history_backend->AddVisits(url1, visits1, history::SOURCE_SYNCED);
diff --git a/chrome/browser/local_discovery/service_discovery_client_mac.mm b/chrome/browser/local_discovery/service_discovery_client_mac.mm index bf78555..2fbb1d5e 100644 --- a/chrome/browser/local_discovery/service_discovery_client_mac.mm +++ b/chrome/browser/local_discovery/service_discovery_client_mac.mm
@@ -201,15 +201,15 @@ void ServiceWatcherImplMac::NetServiceBrowserContainer::Start() { service_discovery_runner_->PostTask( FROM_HERE, - base::Bind(&NetServiceBrowserContainer::StartOnDiscoveryThread, - weak_factory_.GetWeakPtr())); + base::BindOnce(&NetServiceBrowserContainer::StartOnDiscoveryThread, + weak_factory_.GetWeakPtr())); } void ServiceWatcherImplMac::NetServiceBrowserContainer::DiscoverNewServices() { service_discovery_runner_->PostTask( FROM_HERE, - base::Bind(&NetServiceBrowserContainer::DiscoverOnDiscoveryThread, - weak_factory_.GetWeakPtr())); + base::BindOnce(&NetServiceBrowserContainer::DiscoverOnDiscoveryThread, + weak_factory_.GetWeakPtr())); } void @@ -239,7 +239,8 @@ void ServiceWatcherImplMac::NetServiceBrowserContainer::OnServicesUpdate( ServiceWatcher::UpdateType update, const std::string& service) { - callback_runner_->PostTask(FROM_HERE, base::Bind(callback_, update, service)); + callback_runner_->PostTask(FROM_HERE, + base::BindOnce(callback_, update, service)); } void ServiceWatcherImplMac::NetServiceBrowserContainer::DeleteSoon() { @@ -317,8 +318,8 @@ void ServiceResolverImplMac::NetServiceContainer::StartResolving() { service_discovery_runner_->PostTask( FROM_HERE, - base::Bind(&NetServiceContainer::StartResolvingOnDiscoveryThread, - weak_factory_.GetWeakPtr())); + base::BindOnce(&NetServiceContainer::StartResolvingOnDiscoveryThread, + weak_factory_.GetWeakPtr())); } void ServiceResolverImplMac::NetServiceContainer::DeleteSoon() {
diff --git a/chrome/browser/local_discovery/service_discovery_device_lister.cc b/chrome/browser/local_discovery/service_discovery_device_lister.cc index c6fbe244..8a44b2b0 100644 --- a/chrome/browser/local_discovery/service_discovery_device_lister.cc +++ b/chrome/browser/local_discovery/service_discovery_device_lister.cc
@@ -103,9 +103,10 @@ // service to detect non-graceful shutdowns. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&ServiceDiscoveryDeviceListerImpl::OnServiceUpdated, - weak_factory_.GetWeakPtr(), ServiceWatcher::UPDATE_CHANGED, - service_description.service_name), + base::BindOnce(&ServiceDiscoveryDeviceListerImpl::OnServiceUpdated, + weak_factory_.GetWeakPtr(), + ServiceWatcher::UPDATE_CHANGED, + service_description.service_name), base::TimeDelta::FromSeconds(kMacServiceResolvingIntervalSecs)); #endif } else {
diff --git a/chrome/browser/media_galleries/win/mtp_device_delegate_impl_win.cc b/chrome/browser/media_galleries/win/mtp_device_delegate_impl_win.cc index c79f0b2..73d2f6f 100644 --- a/chrome/browser/media_galleries/win/mtp_device_delegate_impl_win.cc +++ b/chrome/browser/media_galleries/win/mtp_device_delegate_impl_win.cc
@@ -531,9 +531,8 @@ PortableDeviceMapService::GetInstance()->MarkPortableDeviceForDeletion( storage_device_info_.registered_device_path); media_task_runner_->PostTask( - FROM_HERE, - base::Bind(&DeletePortableDeviceOnBlockingPoolThread, - storage_device_info_.registered_device_path)); + FROM_HERE, base::BindOnce(&DeletePortableDeviceOnBlockingPoolThread, + storage_device_info_.registered_device_path)); while (!pending_tasks_.empty()) pending_tasks_.pop(); delete this;
diff --git a/chrome/browser/metrics/perf/DEPS b/chrome/browser/metrics/perf/DEPS index 9666bd8..d6abddad 100644 --- a/chrome/browser/metrics/perf/DEPS +++ b/chrome/browser/metrics/perf/DEPS
@@ -1,4 +1,3 @@ include_rules = [ "+dbus", ] -
diff --git a/chrome/browser/metrics/perf/heap_collector.cc b/chrome/browser/metrics/perf/heap_collector.cc new file mode 100644 index 0000000..4422571 --- /dev/null +++ b/chrome/browser/metrics/perf/heap_collector.cc
@@ -0,0 +1,225 @@ +// 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/metrics/perf/heap_collector.h" + +#include <memory> +#include <string> +#include <utility> + +#include "base/allocator/allocator_extension.h" +#include "base/command_line.h" +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/metrics/field_trial_params.h" +#include "base/process/process_handle.h" +#include "base/rand_util.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_split.h" +#include "base/system/sys_info.h" +#include "base/task/post_task.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_list.h" +#include "third_party/metrics_proto/sampled_profile.pb.h" + +namespace metrics { + +// Feature for controlling the heap collection parameters. +const base::Feature kCWPHeapCollection{"CWPHeapCollection", + base::FEATURE_DISABLED_BY_DEFAULT}; + +namespace { + +// Name of the heap collector. It is appended to the UMA metric names for +// reporting collection and upload status. +const char kHeapCollectorName[] = "Heap"; + +// The approximate gap in bytes between sampling actions. Heap allocations are +// sampled using a geometric distribution with the specified mean. +const size_t kHeapSamplingIntervalBytes = 1 * 1024 * 1024; + +// Feature parameters that control the behavior of the heap collector. +constexpr base::FeatureParam<int> kSamplingIntervalBytes{ + &kCWPHeapCollection, "SamplingIntervalBytes", kHeapSamplingIntervalBytes}; + +constexpr base::FeatureParam<int> kPeriodicCollectionIntervalMs{ + &kCWPHeapCollection, "PeriodicCollectionIntervalMs", + 3 * 3600 * 1000}; // 3h + +constexpr base::FeatureParam<int> kResumeFromSuspendSamplingFactor{ + &kCWPHeapCollection, "ResumeFromSuspend::SamplingFactor", 10}; + +constexpr base::FeatureParam<int> kResumeFromSuspendMaxDelaySec{ + &kCWPHeapCollection, "ResumeFromSuspend::MaxDelaySec", 5}; + +constexpr base::FeatureParam<int> kRestoreSessionSamplingFactor{ + &kCWPHeapCollection, "RestoreSession::SamplingFactor", 10}; + +constexpr base::FeatureParam<int> kRestoreSessionMaxDelaySec{ + &kCWPHeapCollection, "RestoreSession::MaxDelaySec", 10}; + +// Limit the total size of protobufs that can be cached, so they don't take up +// too much memory. If the size of cached protobufs exceeds this value, stop +// collecting further perf data. The current value is 2 MB. +const size_t kCachedHeapDataProtobufSizeThreshold = 2 * 1024 * 1024; + +// Location of quipper on ChromeOS. +const char kQuipperLocation[] = "/usr/bin/quipper"; + +// Quipper arguments for passing in a profile and the process PID. +const char kQuipperHeapProfile[] = "input_heap_profile"; +const char kQuipperProcessPid[] = "pid"; + +// Deletes the temp file when the object goes out of scope. +class FileDeleter { + public: + explicit FileDeleter(const base::FilePath& temp_dir) : temp_dir_(temp_dir) {} + ~FileDeleter(); + + private: + const base::FilePath temp_dir_; + + DISALLOW_COPY_AND_ASSIGN(FileDeleter); +}; + +FileDeleter::~FileDeleter() { + base::PostTaskWithTraits(FROM_HERE, + {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, + base::BindOnce(base::IgnoreResult(&base::DeleteFile), + std::move(temp_dir_), false)); +} + +void SetHeapSamplingPeriod(size_t sampling_period) { + bool res = base::allocator::SetNumericProperty( + "tcmalloc.sampling_period_bytes", sampling_period); + DCHECK(res); +} + +} // namespace + +HeapCollector::HeapCollector() + : MetricCollector(kHeapCollectorName), + sampling_period_bytes_(kHeapSamplingIntervalBytes) { + BrowserList::AddObserver(this); +} + +HeapCollector::~HeapCollector() { + // Disable heap sampling when the collector exits. + SetHeapSamplingPeriod(0); + BrowserList::RemoveObserver(this); +} + +void HeapCollector::Init() { + if (base::FeatureList::IsEnabled(kCWPHeapCollection)) + SetCollectionParamsFromFeatureParams(); + + size_t sampling_period = 0; + // Enable sampling if no incognito session is active. + if (!BrowserList::IsIncognitoSessionActive()) { + sampling_period = sampling_period_bytes_; + } + SetHeapSamplingPeriod(sampling_period); + + MetricCollector::Init(); +} + +void HeapCollector::OnBrowserAdded(Browser* browser) { + // Pause heap sampling when an incognito session is opened. + if (browser->profile()->IsOffTheRecord()) { + SetHeapSamplingPeriod(0); + } +} + +void HeapCollector::OnBrowserRemoved(Browser* browser) { + // Resume heap sampling if no incognito sessions are active. + if (!BrowserList::IsIncognitoSessionActive()) { + SetHeapSamplingPeriod(sampling_period_bytes_); + } +} + +void HeapCollector::SetCollectionParamsFromFeatureParams() { + sampling_period_bytes_ = kSamplingIntervalBytes.Get(); + collection_params_.periodic_interval = + base::TimeDelta::FromMilliseconds(kPeriodicCollectionIntervalMs.Get()); + collection_params_.resume_from_suspend.sampling_factor = + kResumeFromSuspendSamplingFactor.Get(); + collection_params_.resume_from_suspend.max_collection_delay = + base::TimeDelta::FromSeconds(kResumeFromSuspendMaxDelaySec.Get()); + collection_params_.restore_session.sampling_factor = + kRestoreSessionSamplingFactor.Get(); + collection_params_.restore_session.max_collection_delay = + base::TimeDelta::FromSeconds(kRestoreSessionMaxDelaySec.Get()); +} + +bool HeapCollector::ShouldCollect() const { + // Do not collect further data if we've already collected a substantial amount + // of data, as indicated by |kCachedHeapDataProtobufSizeThreshold|. + if (cached_profile_data_size() >= kCachedHeapDataProtobufSizeThreshold) { + AddToUmaHistogram(CollectionAttemptStatus::NOT_READY_TO_COLLECT); + return false; + } + return true; +} + +void HeapCollector::CollectProfile( + std::unique_ptr<SampledProfile> sampled_profile) { + base::Optional<base::FilePath> temp_file = DumpProfileToTempFile(); + if (!temp_file) + return; + + base::CommandLine quipper = MakeQuipperCommand(temp_file.value()); + ParseAndSaveProfile(quipper, temp_file.value(), std::move(sampled_profile)); +} + +base::Optional<base::FilePath> HeapCollector::DumpProfileToTempFile() { + base::FilePath temp_path; + if (!base::CreateTemporaryFile(&temp_path)) { + AddToUmaHistogram(CollectionAttemptStatus::UNABLE_TO_COLLECT); + return base::nullopt; + } + std::string writer; + base::allocator::GetHeapSample(&writer); + base::File temp(temp_path, base::File::FLAG_CREATE_ALWAYS | + base::File::FLAG_READ | + base::File::FLAG_WRITE); + DCHECK(temp.created()); + DCHECK(temp.IsValid()); + int res = temp.WriteAtCurrentPos(writer.c_str(), writer.length()); + DCHECK_EQ(res, static_cast<int>(writer.length())); + temp.Close(); + return base::make_optional<base::FilePath>(temp_path); +} + +base::CommandLine HeapCollector::MakeQuipperCommand( + const base::FilePath& profile_path) { + base::CommandLine quipper{base::FilePath(kQuipperLocation)}; + quipper.AppendSwitchPath(kQuipperHeapProfile, profile_path); + quipper.AppendSwitchASCII(kQuipperProcessPid, + std::to_string(base::GetCurrentProcId())); + return quipper; +} + +void HeapCollector::ParseAndSaveProfile( + const base::CommandLine& parser, + const base::FilePath& profile_path, + std::unique_ptr<SampledProfile> sampled_profile) { + // We may exit due to parsing errors, so use a FileDeleter to remove the + // temporary profile data on all paths. + FileDeleter file_deleter(profile_path); + + // Run the parser command on the profile file. + std::string output; + if (!base::GetAppOutput(parser, &output)) { + AddToUmaHistogram(CollectionAttemptStatus::ILLEGAL_DATA_RETURNED); + return; + } + + SaveSerializedPerfProto(std::move(sampled_profile), + PerfProtoType::PERF_TYPE_DATA, output); +} + +} // namespace metrics
diff --git a/chrome/browser/metrics/perf/heap_collector.h b/chrome/browser/metrics/perf/heap_collector.h new file mode 100644 index 0000000..d715627 --- /dev/null +++ b/chrome/browser/metrics/perf/heap_collector.h
@@ -0,0 +1,76 @@ +// 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_METRICS_PERF_HEAP_COLLECTOR_H_ +#define CHROME_BROWSER_METRICS_PERF_HEAP_COLLECTOR_H_ + +#include <map> +#include <memory> +#include <string> + +#include "base/feature_list.h" +#include "base/optional.h" +#include "chrome/browser/metrics/perf/metric_collector.h" +#include "chrome/browser/metrics/perf/perf_output.h" +#include "chrome/browser/ui/browser_list_observer.h" + +class Browser; + +namespace base { +class CommandLine; +class FilePath; +} // namespace base + +namespace metrics { + +// Feature for controlling the heap collection parameters. +extern const base::Feature kCWPHeapCollection; + +// Enables collection of heap profiles using the tcmalloc heap sampling +// profiler. +class HeapCollector : public MetricCollector, public BrowserListObserver { + public: + HeapCollector(); + ~HeapCollector() override; + + // MetricCollector: + void Init() override; + + protected: + // MetricCollector: + bool ShouldCollect() const override; + void CollectProfile(std::unique_ptr<SampledProfile> sampled_profile) override; + + // BrowserListObserver: + void OnBrowserAdded(Browser* browser) override; + void OnBrowserRemoved(Browser* browser) override; + + // Fetches a heap profile from tcmalloc, dumps it to a temp file, and returns + // the path. + base::Optional<base::FilePath> DumpProfileToTempFile(); + + // Generates a quipper command to parse the given profile file. + base::CommandLine MakeQuipperCommand(const base::FilePath& profile_path); + + // Executes the given command line to parse a profile stored at the given + // path and saves it in the given sampled profile. The given temporary profile + // file is removed after parsing. + void ParseAndSaveProfile(const base::CommandLine& parser, + const base::FilePath& profile_path, + std::unique_ptr<SampledProfile> sampled_profile); + + private: + // Change the values in |collection_params_| based on the values of field + // trial parameters. + void SetCollectionParamsFromFeatureParams(); + + // Heap sampling period. + size_t sampling_period_bytes_; + + DISALLOW_COPY_AND_ASSIGN(HeapCollector); +}; + +} // namespace metrics + +#endif // CHROME_BROWSER_METRICS_PERF_HEAP_COLLECTOR_H_
diff --git a/chrome/browser/metrics/perf/heap_collector_unittest.cc b/chrome/browser/metrics/perf/heap_collector_unittest.cc new file mode 100644 index 0000000..d3ab1af --- /dev/null +++ b/chrome/browser/metrics/perf/heap_collector_unittest.cc
@@ -0,0 +1,411 @@ +// 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/metrics/perf/heap_collector.h" + +#include <memory> +#include <string> +#include <unordered_map> +#include <utility> +#include <vector> + +#include "base/allocator/allocator_extension.h" +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/macros.h" +#include "base/test/scoped_feature_list.h" +#include "base/test/test_simple_task_runner.h" +#include "base/threading/thread_task_runner_handle.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/test/base/test_browser_window.h" +#include "chrome/test/base/testing_profile.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/metrics_proto/sampled_profile.pb.h" + +namespace metrics { + +namespace { + +// Returns a sample PerfDataProto for a heap profile. +PerfDataProto GetSampleHeapPerfDataProto() { + PerfDataProto proto; + + // Add file attributes. + PerfDataProto_PerfFileAttr* file_attr = proto.add_file_attrs(); + PerfDataProto_PerfEventAttr* event_attr = file_attr->mutable_attr(); + event_attr->set_type(1); // PERF_TYPE_SOFTWARE + event_attr->set_size(96); // PERF_ATTR_SIZE_VER3 + event_attr->set_config(9); // PERF_COUNT_SW_DUMMY + event_attr->set_sample_id_all(true); + event_attr->set_sample_period(111222); + event_attr->set_sample_type(1 /*PERF_SAMPLE_IP*/ | 2 /*PERF_SAMPLE_TID*/ | + 32 /*PERF_SAMPLE_CALLCHAIN*/ | + 64 /*PERF_SAMPLE_ID*/ | + 256 /*PERF_SAMPLE_PERIOD*/); + event_attr->set_mmap(true); + file_attr->add_ids(0); + + PerfDataProto_PerfEventType* event_type = proto.add_event_types(); + event_type->set_id(9); // PERF_COUNT_SW_DUMMY + + file_attr = proto.add_file_attrs(); + event_attr = file_attr->mutable_attr(); + event_attr->set_type(1); // PERF_TYPE_SOFTWARE + event_attr->set_size(96); // PERF_ATTR_SIZE_VER3 + event_attr->set_config(9); // PERF_COUNT_SW_DUMMY + event_attr->set_sample_id_all(true); + event_attr->set_sample_period(111222); + event_attr->set_sample_type(1 /*PERF_SAMPLE_IP*/ | 2 /*PERF_SAMPLE_TID*/ | + 32 /*PERF_SAMPLE_CALLCHAIN*/ | + 64 /*PERF_SAMPLE_ID*/ | + 256 /*PERF_SAMPLE_PERIOD*/); + file_attr->add_ids(1); + + event_type = proto.add_event_types(); + event_type->set_id(9); // PERF_COUNT_SW_DUMMY + + // Add MMAP event. + PerfDataProto_PerfEvent* event = proto.add_events(); + PerfDataProto_EventHeader* header = event->mutable_header(); + header->set_type(1); // PERF_RECORD_MMAP + header->set_misc(0); + header->set_size(0); + + PerfDataProto_MMapEvent* mmap = event->mutable_mmap_event(); + mmap->set_pid(3456); + mmap->set_tid(3456); + mmap->set_start(0x617aa770f000); + mmap->set_len(0x617ab0689000 - 0x617aa770f000); + mmap->set_pgoff(16); + + PerfDataProto_SampleInfo* sample_info = mmap->mutable_sample_info(); + sample_info->set_pid(3456); + sample_info->set_tid(3456); + sample_info->set_id(0); + + // Add Sample events. + event = proto.add_events(); + header = event->mutable_header(); + header->set_type(9); // PERF_RECORD_SAMPLE + header->set_misc(2); // PERF_RECORD_MISC_USER + header->set_size(0); + + double scale = 1 / (1 - exp(-(1024.00 / 2.00) / 111222.00)); + + PerfDataProto_SampleEvent* sample = event->mutable_sample_event(); + sample->set_ip(0x617aae951c31); + sample->set_pid(3456); + sample->set_tid(3456); + sample->set_id(0); + sample->set_period(2 * scale); + sample->add_callchain(static_cast<uint64_t>(-512)); // PERF_CONTEXT_USER + sample->add_callchain(0x617aae951c31); + sample->add_callchain(0x617aae95062e); + + event = proto.add_events(); + header = event->mutable_header(); + header->set_type(9); // PERF_RECORD_SAMPLE + header->set_misc(2); // PERF_RECORD_MISC_USER + header->set_size(0); + + sample = event->mutable_sample_event(); + sample->set_ip(0x617aae951c31); + sample->set_pid(3456); + sample->set_tid(3456); + sample->set_id(1); + sample->set_period(1024 * scale); + sample->add_callchain(static_cast<uint64_t>(-512)); // PERF_CONTEXT_USER + sample->add_callchain(0x617aae951c31); + sample->add_callchain(0x617aae95062e); + + return proto; +} + +// Allows access to some private methods for testing. +class TestHeapCollector : public HeapCollector { + public: + TestHeapCollector() {} + + using HeapCollector::collection_params; + using HeapCollector::CollectProfile; + using HeapCollector::DumpProfileToTempFile; + using HeapCollector::MakeQuipperCommand; + using HeapCollector::ParseAndSaveProfile; + + private: + DISALLOW_COPY_AND_ASSIGN(TestHeapCollector); +}; + +void ReadHeapSamplingPeriod(size_t* sampling_period) { + ASSERT_TRUE(base::allocator::GetNumericProperty( + "tcmalloc.sampling_period_bytes", sampling_period)) + << "Failed to read heap sampling period"; +} + +} // namespace + +class HeapCollectorTest : public testing::Test { + public: + HeapCollectorTest() {} + + // Opens a new browser window, which can be incognito, and returns a unique + // handle for it. + size_t OpenBrowserWindow(bool incognito) { + auto browser_window = std::make_unique<TestBrowserWindow>(); + Profile* browser_profile = + incognito ? profile_->GetOffTheRecordProfile() : profile_.get(); + Browser::CreateParams params(browser_profile, true); + params.type = Browser::TYPE_TABBED; + params.window = browser_window.get(); + auto browser = std::make_unique<Browser>(params); + + size_t handle = next_browser_id++; + open_browsers_[handle] = + std::make_pair(std::move(browser_window), std::move(browser)); + return handle; + } + + // Closes the browser window with the given handle. + void CloseBrowserWindow(size_t handle) { + auto it = open_browsers_.find(handle); + ASSERT_FALSE(it == open_browsers_.end()); + open_browsers_.erase(it); + } + + void SetUp() override { + // Instantiate a testing profile. + TestingProfile::Builder profile_builder; + profile_ = profile_builder.Build(); + + // Create a heap collector. + heap_collector_ = std::make_unique<TestHeapCollector>(); + + // HeapCollector requires the user to be logged in. + heap_collector_->OnUserLoggedIn(); + } + + void TearDown() override { + heap_collector_.reset(); + open_browsers_.clear(); + profile_.reset(); + } + + protected: + // Needed to pass PrerenderManager's DCHECKs. + content::TestBrowserThreadBundle test_browser_thread_bundle_; + + // The associated testing browser profile. + std::unique_ptr<TestingProfile> profile_; + + // Keep track of the open browsers and accompanying windows. + std::unordered_map< + size_t, + std::pair<std::unique_ptr<TestBrowserWindow>, std::unique_ptr<Browser>>> + open_browsers_; + static size_t next_browser_id; + + std::unique_ptr<TestHeapCollector> heap_collector_; + + DISALLOW_COPY_AND_ASSIGN(HeapCollectorTest); +}; + +size_t HeapCollectorTest::next_browser_id = 1; + +TEST_F(HeapCollectorTest, CheckSetup) { + heap_collector_->Init(); + + // No profiles are cached on start. + std::vector<SampledProfile> stored_profiles; + EXPECT_FALSE(heap_collector_->GetSampledProfiles(&stored_profiles)); + EXPECT_TRUE(stored_profiles.empty()); + + // Heap sampling is enabled when no incognito window is open. + size_t sampling_period; + ReadHeapSamplingPeriod(&sampling_period); + EXPECT_GT(sampling_period, 0u); +} + +TEST_F(HeapCollectorTest, IncognitoWindowDisablesSamplingOnInit) { + OpenBrowserWindow(/*incognito=*/true); + heap_collector_->Init(); + + // Heap sampling is disabled when an incognito session is active. + size_t sampling_period; + ReadHeapSamplingPeriod(&sampling_period); + EXPECT_EQ(sampling_period, 0u); +} + +TEST_F(HeapCollectorTest, IncognitoWindowPausesSampling) { + heap_collector_->Init(); + + // Heap sampling is enabled. + size_t sampling_period; + ReadHeapSamplingPeriod(&sampling_period); + EXPECT_GT(sampling_period, 0u); + + // Opening an incognito window disables sampling. + auto win1 = OpenBrowserWindow(/*incognito=*/true); + ReadHeapSamplingPeriod(&sampling_period); + EXPECT_EQ(sampling_period, 0u); + + // Opening a regular window doesn't resume sampling. + OpenBrowserWindow(/*incognito=*/false); + // Heap sampling is still disabled. + ReadHeapSamplingPeriod(&sampling_period); + EXPECT_EQ(sampling_period, 0u); + + // Open another incognito window and close the first one. + auto win3 = OpenBrowserWindow(/*incognito=*/true); + CloseBrowserWindow(win1); + // Heap sampling is still disabled. + ReadHeapSamplingPeriod(&sampling_period); + EXPECT_EQ(sampling_period, 0u); + + // Closing the last incognito window resumes heap sampling. + CloseBrowserWindow(win3); + // Heap sampling is enabled. + ReadHeapSamplingPeriod(&sampling_period); + EXPECT_GT(sampling_period, 0u); +} + +TEST_F(HeapCollectorTest, DumpProfileToTempFile) { + base::Optional<base::FilePath> got_path = + heap_collector_->DumpProfileToTempFile(); + // Check that we got a path. + ASSERT_TRUE(got_path); + // Check that the file is readable and not empty. + base::File temp(got_path.value(), + base::File::FLAG_OPEN | base::File::FLAG_READ); + ASSERT_TRUE(temp.IsValid()); + EXPECT_GT(temp.GetLength(), 0); + temp.Close(); + // We must be able to remove the temp file. + ASSERT_TRUE(base::DeleteFile(got_path.value(), false)); +} + +TEST_F(HeapCollectorTest, MakeQuipperCommand) { + const base::FilePath kTempProfile( + FILE_PATH_LITERAL("/tmp/MakeQuipperCommand.test")); + base::CommandLine got = heap_collector_->MakeQuipperCommand(kTempProfile); + + // Check that we got the correct two switch names. + ASSERT_EQ(got.GetSwitches().size(), 2u); + EXPECT_TRUE(got.HasSwitch("input_heap_profile")); + EXPECT_TRUE(got.HasSwitch("pid")); + + // Check that we got the correct program name and switch values. + EXPECT_EQ(got.GetProgram().value(), "/usr/bin/quipper"); + EXPECT_EQ(got.GetSwitchValuePath("input_heap_profile"), kTempProfile); + EXPECT_EQ(got.GetSwitchValueASCII("pid"), + std::to_string(base::GetCurrentProcId())); +} + +TEST_F(HeapCollectorTest, ParseAndSaveProfile) { + // Write a sample perf data proto to a temp file. + const base::FilePath kTempProfile( + FILE_PATH_LITERAL("/tmp/ParseAndSaveProfile.test")); + PerfDataProto heap_proto = GetSampleHeapPerfDataProto(); + std::string serialized_proto = heap_proto.SerializeAsString(); + + base::File temp(kTempProfile, base::File::FLAG_CREATE_ALWAYS | + base::File::FLAG_READ | + base::File::FLAG_WRITE); + EXPECT_TRUE(temp.created()); + EXPECT_TRUE(temp.IsValid()); + int res = temp.WriteAtCurrentPos(serialized_proto.c_str(), + serialized_proto.length()); + EXPECT_EQ(res, static_cast<int>(serialized_proto.length())); + temp.Close(); + + // Create a command line that copies the input file to the output. + base::CommandLine::StringVector argv; + argv.push_back("cat"); + argv.push_back(kTempProfile.value()); + base::CommandLine cat(argv); + + // Run the command. + auto sampled_profile = std::make_unique<SampledProfile>(); + sampled_profile->set_trigger_event(SampledProfile::PERIODIC_COLLECTION); + heap_collector_->ParseAndSaveProfile(cat, kTempProfile, + std::move(sampled_profile)); + + // Check that the profile was cached. + std::vector<SampledProfile> stored_profiles; + EXPECT_TRUE(heap_collector_->GetSampledProfiles(&stored_profiles)); + ASSERT_EQ(1U, stored_profiles.size()); + + const SampledProfile& profile = stored_profiles[0]; + EXPECT_EQ(SampledProfile::PERIODIC_COLLECTION, profile.trigger_event()); + EXPECT_TRUE(profile.has_ms_after_boot()); + EXPECT_TRUE(profile.has_ms_after_login()); + + ASSERT_TRUE(profile.has_perf_data()); + EXPECT_EQ(serialized_proto, profile.perf_data().SerializeAsString()); + + // Check that the temp profile file is removed after pending tasks complete. + heap_collector_->Deactivate(); + test_browser_thread_bundle_.RunUntilIdle(); + temp = + base::File(kTempProfile, base::File::FLAG_OPEN | base::File::FLAG_READ); + ASSERT_FALSE(temp.IsValid()); +} + +class HeapCollectorCollectionParamsTest : public testing::Test { + public: + HeapCollectorCollectionParamsTest() + : task_runner_(base::MakeRefCounted<base::TestSimpleTaskRunner>()), + task_runner_handle_(task_runner_) {} + + private: + scoped_refptr<base::TestSimpleTaskRunner> task_runner_; + base::ThreadTaskRunnerHandle task_runner_handle_; + + DISALLOW_COPY_AND_ASSIGN(HeapCollectorCollectionParamsTest); +}; + +TEST_F(HeapCollectorCollectionParamsTest, Parameters_Override) { + std::map<std::string, std::string> params; + params.insert(std::make_pair("SamplingIntervalBytes", "800000")); + params.insert(std::make_pair("PeriodicCollectionIntervalMs", "3600000")); + params.insert(std::make_pair("ResumeFromSuspend::SamplingFactor", "1")); + params.insert(std::make_pair("ResumeFromSuspend::MaxDelaySec", "10")); + params.insert(std::make_pair("RestoreSession::SamplingFactor", "2")); + params.insert(std::make_pair("RestoreSession::MaxDelaySec", "20")); + + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndEnableFeatureWithParameters(kCWPHeapCollection, + params); + + TestHeapCollector heap_collector; + const auto& parsed_params = heap_collector.collection_params(); + + // Not initialized yet: + size_t sampling_period; + ReadHeapSamplingPeriod(&sampling_period); + EXPECT_NE(800000u, sampling_period); + EXPECT_NE(base::TimeDelta::FromHours(1), parsed_params.periodic_interval); + EXPECT_NE(1, parsed_params.resume_from_suspend.sampling_factor); + EXPECT_NE(base::TimeDelta::FromSeconds(10), + parsed_params.resume_from_suspend.max_collection_delay); + EXPECT_NE(2, parsed_params.restore_session.sampling_factor); + EXPECT_NE(base::TimeDelta::FromSeconds(20), + parsed_params.restore_session.max_collection_delay); + + heap_collector.Init(); + + ReadHeapSamplingPeriod(&sampling_period); + EXPECT_EQ(800000u, sampling_period); + EXPECT_EQ(base::TimeDelta::FromHours(1), parsed_params.periodic_interval); + EXPECT_EQ(1, parsed_params.resume_from_suspend.sampling_factor); + EXPECT_EQ(base::TimeDelta::FromSeconds(10), + parsed_params.resume_from_suspend.max_collection_delay); + EXPECT_EQ(2, parsed_params.restore_session.sampling_factor); + EXPECT_EQ(base::TimeDelta::FromSeconds(20), + parsed_params.restore_session.max_collection_delay); +} + +} // namespace metrics
diff --git a/chrome/browser/metrics/perf/metric_collector.cc b/chrome/browser/metrics/perf/metric_collector.cc index 97f1b8e..d1f5030a 100644 --- a/chrome/browser/metrics/perf/metric_collector.cc +++ b/chrome/browser/metrics/perf/metric_collector.cc
@@ -312,6 +312,7 @@ // Add the collected data to the container of collected SampledProfiles. cached_profile_data_.resize(cached_profile_data_.size() + 1); cached_profile_data_.back().Swap(sampled_profile.get()); + AddToUmaHistogram(CollectionAttemptStatus::SUCCESS); } size_t MetricCollector::cached_profile_data_size() const {
diff --git a/chrome/browser/metrics/perf/metric_collector.h b/chrome/browser/metrics/perf/metric_collector.h index 77e3e17..9b3e071 100644 --- a/chrome/browser/metrics/perf/metric_collector.h +++ b/chrome/browser/metrics/perf/metric_collector.h
@@ -71,6 +71,7 @@ PROTOBUF_NOT_PARSED, ILLEGAL_DATA_RETURNED, ALREADY_COLLECTING, + UNABLE_TO_COLLECT, NUM_OUTCOMES };
diff --git a/chrome/browser/metrics/perf/profile_provider_chromeos.cc b/chrome/browser/metrics/perf/profile_provider_chromeos.cc index 83dfdda..269a068 100644 --- a/chrome/browser/metrics/perf/profile_provider_chromeos.cc +++ b/chrome/browser/metrics/perf/profile_provider_chromeos.cc
@@ -4,7 +4,11 @@ #include "chrome/browser/metrics/perf/profile_provider_chromeos.h" +#include "base/allocator/buildflags.h" #include "base/bind.h" +#include "base/metrics/field_trial_params.h" +#include "base/rand_util.h" +#include "chrome/browser/metrics/perf/heap_collector.h" #include "chrome/browser/metrics/perf/metric_collector.h" #include "chrome/browser/metrics/perf/perf_events_collector.h" #include "chromeos/dbus/dbus_thread_manager.h" @@ -14,6 +18,15 @@ namespace { +#if BUILDFLAG(USE_NEW_TCMALLOC) +// Sampling factor for enabling the heap collector. The heap collector is +// enabled with a probability of 1 / <sampling_factor>. A value of 5 implies a +// 20% probability. A value of 1 implies a 100% probability. A value <= 0 +// disables the heap collector. +constexpr base::FeatureParam<int> kSamplingFactorForEnablingHeapCollector{ + &kCWPHeapCollection, "SamplingFactorForEnablingHeapCollector", 0}; +#endif + // Returns true if a normal user is logged in. Returns false otherwise (e.g. if // logged in as a guest or as a kiosk app). bool IsNormalUserLoggedIn() { @@ -34,6 +47,16 @@ } void ProfileProvider::Init() { +#if BUILDFLAG(USE_NEW_TCMALLOC) + if (base::FeatureList::IsEnabled(kCWPHeapCollection)) { + // Register a heap collector with a probability obtained from field params. + int sampling_factor = kSamplingFactorForEnablingHeapCollector.Get(); + if (sampling_factor > 0 && base::RandGenerator(sampling_factor) == 0) { + collectors_.push_back(std::make_unique<HeapCollector>()); + } + } +#endif + for (auto& collector : collectors_) { collector->Init(); }
diff --git a/chrome/browser/metrics/perf/profile_provider_chromeos_unittest.cc b/chrome/browser/metrics/perf/profile_provider_chromeos_unittest.cc index a1b38583..eabcad12 100644 --- a/chrome/browser/metrics/perf/profile_provider_chromeos_unittest.cc +++ b/chrome/browser/metrics/perf/profile_provider_chromeos_unittest.cc
@@ -11,9 +11,12 @@ #include <utility> #include <vector> +#include "base/allocator/buildflags.h" #include "base/macros.h" +#include "base/test/scoped_feature_list.h" #include "base/test/test_simple_task_runner.h" #include "base/threading/thread_task_runner_handle.h" +#include "chrome/browser/metrics/perf/heap_collector.h" #include "chrome/browser/metrics/perf/metric_collector.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/login/login_state/login_state.h" @@ -277,4 +280,84 @@ ExpectTwoStoredPerfProfiles<SampledProfile::RESTORE_SESSION>(stored_profiles); } +namespace { + +class TestParamsProfileProvider : public ProfileProvider { + public: + TestParamsProfileProvider() {} + + using ProfileProvider::collectors_; + + private: + DISALLOW_COPY_AND_ASSIGN(TestParamsProfileProvider); +}; + +} // namespace + +class ProfileProviderFeatureParamsTest : public testing::Test { + public: + ProfileProviderFeatureParamsTest() + : task_runner_(base::MakeRefCounted<base::TestSimpleTaskRunner>()), + task_runner_handle_(task_runner_) {} + + void SetUp() override { + // ProfileProvider requires chromeos::LoginState and + // chromeos::DBusThreadManager to be initialized. + chromeos::LoginState::Initialize(); + chromeos::DBusThreadManager::Initialize(); + } + + void TearDown() override { + chromeos::DBusThreadManager::Shutdown(); + chromeos::LoginState::Shutdown(); + } + + private: + scoped_refptr<base::TestSimpleTaskRunner> task_runner_; + base::ThreadTaskRunnerHandle task_runner_handle_; + + DISALLOW_COPY_AND_ASSIGN(ProfileProviderFeatureParamsTest); +}; + +TEST_F(ProfileProviderFeatureParamsTest, HeapCollectorDisabled) { + std::map<std::string, std::string> params; + params.insert(std::make_pair("SamplingFactorForEnablingHeapCollector", "0")); + + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndEnableFeatureWithParameters(kCWPHeapCollection, + params); + + TestParamsProfileProvider profile_provider; + // We should have one collector registered. + EXPECT_EQ(1u, profile_provider.collectors_.size()); + + // After initialization, we should still have a single collector, because the + // sampling factor param is set to 0. + profile_provider.Init(); + EXPECT_EQ(1u, profile_provider.collectors_.size()); +} + +TEST_F(ProfileProviderFeatureParamsTest, HeapCollectorEnabled) { + std::map<std::string, std::string> params; + params.insert(std::make_pair("SamplingFactorForEnablingHeapCollector", "1")); + + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndEnableFeatureWithParameters(kCWPHeapCollection, + params); + + TestParamsProfileProvider profile_provider; + // We should have one collector registered. + EXPECT_EQ(1u, profile_provider.collectors_.size()); + + // After initialization, if the new tcmalloc is enabled, we should have two + // collectors, because the sampling factor param is set to 1. Otherwise, we + // must still have one collector only. + profile_provider.Init(); +#if BUILDFLAG(USE_NEW_TCMALLOC) + EXPECT_EQ(2u, profile_provider.collectors_.size()); +#else + EXPECT_EQ(1u, profile_provider.collectors_.size()); +#endif +} + } // namespace metrics
diff --git a/chrome/browser/offline_pages/android/evaluation/evaluation_test_scheduler.cc b/chrome/browser/offline_pages/android/evaluation/evaluation_test_scheduler.cc index 17bfb02..b6c6da3 100644 --- a/chrome/browser/offline_pages/android/evaluation/evaluation_test_scheduler.cc +++ b/chrome/browser/offline_pages/android/evaluation/evaluation_test_scheduler.cc
@@ -31,8 +31,8 @@ void StartProcessing(); void ProcessingDoneCallback(bool result) { - base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, - base::Bind(&StartProcessing)); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(&StartProcessing)); } void GetAllRequestsDone( @@ -50,7 +50,7 @@ if (net::NetworkChangeNotifier::GetConnectionType() == net::NetworkChangeNotifier::ConnectionType::CONNECTION_NONE) { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, base::Bind(&StartProcessing), + FROM_HERE, base::BindOnce(&StartProcessing), base::TimeDelta::FromSeconds(2)); return; } @@ -82,8 +82,8 @@ } coordinator_->GetLogger()->RecordActivity(std::string(kLogTag) + " Start schedule!"); - base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, - base::Bind(&StartProcessing)); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(&StartProcessing)); } void EvaluationTestScheduler::BackupSchedule( @@ -109,8 +109,8 @@ } void EvaluationTestScheduler::ImmediateScheduleCallback(bool result) { - base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, - base::Bind(&StartProcessing)); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(&StartProcessing)); } } // namespace android
diff --git a/chrome/browser/offline_pages/offline_page_request_handler.cc b/chrome/browser/offline_pages/offline_page_request_handler.cc index 8516800..33a73be5 100644 --- a/chrome/browser/offline_pages/offline_page_request_handler.cc +++ b/chrome/browser/offline_pages/offline_page_request_handler.cc
@@ -550,8 +550,8 @@ void OfflinePageRequestHandler::Start() { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&OfflinePageRequestHandler::StartAsync, - weak_ptr_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&OfflinePageRequestHandler::StartAsync, + weak_ptr_factory_.GetWeakPtr())); } void OfflinePageRequestHandler::StartAsync() {
diff --git a/chrome/browser/offline_pages/prefetch/prefetch_instance_id_proxy.cc b/chrome/browser/offline_pages/prefetch/prefetch_instance_id_proxy.cc index 40650cf..1f5a7b4 100644 --- a/chrome/browser/offline_pages/prefetch/prefetch_instance_id_proxy.cc +++ b/chrome/browser/offline_pages/prefetch/prefetch_instance_id_proxy.cc
@@ -41,9 +41,9 @@ DCHECK(IsPrefetchingOfflinePagesEnabled()); if (!token_.empty()) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&PrefetchInstanceIDProxy::GotGCMToken, - weak_factory_.GetWeakPtr(), callback, token_, - InstanceID::SUCCESS)); + FROM_HERE, base::BindOnce(&PrefetchInstanceIDProxy::GotGCMToken, + weak_factory_.GetWeakPtr(), callback, token_, + InstanceID::SUCCESS)); return; }
diff --git a/chrome/browser/password_manager/password_store_mac.cc b/chrome/browser/password_manager/password_store_mac.cc index 0b4c380..effbb927 100644 --- a/chrome/browser/password_manager/password_store_mac.cc +++ b/chrome/browser/password_manager/password_store_mac.cc
@@ -52,8 +52,8 @@ /*changes=*/nullptr); initial_status_ = MigrationStatus::MIGRATION_STOPPED; main_task_runner()->PostTask( - FROM_HERE, - base::Bind(&PasswordStoreMac::UpdateStatusPref, this, initial_status_)); + FROM_HERE, base::BindOnce(&PasswordStoreMac::UpdateStatusPref, this, + initial_status_)); } UMA_HISTOGRAM_ENUMERATION(
diff --git a/chrome/browser/performance_manager/graph/node_base.cc b/chrome/browser/performance_manager/graph/node_base.cc index a9f2fa6a..f062d8e 100644 --- a/chrome/browser/performance_manager/graph/node_base.cc +++ b/chrome/browser/performance_manager/graph/node_base.cc
@@ -84,7 +84,8 @@ // static NodeBase* NodeBase::PassOwnershipToGraph(std::unique_ptr<NodeBase> new_cu) { - return new_cu->graph()->AddNewNode(std::move(new_cu)); + auto *graph = new_cu->graph(); + return graph->AddNewNode(std::move(new_cu)); } } // namespace performance_manager
diff --git a/chrome/browser/platform_util_win.cc b/chrome/browser/platform_util_win.cc index 7315c64..86f5e659 100644 --- a/chrome/browser/platform_util_win.cc +++ b/chrome/browser/platform_util_win.cc
@@ -114,7 +114,7 @@ base::CreateCOMSTATaskRunnerWithTraits( {base::MayBlock(), base::TaskPriority::USER_BLOCKING}) ->PostTask(FROM_HERE, - base::Bind(&ShowItemInFolderOnWorkerThread, full_path)); + base::BindOnce(&ShowItemInFolderOnWorkerThread, full_path)); } namespace internal { @@ -138,7 +138,7 @@ base::CreateCOMSTATaskRunnerWithTraits( {base::MayBlock(), base::TaskPriority::USER_BLOCKING}) - ->PostTask(FROM_HERE, base::Bind(&OpenExternalOnWorkerThread, url)); + ->PostTask(FROM_HERE, base::BindOnce(&OpenExternalOnWorkerThread, url)); } } // namespace platform_util
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service_mobile.cc b/chrome/browser/policy/cloud/user_policy_signin_service_mobile.cc index 025916b..e250c90a 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_mobile.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service_mobile.cc
@@ -137,8 +137,8 @@ base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&UserPolicySigninService::RegisterCloudPolicyService, - weak_factory_.GetWeakPtr()), + base::BindOnce(&UserPolicySigninService::RegisterCloudPolicyService, + weak_factory_.GetWeakPtr()), try_registration_delay); }
diff --git a/chrome/browser/policy/policy_path_parser_mac.mm b/chrome/browser/policy/policy_path_parser_mac.mm index eb093e8..c2812482 100644 --- a/chrome/browser/policy/policy_path_parser_mac.mm +++ b/chrome/browser/policy/policy_path_parser_mac.mm
@@ -91,6 +91,8 @@ int error = SCError(); LOG(ERROR) << "Machine name variable can not be resolved. Error: " << error << " - " << SCErrorString(error); + // Revert to a safe default if it is impossible to fetch the real name. + result.replace(position, strlen(kMachineNamePolicyVarName), "localhost"); } } return result;
diff --git a/chrome/browser/policy/policy_path_parser_unittest.cc b/chrome/browser/policy/policy_path_parser_unittest.cc index 54eea1a5..893b760 100644 --- a/chrome/browser/policy/policy_path_parser_unittest.cc +++ b/chrome/browser/policy/policy_path_parser_unittest.cc
@@ -23,17 +23,7 @@ } }; -// TODO(pastarmovj): Modify test or change the logic after investigating why it -// is flaky. Please only redisable after it has had a chance to run for a few -// times. See bug http://crbug.com/327520 for context. -// TODO(pastarmovj): Disabling on Mac OS X as the test is flaky. See -// crbug.com/458590 for details. -#if defined(OS_MACOSX) -#define MAYBE_AllPlatformVariables DISABLED_AllPlatformVariables -#else -#define MAYBE_AllPlatformVariables AllPlatformVariables -#endif -TEST_F(PolicyPathParserTests, MAYBE_AllPlatformVariables) { +TEST_F(PolicyPathParserTests, AllPlatformVariables) { // No vars whatsoever no substitution should occur. base::FilePath::StringType no_vars(FILE_PATH_LITERAL("//$C/shares")); base::FilePath::StringType no_vars_result =
diff --git a/chrome/browser/prefs/incognito_mode_prefs.cc b/chrome/browser/prefs/incognito_mode_prefs.cc index 6f3bb9c..3b39702 100644 --- a/chrome/browser/prefs/incognito_mode_prefs.cc +++ b/chrome/browser/prefs/incognito_mode_prefs.cc
@@ -196,7 +196,7 @@ void IncognitoModePrefs::InitializePlatformParentalControls() { base::CreateCOMSTATaskRunnerWithTraits( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}) - ->PostTask(FROM_HERE, base::Bind(base::IgnoreResult( + ->PostTask(FROM_HERE, base::BindOnce(base::IgnoreResult( &PlatformParentalControlsValue::GetInstance))); } #endif
diff --git a/chrome/browser/previews/previews_lite_page_infobar_delegate.cc b/chrome/browser/previews/previews_lite_page_infobar_delegate.cc index 97044d1..4ca3b781 100644 --- a/chrome/browser/previews/previews_lite_page_infobar_delegate.cc +++ b/chrome/browser/previews/previews_lite_page_infobar_delegate.cc
@@ -75,7 +75,7 @@ #if defined(OS_ANDROID) int PreviewsLitePageInfoBarDelegate::GetIconId() const { - return IDR_ANDROID_INFOBAR_PREVIEWS; + return IDR_ANDROID_INFOBAR_LITE_MODE; } base::string16 PreviewsLitePageInfoBarDelegate::GetLinkText() const {
diff --git a/chrome/browser/previews/previews_lite_page_infobar_delegate_unittest.cc b/chrome/browser/previews/previews_lite_page_infobar_delegate_unittest.cc index a3c8837..c849b90 100644 --- a/chrome/browser/previews/previews_lite_page_infobar_delegate_unittest.cc +++ b/chrome/browser/previews/previews_lite_page_infobar_delegate_unittest.cc
@@ -80,7 +80,7 @@ #if defined(OS_ANDROID) ASSERT_EQ(l10n_util::GetStringUTF16(IDS_LITE_PAGE_PREVIEWS_SETTINGS_LINK), infobar->GetLinkText()); - ASSERT_EQ(IDR_ANDROID_INFOBAR_PREVIEWS, infobar->GetIconId()); + ASSERT_EQ(IDR_ANDROID_INFOBAR_LITE_MODE, infobar->GetIconId()); #else ASSERT_EQ(base::string16(), infobar->GetLinkText()); ASSERT_EQ(PreviewsLitePageInfoBarDelegate::kNoIconID, infobar->GetIconId());
diff --git a/chrome/browser/profiles/profile_shortcut_manager_win.cc b/chrome/browser/profiles/profile_shortcut_manager_win.cc index 2c4391fb1..d55bcc7 100644 --- a/chrome/browser/profiles/profile_shortcut_manager_win.cc +++ b/chrome/browser/profiles/profile_shortcut_manager_win.cc
@@ -830,7 +830,7 @@ const base::FilePath& profile_path) { base::CreateCOMSTATaskRunnerWithTraits({base::MayBlock()}) ->PostTask(FROM_HERE, - base::Bind(&DeleteDesktopShortcuts, profile_path, false)); + base::BindOnce(&DeleteDesktopShortcuts, profile_path, false)); } void ProfileShortcutManagerWin::HasProfileShortcuts( @@ -905,8 +905,9 @@ } base::CreateCOMSTATaskRunnerWithTraits({base::MayBlock()}) - ->PostTask(FROM_HERE, base::Bind(&DeleteDesktopShortcuts, profile_path, - deleting_down_to_last_profile)); + ->PostTask(FROM_HERE, + base::BindOnce(&DeleteDesktopShortcuts, profile_path, + deleting_down_to_last_profile)); } void ProfileShortcutManagerWin::OnProfileNameChanged( @@ -1000,9 +1001,9 @@ } } base::CreateCOMSTATaskRunnerWithTraits({base::MayBlock()}) - ->PostTask( - FROM_HERE, - base::Bind(&CreateOrUpdateDesktopShortcutsAndIconForProfile, params)); + ->PostTask(FROM_HERE, + base::BindOnce( + &CreateOrUpdateDesktopShortcutsAndIconForProfile, params)); entry->SetShortcutName(params.profile_name); }
diff --git a/chrome/browser/resources/settings/people_page/account_manager.html b/chrome/browser/resources/settings/people_page/account_manager.html index f19e5239..d6d68bd 100644 --- a/chrome/browser/resources/settings/people_page/account_manager.html +++ b/chrome/browser/resources/settings/people_page/account_manager.html
@@ -40,13 +40,13 @@ width: 24px; } - #error-badge { + .error-badge { left: 60%; position: relative; top: 60%; } - :host-context([dir='rtl']) #error-badge { + :host-context([dir='rtl']) .error-badge { left: auto; right: 60%; } @@ -71,7 +71,8 @@ <div class="profile-icon" style="background-image: [[getIconImageSet_(item.pic)]]"> <template is="dom-if" if="[[!item.isSignedIn]]"> - <img id="error-badge" src="chrome://resources/images/error_badge.svg"> + <img class="error-badge" + src="chrome://resources/images/error_badge.svg"> </template> </div> @@ -83,15 +84,21 @@ </template> <!-- Else, display a re-authentication message --> <template is="dom-if" if="[[!item.isSignedIn]]"> - <span style="color:red">$i18n{accountManagerSignedOutAccountName}</span> + <span style="color:red"> + $i18n{accountManagerSignedOutAccountName} + </span> </template> <div class="secondary">[[item.email]]</div> </div> </div> - <template is="dom-if" if="[[shouldShowReauthenticationButton_(item)]]"> - <paper-button on-click="onReauthenticationTap_">$i18n{accountManagerReauthenticationLabel}</paper-button> + <template is="dom-if" + if="[[shouldShowReauthenticationButton_(item)]]"> + <paper-button class="reauth-button" + on-click="onReauthenticationTap_"> + $i18n{accountManagerReauthenticationLabel} + </paper-button> </template> <paper-icon-button-light class="icon-more-vert"
diff --git a/chrome/browser/resources/settings/people_page/account_manager.js b/chrome/browser/resources/settings/people_page/account_manager.js index 2bb2b8b..37d637f 100644 --- a/chrome/browser/resources/settings/people_page/account_manager.js +++ b/chrome/browser/resources/settings/people_page/account_manager.js
@@ -92,12 +92,11 @@ }, /** - * @param {!Event} event + * @param {!CustomEvent<!{model: !{item: !settings.Account}}>} event * @private */ onReauthenticationTap_: function(event) { - this.browserProxy_.reauthenticateAccount( - this.$['account-list'].itemForElement(event.path[0]).email); + this.browserProxy_.reauthenticateAccount(event.model.item.email); }, /**
diff --git a/chrome/browser/resources/settings/route.js b/chrome/browser/resources/settings/route.js index 61d7c61c..8d46e3b0 100644 --- a/chrome/browser/resources/settings/route.js +++ b/chrome/browser/resources/settings/route.js
@@ -10,6 +10,7 @@ * ABOUT_ABOUT: (undefined|!settings.Route), * ACCESSIBILITY: (undefined|!settings.Route), * ACCOUNTS: (undefined|!settings.Route), + * ACCOUNT_MANAGER: (undefined|!settings.Route), * ADVANCED: (undefined|!settings.Route), * ADDRESSES: (undefined|!settings.Route), * ANDROID_APPS: (undefined|!settings.Route),
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.cc index 37a84295..638fa057 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.cc
@@ -402,7 +402,7 @@ // request is sent to the parent process and before the response gets // handled on the IPC thread. base::SequencedTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind([]() { exit(kDeliberateCrashExitCode); })); + FROM_HERE, base::BindOnce([]() { exit(kDeliberateCrashExitCode); })); } (*chrome_prompt_ptr_)
diff --git a/chrome/browser/safe_browsing/test_safe_browsing_database_helper.cc b/chrome/browser/safe_browsing/test_safe_browsing_database_helper.cc index b28a68c..bddda286 100644 --- a/chrome/browser/safe_browsing/test_safe_browsing_database_helper.cc +++ b/chrome/browser/safe_browsing/test_safe_browsing_database_helper.cc
@@ -33,7 +33,7 @@ void DisplayBlockingPage(const UnsafeResource& resource) override { resource.callback_thread->PostTask( - FROM_HERE, base::Bind(resource.callback, true /* proceed */)); + FROM_HERE, base::BindOnce(resource.callback, true /* proceed */)); } private:
diff --git a/chrome/browser/service_process/service_process_control.cc b/chrome/browser/service_process/service_process_control.cc index 80e2f23..28e34f80 100644 --- a/chrome/browser/service_process/service_process_control.cc +++ b/chrome/browser/service_process/service_process_control.cc
@@ -370,7 +370,7 @@ // If the service process is not launched yet then check again in 2 seconds. const base::TimeDelta kDetectLaunchRetry = base::TimeDelta::FromSeconds(2); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, base::Bind(&Launcher::DoDetectLaunched, this), + FROM_HERE, base::BindOnce(&Launcher::DoDetectLaunched, this), kDetectLaunchRetry); }
diff --git a/chrome/browser/shell_integration.cc b/chrome/browser/shell_integration.cc index eb425442..d38034b 100644 --- a/chrome/browser/shell_integration.cc +++ b/chrome/browser/shell_integration.cc
@@ -156,12 +156,12 @@ void DefaultWebClientWorker::StartCheckIsDefault() { g_sequenced_task_runner.Get()->PostTask( FROM_HERE, - base::Bind(&DefaultWebClientWorker::CheckIsDefault, this, false)); + base::BindOnce(&DefaultWebClientWorker::CheckIsDefault, this, false)); } void DefaultWebClientWorker::StartSetAsDefault() { g_sequenced_task_runner.Get()->PostTask( - FROM_HERE, base::Bind(&DefaultWebClientWorker::SetAsDefault, this)); + FROM_HERE, base::BindOnce(&DefaultWebClientWorker::SetAsDefault, this)); } ///////////////////////////////////////////////////////////////////////////////
diff --git a/chrome/browser/shell_integration_win.cc b/chrome/browser/shell_integration_win.cc index 17433d1..061c0c2 100644 --- a/chrome/browser/shell_integration_win.cc +++ b/chrome/browser/shell_integration_win.cc
@@ -734,7 +734,7 @@ // urgent task. base::CreateCOMSTATaskRunnerWithTraits( {base::MayBlock(), base::TaskPriority::BEST_EFFORT}) - ->PostTask(FROM_HERE, base::Bind(&MigrateTaskbarPinsCallback)); + ->PostTask(FROM_HERE, base::BindOnce(&MigrateTaskbarPinsCallback)); } void GetIsPinnedToTaskbarState(
diff --git a/chrome/browser/speech/extension_api/tts_extension_apitest.cc b/chrome/browser/speech/extension_api/tts_extension_apitest.cc index 168b2aea..3812af1f 100644 --- a/chrome/browser/speech/extension_api/tts_extension_apitest.cc +++ b/chrome/browser/speech/extension_api/tts_extension_apitest.cc
@@ -106,9 +106,9 @@ void SendEndEventOnSavedUtteranceId() { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&MockTtsPlatformImpl::SendEvent, ptr_factory_.GetWeakPtr(), - false, g_saved_utterance_id, content::TTS_EVENT_END, 0, 0, - std::string()), + base::BindOnce(&MockTtsPlatformImpl::SendEvent, + ptr_factory_.GetWeakPtr(), false, g_saved_utterance_id, + content::TTS_EVENT_END, 0, 0, std::string()), base::TimeDelta()); } @@ -119,9 +119,10 @@ const content::UtteranceContinuousParameters& params) { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&MockTtsPlatformImpl::SendEvent, ptr_factory_.GetWeakPtr(), - false, utterance_id, content::TTS_EVENT_END, - utterance.size(), 0, std::string()), + base::BindOnce(&MockTtsPlatformImpl::SendEvent, + ptr_factory_.GetWeakPtr(), false, utterance_id, + content::TTS_EVENT_END, utterance.size(), 0, + std::string()), base::TimeDelta()); } @@ -133,9 +134,10 @@ const content::UtteranceContinuousParameters& params) { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&MockTtsPlatformImpl::SendEvent, ptr_factory_.GetWeakPtr(), - true, utterance_id, content::TTS_EVENT_END, utterance.size(), - 0, std::string()), + base::BindOnce(&MockTtsPlatformImpl::SendEvent, + ptr_factory_.GetWeakPtr(), true, utterance_id, + content::TTS_EVENT_END, utterance.size(), 0, + std::string()), base::TimeDelta()); } @@ -148,9 +150,9 @@ if (i == 0 || utterance[i - 1] == ' ') { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&MockTtsPlatformImpl::SendEvent, - ptr_factory_.GetWeakPtr(), false, utterance_id, - content::TTS_EVENT_WORD, i, 1, std::string()), + base::BindOnce(&MockTtsPlatformImpl::SendEvent, + ptr_factory_.GetWeakPtr(), false, utterance_id, + content::TTS_EVENT_WORD, i, 1, std::string()), base::TimeDelta()); } } @@ -167,9 +169,9 @@ if (wait_for_non_empty_queue && tts_controller->QueueSize() == 0) { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&MockTtsPlatformImpl::SendEvent, ptr_factory_.GetWeakPtr(), - true, utterance_id, event_type, char_index, length, - message), + base::BindOnce(&MockTtsPlatformImpl::SendEvent, + ptr_factory_.GetWeakPtr(), true, utterance_id, + event_type, char_index, length, message), base::TimeDelta::FromMilliseconds(100)); return; }
diff --git a/chrome/browser/supervised_user/supervised_user_navigation_throttle.cc b/chrome/browser/supervised_user/supervised_user_navigation_throttle.cc index f031118..968a0ef 100644 --- a/chrome/browser/supervised_user/supervised_user_navigation_throttle.cc +++ b/chrome/browser/supervised_user/supervised_user_navigation_throttle.cc
@@ -176,8 +176,8 @@ // SupervisedUserNavigationObserver. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&SupervisedUserNavigationThrottle::ShowInterstitialAsync, - weak_ptr_factory_.GetWeakPtr(), reason)); + base::BindOnce(&SupervisedUserNavigationThrottle::ShowInterstitialAsync, + weak_ptr_factory_.GetWeakPtr(), reason)); } void SupervisedUserNavigationThrottle::ShowInterstitialAsync(
diff --git a/chrome/browser/sync/test/integration/autofill_helper.cc b/chrome/browser/sync/test/integration/autofill_helper.cc index 9684611..d8744726 100644 --- a/chrome/browser/sync/test/integration/autofill_helper.cc +++ b/chrome/browser/sync/test/integration/autofill_helper.cc
@@ -86,7 +86,7 @@ AutofillWebDataServiceObserverOnDBSequence*) = &AutofillWebDataService::AddObserver; wds->GetDBTaskRunner()->PostTask( - FROM_HERE, base::Bind(add_observer_func, wds, &mock_observer)); + FROM_HERE, base::BindOnce(add_observer_func, wds, &mock_observer)); wds->RemoveFormValueForElementName(key.name(), key.value()); done_event.Wait(); @@ -95,7 +95,7 @@ AutofillWebDataServiceObserverOnDBSequence*) = &AutofillWebDataService::RemoveObserver; wds->GetDBTaskRunner()->PostTask( - FROM_HERE, base::Bind(remove_observer_func, wds, &mock_observer)); + FROM_HERE, base::BindOnce(remove_observer_func, wds, &mock_observer)); } void GetAllAutofillEntriesOnDBSequence(AutofillWebDataService* wds, @@ -108,8 +108,8 @@ std::vector<AutofillEntry> GetAllAutofillEntries(AutofillWebDataService* wds) { std::vector<AutofillEntry> entries; wds->GetDBTaskRunner()->PostTask( - FROM_HERE, base::Bind(&GetAllAutofillEntriesOnDBSequence, - base::Unretained(wds), &entries)); + FROM_HERE, base::BindOnce(&GetAllAutofillEntriesOnDBSequence, + base::Unretained(wds), &entries)); WaitForCurrentTasksToComplete(wds->GetDBTaskRunner()); return entries; } @@ -236,7 +236,7 @@ AutofillWebDataServiceObserverOnDBSequence*) = &AutofillWebDataService::AddObserver; wds->GetDBTaskRunner()->PostTask( - FROM_HERE, base::Bind(add_observer_func, wds, &mock_observer)); + FROM_HERE, base::BindOnce(add_observer_func, wds, &mock_observer)); wds->AddFormFields(form_fields); done_event.Wait(); @@ -246,7 +246,7 @@ AutofillWebDataServiceObserverOnDBSequence*) = &AutofillWebDataService::RemoveObserver; wds->GetDBTaskRunner()->PostTask( - FROM_HERE, base::Bind(remove_observer_func, wds, &mock_observer)); + FROM_HERE, base::BindOnce(remove_observer_func, wds, &mock_observer)); } void RemoveKey(int profile, const AutofillKey& key) {
diff --git a/chrome/browser/sync_file_system/drive_backend/drive_service_on_worker.cc b/chrome/browser/sync_file_system/drive_backend/drive_service_on_worker.cc index e895a76..92a7a2d 100644 --- a/chrome/browser/sync_file_system/drive_backend/drive_service_on_worker.cc +++ b/chrome/browser/sync_file_system/drive_backend/drive_service_on_worker.cc
@@ -171,10 +171,11 @@ DCHECK(sequence_checker_.CalledOnValidSequence()); ui_task_runner_->PostTask( - FROM_HERE, base::Bind(&DriveServiceWrapper::GetRemainingTeamDriveList, - wrapper_, page_token, - RelayCallbackToTaskRunner(worker_task_runner_.get(), - FROM_HERE, callback))); + FROM_HERE, + base::BindOnce(&DriveServiceWrapper::GetRemainingTeamDriveList, wrapper_, + page_token, + RelayCallbackToTaskRunner(worker_task_runner_.get(), + FROM_HERE, callback))); return google_apis::CancelCallback(); }
diff --git a/chrome/browser/task_manager/providers/fallback_task_provider.cc b/chrome/browser/task_manager/providers/fallback_task_provider.cc index 5f14796..757623a 100644 --- a/chrome/browser/task_manager/providers/fallback_task_provider.cc +++ b/chrome/browser/task_manager/providers/fallback_task_provider.cc
@@ -94,8 +94,8 @@ base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&FallbackTaskProvider::ShowPendingTask, - it->second.GetWeakPtr(), task), + base::BindOnce(&FallbackTaskProvider::ShowPendingTask, + it->second.GetWeakPtr(), task), kTimeDelayForPendingTask); }
diff --git a/chrome/browser/task_manager/sampling/task_manager_io_thread_helper.cc b/chrome/browser/task_manager/sampling/task_manager_io_thread_helper.cc index 639f36d..73db7cb 100644 --- a/chrome/browser/task_manager/sampling/task_manager_io_thread_helper.cc +++ b/chrome/browser/task_manager/sampling/task_manager_io_thread_helper.cc
@@ -114,8 +114,8 @@ // them after one second from now. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&TaskManagerIoThreadHelper::OnMultipleBytesTransferredIO, - weak_factory_.GetWeakPtr()), + base::BindOnce(&TaskManagerIoThreadHelper::OnMultipleBytesTransferredIO, + weak_factory_.GetWeakPtr()), base::TimeDelta::FromSeconds(1)); }
diff --git a/chrome/browser/themes/theme_service.cc b/chrome/browser/themes/theme_service.cc index 50cfc6b..857a57c 100644 --- a/chrome/browser/themes/theme_service.cc +++ b/chrome/browser/themes/theme_service.cc
@@ -610,8 +610,8 @@ // RemoveUnusedThemes is called on a task because ClearAllThemeData() may // be called as a result of OnExtensionUnloaded(). base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&ThemeService::RemoveUnusedThemes, - weak_ptr_factory_.GetWeakPtr(), true)); + FROM_HERE, base::BindOnce(&ThemeService::RemoveUnusedThemes, + weak_ptr_factory_.GetWeakPtr(), true)); } void ThemeService::FixInconsistentPreferencesIfNeeded() {} @@ -845,8 +845,9 @@ #endif base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, base::Bind(&ThemeService::RemoveUnusedThemes, - weak_ptr_factory_.GetWeakPtr(), false), + FROM_HERE, + base::BindOnce(&ThemeService::RemoveUnusedThemes, + weak_ptr_factory_.GetWeakPtr(), false), base::TimeDelta::FromSeconds(kRemoveUnusedThemesStartupDelay)); } @@ -928,8 +929,8 @@ // Write the packed file to disk. extensions::GetExtensionFileTaskRunner()->PostTask( - FROM_HERE, base::Bind(&WritePackToDiskCallback, base::RetainedRef(pack), - extension->path())); + FROM_HERE, base::BindOnce(&WritePackToDiskCallback, + base::RetainedRef(pack), extension->path())); const std::string previous_theme_id = GetThemeID(); const bool previous_using_system_theme = UsingSystemTheme();
diff --git a/chrome/browser/ui/autofill/card_unmask_prompt_view_browsertest.cc b/chrome/browser/ui/autofill/card_unmask_prompt_view_browsertest.cc index c2173d9..a7053c2d 100644 --- a/chrome/browser/ui/autofill/card_unmask_prompt_view_browsertest.cc +++ b/chrome/browser/ui/autofill/card_unmask_prompt_view_browsertest.cc
@@ -95,9 +95,9 @@ } base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&TestCardUnmaskPromptController::ShowVerificationResult, - weak_factory_.GetWeakPtr(), verification_message, - /*allow_retry=*/expected_failure_temporary_), + base::BindOnce(&TestCardUnmaskPromptController::ShowVerificationResult, + weak_factory_.GetWeakPtr(), verification_message, + /*allow_retry=*/expected_failure_temporary_), GetSuccessMessageDuration()); }
diff --git a/chrome/browser/ui/cocoa/first_run_dialog.mm b/chrome/browser/ui/cocoa/first_run_dialog.mm index cce027c..0f4eeeab 100644 --- a/chrome/browser/ui/cocoa/first_run_dialog.mm +++ b/chrome/browser/ui/cocoa/first_run_dialog.mm
@@ -157,8 +157,8 @@ // Barring a shutdown signal, the run loop will quit when the user closes the // first run dialog. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&FirstRunShowBridge::ShowDialog, bridge.get(), - run_loop.QuitClosure())); + FROM_HERE, base::BindOnce(&FirstRunShowBridge::ShowDialog, bridge.get(), + run_loop.QuitClosure())); run_loop.Run(); static_cast<BrowserProcessImpl*>(g_browser_process)->ClearQuitClosure();
diff --git a/chrome/browser/ui/cocoa/history_menu_bridge.mm b/chrome/browser/ui/cocoa/history_menu_bridge.mm index a6f2115..5bd546b 100644 --- a/chrome/browser/ui/cocoa/history_menu_bridge.mm +++ b/chrome/browser/ui/cocoa/history_menu_bridge.mm
@@ -240,7 +240,7 @@ if (!is_menu_open_ && need_recreate_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&HistoryMenuBridge::CreateMenu, base::Unretained(this))); + base::BindOnce(&HistoryMenuBridge::CreateMenu, base::Unretained(this))); } }
diff --git a/chrome/browser/ui/cocoa/keystone_infobar_delegate.mm b/chrome/browser/ui/cocoa/keystone_infobar_delegate.mm index 8c809b2..2be2e21 100644 --- a/chrome/browser/ui/cocoa/keystone_infobar_delegate.mm +++ b/chrome/browser/ui/cocoa/keystone_infobar_delegate.mm
@@ -54,8 +54,9 @@ const base::TimeDelta kCanExpireOnNavigationAfterDelay = base::TimeDelta::FromSeconds(8); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, base::Bind(&KeystonePromotionInfoBarDelegate::SetCanExpire, - weak_ptr_factory_.GetWeakPtr()), + FROM_HERE, + base::BindOnce(&KeystonePromotionInfoBarDelegate::SetCanExpire, + weak_ptr_factory_.GetWeakPtr()), kCanExpireOnNavigationAfterDelay); }
diff --git a/chrome/browser/ui/find_bar/find_bar_controller.cc b/chrome/browser/ui/find_bar/find_bar_controller.cc index 53094a6..a731531 100644 --- a/chrome/browser/ui/find_bar/find_bar_controller.cc +++ b/chrome/browser/ui/find_bar/find_bar_controller.cc
@@ -123,10 +123,6 @@ ResultAction result_action) { find_bar_->Hide(true); - // If the user searches again for this string, it should notify if the result - // comes back empty again. - alerted_search_.clear(); - // |web_contents_| can be NULL for a number of reasons, for example when the // tab is closing. We must guard against that case. See issue 8030. if (web_contents_) { @@ -209,39 +205,14 @@ } //////////////////////////////////////////////////////////////////////////////// -// FindBarHost, content::NotificationObserver implementation: +// FindBarController, content::NotificationObserver implementation: void FindBarController::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { - FindTabHelper* find_tab_helper = - FindTabHelper::FromWebContents(web_contents_); if (type == chrome::NOTIFICATION_FIND_RESULT_AVAILABLE) { - // Don't update for notifications from WebContentses other than the one we - // are actively tracking. - if (content::Source<WebContents>(source).ptr() == web_contents_) { - UpdateFindBarForCurrentResult(); - - // A final update can occur multiple times if the document changes. - if (find_tab_helper->find_result().final_update() && - find_tab_helper->find_result().number_of_matches() == 0) { - const base::string16& last_search = - find_tab_helper->previous_find_text(); - const base::string16& current_search = find_tab_helper->find_text(); - - // Alert the user once per unique search, if they aren't backspacing. - if (current_search != alerted_search_) { - // Keep track of the last notified search string, even if the - // notification itself is elided. - if (!base::StartsWith(last_search, current_search, - base::CompareCase::SENSITIVE)) { - find_bar_->AudibleAlert(); - } - - alerted_search_ = current_search; - } - } - } + DCHECK(content::Source<WebContents>(source).ptr() == web_contents_); + OnFindResultAvailable(); } else if (type == content::NOTIFICATION_NAV_ENTRY_COMMITTED) { NavigationController* source_controller = content::Source<NavigationController>(source).ptr(); @@ -300,6 +271,33 @@ return new_pos; } +void FindBarController::OnFindResultAvailable() { + UpdateFindBarForCurrentResult(); + + FindTabHelper* find_tab_helper = + FindTabHelper::FromWebContents(web_contents_); + + // Only "final" results may audibly alert the user. + if (!find_tab_helper->find_result().final_update()) + return; + + const base::string16& current_search = find_tab_helper->find_text(); + + // If no results were found, play an audible alert (depending upon platform + // convention). Alert only once per unique search, and don't alert on + // backspace. + if ((find_tab_helper->find_result().number_of_matches() == 0) && + (current_search != find_tab_helper->last_completed_find_text() && + !base::StartsWith(find_tab_helper->previous_find_text(), current_search, + base::CompareCase::SENSITIVE))) { + find_bar_->AudibleAlert(); + } + + // Record the completion of the search to suppress future alerts, even if the + // page's contents change. + find_tab_helper->set_last_completed_find_text(current_search); +} + void FindBarController::UpdateFindBarForCurrentResult() { FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents_);
diff --git a/chrome/browser/ui/find_bar/find_bar_controller.h b/chrome/browser/ui/find_bar/find_bar_controller.h index ac510bd6..f6c5692c 100644 --- a/chrome/browser/ui/find_bar/find_bar_controller.h +++ b/chrome/browser/ui/find_bar/find_bar_controller.h
@@ -88,8 +88,12 @@ const gfx::Rect& avoid_overlapping_rect); private: - // Sents an update to the find bar with the tab contents' current result. The - // web_contents_ must be non-NULL before this call. Theis handles + // Called when we've received notice of a find result for the associated + // WebContents. + void OnFindResultAvailable(); + + // Sends an update to the find bar with the tab contents' current result. The + // web_contents_ must be non-NULL before this call. This handles // de-flickering in addition to just calling the update function. void UpdateFindBarForCurrentResult(); @@ -117,12 +121,6 @@ int last_reported_matchcount_ = 0; int last_reported_ordinal_ = 0; - // Used to keep track of whether the user has been notified that the find came - // up empty. A single find session can result in multiple final updates, if - // the document contents change dynamically. It's a nuisance to notify the - // user more than once that a search came up empty, however. - base::string16 alerted_search_; - DISALLOW_COPY_AND_ASSIGN(FindBarController); };
diff --git a/chrome/browser/ui/find_bar/find_bar_host_browsertest.cc b/chrome/browser/ui/find_bar/find_bar_host_browsertest.cc index 8d4afa7..9b67ca5 100644 --- a/chrome/browser/ui/find_bar/find_bar_host_browsertest.cc +++ b/chrome/browser/ui/find_bar/find_bar_host_browsertest.cc
@@ -339,6 +339,31 @@ EXPECT_EQ(1u, GetFindBarAudibleAlertsForBrowser(browser())); } +// This test navigates to a different page after a successful search and +// verifies this doesn't cause any extraneous dings. +IN_PROC_BROWSER_TEST_F(FindInPageControllerTest, NoAudibleAlertOnNavigation) { + // First we navigate to our frames page. + GURL url = GetURL(kFramePage); + ui_test_utils::NavigateToURL(browser(), url); + + int ordinal = 0; + WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + EXPECT_EQ(0u, GetFindBarAudibleAlertsForBrowser(browser())); + + // Search for a string in the page. + EXPECT_EQ( + 1, FindInPageASCII(web_contents, "google", kFwd, kIgnoreCase, &ordinal)); + EXPECT_EQ(1, ordinal); + EXPECT_EQ(0u, GetFindBarAudibleAlertsForBrowser(browser())); + + // Navigate to a different page. + ui_test_utils::NavigateToURL(browser(), GetURL("specialchar.html")); + + // Ensure that there was no audible alert. + EXPECT_EQ(0u, GetFindBarAudibleAlertsForBrowser(browser())); +} + // Verify search selection coordinates. The data file used is set-up such that // the text occurs on the same line, and we verify their positions by verifying // their relative positions.
diff --git a/chrome/browser/ui/find_bar/find_tab_helper.cc b/chrome/browser/ui/find_bar/find_tab_helper.cc index 4574c6e..e72ea07 100644 --- a/chrome/browser/ui/find_bar/find_tab_helper.cc +++ b/chrome/browser/ui/find_bar/find_tab_helper.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/ui/find_bar/find_tab_helper.h" +#include <utility> #include <vector> #include "base/strings/string_util.h" @@ -115,6 +116,7 @@ previous_find_text_ = find_text_; } find_text_.clear(); + last_completed_find_text_.clear(); find_op_aborted_ = true; last_search_result_ = FindNotificationDetails();
diff --git a/chrome/browser/ui/find_bar/find_tab_helper.h b/chrome/browser/ui/find_bar/find_tab_helper.h index 729a7990..4b47546 100644 --- a/chrome/browser/ui/find_bar/find_tab_helper.h +++ b/chrome/browser/ui/find_bar/find_tab_helper.h
@@ -61,6 +61,16 @@ // Accessor for the previous search we issued. base::string16 previous_find_text() const { return previous_find_text_; } + // Accessor for the latest search for which a final result was reported. + base::string16 last_completed_find_text() const { + return last_completed_find_text_; + } + + void set_last_completed_find_text( + const base::string16& last_completed_find_text) { + last_completed_find_text_ = last_completed_find_text; + } + gfx::Range selected_range() const { return selected_range_; } void set_selected_range(const gfx::Range& selected_range) { selected_range_ = selected_range; @@ -121,6 +131,14 @@ // The string we searched for before |find_text_|. base::string16 previous_find_text_; + // Used to keep track the last completed search. A single find session can + // result in multiple final updates, if the document contents change + // dynamically. It's a nuisance to notify the user more than once that a + // search came up empty, and we never want to notify the user that a + // previously successful search's results were removed because, + // for instance, the page is being torn down during navigation. + base::string16 last_completed_find_text_; + // The selection within the text. gfx::Range selected_range_;
diff --git a/chrome/browser/ui/views/autofill/autofill_popup_view_native_views.cc b/chrome/browser/ui/views/autofill/autofill_popup_view_native_views.cc index 3deee8fb..03562bbb 100644 --- a/chrome/browser/ui/views/autofill/autofill_popup_view_native_views.cc +++ b/chrome/browser/ui/views/autofill/autofill_popup_view_native_views.cc
@@ -393,7 +393,7 @@ (GetLayoutType() == PopupItemLayoutType::kLeadingIcon || GetLayoutType() == PopupItemLayoutType::kTwoLinesLeadingIcon)) { AddIcon(icon); - AddSpacerWithSize(views::MenuConfig::instance().item_horizontal_padding, + AddSpacerWithSize(GetHorizontalMargin(), /*resize=*/false, layout_manager); } @@ -430,7 +430,7 @@ AddChildView(description_label); if (!icon.isNull() && GetLayoutType() == PopupItemLayoutType::kTrailingIcon) { - AddSpacerWithSize(views::MenuConfig::instance().item_horizontal_padding, + AddSpacerWithSize(GetHorizontalMargin(), /*resize=*/false, layout_manager); AddIcon(icon); }
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_bar_view_test.cc b/chrome/browser/ui/views/bookmarks/bookmark_bar_view_test.cc index 1a55c267..b12ee4b 100644 --- a/chrome/browser/ui/views/bookmarks/bookmark_bar_view_test.cc +++ b/chrome/browser/ui/views/bookmarks/bookmark_bar_view_test.cc
@@ -2292,7 +2292,7 @@ base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&BookmarkBarViewTest26::Step3, base::Unretained(this))); + base::BindOnce(&BookmarkBarViewTest26::Step3, base::Unretained(this))); } void Step3() {
diff --git a/chrome/browser/ui/views/chrome_views_delegate_chromeos.cc b/chrome/browser/ui/views/chrome_views_delegate_chromeos.cc index 16359c5..22434a76 100644 --- a/chrome/browser/ui/views/chrome_views_delegate_chromeos.cc +++ b/chrome/browser/ui/views/chrome_views_delegate_chromeos.cc
@@ -40,7 +40,7 @@ if (accelerator_controller->ShouldCloseMenuAndRepostAccelerator( accelerator)) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(ProcessAcceleratorNow, accelerator)); + FROM_HERE, base::BindOnce(ProcessAcceleratorNow, accelerator)); return views::ViewsDelegate::ProcessMenuAcceleratorResult::CLOSE_MENU; }
diff --git a/chrome/browser/ui/views/frame/app_menu_button.cc b/chrome/browser/ui/views/frame/app_menu_button.cc index b7baf66..676dd1e 100644 --- a/chrome/browser/ui/views/frame/app_menu_button.cc +++ b/chrome/browser/ui/views/frame/app_menu_button.cc
@@ -7,12 +7,15 @@ #include <utility> #include "chrome/browser/ui/toolbar/app_menu_model.h" +#include "chrome/browser/ui/views/chrome_typography.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" AppMenuButton::AppMenuButton(views::MenuButtonListener* menu_button_listener) - : views::MenuButton(base::string16(), menu_button_listener) {} + : views::MenuButton(base::string16(), + menu_button_listener, + CONTEXT_TOOLBAR_BUTTON) {} AppMenuButton::~AppMenuButton() {}
diff --git a/chrome/browser/ui/views/passwords/password_bubble_interactive_uitest.cc b/chrome/browser/ui/views/passwords/password_bubble_interactive_uitest.cc index 378b041..9466be3 100644 --- a/chrome/browser/ui/views/passwords/password_bubble_interactive_uitest.cc +++ b/chrome/browser/ui/views/passwords/password_bubble_interactive_uitest.cc
@@ -312,7 +312,7 @@ PasswordBubbleViewBase::manage_password_bubble(); bool ran_event_task = false; base::SequencedTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(press_button, bubble, &ran_event_task)); + FROM_HERE, base::BindOnce(press_button, bubble, &ran_event_task)); EXPECT_TRUE(IsBubbleShowing()); // Close the tab.
diff --git a/chrome/browser/ui/views/select_file_dialog_extension.cc b/chrome/browser/ui/views/select_file_dialog_extension.cc index 96831291..8c93be1 100644 --- a/chrome/browser/ui/views/select_file_dialog_extension.cc +++ b/chrome/browser/ui/views/select_file_dialog_extension.cc
@@ -238,10 +238,11 @@ if (profile_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&extensions::ExtensionService::ReloadExtension, - base::Unretained(extensions::ExtensionSystem::Get(profile_) - ->extension_service()), - extension_id)); + base::BindOnce( + &extensions::ExtensionService::ReloadExtension, + base::Unretained(extensions::ExtensionSystem::Get(profile_) + ->extension_service()), + extension_id)); } dialog->GetWidget()->Close();
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 4a025ea..f51f7bd 100644 --- a/chrome/browser/ui/views/toolbar/browser_app_menu_button.cc +++ b/chrome/browser/ui/views/toolbar/browser_app_menu_button.cc
@@ -303,8 +303,10 @@ } void BrowserAppMenuButton::UpdateBorder() { - SetBorder(views::CreateEmptyBorder(GetLayoutInsets(TOOLBAR_BUTTON) + - *GetProperty(views::kInternalPaddingKey))); + gfx::Insets new_insets = GetLayoutInsets(TOOLBAR_BUTTON) + + *GetProperty(views::kInternalPaddingKey); + if (!border() || border()->GetInsets() != new_insets) + SetBorder(views::CreateEmptyBorder(new_insets)); } void BrowserAppMenuButton::OnBoundsChanged(const gfx::Rect& previous_bounds) {
diff --git a/chrome/browser/ui/views/toolbar/toolbar_button.cc b/chrome/browser/ui/views/toolbar/toolbar_button.cc index 5e7915e..6da32a3 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_button.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_button.cc
@@ -62,6 +62,8 @@ // make to the leading margin to handle Fitts' Law, it's easier to just // allocate the property once and modify the value. SetProperty(views::kInternalPaddingKey, new gfx::Insets()); + + UpdateHighlightBackgroundAndInsets(); } ToolbarButton::~ToolbarButton() {} @@ -101,21 +103,24 @@ SetEnabledTextColors(*highlight_color_); } - gfx::Insets insets = GetLayoutInsets(TOOLBAR_BUTTON) + layout_inset_delta_ + - *GetProperty(views::kInternalPaddingKey); + gfx::Insets new_insets = GetLayoutInsets(TOOLBAR_BUTTON) + + layout_inset_delta_ + + *GetProperty(views::kInternalPaddingKey); + if (!GetText().empty()) { const int text_side_inset = highlight_radius / 2; // Some subclasses (AvatarToolbarButton) may be change alignment. This adds // an inset to the text-label side. if (horizontal_alignment() == gfx::ALIGN_RIGHT) { - insets += gfx::Insets(0, text_side_inset, 0, 0); + new_insets += gfx::Insets(0, text_side_inset, 0, 0); } else { - insets += gfx::Insets(0, 0, 0, text_side_inset); + new_insets += gfx::Insets(0, 0, 0, text_side_inset); } } - SetBorder(views::CreateEmptyBorder(insets)); + if (!border() || new_insets != border()->GetInsets()) + SetBorder(views::CreateEmptyBorder(new_insets)); } void ToolbarButton::SetLayoutInsetDelta(const gfx::Insets& inset_delta) {
diff --git a/chrome/browser/ui/views/try_chrome_dialog_win/try_chrome_dialog_browsertest.cc b/chrome/browser/ui/views/try_chrome_dialog_win/try_chrome_dialog_browsertest.cc index 4fd1e86..d441552 100644 --- a/chrome/browser/ui/views/try_chrome_dialog_win/try_chrome_dialog_browsertest.cc +++ b/chrome/browser/ui/views/try_chrome_dialog_win/try_chrome_dialog_browsertest.cc
@@ -135,8 +135,8 @@ // process. void PostRendezvousTask() { base::SequencedTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&TryChromeDialog::OnProcessNotification, - base::Unretained(dialog_.get()))); + FROM_HERE, base::BindOnce(&TryChromeDialog::OnProcessNotification, + base::Unretained(dialog_.get()))); } // Runs a loop until it is quit via either the dialog being shown (by way of
diff --git a/chrome/browser/vr/BUILD.gn b/chrome/browser/vr/BUILD.gn index 069ae578..359a4107 100644 --- a/chrome/browser/vr/BUILD.gn +++ b/chrome/browser/vr/BUILD.gn
@@ -189,12 +189,8 @@ "//base", "//cc/animation", "//chrome/app:generated_resources", - "//chrome/app/vector_icons", - "//chrome/browser/vr/vector_icons", "//chrome/common:constants", - "//components/omnibox/browser:vector_icons", "//components/url_formatter", - "//components/vector_icons", "//media", "//net", "//skia", @@ -279,14 +275,11 @@ "//base", "//cc/animation", "//cc/paint", - "//chrome/browser/vr/vector_icons", "//chrome/common:constants", "//components/omnibox/browser", "//components/omnibox/browser", - "//components/omnibox/browser:vector_icons", "//components/rappor/public:public", "//components/ukm/content", - "//components/vector_icons", "//content/public/browser", "//device/vr", "//device/vr/buildflags:buildflags", @@ -416,10 +409,14 @@ deps = [ "//base", "//chrome/app:generated_resources", + "//chrome/app/vector_icons", + "//chrome/browser/vr/vector_icons", + "//components/omnibox/browser:vector_icons", "//components/rappor:rappor", "//components/security_state/core", "//components/ukm/content", "//components/url_formatter", + "//components/vector_icons", "//content/public/browser:browser", "//media", "//net",
diff --git a/chrome/browser/vr/elements/disc_button_unittest.cc b/chrome/browser/vr/elements/disc_button_unittest.cc index 7b8df43..e740863 100644 --- a/chrome/browser/vr/elements/disc_button_unittest.cc +++ b/chrome/browser/vr/elements/disc_button_unittest.cc
@@ -11,14 +11,14 @@ #include "chrome/browser/vr/elements/ui_element.h" #include "chrome/browser/vr/elements/vector_icon.h" #include "chrome/browser/vr/ui_scene_constants.h" -#include "components/vector_icons/vector_icons.h" +#include "chrome/browser/vr/ui_support.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/geometry/point_f.h" namespace vr { TEST(DiscButton, HoverTest) { - DiscButton button(base::RepeatingCallback<void()>(), vector_icons::kMicIcon, + DiscButton button(base::RepeatingCallback<void()>(), GetVrIcon(kVrMicIcon), nullptr); button.SetSize(1.0f, 1.0f); button.set_hover_offset(0.5f); @@ -44,7 +44,7 @@ } TEST(DiscButton, SizePropagatesToSubElements) { - DiscButton button(base::RepeatingCallback<void()>(), vector_icons::kMicIcon, + DiscButton button(base::RepeatingCallback<void()>(), GetVrIcon(kVrMicIcon), nullptr); gfx::SizeF size(1000.0f, 1000.0f); gfx::SizeF icon_size = size; @@ -69,7 +69,7 @@ } TEST(DiscButton, DrawPhasePropagatesToSubElements) { - DiscButton button(base::RepeatingCallback<void()>(), vector_icons::kMicIcon, + DiscButton button(base::RepeatingCallback<void()>(), GetVrIcon(kVrMicIcon), nullptr); button.SetDrawPhase(kPhaseOverlayForeground); @@ -79,7 +79,7 @@ } TEST(DiscButton, NamePropagatesToSubElements) { - DiscButton button(base::RepeatingCallback<void()>(), vector_icons::kMicIcon, + DiscButton button(base::RepeatingCallback<void()>(), GetVrIcon(kVrMicIcon), nullptr); button.SetName(kCloseButton);
diff --git a/chrome/browser/vr/elements/indicator_spec.cc b/chrome/browser/vr/elements/indicator_spec.cc index 01005c2..f44e73f 100644 --- a/chrome/browser/vr/elements/indicator_spec.cc +++ b/chrome/browser/vr/elements/indicator_spec.cc
@@ -3,9 +3,8 @@ // found in the LICENSE file. #include "chrome/browser/vr/elements/indicator_spec.h" -#include "chrome/browser/vr/vector_icons/vector_icons.h" +#include "chrome/browser/vr/ui_support.h" #include "chrome/grit/generated_resources.h" -#include "components/vector_icons/vector_icons.h" namespace vr { @@ -43,7 +42,7 @@ std::vector<IndicatorSpec> specs = { {kLocationAccessIndicator, kWebVrLocationAccessIndicator, - kMyLocationIcon, + GetVrIcon(kVrMyLocationIcon), IDS_VR_SHELL_SITE_IS_TRACKING_LOCATION, // Background tabs cannot track high accuracy location. 0, @@ -52,7 +51,7 @@ false}, {kAudioCaptureIndicator, kWebVrAudioCaptureIndicator, - vector_icons::kMicIcon, + GetVrIcon(kVrMicIcon), IDS_VR_SHELL_SITE_IS_USING_MICROPHONE, IDS_VR_SHELL_BG_IS_USING_MICROPHONE, IDS_VR_SHELL_SITE_CAN_USE_MICROPHONE, @@ -60,7 +59,7 @@ false}, {kVideoCaptureIndicator, kWebVrVideoCaptureIndicator, - vector_icons::kVideocamIcon, + GetVrIcon(kVrVideocamIcon), IDS_VR_SHELL_SITE_IS_USING_CAMERA, IDS_VR_SHELL_BG_IS_USING_CAMERA, IDS_VR_SHELL_SITE_CAN_USE_CAMERA, @@ -68,7 +67,7 @@ false}, {kBluetoothConnectedIndicator, kWebVrBluetoothConnectedIndicator, - vector_icons::kBluetoothConnectedIcon, + GetVrIcon(kVrBluetoothConnectedIcon), IDS_VR_SHELL_SITE_IS_USING_BLUETOOTH, IDS_VR_SHELL_BG_IS_USING_BLUETOOTH, IDS_VR_SHELL_SITE_CAN_USE_BLUETOOTH, @@ -76,7 +75,7 @@ false}, {kScreenCaptureIndicator, kWebVrScreenCaptureIndicator, - vector_icons::kScreenShareIcon, + GetVrIcon(kVrScreenShareIcon), IDS_VR_SHELL_SITE_IS_SHARING_SCREEN, IDS_VR_SHELL_BG_IS_SHARING_SCREEN, IDS_VR_SHELL_SITE_CAN_SHARE_SCREEN,
diff --git a/chrome/browser/vr/elements/reticle.cc b/chrome/browser/vr/elements/reticle.cc index 7c3f046..0511dec 100644 --- a/chrome/browser/vr/elements/reticle.cc +++ b/chrome/browser/vr/elements/reticle.cc
@@ -12,7 +12,6 @@ #include "chrome/browser/vr/ui_element_renderer.h" #include "chrome/browser/vr/ui_scene.h" #include "chrome/browser/vr/ui_scene_constants.h" -#include "chrome/browser/vr/vector_icons/vector_icons.h" #include "chrome/browser/vr/vr_gl_util.h" namespace vr {
diff --git a/chrome/browser/vr/elements/vector_icon_button_unittest.cc b/chrome/browser/vr/elements/vector_icon_button_unittest.cc index 243f8412..52688dd 100644 --- a/chrome/browser/vr/elements/vector_icon_button_unittest.cc +++ b/chrome/browser/vr/elements/vector_icon_button_unittest.cc
@@ -6,14 +6,14 @@ #include "chrome/browser/vr/elements/rect.h" #include "chrome/browser/vr/elements/vector_icon.h" -#include "components/vector_icons/vector_icons.h" +#include "chrome/browser/vr/ui_support.h" #include "testing/gtest/include/gtest/gtest.h" namespace vr { TEST(VectorIconButton, CornerRadiiOnResize) { VectorIconButton button(base::RepeatingCallback<void()>(), - vector_icons::kMicIcon, nullptr); + GetVrIcon(kVrMicIcon), nullptr); button.SetSize(1.0f, 1.0f); button.set_corner_radius(0.25f);
diff --git a/chrome/browser/vr/elements/vector_icon_unittest.cc b/chrome/browser/vr/elements/vector_icon_unittest.cc index 5c4591aa..4d64ba3 100644 --- a/chrome/browser/vr/elements/vector_icon_unittest.cc +++ b/chrome/browser/vr/elements/vector_icon_unittest.cc
@@ -12,7 +12,7 @@ #include "chrome/browser/vr/test/animation_utils.h" #include "chrome/browser/vr/test/constants.h" #include "chrome/browser/vr/ui_scene.h" -#include "components/vector_icons/vector_icons.h" +#include "chrome/browser/vr/ui_support.h" namespace vr { @@ -39,7 +39,7 @@ TEST(VectorIcon, SmokeTest) { UiScene scene; auto icon = std::make_unique<TestVectorIcon>(kMaximumWidth); - icon->SetIcon(vector_icons::kCloseRoundedIcon); + icon->SetIcon(GetVrIcon(kVrCloseRoundedIcon)); UiTexture* texture = icon->GetTexture(); scene.AddUiElement(kRoot, std::move(icon)); base::TimeTicks start_time = MsToTicks(1);
diff --git a/chrome/browser/vr/ui_scene_creator.cc b/chrome/browser/vr/ui_scene_creator.cc index a6875eb..afc9756 100644 --- a/chrome/browser/vr/ui_scene_creator.cc +++ b/chrome/browser/vr/ui_scene_creator.cc
@@ -21,7 +21,6 @@ #include "cc/animation/animation_target.h" #include "cc/animation/keyframe_effect.h" #include "cc/animation/keyframed_animation_curve.h" -#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/vr/content_input_delegate.h" #include "chrome/browser/vr/databinding/binding.h" #include "chrome/browser/vr/databinding/vector_binding.h" @@ -71,12 +70,9 @@ #include "chrome/browser/vr/ui_browser_interface.h" #include "chrome/browser/vr/ui_scene.h" #include "chrome/browser/vr/ui_scene_constants.h" -#include "chrome/browser/vr/vector_icons/vector_icons.h" #include "chrome/grit/generated_resources.h" -#include "components/omnibox/browser/vector_icons.h" #include "components/strings/grit/components_strings.h" #include "components/url_formatter/elide_url.h" -#include "components/vector_icons/vector_icons.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/gfx/transform_util.h" @@ -502,7 +498,7 @@ auto app_button = Create<VectorIcon>(kControllerAppButton, kPhaseForeground, 100); - app_button->SetIcon(kDaydreamControllerAppButtonIcon); + app_button->SetIcon(GetVrIcon(kVrDaydreamControllerAppButtonIcon)); app_button->SetColor(model->color_scheme().controller_button); app_button->SetSize(kControllerSmallButtonSize, kControllerSmallButtonSize); app_button->SetRotate(1, 0, 0, -base::kPiFloat / 2); @@ -524,7 +520,7 @@ auto home_button = Create<VectorIcon>(kControllerHomeButton, kPhaseForeground, 100); - home_button->SetIcon(kDaydreamControllerHomeButtonIcon); + home_button->SetIcon(GetVrIcon(kVrDaydreamControllerHomeButtonIcon)); home_button->SetColor(model->color_scheme().controller_button); home_button->SetSize(kControllerSmallButtonSize, kControllerSmallButtonSize); home_button->SetRotate(1, 0, 0, -base::kPiFloat / 2); @@ -1468,7 +1464,7 @@ switch (prompt) { case ExternalPromptNotificationType::kPromptGenericPermission: message_id = IDS_VR_DESKTOP_GENERIC_PERMISSION_PROMPT; - icon = &kOpenInBrowserIcon; + icon = &GetVrIcon(kVrOpenInBrowserIcon); break; case ExternalPromptNotificationType::kPromptNone: NOTREACHED(); @@ -1584,7 +1580,7 @@ auto timeout_icon = Create<VectorIcon>(kWebVrTimeoutMessageIcon, kPhaseForeground, 512); - timeout_icon->SetIcon(kSadTabIcon); + timeout_icon->SetIcon(GetVrIcon(kVrSadTabIcon)); timeout_icon->set_hit_testable(true); timeout_icon->SetSize(kTimeoutMessageIconWidthDMM, kTimeoutMessageIconHeightDMM); @@ -1606,7 +1602,7 @@ Create<DiscButton>(kWebVrTimeoutMessageButton, kPhaseForeground, base::BindRepeating(&UiBrowserInterface::ExitPresent, base::Unretained(browser_)), - vector_icons::kCloseRoundedIcon, audio_delegate_); + GetVrIcon(kVrCloseRoundedIcon), audio_delegate_); button->SetVisible(false); button->SetTranslate(0, -kTimeoutMessageTextWidthDMM, 0); button->SetRotate(1, 0, 0, kTimeoutButtonRotationRad); @@ -1743,7 +1739,7 @@ &Rect::SetColor); auto microphone_icon = std::make_unique<VectorIcon>(512); - microphone_icon->SetIcon(vector_icons::kMicIcon); + microphone_icon->SetIcon(GetVrIcon(kVrMicIcon)); microphone_icon->SetName(kSpeechRecognitionMicrophoneIcon); microphone_icon->SetDrawPhase(kPhaseForeground); microphone_icon->SetSize(kCloseButtonDiameter, kCloseButtonDiameter); @@ -1810,7 +1806,7 @@ kSpeechRecognitionListeningCloseButton, kPhaseForeground, base::BindRepeating(&UiBrowserInterface::SetVoiceSearchActive, base::Unretained(browser_), false), - vector_icons::kCloseRoundedIcon, audio_delegate_); + GetVrIcon(kVrCloseRoundedIcon), audio_delegate_); close_button->SetSize(kVoiceSearchCloseButtonDiameter, kVoiceSearchCloseButtonDiameter); close_button->set_hover_offset(kButtonZOffsetHoverDMM * kContentDistance); @@ -1923,7 +1919,7 @@ auto reposition_icon = std::make_unique<VectorIcon>(128); reposition_icon->set_owner_name_for_test(kRepositionCursor); reposition_icon->SetType(kTypeCursorForeground); - reposition_icon->SetIcon(kRepositionIcon); + reposition_icon->SetIcon(GetVrIcon(kVrRepositionIcon)); reposition_icon->SetDrawPhase(kPhaseForeground); reposition_icon->SetSize(kRepositionCursorSize, kRepositionCursorSize); VR_BIND_COLOR(model_, reposition_icon.get(), &ColorScheme::cursor_foreground, @@ -2017,7 +2013,7 @@ kUrlBarBackButton, kPhaseForeground, base::BindRepeating(&UiBrowserInterface::NavigateBack, base::Unretained(browser_)), - vector_icons::kBackArrowIcon, audio_delegate_); + GetVrIcon(kVrBackArrowIcon), audio_delegate_); back_button->SetSize(kUrlBarEndButtonWidthDMM, kUrlBarHeightDMM); back_button->SetCornerRadii( {kUrlBarHeightDMM / 2, 0, kUrlBarHeightDMM / 2, 0}); @@ -2082,7 +2078,7 @@ kUrlBarSecurityButton, kPhaseForeground, base::BindRepeating(&UiBrowserInterface::ShowPageInfo, base::Unretained(browser_)), - gfx::kNoneIcon, audio_delegate_); + GetVrIcon(kVrNoneIcon), audio_delegate_); security_button->SetIconScaleFactor(kUrlBarButtonIconScaleFactor); security_button->SetSize(kUrlBarButtonSizeDMM, kUrlBarButtonSizeDMM); security_button->set_corner_radius(kUrlBarItemCornerRadiusDMM); @@ -2165,7 +2161,7 @@ base::BindRepeating( [](Model* model) { model->overflow_menu_enabled = true; }, base::Unretained(model_)), - kMoreVertIcon, audio_delegate_); + GetVrIcon(kVrMoreVertIcon), audio_delegate_); overflow_button->SetSize(kUrlBarEndButtonWidthDMM, kUrlBarHeightDMM); overflow_button->SetCornerRadii( {0, kUrlBarHeightDMM / 2, 0, kUrlBarHeightDMM / 2}); @@ -2227,8 +2223,8 @@ std::vector< std::tuple<UiElementName, LayoutAlignment, const gfx::VectorIcon&>> menu_buttons = { - {kOverflowMenuForwardButton, LEFT, vector_icons::kForwardArrowIcon}, - {kOverflowMenuReloadButton, RIGHT, vector_icons::kReloadIcon}, + {kOverflowMenuForwardButton, LEFT, GetVrIcon(kVrForwardArrowIcon)}, + {kOverflowMenuReloadButton, RIGHT, GetVrIcon(kVrReloadIcon)}, }; for (auto& item : menu_buttons) { auto button = Create<VectorIconButton>(std::get<0>(item), kPhaseForeground, @@ -2527,7 +2523,7 @@ base::BindRepeating( [](UiBrowserInterface* b, Ui* ui) { b->SetVoiceSearchActive(true); }, base::Unretained(browser_), base::Unretained(ui_)), - vector_icons::kMicIcon, audio_delegate_); + GetVrIcon(kVrMicIcon), audio_delegate_); mic_button->SetSize(kUrlBarButtonSizeDMM, kUrlBarButtonSizeDMM); mic_button->SetIconScaleFactor(kUrlBarButtonIconScaleFactor); mic_button->set_hover_offset(kUrlBarButtonHoverOffsetDMM); @@ -2571,7 +2567,7 @@ base::BindRepeating( [](Model* model) { model->pop_mode(kModeEditingOmnibox); }, base::Unretained(model_)), - vector_icons::kBackArrowIcon, audio_delegate_); + GetVrIcon(kVrBackArrowIcon), audio_delegate_); close_button->SetSize(kOmniboxCloseButtonDiameterDMM, kOmniboxCloseButtonDiameterDMM); close_button->SetTranslate(0, kOmniboxCloseButtonVerticalOffsetDMM, 0); @@ -2651,7 +2647,7 @@ base::Unretained(model_), base::Unretained(browser_)); std::unique_ptr<DiscButton> element = Create<DiscButton>(kCloseButton, kPhaseForeground, click_handler, - vector_icons::kCloseRoundedIcon, audio_delegate_); + GetVrIcon(kVrCloseRoundedIcon), audio_delegate_); element->set_contributes_to_parent_bounds(false); element->SetSize(kCloseButtonDiameter, kCloseButtonDiameter); element->set_hover_offset(kButtonZOffsetHoverDMM * kCloseButtonDistance); @@ -2712,7 +2708,7 @@ switch (type) { case kModalPromptTypeExitVRForVoiceSearchRecordAudioOsPermission: message_id = IDS_VR_SHELL_AUDIO_PERMISSION_PROMPT_DESCRIPTION; - icon = &vector_icons::kMicIcon; + icon = &GetVrIcon(kVrMicIcon); primary_button_text_id = IDS_VR_SHELL_AUDIO_PERMISSION_PROMPT_CONTINUE_BUTTON; secondary_button_text_id = @@ -2720,7 +2716,7 @@ break; case kModalPromptTypeUpdateKeyboard: message_id = IDS_VR_UPDATE_KEYBOARD_PROMPT; - icon = &vector_icons::kInfoOutlineIcon; + icon = &GetVrIcon(kVrInfoOutlineIcon); primary_button_text_id = IDS_VR_SHELL_AUDIO_PERMISSION_PROMPT_CONTINUE_BUTTON; secondary_button_text_id = @@ -2728,7 +2724,7 @@ break; case kModalPromptTypeExitVRForSiteInfo: message_id = IDS_VR_SHELL_EXIT_PROMPT_DESCRIPTION_SITE_INFO; - icon = &vector_icons::kInfoOutlineIcon; + icon = &GetVrIcon(kVrInfoOutlineIcon); primary_button_text_id = IDS_VR_SHELL_EXIT_PROMPT_EXIT_VR_BUTTON; secondary_button_text_id = IDS_VR_BUTTON_BACK; @@ -2737,7 +2733,7 @@ case kModalPromptTypeExitVRForConnectionSecurityInfo: case kModalPromptTypeGenericUnsupportedFeature: message_id = IDS_VR_SHELL_EXIT_PROMPT_DESCRIPTION; - icon = &vector_icons::kInfoOutlineIcon; + icon = &GetVrIcon(kVrInfoOutlineIcon); primary_button_text_id = IDS_VR_SHELL_EXIT_PROMPT_EXIT_VR_BUTTON; secondary_button_text_id = IDS_VR_BUTTON_BACK; @@ -2788,7 +2784,7 @@ IndicatorSpec app_button_spec = {kNone, kWebVrExclusiveScreenToast, - kRemoveCircleOutlineIcon, + GetVrIcon(kVrRemoveCircleOutlineIcon), IDS_PRESS_APP_TO_EXIT, 0, 0,
diff --git a/chrome/browser/vr/ui_support.cc b/chrome/browser/vr/ui_support.cc index f70c633..47e15234 100644 --- a/chrome/browser/vr/ui_support.cc +++ b/chrome/browser/vr/ui_support.cc
@@ -4,6 +4,13 @@ #include "chrome/browser/vr/ui_support.h" +#include "build/build_config.h" +#include "chrome/app/vector_icons/vector_icons.h" +#include "chrome/browser/vr/vector_icons/vector_icons.h" +#include "components/omnibox/browser/vector_icons.h" +#include "components/vector_icons/vector_icons.h" +#include "ui/gfx/paint_vector_icon.h" + namespace vr { UScriptCode UScriptGetScript(UChar32 codepoint, UErrorCode* err) { @@ -20,4 +27,50 @@ net::UnescapeRule::NORMAL, new_parsed, nullptr, nullptr); } +const gfx::VectorIcon& GetVrIcon(VrIconId icon) { + switch (icon) { + case kVrNoneIcon: + return gfx::kNoneIcon; + case kVrReloadIcon: + return vector_icons::kReloadIcon; + case kVrVideocamIcon: + return vector_icons::kVideocamIcon; + case kVrBackArrowIcon: + return vector_icons::kBackArrowIcon; + case kVrInfoOutlineIcon: + return vector_icons::kInfoOutlineIcon; + case kVrScreenShareIcon: + return vector_icons::kScreenShareIcon; + case kVrCloseRoundedIcon: + return vector_icons::kCloseRoundedIcon; + case kVrForwardArrowIcon: + return vector_icons::kForwardArrowIcon; + case kVrBluetoothConnectedIcon: + return vector_icons::kBluetoothConnectedIcon; + case kVrMicIcon: + return vector_icons::kMicIcon; + case kVrMyLocationIcon: + return kMyLocationIcon; + case kVrRepositionIcon: + return kRepositionIcon; + case kVrMoreVertIcon: + return kMoreVertIcon; + case kVrSadTabIcon: + return kSadTabIcon; + case kVrRemoveCircleOutlineIcon: + return kRemoveCircleOutlineIcon; + case kVrDaydreamControllerAppButtonIcon: + return kDaydreamControllerAppButtonIcon; + case kVrDaydreamControllerHomeButtonIcon: + return kDaydreamControllerHomeButtonIcon; +#if !defined(OS_ANDROID) + case kVrOpenInBrowserIcon: + return kOpenInBrowserIcon; +#endif + default: + NOTREACHED(); + return gfx::kNoneIcon; + } +} + } // namespace vr
diff --git a/chrome/browser/vr/ui_support.h b/chrome/browser/vr/ui_support.h index e1e819c..97c6374 100644 --- a/chrome/browser/vr/ui_support.h +++ b/chrome/browser/vr/ui_support.h
@@ -10,6 +10,7 @@ #include "third_party/icu/source/common/unicode/uchar.h" #include "third_party/icu/source/common/unicode/uscript.h" #include "third_party/icu/source/common/unicode/utypes.h" +#include "ui/gfx/vector_icon_types.h" #include "url/gurl.h" namespace vr { @@ -25,6 +26,29 @@ VR_BASE_EXPORT base::string16 FormatUrlForVr(const GURL& gurl, url::Parsed* new_parsed); +enum VrIconId { + kVrNoneIcon, + kVrReloadIcon, + kVrVideocamIcon, + kVrBackArrowIcon, + kVrInfoOutlineIcon, + kVrScreenShareIcon, + kVrCloseRoundedIcon, + kVrForwardArrowIcon, + kVrBluetoothConnectedIcon, + kVrMicIcon, + kVrMyLocationIcon, + kVrRepositionIcon, + kVrMoreVertIcon, + kVrSadTabIcon, + kVrRemoveCircleOutlineIcon, + kVrDaydreamControllerAppButtonIcon, + kVrDaydreamControllerHomeButtonIcon, + kVrOpenInBrowserIcon, +}; + +VR_BASE_EXPORT const gfx::VectorIcon& GetVrIcon(VrIconId icon); + } // namespace vr #endif // CHROME_BROWSER_VR_UI_SUPPORT_H_
diff --git a/chrome/browser/win/jumplist.cc b/chrome/browser/win/jumplist.cc index dd89c5ae..9ddd96c 100644 --- a/chrome/browser/win/jumplist.cc +++ b/chrome/browser/win/jumplist.cc
@@ -624,14 +624,14 @@ base::FilePath icon_dir = GenerateJumplistIconDirName(profile_dir, FILE_PATH_LITERAL("")); delete_jumplisticons_task_runner_->PostTask( - FROM_HERE, - base::Bind(&DeleteDirectory, std::move(icon_dir), kFileDeleteLimit)); + FROM_HERE, base::BindOnce(&DeleteDirectory, std::move(icon_dir), + kFileDeleteLimit)); base::FilePath icon_dir_old = GenerateJumplistIconDirName(profile_dir, FILE_PATH_LITERAL("Old")); delete_jumplisticons_task_runner_->PostTask( - FROM_HERE, base::Bind(&DeleteDirectory, std::move(icon_dir_old), - kFileDeleteLimit)); + FROM_HERE, base::BindOnce(&DeleteDirectory, std::move(icon_dir_old), + kFileDeleteLimit)); } }
diff --git a/chrome/browser/win/taskbar_icon_finder.cc b/chrome/browser/win/taskbar_icon_finder.cc index a6a4343..af2d57d 100644 --- a/chrome/browser/win/taskbar_icon_finder.cc +++ b/chrome/browser/win/taskbar_icon_finder.cc
@@ -109,8 +109,8 @@ gfx::Rect rect; DoOnComTask(&rect); finder_runner->PostTask(FROM_HERE, - base::Bind(&TaskbarIconFinder::OnComplete, - base::Unretained(finder), rect)); + base::BindOnce(&TaskbarIconFinder::OnComplete, + base::Unretained(finder), rect)); } // static
diff --git a/chrome/chrome_watcher/chrome_watcher_main.cc b/chrome/chrome_watcher/chrome_watcher_main.cc index 2cfdd1d..81b3493c 100644 --- a/chrome/chrome_watcher/chrome_watcher_main.cc +++ b/chrome/chrome_watcher/chrome_watcher_main.cc
@@ -322,8 +322,9 @@ } if (!background_thread_.task_runner()->PostTask( - FROM_HERE, base::Bind(&BrowserMonitor::Watch, base::Unretained(this), - base::Passed(&on_initialized_event)))) { + FROM_HERE, + base::BindOnce(&BrowserMonitor::Watch, base::Unretained(this), + std::move(on_initialized_event)))) { background_thread_.Stop(); return false; } @@ -355,8 +356,9 @@ // Note that the browser has exited. browser_exited_.Signal(); - main_thread_->PostTask(FROM_HERE, - base::Bind(&BrowserMonitor::BrowserExited, base::Unretained(this))); + main_thread_->PostTask( + FROM_HERE, + base::BindOnce(&BrowserMonitor::BrowserExited, base::Unretained(this))); } void BrowserMonitor::BrowserExited() {
diff --git a/chrome/common/chrome_features.cc b/chrome/common/chrome_features.cc index 45734c99..e18c10a 100644 --- a/chrome/common/chrome_features.cc +++ b/chrome/common/chrome_features.cc
@@ -653,10 +653,6 @@ const base::Feature kCrosCompUpdates{"CrosCompUpdates", base::FEATURE_ENABLED_BY_DEFAULT}; -// Enables or disables Chrome OS Component updates on Chrome OS. -const base::Feature kCrOSComponent{"CrOSComponent", - base::FEATURE_ENABLED_BY_DEFAULT}; - // Enables or disables TPM firmware update capability on Chrome OS. const base::Feature kTPMFirmwareUpdate{"TPMFirmwareUpdate", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/chrome/common/chrome_features.h b/chrome/common/chrome_features.h index 323e8fb..ebcbc85 100644 --- a/chrome/common/chrome_features.h +++ b/chrome/common/chrome_features.h
@@ -438,8 +438,6 @@ COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kCrosCompUpdates; -COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kCrOSComponent; - COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kTPMFirmwareUpdate; COMPONENT_EXPORT(CHROME_FEATURES)
diff --git a/chrome/common/service_process_util_mac_unittest.mm b/chrome/common/service_process_util_mac_unittest.mm index ac2d1fe8..1e16505 100644 --- a/chrome/common/service_process_util_mac_unittest.mm +++ b/chrome/common/service_process_util_mac_unittest.mm
@@ -132,7 +132,7 @@ // Flaky: https://crbug.com/903823 TEST_F(ServiceProcessStateFileManipulationTest, DISABLED_DeleteFile) { GetIOTaskRunner()->PostTask(FROM_HERE, - base::Bind(&DeleteFunc, executable_path())); + base::BindOnce(&DeleteFunc, executable_path())); Run(); ASSERT_TRUE(mock_launchd()->remove_called()); ASSERT_TRUE(mock_launchd()->delete_called()); @@ -140,7 +140,7 @@ TEST_F(ServiceProcessStateFileManipulationTest, DeleteBundle) { GetIOTaskRunner()->PostTask(FROM_HERE, - base::Bind(&DeleteFunc, bundle_path())); + base::BindOnce(&DeleteFunc, bundle_path())); Run(); ASSERT_TRUE(mock_launchd()->remove_called()); ASSERT_TRUE(mock_launchd()->delete_called()); @@ -148,8 +148,8 @@ TEST_F(ServiceProcessStateFileManipulationTest, MoveBundle) { base::FilePath new_loc = GetTempDirPath().AppendASCII("MoveBundle"); - GetIOTaskRunner()->PostTask(FROM_HERE, - base::Bind(&MoveFunc, bundle_path(), new_loc)); + GetIOTaskRunner()->PostTask( + FROM_HERE, base::BindOnce(&MoveFunc, bundle_path(), new_loc)); Run(); ASSERT_TRUE(mock_launchd()->restart_called()); ASSERT_TRUE(mock_launchd()->write_called()); @@ -158,7 +158,7 @@ TEST_F(ServiceProcessStateFileManipulationTest, MoveFile) { base::FilePath new_loc = GetTempDirPath().AppendASCII("MoveFile"); GetIOTaskRunner()->PostTask( - FROM_HERE, base::Bind(&MoveFunc, executable_path(), new_loc)); + FROM_HERE, base::BindOnce(&MoveFunc, executable_path(), new_loc)); Run(); ASSERT_TRUE(mock_launchd()->remove_called()); ASSERT_TRUE(mock_launchd()->delete_called()); @@ -166,8 +166,9 @@ TEST_F(ServiceProcessStateFileManipulationTest, TrashBundle) { GetIOTaskRunner()->PostTask( - FROM_HERE, base::Bind(&ServiceProcessStateFileManipulationTest::TrashFunc, - base::Unretained(this), bundle_path())); + FROM_HERE, + base::BindOnce(&ServiceProcessStateFileManipulationTest::TrashFunc, + base::Unretained(this), bundle_path())); Run(); ASSERT_TRUE(mock_launchd()->remove_called()); ASSERT_TRUE(mock_launchd()->delete_called()); @@ -179,7 +180,7 @@ TEST_F(ServiceProcessStateFileManipulationTest, ChangeAttr) { ScopedAttributesRestorer restorer(bundle_path(), 0777); GetIOTaskRunner()->PostTask(FROM_HERE, - base::Bind(&ChangeAttr, bundle_path(), 0222)); + base::BindOnce(&ChangeAttr, bundle_path(), 0222)); Run(); ASSERT_TRUE(mock_launchd()->remove_called()); ASSERT_TRUE(mock_launchd()->delete_called());
diff --git a/chrome/common/service_process_util_posix.cc b/chrome/common/service_process_util_posix.cc index c23fbb2..999b601 100644 --- a/chrome/common/service_process_util_posix.cc +++ b/chrome/common/service_process_util_posix.cc
@@ -190,8 +190,9 @@ state_->task_runner = std::move(task_runner); state_->task_runner->PostTask( - FROM_HERE, base::Bind(&ServiceProcessState::StateData::SignalReady, - base::Unretained(state_), &signal_ready, &success)); + FROM_HERE, + base::BindOnce(&ServiceProcessState::StateData::SignalReady, + base::Unretained(state_), &signal_ready, &success)); signal_ready.Wait(); return success; }
diff --git a/chrome/installer/test/BUILD.gn b/chrome/installer/test/BUILD.gn index cb7f71f..4b0d73c 100644 --- a/chrome/installer/test/BUILD.gn +++ b/chrome/installer/test/BUILD.gn
@@ -2,25 +2,33 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//build/symlink.gni") import("//testing/test.gni") - assert(is_win) -executable("alternate_version_generator") { - testonly = true - sources = [ - "alternate_version_generator_main.cc", - ] +if (current_toolchain == host_toolchain) { + executable("alternate_version_generator") { + testonly = true + sources = [ + "alternate_version_generator_main.cc", + ] - deps = [ - ":alternate_version_generator_lib", - "//base", - "//base/test:test_support", - "//build/win:default_exe_manifest", - "//chrome/common:constants", - "//chrome/installer/util:with_rc_strings", - "//testing/gtest", - ] + deps = [ + ":alternate_version_generator_lib", + "//base", + "//base/test:test_support", + "//build/win:default_exe_manifest", + "//chrome/common:constants", + "//chrome/installer/util:with_rc_strings", + "//testing/gtest", + ] + } +} else { + binary_symlink("alternate_version_generator") { + testonly = true + binary_label = ":$target_name($host_toolchain)" + binary_output_name = "alternate_version_generator.exe" + } } static_library("alternate_version_generator_lib") {
diff --git a/chrome/renderer/chrome_content_renderer_client.cc b/chrome/renderer/chrome_content_renderer_client.cc index 2e90fc9..af2fc4e 100644 --- a/chrome/renderer/chrome_content_renderer_client.cc +++ b/chrome/renderer/chrome_content_renderer_client.cc
@@ -326,8 +326,8 @@ // |module_event_sink|: it is owned by a ChromeContentRendererClient, which is // a leaked singleton in the process. io_task_runner->PostTask( - FROM_HERE, base::Bind(&HandleModuleEventOnIOThread, - base::ConstRef(module_event_sink), event)); + FROM_HERE, base::BindOnce(&HandleModuleEventOnIOThread, + base::ConstRef(module_event_sink), event)); } #endif
diff --git a/chrome/renderer/chrome_render_thread_observer.cc b/chrome/renderer/chrome_render_thread_observer.cc index 416e82b0..27f5b5e6 100644 --- a/chrome/renderer/chrome_render_thread_observer.cc +++ b/chrome/renderer/chrome_render_thread_observer.cc
@@ -94,8 +94,8 @@ if (!weak_factory_.HasWeakPtrs()) { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&RendererResourceDelegate::InformHostOfCacheStats, - weak_factory_.GetWeakPtr()), + base::BindOnce(&RendererResourceDelegate::InformHostOfCacheStats, + weak_factory_.GetWeakPtr()), base::TimeDelta::FromMilliseconds(kCacheStatsDelayMS)); }
diff --git a/chrome/renderer/extensions/automation_internal_custom_bindings.cc b/chrome/renderer/extensions/automation_internal_custom_bindings.cc index a42637a..f763660 100644 --- a/chrome/renderer/extensions/automation_internal_custom_bindings.cc +++ b/chrome/renderer/extensions/automation_internal_custom_bindings.cc
@@ -452,8 +452,9 @@ bool OnMessageReceived(const IPC::Message& message) override { task_runner_->PostTask( FROM_HERE, - base::Bind(&AutomationMessageFilter::OnMessageReceivedOnRenderThread, - this, message)); + base::BindOnce( + &AutomationMessageFilter::OnMessageReceivedOnRenderThread, this, + message)); // Always return false in case there are multiple // AutomationInternalCustomBindings instances attached to the same thread.
diff --git a/chrome/service/service_process.cc b/chrome/service/service_process.cc index 88d7c4d..5c6a76ec 100644 --- a/chrome/service/service_process.cc +++ b/chrome/service/service_process.cc
@@ -421,7 +421,7 @@ void ServiceProcess::ScheduleShutdownCheck() { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&ServiceProcess::ShutdownIfNeeded, base::Unretained(this)), + base::BindOnce(&ServiceProcess::ShutdownIfNeeded, base::Unretained(this)), base::TimeDelta::FromSeconds(kShutdownDelaySeconds)); }
diff --git a/chrome/service/service_utility_process_host.cc b/chrome/service/service_utility_process_host.cc index 25fbc02..d090a00 100644 --- a/chrome/service/service_utility_process_host.cc +++ b/chrome/service/service_utility_process_host.cc
@@ -480,7 +480,7 @@ // If we are yet to receive a reply then notify the client that the // child died. client_task_runner_->PostTask( - FROM_HERE, base::Bind(&Client::OnChildDied, client_.get())); + FROM_HERE, base::BindOnce(&Client::OnChildDied, client_.get())); ReportUmaEvent(SERVICE_UTILITY_DISCONNECTED); } @@ -559,8 +559,8 @@ ReportUmaEvent(success ? SERVICE_UTILITY_METAFILE_SUCCEEDED : SERVICE_UTILITY_METAFILE_FAILED); client_task_runner_->PostTask( - FROM_HERE, base::Bind(&Client::OnRenderPDFPagesToMetafileDone, - client_.get(), success)); + FROM_HERE, base::BindOnce(&Client::OnRenderPDFPagesToMetafileDone, + client_.get(), success)); pdf_to_emf_state_.reset(); // The child process has finished at this point. This host is done as well. @@ -574,8 +574,9 @@ ReportUmaEvent(SERVICE_UTILITY_CAPS_SUCCEEDED); waiting_for_reply_ = false; client_task_runner_->PostTask( - FROM_HERE, base::Bind(&Client::OnGetPrinterCapsAndDefaults, client_.get(), - true, printer_name, caps_and_defaults)); + FROM_HERE, + base::BindOnce(&Client::OnGetPrinterCapsAndDefaults, client_.get(), true, + printer_name, caps_and_defaults)); // The child process disconnects itself and this host deletes itself via // OnChildDisconnected(). } @@ -588,8 +589,8 @@ waiting_for_reply_ = false; client_task_runner_->PostTask( FROM_HERE, - base::Bind(&Client::OnGetPrinterSemanticCapsAndDefaults, client_.get(), - true, printer_name, caps_and_defaults)); + base::BindOnce(&Client::OnGetPrinterSemanticCapsAndDefaults, + client_.get(), true, printer_name, caps_and_defaults)); // The child process disconnects itself and this host deletes itself via // OnChildDisconnected(). } @@ -601,8 +602,8 @@ waiting_for_reply_ = false; client_task_runner_->PostTask( FROM_HERE, - base::Bind(&Client::OnGetPrinterCapsAndDefaults, client_.get(), false, - printer_name, printing::PrinterCapsAndDefaults())); + base::BindOnce(&Client::OnGetPrinterCapsAndDefaults, client_.get(), false, + printer_name, printing::PrinterCapsAndDefaults())); // The child process disconnects itself and this host deletes itself via // OnChildDisconnected(). } @@ -613,9 +614,9 @@ ReportUmaEvent(SERVICE_UTILITY_SEMANTIC_CAPS_FAILED); waiting_for_reply_ = false; client_task_runner_->PostTask( - FROM_HERE, base::Bind(&Client::OnGetPrinterSemanticCapsAndDefaults, - client_.get(), false, printer_name, - printing::PrinterSemanticCapsAndDefaults())); + FROM_HERE, base::BindOnce(&Client::OnGetPrinterSemanticCapsAndDefaults, + client_.get(), false, printer_name, + printing::PrinterSemanticCapsAndDefaults())); // The child process disconnects itself and this host deletes itself via // OnChildDisconnected(). }
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index ffbedd8..8d4e568 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -2,6 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//build/config/allocator.gni") import("//build/config/chrome_build.gni") import("//build/config/compiler/compiler.gni") import("//build/config/crypto.gni") @@ -3676,6 +3677,9 @@ "//ash/strings", "//chrome/browser/resources/chromeos/zip_archiver/cpp:ziparchiver_unittests", ] + if (use_new_tcmalloc) { + sources += [ "../browser/metrics/perf/heap_collector_unittest.cc" ] + } } if (use_x11 || use_ozone) {
diff --git a/chrome/test/base/in_process_browser_test.cc b/chrome/test/base/in_process_browser_test.cc index 6aa5444..c4808c4 100644 --- a/chrome/test/base/in_process_browser_test.cc +++ b/chrome/test/base/in_process_browser_test.cc
@@ -614,7 +614,7 @@ // AttemptExit exits the message loop after everything has been // shut down properly. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&chrome::AttemptExit)); + FROM_HERE, base::BindOnce(&chrome::AttemptExit)); RunUntilBrowserProcessQuits(); #if defined(OS_MACOSX)
diff --git a/chrome/test/base/testing_profile.cc b/chrome/test/base/testing_profile.cc index 88339f4..2cfe367 100644 --- a/chrome/test/base/testing_profile.cc +++ b/chrome/test/base/testing_profile.cc
@@ -266,7 +266,7 @@ if (delegate_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&TestingProfile::FinishInit, base::Unretained(this))); + base::BindOnce(&TestingProfile::FinishInit, base::Unretained(this))); } else { FinishInit(); } @@ -326,7 +326,7 @@ if (delegate_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&TestingProfile::FinishInit, base::Unretained(this))); + base::BindOnce(&TestingProfile::FinishInit, base::Unretained(this))); } else { FinishInit(); }
diff --git a/chrome/test/base/view_event_test_base.cc b/chrome/test/base/view_event_test_base.cc index 69520fad..c819a63a 100644 --- a/chrome/test/base/view_event_test_base.cc +++ b/chrome/test/base/view_event_test_base.cc
@@ -165,8 +165,8 @@ // Schedule a task that starts the test. Need to do this as we're going to // run the message loop. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&ViewEventTestBase::DoTestOnMessageLoop, - base::Unretained(this))); + FROM_HERE, base::BindOnce(&ViewEventTestBase::DoTestOnMessageLoop, + base::Unretained(this))); content::RunThisRunLoop(&run_loop_); }
diff --git a/chrome/test/chromedriver/test/run_webdriver_tests.py b/chrome/test/chromedriver/test/run_webdriver_tests.py index 4fcfcdb..8b573e4a 100644 --- a/chrome/test/chromedriver/test/run_webdriver_tests.py +++ b/chrome/test/chromedriver/test/run_webdriver_tests.py
@@ -10,6 +10,9 @@ import sys import json import time +import logging + +_log = logging.getLogger(__name__) _TEST_DIR = os.path.abspath(os.path.dirname(__file__)) _CHROMEDRIVER_DIR = os.path.join(_TEST_DIR, os.pardir) @@ -17,15 +20,21 @@ _CLIENT_DIR = os.path.join(_CHROMEDRIVER_DIR, "client") _SERVER_DIR = os.path.join(_CHROMEDRIVER_DIR, "server") -sys.path.insert(1, _CHROMEDRIVER_DIR) +sys.path.insert(0, _CHROMEDRIVER_DIR) import util -sys.path.insert(1, _SERVER_DIR) +sys.path.insert(0, _SERVER_DIR) import server -WD_CLIENT_PATH = ('third_party/blink/tools/blinkpy/' - 'third_party/wpt/wpt/tools/webdriver') -WEBDRIVER_CLIENT_ABS_PATH = os.path.join(SRC_DIR, WD_CLIENT_PATH) +BLINK_TOOLS_PATH = 'third_party/blink/tools' +BLINK_TOOLS_ABS_PATH = os.path.join(SRC_DIR, BLINK_TOOLS_PATH) + +sys.path.insert(0, BLINK_TOOLS_ABS_PATH) +from blinkpy.common.host import Host +from blinkpy.common.system.log_utils import configure_logging + +WD_CLIENT_PATH = 'blinkpy/third_party/wpt/wpt/tools/webdriver' +WEBDRIVER_CLIENT_ABS_PATH = os.path.join(BLINK_TOOLS_ABS_PATH, WD_CLIENT_PATH) class WebDriverTestResult(object): @@ -84,15 +93,26 @@ } } }, + "args": [ + "--host-resolver-rules=" + "MAP nonexistent.*.test ~NOTFOUND, " + "MAP *.test 127.0.0.1" + ] + } }) + + # Port numbers are defined at + # https://cs.chromium.org/chromium/src/third_party/blink/tools + # /blinkpy/web_tests/servers/wptserve.py?l=23&rcl=375b34c6ba64 + # 5d00c1413e4c6106c7bb74581c85 os.environ["WD_SERVER_CONFIG"] = json.dumps({ "browser_host": "web-platform.test", - "ports": {"http": [8000, 8001]}}) + "ports": {"ws": [9001], "wss": [9444], "http": [8001], "https": [8444]}}) def run_test(path): subtests = SubtestResultRecorder() - pytest.main(["--show-capture", "no", path], plugins=[subtests]) + pytest.main(["-s", path], plugins=[subtests]) return subtests.result if __name__ == '__main__': @@ -116,9 +136,19 @@ parser.add_argument( '--test-path', help='Path to the WPT WebDriver tests') + parser.add_argument( + '-v', '--verbose', action='store_true', + help='log extra details that may be helpful when debugging') options = parser.parse_args() + log_level = logging.DEBUG if options.verbose else logging.INFO + configure_logging(logging_level=log_level, include_time=True) + + # Starts WPT Serve to serve the WPT WebDriver test content. + port = Host().port_factory.get() + port.start_wptserve() + options.chromedriver = util.GetAbsolutePathOfUserPath(options.chromedriver) if (not os.path.exists(options.chromedriver) and util.GetPlatformName() == 'win' and @@ -132,7 +162,7 @@ chromedriver_server = server.Server(options.chromedriver, options.log_path) if not chromedriver_server.IsRunning(): - print 'ChromeDriver is not running.' + _log.error('ChromeDriver is not running.') sys.exit(1) set_up_config(chromedriver_server) @@ -140,22 +170,25 @@ test_path = options.test_path start_time = time.time() test_results = [] - sys.path.insert(1, WEBDRIVER_CLIENT_ABS_PATH) - if os.path.isfile(test_path): - test_results = run_test(test_path) - elif os.path.isdir(test_path): - for root, dirnames, filenames in os.walk(test_path): - for filename in filenames: - if '__init__' in filename: - continue - test_file = os.path.join(root, filename) - test_results += run_test(test_file) - else: - print '%s is not a file nor directory.' % test_path - sys.exit(1) - sys.path.remove(WEBDRIVER_CLIENT_ABS_PATH) - - chromedriver_server.Kill() + sys.path.insert(0, WEBDRIVER_CLIENT_ABS_PATH) + try: + if os.path.isfile(test_path): + test_results = run_test(test_path) + elif os.path.isdir(test_path): + for root, dirnames, filenames in os.walk(test_path): + for filename in filenames: + if '__init__' in filename: + continue + test_file = os.path.join(root, filename) + test_results += run_test(test_file) + else: + _log.error('%s is not a file nor directory.' % test_path) + sys.exit(1) + except KeyboardInterrupt as e: + _log.error(e) + finally: + chromedriver_server.Kill() + port.stop_wptserve() if options.isolated_script_test_output: output = {
diff --git a/chrome/test/data/webui/settings/people_page_account_manager_test.js b/chrome/test/data/webui/settings/people_page_account_manager_test.js index efd0741..db50e51 100644 --- a/chrome/test/data/webui/settings/people_page_account_manager_test.js +++ b/chrome/test/data/webui/settings/people_page_account_manager_test.js
@@ -9,6 +9,7 @@ super([ 'getAccounts', 'addAccount', + 'reauthenticateAccount', 'removeAccount', 'showWelcomeDialogIfRequired', ]); @@ -24,6 +25,7 @@ id: '123', accountType: 1, isDeviceAccount: true, + isSignedIn: true, fullName: 'Device Account', email: 'admin@domain.com', pic: 'data:image/png;base64,abc123', @@ -32,10 +34,20 @@ id: '456', accountType: 1, isDeviceAccount: false, - fullName: 'Secondary Account', - email: 'user@domain.com', + isSignedIn: true, + fullName: 'Secondary Account 1', + email: 'user1@example.com', pic: '', }, + { + id: '789', + accountType: 1, + isDeviceAccount: false, + isSignedIn: false, + fullName: 'Secondary Account 2', + email: 'user2@example.com', + pic: '', + } ]); }); } @@ -46,6 +58,11 @@ } /** @override */ + reauthenticateAccount(account_email) { + this.methodCalled('reauthenticateAccount', account_email); + } + + /** @override */ removeAccount(account) { this.methodCalled('removeAccount', account); } @@ -83,8 +100,8 @@ test('AccountListIsPopulatedAtStartup', function() { return browserProxy.whenCalled('getAccounts').then(() => { Polymer.dom.flush(); - // 2 accounts were added in |getAccounts()| mock above. - assertEquals(2, accountList.items.length); + // 3 accounts were added in |getAccounts()| mock above. + assertEquals(3, accountList.items.length); }); }); @@ -93,6 +110,18 @@ assertEquals(1, browserProxy.getCallCount('addAccount')); }); + test('ReauthenticateAccount', function() { + return browserProxy.whenCalled('getAccounts').then(() => { + Polymer.dom.flush(); + accountManager.root.querySelectorAll('.reauth-button')[0].click(); + assertEquals(1, browserProxy.getCallCount('reauthenticateAccount')); + return browserProxy.whenCalled('reauthenticateAccount') + .then((account_email) => { + assertEquals('user2@example.com', account_email); + }); + }); + }); + test('RemoveAccount', function() { return browserProxy.whenCalled('getAccounts').then(() => { Polymer.dom.flush();
diff --git a/chrome/test/ppapi/ppapi_test.cc b/chrome/test/ppapi/ppapi_test.cc index 9a902af..f5192ef4 100644 --- a/chrome/test/ppapi/ppapi_test.cc +++ b/chrome/test/ppapi/ppapi_test.cc
@@ -97,8 +97,8 @@ // InfoBarContainer) may still need to access it. Instead, post a task to // do all necessary infobar manipulation as soon as this call stack returns. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&InfoBarObserver::VerifyInfoBarState, base::Unretained(this))); + FROM_HERE, base::BindOnce(&InfoBarObserver::VerifyInfoBarState, + base::Unretained(this))); } void PPAPITestBase::InfoBarObserver::OnManagerShuttingDown(
diff --git a/chrome/utility/image_writer/disk_unmounter_mac.cc b/chrome/utility/image_writer/disk_unmounter_mac.cc index d410707a..d107dee5 100644 --- a/chrome/utility/image_writer/disk_unmounter_mac.cc +++ b/chrome/utility/image_writer/disk_unmounter_mac.cc
@@ -38,8 +38,8 @@ failure_continuation_ = failure_continuation; cf_thread_.task_runner()->PostTask( - FROM_HERE, base::Bind(&DiskUnmounterMac::UnmountOnWorker, - base::Unretained(this), device_path)); + FROM_HERE, base::BindOnce(&DiskUnmounterMac::UnmountOnWorker, + base::Unretained(this), device_path)); } // static
diff --git a/chromecast/net/connectivity_checker_impl.cc b/chromecast/net/connectivity_checker_impl.cc index c3772b7..a1b172e0 100644 --- a/chromecast/net/connectivity_checker_impl.cc +++ b/chromecast/net/connectivity_checker_impl.cc
@@ -202,7 +202,8 @@ // Some products don't have an idle screen that makes periodic network // requests. Schedule another check to ensure connectivity hasn't dropped. task_runner_->PostDelayedTask( - FROM_HERE, base::Bind(&ConnectivityCheckerImpl::CheckInternal, this), + FROM_HERE, + base::BindOnce(&ConnectivityCheckerImpl::CheckInternal, this), base::TimeDelta::FromSeconds(kConnectivitySuccessPeriodSeconds)); timeout_.Cancel(); return;
diff --git a/chromecast/renderer/extensions/automation_internal_custom_bindings.cc b/chromecast/renderer/extensions/automation_internal_custom_bindings.cc index e6a5cfd..39e67a9 100644 --- a/chromecast/renderer/extensions/automation_internal_custom_bindings.cc +++ b/chromecast/renderer/extensions/automation_internal_custom_bindings.cc
@@ -453,8 +453,9 @@ bool OnMessageReceived(const IPC::Message& message) override { task_runner_->PostTask( FROM_HERE, - base::Bind(&AutomationMessageFilter::OnMessageReceivedOnRenderThread, - this, message)); + base::BindOnce( + &AutomationMessageFilter::OnMessageReceivedOnRenderThread, this, + message)); // Always return false in case there are multiple // AutomationInternalCustomBindings instances attached to the same thread.
diff --git a/chromeos/BUILD.gn b/chromeos/BUILD.gn index 17e520e..2b31d0f 100644 --- a/chromeos/BUILD.gn +++ b/chromeos/BUILD.gn
@@ -278,7 +278,7 @@ # To diagnose tast failures or disable tests, see go/tast-failures tast_test("chrome_all_tast_tests") { # To disable a specific test, add it the following list. - tast_disabled_tests = [ "security.Mtab" ] # crbug.com/931431 + tast_disabled_tests = [] } tast_test("chrome_kevin_tast_tests") { # Tests that fail on Kevin devices.
diff --git a/chromeos/services/assistant/default_url_request_context_getter.cc b/chromeos/services/assistant/default_url_request_context_getter.cc index d77325e..b4e3e04 100644 --- a/chromeos/services/assistant/default_url_request_context_getter.cc +++ b/chromeos/services/assistant/default_url_request_context_getter.cc
@@ -78,8 +78,9 @@ const std::string& bypass_list) { network_task_runner_->PostTask( FROM_HERE, - base::Bind(&DefaultURLRequestContextGetter::SetProxyConfigurationInternal, - this, proxy_server, bypass_list)); + base::BindOnce( + &DefaultURLRequestContextGetter::SetProxyConfigurationInternal, this, + proxy_server, bypass_list)); } void DefaultURLRequestContextGetter::SetProxyConfigurationInternal(
diff --git a/chromeos/services/secure_channel/secure_channel_initializer.cc b/chromeos/services/secure_channel/secure_channel_initializer.cc index 8773efb0..9083df2a 100644 --- a/chromeos/services/secure_channel/secure_channel_initializer.cc +++ b/chromeos/services/secure_channel/secure_channel_initializer.cc
@@ -71,7 +71,7 @@ // call as a task to ensure that it is returned asynchronously, even in tests. task_runner->PostTask( FROM_HERE, - base::Bind( + base::BindOnce( device::BluetoothAdapterFactory::GetAdapter, base::Bind(&SecureChannelInitializer::OnBluetoothAdapterReceived, weak_ptr_factory_.GetWeakPtr())));
diff --git a/chromeos/tpm/install_attributes.cc b/chromeos/tpm/install_attributes.cc index 8ba4772..01ef7a0 100644 --- a/chromeos/tpm/install_attributes.cc +++ b/chromeos/tpm/install_attributes.cc
@@ -435,8 +435,9 @@ if (!result.has_value() && dbus_retries_remaining) { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&InstallAttributes::TriggerConsistencyCheck, - weak_ptr_factory_.GetWeakPtr(), dbus_retries_remaining - 1), + base::BindOnce(&InstallAttributes::TriggerConsistencyCheck, + weak_ptr_factory_.GetWeakPtr(), + dbus_retries_remaining - 1), base::TimeDelta::FromSeconds(kDbusRetryIntervalInSeconds)); return; }
diff --git a/components/autofill/content/renderer/password_autofill_agent.cc b/components/autofill/content/renderer/password_autofill_agent.cc index ed933f7..f628dd6 100644 --- a/components/autofill/content/renderer/password_autofill_agent.cc +++ b/components/autofill/content/renderer/password_autofill_agent.cc
@@ -1015,10 +1015,6 @@ element != password_info->password_field)) return true; - UMA_HISTOGRAM_BOOLEAN( - "PasswordManager.AutocompletePopupSuppressedByGeneration", - generation_popup_showing); - if (generation_popup_showing) return false;
diff --git a/components/cloud_devices/common/description_items.h b/components/cloud_devices/common/description_items.h index fbeb3a8..5e2348e1 100644 --- a/components/cloud_devices/common/description_items.h +++ b/components/cloud_devices/common/description_items.h
@@ -63,7 +63,7 @@ return base::ContainsValue(options_, option); } - void AddOption(const Option& option) { options_.push_back(option); } + void AddOption(Option&& option) { options_.emplace_back(std::move(option)); } private: typedef std::vector<Option> OptionVector; @@ -81,11 +81,19 @@ class SelectionCapability { public: SelectionCapability(); + SelectionCapability(SelectionCapability&& other); ~SelectionCapability(); + SelectionCapability& operator=(SelectionCapability&& other); + + bool operator==(const SelectionCapability& other) const; + bool LoadFrom(const CloudDeviceDescription& description); void SaveTo(CloudDeviceDescription* description) const; + bool LoadFrom(const base::Value& dict); + void SaveTo(base::Value* dict) const; + void Reset() { options_.clear(); default_idx_ = -1;
diff --git a/components/cloud_devices/common/description_items_inl.h b/components/cloud_devices/common/description_items_inl.h index e4f8be9..b63800a 100644 --- a/components/cloud_devices/common/description_items_inl.h +++ b/components/cloud_devices/common/description_items_inl.h
@@ -54,7 +54,7 @@ Option option; if (!option_value.is_dict() || !Traits::Load(option_value, &option)) return false; - AddOption(option); + AddOption(std::move(option)); } return IsValid(); } @@ -78,10 +78,24 @@ } template <class Option, class Traits> +SelectionCapability<Option, Traits>::SelectionCapability( + SelectionCapability&& other) = default; + +template <class Option, class Traits> SelectionCapability<Option, Traits>::~SelectionCapability() { } template <class Option, class Traits> +SelectionCapability<Option, Traits>& SelectionCapability<Option, Traits>:: +operator=(SelectionCapability&& other) = default; + +template <class Option, class Traits> +bool SelectionCapability<Option, Traits>::operator==( + const SelectionCapability<Option, Traits>& other) const { + return options_ == other.options_ && default_idx_ == other.default_idx_; +} + +template <class Option, class Traits> bool SelectionCapability<Option, Traits>::IsValid() const { if (empty()) return false; // This type of capabilities can't be empty @@ -95,13 +109,28 @@ template <class Option, class Traits> bool SelectionCapability<Option, Traits>::LoadFrom( const CloudDeviceDescription& description) { - Reset(); const base::Value* item = description.GetItem(Traits::GetCapabilityPath(), base::Value::Type::DICTIONARY); - if (!item) + if (!item) { + Reset(); return false; + } + return LoadFrom(*item); +} + +template <class Option, class Traits> +void SelectionCapability<Option, Traits>::SaveTo( + CloudDeviceDescription* description) const { + DCHECK(IsValid()); + SaveTo(description->CreateItem(Traits::GetCapabilityPath(), + base::Value::Type::DICTIONARY)); +} + +template <class Option, class Traits> +bool SelectionCapability<Option, Traits>::LoadFrom(const base::Value& dict) { + Reset(); const base::Value* options_value = - item->FindKeyOfType(json::kKeyOption, base::Value::Type::LIST); + dict.FindKeyOfType(json::kKeyOption, base::Value::Type::LIST); if (!options_value) return false; const base::Value::ListStorage& options = options_value->GetList(); @@ -120,8 +149,7 @@ } template <class Option, class Traits> -void SelectionCapability<Option, Traits>::SaveTo( - CloudDeviceDescription* description) const { +void SelectionCapability<Option, Traits>::SaveTo(base::Value* dict) const { DCHECK(IsValid()); base::Value options_list(base::Value::Type::LIST); for (size_t i = 0; i < options_.size(); ++i) { @@ -131,9 +159,7 @@ Traits::Save(options_[i], &option_value); options_list.GetList().emplace_back(std::move(option_value)); } - description - ->CreateItem(Traits::GetCapabilityPath(), base::Value::Type::DICTIONARY) - ->SetKey(json::kKeyOption, std::move(options_list)); + dict->SetKey(json::kKeyOption, std::move(options_list)); } template <class Traits>
diff --git a/components/cloud_devices/common/printer_description.cc b/components/cloud_devices/common/printer_description.cc index 89d74914..94be3b2a 100644 --- a/components/cloud_devices/common/printer_description.cc +++ b/components/cloud_devices/common/printer_description.cc
@@ -14,6 +14,7 @@ #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/stl_util.h" +#include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/values.h" @@ -33,8 +34,12 @@ const char kKeyCustomDisplayName[] = "custom_display_name"; const char kKeyContentType[] = "content_type"; +const char kKeyDisplayName[] = "display_name"; +const char kKeyId[] = "id"; const char kKeyName[] = "name"; const char kKeyType[] = "type"; +const char kKeyValue[] = "value"; +const char kKeyValueType[] = "value_type"; const char kKeyVendorId[] = "vendor_id"; // extern is required to be used in templates. @@ -51,6 +56,10 @@ extern const char kOptionPageRange[] = "page_range"; extern const char kOptionReverse[] = "reverse_order"; extern const char kOptionPwgRasterConfig[] = "pwg_raster_config"; +extern const char kOptionRangeCapability[] = "range_cap"; +extern const char kOptionSelectCapability[] = "select_cap"; +extern const char kOptionTypedValueCapability[] = "typed_value_cap"; +extern const char kOptionVendorCapability[] = "vendor_capability"; const char kMarginBottom[] = "bottom_microns"; const char kMarginLeft[] = "left_microns"; @@ -73,6 +82,22 @@ const char kPwgRasterReverseOrderStreaming[] = "reverse_order_streaming"; const char kPwgRasterRotateAllPages[] = "rotate_all_pages"; +const char kVendorCapabilityMinValue[] = "min"; +const char kVendorCapabilityMaxValue[] = "max"; +const char kVendorCapabilityDefaultValue[] = "default"; + +const char kTypeRangeVendorCapabilityFloat[] = "FLOAT"; +const char kTypeRangeVendorCapabilityInteger[] = "INTEGER"; + +const char kTypeTypedValueVendorCapabilityBoolean[] = "BOOLEAN"; +const char kTypeTypedValueVendorCapabilityFloat[] = "FLOAT"; +const char kTypeTypedValueVendorCapabilityInteger[] = "INTEGER"; +const char kTypeTypedValueVendorCapabilityString[] = "STRING"; + +const char kTypeVendorCapabilityRange[] = "RANGE"; +const char kTypeVendorCapabilitySelect[] = "SELECT"; +const char kTypeVendorCapabilityTypedValue[] = "TYPED_VALUE"; + const char kTypeColorColor[] = "STANDARD_COLOR"; const char kTypeColorMonochrome[] = "STANDARD_MONOCHROME"; const char kTypeColorCustomColor[] = "CUSTOM_COLOR"; @@ -105,6 +130,38 @@ const char kTypeDocumentSheetBackManualTumble[] = "MANUAL_TUMBLE"; const char kTypeDocumentSheetBackFlipped[] = "FLIPPED"; +const struct RangeVendorCapabilityTypeNames { + RangeVendorCapability::ValueType id; + const char* json_name; +} kRangeVendorCapabilityTypeNames[] = { + {RangeVendorCapability::ValueType::FLOAT, kTypeRangeVendorCapabilityFloat}, + {RangeVendorCapability::ValueType::INTEGER, + kTypeRangeVendorCapabilityInteger}, +}; + +const struct TypedValueVendorCapabilityTypeNames { + TypedValueVendorCapability::ValueType id; + const char* json_name; +} kTypedValueVendorCapabilityTypeNames[] = { + {TypedValueVendorCapability::ValueType::BOOLEAN, + kTypeTypedValueVendorCapabilityBoolean}, + {TypedValueVendorCapability::ValueType::FLOAT, + kTypeTypedValueVendorCapabilityFloat}, + {TypedValueVendorCapability::ValueType::INTEGER, + kTypeTypedValueVendorCapabilityInteger}, + {TypedValueVendorCapability::ValueType::STRING, + kTypeTypedValueVendorCapabilityString}, +}; + +const struct VendorCapabilityTypeNames { + VendorCapability::Type id; + const char* json_name; +} kVendorCapabilityTypeNames[] = { + {VendorCapability::Type::RANGE, kTypeVendorCapabilityRange}, + {VendorCapability::Type::SELECT, kTypeVendorCapabilitySelect}, + {VendorCapability::Type::TYPED_VALUE, kTypeVendorCapabilityTypedValue}, +}; + const struct ColorNames { ColorType id; const char* const json_name; @@ -418,6 +475,336 @@ PwgRasterConfig::~PwgRasterConfig() {} +RangeVendorCapability::RangeVendorCapability() = default; + +RangeVendorCapability::RangeVendorCapability(ValueType value_type, + const std::string& min_value, + const std::string& max_value) + : RangeVendorCapability(value_type, + min_value, + max_value, + /*default_value=*/"") {} + +RangeVendorCapability::RangeVendorCapability(ValueType value_type, + const std::string& min_value, + const std::string& max_value, + const std::string& default_value) + : value_type_(value_type), + min_value_(min_value), + max_value_(max_value), + default_value_(default_value) {} + +RangeVendorCapability::RangeVendorCapability(RangeVendorCapability&& other) = + default; + +RangeVendorCapability::~RangeVendorCapability() = default; + +RangeVendorCapability& RangeVendorCapability::operator=( + RangeVendorCapability&& other) = default; + +bool RangeVendorCapability::operator==( + const RangeVendorCapability& other) const { + return value_type_ == other.value_type_ && min_value_ == other.min_value_ && + max_value_ == other.max_value_ && + default_value_ == other.default_value_; +} + +bool RangeVendorCapability::IsValid() const { + if (min_value_.empty() || max_value_.empty()) + return false; + switch (value_type_) { + case ValueType::FLOAT: { + double min_value; + double max_value; + if (!base::StringToDouble(min_value_, &min_value) || + !base::StringToDouble(max_value_, &max_value) || + min_value > max_value) { + return false; + } + if (!default_value_.empty()) { + double default_value; + if (!base::StringToDouble(default_value_, &default_value) || + default_value < min_value || default_value > max_value) { + return false; + } + } + return true; + } + case ValueType::INTEGER: { + int min_value; + int max_value; + if (!base::StringToInt(min_value_, &min_value) || + !base::StringToInt(max_value_, &max_value) || min_value > max_value) { + return false; + } + if (!default_value_.empty()) { + int default_value; + if (!base::StringToInt(default_value_, &default_value) || + default_value < min_value || default_value > max_value) { + return false; + } + } + return true; + } + } + NOTREACHED() << "Bad range capability value type"; + return false; +} + +bool RangeVendorCapability::LoadFrom(const base::Value& dict) { + const std::string* value_type_str = dict.FindStringKey(kKeyValueType); + if (!value_type_str || !TypeFromString(kRangeVendorCapabilityTypeNames, + *value_type_str, &value_type_)) { + return false; + } + const std::string* min_value_str = + dict.FindStringKey(kVendorCapabilityMinValue); + if (!min_value_str) + return false; + min_value_ = *min_value_str; + const std::string* max_value_str = + dict.FindStringKey(kVendorCapabilityMaxValue); + if (!max_value_str) + return false; + max_value_ = *max_value_str; + const std::string* default_value_str = + dict.FindStringKey(kVendorCapabilityDefaultValue); + if (default_value_str) + default_value_ = *default_value_str; + return IsValid(); +} + +void RangeVendorCapability::SaveTo(base::Value* dict) const { + DCHECK(IsValid()); + dict->SetKey( + kKeyValueType, + base::Value(TypeToString(kRangeVendorCapabilityTypeNames, value_type_))); + dict->SetKey(kVendorCapabilityMinValue, base::Value(min_value_)); + dict->SetKey(kVendorCapabilityMaxValue, base::Value(max_value_)); + if (!default_value_.empty()) + dict->SetKey(kVendorCapabilityDefaultValue, base::Value(default_value_)); +} + +SelectVendorCapabilityOption::SelectVendorCapabilityOption() = default; + +SelectVendorCapabilityOption::SelectVendorCapabilityOption( + const std::string& value, + const std::string& display_name) + : value(value), display_name(display_name) {} + +SelectVendorCapabilityOption::~SelectVendorCapabilityOption() = default; + +bool SelectVendorCapabilityOption::operator==( + const SelectVendorCapabilityOption& other) const { + return value == other.value && display_name == other.display_name; +} + +bool SelectVendorCapabilityOption::IsValid() const { + return !value.empty() && !display_name.empty(); +} + +TypedValueVendorCapability::TypedValueVendorCapability() = default; + +TypedValueVendorCapability::TypedValueVendorCapability(ValueType value_type) + : TypedValueVendorCapability(value_type, /*default_value=*/"") {} + +TypedValueVendorCapability::TypedValueVendorCapability( + ValueType value_type, + const std::string& default_value) + : value_type_(value_type), default_value_(default_value) {} + +TypedValueVendorCapability::TypedValueVendorCapability( + TypedValueVendorCapability&& other) = default; + +TypedValueVendorCapability::~TypedValueVendorCapability() = default; + +TypedValueVendorCapability& TypedValueVendorCapability::operator=( + TypedValueVendorCapability&& other) = default; + +bool TypedValueVendorCapability::operator==( + const TypedValueVendorCapability& other) const { + return value_type_ == other.value_type_ && + default_value_ == other.default_value_; +} + +bool TypedValueVendorCapability::IsValid() const { + if (default_value_.empty()) + return true; + switch (value_type_) { + case ValueType::BOOLEAN: + return default_value_ == "true" || default_value_ == "false"; + case ValueType::FLOAT: { + double value; + return base::StringToDouble(default_value_, &value); + } + case ValueType::INTEGER: { + int value; + return base::StringToInt(default_value_, &value); + } + case ValueType::STRING: + return true; + } + NOTREACHED() << "Bad typed value capability value type"; + return false; +} + +bool TypedValueVendorCapability::LoadFrom(const base::Value& dict) { + const std::string* value_type_str = dict.FindStringKey(kKeyValueType); + if (!value_type_str || !TypeFromString(kTypedValueVendorCapabilityTypeNames, + *value_type_str, &value_type_)) { + return false; + } + const std::string* default_value_str = + dict.FindStringKey(kVendorCapabilityDefaultValue); + if (default_value_str) + default_value_ = *default_value_str; + return IsValid(); +} + +void TypedValueVendorCapability::SaveTo(base::Value* dict) const { + DCHECK(IsValid()); + dict->SetKey(kKeyValueType, + base::Value(TypeToString(kTypedValueVendorCapabilityTypeNames, + value_type_))); + if (!default_value_.empty()) + dict->SetKey(kVendorCapabilityDefaultValue, base::Value(default_value_)); +} + +VendorCapability::VendorCapability() = default; + +VendorCapability::VendorCapability(Type type, + const std::string& id, + const std::string& display_name, + RangeVendorCapability range_capability) + : type_(type), + id_(id), + display_name_(display_name), + range_capability_(std::move(range_capability)) {} + +VendorCapability::VendorCapability(Type type, + const std::string& id, + const std::string& display_name, + SelectVendorCapability select_capability) + : type_(type), + id_(id), + display_name_(display_name), + select_capability_(std::move(select_capability)) {} + +VendorCapability::VendorCapability( + Type type, + const std::string& id, + const std::string& display_name, + TypedValueVendorCapability typed_value_capability) + : type_(type), + id_(id), + display_name_(display_name), + typed_value_capability_(std::move(typed_value_capability)) {} + +VendorCapability::VendorCapability(VendorCapability&& other) = default; + +VendorCapability::~VendorCapability() = default; + +bool VendorCapability::operator==(const VendorCapability& other) const { + return type_ == other.type_ && id_ == other.id_ && + display_name_ == other.display_name_ && + range_capability_ == other.range_capability_ && + select_capability_ == other.select_capability_ && + typed_value_capability_ == other.typed_value_capability_; +} + +bool VendorCapability::IsValid() const { + if (id_.empty() || display_name_.empty()) + return false; + switch (type_) { + case Type::RANGE: + return !select_capability_ && !typed_value_capability_ && + range_capability_ && range_capability_.value().IsValid(); + case Type::SELECT: + return !range_capability_ && !typed_value_capability_ && + select_capability_ && select_capability_.value().IsValid(); + case Type::TYPED_VALUE: + return !range_capability_ && !select_capability_ && + typed_value_capability_ && + typed_value_capability_.value().IsValid(); + } + NOTREACHED() << "Bad vendor capability type"; + return false; +} + +bool VendorCapability::LoadFrom(const base::Value& dict) { + const std::string* type_str = dict.FindStringKey(kKeyType); + if (!type_str || + !TypeFromString(kVendorCapabilityTypeNames, *type_str, &type_)) { + return false; + } + const std::string* id_str = dict.FindStringKey(kKeyId); + if (!id_str) + return false; + id_ = *id_str; + const std::string* display_name_str = dict.FindStringKey(kKeyDisplayName); + if (!display_name_str) + return false; + display_name_ = *display_name_str; + + const base::Value* range_capability_value = + dict.FindKey(kOptionRangeCapability); + if (range_capability_value) { + if (!range_capability_value->is_dict()) + return false; + range_capability_ = RangeVendorCapability(); + if (!range_capability_.value().LoadFrom(*range_capability_value)) + return false; + } + + const base::Value* select_capability_value = + dict.FindKey(kOptionSelectCapability); + if (select_capability_value) { + if (!select_capability_value->is_dict()) + return false; + select_capability_ = SelectVendorCapability(); + if (!select_capability_.value().LoadFrom(*select_capability_value)) + return false; + } + + const base::Value* typed_value_capability_value = + dict.FindKey(kOptionTypedValueCapability); + if (typed_value_capability_value) { + if (!typed_value_capability_value->is_dict()) + return false; + typed_value_capability_ = TypedValueVendorCapability(); + if (!typed_value_capability_.value().LoadFrom( + *typed_value_capability_value)) { + return false; + } + } + + return IsValid(); +} + +void VendorCapability::SaveTo(base::Value* dict) const { + DCHECK(IsValid()); + dict->SetKey(kKeyType, + base::Value(TypeToString(kVendorCapabilityTypeNames, type_))); + dict->SetKey(kKeyId, base::Value(id_)); + dict->SetKey(kKeyDisplayName, base::Value(display_name_)); + + if (range_capability_) { + base::Value range_capability_value(base::Value::Type::DICTIONARY); + range_capability_.value().SaveTo(&range_capability_value); + dict->SetKey(kOptionRangeCapability, std::move(range_capability_value)); + } else if (select_capability_) { + base::Value select_capability_value(base::Value::Type::DICTIONARY); + select_capability_.value().SaveTo(&select_capability_value); + dict->SetKey(kOptionSelectCapability, std::move(select_capability_value)); + } else { + DCHECK(typed_value_capability_); + base::Value typed_value_capability_value(base::Value::Type::DICTIONARY); + typed_value_capability_.value().SaveTo(&typed_value_capability_value); + dict->SetKey(kOptionTypedValueCapability, + std::move(typed_value_capability_value)); + } +} + Color::Color() : type(ColorType::AUTO_COLOR) {} Color::Color(ColorType type) : type(type) { @@ -658,6 +1045,48 @@ } }; +class VendorCapabilityTraits : public ItemsTraits<kOptionVendorCapability> { + public: + static bool IsValid(const VendorCapability& option) { + return option.IsValid(); + } + + static bool Load(const base::Value& dict, VendorCapability* option) { + return option->LoadFrom(dict); + } + + static void Save(const VendorCapability& option, base::Value* dict) { + option.SaveTo(dict); + } +}; + +class SelectVendorCapabilityTraits + : public ItemsTraits<kOptionSelectCapability> { + public: + static bool IsValid(const SelectVendorCapabilityOption& option) { + return option.IsValid(); + } + + static bool Load(const base::Value& dict, + SelectVendorCapabilityOption* option) { + const std::string* value = dict.FindStringKey(kKeyValue); + if (!value) + return false; + option->value = *value; + const std::string* display_name = dict.FindStringKey(kKeyDisplayName); + if (!display_name) + return false; + option->display_name = *display_name; + return true; + } + + static void Save(const SelectVendorCapabilityOption& option, + base::Value* dict) { + dict->SetKey(kKeyValue, base::Value(option.value)); + dict->SetKey(kKeyDisplayName, base::Value(option.display_name)); + } +}; + class ColorTraits : public ItemsTraits<kOptionColor> { public: static bool IsValid(const Color& option) { return option.IsValid(); } @@ -926,6 +1355,9 @@ template class ListCapability<ContentType, ContentTypeTraits>; template class ValueCapability<PwgRasterConfig, PwgRasterConfigTraits>; +template class ListCapability<VendorCapability, VendorCapabilityTraits>; +template class SelectionCapability<SelectVendorCapabilityOption, + SelectVendorCapabilityTraits>; template class SelectionCapability<Color, ColorTraits>; template class SelectionCapability<DuplexType, DuplexTraits>; template class SelectionCapability<OrientationType, OrientationTraits>;
diff --git a/components/cloud_devices/common/printer_description.h b/components/cloud_devices/common/printer_description.h index a688a23b..3253758 100644 --- a/components/cloud_devices/common/printer_description.h +++ b/components/cloud_devices/common/printer_description.h
@@ -11,6 +11,7 @@ #include <vector> #include "base/logging.h" +#include "base/optional.h" #include "components/cloud_devices/common/description_items.h" // Defines printer options, CDD and CJT items. @@ -20,6 +21,12 @@ namespace printer { +struct SelectVendorCapabilityOption; +class SelectVendorCapabilityTraits; +typedef SelectionCapability<SelectVendorCapabilityOption, + SelectVendorCapabilityTraits> + SelectVendorCapability; + typedef std::string ContentType; enum class DocumentSheetBack { @@ -44,6 +51,140 @@ bool rotate_all_pages; }; +class RangeVendorCapability { + public: + enum class ValueType { + FLOAT, + INTEGER, + }; + + RangeVendorCapability(); + RangeVendorCapability(ValueType value_type, + const std::string& min_value, + const std::string& max_value); + RangeVendorCapability(ValueType value_type, + const std::string& min_value, + const std::string& max_value, + const std::string& default_value); + RangeVendorCapability(RangeVendorCapability&& other); + ~RangeVendorCapability(); + + RangeVendorCapability& operator=(RangeVendorCapability&& other); + + bool operator==(const RangeVendorCapability& other) const; + bool operator!=(const RangeVendorCapability& other) const { + return !(*this == other); + } + + bool IsValid() const; + bool LoadFrom(const base::Value& dict); + void SaveTo(base::Value* dict) const; + + private: + ValueType value_type_; + std::string min_value_; + std::string max_value_; + std::string default_value_; + + DISALLOW_COPY_AND_ASSIGN(RangeVendorCapability); +}; + +struct SelectVendorCapabilityOption { + SelectVendorCapabilityOption(); + SelectVendorCapabilityOption(const std::string& value, + const std::string& display_name); + ~SelectVendorCapabilityOption(); + + bool IsValid() const; + bool operator==(const SelectVendorCapabilityOption& other) const; + bool operator!=(const SelectVendorCapabilityOption& other) const { + return !(*this == other); + } + + std::string value; + std::string display_name; +}; + +class TypedValueVendorCapability { + public: + enum class ValueType { + BOOLEAN, + FLOAT, + INTEGER, + STRING, + }; + + TypedValueVendorCapability(); + explicit TypedValueVendorCapability(ValueType value_type); + TypedValueVendorCapability(ValueType value_type, + const std::string& default_value); + TypedValueVendorCapability(TypedValueVendorCapability&& other); + ~TypedValueVendorCapability(); + + TypedValueVendorCapability& operator=(TypedValueVendorCapability&& other); + + bool operator==(const TypedValueVendorCapability& other) const; + bool operator!=(const TypedValueVendorCapability& other) const { + return !(*this == other); + } + + bool IsValid() const; + bool LoadFrom(const base::Value& dict); + void SaveTo(base::Value* dict) const; + + private: + ValueType value_type_; + std::string default_value_; + + DISALLOW_COPY_AND_ASSIGN(TypedValueVendorCapability); +}; + +class VendorCapability { + public: + enum class Type { + RANGE, + SELECT, + TYPED_VALUE, + }; + + VendorCapability(); + VendorCapability(Type type, + const std::string& id, + const std::string& display_name, + RangeVendorCapability range_capability); + VendorCapability(Type type, + const std::string& id, + const std::string& display_name, + SelectVendorCapability select_capability); + VendorCapability(Type type, + const std::string& id, + const std::string& display_name, + TypedValueVendorCapability typed_value_capability); + VendorCapability(VendorCapability&& other); + ~VendorCapability(); + + bool operator==(const VendorCapability& other) const; + bool operator!=(const VendorCapability& other) const { + return !(*this == other); + } + + bool IsValid() const; + bool LoadFrom(const base::Value& dict); + void SaveTo(base::Value* dict) const; + + private: + Type type_; + std::string id_; + std::string display_name_; + + // If the CDD is valid, exactly one of the capabilities has non-nullopt value. + base::Optional<RangeVendorCapability> range_capability_; + base::Optional<SelectVendorCapability> select_capability_; + base::Optional<TypedValueVendorCapability> typed_value_capability_; + + DISALLOW_COPY_AND_ASSIGN(VendorCapability); +}; + enum class ColorType { STANDARD_COLOR, STANDARD_MONOCHROME, @@ -343,6 +484,7 @@ class ContentTypeTraits; class PwgRasterConfigTraits; +class VendorCapabilityTraits; class ColorTraits; class DuplexTraits; class OrientationTraits; @@ -357,6 +499,8 @@ typedef ListCapability<ContentType, ContentTypeTraits> ContentTypesCapability; typedef ValueCapability<PwgRasterConfig, PwgRasterConfigTraits> PwgRasterConfigCapability; +typedef ListCapability<VendorCapability, VendorCapabilityTraits> + VendorCapabilities; typedef SelectionCapability<Color, ColorTraits> ColorCapability; typedef SelectionCapability<DuplexType, DuplexTraits> DuplexCapability; typedef SelectionCapability<OrientationType, OrientationTraits>
diff --git a/components/cloud_devices/common/printer_description_unittest.cc b/components/cloud_devices/common/printer_description_unittest.cc index d123dbb..734cbe2 100644 --- a/components/cloud_devices/common/printer_description_unittest.cc +++ b/components/cloud_devices/common/printer_description_unittest.cc
@@ -270,6 +270,254 @@ " }" "}"; +const char kIntegerRangeVendorCapabilityJson[] = + "{" + " 'value_type': 'INTEGER'," + " 'min': '0'," + " 'max': '10'" + "}"; + +const char kFloatDefaultRangeVendorCapabilityJson[] = + "{" + " 'value_type': 'FLOAT'," + " 'min': '0.0'," + " 'max': '1.0'," + " 'default': '0.5'" + "}"; + +const char kInvalidTypeRangeVendorCapabilityJson[] = + "{" + " 'value_type': 'BOOLEAN'," + " 'min': '0.0'," + " 'max': '1.0'" + "}"; + +const char kMissingMinValueRangeVendorCapabilityJson[] = + "{" + " 'value_type': 'INT'," + " 'max': '10'" + "}"; + +const char kInvalidBoundariesRangeVendorCapabilityJson[] = + "{" + " 'value_type': 'INT'," + " 'min': '10'," + " 'max': '0'" + "}"; + +const char kInvalidDefaultValueRangeVendorCapabilityJson[] = + "{" + " 'value_type': 'FLOAT'," + " 'min': '0.0'," + " 'max': '5.0'," + " 'default': '10.0'" + "}"; + +const char kSelectVendorCapabilityJson[] = + "{" + " 'option': [ {" + " 'value': 'value_1'," + " 'display_name': 'name_1'" + " }, {" + " 'value': 'value_2'," + " 'display_name': 'name_2'," + " 'is_default': true" + " } ]" + "}"; + +const char kNotListSelectVendorCapabilityJson[] = + "{" + " 'option': {" + " 'value': 'value'," + " 'display_name': 'name'" + " }" + "}"; + +const char kMissingValueSelectVendorCapabilityJson[] = + "{" + " 'option': [ {" + " 'display_name': 'name'" + " } ]" + "}"; + +const char kMissingDisplayNameSelectVendorCapabilityJson[] = + "{" + " 'option': [ {" + " 'value': 'value'" + " } ]" + "}"; + +const char kNoDefaultSelectVendorCapabilityJson[] = + "{" + " 'option': [ {" + " 'value': 'value'," + " 'display_name': 'name'" + " } ]" + "}"; + +const char kSeveralDefaultsSelectVendorCapabilityJson[] = + "{" + " 'option': [ {" + " 'value': 'value_1'," + " 'display_name': 'name_1'," + " 'is_default': true" + " }, {" + " 'value': 'value_2'," + " 'display_name': 'name_2'," + " 'is_default': true" + " } ]" + "}"; + +const char kBooleanTypedValueVendorCapabilityJson[] = + "{" + " 'value_type': 'BOOLEAN'," + " 'default': 'true'" + "}"; + +const char kFloatTypedValueVendorCapabilityJson[] = + "{" + " 'value_type': 'FLOAT'," + " 'default': '1.0'" + "}"; + +const char kIntegerTypedValueVendorCapabilityJson[] = + "{" + " 'value_type': 'INTEGER'," + " 'default': '10'" + "}"; + +const char kStringTypedValueVendorCapabilityJson[] = + "{" + " 'value_type': 'STRING'," + " 'default': 'value'" + "}"; + +const char kMissingValueTypeTypedValueVendorCapabilityJson[] = + "{" + " 'default': 'value'" + "}"; + +const char kInvalidBooleanTypedValueVendorCapabilityJson[] = + "{" + " 'value_type': 'BOOLEAN'," + " 'default': '1'" + "}"; + +const char kInvalidFloatTypedValueVendorCapabilityJson[] = + "{" + " 'value_type': 'FLOAT'," + " 'default': '1.1.1.1'" + "}"; + +const char kInvalidIntegerTypedValueVendorCapabilityJson[] = + "{" + " 'value_type': 'INTEGER'," + " 'default': 'true'" + "}"; + +const char kVendorCapabilityOnlyCdd[] = + "{" + " 'version': '1.0'," + " 'printer': {" + " 'vendor_capability': [ {" + " 'id': 'id_1'," + " 'display_name': 'name_1'," + " 'type': 'RANGE'," + " 'range_cap': {" + " 'value_type': 'INTEGER'," + " 'min': '1'," + " 'max': '10'" + " }" + " }, {" + " 'id': 'id_2'," + " 'display_name': 'name_2'," + " 'type': 'SELECT'," + " 'select_cap': {" + " 'option': [ {" + " 'value': 'value'," + " 'display_name': 'name'," + " 'is_default': true" + " } ]" + " }" + " }, {" + " 'id': 'id_3'," + " 'display_name': 'name_3'," + " 'type': 'TYPED_VALUE'," + " 'typed_value_cap': {" + " 'value_type': 'INTEGER'," + " 'default': '1'" + " }" + " } ]" + " }" + "}"; + +const char kMissingIdVendorCapabilityCdd[] = + "{" + " 'version': '1.0'," + " 'printer': {" + " 'vendor_capability': [ {" + " 'display_name': 'name_1'," + " 'type': 'RANGE'," + " 'range_cap': {" + " 'value_type': 'INTEGER'," + " 'min': '1'," + " 'max': '10'" + " }" + " } ]" + " }" + "}"; + +const char kInvalidInnerCapabilityVendorCapabilityCdd[] = + "{" + " 'version': '1.0'," + " 'printer': {" + " 'vendor_capability': [ {" + " 'display_name': 'name_1'," + " 'type': 'RANGE'," + " 'range_cap': {" + " 'value_type': 'INTEGER'," + " 'min': '10'," + " 'max': '1'" + " }" + " } ]" + " }" + "}"; + +const char kNoInnerCapabilityVendorCapabilityCdd[] = + "{" + " 'version': '1.0'," + " 'printer': {" + " 'vendor_capability': [ {" + " 'display_name': 'name_1'," + " 'type': 'RANGE'" + " } ]" + " }" + "}"; + +const char kSeveralInnerCapabilitiesVendorCapabilityCdd[] = + "{" + " 'version': '1.0'," + " 'printer': {" + " 'vendor_capability': [ {" + " 'id': 'id_1'," + " 'display_name': 'name_1'," + " 'type': 'RANGE'," + " 'range_cap': {" + " 'value_type': 'INTEGER'," + " 'min': '1'," + " 'max': '10'" + " }," + " 'select_cap': {" + " 'option': [ {" + " 'value': 'value'," + " 'display_name': 'name'," + " 'is_default': true" + " } ]" + " }" + " } ]" + " }" + "}"; + const char kCjt[] = "{" " 'version': '1.0'," @@ -338,6 +586,38 @@ " }" "}"; +const struct TestRangeCapabilities { + const char* const json_name; + RangeVendorCapability range_capability; +} kTestRangeCapabilities[] = { + {kIntegerRangeVendorCapabilityJson, + RangeVendorCapability(RangeVendorCapability::ValueType::INTEGER, + "0", + "10")}, + {kFloatDefaultRangeVendorCapabilityJson, + RangeVendorCapability(RangeVendorCapability::ValueType::FLOAT, + "0.0", + "1.0", + "0.5")}}; + +const struct TestTypedValueCapabilities { + const char* const json_name; + TypedValueVendorCapability typed_value_capability; +} kTestTypedValueCapabilities[] = { + {kBooleanTypedValueVendorCapabilityJson, + TypedValueVendorCapability(TypedValueVendorCapability::ValueType::BOOLEAN, + "true")}, + {kFloatTypedValueVendorCapabilityJson, + TypedValueVendorCapability(TypedValueVendorCapability::ValueType::FLOAT, + "1.0")}, + {kIntegerTypedValueVendorCapabilityJson, + TypedValueVendorCapability(TypedValueVendorCapability::ValueType::INTEGER, + "10")}, + {kStringTypedValueVendorCapabilityJson, + TypedValueVendorCapability(TypedValueVendorCapability::ValueType::STRING, + "value")}, +}; + TEST(PrinterDescriptionTest, CddInit) { CloudDeviceDescription description; EXPECT_EQ(NormalizeJson(kDefaultCdd), NormalizeJson(description.ToString())); @@ -616,6 +896,194 @@ } } +TEST(PrinterDescriptionTest, CddGetRangeVendorCapability) { + for (const auto& capacity : kTestRangeCapabilities) { + std::unique_ptr<base::Value> value = + base::JSONReader::Read(NormalizeJson(capacity.json_name)); + ASSERT_TRUE(value); + base::Value description = base::Value::FromUniquePtrValue(std::move(value)); + RangeVendorCapability range_capability; + EXPECT_TRUE(range_capability.LoadFrom(description)); + EXPECT_EQ(capacity.range_capability, range_capability); + } + + const char* const kInvalidJsonNames[] = { + kMissingMinValueRangeVendorCapabilityJson, + kInvalidTypeRangeVendorCapabilityJson, + kInvalidBoundariesRangeVendorCapabilityJson, + kInvalidDefaultValueRangeVendorCapabilityJson}; + for (const char* invalid_json_name : kInvalidJsonNames) { + std::unique_ptr<base::Value> value = + base::JSONReader::Read(NormalizeJson(invalid_json_name)); + ASSERT_TRUE(value); + base::Value description = base::Value::FromUniquePtrValue(std::move(value)); + RangeVendorCapability range_capability; + EXPECT_FALSE(range_capability.LoadFrom(description)); + } +} + +TEST(PrinterDescriptionTest, CddSetRangeVendorCapability) { + for (const auto& capacity : kTestRangeCapabilities) { + base::Value range_capability_value(base::Value::Type::DICTIONARY); + capacity.range_capability.SaveTo(&range_capability_value); + std::string range_capability_str; + EXPECT_TRUE(base::JSONWriter::WriteWithOptions( + range_capability_value, base::JSONWriter::OPTIONS_PRETTY_PRINT, + &range_capability_str)); + EXPECT_EQ(NormalizeJson(capacity.json_name), + NormalizeJson(range_capability_str)); + } +} + +TEST(PrinterDescriptionTest, CddGetSelectVendorCapability) { + { + std::unique_ptr<base::Value> value = + base::JSONReader::Read(NormalizeJson(kSelectVendorCapabilityJson)); + ASSERT_TRUE(value); + base::Value description = base::Value::FromUniquePtrValue(std::move(value)); + SelectVendorCapability select_capability; + EXPECT_TRUE(select_capability.LoadFrom(description)); + EXPECT_EQ(2u, select_capability.size()); + EXPECT_TRUE(select_capability.Contains( + SelectVendorCapabilityOption("value_1", "name_1"))); + EXPECT_TRUE(select_capability.Contains( + SelectVendorCapabilityOption("value_2", "name_2"))); + EXPECT_EQ(SelectVendorCapabilityOption("value_2", "name_2"), + select_capability.GetDefault()); + } + + const char* const kInvalidJsonNames[] = { + kNotListSelectVendorCapabilityJson, + kMissingValueSelectVendorCapabilityJson, + kMissingDisplayNameSelectVendorCapabilityJson, + kNoDefaultSelectVendorCapabilityJson, + kSeveralDefaultsSelectVendorCapabilityJson}; + for (const char* invalid_json_name : kInvalidJsonNames) { + std::unique_ptr<base::Value> value = + base::JSONReader::Read(NormalizeJson(invalid_json_name)); + ASSERT_TRUE(value); + base::Value description = base::Value::FromUniquePtrValue(std::move(value)); + SelectVendorCapability select_capability; + EXPECT_FALSE(select_capability.LoadFrom(description)); + } +} + +TEST(PrinterDescriptionTest, CddSetSelectVendorCapability) { + SelectVendorCapability select_capability; + select_capability.AddOption( + SelectVendorCapabilityOption("value_1", "name_1")); + select_capability.AddDefaultOption( + SelectVendorCapabilityOption("value_2", "name_2"), true); + base::Value select_capability_value(base::Value::Type::DICTIONARY); + select_capability.SaveTo(&select_capability_value); + std::string select_capability_str; + EXPECT_TRUE(base::JSONWriter::WriteWithOptions( + select_capability_value, base::JSONWriter::OPTIONS_PRETTY_PRINT, + &select_capability_str)); + EXPECT_EQ(NormalizeJson(kSelectVendorCapabilityJson), + NormalizeJson(select_capability_str)); +} + +TEST(PrinterDescriptionTest, CddGetTypedValueVendorCapability) { + for (const auto& capacity : kTestTypedValueCapabilities) { + std::unique_ptr<base::Value> value = + base::JSONReader::Read(NormalizeJson(capacity.json_name)); + ASSERT_TRUE(value); + base::Value description = base::Value::FromUniquePtrValue(std::move(value)); + TypedValueVendorCapability typed_value_capability; + EXPECT_TRUE(typed_value_capability.LoadFrom(description)); + EXPECT_EQ(capacity.typed_value_capability, typed_value_capability); + } + + const char* const kInvalidJsonNames[] = { + kMissingValueTypeTypedValueVendorCapabilityJson, + kInvalidBooleanTypedValueVendorCapabilityJson, + kInvalidFloatTypedValueVendorCapabilityJson, + kInvalidIntegerTypedValueVendorCapabilityJson}; + for (const char* invalid_json_name : kInvalidJsonNames) { + std::unique_ptr<base::Value> value = + base::JSONReader::Read(NormalizeJson(invalid_json_name)); + ASSERT_TRUE(value); + base::Value description = base::Value::FromUniquePtrValue(std::move(value)); + TypedValueVendorCapability typed_value_capability; + EXPECT_FALSE(typed_value_capability.LoadFrom(description)); + } +} + +TEST(PrinterDescriptionTest, CddSetTypedValueVendorCapability) { + for (const auto& capacity : kTestTypedValueCapabilities) { + base::Value typed_value_capability_value(base::Value::Type::DICTIONARY); + capacity.typed_value_capability.SaveTo(&typed_value_capability_value); + std::string typed_value_capability_str; + EXPECT_TRUE(base::JSONWriter::WriteWithOptions( + typed_value_capability_value, base::JSONWriter::OPTIONS_PRETTY_PRINT, + &typed_value_capability_str)); + EXPECT_EQ(NormalizeJson(capacity.json_name), + NormalizeJson(typed_value_capability_str)); + } +} + +TEST(PrinterDescriptionTest, CddGetVendorCapability) { + { + CloudDeviceDescription description; + ASSERT_TRUE( + description.InitFromString(NormalizeJson(kVendorCapabilityOnlyCdd))); + + VendorCapabilities vendor_capabilities; + EXPECT_TRUE(vendor_capabilities.LoadFrom(description)); + EXPECT_EQ(3u, vendor_capabilities.size()); + EXPECT_TRUE(vendor_capabilities.Contains(VendorCapability( + VendorCapability::Type::RANGE, "id_1", "name_1", + RangeVendorCapability(RangeVendorCapability::ValueType::INTEGER, "1", + "10")))); + SelectVendorCapability select_capability; + select_capability.AddDefaultOption( + SelectVendorCapabilityOption("value", "name"), true); + EXPECT_TRUE(vendor_capabilities.Contains( + VendorCapability(VendorCapability::Type::SELECT, "id_2", "name_2", + std::move(select_capability)))); + EXPECT_TRUE(vendor_capabilities.Contains(VendorCapability( + VendorCapability::Type::TYPED_VALUE, "id_3", "name_3", + TypedValueVendorCapability( + TypedValueVendorCapability::ValueType::INTEGER, "1")))); + } + + const char* const kInvalidJsonNames[] = { + kMissingIdVendorCapabilityCdd, kInvalidInnerCapabilityVendorCapabilityCdd, + kNoInnerCapabilityVendorCapabilityCdd, + kSeveralInnerCapabilitiesVendorCapabilityCdd}; + for (const char* invalid_json_name : kInvalidJsonNames) { + CloudDeviceDescription description; + ASSERT_TRUE(description.InitFromString(NormalizeJson(invalid_json_name))); + VendorCapabilities vendor_capabilities; + EXPECT_FALSE(vendor_capabilities.LoadFrom(description)); + } +} + +TEST(PrinterDescriptionTest, CddSetVendorCapability) { + CloudDeviceDescription description; + + VendorCapabilities vendor_capabilities; + vendor_capabilities.AddOption(VendorCapability( + VendorCapability::Type::RANGE, "id_1", "name_1", + RangeVendorCapability(RangeVendorCapability::ValueType::INTEGER, "1", + "10"))); + SelectVendorCapability select_capability; + select_capability.AddDefaultOption( + SelectVendorCapabilityOption("value", "name"), true); + vendor_capabilities.AddOption(VendorCapability(VendorCapability::Type::SELECT, + "id_2", "name_2", + std::move(select_capability))); + vendor_capabilities.AddOption(VendorCapability( + VendorCapability::Type::TYPED_VALUE, "id_3", "name_3", + TypedValueVendorCapability(TypedValueVendorCapability::ValueType::INTEGER, + "1"))); + + vendor_capabilities.SaveTo(&description); + EXPECT_EQ(NormalizeJson(kVendorCapabilityOnlyCdd), + NormalizeJson(description.ToString())); +} + TEST(PrinterDescriptionTest, CddGetAll) { CloudDeviceDescription description; ASSERT_TRUE(description.InitFromString(NormalizeJson(kCdd)));
diff --git a/components/feed/core/feed_scheduler_host.cc b/components/feed/core/feed_scheduler_host.cc index f7a488e..cd032e4 100644 --- a/components/feed/core/feed_scheduler_host.cc +++ b/components/feed/core/feed_scheduler_host.cc
@@ -139,6 +139,64 @@ /*bucket_count=*/50); } +void ReportReasonForNotRefreshingByBehavior( + NativeRequestBehavior behavior, + FeedSchedulerHost::ShouldRefreshResult status) { + DCHECK_NE(status, FeedSchedulerHost::kShouldRefresh); + switch (behavior) { + case kNoRequestWithWait: + UMA_HISTOGRAM_ENUMERATION( + "ContentSuggestions.Feed.Scheduler.ShouldRefreshResult." + "NoRequestWithWait", + status); + break; + case kNoRequestWithContent: + UMA_HISTOGRAM_ENUMERATION( + "ContentSuggestions.Feed.Scheduler.ShouldRefreshResult." + "NoRequestWithContent", + status); + break; + case kNoRequestWithTimeout: + UMA_HISTOGRAM_ENUMERATION( + "ContentSuggestions.Feed.Scheduler.ShouldRefreshResult." + "NoRequestWithTimeout", + status); + break; + case kUnknown: + case kRequestWithWait: + case kRequestWithContent: + case kRequestWithTimeout: + NOTREACHED(); + break; + } +} + +void ReportReasonForNotRefreshingByTrigger( + FeedSchedulerHost::TriggerType trigger_type, + FeedSchedulerHost::ShouldRefreshResult status) { + DCHECK_NE(status, FeedSchedulerHost::kShouldRefresh); + switch (trigger_type) { + case FeedSchedulerHost::TriggerType::kNtpShown: + UMA_HISTOGRAM_ENUMERATION( + "ContentSuggestions.Feed.Scheduler.ShouldRefreshResult." + "RequestByNtpShown", + status); + break; + case FeedSchedulerHost::TriggerType::kForegrounded: + UMA_HISTOGRAM_ENUMERATION( + "ContentSuggestions.Feed.Scheduler.ShouldRefreshResult." + "RequestByForegrounded", + status); + break; + case FeedSchedulerHost::TriggerType::kFixedTimer: + UMA_HISTOGRAM_ENUMERATION( + "ContentSuggestions.Feed.Scheduler.ShouldRefreshResult." + "RequestByFixedTimer", + status); + break; + } +} + } // namespace FeedSchedulerHost::FeedSchedulerHost(PrefService* profile_prefs, @@ -225,7 +283,8 @@ } NativeRequestBehavior behavior; - if (ShouldRefresh(TriggerType::kNtpShown)) { + ShouldRefreshResult refresh_status = ShouldRefresh(TriggerType::kNtpShown); + if (kShouldRefresh == refresh_status) { if (!has_content) { behavior = kRequestWithWait; } else if (IsContentStale(content_creation_date_time)) { @@ -248,6 +307,7 @@ } else { behavior = kNoRequestWithContent; } + ReportReasonForNotRefreshingByBehavior(behavior, refresh_status); } OnSuggestionsShown(); @@ -282,8 +342,13 @@ void FeedSchedulerHost::OnForegrounded() { DCHECK(refresh_callback_); - if (ShouldRefresh(TriggerType::kForegrounded)) { + ShouldRefreshResult refresh_status = + ShouldRefresh(TriggerType::kForegrounded); + if (kShouldRefresh == refresh_status) { refresh_callback_.Run(); + } else { + ReportReasonForNotRefreshingByTrigger(TriggerType::kForegrounded, + refresh_status); } } @@ -298,7 +363,8 @@ CancelFixedTimerWakeUp(); } - if (ShouldRefresh(TriggerType::kFixedTimer)) { + ShouldRefreshResult refresh_status = ShouldRefresh(TriggerType::kFixedTimer); + if (kShouldRefresh == refresh_status) { // There shouldn't typically be anything in |fixed_timer_completion_| right // now, but if there was, run it before we replace it. TryRun(std::move(fixed_timer_completion_)); @@ -306,6 +372,8 @@ fixed_timer_completion_ = std::move(on_completion); refresh_callback_.Run(); } else { + ReportReasonForNotRefreshingByTrigger(TriggerType::kFixedTimer, + refresh_status); // The task driving this doesn't need to stay around, since no work is being // done on its behalf. TryRun(std::move(on_completion)); @@ -343,11 +411,17 @@ suppress_refreshes_until_ = clock_->Now() + base::TimeDelta::FromMinutes(kSuppressRefreshDurationMinutes.Get()); - } else if (ShouldRefresh(TriggerType::kNtpShown)) { + } + + ShouldRefreshResult refresh_status = ShouldRefresh(TriggerType::kNtpShown); + if (kShouldRefresh == refresh_status) { // Instead of using |refresh_callback_|, instead return our desire to // refresh back up to our caller. This allows more information to be given // all at once to the Feed which allows it to act more intelligently. return true; + } else { + ReportReasonForNotRefreshingByTrigger(TriggerType::kNtpShown, + refresh_status); } return false; @@ -357,35 +431,36 @@ OnForegrounded(); } -bool FeedSchedulerHost::ShouldRefresh(TriggerType trigger) { +FeedSchedulerHost::ShouldRefreshResult FeedSchedulerHost::ShouldRefresh( + TriggerType trigger) { if (clock_->Now() < outstanding_request_until_) { DVLOG(2) << "Outstanding request stopped refresh from trigger " << static_cast<int>(trigger); - return false; + return kDontRefreshOutstandingRequest; } if (base::ContainsKey(disabled_triggers_, trigger)) { DVLOG(2) << "Disabled trigger stopped refresh from trigger " << static_cast<int>(trigger); - return false; + return kDontRefreshTriggerDisabled; } if (net::NetworkChangeNotifier::IsOffline()) { DVLOG(2) << "Network is offline stopped refresh from trigger " << static_cast<int>(trigger); - return false; + return kDontRefreshNetworkOffline; } if (eula_accepted_notifier_ && !eula_accepted_notifier_->IsEulaAccepted()) { DVLOG(2) << "EULA not being accepted stopped refresh from trigger " << static_cast<int>(trigger); - return false; + return kDontRefreshEulaNotAccepted; } if (!profile_prefs_->GetBoolean(prefs::kArticlesListVisible)) { DVLOG(2) << "Articles being hidden stopped refresh from trigger " << static_cast<int>(trigger); - return false; + return kDontRefreshArticlesHidden; } base::TimeDelta attempt_age = @@ -407,13 +482,13 @@ if (clock_->Now() < suppress_refreshes_until_) { DVLOG(2) << "Refresh suppression until " << suppress_refreshes_until_ << " stopped refresh from trigger " << static_cast<int>(trigger); - return false; + return kDontRefreshRefreshSuppressed; } if (attempt_age < GetTriggerThreshold(trigger)) { DVLOG(2) << "Last attempt age of " << attempt_age << " stopped refresh from trigger " << static_cast<int>(trigger); - return false; + return kDontRefreshNotStale; } auto throttlerIter = throttlers_.find(user_class); @@ -421,7 +496,7 @@ !throttlerIter->second->RequestQuota()) { DVLOG(2) << "Throttler stopped refresh from trigger " << static_cast<int>(trigger); - return false; + return kDontRefreshRefreshThrottled; } switch (trigger) { @@ -443,7 +518,7 @@ clock_->Now() + base::TimeDelta::FromSeconds(kTimeoutDurationSeconds.Get()); - return true; + return kShouldRefresh; } bool FeedSchedulerHost::IsContentStale(base::Time content_creation_date_time) {
diff --git a/components/feed/core/feed_scheduler_host.h b/components/feed/core/feed_scheduler_host.h index 3146936..a0d00d0 100644 --- a/components/feed/core/feed_scheduler_host.h +++ b/components/feed/core/feed_scheduler_host.h
@@ -60,6 +60,24 @@ kMaxValue = kFixedTimer }; + // Enum for the status of the refresh, reported through UMA. + // If any new values are added, update the corresponding definition in + // enums.xml. + // These values are persisted to logs. Entries should not be renumbered and + // numeric values should never be reused. + enum ShouldRefreshResult { + kShouldRefresh = 0, + kDontRefreshOutstandingRequest = 1, + kDontRefreshTriggerDisabled = 2, + kDontRefreshNetworkOffline = 3, + kDontRefreshEulaNotAccepted = 4, + kDontRefreshArticlesHidden = 5, + kDontRefreshRefreshSuppressed = 6, + kDontRefreshNotStale = 7, + kDontRefreshRefreshThrottled = 8, + kMaxValue = kDontRefreshRefreshThrottled, + }; + FeedSchedulerHost(PrefService* profile_prefs, PrefService* local_state, base::Clock* clock); @@ -126,7 +144,7 @@ // If this method is called and returns true we presume the refresh will // happen, therefore we report metrics respectively and update // |tracking_oustanding_request_|. - bool ShouldRefresh(TriggerType trigger); + ShouldRefreshResult ShouldRefresh(TriggerType trigger); // Decides if content whose age is the difference between now and // |content_creation_date_time| is old enough to be considered stale.
diff --git a/components/history/core/browser/history_backend.cc b/components/history/core/browser/history_backend.cc index fb5726e..82d4cef2 100644 --- a/components/history/core/browser/history_backend.cc +++ b/components/history/core/browser/history_backend.cc
@@ -197,16 +197,18 @@ } HistoryBackend::HistoryBackend( - Delegate* delegate, + std::unique_ptr<Delegate> delegate, std::unique_ptr<HistoryBackendClient> backend_client, scoped_refptr<base::SequencedTaskRunner> task_runner) - : delegate_(delegate), + : delegate_(std::move(delegate)), scheduled_kill_db_(false), expirer_(this, backend_client.get(), task_runner), recent_redirects_(kMaxRedirectCount), segment_queried_(false), backend_client_(std::move(backend_client)), - task_runner_(task_runner) {} + task_runner_(task_runner) { + DCHECK(delegate_); +} HistoryBackend::~HistoryBackend() { DCHECK(scheduled_commit_.IsCancelled()) << "Deleting without cleanup"; @@ -265,10 +267,6 @@ // Any scheduled commit will have a reference to us, we must make it // release that reference before we can be destroyed. CancelScheduledCommit(); - - // Release our reference to the delegate, this reference will be keeping the - // history service alive. - delegate_.reset(); } #if defined(OS_IOS) @@ -1133,9 +1131,7 @@ } db_->SetKeywordSearchTermsForURL(row.id(), keyword_id, term); - - if (delegate_) - delegate_->NotifyKeywordSearchTermUpdated(row, keyword_id, term); + delegate_->NotifyKeywordSearchTermUpdated(row, keyword_id, term); ScheduleCommit(); } @@ -1156,9 +1152,7 @@ if (!url_id) return; db_->DeleteKeywordSearchTermForURL(url_id); - - if (delegate_) - delegate_->NotifyKeywordSearchTermDeleted(url_id); + delegate_->NotifyKeywordSearchTermDeleted(url_id); ScheduleCommit(); } @@ -2638,8 +2632,7 @@ void HistoryBackend::NotifyFaviconsChanged(const std::set<GURL>& page_urls, const GURL& icon_url) { - if (delegate_) - delegate_->NotifyFaviconsChanged(page_urls, icon_url); + delegate_->NotifyFaviconsChanged(page_urls, icon_url); } void HistoryBackend::NotifyURLVisited(ui::PageTransition transition, @@ -2649,8 +2642,7 @@ for (HistoryBackendObserver& observer : observers_) observer.OnURLVisited(this, transition, row, redirects, visit_time); - if (delegate_) - delegate_->NotifyURLVisited(transition, row, redirects, visit_time); + delegate_->NotifyURLVisited(transition, row, redirects, visit_time); } void HistoryBackend::NotifyURLsModified(const URLRows& changed_urls, @@ -2658,8 +2650,7 @@ for (HistoryBackendObserver& observer : observers_) observer.OnURLsModified(this, changed_urls, is_from_expiration); - if (delegate_) - delegate_->NotifyURLsModified(changed_urls); + delegate_->NotifyURLsModified(changed_urls); } void HistoryBackend::NotifyURLsDeleted(DeletionInfo deletion_info) { @@ -2676,8 +2667,7 @@ deletion_info.deleted_rows(), deletion_info.favicon_urls()); } - if (delegate_) - delegate_->NotifyURLsDeleted(std::move(deletion_info)); + delegate_->NotifyURLsDeleted(std::move(deletion_info)); } // Deleting --------------------------------------------------------------------
diff --git a/components/history/core/browser/history_backend.h b/components/history/core/browser/history_backend.h index 2ffbe2d..c3b1094 100644 --- a/components/history/core/browser/history_backend.h +++ b/components/history/core/browser/history_backend.h
@@ -185,7 +185,7 @@ // may be null. // // This constructor is fast and does no I/O, so can be called at any time. - HistoryBackend(Delegate* delegate, + HistoryBackend(std::unique_ptr<Delegate> delegate, std::unique_ptr<HistoryBackendClient> backend_client, scoped_refptr<base::SequencedTaskRunner> task_runner);
diff --git a/components/history/core/browser/history_backend_unittest.cc b/components/history/core/browser/history_backend_unittest.cc index ff4bcd5..69a9996 100644 --- a/components/history/core/browser/history_backend_unittest.cc +++ b/components/history/core/browser/history_backend_unittest.cc
@@ -254,9 +254,10 @@ if (!base::CreateNewTempDirectory(FILE_PATH_LITERAL("BackendTest"), &test_dir_)) return; - backend_ = new HistoryBackend(new HistoryBackendTestDelegate(this), - history_client_.CreateBackendClient(), - base::ThreadTaskRunnerHandle::Get()); + backend_ = base::MakeRefCounted<HistoryBackend>( + std::make_unique<HistoryBackendTestDelegate>(this), + history_client_.CreateBackendClient(), + base::ThreadTaskRunnerHandle::Get()); backend_->Init(false, TestHistoryDatabaseParamsForPath(test_dir_)); } @@ -1666,9 +1667,10 @@ base::FilePath new_history_file = new_history_path.Append(kHistoryFilename); ASSERT_TRUE(base::CopyFile(old_history_path, new_history_file)); - backend_ = new HistoryBackend(new HistoryBackendTestDelegate(this), - history_client_.CreateBackendClient(), - base::ThreadTaskRunnerHandle::Get()); + backend_ = base::MakeRefCounted<HistoryBackend>( + std::make_unique<HistoryBackendTestDelegate>(this), + history_client_.CreateBackendClient(), + base::ThreadTaskRunnerHandle::Get()); backend_->Init(false, TestHistoryDatabaseParamsForPath(new_history_path)); backend_->Closing(); backend_ = nullptr; @@ -3360,9 +3362,10 @@ base::FilePath new_history_file = new_history_path.Append(kHistoryFilename); ASSERT_TRUE(base::CopyFile(old_history, new_history_file)); - backend_ = new HistoryBackend(new HistoryBackendTestDelegate(this), - history_client_.CreateBackendClient(), - base::ThreadTaskRunnerHandle::Get()); + backend_ = base::MakeRefCounted<HistoryBackend>( + std::make_unique<HistoryBackendTestDelegate>(this), + history_client_.CreateBackendClient(), + base::ThreadTaskRunnerHandle::Get()); backend_->Init(false, TestHistoryDatabaseParamsForPath(new_history_path)); backend_->Closing(); backend_ = nullptr;
diff --git a/components/history/core/browser/history_service.cc b/components/history/core/browser/history_service.cc index bdfb446..5d0faea 100644 --- a/components/history/core/browser/history_service.cc +++ b/components/history/core/browser/history_service.cc
@@ -895,31 +895,8 @@ // Get rid of the in-memory backend. in_memory_backend_.reset(); - // The backend's destructor must run on the history thread since it is not - // threadsafe. So this thread must not be the last thread holding a - // reference to the backend, or a crash could happen. - // - // We have a reference to the history backend. There is also an extra - // reference held by our delegate installed in the backend, which - // HistoryBackend::Closing will release. This means if we scheduled a call - // to HistoryBackend::Closing and *then* released our backend reference, - // there will be a race between us and the backend's Closing function to see - // who is the last holder of a reference. If the backend thread's Closing - // manages to run before we release our backend refptr, the last reference - // will be held by this thread and the destructor will be called from here. - // - // Therefore, we create a closure to run the Closing operation first. This - // holds a reference to the backend. Then we release our reference, then we - // schedule the task to run. After the task runs, it will delete its - // reference from the history thread, ensuring everything works properly. - // - // TODO(ajwong): Cleanup HistoryBackend lifetime issues. - // See http://crbug.com/99767. - base::Closure closing_task = - base::Bind(&HistoryBackend::Closing, history_backend_); - ScheduleTask(PRIORITY_NORMAL, closing_task); - closing_task.Reset(); - backend_task_runner_->ReleaseSoon(FROM_HERE, std::move(history_backend_)); + ScheduleTask(PRIORITY_NORMAL, base::BindOnce(&HistoryBackend::Closing, + std::move(history_backend_))); } // Clear |backend_task_runner_| to make sure it's not used after Cleanup(). @@ -955,9 +932,9 @@ } // Create the history backend. - scoped_refptr<HistoryBackend> backend(new HistoryBackend( - new BackendDelegate(weak_ptr_factory_.GetWeakPtr(), - base::ThreadTaskRunnerHandle::Get()), + scoped_refptr<HistoryBackend> backend(base::MakeRefCounted<HistoryBackend>( + std::make_unique<BackendDelegate>(weak_ptr_factory_.GetWeakPtr(), + base::ThreadTaskRunnerHandle::Get()), history_client_ ? history_client_->CreateBackendClient() : nullptr, backend_task_runner_)); history_backend_.swap(backend);
diff --git a/components/history/core/browser/sync/typed_url_sync_bridge_unittest.cc b/components/history/core/browser/sync/typed_url_sync_bridge_unittest.cc index ec95383..5f1ce83 100644 --- a/components/history/core/browser/sync/typed_url_sync_bridge_unittest.cc +++ b/components/history/core/browser/sync/typed_url_sync_bridge_unittest.cc
@@ -234,7 +234,7 @@ class TestHistoryBackend : public HistoryBackend { public: TestHistoryBackend() - : HistoryBackend(new TestHistoryBackendDelegate(), + : HistoryBackend(std::make_unique<TestHistoryBackendDelegate>(), nullptr, base::ThreadTaskRunnerHandle::Get()) {}
diff --git a/components/history/core/test/history_backend_db_base_test.cc b/components/history/core/test/history_backend_db_base_test.cc index 2308e223..61b10a0 100644 --- a/components/history/core/test/history_backend_db_base_test.cc +++ b/components/history/core/test/history_backend_db_base_test.cc
@@ -82,8 +82,9 @@ } void HistoryBackendDBBaseTest::CreateBackendAndDatabase() { - backend_ = new HistoryBackend(new BackendDelegate(this), nullptr, - base::ThreadTaskRunnerHandle::Get()); + backend_ = base::MakeRefCounted<HistoryBackend>( + std::make_unique<BackendDelegate>(this), nullptr, + base::ThreadTaskRunnerHandle::Get()); backend_->Init(false, TestHistoryDatabaseParamsForPath(history_dir_)); db_ = backend_->db_.get(); @@ -92,8 +93,9 @@ } void HistoryBackendDBBaseTest::CreateBackendAndDatabaseAllowFail() { - backend_ = new HistoryBackend(new BackendDelegate(this), nullptr, - base::ThreadTaskRunnerHandle::Get()); + backend_ = base::MakeRefCounted<HistoryBackend>( + std::make_unique<BackendDelegate>(this), nullptr, + base::ThreadTaskRunnerHandle::Get()); backend_->Init(false, TestHistoryDatabaseParamsForPath(history_dir_)); db_ = backend_->db_.get();
diff --git a/components/invalidation/impl/fcm_invalidation_service.cc b/components/invalidation/impl/fcm_invalidation_service.cc index 6cbf941..dcb233e7 100644 --- a/components/invalidation/impl/fcm_invalidation_service.cc +++ b/components/invalidation/impl/fcm_invalidation_service.cc
@@ -129,6 +129,9 @@ const { return_callback.Run(diagnostic_info_.CollectDebugData()); invalidator_registrar_.RequestDetailedStatus(return_callback); + if (identity_provider_) { + identity_provider_->RequestDetailedStatus(return_callback); + } if (IsStarted()) { invalidator_->RequestDetailedStatus(return_callback); }
diff --git a/components/invalidation/public/BUILD.gn b/components/invalidation/public/BUILD.gn index 6bfae174..3d55989 100644 --- a/components/invalidation/public/BUILD.gn +++ b/components/invalidation/public/BUILD.gn
@@ -35,6 +35,7 @@ ] deps = [ "//base", + "//base:i18n", ] }
diff --git a/components/invalidation/public/identity_provider.cc b/components/invalidation/public/identity_provider.cc index 54d4eef..1424cc1 100644 --- a/components/invalidation/public/identity_provider.cc +++ b/components/invalidation/public/identity_provider.cc
@@ -4,6 +4,8 @@ #include "components/invalidation/public/identity_provider.h" +#include "base/i18n/time_formatting.h" + namespace invalidation { IdentityProvider::Observer::~Observer() {} @@ -22,16 +24,21 @@ void IdentityProvider::ProcessRefreshTokenUpdateForAccount( const std::string& account_id) { - if (account_id != GetActiveAccountId()) + if (account_id != GetActiveAccountId()) { + diagnostic_info_.token_update_for_not_active_account_count++; return; + } + diagnostic_info_.account_token_updated = base::Time::Now(); for (auto& observer : observers_) observer.OnActiveAccountRefreshTokenUpdated(); } void IdentityProvider::ProcessRefreshTokenRemovalForAccount( const std::string& account_id) { - if (account_id != GetActiveAccountId()) + if (account_id != GetActiveAccountId()) { + diagnostic_info_.token_removal_for_not_active_account_count++; return; + } for (auto& observer : observers_) observer.OnActiveAccountRefreshTokenRemoved(); } @@ -46,4 +53,24 @@ observer.OnActiveAccountLogout(); } +void IdentityProvider::RequestDetailedStatus( + base::RepeatingCallback<void(const base::DictionaryValue&)> return_callback) + const { + return_callback.Run(diagnostic_info_.CollectDebugData()); +} + +IdentityProvider::Diagnostics::Diagnostics() {} + +base::DictionaryValue IdentityProvider::Diagnostics::CollectDebugData() const { + base::DictionaryValue status; + + status.SetInteger("IdentityProvider.token-removal-for-not-active-account", + token_removal_for_not_active_account_count); + status.SetInteger("IdentityProvider.token-update-for-not-active-account", + token_update_for_not_active_account_count); + status.SetString("IdentityProvider.account-token-updated", + base::TimeFormatShortDateAndTime(account_token_updated)); + return status; +} + } // namespace invalidation
diff --git a/components/invalidation/public/identity_provider.h b/components/invalidation/public/identity_provider.h index 51a85b7..a763163 100644 --- a/components/invalidation/public/identity_provider.h +++ b/components/invalidation/public/identity_provider.h
@@ -11,6 +11,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/observer_list.h" +#include "base/values.h" #include "google_apis/gaia/oauth2_token_service.h" namespace invalidation { @@ -88,6 +89,9 @@ void AddObserver(Observer* observer); void RemoveObserver(Observer* observer); + void RequestDetailedStatus( + base::RepeatingCallback<void(const base::DictionaryValue&)> caller) const; + protected: IdentityProvider(); @@ -106,6 +110,18 @@ void FireOnActiveAccountLogout(); private: + struct Diagnostics { + Diagnostics(); + + // Collect all the internal variables in a single readable dictionary. + base::DictionaryValue CollectDebugData() const; + + int token_removal_for_not_active_account_count = 0; + int token_update_for_not_active_account_count = 0; + base::Time account_token_updated; + }; + + Diagnostics diagnostic_info_; base::ObserverList<Observer, true>::Unchecked observers_; DISALLOW_COPY_AND_ASSIGN(IdentityProvider);
diff --git a/components/keyed_service/OWNERS b/components/keyed_service/OWNERS index 39557cd..10af5a5b 100644 --- a/components/keyed_service/OWNERS +++ b/components/keyed_service/OWNERS
@@ -1 +1,2 @@ blundell@chromium.org +sdefresne@chromium.org
diff --git a/components/leveldb_proto/OWNERS b/components/leveldb_proto/OWNERS index f473a87..a120a02 100644 --- a/components/leveldb_proto/OWNERS +++ b/components/leveldb_proto/OWNERS
@@ -1,4 +1,5 @@ mathp@chromium.org nyquist@chromium.org +ssid@chromium.org # COMPONENT: Internals
diff --git a/components/password_manager/core/browser/password_manager.cc b/components/password_manager/core/browser/password_manager.cc index 932d9a5..9cf66f8 100644 --- a/components/password_manager/core/browser/password_manager.cc +++ b/components/password_manager/core/browser/password_manager.cc
@@ -974,6 +974,31 @@ DropFormManagers(); } +#if defined(OS_IOS) +void PasswordManager::PresaveGeneratedPassword( + PasswordManagerDriver* driver, + const FormData& form, + const base::string16& generated_password, + const base::string16& generation_element, + bool is_manually_triggered) { + // TODO(https://crbug.com/886583): Implement it. +} + +void PasswordManager::UpdateGeneratedPasswordOnUserInput( + PasswordManagerDriver* driver, + const base::string16& form_identifier, + const base::string16& field_identifier, + const base::string16& field_value) { + // TODO(https://crbug.com/886583): Implement it. +} + +void PasswordManager::OnPasswordNoLongerGenerated( + PasswordManagerDriver* driver) { + // TODO(https://crbug.com/886583): Implement it. +} + +#endif + void PasswordManager::ProvisionallySaveManager( const PasswordForm& form, PasswordFormManager* matched_manager,
diff --git a/components/password_manager/core/browser/password_manager.h b/components/password_manager/core/browser/password_manager.h index f04478a..be1f968 100644 --- a/components/password_manager/core/browser/password_manager.h +++ b/components/password_manager/core/browser/password_manager.h
@@ -191,6 +191,36 @@ // Notifies that Credential Management API function store() is called. void NotifyStorePasswordCalled(); +#if defined(OS_IOS) + // TODO(https://crbug.com/866444): Use these methods instead olds ones when + // the old parser is gone. + + // Presaves the form with |generated_password|. This function is called once + // when the user accepts the generated password. The password was generated in + // the field with identifier |generation_element|. |driver| corresponds to the + // |form| parent frame. + void PresaveGeneratedPassword(PasswordManagerDriver* driver, + const autofill::FormData& form, + const base::string16& generated_password, + const base::string16& generation_element, + bool is_manually_triggered); + + // Updates the presaved credential with the generated password when the user + // types in field with |field_identifier|, which is in form with + // |form_identifier| and the field value is |field_value|. |driver| + // corresponds to the form parent frame. + void UpdateGeneratedPasswordOnUserInput( + PasswordManagerDriver* driver, + const base::string16& form_identifier, + const base::string16& field_identifier, + const base::string16& field_value); + + // Stops treating a password as generated. |driver| corresponds to the + // form parent frame. + void OnPasswordNoLongerGenerated(PasswordManagerDriver* driver); + +#endif + private: FRIEND_TEST_ALL_PREFIXES( PasswordManagerTest,
diff --git a/components/payments/core/features.cc b/components/payments/core/features.cc index 47cd23d6..e96ce47 100644 --- a/components/payments/core/features.cc +++ b/components/payments/core/features.cc
@@ -15,15 +15,19 @@ base::FEATURE_DISABLED_BY_DEFAULT}; #endif +// TODO(rouslan): Remove this. const base::Feature kWebPaymentsMethodSectionOrderV2{ "WebPaymentsMethodSectionOrderV2", base::FEATURE_DISABLED_BY_DEFAULT}; +// TODO(rouslan): Remove this. const base::Feature kWebPaymentsModifiers{"WebPaymentsModifiers", base::FEATURE_ENABLED_BY_DEFAULT}; +// TODO(rouslan): Remove this. const base::Feature kWebPaymentsSingleAppUiSkip{ "WebPaymentsSingleAppUiSkip", base::FEATURE_ENABLED_BY_DEFAULT}; +// TODO(rouslan): Remove this. const base::Feature kWebPaymentsJustInTimePaymentApp{ "WebPaymentsJustInTimePaymentApp", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/components/signin/core/browser/account_reconcilor.cc b/components/signin/core/browser/account_reconcilor.cc index 02e2c27..4d7d458 100644 --- a/components/signin/core/browser/account_reconcilor.cc +++ b/components/signin/core/browser/account_reconcilor.cc
@@ -725,16 +725,15 @@ // For each account known to chrome, PerformMergeAction() if the account is // not already in the cookie jar or its state is invalid, or signal merge // completed otherwise. Make a copy of |add_to_cookie_| since calls to - // SignalComplete() will change the array. + // OnAddAccountToCookieCompleted() will change the array. std::vector<std::string> add_to_cookie_copy = add_to_cookie_; int added_to_cookie = 0; for (size_t i = 0; i < add_to_cookie_copy.size(); ++i) { if (gaia_accounts.end() != std::find_if(gaia_accounts.begin(), gaia_accounts.end(), AccountEqualToFunc(AccountForId(add_to_cookie_copy[i])))) { - cookie_manager_service_->SignalComplete( - add_to_cookie_copy[i], - GoogleServiceAuthError::AuthErrorNone()); + OnAddAccountToCookieCompleted(add_to_cookie_copy[i], + GoogleServiceAuthError::AuthErrorNone()); } else { PerformMergeAction(add_to_cookie_copy[i]); if (original_gaia_accounts.end() ==
diff --git a/components/signin/core/browser/gaia_cookie_manager_service.h b/components/signin/core/browser/gaia_cookie_manager_service.h index 45f3cfc..26038ed 100644 --- a/components/signin/core/browser/gaia_cookie_manager_service.h +++ b/components/signin/core/browser/gaia_cookie_manager_service.h
@@ -288,12 +288,6 @@ // Signout all accounts. void LogOutAllAccounts(gaia::GaiaSource source); - // Call observers when merge session completes. This public so that callers - // that know that a given account is already in the cookie jar can simply - // inform the observers. - void SignalComplete(const std::string& account_id, - const GoogleServiceAuthError& error); - // Call observers when setting accounts in cookie completes. void SignalSetAccountsComplete(const GoogleServiceAuthError& error); @@ -332,6 +326,10 @@ scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory(); + // Calls the AddAccountToCookie completion callback. + void SignalComplete(const std::string& account_id, + const GoogleServiceAuthError& error); + // Marks the list account being staled, and for iOS only, it triggers to fetch // the list of accounts (on iOS there is no OnCookieChange() notification). void MarkListAccountsStale();
diff --git a/components/variations/service/variations_field_trial_creator_unittest.cc b/components/variations/service/variations_field_trial_creator_unittest.cc index c1088cda..3910b35 100644 --- a/components/variations/service/variations_field_trial_creator_unittest.cc +++ b/components/variations/service/variations_field_trial_creator_unittest.cc
@@ -30,7 +30,6 @@ #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_ANDROID) -#include "components/variations/android/variations_seed_bridge.h" #include "components/variations/seed_response.h" #endif // OS_ANDROID @@ -99,6 +98,7 @@ Study* study = seed.mutable_study(0); Study::Filter* filter = study->mutable_filter(); filter->add_country(kTestSeedCountry); + filter->add_platform(Study::PLATFORM_ANDROID); return seed; }
diff --git a/components/variations/study_filtering.cc b/components/variations/study_filtering.cc index 6f1e2177..54aa57b 100644 --- a/components/variations/study_filtering.cc +++ b/components/variations/study_filtering.cc
@@ -107,10 +107,6 @@ } bool CheckStudyPlatform(const Study::Filter& filter, Study::Platform platform) { - // An empty platform list matches all platforms. - if (filter.platform_size() == 0) - return true; - for (int i = 0; i < filter.platform_size(); ++i) { if (filter.platform(i) == platform) return true;
diff --git a/components/variations/study_filtering_unittest.cc b/components/variations/study_filtering_unittest.cc index 184747fda..2b11e1af 100644 --- a/components/variations/study_filtering_unittest.cc +++ b/components/variations/study_filtering_unittest.cc
@@ -222,10 +222,10 @@ Study::Filter filter; // Check in the forwarded order. The loop cond is <= base::size(platforms) - // instead of < so that the result of adding the last channel gets checked. + // instead of < so that the result of adding the last platform gets checked. for (size_t i = 0; i <= base::size(platforms); ++i) { for (size_t j = 0; j < base::size(platforms); ++j) { - const bool expected = platform_added[j] || filter.platform_size() == 0; + const bool expected = platform_added[j]; const bool result = internal::CheckStudyPlatform(filter, platforms[j]); EXPECT_EQ(expected, result) << "Case " << i << "," << j << " failed!"; } @@ -241,7 +241,7 @@ memset(&platform_added, 0, sizeof(platform_added)); for (size_t i = 0; i <= base::size(platforms); ++i) { for (size_t j = 0; j < base::size(platforms); ++j) { - const bool expected = platform_added[j] || filter.platform_size() == 0; + const bool expected = platform_added[j]; const bool result = internal::CheckStudyPlatform(filter, platforms[j]); EXPECT_EQ(expected, result) << "Case " << i << "," << j << " failed!"; } @@ -575,6 +575,7 @@ study->set_default_experiment_name("Default"); AddExperiment("Default", 100, study); study->set_consistency(test.consistency); + study->mutable_filter()->add_platform(Study::PLATFORM_ANDROID); if (test.filter_country) study->mutable_filter()->add_country(test.filter_country); if (test.filter_exclude_country) @@ -585,7 +586,7 @@ client_state.reference_date = base::Time::Now(); client_state.version = base::Version("20.0.0.0"); client_state.channel = Study::STABLE; - client_state.form_factor = Study::DESKTOP; + client_state.form_factor = Study::PHONE; client_state.platform = Study::PLATFORM_ANDROID; client_state.session_consistency_country = kSessionCountry; client_state.permanent_consistency_country = kPermanentCountry;
diff --git a/components/viz/client/hit_test_data_provider_draw_quad_unittest.cc b/components/viz/client/hit_test_data_provider_draw_quad_unittest.cc index 44349935..b085253 100644 --- a/components/viz/client/hit_test_data_provider_draw_quad_unittest.cc +++ b/components/viz/client/hit_test_data_provider_draw_quad_unittest.cc
@@ -313,4 +313,109 @@ hit_test_region_list->regions[0].transform); } +// Test to ensure that we account for shape-rects in hit-test data when it's +// present in the filters of the RenderPass. +TEST(HitTestDataProviderDrawQuad, HitTestDataShapeFilters) { + std::unique_ptr<HitTestDataProvider> hit_test_data_provider = + std::make_unique<HitTestDataProviderDrawQuad>( + true /* should_ask_for_child_region */, + true /* root_accepts_events */); + + constexpr gfx::Rect kFrameRect(0, 0, 1024, 768); + gfx::Rect child_rect(200, 100); + gfx::Transform invertible_transform; + invertible_transform.Translate(200, 100); + + RenderPassList pass_list; + + // A render pass that has shape filters. + SurfaceId child_surface_id1 = CreateChildSurfaceId(2); + SurfaceId child_surface_id2 = CreateChildSurfaceId(3); + + auto pass1 = RenderPass::Create(); + pass1->SetNew(1, kFrameRect, kFrameRect, invertible_transform); + // Create a filter with three shapes, the first two are included in + // surface_quad_1 and the other one intersects sueface_quad_2. These rects are + // in DIP space. + cc::FilterOperations filters; + filters.Append(cc::FilterOperation::CreateAlphaThresholdFilter( + {gfx::Rect(101, 51, 25, 25), gfx::Rect(151, 51, 25, 25), + gfx::Rect(325, 200, 200, 200)}, + 0.f, 0.f)); + pass1->filters = filters; + auto* shared_state_1 = pass1->CreateAndAppendSharedQuadState(); + shared_state_1->SetAll(invertible_transform, kFrameRect, kFrameRect, + kFrameRect, false, false, 1, SkBlendMode::kSrcOver, 0); + + auto* surface_quad_1 = pass1->CreateAndAppendDrawQuad<SurfaceDrawQuad>(); + surface_quad_1->SetNew( + pass1->shared_quad_state_list.back(), child_rect, child_rect, + SurfaceRange(child_surface_id1), SK_ColorWHITE, + /*stretch_content_to_fill_bounds=*/false, /*ignores_input_event=*/false); + + gfx::Rect child_rect2(400, 400, 100, 100); + auto* surface_quad_2 = pass1->CreateAndAppendDrawQuad<SurfaceDrawQuad>(); + surface_quad_2->SetNew( + pass1->shared_quad_state_list.back(), child_rect2, child_rect2, + SurfaceRange(child_surface_id2), SK_ColorWHITE, + /*stretch_content_to_fill_bounds=*/false, /*ignores_input_event=*/false); + + pass_list.push_back(std::move(pass1)); + + auto compositor_frame = CompositorFrameBuilder() + .SetRenderPassList(std::move(pass_list)) + .SetDeviceScaleFactor(2.f) + .Build(); + base::Optional<HitTestRegionList> hit_test_region_list = + hit_test_data_provider->GetHitTestData(compositor_frame); + + // Expect three hit-test regions, two from the first draw-quad and the other + // from the second draw-quad. + EXPECT_EQ(3u, hit_test_region_list->regions.size()); + EXPECT_EQ(child_surface_id1.frame_sink_id(), + hit_test_region_list->regions[0].frame_sink_id); + EXPECT_EQ(gfx::Rect(2, 2, 50, 50), hit_test_region_list->regions[0].rect); + EXPECT_EQ(child_surface_id1.frame_sink_id(), + hit_test_region_list->regions[1].frame_sink_id); + EXPECT_EQ(gfx::Rect(102, 2, 50, 50), hit_test_region_list->regions[1].rect); + EXPECT_EQ(child_surface_id2.frame_sink_id(), + hit_test_region_list->regions[2].frame_sink_id); + EXPECT_EQ(gfx::Rect(450, 400, 50, 100), + hit_test_region_list->regions[2].rect); + + // Build another CompositorFrame with device-scale-factor=0.5f. + auto pass2 = RenderPass::Create(); + pass2->SetNew(2, kFrameRect, kFrameRect, invertible_transform); + // Create a filter with a shapes included in surface_quad_3, in DIP space. + cc::FilterOperations filters2; + filters2.Append(cc::FilterOperation::CreateAlphaThresholdFilter( + {gfx::Rect(600, 200, 300, 300)}, 0.f, 0.f)); + pass2->filters = filters2; + auto* shared_state_2 = pass2->CreateAndAppendSharedQuadState(); + shared_state_2->SetAll(invertible_transform, kFrameRect, kFrameRect, + kFrameRect, false, false, 1, SkBlendMode::kSrcOver, 0); + + auto* surface_quad_3 = pass2->CreateAndAppendDrawQuad<SurfaceDrawQuad>(); + surface_quad_3->SetNew( + pass2->shared_quad_state_list.back(), child_rect, child_rect, + SurfaceRange(child_surface_id1), SK_ColorWHITE, + /*stretch_content_to_fill_bounds=*/false, /*ignores_input_event=*/false); + + pass_list.push_back(std::move(pass2)); + + auto compositor_frame_2 = CompositorFrameBuilder() + .SetRenderPassList(std::move(pass_list)) + .SetDeviceScaleFactor(.5f) + .Build(); + base::Optional<HitTestRegionList> hit_test_region_list_2 = + hit_test_data_provider->GetHitTestData(compositor_frame_2); + + // Expect one region included in surface_quad_3. + EXPECT_EQ(1u, hit_test_region_list_2->regions.size()); + EXPECT_EQ(child_surface_id1.frame_sink_id(), + hit_test_region_list_2->regions[0].frame_sink_id); + EXPECT_EQ(gfx::Rect(100, 0, 100, 100), + hit_test_region_list_2->regions[0].rect); +} + } // namespace viz
diff --git a/components/viz/common/hit_test/hit_test_data_builder.cc b/components/viz/common/hit_test/hit_test_data_builder.cc index 4751d12..91d30a5 100644 --- a/components/viz/common/hit_test/hit_test_data_builder.cc +++ b/components/viz/common/hit_test/hit_test_data_builder.cc
@@ -5,30 +5,13 @@ #include "components/viz/common/hit_test/hit_test_data_builder.h" #include "components/viz/common/quads/surface_draw_quad.h" +#include "ui/gfx/geometry/rect_conversions.h" namespace viz { +namespace { -// static -base::Optional<HitTestRegionList> HitTestDataBuilder::CreateHitTestData( - const CompositorFrame& compositor_frame, - bool root_accepts_events, - bool should_ask_for_child_region) { - base::Optional<HitTestRegionList> hit_test_region_list(base::in_place); - hit_test_region_list->flags = - (root_accepts_events ? HitTestRegionFlags::kHitTestMine - : HitTestRegionFlags::kHitTestIgnore) | - HitTestRegionFlags::kHitTestMouse | HitTestRegionFlags::kHitTestTouch; - hit_test_region_list->bounds.set_size(compositor_frame.size_in_pixels()); - AddHitTestDataFromRenderPass( - compositor_frame, compositor_frame.render_pass_list.back()->id, - &hit_test_region_list->regions, should_ask_for_child_region); - return hit_test_region_list; -} - -// static -const RenderPass* HitTestDataBuilder::GetRenderPassInFrame( - const CompositorFrame& frame, - RenderPassId render_pass_id) { +const RenderPass* GetRenderPassInFrame(const CompositorFrame& frame, + RenderPassId render_pass_id) { if (!render_pass_id) return frame.render_pass_list.back().get(); @@ -40,12 +23,65 @@ return nullptr; } -// static -void HitTestDataBuilder::AddHitTestDataFromRenderPass( - const CompositorFrame& frame, - RenderPassId render_pass_id, - std::vector<HitTestRegion>* regions, - bool should_ask_for_child_region) { +void AddHitTestRegion(const FrameSinkId& frame_sink_id, + const gfx::Rect& visible_rect, + const gfx::Transform& hit_test_region_transform, + std::vector<HitTestRegion>* regions, + bool should_ask_for_child_region) { + regions->emplace_back(); + HitTestRegion* hit_test_region = ®ions->back(); + hit_test_region->frame_sink_id = frame_sink_id; + hit_test_region->flags = HitTestRegionFlags::kHitTestMouse | + HitTestRegionFlags::kHitTestTouch | + HitTestRegionFlags::kHitTestChildSurface; + if (should_ask_for_child_region) { + hit_test_region->flags |= HitTestRegionFlags::kHitTestAsk; + hit_test_region->async_hit_test_reasons = + AsyncHitTestReasons::kUseDrawQuadData; + } + hit_test_region->rect = visible_rect; + hit_test_region->transform = hit_test_region_transform; +} + +std::vector<gfx::Rect> ExtractAlphaRects( + const cc::FilterOperations& filters, + const gfx::Rect& surface_quad_rect, + const gfx::Transform& quad_to_target_transform, + const gfx::Transform& target_to_quad_transform, + float device_scale_factor) { + std::vector<gfx::Rect> filter_regions; + if (filters.IsEmpty()) + return filter_regions; + + size_t i = 0; + for (i = 0; i < filters.size(); ++i) { + const cc::FilterOperation& op = filters.at(i); + if (op.type() == cc::FilterOperation::ALPHA_THRESHOLD) { + if (op.shape().empty()) + return filter_regions; + + for (const gfx::Rect& rect : op.shape()) { + gfx::RectF rect_in_pixels( + gfx::ScaleRect(gfx::RectF(rect), device_scale_factor)); + gfx::RectF surface_quad_rect_in_pass(surface_quad_rect); + quad_to_target_transform.TransformRect(&surface_quad_rect_in_pass); + if (surface_quad_rect_in_pass.Intersects(rect_in_pixels)) { + gfx::RectF visible_rect(surface_quad_rect_in_pass); + visible_rect.Intersect(rect_in_pixels); + target_to_quad_transform.TransformRect(&visible_rect); + filter_regions.push_back(gfx::ToNearestRect(visible_rect)); + } + } + return filter_regions; + } + } + return filter_regions; +} + +void AddHitTestDataFromRenderPass(const CompositorFrame& frame, + RenderPassId render_pass_id, + std::vector<HitTestRegion>* regions, + bool should_ask_for_child_region) { const RenderPass* render_pass = GetRenderPassInFrame(frame, render_pass_id); if (!render_pass) return; @@ -86,22 +122,24 @@ if (!quad_to_target_transform.GetInverse(&target_to_quad_transform)) { continue; } - - regions->emplace_back(); - HitTestRegion* hit_test_region = ®ions->back(); - hit_test_region->frame_sink_id = - surface_quad->surface_range.end().frame_sink_id(); - hit_test_region->flags = HitTestRegionFlags::kHitTestMouse | - HitTestRegionFlags::kHitTestTouch | - HitTestRegionFlags::kHitTestChildSurface; - if (should_ask_for_child_region) { - hit_test_region->flags |= HitTestRegionFlags::kHitTestAsk; - hit_test_region->async_hit_test_reasons = - AsyncHitTestReasons::kUseDrawQuadData; - } - hit_test_region->rect = surface_quad->rect; - hit_test_region->transform = + gfx::Transform hit_test_region_transform = target_to_quad_transform * transform_from_root_target; + + const auto& filters = render_pass->filters; + std::vector<gfx::Rect> filter_regions = ExtractAlphaRects( + filters, surface_quad->rect, quad_to_target_transform, + target_to_quad_transform, frame.device_scale_factor()); + if (filter_regions.empty()) { + AddHitTestRegion(surface_quad->surface_range.end().frame_sink_id(), + surface_quad->rect, hit_test_region_transform, regions, + should_ask_for_child_region); + } else { + for (const auto& filter_region : filter_regions) { + AddHitTestRegion(surface_quad->surface_range.end().frame_sink_id(), + filter_region, hit_test_region_transform, regions, + should_ask_for_child_region); + } + } } else if (quad->material == DrawQuad::RENDER_PASS) { const RenderPassDrawQuad* render_quad = RenderPassDrawQuad::MaterialCast(quad); @@ -111,4 +149,23 @@ } } +} // namespace + +// static +base::Optional<HitTestRegionList> HitTestDataBuilder::CreateHitTestData( + const CompositorFrame& compositor_frame, + bool root_accepts_events, + bool should_ask_for_child_region) { + base::Optional<HitTestRegionList> hit_test_region_list(base::in_place); + hit_test_region_list->flags = + (root_accepts_events ? HitTestRegionFlags::kHitTestMine + : HitTestRegionFlags::kHitTestIgnore) | + HitTestRegionFlags::kHitTestMouse | HitTestRegionFlags::kHitTestTouch; + hit_test_region_list->bounds.set_size(compositor_frame.size_in_pixels()); + AddHitTestDataFromRenderPass( + compositor_frame, compositor_frame.render_pass_list.back()->id, + &hit_test_region_list->regions, should_ask_for_child_region); + return hit_test_region_list; +} + } // namespace viz
diff --git a/components/viz/common/hit_test/hit_test_data_builder.h b/components/viz/common/hit_test/hit_test_data_builder.h index 526101e..5eea8d9 100644 --- a/components/viz/common/hit_test/hit_test_data_builder.h +++ b/components/viz/common/hit_test/hit_test_data_builder.h
@@ -23,14 +23,6 @@ bool should_ask_for_child_region); private: - static const RenderPass* GetRenderPassInFrame(const CompositorFrame& frame, - RenderPassId render_pass_id); - - static void AddHitTestDataFromRenderPass(const CompositorFrame& frame, - RenderPassId render_pass_id, - std::vector<HitTestRegion>* regions, - bool should_ask_for_child_region); - DISALLOW_COPY_AND_ASSIGN(HitTestDataBuilder); };
diff --git a/components/viz/host/hit_test/hit_test_query.cc b/components/viz/host/hit_test/hit_test_query.cc index 9d40b3f7..7e74fc7 100644 --- a/components/viz/host/hit_test/hit_test_query.cc +++ b/components/viz/host/hit_test/hit_test_query.cc
@@ -227,10 +227,6 @@ size_t child_region = region_index + 1; size_t child_region_end = child_region + region_child_count; gfx::PointF location_in_target = location_transformed; - if (!features::IsVizHitTestingSurfaceLayerEnabled() && - is_location_relative_to_parent) { - location_in_target -= hit_test_data_[region_index].rect.OffsetFromOrigin(); - } const uint32_t flags = hit_test_data_[region_index].flags; @@ -291,10 +287,6 @@ } hit_test_data_[region_index].transform().TransformPoint(location_in_target); - if (!features::IsVizHitTestingSurfaceLayerEnabled()) { - location_in_target->Offset(-hit_test_data_[region_index].rect.x(), - -hit_test_data_[region_index].rect.y()); - } if (!target_ancestor) return true; @@ -333,10 +325,6 @@ // found immediately. if (hit_test_data_[region_index].frame_sink_id == target) { *transform = hit_test_data_[region_index].transform(); - if (!features::IsVizHitTestingSurfaceLayerEnabled()) { - transform->Translate(-hit_test_data_[region_index].rect.x(), - -hit_test_data_[region_index].rect.y()); - } return true; } @@ -353,10 +341,6 @@ if (GetTransformToTargetRecursively(target, child_region, &transform_to_child)) { gfx::Transform region_transform(hit_test_data_[region_index].transform()); - if (!features::IsVizHitTestingSurfaceLayerEnabled()) { - region_transform.Translate(-hit_test_data_[region_index].rect.x(), - -hit_test_data_[region_index].rect.y()); - } *transform = transform_to_child * region_transform; return true; }
diff --git a/components/viz/host/hit_test/hit_test_query.h b/components/viz/host/hit_test/hit_test_query.h index df8e5da3..8261e31 100644 --- a/components/viz/host/hit_test/hit_test_query.h +++ b/components/viz/host/hit_test/hit_test_query.h
@@ -57,7 +57,9 @@ // 1. The list is in ascending (front to back) z-order. // 2. Children count includes children of children. // 3. After applying transform to the incoming point, point is in the same - // coordinate system as the bounds it is comparing against. + // coordinate system as the bounds it is comparing against. We shouldn't + // need to apply rect's origin offset as it should be included in this + // transform. // For example, // +e-------------+ // | +c---------|
diff --git a/components/viz/host/hit_test/hit_test_query_unittest.cc b/components/viz/host/hit_test/hit_test_query_unittest.cc index 1b62a21..29c876f 100644 --- a/components/viz/host/hit_test/hit_test_query_unittest.cc +++ b/components/viz/host/hit_test/hit_test_query_unittest.cc
@@ -361,12 +361,13 @@ gfx::Rect e_bounds_in_e = gfx::Rect(0, 0, 600, 600); gfx::Rect c_bounds_in_e = gfx::Rect(0, 0, 800, 800); gfx::Rect a_bounds_in_c = gfx::Rect(0, 0, 200, 100); - gfx::Rect b_bounds_in_c = gfx::Rect(0, 100, 800, 600); + gfx::Rect b_bounds_in_c = gfx::Rect(0, 0, 800, 600); gfx::Rect d_bounds_in_e = gfx::Rect(0, 0, 800, 800); gfx::Transform transform_e_to_e, transform_e_to_c, transform_c_to_a, transform_c_to_b, transform_e_to_d; transform_e_to_c.Translate(-200, -100); transform_e_to_d.Translate(-400, -50); + transform_c_to_b.Translate(0, -100); active_data_.push_back(AggregatedHitTestRegion( e_id, HitTestRegionFlags::kHitTestMine | HitTestRegionFlags::kHitTestMouse, @@ -1097,14 +1098,15 @@ FrameSinkId b_id = FrameSinkId(4, 4); FrameSinkId d_id = FrameSinkId(5, 5); gfx::Rect e_bounds_in_e = gfx::Rect(0, 0, 600, 600); - gfx::Rect c_bounds_in_e = gfx::Rect(0, 50, 800, 800); + gfx::Rect c_bounds_in_e = gfx::Rect(0, 0, 800, 800); gfx::Rect a_bounds_in_c = gfx::Rect(0, 0, 200, 100); - gfx::Rect b_bounds_in_c = gfx::Rect(0, 100, 800, 600); + gfx::Rect b_bounds_in_c = gfx::Rect(0, 0, 800, 600); gfx::Rect d_bounds_in_e = gfx::Rect(0, 0, 800, 800); gfx::Transform transform_e_to_e, transform_e_to_c, transform_c_to_a, transform_c_to_b, transform_e_to_d; - transform_e_to_c.Translate(-200, -100); + transform_e_to_c.Translate(-200, -150); transform_e_to_d.Translate(-400, -50); + transform_c_to_b.Translate(0, -100); transform_c_to_b.Skew(2, 3); transform_c_to_b.Scale(.5f, .7f); active_data_.push_back(AggregatedHitTestRegion( @@ -1150,7 +1152,6 @@ gfx::Transform transform_to_b; gfx::Transform expected_transform_to_b; expected_transform_to_b.Translate(-200, -150); - expected_transform_to_b.Translate(0, -100); expected_transform_to_b.ConcatTransform(transform_c_to_b); EXPECT_TRUE(hit_test_query().GetTransformToTarget(b_id, &transform_to_b)); // Use ToString so that we can compare float.
diff --git a/components/viz/host/host_gpu_memory_buffer_manager_unittest.cc b/components/viz/host/host_gpu_memory_buffer_manager_unittest.cc index d91186c..5f5c092 100644 --- a/components/viz/host/host_gpu_memory_buffer_manager_unittest.cc +++ b/components/viz/host/host_gpu_memory_buffer_manager_unittest.cc
@@ -21,6 +21,10 @@ #include "ui/ozone/public/ozone_platform.h" #endif +#if defined(OS_ANDROID) +#include "base/android/android_hardware_buffer_compat.h" +#endif + namespace viz { namespace { @@ -210,6 +214,9 @@ native_pixmap_supported = ui::OzonePlatform::GetInstance()->IsNativePixmapConfigSupported( gfx::BufferFormat::RGBA_8888, gfx::BufferUsage::GPU_READ); +#elif defined(OS_ANDROID) + native_pixmap_supported = + base::AndroidHardwareBufferCompat::IsSupportAvailable(); #elif defined(OS_MACOSX) || defined(OS_WIN) native_pixmap_supported = true; #endif
diff --git a/components/viz/service/hit_test/hit_test_aggregator.cc b/components/viz/service/hit_test/hit_test_aggregator.cc index 8475646..ed7a0c3 100644 --- a/components/viz/service/hit_test/hit_test_aggregator.cc +++ b/components/viz/service/hit_test/hit_test_aggregator.cc
@@ -64,7 +64,6 @@ aggregate_timer.Elapsed(), base::TimeDelta::FromMicroseconds(1), base::TimeDelta::FromSeconds(10), 50); - referenced_child_regions_.clear(); SendHitTestData(); if (hit_test_debug_ && render_passes) { @@ -180,6 +179,7 @@ trace_id ? TRACE_EVENT_FLAG_FLOW_IN : TRACE_EVENT_FLAG_NONE, "step", "AggregateHitTestData(Root)"); + DCHECK(referenced_child_regions_.empty()); referenced_child_regions_.insert(surface_id.frame_sink_id()); size_t region_index = 1; @@ -187,7 +187,9 @@ if (region_index >= hit_test_data_capacity_ - 1) break; region_index = AppendRegion(region_index, region); + DCHECK_EQ(referenced_child_regions_.size(), 1u); } + referenced_child_regions_.erase(referenced_child_regions_.begin()); DCHECK_GE(region_index, 1u); int32_t child_count = region_index - 1; @@ -269,6 +271,7 @@ break; } } + referenced_child_regions_.erase(region.frame_sink_id); } DCHECK_GE(region_index - parent_index - 1, 0u); int32_t child_count = region_index - parent_index - 1;
diff --git a/components/viz/service/hit_test/hit_test_aggregator.h b/components/viz/service/hit_test/hit_test_aggregator.h index 2b53f958..3d09c668 100644 --- a/components/viz/service/hit_test/hit_test_aggregator.h +++ b/components/viz/service/hit_test/hit_test_aggregator.h
@@ -95,8 +95,10 @@ bool hit_test_debug_ = false; uint32_t hit_test_debug_ask_regions_ = 0; - // This is the set of FrameSinkIds referenced in the aggregation so far, used - // to detect cycles. + // This is the set of FrameSinkIds referenced in the aggregation in this tree + // chain so far, used to detect cycles. We can have regions that have the + // same FrameSinkId, e.g. when ALPHA_SHAPE is set in cc::FilterOperations, + // but only at the same hierarchy level. base::flat_set<FrameSinkId> referenced_child_regions_; base::flat_map<FrameSinkId, uint64_t> last_active_frame_index_;
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index cb2213e..b395884 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -175,9 +175,6 @@ const base::Feature kFreezeFramesOnVisibility{ "FreezeFramesOnVisibility", base::FEATURE_DISABLED_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}; @@ -421,6 +418,7 @@ // Service worker based payment apps as defined by w3c here: // https://w3c.github.io/webpayments-payment-apps-api/ +// TODO(rouslan): Remove this. const base::Feature kServiceWorkerPaymentApps{"ServiceWorkerPaymentApps", base::FEATURE_ENABLED_BY_DEFAULT}; @@ -592,6 +590,7 @@ "ExperimentalProductivityFeatures", base::FEATURE_DISABLED_BY_DEFAULT}; // The JavaScript API for payments on the web. +// TODO(rouslan): Remove this. const base::Feature kWebPayments{"WebPayments", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index 9a957af..e09913c 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -50,7 +50,6 @@ CONTENT_EXPORT extern const base::Feature kFramebustingNeedsSameOriginOrUserGesture; CONTENT_EXPORT extern const base::Feature kFreezeFramesOnVisibility; -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/test/render_view_test.cc b/content/public/test/render_view_test.cc index 1e5072f3..1ad0452 100644 --- a/content/public/test/render_view_test.cc +++ b/content/public/test/render_view_test.cc
@@ -172,10 +172,8 @@ } RenderViewTest::RenderViewTest() { - // Overrides creation of RenderFrameImpl, but does not need to - // override behaviour of WebWidgetClient. - RenderFrameImpl::InstallCreateHook(&TestRenderFrame::CreateTestRenderFrame, - nullptr, nullptr); + // Overrides creation of RenderFrameImpl. + RenderFrameImpl::InstallCreateHook(&TestRenderFrame::CreateTestRenderFrame); } RenderViewTest::~RenderViewTest() {
diff --git a/content/public/test/web_test_support.h b/content/public/test/web_test_support.h index 0a644b93..282725e7 100644 --- a/content/public/test/web_test_support.h +++ b/content/public/test/web_test_support.h
@@ -30,9 +30,9 @@ } namespace test_runner { -class WebFrameTestProxyBase; -class WebViewTestProxyBase; -class WebWidgetTestProxyBase; +class WebFrameTestProxy; +class WebViewTestProxy; +class WebWidgetTestProxy; } // namespace test_runner namespace content { @@ -56,22 +56,15 @@ // Turn a renderer into web test mode. void EnableRendererWebTestMode(); -// "Casts" |render_view| to |WebViewTestProxyBase|. Caller has to ensure that +// "Casts" |render_view| to |WebViewTestProxy|. Caller has to ensure that // prior to construction of |render_view|, EnableWebTestProxyCreation was // called. -test_runner::WebViewTestProxyBase* GetWebViewTestProxyBase( - RenderView* render_view); +test_runner::WebViewTestProxy* GetWebViewTestProxy(RenderView* render_view); -// "Casts" |render_frame| to |WebFrameTestProxyBase|. Caller has to ensure -// that prior to construction of |render_frame|, EnableTestProxyCreation -// was called. -test_runner::WebFrameTestProxyBase* GetWebFrameTestProxyBase( - RenderFrame* render_frame); - -// Gets WebWidgetTestProxyBase associated with |frame| (either the view's widget +// Gets WebWidgetTestProxy associated with |frame| (either the view's widget // or the local root's frame widget). Caller has to ensure that prior to -// construction of |render_frame|, EnableTestProxyCreation was called. -test_runner::WebWidgetTestProxyBase* GetWebWidgetTestProxyBase( +// construction of |render_frame|, EnableWebTestProxyCreation was called. +test_runner::WebWidgetTestProxy* GetWebWidgetTestProxy( blink::WebLocalFrame* frame); // Enable injecting of a WebViewTestProxy between WebViews and RenderViews, @@ -102,11 +95,11 @@ float GetWindowToViewportScale(RenderView* render_view); // Converts |event| from screen coordinates to coordinates used by the widget -// associated with the |web_widget_test_proxy_base|. Returns nullptr if no +// associated with the |web_widget_test_proxy|. Returns nullptr if no // transformation was necessary (e.g. for a keyboard event OR if widget requires // no scaling and has coordinates starting at (0,0)). std::unique_ptr<blink::WebInputEvent> TransformScreenToWidgetCoordinates( - test_runner::WebWidgetTestProxyBase* web_widget_test_proxy_base, + test_runner::WebWidgetTestProxy* web_widget_test_proxy, const blink::WebInputEvent& event); // Get the color space for a given name string. This is not in the ColorSpace
diff --git a/content/renderer/java/OWNERS b/content/renderer/java/OWNERS index 0cebb68..ce79cad 100644 --- a/content/renderer/java/OWNERS +++ b/content/renderer/java/OWNERS
@@ -1,2 +1,2 @@ -mnaganov@chromium.org +michaelbai@chromium.org torne@chromium.org
diff --git a/content/renderer/media/webrtc/rtc_peer_connection_handler.cc b/content/renderer/media/webrtc/rtc_peer_connection_handler.cc index 8d756195..2d43471 100644 --- a/content/renderer/media/webrtc/rtc_peer_connection_handler.cc +++ b/content/renderer/media/webrtc/rtc_peer_connection_handler.cc
@@ -602,6 +602,17 @@ : MediaStreamTrackMetrics::Kind::kVideo; } +bool IsHostnameCandidate(const blink::WebRTCICECandidate& candidate) { + // Currently the legitimate hostname candidates have only the .local + // top-level domain, which are gathered when the mDNS concealment of local + // IPs is enabled. + const char kLocalTld[] = ".local"; + if (!candidate.Address().ContainsOnlyASCII()) + return false; + return base::EndsWith(candidate.Address().Ascii(), kLocalTld, + base::CompareCase::INSENSITIVE_ASCII); +} + } // namespace // Implementation of LocalRTCStatsRequest. @@ -2245,7 +2256,7 @@ ++num_local_candidates_ipv4_; } else if (address_family == AF_INET6) { ++num_local_candidates_ipv6_; - } else { + } else if (!IsHostnameCandidate(*web_candidate)) { NOTREACHED(); } }
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index 79b954f..1c25f22 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -583,10 +583,6 @@ RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl = nullptr; -RenderFrameImpl::CreateRenderWidgetForChildLocalRootFunction - g_create_render_widget = nullptr; -RenderFrameImpl::RenderWidgetForChildLocalRootInitializedCallback - g_render_widget_initialized = nullptr; WebString ConvertRelativePathToHtmlAttribute(const base::FilePath& path) { DCHECK(!path.IsAbsolute()); @@ -1535,23 +1531,11 @@ // Makes a new RenderWidget for the child local root. It provides the // local root with a new compositing, painting, and input coordinate // space/context. - scoped_refptr<RenderWidget> render_widget; - if (g_create_render_widget) { - // Web test hooks inject a different type (subclass) for RenderWidget, - // allowing it to override the behaviour of the WebWidgetClient which - // RenderWidget provides. - render_widget = g_create_render_widget( - widget_params.routing_id, compositor_deps, - screen_info_from_main_frame, blink::kWebDisplayModeUndefined, - /*is_frozen=*/false, widget_params.hidden, - /*never_visible=*/false); - } else { - render_widget = base::MakeRefCounted<RenderWidget>( - widget_params.routing_id, compositor_deps, - screen_info_from_main_frame, blink::kWebDisplayModeUndefined, - /*is_frozen=*/false, widget_params.hidden, - /*never_visible=*/false); - } + scoped_refptr<RenderWidget> render_widget = RenderWidget::CreateForFrame( + widget_params.routing_id, compositor_deps, screen_info_from_main_frame, + blink::kWebDisplayModeUndefined, + /*is_frozen=*/false, widget_params.hidden, + /*never_visible=*/false, /*widget_request=*/nullptr); // Non-owning pointer that is self-referencing and destroyed by calling // Close(). We use the new RenderWidget as the client for this @@ -1570,10 +1554,6 @@ // pulling the device scale factor off the WebView itself. render_widget->UpdateWebViewWithDeviceScaleFactor(); - // Web test hooks to set up the injected type for RenderWidget. - if (g_render_widget_initialized) - g_render_widget_initialized(render_widget.get()); - render_frame->render_widget_ = std::move(render_widget); } @@ -1618,15 +1598,9 @@ // static void RenderFrameImpl::InstallCreateHook( - CreateRenderFrameImplFunction create_frame, - CreateRenderWidgetForChildLocalRootFunction create_widget, - RenderWidgetForChildLocalRootInitializedCallback widget_initialized) { + CreateRenderFrameImplFunction create_frame) { DCHECK(!g_create_render_frame_impl); - DCHECK(!g_create_render_widget); - DCHECK(!g_render_widget_initialized); g_create_render_frame_impl = create_frame; - g_create_render_widget = create_widget; - g_render_widget_initialized = widget_initialized; } // static
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index 75a649b..eb842be2 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -275,24 +275,10 @@ }; using CreateRenderFrameImplFunction = RenderFrameImpl* (*)(CreateParams); - using CreateRenderWidgetForChildLocalRootFunction = - RenderWidget* (*)(int32_t, - CompositorDependencies*, - const ScreenInfo&, - blink::WebDisplayMode display_mode, - bool, - bool, - bool); - using RenderWidgetForChildLocalRootInitializedCallback = - void (*)(RenderWidget*); - // Web tests override the creation of RenderFrames and RenderWidgets in - // order to inject their own (subclass) type and change behaviour inside the - // tests. - static void InstallCreateHook( - CreateRenderFrameImplFunction create_frame, - CreateRenderWidgetForChildLocalRootFunction create_widget, - RenderWidgetForChildLocalRootInitializedCallback widget_initialized); + // Web tests override the creation of RenderFrames in order to inject a + // partial testing fake. + static void InstallCreateHook(CreateRenderFrameImplFunction create_frame); // Looks up and returns the WebFrame corresponding to a given opener frame // routing ID.
diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc index 35759ddd..72b2236 100644 --- a/content/renderer/render_thread_impl.cc +++ b/content/renderer/render_thread_impl.cc
@@ -1733,16 +1733,6 @@ 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 7b0b08e1..7ce1d9f 100644 --- a/content/renderer/render_thread_impl.h +++ b/content/renderer/render_thread_impl.h
@@ -480,8 +480,6 @@ blink::mojom::StoragePartitionService* GetStoragePartitionService(); mojom::RendererHost* GetRendererHost(); - void RequestPurgeMemory(); - struct RendererMemoryMetrics { size_t partition_alloc_kb; size_t blink_gc_kb;
diff --git a/content/renderer/render_thread_impl_browsertest.cc b/content/renderer/render_thread_impl_browsertest.cc index c4970c9c..16836320 100644 --- a/content/renderer/render_thread_impl_browsertest.cc +++ b/content/renderer/render_thread_impl_browsertest.cc
@@ -17,14 +17,12 @@ #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" #include "base/strings/string_number_conversions.h" #include "base/task/post_task.h" #include "base/task/task_scheduler/task_scheduler.h" -#include "base/test/scoped_feature_list.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_task_runner_handle.h" #include "content/app/mojo/mojo_init.h" @@ -239,28 +237,6 @@ 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_; @@ -281,13 +257,9 @@ 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); }; @@ -318,79 +290,6 @@ 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 89983ab..ad39308 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -464,14 +464,21 @@ RenderViewImpl::RenderViewImpl(CompositorDependencies* compositor_deps, const mojom::CreateViewParams& params) - : render_widget_(new RenderWidget( - params.main_frame_widget_routing_id, - compositor_deps, - params.visual_properties.screen_info, - params.visual_properties.display_mode, - /*is_frozen=*/params.main_frame_routing_id == MSG_ROUTING_NONE, - params.hidden, - params.never_visible)), + : render_widget_([compositor_deps, ¶ms] { + // TODO(https://crbug.com/545684): This is a transitor hack + // until the creation of RenderWidget is taken out of the constructor. + auto render_widget = RenderWidget::CreateForFrame( + params.main_frame_widget_routing_id, compositor_deps, + params.visual_properties.screen_info, + params.visual_properties.display_mode, + /*is_frozen=*/params.main_frame_routing_id == MSG_ROUTING_NONE, + params.hidden, params.never_visible, + /*widget_request=*/nullptr); + // The lifetime |render_widget_| is handled manually for the + // mainframe widget. The matching Release() is in Initialize(). + render_widget->AddRef(); + return render_widget.get(); + }()), routing_id_(params.view_id), renderer_wide_named_frame_lookup_( params.renderer_wide_named_frame_lookup), @@ -507,7 +514,14 @@ webview_ = WebView::Create(this, params->hidden, /*compositing_enabled=*/true, opener_frame ? opener_frame->View() : nullptr); + + // The GetWidget->Init() call causes an AddRef() to itself meaning that + // IPC system has taken conceptual ownership of the object. RenderView + // can and must now manually Release() the RenderWidget to balance out the + // extra refcount it had been using to preserve the RenderWidget from + // construction to initialization. GetWidget()->Init(std::move(show_callback), webview_->MainFrameWidget()); + GetWidget()->Release(); g_view_map.Get().insert(std::make_pair(webview(), this)); g_routing_id_view_map.Get().insert(std::make_pair(GetRoutingID(), this)); @@ -1092,6 +1106,10 @@ g_view_map.Get().erase(webview_); webview_ = nullptr; g_routing_id_view_map.Get().erase(GetRoutingID()); + + // The |render_widget_| is deleted after DidCloseWidget() returns. Drop the + // reference to it to avoid a UaF. + render_widget_ = nullptr; } void RenderViewImpl::CancelPagePopupForWidget() { @@ -1454,7 +1472,7 @@ // RenderWidget for the frame making the popup. RenderWidget* view_render_widget = GetWidget(); - auto popup_widget = base::MakeRefCounted<RenderWidget>( + auto popup_widget = RenderWidget::CreateForPopup( widget_routing_id, view_render_widget->compositor_deps(), view_render_widget->screen_info(), blink::kWebDisplayModeUndefined, /*is_frozen=*/false,
diff --git a/content/renderer/render_view_impl.h b/content/renderer/render_view_impl.h index e454434c..354194f 100644 --- a/content/renderer/render_view_impl.h +++ b/content/renderer/render_view_impl.h
@@ -520,6 +520,15 @@ // it in the same order in the .cc file as it was in the header. // --------------------------------------------------------------------------- + // This is the |render_widget_| for the main frame. Its lifetime is controlled + // via IPC messages to RenderWidget (see WidgetMsg_Close). RenderView + // holds a weak reference to this object and relies on + // RenderWidgetDelegate::DidCloseWidget() to avoid UaF. + // + // Instances of RenderWidget for child frame local roots, popups, and + // fullscreen widgets are never contained by this pointer. Child frame + // local roots are owned by a RenderFrame. The others are owned by the IPC + // system. RenderWidget* render_widget_; // Routing ID that allows us to communicate with the corresponding
diff --git a/content/renderer/render_widget.cc b/content/renderer/render_widget.cc index 270f8c5..6e9192e 100644 --- a/content/renderer/render_widget.cc +++ b/content/renderer/render_widget.cc
@@ -169,6 +169,9 @@ namespace { +RenderWidget::CreateRenderWidgetFunction g_create_render_widget_for_frame = + nullptr; + using RoutingIDWidgetMap = std::map<int32_t, RenderWidget*>; base::LazyInstance<RoutingIDWidgetMap>::Leaky g_routing_id_widget_map = LAZY_INSTANCE_INITIALIZER; @@ -389,6 +392,46 @@ // RenderWidget --------------------------------------------------------------- +// static +void RenderWidget::InstallCreateForFrameHook( + CreateRenderWidgetFunction create_widget) { + g_create_render_widget_for_frame = create_widget; +} + +scoped_refptr<RenderWidget> RenderWidget::CreateForFrame( + int32_t widget_routing_id, + CompositorDependencies* compositor_deps, + const ScreenInfo& screen_info, + blink::WebDisplayMode display_mode, + bool is_frozen, + bool hidden, + bool never_visible, + mojom::WidgetRequest widget_request) { + if (g_create_render_widget_for_frame) { + return g_create_render_widget_for_frame( + widget_routing_id, compositor_deps, screen_info, display_mode, + is_frozen, hidden, never_visible, std::move(widget_request)); + } + + return base::WrapRefCounted(new RenderWidget( + widget_routing_id, compositor_deps, screen_info, display_mode, is_frozen, + hidden, never_visible, std::move(widget_request))); +} + +scoped_refptr<RenderWidget> RenderWidget::CreateForPopup( + int32_t widget_routing_id, + CompositorDependencies* compositor_deps, + const ScreenInfo& screen_info, + blink::WebDisplayMode display_mode, + bool is_frozen, + bool hidden, + bool never_visible, + mojom::WidgetRequest widget_request) { + return base::WrapRefCounted(new RenderWidget( + widget_routing_id, compositor_deps, screen_info, display_mode, is_frozen, + hidden, never_visible, std::move(widget_request))); +} + RenderWidget::RenderWidget(int32_t widget_routing_id, CompositorDependencies* compositor_deps, const ScreenInfo& screen_info, @@ -706,6 +749,15 @@ // If there is a Send call on the stack, then it could be dangerous to close // now. Post a task that only gets invoked when there are no nested message // loops. + // + // The asynchronous Close() takes an owning reference to |this| keeping the + // object alive beyond the Release() below. It is the last reference to this + // object. + // + // TODO(https://crbug.com/545684): The actual lifetime for RenderWidget + // seems to be single-owner. It is either owned by "IPC" events (popup, + // mainframe, and fullscreen), or a RenderFrame. If Close() self-deleting, + // all the ref-counting mess could be removed. GetCleanupTaskRunner()->PostNonNestableTask( FROM_HERE, base::BindOnce(&RenderWidget::Close, this));
diff --git a/content/renderer/render_widget.h b/content/renderer/render_widget.h index 888a92f..7bed745 100644 --- a/content/renderer/render_widget.h +++ b/content/renderer/render_widget.h
@@ -158,22 +158,51 @@ TTFAP_5MIN_AFTER_BACKGROUNDED, }; - // An Init*() method must be called after creating a RenderWidget, which will - // make the RenderWidget self-referencing. Then it can be deleted by calling - // Close(). - RenderWidget(int32_t widget_routing_id, - CompositorDependencies* compositor_deps, - const ScreenInfo& screen_info, - blink::WebDisplayMode display_mode, - bool is_frozen, - bool hidden, - bool never_visible, - mojom::WidgetRequest widget_request = nullptr); + // Convenience type for creation method taken by InstallCreateForFrameHook(). + // The method signature matches the RenderWidget constructor. + using CreateRenderWidgetFunction = + scoped_refptr<RenderWidget> (*)(int32_t, + CompositorDependencies*, + const ScreenInfo&, + blink::WebDisplayMode display_mode, + bool, + bool, + bool, + mojom::WidgetRequest widget_request); + // Overrides the implementation of CreateForFrame() function below. Used by + // web tests to return a partial fake of RenderWidget. + static void InstallCreateForFrameHook( + CreateRenderWidgetFunction create_widget); + + // Creates a RenderWidget that is meant to be associated with a RenderFrame. + // Testing infrastructure, such as test_runner, can override this function + // by calling InstallCreateForFrameHook(). + static scoped_refptr<RenderWidget> CreateForFrame( + int32_t widget_routing_id, + CompositorDependencies* compositor_deps, + const ScreenInfo& screen_info, + blink::WebDisplayMode display_mode, + bool is_frozen, + bool hidden, + bool never_visible, + mojom::WidgetRequest widget_request); + + // Creates a RenderWidget for a popup. This is separate from CreateForFrame() + // because popups do not not need to be faked out. + static scoped_refptr<RenderWidget> CreateForPopup( + int32_t widget_routing_id, + CompositorDependencies* compositor_deps, + const ScreenInfo& screen_info, + blink::WebDisplayMode display_mode, + bool is_frozen, + bool hidden, + bool never_visible, + mojom::WidgetRequest widget_request); // Initialize a new RenderWidget for a popup. The |show_callback| is called // when RenderWidget::Show() happens. This method increments the reference - // count on the RenderWidget, making it self-referencing, which can be - // released by calling Close(). + // count on the RenderWidget, making it self-referencing, which is then + // release when a WidgetMsg_Close IPC is received. void InitForPopup(ShowCallback show_callback, blink::WebPagePopup* web_page_popup); @@ -582,6 +611,17 @@ base::WeakPtr<RenderWidget> AsWeakPtr(); protected: + // An Init*() method must be called after creating a RenderWidget, which will + // make the RenderWidget self-referencing. Then it can be deleted by calling + // by calling OnClose(). + RenderWidget(int32_t widget_routing_id, + CompositorDependencies* compositor_deps, + const ScreenInfo& screen_info, + blink::WebDisplayMode display_mode, + bool is_frozen, + bool hidden, + bool never_visible, + mojom::WidgetRequest widget_request); ~RenderWidget() override; // Close the underlying WebWidget and stop the compositor.
diff --git a/content/renderer/render_widget_unittest.cc b/content/renderer/render_widget_unittest.cc index 513c293d..16be558 100644 --- a/content/renderer/render_widget_unittest.cc +++ b/content/renderer/render_widget_unittest.cc
@@ -172,7 +172,8 @@ blink::kWebDisplayModeUndefined, false, false, - false), + false, + nullptr), always_overscroll_(false) { InitForPopup(base::NullCallback(), &mock_page_popup_); @@ -447,7 +448,8 @@ blink::kWebDisplayModeUndefined, false, false, - false) { + false, + nullptr) { InitForPopup(RenderWidget::ShowCallback(), &stub_page_popup_); }
diff --git a/content/renderer/renderer_blink_platform_impl.cc b/content/renderer/renderer_blink_platform_impl.cc index 6fa35ba6..a1538e5 100644 --- a/content/renderer/renderer_blink_platform_impl.cc +++ b/content/renderer/renderer_blink_platform_impl.cc
@@ -1069,18 +1069,6 @@ } //------------------------------------------------------------------------------ -void RendererBlinkPlatformImpl::RequestPurgeMemory() { - auto* render_thread = RenderThreadImpl::current(); - // RenderThreadImpl is null in some tests. - if (!render_thread) - return; - render_thread->RequestPurgeMemory(); -} - -void RendererBlinkPlatformImpl::SetMemoryPressureNotificationsSuppressed( - bool suppressed) { - base::MemoryPressureListener::SetNotificationsSuppressed(suppressed); -} void RendererBlinkPlatformImpl::InitializeWebDatabaseHostIfNeeded() { if (!web_database_host_) {
diff --git a/content/renderer/renderer_blink_platform_impl.h b/content/renderer/renderer_blink_platform_impl.h index e3d39d7..38ff3be 100644 --- a/content/renderer/renderer_blink_platform_impl.h +++ b/content/renderer/renderer_blink_platform_impl.h
@@ -234,8 +234,6 @@ scoped_refptr<network::SharedURLLoaderFactory> factory) override; std::unique_ptr<blink::WebDataConsumerHandle> CreateDataConsumerHandle( mojo::ScopedDataPipeConsumerHandle handle) override; - void RequestPurgeMemory() override; - void SetMemoryPressureNotificationsSuppressed(bool suppressed) override; // Returns non-null. // It is invalid to call this in an incomplete env where
diff --git a/content/shell/renderer/web_test/blink_test_runner.cc b/content/shell/renderer/web_test/blink_test_runner.cc index 2ac4a761..838d015 100644 --- a/content/shell/renderer/web_test/blink_test_runner.cc +++ b/content/shell/renderer/web_test/blink_test_runner.cc
@@ -325,15 +325,15 @@ std::unique_ptr<blink::WebInputEvent> BlinkTestRunner::TransformScreenToWidgetCoordinates( - test_runner::WebWidgetTestProxyBase* web_widget_test_proxy_base, + test_runner::WebWidgetTestProxy* web_widget_test_proxy, const blink::WebInputEvent& event) { - return content::TransformScreenToWidgetCoordinates(web_widget_test_proxy_base, + return content::TransformScreenToWidgetCoordinates(web_widget_test_proxy, event); } -test_runner::WebWidgetTestProxyBase* BlinkTestRunner::GetWebWidgetTestProxyBase( +test_runner::WebWidgetTestProxy* BlinkTestRunner::GetWebWidgetTestProxy( blink::WebLocalFrame* frame) { - return content::GetWebWidgetTestProxyBase(frame); + return content::GetWebWidgetTestProxy(frame); } void BlinkTestRunner::EnableUseZoomForDSF() {
diff --git a/content/shell/renderer/web_test/blink_test_runner.h b/content/shell/renderer/web_test/blink_test_runner.h index 392ca7b1..d97628db 100644 --- a/content/shell/renderer/web_test/blink_test_runner.h +++ b/content/shell/renderer/web_test/blink_test_runner.h
@@ -95,9 +95,9 @@ void SetDeviceColorSpace(const std::string& name) override; float GetWindowToViewportScale() override; std::unique_ptr<blink::WebInputEvent> TransformScreenToWidgetCoordinates( - test_runner::WebWidgetTestProxyBase* web_widget_test_proxy_base, + test_runner::WebWidgetTestProxy* web_widget_test_proxy, const blink::WebInputEvent& event) override; - test_runner::WebWidgetTestProxyBase* GetWebWidgetTestProxyBase( + test_runner::WebWidgetTestProxy* GetWebWidgetTestProxy( blink::WebLocalFrame* frame) override; void EnableUseZoomForDSF() override; bool IsUseZoomForDSFEnabled() override;
diff --git a/content/shell/renderer/web_test/web_test_content_renderer_client.cc b/content/shell/renderer/web_test/web_test_content_renderer_client.cc index d5046e21..150d86c8 100644 --- a/content/shell/renderer/web_test/web_test_content_renderer_client.cc +++ b/content/shell/renderer/web_test/web_test_content_renderer_client.cc
@@ -72,23 +72,16 @@ void WebTestContentRendererClient::RenderFrameCreated( RenderFrame* render_frame) { - test_runner::WebFrameTestProxyBase* frame_proxy = - GetWebFrameTestProxyBase(render_frame); - frame_proxy->set_web_frame(render_frame->GetWebFrame()); new WebTestRenderFrameObserver(render_frame); } void WebTestContentRendererClient::RenderViewCreated(RenderView* render_view) { new ShellRenderViewObserver(render_view); - test_runner::WebViewTestProxyBase* proxy = - GetWebViewTestProxyBase(render_view); - proxy->set_web_view(render_view->GetWebView()); - // TODO(lfg): We should fix the TestProxy to track the WebWidgets on every - // local root in WebFrameTestProxy instead of having only the WebWidget for - // the main frame in WebViewTestProxy. - proxy->web_widget_test_proxy_base()->set_web_widget( - render_view->GetWebView()->MainFrameWidget()); + // TODO(https://crbug.com/545684): Does this function need to exist? Can + // this all just be in the CreateWebViewTestProxy() or does + // RenderViewCreated() get manually invoked by the test runner? + test_runner::WebViewTestProxy* proxy = GetWebViewTestProxy(render_view); proxy->Reset(); BlinkTestRunner* test_runner = BlinkTestRunner::Get(render_view);
diff --git a/content/shell/test_runner/BUILD.gn b/content/shell/test_runner/BUILD.gn index 280d2fa..0ba658a6 100644 --- a/content/shell/test_runner/BUILD.gn +++ b/content/shell/test_runner/BUILD.gn
@@ -78,12 +78,8 @@ "web_test_runner.h", "web_test_runtime_flags.cc", "web_test_runtime_flags.h", - "web_view_test_client.cc", - "web_view_test_client.h", "web_view_test_proxy.cc", "web_view_test_proxy.h", - "web_widget_test_client.cc", - "web_widget_test_client.h", "web_widget_test_proxy.cc", "web_widget_test_proxy.h", ]
diff --git a/content/shell/test_runner/accessibility_controller.cc b/content/shell/test_runner/accessibility_controller.cc index b7df52f..3957b4a 100644 --- a/content/shell/test_runner/accessibility_controller.cc +++ b/content/shell/test_runner/accessibility_controller.cc
@@ -137,9 +137,9 @@ } AccessibilityController::AccessibilityController( - WebViewTestProxyBase* web_view_test_proxy_base) + WebViewTestProxy* web_view_test_proxy) : log_accessibility_events_(false), - web_view_test_proxy_base_(web_view_test_proxy_base), + web_view_test_proxy_(web_view_test_proxy), weak_factory_(this) {} AccessibilityController::~AccessibilityController() {} @@ -277,7 +277,7 @@ } blink::WebView* AccessibilityController::web_view() { - return web_view_test_proxy_base_->web_view(); + return web_view_test_proxy_->webview(); } blink::WebAXObject
diff --git a/content/shell/test_runner/accessibility_controller.h b/content/shell/test_runner/accessibility_controller.h index cb78aa1a..9a74baea 100644 --- a/content/shell/test_runner/accessibility_controller.h +++ b/content/shell/test_runner/accessibility_controller.h
@@ -9,6 +9,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "content/shell/test_runner/test_runner_export.h" #include "content/shell/test_runner/web_ax_object_proxy.h" #include "third_party/blink/public/web/web_ax_object.h" #include "v8/include/v8.h" @@ -22,12 +23,11 @@ namespace test_runner { -class WebViewTestProxyBase; +class WebViewTestProxy; -class AccessibilityController { +class TEST_RUNNER_EXPORT AccessibilityController { public: - explicit AccessibilityController( - WebViewTestProxyBase* web_view_test_proxy_base); + explicit AccessibilityController(WebViewTestProxy* web_view_test_proxy); ~AccessibilityController(); void Reset(); @@ -61,7 +61,7 @@ v8::Persistent<v8::Function> notification_callback_; blink::WebView* web_view(); - WebViewTestProxyBase* web_view_test_proxy_base_; + WebViewTestProxy* web_view_test_proxy_; std::unique_ptr<blink::WebAXContext> ax_context_;
diff --git a/content/shell/test_runner/event_sender.cc b/content/shell/test_runner/event_sender.cc index b38e956..0f62861 100644 --- a/content/shell/test_runner/event_sender.cc +++ b/content/shell/test_runner/event_sender.cc
@@ -1314,8 +1314,8 @@ milliseconds(0), modifiers(0) {} -EventSender::EventSender(WebWidgetTestProxyBase* web_widget_test_proxy_base) - : web_widget_test_proxy_base_(web_widget_test_proxy_base), +EventSender::EventSender(WebWidgetTestProxy* web_widget_test_proxy) + : web_widget_test_proxy_(web_widget_test_proxy), replaying_saved_events_(false), weak_factory_(this) { Reset(); @@ -1831,32 +1831,32 @@ } void EventSender::ZoomPageIn() { - const std::vector<WebViewTestProxyBase*>& window_list = + const std::vector<WebViewTestProxy*>& window_list = interfaces()->GetWindowList(); for (size_t i = 0; i < window_list.size(); ++i) { - window_list.at(i)->web_view()->SetZoomLevel( - window_list.at(i)->web_view()->ZoomLevel() + 1); + window_list.at(i)->webview()->SetZoomLevel( + window_list.at(i)->webview()->ZoomLevel() + 1); } } void EventSender::ZoomPageOut() { - const std::vector<WebViewTestProxyBase*>& window_list = + const std::vector<WebViewTestProxy*>& window_list = interfaces()->GetWindowList(); for (size_t i = 0; i < window_list.size(); ++i) { - window_list.at(i)->web_view()->SetZoomLevel( - window_list.at(i)->web_view()->ZoomLevel() - 1); + window_list.at(i)->webview()->SetZoomLevel( + window_list.at(i)->webview()->ZoomLevel() - 1); } } void EventSender::SetPageZoomFactor(double zoom_factor) { - const std::vector<WebViewTestProxyBase*>& window_list = + const std::vector<WebViewTestProxy*>& window_list = interfaces()->GetWindowList(); for (size_t i = 0; i < window_list.size(); ++i) { - window_list.at(i)->web_view()->SetZoomLevel(std::log(zoom_factor) / - std::log(1.2)); + window_list.at(i)->webview()->SetZoomLevel(std::log(zoom_factor) / + std::log(1.2)); } } @@ -2903,24 +2903,23 @@ } TestInterfaces* EventSender::interfaces() { - return web_widget_test_proxy_base_->web_view_test_proxy_base() - ->test_interfaces(); + return web_widget_test_proxy_->GetWebViewTestProxy()->test_interfaces(); } WebTestDelegate* EventSender::delegate() { - return web_widget_test_proxy_base_->web_view_test_proxy_base()->delegate(); + return web_widget_test_proxy_->GetWebViewTestProxy()->delegate(); } const blink::WebView* EventSender::view() const { - return web_widget_test_proxy_base_->web_view_test_proxy_base()->web_view(); + return web_widget_test_proxy_->GetWebViewTestProxy()->webview(); } blink::WebView* EventSender::view() { - return web_widget_test_proxy_base_->web_view_test_proxy_base()->web_view(); + return web_widget_test_proxy_->GetWebViewTestProxy()->webview(); } blink::WebWidget* EventSender::widget() { - return web_widget_test_proxy_base_->web_widget(); + return web_widget_test_proxy_->GetWebWidget(); } blink::WebFrameWidget* EventSender::mainFrameWidget() { @@ -2929,8 +2928,8 @@ std::unique_ptr<WebInputEvent> EventSender::TransformScreenToWidgetCoordinates( const WebInputEvent& event) { - return delegate()->TransformScreenToWidgetCoordinates( - web_widget_test_proxy_base_, event); + return delegate()->TransformScreenToWidgetCoordinates(web_widget_test_proxy_, + event); } void EventSender::UpdateLifecycleToPrePaint() {
diff --git a/content/shell/test_runner/event_sender.h b/content/shell/test_runner/event_sender.h index 800a89ca..21c4160 100644 --- a/content/shell/test_runner/event_sender.h +++ b/content/shell/test_runner/event_sender.h
@@ -17,6 +17,7 @@ #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "build/build_config.h" +#include "content/shell/test_runner/test_runner_export.h" #include "third_party/blink/public/platform/web_drag_data.h" #include "third_party/blink/public/platform/web_drag_operation.h" #include "third_party/blink/public/platform/web_input_event.h" @@ -31,16 +32,16 @@ class WebView; class WebWidget; struct WebContextMenuData; -} +} // namespace blink namespace gin { class Arguments; -} +} // namespace gin namespace test_runner { class TestInterfaces; -class WebWidgetTestProxyBase; +class WebWidgetTestProxy; class WebTestDelegate; // Key event location code introduced in DOM Level 3. @@ -52,9 +53,9 @@ DOMKeyLocationNumpad = 0x03 }; -class EventSender { +class TEST_RUNNER_EXPORT EventSender { public: - explicit EventSender(WebWidgetTestProxyBase*); + explicit EventSender(WebWidgetTestProxy*); virtual ~EventSender(); void Reset(); @@ -261,7 +262,7 @@ int wm_sys_dead_char_; #endif - WebWidgetTestProxyBase* web_widget_test_proxy_base_; + WebWidgetTestProxy* web_widget_test_proxy_; TestInterfaces* interfaces(); WebTestDelegate* delegate(); const blink::WebView* view() const;
diff --git a/content/shell/test_runner/test_interfaces.cc b/content/shell/test_runner/test_interfaces.cc index a5c59079..7ceea1f1 100644 --- a/content/shell/test_runner/test_interfaces.cc +++ b/content/shell/test_runner/test_interfaces.cc
@@ -65,8 +65,8 @@ gamepad_controller_->Reset(); blink::WebCache::Clear(); - for (WebViewTestProxyBase* web_view_test_proxy_base : window_list_) - web_view_test_proxy_base->Reset(); + for (WebViewTestProxy* web_view_test_proxy : window_list_) + web_view_test_proxy->Reset(); } void TestInterfaces::ResetAll() { @@ -125,12 +125,12 @@ test_runner_->set_is_web_platform_tests_mode(); } -void TestInterfaces::WindowOpened(WebViewTestProxyBase* proxy) { +void TestInterfaces::WindowOpened(WebViewTestProxy* proxy) { window_list_.push_back(proxy); } -void TestInterfaces::WindowClosed(WebViewTestProxyBase* proxy) { - std::vector<WebViewTestProxyBase*>::iterator pos = +void TestInterfaces::WindowClosed(WebViewTestProxy* proxy) { + std::vector<WebViewTestProxy*>::iterator pos = std::find(window_list_.begin(), window_list_.end(), proxy); if (pos == window_list_.end()) { NOTREACHED(); @@ -138,7 +138,7 @@ } window_list_.erase(pos); - if (proxy->web_view() == main_view_) + if (proxy->webview() == main_view_) SetMainView(nullptr); } @@ -150,7 +150,7 @@ return delegate_; } -const std::vector<WebViewTestProxyBase*>& TestInterfaces::GetWindowList() { +const std::vector<WebViewTestProxy*>& TestInterfaces::GetWindowList() { return window_list_; }
diff --git a/content/shell/test_runner/test_interfaces.h b/content/shell/test_runner/test_interfaces.h index 58bbbb8..8952824 100644 --- a/content/shell/test_runner/test_interfaces.h +++ b/content/shell/test_runner/test_interfaces.h
@@ -24,7 +24,7 @@ class GamepadController; class TestRunner; class WebTestDelegate; -class WebViewTestProxyBase; +class WebViewTestProxy; class TestInterfaces { public: @@ -41,12 +41,12 @@ void ConfigureForTestWithURL(const blink::WebURL& test_url, bool protocol_mode); - void WindowOpened(WebViewTestProxyBase* proxy); - void WindowClosed(WebViewTestProxyBase* proxy); + void WindowOpened(WebViewTestProxy* proxy); + void WindowClosed(WebViewTestProxy* proxy); TestRunner* GetTestRunner(); WebTestDelegate* GetDelegate(); - const std::vector<WebViewTestProxyBase*>& GetWindowList(); + const std::vector<WebViewTestProxy*>& GetWindowList(); blink::WebThemeEngine* GetThemeEngine(); private: @@ -54,7 +54,7 @@ std::unique_ptr<TestRunner> test_runner_; WebTestDelegate* delegate_; - std::vector<WebViewTestProxyBase*> window_list_; + std::vector<WebViewTestProxy*> window_list_; blink::WebView* main_view_; std::unique_ptr<MockWebThemeEngine> theme_engine_;
diff --git a/content/shell/test_runner/test_runner.cc b/content/shell/test_runner/test_runner.cc index edb1eaa..421b6a3c 100644 --- a/content/shell/test_runner/test_runner.cc +++ b/content/shell/test_runner/test_runner.cc
@@ -1728,8 +1728,8 @@ changed_values); bool allowed = web_test_runtime_flags_.plugins_allowed(); - for (WebViewTestProxyBase* window : test_interfaces_->GetWindowList()) - window->web_view()->GetSettings()->SetPluginsEnabled(allowed); + for (WebViewTestProxy* window : test_interfaces_->GetWindowList()) + window->webview()->GetSettings()->SetPluginsEnabled(allowed); } } @@ -2138,8 +2138,8 @@ orientation = blink::kWebScreenOrientationLandscapeSecondary; } - for (WebViewTestProxyBase* window : test_interfaces_->GetWindowList()) { - blink::WebFrame* main_frame = window->web_view()->MainFrame(); + for (WebViewTestProxy* window : test_interfaces_->GetWindowList()) { + blink::WebFrame* main_frame = window->webview()->MainFrame(); // TODO(lukasza): Need to make this work for remote frames. if (main_frame->IsWebLocalFrame()) { mock_screen_orientation_client_->UpdateDeviceOrientation( @@ -2242,8 +2242,8 @@ web_test_runtime_flags_.set_accept_languages(accept_languages); OnWebTestRuntimeFlagsChanged(); - for (WebViewTestProxyBase* window : test_interfaces_->GetWindowList()) - window->web_view()->AcceptLanguagesChanged(); + for (WebViewTestProxy* window : test_interfaces_->GetWindowList()) + window->webview()->AcceptLanguagesChanged(); } void TestRunner::SetPluginsEnabled(bool enabled) { @@ -2361,8 +2361,8 @@ void TestRunner::SetPluginsAllowed(bool allowed) { web_test_runtime_flags_.set_plugins_allowed(allowed); - for (WebViewTestProxyBase* window : test_interfaces_->GetWindowList()) - window->web_view()->GetSettings()->SetPluginsEnabled(allowed); + for (WebViewTestProxy* window : test_interfaces_->GetWindowList()) + window->webview()->GetSettings()->SetPluginsEnabled(allowed); OnWebTestRuntimeFlagsChanged(); }
diff --git a/content/shell/test_runner/test_runner_for_specific_view.cc b/content/shell/test_runner/test_runner_for_specific_view.cc index d49a697..032708a 100644 --- a/content/shell/test_runner/test_runner_for_specific_view.cc +++ b/content/shell/test_runner/test_runner_for_specific_view.cc
@@ -683,8 +683,7 @@ } blink::WebView* TestRunnerForSpecificView::web_view() { - // TODO(danakj): This could grab the GetWebView() off RenderViewImpl instead. - return web_view_test_proxy_->web_view(); + return web_view_test_proxy_->webview(); } WebTestDelegate* TestRunnerForSpecificView::delegate() {
diff --git a/content/shell/test_runner/test_runner_for_specific_view.h b/content/shell/test_runner/test_runner_for_specific_view.h index 8a28939..ea0e034 100644 --- a/content/shell/test_runner/test_runner_for_specific_view.h +++ b/content/shell/test_runner/test_runner_for_specific_view.h
@@ -13,6 +13,7 @@ #include "base/callback_forward.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "content/shell/test_runner/test_runner_export.h" #include "v8/include/v8.h" class GURL; @@ -42,7 +43,7 @@ // - testRunner.capturePixelsAsyncThen // - testRunner.setPageVisibility // Note that "global" bindings are handled by TestRunner class. -class TestRunnerForSpecificView { +class TEST_RUNNER_EXPORT TestRunnerForSpecificView { public: explicit TestRunnerForSpecificView(WebViewTestProxy* web_view_test_proxy); ~TestRunnerForSpecificView();
diff --git a/content/shell/test_runner/text_input_controller.cc b/content/shell/test_runner/text_input_controller.cc index 42a70b2b..74b6018f 100644 --- a/content/shell/test_runner/text_input_controller.cc +++ b/content/shell/test_runner/text_input_controller.cc
@@ -196,10 +196,8 @@ } // TextInputController --------------------------------------------------------- -TextInputController::TextInputController( - WebViewTestProxyBase* web_view_test_proxy_base) - : web_view_test_proxy_base_(web_view_test_proxy_base), - weak_factory_(this) {} +TextInputController::TextInputController(WebViewTestProxy* web_view_test_proxy) + : web_view_test_proxy_(web_view_test_proxy), weak_factory_(this) {} TextInputController::~TextInputController() {} @@ -400,12 +398,12 @@ CHECK(view()->MainFrame()->IsWebLocalFrame()) << "WebView does not have a local main frame and" " cannot handle input method controller tasks."; - web_view_test_proxy_base_->delegate()->ForceTextInputStateUpdate( + web_view_test_proxy_->delegate()->ForceTextInputStateUpdate( view()->MainFrame()->ToWebLocalFrame()); } blink::WebView* TextInputController::view() { - return web_view_test_proxy_base_->web_view(); + return web_view_test_proxy_->webview(); } blink::WebInputMethodController*
diff --git a/content/shell/test_runner/text_input_controller.h b/content/shell/test_runner/text_input_controller.h index a7f03e31..a1ee9263 100644 --- a/content/shell/test_runner/text_input_controller.h +++ b/content/shell/test_runner/text_input_controller.h
@@ -10,6 +10,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "content/shell/test_runner/test_runner_export.h" namespace blink { class WebInputMethodController; @@ -19,14 +20,14 @@ namespace test_runner { -class WebViewTestProxyBase; +class WebViewTestProxy; // TextInputController is bound to window.textInputController in Javascript // when content_shell is running. Web tests use it to exercise various // corners of text input. -class TextInputController { +class TEST_RUNNER_EXPORT TextInputController { public: - explicit TextInputController(WebViewTestProxyBase* web_view_test_proxy_base); + explicit TextInputController(WebViewTestProxy* web_view_test_proxy); ~TextInputController(); void Install(blink::WebLocalFrame* frame); @@ -55,7 +56,7 @@ // accepting IME. Could return nullptr if no such frame exists. blink::WebInputMethodController* GetInputMethodController(); - WebViewTestProxyBase* web_view_test_proxy_base_; + WebViewTestProxy* web_view_test_proxy_; base::WeakPtrFactory<TextInputController> weak_factory_;
diff --git a/content/shell/test_runner/web_frame_test_client.cc b/content/shell/test_runner/web_frame_test_client.cc index 4da5a48..feea07d2 100644 --- a/content/shell/test_runner/web_frame_test_client.cc +++ b/content/shell/test_runner/web_frame_test_client.cc
@@ -142,16 +142,15 @@ } // namespace -WebFrameTestClient::WebFrameTestClient( - WebTestDelegate* delegate, - WebViewTestProxyBase* web_view_test_proxy_base, - WebFrameTestProxyBase* web_frame_test_proxy_base) +WebFrameTestClient::WebFrameTestClient(WebTestDelegate* delegate, + WebViewTestProxy* web_view_test_proxy, + WebFrameTestProxy* web_frame_test_proxy) : delegate_(delegate), - web_view_test_proxy_base_(web_view_test_proxy_base), - web_frame_test_proxy_base_(web_frame_test_proxy_base) { + web_view_test_proxy_(web_view_test_proxy), + web_frame_test_proxy_(web_frame_test_proxy) { DCHECK(delegate_); - DCHECK(web_frame_test_proxy_base_); - DCHECK(web_view_test_proxy_base_); + DCHECK(web_frame_test_proxy_); + DCHECK(web_view_test_proxy_); } WebFrameTestClient::~WebFrameTestClient() {} @@ -317,7 +316,7 @@ return; AccessibilityController* accessibility_controller = - web_view_test_proxy_base_->accessibility_controller(); + web_view_test_proxy_->accessibility_controller(); accessibility_controller->NotificationReceived(obj, event_name); if (accessibility_controller->ShouldLogAccessibilityEvents()) { std::string message("AccessibilityNotification - "); @@ -351,7 +350,7 @@ blink::WebPlugin* WebFrameTestClient::CreatePlugin( const blink::WebPluginParams& params) { - blink::WebLocalFrame* frame = web_frame_test_proxy_base_->web_frame(); + blink::WebLocalFrame* frame = web_frame_test_proxy_->GetWebFrame(); if (TestPlugin::IsSupportedMimeType(params.mime_type)) return TestPlugin::Create(params, delegate_, frame); return delegate_->CreatePluginPlaceholder(params); @@ -359,7 +358,7 @@ void WebFrameTestClient::ShowContextMenu( const blink::WebContextMenuData& context_menu_data) { - delegate_->GetWebWidgetTestProxyBase(web_frame_test_proxy_base_->web_frame()) + delegate_->GetWebWidgetTestProxy(web_frame_test_proxy_->GetWebFrame()) ->event_sender() ->SetContextMenuData(context_menu_data); } @@ -378,8 +377,8 @@ void WebFrameTestClient::DidReceiveTitle(const blink::WebString& title, blink::WebTextDirection direction) { if (test_runner()->shouldDumpFrameLoadCallbacks() && - web_frame_test_proxy_base_->web_frame()) { - PrintFrameDescription(delegate_, web_frame_test_proxy_base_->web_frame()); + web_frame_test_proxy_->GetWebFrame()) { + PrintFrameDescription(delegate_, web_frame_test_proxy_->GetWebFrame()); delegate_->PrintMessage(std::string(" - didReceiveTitle: ") + title.Utf8() + "\n"); } @@ -391,7 +390,7 @@ void WebFrameTestClient::DidChangeIcon(blink::WebIconURL::Type icon_type) { if (test_runner()->shouldDumpIconChanges()) { - PrintFrameDescription(delegate_, web_frame_test_proxy_base_->web_frame()); + PrintFrameDescription(delegate_, web_frame_test_proxy_->GetWebFrame()); delegate_->PrintMessage(std::string(" - didChangeIcons\n")); } } @@ -399,19 +398,18 @@ void WebFrameTestClient::DidFailLoad(const blink::WebURLError& error, blink::WebHistoryCommitType commit_type) { if (test_runner()->shouldDumpFrameLoadCallbacks()) { - PrintFrameDescription(delegate_, web_frame_test_proxy_base_->web_frame()); + PrintFrameDescription(delegate_, web_frame_test_proxy_->GetWebFrame()); delegate_->PrintMessage(" - didFailLoadWithError\n"); } } void WebFrameTestClient::DidStartLoading() { - test_runner()->tryToSetTopLoadingFrame( - web_frame_test_proxy_base_->web_frame()); + test_runner()->tryToSetTopLoadingFrame(web_frame_test_proxy_->GetWebFrame()); } void WebFrameTestClient::DidStopLoading() { test_runner()->tryToClearTopLoadingFrame( - web_frame_test_proxy_base_->web_frame()); + web_frame_test_proxy_->GetWebFrame()); } void WebFrameTestClient::DidDispatchPingLoader(const blink::WebURL& url) { @@ -581,10 +579,10 @@ } void WebFrameTestClient::DidClearWindowObject() { - blink::WebLocalFrame* frame = web_frame_test_proxy_base_->web_frame(); - web_view_test_proxy_base_->test_interfaces()->BindTo(frame); - web_view_test_proxy_base_->BindTo(frame); - delegate_->GetWebWidgetTestProxyBase(frame)->BindTo(frame); + blink::WebLocalFrame* frame = web_frame_test_proxy_->GetWebFrame(); + web_view_test_proxy_->test_interfaces()->BindTo(frame); + web_view_test_proxy_->BindTo(frame); + delegate_->GetWebWidgetTestProxy(frame)->BindTo(frame); } blink::WebEffectiveConnectionType @@ -593,7 +591,7 @@ } TestRunner* WebFrameTestClient::test_runner() { - return web_view_test_proxy_base_->test_interfaces()->GetTestRunner(); + return web_view_test_proxy_->test_interfaces()->GetTestRunner(); } } // namespace test_runner
diff --git a/content/shell/test_runner/web_frame_test_client.h b/content/shell/test_runner/web_frame_test_client.h index 1f1b876..ef5d20c9 100644 --- a/content/shell/test_runner/web_frame_test_client.h +++ b/content/shell/test_runner/web_frame_test_client.h
@@ -14,9 +14,9 @@ namespace test_runner { class TestRunner; -class WebFrameTestProxyBase; +class WebFrameTestProxy; class WebTestDelegate; -class WebViewTestProxyBase; +class WebViewTestProxy; // WebFrameTestClient implements WebLocalFrameClient interface, providing // behavior expected by tests. WebFrameTestClient ends up used by @@ -26,10 +26,10 @@ class WebFrameTestClient : public blink::WebLocalFrameClient { public: // Caller has to ensure that all arguments (|delegate|, - // |web_view_test_proxy_base_| and so forth) live longer than |this|. + // |web_view_test_proxy| and so forth) live longer than |this|. WebFrameTestClient(WebTestDelegate* delegate, - WebViewTestProxyBase* web_view_test_proxy_base, - WebFrameTestProxyBase* web_frame_test_proxy_base); + WebViewTestProxy* web_view_test_proxy, + WebFrameTestProxy* web_frame_test_proxy); ~WebFrameTestClient() override; bool ShouldContinueNavigation(const blink::WebNavigationInfo& info); @@ -84,8 +84,8 @@ // Borrowed pointers to other parts of web tests state. WebTestDelegate* delegate_; - WebViewTestProxyBase* web_view_test_proxy_base_; - WebFrameTestProxyBase* web_frame_test_proxy_base_; + WebViewTestProxy* web_view_test_proxy_; + WebFrameTestProxy* web_frame_test_proxy_; DISALLOW_COPY_AND_ASSIGN(WebFrameTestClient); };
diff --git a/content/shell/test_runner/web_frame_test_proxy.h b/content/shell/test_runner/web_frame_test_proxy.h index e51cbf6b..36e8055 100644 --- a/content/shell/test_runner/web_frame_test_proxy.h +++ b/content/shell/test_runner/web_frame_test_proxy.h
@@ -20,35 +20,15 @@ namespace content { class RenderViewImpl; -} +} // namespace content namespace test_runner { class WebTestInterfaces; -class TEST_RUNNER_EXPORT WebFrameTestProxyBase { - public: - blink::WebLocalFrame* web_frame() const { return web_frame_; } - void set_web_frame(blink::WebLocalFrame* frame) { - DCHECK(frame); - DCHECK(!web_frame_); - web_frame_ = frame; - } - - protected: - WebFrameTestProxyBase() = default; - ~WebFrameTestProxyBase() = default; - - private: - blink::WebLocalFrame* web_frame_ = nullptr; - - DISALLOW_COPY_AND_ASSIGN(WebFrameTestProxyBase); -}; - // WebFrameTestProxy is used during running web tests instead of a // RenderFrameImpl to inject test-only behaviour by overriding methods in the // base class. -class TEST_RUNNER_EXPORT WebFrameTestProxy : public content::RenderFrameImpl, - public WebFrameTestProxyBase { +class TEST_RUNNER_EXPORT WebFrameTestProxy : public content::RenderFrameImpl { public: template <typename... Args> explicit WebFrameTestProxy(Args&&... args)
diff --git a/content/shell/test_runner/web_test_delegate.h b/content/shell/test_runner/web_test_delegate.h index 8b6457b..6a39a4e1 100644 --- a/content/shell/test_runner/web_test_delegate.h +++ b/content/shell/test_runner/web_test_delegate.h
@@ -37,7 +37,7 @@ namespace test_runner { -class WebWidgetTestProxyBase; +class WebWidgetTestProxy; struct TestPreferences; constexpr int kDefaultDatabaseQuota = -1; @@ -130,17 +130,17 @@ // Converts |event| from screen coordinates used by test_runner::EventSender // into coordinates that are understood by the widget associated with - // |web_widget_test_proxy_base|. Returns nullptr if no transformation was + // |web_widget_test_proxy|. Returns nullptr if no transformation was // necessary (e.g. for a keyboard event OR if widget requires no scaling // and has coordinates starting at (0,0)). virtual std::unique_ptr<blink::WebInputEvent> TransformScreenToWidgetCoordinates( - test_runner::WebWidgetTestProxyBase* web_widget_test_proxy_base, + test_runner::WebWidgetTestProxy* web_widget_test_proxy, const blink::WebInputEvent& event) = 0; - // Gets WebWidgetTestProxyBase associated with |frame| (associated with either + // Gets WebWidgetTestProxy associated with |frame| (associated with either // a RenderView or a RenderWidget for the local root). - virtual test_runner::WebWidgetTestProxyBase* GetWebWidgetTestProxyBase( + virtual test_runner::WebWidgetTestProxy* GetWebWidgetTestProxy( blink::WebLocalFrame* frame) = 0; // Enable zoom-for-dsf option.
diff --git a/content/shell/test_runner/web_test_interfaces.cc b/content/shell/test_runner/web_test_interfaces.cc index d535da3..db6c5bd 100644 --- a/content/shell/test_runner/web_test_interfaces.cc +++ b/content/shell/test_runner/web_test_interfaces.cc
@@ -10,7 +10,6 @@ #include "content/shell/test_runner/test_runner.h" #include "content/shell/test_runner/web_frame_test_client.h" #include "content/shell/test_runner/web_view_test_proxy.h" -#include "content/shell/test_runner/web_widget_test_client.h" #include "content/shell/test_runner/web_widget_test_proxy.h" namespace test_runner { @@ -57,19 +56,18 @@ } std::unique_ptr<WebFrameTestClient> WebTestInterfaces::CreateWebFrameTestClient( - WebViewTestProxyBase* web_view_test_proxy_base, - WebFrameTestProxyBase* web_frame_test_proxy_base) { + WebViewTestProxy* web_view_test_proxy, + WebFrameTestProxy* web_frame_test_proxy) { // TODO(lukasza): Do not pass the WebTestDelegate below - it's lifetime can // differ from the lifetime of WebFrameTestClient - https://crbug.com/606594. - return std::make_unique<WebFrameTestClient>(interfaces_->GetDelegate(), - web_view_test_proxy_base, - web_frame_test_proxy_base); + return std::make_unique<WebFrameTestClient>( + interfaces_->GetDelegate(), web_view_test_proxy, web_frame_test_proxy); } std::vector<blink::WebView*> WebTestInterfaces::GetWindowList() { std::vector<blink::WebView*> result; - for (WebViewTestProxyBase* proxy : interfaces_->GetWindowList()) - result.push_back(proxy->web_view()); + for (WebViewTestProxy* proxy : interfaces_->GetWindowList()) + result.push_back(proxy->webview()); return result; }
diff --git a/content/shell/test_runner/web_test_interfaces.h b/content/shell/test_runner/web_test_interfaces.h index 638833f..2da2e3f 100644 --- a/content/shell/test_runner/web_test_interfaces.h +++ b/content/shell/test_runner/web_test_interfaces.h
@@ -24,9 +24,9 @@ class TestInterfaces; class WebFrameTestClient; -class WebFrameTestProxyBase; +class WebFrameTestProxy; class WebTestDelegate; -class WebViewTestProxyBase; +class WebViewTestProxy; class WebTestRunner; class TEST_RUNNER_EXPORT WebTestInterfaces { @@ -57,10 +57,10 @@ // Creates a WebLocalFrameClient implementation providing test behavior (i.e. // forwarding javascript console output to the test harness). The caller // should guarantee that the returned object won't be used beyond the lifetime - // of WebTestInterfaces and/or the lifetime of |web_view_test_proxy_base|. + // of WebTestInterfaces and/or the lifetime of |web_view_test_proxy|. std::unique_ptr<WebFrameTestClient> CreateWebFrameTestClient( - WebViewTestProxyBase* web_view_test_proxy_base, - WebFrameTestProxyBase* web_frame_test_proxy_base); + WebViewTestProxy* web_view_test_proxy, + WebFrameTestProxy* web_frame_test_proxy); // Gets a list of currently opened windows created by the current test. std::vector<blink::WebView*> GetWindowList();
diff --git a/content/shell/test_runner/web_view_test_client.cc b/content/shell/test_runner/web_view_test_client.cc deleted file mode 100644 index 691501df..0000000 --- a/content/shell/test_runner/web_view_test_client.cc +++ /dev/null
@@ -1,120 +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 "content/shell/test_runner/web_view_test_client.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/i18n/rtl.h" -#include "base/strings/string16.h" -#include "base/strings/utf_string_conversions.h" -#include "base/time/time.h" -#include "content/shell/test_runner/event_sender.h" -#include "content/shell/test_runner/mock_screen_orientation_client.h" -#include "content/shell/test_runner/test_common.h" -#include "content/shell/test_runner/test_interfaces.h" -#include "content/shell/test_runner/test_runner.h" -#include "content/shell/test_runner/test_runner_for_specific_view.h" -#include "content/shell/test_runner/web_test_delegate.h" -#include "content/shell/test_runner/web_view_test_proxy.h" -#include "content/shell/test_runner/web_widget_test_proxy.h" -#include "third_party/blink/public/platform/web_url_request.h" -#include "third_party/blink/public/web/web_frame.h" -#include "third_party/blink/public/web/web_local_frame.h" -#include "third_party/blink/public/web/web_page_popup.h" -#include "third_party/blink/public/web/web_print_params.h" -#include "third_party/blink/public/web/web_view.h" -#include "third_party/blink/public/web/web_widget.h" - -namespace test_runner { - -WebViewTestClient::WebViewTestClient( - WebViewTestProxyBase* web_view_test_proxy_base) - : web_view_test_proxy_base_(web_view_test_proxy_base) { - DCHECK(web_view_test_proxy_base); -} - -WebViewTestClient::~WebViewTestClient() {} - -// The output from these methods in web test mode should match that -// expected by the web tests. See EditingDelegate.m in DumpRenderTree. - -blink::WebView* WebViewTestClient::CreateView( - blink::WebLocalFrame* frame, - const blink::WebURLRequest& request, - const blink::WebWindowFeatures& features, - const blink::WebString& frame_name, - blink::WebNavigationPolicy policy, - bool suppress_opener, - blink::WebSandboxFlags sandbox_flags, - const blink::SessionStorageNamespaceId& session_storage_namespace_id) { - if (test_runner()->shouldDumpNavigationPolicy()) { - delegate()->PrintMessage("Default policy for createView for '" + - URLDescription(request.Url()) + "' is '" + - WebNavigationPolicyToString(policy) + "'\n"); - } - - if (!test_runner()->canOpenWindows()) - return nullptr; - if (test_runner()->shouldDumpCreateView()) - delegate()->PrintMessage(std::string("createView(") + - URLDescription(request.Url()) + ")\n"); - - // The return value below is used to communicate to WebViewTestProxy whether - // it should forward the createView request to RenderViewImpl or not. The - // somewhat ugly cast is used to do this while fitting into the existing - // WebViewClient interface. - return reinterpret_cast<blink::WebView*>(0xdeadbeef); -} - -// Simulate a print by going into print mode and then exit straight away. -void WebViewTestClient::PrintPage(blink::WebLocalFrame* frame) { - blink::WebSize page_size_in_pixels = frame->View()->MainFrameWidget()->Size(); - if (page_size_in_pixels.IsEmpty()) - return; - blink::WebPrintParams printParams(page_size_in_pixels); - frame->PrintBegin(printParams); - frame->PrintEnd(); -} - -blink::WebString WebViewTestClient::AcceptLanguages() { - return blink::WebString::FromUTF8(test_runner()->GetAcceptLanguages()); -} - -WebTestDelegate* WebViewTestClient::delegate() { - return web_view_test_proxy_base_->delegate(); -} - -void WebViewTestClient::DidFocus(blink::WebLocalFrame* calling_frame) { - test_runner()->SetFocus(web_view_test_proxy_base_->web_view(), true); -} - -TestRunner* WebViewTestClient::test_runner() { - return web_view_test_proxy_base_->test_interfaces()->GetTestRunner(); -} - -bool WebViewTestClient::CanHandleGestureEvent() { - return true; -} - -bool WebViewTestClient::CanUpdateLayout() { - return true; -} - -blink::WebScreenInfo WebViewTestClient::GetScreenInfo() { - blink::WebScreenInfo screen_info; - MockScreenOrientationClient* mock_client = - test_runner()->getMockScreenOrientationClient(); - if (mock_client->IsDisabled()) { - // Indicate to WebViewTestProxy that there is no test/mock info. - screen_info.orientation_type = blink::kWebScreenOrientationUndefined; - } else { - // Override screen orientation information with mock data. - screen_info.orientation_type = mock_client->CurrentOrientationType(); - screen_info.orientation_angle = mock_client->CurrentOrientationAngle(); - } - return screen_info; -} - -} // namespace test_runner
diff --git a/content/shell/test_runner/web_view_test_client.h b/content/shell/test_runner/web_view_test_client.h deleted file mode 100644 index f8daefb..0000000 --- a/content/shell/test_runner/web_view_test_client.h +++ /dev/null
@@ -1,60 +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 CONTENT_SHELL_TEST_RUNNER_WEB_VIEW_TEST_CLIENT_H_ -#define CONTENT_SHELL_TEST_RUNNER_WEB_VIEW_TEST_CLIENT_H_ - -#include "base/macros.h" -#include "third_party/blink/public/web/web_view_client.h" - -namespace blink { -class WebView; -} // namespace blink - -namespace test_runner { - -class TestRunner; -class WebTestDelegate; -class WebViewTestProxyBase; - -// WebViewTestClient implements WebViewClient interface, providing behavior -// expected by tests. WebViewTestClient ends up used by WebViewTestProxy -// which coordinates forwarding WebViewClient calls either to -// WebViewTestClient or to the product code (i.e. to RenderViewImpl). -class WebViewTestClient : public blink::WebViewClient { - public: - // Caller has to ensure |web_view_test_proxy_base| lives longer than |this|. - explicit WebViewTestClient(WebViewTestProxyBase* web_view_test_proxy_base); - - ~WebViewTestClient() override; - - // WebViewClient overrides needed by WebViewTestProxy. - blink::WebView* CreateView(blink::WebLocalFrame* creator, - const blink::WebURLRequest& request, - const blink::WebWindowFeatures& features, - const blink::WebString& frame_name, - blink::WebNavigationPolicy policy, - bool suppress_opener, - blink::WebSandboxFlags, - const blink::SessionStorageNamespaceId&) override; - void PrintPage(blink::WebLocalFrame* frame) override; - blink::WebString AcceptLanguages() override; - void DidFocus(blink::WebLocalFrame* calling_frame) override; - bool CanHandleGestureEvent() override; - bool CanUpdateLayout() override; - blink::WebScreenInfo GetScreenInfo() override; - - private: - WebTestDelegate* delegate(); - TestRunner* test_runner(); - - // Borrowed pointer to WebViewTestProxyBase. - WebViewTestProxyBase* web_view_test_proxy_base_; - - DISALLOW_COPY_AND_ASSIGN(WebViewTestClient); -}; - -} // namespace test_runner - -#endif // CONTENT_SHELL_TEST_RUNNER_WEB_VIEW_TEST_CLIENT_H_
diff --git a/content/shell/test_runner/web_view_test_proxy.cc b/content/shell/test_runner/web_view_test_proxy.cc index c474b37..132bfe8 100644 --- a/content/shell/test_runner/web_view_test_proxy.cc +++ b/content/shell/test_runner/web_view_test_proxy.cc
@@ -8,206 +8,25 @@ #include <stdint.h> #include "content/renderer/compositor/layer_tree_view.h" -#include "content/shell/test_runner/accessibility_controller.h" +#include "content/shell/test_runner/mock_screen_orientation_client.h" +#include "content/shell/test_runner/test_common.h" #include "content/shell/test_runner/test_interfaces.h" #include "content/shell/test_runner/test_runner.h" -#include "content/shell/test_runner/test_runner_for_specific_view.h" -#include "content/shell/test_runner/text_input_controller.h" #include "content/shell/test_runner/web_test_delegate.h" #include "content/shell/test_runner/web_test_interfaces.h" #include "content/shell/test_runner/web_widget_test_proxy.h" +#include "third_party/blink/public/platform/web_url_request.h" #include "third_party/blink/public/web/web_frame.h" +#include "third_party/blink/public/web/web_local_frame.h" +#include "third_party/blink/public/web/web_print_params.h" #include "third_party/blink/public/web/web_view.h" namespace test_runner { -ProxyWebWidgetClient::ProxyWebWidgetClient( - blink::WebWidgetClient* base_class_widget_client, - blink::WebWidgetClient* widget_test_client, - content::RenderWidget* render_widget) - : base_class_widget_client_(base_class_widget_client), - widget_test_client_(widget_test_client), - render_widget_(render_widget) {} - -void ProxyWebWidgetClient::SetRootLayer(scoped_refptr<cc::Layer> layer) { - base_class_widget_client_->SetRootLayer(std::move(layer)); -} -void ProxyWebWidgetClient::ScheduleAnimation() { - // When using threaded compositing, have the RenderWidget schedule a request - // for a frame, as we use the compositor's scheduler. Otherwise the testing - // WebWidgetClient schedules it. - // Note that for WebViewTestProxy the RenderWidget is not subclassed to - // override the WebWidgetClient, instead it is injected into RenderViewImpl, - // so if we call RenderWidget here we jump out of the test harness as - // intended. - if (!render_widget_->layer_tree_view()->CompositeIsSynchronousForTesting()) - render_widget_->ScheduleAnimation(); - else - widget_test_client_->ScheduleAnimation(); -} -void ProxyWebWidgetClient::IntrinsicSizingInfoChanged( - const blink::WebIntrinsicSizingInfo& info) { - base_class_widget_client_->IntrinsicSizingInfoChanged(info); -} -void ProxyWebWidgetClient::DidMeaningfulLayout( - blink::WebMeaningfulLayout layout) { - base_class_widget_client_->DidMeaningfulLayout(layout); -} -void ProxyWebWidgetClient::DidFirstLayoutAfterFinishedParsing() { - base_class_widget_client_->DidFirstLayoutAfterFinishedParsing(); -} -void ProxyWebWidgetClient::DidChangeCursor(const blink::WebCursorInfo& info) { - base_class_widget_client_->DidChangeCursor(info); -} -void ProxyWebWidgetClient::AutoscrollStart(const blink::WebFloatPoint& p) { - base_class_widget_client_->AutoscrollStart(p); -} -void ProxyWebWidgetClient::AutoscrollFling( - const blink::WebFloatSize& velocity) { - base_class_widget_client_->AutoscrollFling(velocity); -} -void ProxyWebWidgetClient::AutoscrollEnd() { - base_class_widget_client_->AutoscrollEnd(); -} -void ProxyWebWidgetClient::CloseWidgetSoon() { - base_class_widget_client_->CloseWidgetSoon(); -} -void ProxyWebWidgetClient::Show(blink::WebNavigationPolicy policy) { - base_class_widget_client_->Show(policy); -} -blink::WebRect ProxyWebWidgetClient::WindowRect() { - return base_class_widget_client_->WindowRect(); -} -void ProxyWebWidgetClient::SetWindowRect(const blink::WebRect& r) { - base_class_widget_client_->SetWindowRect(r); -} -blink::WebRect ProxyWebWidgetClient::ViewRect() { - return base_class_widget_client_->ViewRect(); -} -void ProxyWebWidgetClient::SetToolTipText(const blink::WebString& text, - blink::WebTextDirection hint) { - widget_test_client_->SetToolTipText(text, hint); - base_class_widget_client_->SetToolTipText(text, hint); -} -bool ProxyWebWidgetClient::RequestPointerLock() { - return widget_test_client_->RequestPointerLock(); -} -void ProxyWebWidgetClient::RequestPointerUnlock() { - widget_test_client_->RequestPointerUnlock(); -} -bool ProxyWebWidgetClient::IsPointerLocked() { - return widget_test_client_->IsPointerLocked(); -} -void ProxyWebWidgetClient::DidHandleGestureEvent( - const blink::WebGestureEvent& event, - bool event_cancelled) { - base_class_widget_client_->DidHandleGestureEvent(event, event_cancelled); -} -void ProxyWebWidgetClient::DidOverscroll( - const blink::WebFloatSize& overscroll_delta, - const blink::WebFloatSize& accumulated_overscroll, - const blink::WebFloatPoint& position_in_viewport, - const blink::WebFloatSize& velocity_in_viewport, - const cc::OverscrollBehavior& behavior) { - base_class_widget_client_->DidOverscroll( - overscroll_delta, accumulated_overscroll, position_in_viewport, - velocity_in_viewport, behavior); -} -void ProxyWebWidgetClient::HasTouchEventHandlers(bool has) { - base_class_widget_client_->HasTouchEventHandlers(has); -} -void ProxyWebWidgetClient::SetNeedsLowLatencyInput(bool needs) { - base_class_widget_client_->SetNeedsLowLatencyInput(needs); -} -void ProxyWebWidgetClient::RequestUnbufferedInputEvents() { - base_class_widget_client_->RequestUnbufferedInputEvents(); -} -void ProxyWebWidgetClient::SetTouchAction(blink::WebTouchAction touch_action) { - base_class_widget_client_->SetTouchAction(touch_action); -} -void ProxyWebWidgetClient::ShowVirtualKeyboardOnElementFocus() { - base_class_widget_client_->ShowVirtualKeyboardOnElementFocus(); -} -void ProxyWebWidgetClient::ConvertViewportToWindow(blink::WebRect* rect) { - base_class_widget_client_->ConvertViewportToWindow(rect); -} -void ProxyWebWidgetClient::ConvertWindowToViewport(blink::WebFloatRect* rect) { - base_class_widget_client_->ConvertWindowToViewport(rect); -} -void ProxyWebWidgetClient::StartDragging(network::mojom::ReferrerPolicy policy, - const blink::WebDragData& data, - blink::WebDragOperationsMask mask, - const SkBitmap& drag_image, - const gfx::Point& image_offset) { - widget_test_client_->StartDragging(policy, data, mask, drag_image, - image_offset); - // Don't forward this call to |base_class_widget_client_| because we don't - // want to do a real drag-and-drop. -} - -WebViewTestProxyBase::WebViewTestProxyBase() - : WebWidgetTestProxyBase(/*main_frame_widget=*/true), - accessibility_controller_( - std::make_unique<AccessibilityController>(this)), - text_input_controller_(std::make_unique<TextInputController>(this)), - // TODO(danakj): We should collapse WebViewTestProxy and - // WebViewTestProxyBase into one class really. They are both - // concrete types now. - view_test_runner_(std::make_unique<TestRunnerForSpecificView>( - static_cast<WebViewTestProxy*>(this))) { - WebWidgetTestProxyBase::set_web_view_test_proxy_base(this); -} - -WebViewTestProxyBase::~WebViewTestProxyBase() { - test_interfaces_->WindowClosed(this); - if (test_interfaces_->GetDelegate() == delegate_) - test_interfaces_->SetDelegate(nullptr); -} - -void WebViewTestProxyBase::Reset() { - accessibility_controller_->Reset(); - // text_input_controller_ doesn't have any state to reset. - view_test_runner_->Reset(); - WebWidgetTestProxyBase::Reset(); - - for (blink::WebFrame* frame = web_view_->MainFrame(); frame; - frame = frame->TraverseNext()) { - if (frame->IsWebLocalFrame()) - delegate_->GetWebWidgetTestProxyBase(frame->ToWebLocalFrame())->Reset(); - } -} - -void WebViewTestProxyBase::BindTo(blink::WebLocalFrame* frame) { - accessibility_controller_->Install(frame); - text_input_controller_->Install(frame); - view_test_runner_->Install(frame); -} - void WebViewTestProxy::Initialize(WebTestInterfaces* interfaces, WebTestDelegate* delegate) { - // On WebViewTestProxyBase. - set_delegate(delegate); - - auto widget_client_impl = - std::make_unique<WebWidgetTestClient>(web_widget_test_proxy_base()); - // This passes calls through to the the |test_widget_client| as well as the - // production client pulled from RenderViewImpl as needed. - widget_client_ = std::make_unique<ProxyWebWidgetClient>( - RenderViewImpl::WidgetClient(), widget_client_impl.get(), - RenderViewImpl::GetWidget()); - // This returns the |proxy_widget_client| as the WebWidgetClient. - view_test_client_ = std::make_unique<WebViewTestClient>(this); - - // On WebWidgetTestProxyBase. - // It's weird that the WebView has the proxy client, but the - // WebWidgetProxyBase has the test one only, but that's because the - // WebWidgetTestProxyBase does not itself use the WebWidgetClient, only its - // subclasses do. - web_widget_test_proxy_base()->set_widget_test_client( - std::move(widget_client_impl)); - - // On WebViewTestProxyBase. - set_test_interfaces(interfaces->GetTestInterfaces()); + delegate_ = delegate; + test_interfaces_ = interfaces->GetTestInterfaces(); test_interfaces()->WindowOpened(this); } @@ -220,42 +39,86 @@ bool suppress_opener, blink::WebSandboxFlags sandbox_flags, const blink::SessionStorageNamespaceId& session_storage_namespace_id) { - if (!view_test_client_->CreateView(creator, request, features, frame_name, - policy, suppress_opener, sandbox_flags, - session_storage_namespace_id)) + if (GetTestRunner()->shouldDumpNavigationPolicy()) { + delegate()->PrintMessage("Default policy for createView for '" + + URLDescription(request.Url()) + "' is '" + + WebNavigationPolicyToString(policy) + "'\n"); + } + + if (!GetTestRunner()->canOpenWindows()) return nullptr; + + if (GetTestRunner()->shouldDumpCreateView()) { + delegate()->PrintMessage(std::string("createView(") + + URLDescription(request.Url()) + ")\n"); + } return RenderViewImpl::CreateView(creator, request, features, frame_name, policy, suppress_opener, sandbox_flags, session_storage_namespace_id); } void WebViewTestProxy::PrintPage(blink::WebLocalFrame* frame) { - view_test_client_->PrintPage(frame); + blink::WebSize page_size_in_pixels = GetWidget()->GetWebWidget()->Size(); + if (page_size_in_pixels.IsEmpty()) + return; + blink::WebPrintParams print_params(page_size_in_pixels); + frame->PrintBegin(print_params); + frame->PrintEnd(); } blink::WebString WebViewTestProxy::AcceptLanguages() { - return view_test_client_->AcceptLanguages(); + return blink::WebString::FromUTF8(GetTestRunner()->GetAcceptLanguages()); } void WebViewTestProxy::DidFocus(blink::WebLocalFrame* calling_frame) { - view_test_client_->DidFocus(calling_frame); + GetTestRunner()->SetFocus(webview(), true); RenderViewImpl::DidFocus(calling_frame); } blink::WebScreenInfo WebViewTestProxy::GetScreenInfo() { blink::WebScreenInfo info = RenderViewImpl::GetScreenInfo(); - blink::WebScreenInfo test_info = view_test_client_->GetScreenInfo(); - if (test_info.orientation_type != blink::kWebScreenOrientationUndefined) { - info.orientation_type = test_info.orientation_type; - info.orientation_angle = test_info.orientation_angle; + + MockScreenOrientationClient* mock_client = + GetTestRunner()->getMockScreenOrientationClient(); + + if (!mock_client->IsDisabled()) { + // Override screen orientation information with mock data. + info.orientation_type = mock_client->CurrentOrientationType(); + info.orientation_angle = mock_client->CurrentOrientationAngle(); } + return info; } -blink::WebWidgetClient* WebViewTestProxy::WidgetClient() { - return widget_client_.get(); +void WebViewTestProxy::Reset() { + accessibility_controller_.Reset(); + // text_input_controller_ doesn't have any state to reset. + view_test_runner_.Reset(); + static_cast<WebWidgetTestProxy*>(GetWidget())->Reset(); + + for (blink::WebFrame* frame = webview()->MainFrame(); frame; + frame = frame->TraverseNext()) { + if (frame->IsWebLocalFrame()) + delegate_->GetWebWidgetTestProxy(frame->ToWebLocalFrame())->Reset(); + } } -WebViewTestProxy::~WebViewTestProxy() = default; +void WebViewTestProxy::BindTo(blink::WebLocalFrame* frame) { + accessibility_controller_.Install(frame); + text_input_controller_.Install(frame); + view_test_runner_.Install(frame); +} + +WebViewTestProxy::~WebViewTestProxy() { + test_interfaces_->WindowClosed(this); + if (test_interfaces_->GetDelegate() == delegate_) + test_interfaces_->SetDelegate(nullptr); + // TODO(https://crbug.com/545684): This delegate seems unnecessarily leaked. + // Make |delegate_| a std::unique_ptr<>? +} + +TestRunner* WebViewTestProxy::GetTestRunner() { + return test_interfaces()->GetTestRunner(); +} } // namespace test_runner
diff --git a/content/shell/test_runner/web_view_test_proxy.h b/content/shell/test_runner/web_view_test_proxy.h index dd64afa..578039a 100644 --- a/content/shell/test_runner/web_view_test_proxy.h +++ b/content/shell/test_runner/web_view_test_proxy.h
@@ -13,9 +13,10 @@ #include "base/macros.h" #include "build/build_config.h" #include "content/renderer/render_view_impl.h" +#include "content/shell/test_runner/accessibility_controller.h" #include "content/shell/test_runner/test_runner_export.h" -#include "content/shell/test_runner/web_view_test_client.h" -#include "content/shell/test_runner/web_widget_test_client.h" +#include "content/shell/test_runner/test_runner_for_specific_view.h" +#include "content/shell/test_runner/text_input_controller.h" #include "content/shell/test_runner/web_widget_test_proxy.h" #include "third_party/blink/public/platform/web_drag_operation.h" #include "third_party/blink/public/platform/web_rect.h" @@ -30,11 +31,9 @@ #include "third_party/blink/public/web/web_widget_client.h" namespace blink { -class WebDragData; class WebLocalFrame; class WebString; class WebView; -class WebWidget; struct WebWindowFeatures; } @@ -46,137 +45,24 @@ class WebTestDelegate; class WebTestInterfaces; -// A WebWidgetClient that manages calls to a client for testing, as well as a -// real client in the WebViewTestProxy base class. -// The |base_class_widget_client| is a real production WebWidgetClient, while -// the |test_widget_client| is a test-only WebWidgetClient. Mostly calls are -// forwarded to the |base_class_widget_client|, but some are intercepted and -// sent to the |test_widget_client| instead, or to both. -class TEST_RUNNER_EXPORT ProxyWebWidgetClient : public blink::WebWidgetClient { - public: - ProxyWebWidgetClient(blink::WebWidgetClient* base_class_widget_client, - blink::WebWidgetClient* widget_test_client, - content::RenderWidget* render_widget); - - // blink::WebWidgetClient implementation. - void SetRootLayer(scoped_refptr<cc::Layer>) override; - void ScheduleAnimation() override; - void IntrinsicSizingInfoChanged( - const blink::WebIntrinsicSizingInfo&) override; - void DidMeaningfulLayout(blink::WebMeaningfulLayout) override; - void DidFirstLayoutAfterFinishedParsing() override; - void DidChangeCursor(const blink::WebCursorInfo&) override; - void AutoscrollStart(const blink::WebFloatPoint&) override; - void AutoscrollFling(const blink::WebFloatSize& velocity) override; - void AutoscrollEnd() override; - void CloseWidgetSoon() override; - void Show(blink::WebNavigationPolicy) override; - blink::WebRect WindowRect() override; - void SetWindowRect(const blink::WebRect&) override; - blink::WebRect ViewRect() override; - void SetToolTipText(const blink::WebString&, - blink::WebTextDirection hint) override; - bool RequestPointerLock() override; - void RequestPointerUnlock() override; - bool IsPointerLocked() override; - void DidHandleGestureEvent(const blink::WebGestureEvent& event, - bool event_cancelled) override; - void DidOverscroll(const blink::WebFloatSize& overscroll_delta, - const blink::WebFloatSize& accumulated_overscroll, - const blink::WebFloatPoint& position_in_viewport, - const blink::WebFloatSize& velocity_in_viewport, - const cc::OverscrollBehavior& behavior) override; - void HasTouchEventHandlers(bool) override; - void SetNeedsLowLatencyInput(bool) override; - void RequestUnbufferedInputEvents() override; - void SetTouchAction(blink::WebTouchAction touch_action) override; - void ShowVirtualKeyboardOnElementFocus() override; - void ConvertViewportToWindow(blink::WebRect* rect) override; - void ConvertWindowToViewport(blink::WebFloatRect* rect) override; - void StartDragging(network::mojom::ReferrerPolicy, - const blink::WebDragData&, - blink::WebDragOperationsMask, - const SkBitmap& drag_image, - const gfx::Point& drag_image_offset) override; - - private: - blink::WebWidgetClient* base_class_widget_client_; - blink::WebWidgetClient* widget_test_client_; - content::RenderWidget* render_widget_; -}; - -// WebViewTestProxyBase is the "brain" of WebViewTestProxy in the sense that -// WebViewTestProxy does the bridge between RenderViewImpl and -// WebViewTestProxyBase and when it requires a behavior to be different from the -// usual, it will call WebViewTestProxyBase that implements the expected -// behavior. See WebViewTestProxy class comments for more information. +// WebViewTestProxy is used to run web tests. This class is a partial fake +// implementation of RenderViewImpl that overrides the minimal necessary +// portions of RenderViewImpl to allow for use in web tests. // -// Uses private inheritence to ensure that code doesn't assume WebViews are -// WebWidgets, and gets to the WebWidget through an accessor instead. -class TEST_RUNNER_EXPORT WebViewTestProxyBase : private WebWidgetTestProxyBase { - public: - blink::WebView* web_view() { return web_view_; } - void set_web_view(blink::WebView* view) { - DCHECK(view); - DCHECK(!web_view_); - web_view_ = view; - } - - WebTestDelegate* delegate() { return delegate_; } - TestInterfaces* test_interfaces() { return test_interfaces_; } - AccessibilityController* accessibility_controller() { - return accessibility_controller_.get(); - } - TestRunnerForSpecificView* view_test_runner() { - return view_test_runner_.get(); - } - - void Reset(); - void BindTo(blink::WebLocalFrame* frame); - - void GetScreenOrientationForTesting(blink::WebScreenInfo&); - - WebWidgetTestProxyBase* web_widget_test_proxy_base() { return this; } - - protected: - WebViewTestProxyBase(); - ~WebViewTestProxyBase(); - - void set_delegate(WebTestDelegate* delegate) { delegate_ = delegate; } - void set_test_interfaces(TestInterfaces* interfaces) { - test_interfaces_ = interfaces; - } - - private: - TestInterfaces* test_interfaces_ = nullptr; - WebTestDelegate* delegate_ = nullptr; - blink::WebView* web_view_ = nullptr; - blink::WebWidget* web_widget_ = nullptr; - std::unique_ptr<AccessibilityController> accessibility_controller_; - std::unique_ptr<TextInputController> text_input_controller_; - std::unique_ptr<TestRunnerForSpecificView> view_test_runner_; - - DISALLOW_COPY_AND_ASSIGN(WebViewTestProxyBase); -}; - -// WebViewTestProxy is used during running web tests. The intent of that class -// is to wrap RenderViewImpl for tests purposes in order to reduce the amount of -// test specific code in the production code. +// This method of injecting test functionality is an outgrowth of legacy. +// In particular, classic dependency injection does not work easily +// because the RenderWidget class is too large with too much entangled +// state, making it hard to factor out creation points for injection. // -// WebViewTestProxy is only doing the glue between RenderViewImpl and -// WebViewTestProxyBase, that means that there is no logic living in this class -// except deciding which base class should be called (could be both). +// While implementing a fake via partial overriding of a class leads to +// a fragile base class problem and implicit coupling of the test code +// and production code, it is the most viable mechanism available without +// a huge refactor. // -// Examples of usage: -// * when a fooClient has a mock implementation, WebViewTestProxy can override -// the fooClient() call and have WebViewTestProxyBase return the mock -// implementation. -// * when a value needs to be overridden by web tests, WebViewTestProxy can -// override RenderViewImpl's getter and call a getter from -// WebViewTestProxyBase instead. In addition, WebViewTestProxyBase will have -// a public setter that could be called from the TestRunner. -class TEST_RUNNER_EXPORT WebViewTestProxy : public content::RenderViewImpl, - public WebViewTestProxyBase { +// Historically, the overridden functionality has been small enough to not +// cause too much trouble. If that changes, then this entire testing +// architecture should be revisited. +class TEST_RUNNER_EXPORT WebViewTestProxy : public content::RenderViewImpl { public: template <typename... Args> explicit WebViewTestProxy(Args&&... args) @@ -197,17 +83,34 @@ blink::WebString AcceptLanguages() override; void DidFocus(blink::WebLocalFrame* calling_frame) override; blink::WebScreenInfo GetScreenInfo() override; - blink::WebWidgetClient* WidgetClient() override; // Exposed for our TestRunner harness. using RenderViewImpl::ApplyPageHidden; + WebTestDelegate* delegate() { return delegate_; } + TestInterfaces* test_interfaces() { return test_interfaces_; } + AccessibilityController* accessibility_controller() { + return &accessibility_controller_; + } + TestRunnerForSpecificView* view_test_runner() { return &view_test_runner_; } + + void Reset(); + void BindTo(blink::WebLocalFrame* frame); + + void GetScreenOrientationForTesting(blink::WebScreenInfo&); + private: // RenderViewImpl has no public destructor. ~WebViewTestProxy() override; - std::unique_ptr<WebViewTestClient> view_test_client_; - std::unique_ptr<blink::WebWidgetClient> widget_client_; + TestRunner* GetTestRunner(); + + TestInterfaces* test_interfaces_ = nullptr; + WebTestDelegate* delegate_ = nullptr; + + AccessibilityController accessibility_controller_{this}; + TextInputController text_input_controller_{this}; + TestRunnerForSpecificView view_test_runner_{this}; DISALLOW_COPY_AND_ASSIGN(WebViewTestProxy); };
diff --git a/content/shell/test_runner/web_widget_test_client.cc b/content/shell/test_runner/web_widget_test_client.cc deleted file mode 100644 index 4b5b59f4..0000000 --- a/content/shell/test_runner/web_widget_test_client.cc +++ /dev/null
@@ -1,116 +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 "content/shell/test_runner/web_widget_test_client.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/logging.h" -#include "base/time/time.h" -#include "content/shell/test_runner/event_sender.h" -#include "content/shell/test_runner/test_interfaces.h" -#include "content/shell/test_runner/test_runner.h" -#include "content/shell/test_runner/test_runner_for_specific_view.h" -#include "content/shell/test_runner/web_test_delegate.h" -#include "content/shell/test_runner/web_view_test_proxy.h" -#include "content/shell/test_runner/web_widget_test_proxy.h" -#include "third_party/blink/public/platform/web_screen_info.h" -#include "third_party/blink/public/web/web_page_popup.h" -#include "third_party/blink/public/web/web_view.h" -#include "third_party/blink/public/web/web_widget.h" - -namespace test_runner { - -WebWidgetTestClient::WebWidgetTestClient( - WebWidgetTestProxyBase* web_widget_test_proxy_base) - : web_widget_test_proxy_base_(web_widget_test_proxy_base), - animation_scheduled_(false), - weak_factory_(this) { - DCHECK(web_widget_test_proxy_base_); -} - -WebWidgetTestClient::~WebWidgetTestClient() {} - -void WebWidgetTestClient::ScheduleAnimation() { - if (!test_runner()->TestIsRunning()) - return; - - if (!animation_scheduled_) { - animation_scheduled_ = true; - delegate()->PostDelayedTask(base::BindOnce(&WebWidgetTestClient::AnimateNow, - weak_factory_.GetWeakPtr()), - base::TimeDelta::FromMilliseconds(1)); - } -} - -void WebWidgetTestClient::AnimateNow() { - if (!animation_scheduled_) - return; - - animation_scheduled_ = false; - bool animation_requires_raster = test_runner()->animation_requires_raster(); - blink::WebWidget* web_widget = web_widget_test_proxy_base_->web_widget(); - web_widget->UpdateAllLifecyclePhasesAndCompositeForTesting( - animation_requires_raster); - - // If this is the main frame, we composite the current PagePopup with the - // widget. - // TODO(danakj): This means that an OOPIF's popup, which is attached to a - // WebView without a main frame, would have no opportunity to execute this - // method call. - if (web_widget_test_proxy_base_->main_frame_widget()) { - blink::WebView* view = - web_widget_test_proxy_base_->web_view_test_proxy_base()->web_view(); - if (blink::WebPagePopup* popup = view->GetPagePopup()) { - popup->UpdateAllLifecyclePhasesAndCompositeForTesting( - animation_requires_raster); - } - } -} - -bool WebWidgetTestClient::RequestPointerLock() { - return view_test_runner()->RequestPointerLock(); -} - -void WebWidgetTestClient::RequestPointerUnlock() { - view_test_runner()->RequestPointerUnlock(); -} - -bool WebWidgetTestClient::IsPointerLocked() { - return view_test_runner()->isPointerLocked(); -} - -void WebWidgetTestClient::SetToolTipText(const blink::WebString& text, - blink::WebTextDirection direction) { - test_runner()->setToolTipText(text); -} - -void WebWidgetTestClient::StartDragging(network::mojom::ReferrerPolicy policy, - const blink::WebDragData& data, - blink::WebDragOperationsMask mask, - const SkBitmap& drag_image, - const gfx::Point& image_offset) { - test_runner()->setDragImage(drag_image); - - // When running a test, we need to fake a drag drop operation otherwise - // Windows waits for real mouse events to know when the drag is over. - web_widget_test_proxy_base_->event_sender()->DoDragDrop(data, mask); -} - -TestRunnerForSpecificView* WebWidgetTestClient::view_test_runner() { - return web_widget_test_proxy_base_->web_view_test_proxy_base() - ->view_test_runner(); -} - -WebTestDelegate* WebWidgetTestClient::delegate() { - return web_widget_test_proxy_base_->web_view_test_proxy_base()->delegate(); -} - -TestRunner* WebWidgetTestClient::test_runner() { - return web_widget_test_proxy_base_->web_view_test_proxy_base() - ->test_interfaces() - ->GetTestRunner(); -} - -} // namespace test_runner
diff --git a/content/shell/test_runner/web_widget_test_client.h b/content/shell/test_runner/web_widget_test_client.h deleted file mode 100644 index 1db3a110..0000000 --- a/content/shell/test_runner/web_widget_test_client.h +++ /dev/null
@@ -1,65 +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 CONTENT_SHELL_TEST_RUNNER_WEB_WIDGET_TEST_CLIENT_H_ -#define CONTENT_SHELL_TEST_RUNNER_WEB_WIDGET_TEST_CLIENT_H_ - -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "third_party/blink/public/web/web_widget_client.h" - -namespace test_runner { - -class TestRunner; -class TestRunnerForSpecificView; -class WebTestDelegate; -class WebWidgetTestProxyBase; - -// WebWidgetTestClient implements WebWidgetClient interface, providing behavior -// expected by tests. WebWidgetTestClient ends up used by WebViewTestProxy -// which coordinates forwarding WebWidgetClient calls either to -// WebWidgetTestClient or to the product code (i.e. currently to -// RenderViewImpl). -class WebWidgetTestClient : public blink::WebWidgetClient { - public: - // Caller has to ensure that all arguments (i.e. |test_runner| and |delegate|) - // live longer than |this|. - explicit WebWidgetTestClient( - WebWidgetTestProxyBase* web_widget_test_proxy_base); - - ~WebWidgetTestClient() override; - - // WebWidgetClient overrides needed by WebWidgetTestProxy. - void ScheduleAnimation() override; - bool RequestPointerLock() override; - void RequestPointerUnlock() override; - bool IsPointerLocked() override; - void SetToolTipText(const blink::WebString& text, - blink::WebTextDirection direction) override; - void StartDragging(network::mojom::ReferrerPolicy policy, - const blink::WebDragData& data, - blink::WebDragOperationsMask mask, - const SkBitmap& drag_image, - const gfx::Point& image_offset) override; - - private: - void AnimateNow(); - - WebTestDelegate* delegate(); - TestRunnerForSpecificView* view_test_runner(); - TestRunner* test_runner(); - - // Borrowed pointer to WebWidgetTestProxyBase. - WebWidgetTestProxyBase* web_widget_test_proxy_base_; - - bool animation_scheduled_; - - base::WeakPtrFactory<WebWidgetTestClient> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(WebWidgetTestClient); -}; - -} // namespace test_runner - -#endif // CONTENT_SHELL_TEST_RUNNER_WEB_WIDGET_TEST_CLIENT_H_
diff --git a/content/shell/test_runner/web_widget_test_proxy.cc b/content/shell/test_runner/web_widget_test_proxy.cc index 5b4da3c..e3961a1d 100644 --- a/content/shell/test_runner/web_widget_test_proxy.cc +++ b/content/shell/test_runner/web_widget_test_proxy.cc
@@ -5,69 +5,59 @@ #include "content/shell/test_runner/web_widget_test_proxy.h" #include "content/renderer/compositor/layer_tree_view.h" -#include "content/shell/test_runner/event_sender.h" +#include "content/shell/test_runner/test_interfaces.h" +#include "content/shell/test_runner/test_runner.h" +#include "content/shell/test_runner/test_runner_for_specific_view.h" +#include "content/shell/test_runner/web_test_delegate.h" #include "content/shell/test_runner/web_test_interfaces.h" #include "content/shell/test_runner/web_view_test_proxy.h" +#include "third_party/blink/public/web/web_local_frame.h" +#include "third_party/blink/public/web/web_page_popup.h" +#include "third_party/blink/public/web/web_view.h" +#include "third_party/blink/public/web/web_widget.h" namespace test_runner { -WebWidgetTestProxyBase::WebWidgetTestProxyBase(bool main_frame_widget) - : main_frame_widget_(main_frame_widget), - event_sender_(std::make_unique<EventSender>(this)) {} - -WebWidgetTestProxyBase::~WebWidgetTestProxyBase() = default; - -void WebWidgetTestProxyBase::Reset() { - event_sender_->Reset(); -} - -void WebWidgetTestProxyBase::BindTo(blink::WebLocalFrame* frame) { - event_sender_->Install(frame); -} - -void WebWidgetTestProxy::Initialize( - WebTestInterfaces* interfaces, - blink::WebWidget* web_widget, - content::RenderViewImpl* render_view_for_local_root) { - // The RenderViewImpl will also be a test proxy type. - auto* view_proxy_for_local_root = - static_cast<WebViewTestProxy*>(render_view_for_local_root); - - // On WebWidgetTestProxyBase. - set_web_widget(web_widget); - set_web_view_test_proxy_base(view_proxy_for_local_root); - set_widget_test_client(std::make_unique<WebWidgetTestClient>(this)); -} - void WebWidgetTestProxy::ScheduleAnimation() { + if (!GetTestRunner()->TestIsRunning()) + return; + // When using threaded compositing, have the RenderWidget schedule a request // for a frame, as we use the compositor's scheduler. Otherwise the testing // WebWidgetClient schedules it. // Note that for WebWidgetTestProxy the RenderWidget is subclassed to override // the WebWidgetClient, so we must call up to the base class RenderWidget // explicitly here to jump out of the test harness as intended. - if (!RenderWidget::layer_tree_view()->CompositeIsSynchronousForTesting()) + if (!RenderWidget::layer_tree_view()->CompositeIsSynchronousForTesting()) { RenderWidget::ScheduleAnimation(); - else - widget_test_client()->ScheduleAnimation(); + return; + } + + if (!animation_scheduled_) { + animation_scheduled_ = true; + GetWebViewTestProxy()->delegate()->PostDelayedTask( + base::BindOnce(&WebWidgetTestProxy::AnimateNow, + weak_factory_.GetWeakPtr()), + base::TimeDelta::FromMilliseconds(1)); + } } bool WebWidgetTestProxy::RequestPointerLock() { - return widget_test_client()->RequestPointerLock(); + return GetViewTestRunner()->RequestPointerLock(); } void WebWidgetTestProxy::RequestPointerUnlock() { - widget_test_client()->RequestPointerUnlock(); + return GetViewTestRunner()->RequestPointerUnlock(); } bool WebWidgetTestProxy::IsPointerLocked() { - return widget_test_client()->IsPointerLocked(); + return GetViewTestRunner()->isPointerLocked(); } void WebWidgetTestProxy::SetToolTipText(const blink::WebString& text, blink::WebTextDirection hint) { RenderWidget::SetToolTipText(text, hint); - widget_test_client()->SetToolTipText(text, hint); + GetTestRunner()->setToolTipText(text); } void WebWidgetTestProxy::StartDragging(network::mojom::ReferrerPolicy policy, @@ -75,12 +65,95 @@ blink::WebDragOperationsMask mask, const SkBitmap& drag_image, const gfx::Point& image_offset) { - widget_test_client()->StartDragging(policy, data, mask, drag_image, - image_offset); - // Don't forward this call to RenderWidget because we don't want to do a - // real drag-and-drop. + GetTestRunner()->setDragImage(drag_image); + + // When running a test, we need to fake a drag drop operation otherwise + // Windows waits for real mouse events to know when the drag is over. + event_sender()->DoDragDrop(data, mask); +} + +WebViewTestProxy* WebWidgetTestProxy::GetWebViewTestProxy() { + if (delegate()) { + // TODO(https://crbug.com/545684): Because WebViewImpl still inherits + // from WebWidget and infact, before a frame is attached, IS actually + // the WebWidget used in blink, it is not possible to walk the object + // relations in the blink side to find the associated RenderViewImpl + // consistently. Thus, here, just directly cast the delegate(). Since + // all creations of RenderViewImpl in the test_runner layer haved been + // shimmed to return a WebViewTestProxy, it is safe to downcast here. + return static_cast<WebViewTestProxy*>(delegate()); + } else { + blink::WebWidget* web_widget = GetWebWidget(); + CHECK(web_widget->IsWebFrameWidget()); + blink::WebView* web_view = + static_cast<blink::WebFrameWidget*>(web_widget)->LocalRoot()->View(); + + content::RenderView* render_view = + content::RenderView::FromWebView(web_view); + // RenderViews are always WebViewTestProxy within the test_runner namespace. + return static_cast<WebViewTestProxy*>(render_view); + } +} + +void WebWidgetTestProxy::Reset() { + event_sender_.Reset(); +} + +void WebWidgetTestProxy::BindTo(blink::WebLocalFrame* frame) { + event_sender_.Install(frame); } WebWidgetTestProxy::~WebWidgetTestProxy() = default; +TestRunnerForSpecificView* WebWidgetTestProxy::GetViewTestRunner() { + return GetWebViewTestProxy()->view_test_runner(); +} + +TestRunner* WebWidgetTestProxy::GetTestRunner() { + return GetWebViewTestProxy()->test_interfaces()->GetTestRunner(); +} + +void WebWidgetTestProxy::AnimateNow() { + if (!animation_scheduled_) + return; + + // For child local roots, it's possible that the backing WebWidget gets + // closed between the ScheduleAnimation() call and this execution + // leading to a nullptr. This happens because child local roots are + // owned by RenderFrames which drops the WebWidget before executing the + // Close() call that would invalidate the |weak_factory_| canceling the + // scheduled calls to AnimateNow(). In main frames, the WebWidget is + // dropped synchronously by Close() avoiding the problem. + // + // Ideally there would not be this divergence between frame types, and/or + // there would be a hook for signaling a stop to the animation. As this is + // not an ideal work, returning early when GetWebWidget() returns nullptr + // is good enough for a fake impl. Also, unicorns are mythical. Sorry. + if (!GetWebWidget()) + return; + + animation_scheduled_ = false; + CHECK(GetTestRunner()); + bool animation_requires_raster = GetTestRunner()->animation_requires_raster(); + blink::WebWidget* web_widget = GetWebWidget(); + CHECK(web_widget); + web_widget->UpdateAllLifecyclePhasesAndCompositeForTesting( + animation_requires_raster); + + // If this RenderWidget is attached to a RenderView, we composite the + // current PagePopup with the widget. + // + // TODO(danakj): This means that an OOPIF's popup, which is attached to a + // WebView without a main frame, would have no opportunity to execute this + // method call. + if (delegate()) { + blink::WebView* view = GetWebViewTestProxy()->webview(); + CHECK(view); + if (blink::WebPagePopup* popup = view->GetPagePopup()) { + popup->UpdateAllLifecyclePhasesAndCompositeForTesting( + animation_requires_raster); + } + } +} + } // namespace test_runner
diff --git a/content/shell/test_runner/web_widget_test_proxy.h b/content/shell/test_runner/web_widget_test_proxy.h index 1d13c097..e388422 100644 --- a/content/shell/test_runner/web_widget_test_proxy.h +++ b/content/shell/test_runner/web_widget_test_proxy.h
@@ -6,18 +6,19 @@ #define CONTENT_SHELL_TEST_RUNNER_WEB_WIDGET_TEST_PROXY_H_ #include <memory> +#include <utility> #include "base/logging.h" #include "base/macros.h" +#include "base/memory/weak_ptr.h" #include "content/renderer/render_widget.h" +#include "content/shell/test_runner/event_sender.h" #include "content/shell/test_runner/test_runner_export.h" -#include "content/shell/test_runner/web_widget_test_client.h" #include "third_party/blink/public/web/web_widget_client.h" namespace blink { class WebLocalFrame; class WebString; -class WebWidget; } namespace content { @@ -26,86 +27,35 @@ namespace test_runner { +class TestRunner; +class TestRunnerForSpecificView; class EventSender; -class WebTestInterfaces; -class WebViewTestProxyBase; +class WebViewTestProxy; -class TEST_RUNNER_EXPORT WebWidgetTestProxyBase { - public: - blink::WebWidget* web_widget() { return web_widget_; } - void set_web_widget(blink::WebWidget* widget) { - DCHECK(widget); - DCHECK(!web_widget_); - web_widget_ = widget; - } - - void set_widget_test_client( - std::unique_ptr<WebWidgetTestClient> widget_test_client) { - DCHECK(widget_test_client); - DCHECK(!widget_test_client_); - widget_test_client_ = std::move(widget_test_client); - } - - WebViewTestProxyBase* web_view_test_proxy_base() const { - return web_view_test_proxy_base_; - } - void set_web_view_test_proxy_base( - WebViewTestProxyBase* web_view_test_proxy_base) { - DCHECK(web_view_test_proxy_base); - DCHECK(!web_view_test_proxy_base_); - web_view_test_proxy_base_ = web_view_test_proxy_base; - } - - bool main_frame_widget() const { return main_frame_widget_; } - EventSender* event_sender() { return event_sender_.get(); } - - void Reset(); - void BindTo(blink::WebLocalFrame* frame); - - protected: - explicit WebWidgetTestProxyBase(bool main_frame_widget); - ~WebWidgetTestProxyBase(); - - blink::WebWidgetClient* widget_test_client() { - return widget_test_client_.get(); - } - - private: - const bool main_frame_widget_; - blink::WebWidget* web_widget_ = nullptr; - WebViewTestProxyBase* web_view_test_proxy_base_ = nullptr; - std::unique_ptr<WebWidgetTestClient> widget_test_client_; - std::unique_ptr<EventSender> event_sender_; - - DISALLOW_COPY_AND_ASSIGN(WebWidgetTestProxyBase); -}; - -// WebWidgetTestProxy is used during running web tests. The intent of the class -// is to wrap RenderWidget for tests purposes in order to reduce the amount of -// test specific code in the production code. +// WebWidgetTestProxy is used to run web tests. This class is a partial fake +// implementation of RenderWidget that overrides the minimal necessary portions +// of RenderWidget to allow for use in web tests. // -// WebWidgetTestProxy is only doing the glue between RenderWidget and -// WebWidgetTestProxyBase, that means that there is no logic living in this -// class except deciding which base class should be called (could be both). +// This method of injecting test functionality is an outgrowth of legacy. +// In particular, classic dependency injection does not work easily +// because the RenderWidget class is too large with too much entangled +// stated, and complex creation (subclass using heavy implementation +// inheritance, multiple modes of operation for frames/popups/fullscreen, etc) +// making it hard to factor our creation points for injection. // -// Examples of usage: -// * when a fooClient has a mock implementation, WebWidgetTestProxy can -// override the fooClient() call and have WebWidgetTestProxyBase return the -// mock implementation. -// * when a value needs to be overridden by web tests, WebWidgetTestProxy can -// override RenderViewImpl's getter and call a getter from -// WebWidgetTestProxyBase instead. In addition, WebWidgetTestProxyBase will -// have a public setter that could be called from the TestRunner. -class TEST_RUNNER_EXPORT WebWidgetTestProxy : public content::RenderWidget, - public WebWidgetTestProxyBase { +// While implementing a fake via partial overriding of a class leads to +// a fragile base class problem and implicit coupling of the test code +// and production code, it is the most viable mechanism available with a huge +// refactor. +// +// Historically, the overridden functionality has been small enough to not +// cause too much trouble. If that changes, then this entire testing +// architecture should be revisited. +class TEST_RUNNER_EXPORT WebWidgetTestProxy : public content::RenderWidget { public: template <typename... Args> explicit WebWidgetTestProxy(Args&&... args) - : RenderWidget(std::forward<Args>(args)...), - WebWidgetTestProxyBase(/*main_frame_widget=*/false) {} - void Initialize(WebTestInterfaces* interfaces, - blink::WebWidget* web_widget, - content::RenderViewImpl* render_view_for_local_root); + : RenderWidget(std::forward<Args>(args)...) {} // WebWidgetClient implementation. void ScheduleAnimation() override; @@ -120,10 +70,32 @@ const SkBitmap& drag_image, const gfx::Point& image_offset) override; + // In the test runner code, it can be expected that the RenderViewImpl will + // actually be a WebViewTestProxy as the creation of RenderView/Frame/Widget + // are all hooked at the same time to provide a consistent set of fake + // objects. + WebViewTestProxy* GetWebViewTestProxy(); + + EventSender* event_sender() { return &event_sender_; } + void Reset(); + void BindTo(blink::WebLocalFrame* frame); + private: - // RenderWidet does not have a public destructor. + // RenderWidget does not have a public destructor. ~WebWidgetTestProxy() override; + TestRunnerForSpecificView* GetViewTestRunner(); + TestRunner* GetTestRunner(); + + void AnimateNow(); + + EventSender event_sender_{this}; + + // For collapsing multiple simulated ScheduleAnimation() calls. + bool animation_scheduled_ = false; + + base::WeakPtrFactory<WebWidgetTestProxy> weak_factory_{this}; + DISALLOW_COPY_AND_ASSIGN(WebWidgetTestProxy); };
diff --git a/content/test/navigation_simulator_impl.cc b/content/test/navigation_simulator_impl.cc index f0cf1afb..f2151552 100644 --- a/content/test/navigation_simulator_impl.cc +++ b/content/test/navigation_simulator_impl.cc
@@ -311,7 +311,7 @@ frame_tree_node_(render_frame_host ? render_frame_host->frame_tree_node() : web_contents->GetMainFrame()->frame_tree_node()), - handle_(nullptr), + request_(nullptr), navigation_url_(original_url), socket_address_("2001:db8::1", 80), initial_method_("GET"), @@ -349,20 +349,21 @@ void NavigationSimulatorImpl::InitializeFromStartedRequest( NavigationRequest* request) { - NavigationHandle* handle = request->navigation_handle(); - DCHECK(handle); - CHECK_LE(NavigationRequest::STARTED, request->state()); - state_ = STARTED; + CHECK(request); + request_ = request; + NavigationHandleImpl* handle = request_->navigation_handle(); + CHECK(handle); + CHECK_LE(NavigationRequest::STARTED, request_->state()); CHECK_EQ(web_contents_, handle->GetWebContents()); CHECK(render_frame_host_); - CHECK_EQ(frame_tree_node_, request->frame_tree_node()); - handle_ = static_cast<NavigationHandleImpl*>(handle); + CHECK_EQ(frame_tree_node_, request_->frame_tree_node()); + state_ = STARTED; navigation_url_ = handle->GetURL(); // |socket_address_| cannot be inferred from the request. // |initial_method_| cannot be set after the request has started. - browser_initiated_ = request->browser_initiated(); + browser_initiated_ = request_->browser_initiated(); // |same_document_| should always be false here. - referrer_ = request->common_params().referrer; + referrer_ = request_->common_params().referrer; transition_ = handle->GetPageTransition(); // |reload_type_| cannot be set after the request has started. // |session_history_offset_| cannot be set after the request has started. @@ -374,7 +375,7 @@ // has already been created. num_did_start_navigation_called_++; RegisterTestThrottle(handle); - PrepareCompleteCallbackOnHandle(); + PrepareCompleteCallbackOnHandle(handle); } void NavigationSimulatorImpl::RegisterTestThrottle(NavigationHandle* handle) { @@ -404,7 +405,7 @@ } state_ = STARTED; - CHECK(handle_); + CHECK(request_); if (IsRendererDebugURL(navigation_url_)) return; @@ -447,7 +448,7 @@ int previous_did_redirect_navigation_called = num_did_redirect_navigation_called_; - PrepareCompleteCallbackOnHandle(); + PrepareCompleteCallbackOnHandle(request_->navigation_handle()); NavigationRequest* request = frame_tree_node_->navigation_request(); CHECK(request) << "Trying to redirect a navigation that does not go to the " "network stack."; @@ -503,7 +504,7 @@ return; } - PrepareCompleteCallbackOnHandle(); + PrepareCompleteCallbackOnHandle(request_->navigation_handle()); if (frame_tree_node_->navigation_request()) { static_cast<TestRenderFrameHost*>(frame_tree_node_->current_frame_host()) ->PrepareForCommitDeprecatedForNavigationSimulator( @@ -511,7 +512,7 @@ } // Synchronous failure can cause the navigation to finish here. - if (!handle_) { + if (!request_) { state_ = FAILED; return; } @@ -539,12 +540,13 @@ CHECK_EQ(1, num_ready_to_commit_called_); } - request_id_ = handle_->GetGlobalRequestID(); + NavigationHandleImpl* handle = request_->navigation_handle(); + request_id_ = handle->GetGlobalRequestID(); // Update the RenderFrameHost now that we know which RenderFrameHost will // commit the navigation. render_frame_host_ = - static_cast<TestRenderFrameHost*>(handle_->GetRenderFrameHost()); + static_cast<TestRenderFrameHost*>(handle->GetRenderFrameHost()); state_ = READY_TO_COMMIT; } @@ -575,19 +577,19 @@ document_interface_broker_blink_request_ = nullptr; } - if (handle_) { + if (request_) { scoped_refptr<net::HttpResponseHeaders> response_headers = new net::HttpResponseHeaders(std::string()); response_headers->AddHeader(std::string("Content-Type: ") + contents_mime_type_); - handle_->set_response_headers_for_testing(response_headers); + request_->navigation_handle()->set_response_headers_for_testing( + response_headers); } auto params = BuildDidCommitProvisionalLoadParams( false /* same_document */, false /* failed_navigation */); render_frame_host_->SimulateCommitProcessed( - handle_->navigation_request(), std::move(params), - std::move(interface_provider_request_), + request_, std::move(params), std::move(interface_provider_request_), std::move(document_interface_broker_content_request_), std::move(document_interface_broker_blink_request_), same_document_); @@ -618,7 +620,7 @@ CHECK(render_frame_host_) << "NavigationSimulatorImpl::AbortCommit can only be " "called for navigations that commit."; - render_frame_host_->AbortCommit(handle_->navigation_request()); + render_frame_host_->AbortCommit(request_); state_ = FINISHED; CHECK_EQ(1, num_did_finish_navigation_called_); @@ -638,17 +640,16 @@ if (state_ == INITIALIZATION) Start(); - CHECK(!handle_->GetResponseHeaders()); - static_cast<NavigationHandleImpl*>(handle_)->set_response_headers_for_testing( - response_headers); + NavigationHandleImpl* handle = request_->navigation_handle(); + CHECK(!handle->GetResponseHeaders()); + handle->set_response_headers_for_testing(response_headers); state_ = FAILED; - PrepareCompleteCallbackOnHandle(); - NavigationRequest* request = frame_tree_node_->navigation_request(); - CHECK(request); + PrepareCompleteCallbackOnHandle(handle); + CHECK(request_); TestNavigationURLLoader* url_loader = - static_cast<TestNavigationURLLoader*>(request->loader_for_testing()); + static_cast<TestNavigationURLLoader*>(request_->loader_for_testing()); CHECK(url_loader); url_loader->SimulateError(error_code); @@ -682,8 +683,8 @@ CHECK_EQ(0, num_did_finish_navigation_called_); // Update the RenderFrameHost now that we know which RenderFrameHost will // commit the error page. - render_frame_host_ = - static_cast<TestRenderFrameHost*>(handle_->GetRenderFrameHost()); + render_frame_host_ = static_cast<TestRenderFrameHost*>( + request_->navigation_handle()->GetRenderFrameHost()); } } @@ -704,8 +705,7 @@ auto params = BuildDidCommitProvisionalLoadParams( false /* same_document */, true /* failed_navigation */); render_frame_host_->SimulateCommitProcessed( - handle_->navigation_request(), std::move(params), - std::move(interface_provider_request_), + request_, std::move(params), std::move(interface_provider_request_), std::move(document_interface_broker_content_request_), std::move(document_interface_broker_blink_request_), false /* same_document */); @@ -740,8 +740,7 @@ document_interface_broker_blink_request_ = nullptr; render_frame_host_->SimulateCommitProcessed( - handle_ ? handle_->navigation_request() : nullptr, std::move(params), - nullptr /* interface_provider_request_ */, + request_, std::move(params), nullptr /* interface_provider_request_ */, nullptr /* document_interface_broker_content_handle */, nullptr /* document_interface_broker_blink_handle */, true /* same_document */); @@ -855,7 +854,7 @@ NavigationHandle* NavigationSimulatorImpl::GetNavigationHandle() const { CHECK_EQ(STARTED, state_); - return handle_; + return request_->navigation_handle(); } content::GlobalRequestID NavigationSimulatorImpl::GetGlobalRequestID() const { @@ -896,7 +895,7 @@ void NavigationSimulatorImpl::DidStartNavigation( NavigationHandle* navigation_handle) { // Check if this navigation is the one we're simulating. - if (handle_) + if (request_) return; NavigationHandleImpl* handle = @@ -905,32 +904,34 @@ if (handle->frame_tree_node() != frame_tree_node_) return; - handle_ = handle; - + request_ = handle->navigation_request(); num_did_start_navigation_called_++; // Add a throttle to count NavigationThrottle calls count. RegisterTestThrottle(handle); - PrepareCompleteCallbackOnHandle(); + PrepareCompleteCallbackOnHandle(handle); } void NavigationSimulatorImpl::DidRedirectNavigation( NavigationHandle* navigation_handle) { - if (navigation_handle == handle_) + if (request_ && navigation_handle == request_->navigation_handle()) num_did_redirect_navigation_called_++; } void NavigationSimulatorImpl::ReadyToCommitNavigation( NavigationHandle* navigation_handle) { - if (navigation_handle == handle_) + if (request_ && navigation_handle == request_->navigation_handle()) num_ready_to_commit_called_++; } void NavigationSimulatorImpl::DidFinishNavigation( NavigationHandle* navigation_handle) { - if (navigation_handle == handle_) { + NavigationRequest* request = + static_cast<NavigationHandleImpl*>(navigation_handle) + ->navigation_request(); + if (request == request_) { num_did_finish_navigation_called_++; - handle_ = nullptr; + request_ = nullptr; } } @@ -971,7 +972,7 @@ // We don't create NavigationRequests nor NavigationHandles for a // navigation to a renderer-debug URL. Instead, the URL is passed to the // current RenderFrameHost so that the renderer process can handle it. - CHECK(!handle_); + CHECK(!request_); CHECK(web_contents_->GetMainFrame()->is_loading()); // A navigation to a renderer-debug URL cannot commit. Simulate the @@ -981,24 +982,24 @@ web_contents_->GetMainFrame()->GetRoutingID())); state_ = FAILED; return false; - } else if (handle_ && + } else if (request_ && web_contents_->GetMainFrame()->GetNavigationHandle() == - handle_) { - CHECK(!IsURLHandledByNetworkStack(handle_->GetURL())); + request_->navigation_handle()) { + CHECK(!IsURLHandledByNetworkStack(request_->common_params().url)); return true; } else if (web_contents_->GetMainFrame() ->same_document_navigation_request() && web_contents_->GetMainFrame() ->same_document_navigation_request() - ->navigation_handle() == handle_) { - CHECK(handle_->IsSameDocument()); + ->navigation_handle() == request_->navigation_handle()) { + CHECK(request_->navigation_handle()->IsSameDocument()); same_document_ = true; return true; } return false; } - CHECK_EQ(handle_, request->navigation_handle()); + CHECK_EQ(request_, request); return true; } @@ -1050,7 +1051,7 @@ if (!request) return false; - CHECK_EQ(handle_, request->navigation_handle()); + CHECK_EQ(request_, request); return true; } @@ -1087,10 +1088,10 @@ std::move(throttle_checks_complete_closure_).Run(); } -void NavigationSimulatorImpl::PrepareCompleteCallbackOnHandle() { - CHECK(handle_); +void NavigationSimulatorImpl::PrepareCompleteCallbackOnHandle( + NavigationHandleImpl* handle) { last_throttle_check_result_.reset(); - handle_->set_complete_callback_for_testing( + handle->set_complete_callback_for_testing( base::BindOnce(&NavigationSimulatorImpl::OnThrottleChecksComplete, weak_factory_.GetWeakPtr())); } @@ -1190,9 +1191,7 @@ } else { params->origin = url::Origin::Create(navigation_url_); params->redirects.push_back(navigation_url_); - params->method = "GET"; - if (handle_ && handle_->IsPost()) - params->method = "POST"; + params->method = request_ ? request_->common_params().method : "GET"; params->http_status_code = 200; params->should_update_history = true; } @@ -1204,7 +1203,8 @@ params->page_state = PageState::CreateForTesting(navigation_url_, false, nullptr, nullptr); } else { - params->nav_entry_id = handle_->pending_nav_entry_id(); + CHECK(request_); + params->nav_entry_id = request_->nav_entry_id(); params->did_create_new_entry = DidCreateNewEntry(); // Simulate Blink assigning an item and document sequence number to the
diff --git a/content/test/navigation_simulator_impl.h b/content/test/navigation_simulator_impl.h index e01d209..a436e99 100644 --- a/content/test/navigation_simulator_impl.h +++ b/content/test/navigation_simulator_impl.h
@@ -164,7 +164,7 @@ // Helper method to set the OnThrottleChecksComplete callback on the // NavigationHandle. - void PrepareCompleteCallbackOnHandle(); + void PrepareCompleteCallbackOnHandle(NavigationHandleImpl* handle); // Check if the navigation corresponds to a same-document navigation. // Only use on renderer-initiated navigations. @@ -207,8 +207,8 @@ FrameTreeNode* frame_tree_node_; - // The NavigationHandle associated with this navigation. - NavigationHandleImpl* handle_; + // The NavigationRequest associated with this navigation. + NavigationRequest* request_; // Note: additional parameters to modify the navigation should be properly // initialized (if needed) in InitializeFromStartedRequest.
diff --git a/content/test/web_test_support.cc b/content/test/web_test_support.cc index 87f21954..1e7e7e1 100644 --- a/content/test/web_test_support.cc +++ b/content/test/web_test_support.cc
@@ -104,38 +104,18 @@ return render_view_proxy; } -RenderWidget* CreateRenderWidgetForChildLocalRoot( +scoped_refptr<RenderWidget> CreateRenderWidgetForFrame( int32_t routing_id, CompositorDependencies* compositor_deps, const ScreenInfo& screen_info, blink::WebDisplayMode display_mode, bool swapped_out, bool hidden, - bool never_visible) { - auto* render_widget_proxy = new test_runner::WebWidgetTestProxy( + bool never_visible, + mojom::WidgetRequest widget_request) { + return base::MakeRefCounted<test_runner::WebWidgetTestProxy>( routing_id, compositor_deps, screen_info, display_mode, swapped_out, - hidden, never_visible); - return render_widget_proxy; -} - -void RenderWidgetForChildLocalRootInitialized(RenderWidget* render_widget) { - test_runner::WebTestInterfaces* interfaces = - WebTestRenderThreadObserver::GetInstance()->test_interfaces(); - - blink::WebWidget* web_widget = render_widget->GetWebWidget(); - auto* web_frame_widget = static_cast<blink::WebFrameWidget*>(web_widget); - // RenderWidgets for a frame will have a local root with a RenderView. - blink::WebView* web_view = web_frame_widget->LocalRoot()->View(); - RenderView* render_view = content::RenderView::FromWebView(web_view); - // RenderViews are always RenderViewImpls internally. - auto* render_view_impl = static_cast<RenderViewImpl*>(render_view); - - // We are here because CreateWebWidgetTestProxy() was used to make the - // RenderWidget, and it creates a WebWidgetTestProxy instead, which is-a - // RenderWidget. - auto* render_widget_proxy = - static_cast<test_runner::WebWidgetTestProxy*>(render_widget); - render_widget_proxy->Initialize(interfaces, web_widget, render_view_impl); + hidden, never_visible, std::move(widget_request)); } RenderFrameImpl* CreateWebFrameTestProxy(RenderFrameImpl::CreateParams params) { @@ -170,56 +150,25 @@ } // namespace -test_runner::WebViewTestProxyBase* GetWebViewTestProxyBase( - RenderView* render_view) { - auto* render_view_proxy = - static_cast<test_runner::WebViewTestProxy*>(render_view); - return static_cast<test_runner::WebViewTestProxyBase*>(render_view_proxy); +test_runner::WebViewTestProxy* GetWebViewTestProxy(RenderView* render_view) { + return static_cast<test_runner::WebViewTestProxy*>(render_view); } -test_runner::WebFrameTestProxyBase* GetWebFrameTestProxyBase( - RenderFrame* render_frame) { - auto* render_frame_proxy = - static_cast<test_runner::WebFrameTestProxy*>(render_frame); - return static_cast<test_runner::WebFrameTestProxyBase*>(render_frame_proxy); -} - -test_runner::WebWidgetTestProxyBase* GetWebWidgetTestProxyBase( +test_runner::WebWidgetTestProxy* GetWebWidgetTestProxy( blink::WebLocalFrame* frame) { DCHECK(frame); RenderFrame* local_root = RenderFrame::FromWebFrame(frame->LocalRoot()); RenderFrameImpl* local_root_impl = static_cast<RenderFrameImpl*>(local_root); DCHECK(local_root); - // TODO(lfg): Simplify once RenderView no longer inherits from RenderWidget. - if (local_root->IsMainFrame()) { - // For main frames, since the RenderWidget is attached to the RenderView - // (subclassed by WebViewTestProxy), we grab the widget stuff through the - // view. - test_runner::WebViewTestProxyBase* web_view_test_proxy_base = - GetWebViewTestProxyBase(local_root->GetRenderView()); - return web_view_test_proxy_base->web_widget_test_proxy_base(); - } else { - // For sub frames, the RenderWidget is independent from the RenderView and - // hangs off the frame. The WebWidgetTestProxy then subclasses the - // RenderWidget since there's no RenderView in the way. From there we can - // go up to the WebWidgetTestProxyBase. - // - // Inheritance: - // RenderWidget WebWidgetTestProxyBase - // \\ // - // WebWidgetTestProxy - RenderWidget* render_widget = local_root_impl->GetLocalRootRenderWidget(); - auto* proxy = static_cast<test_runner::WebWidgetTestProxy*>(render_widget); - return static_cast<test_runner::WebWidgetTestProxyBase*>(proxy); - } + return static_cast<test_runner::WebWidgetTestProxy*>( + local_root_impl->GetLocalRootRenderWidget()); } void EnableWebTestProxyCreation() { RenderViewImpl::InstallCreateHook(CreateWebViewTestProxy); - RenderFrameImpl::InstallCreateHook(CreateWebFrameTestProxy, - CreateRenderWidgetForChildLocalRoot, - RenderWidgetForChildLocalRootInitialized); + RenderWidget::InstallCreateForFrameHook(CreateRenderWidgetForFrame); + RenderFrameImpl::InstallCreateHook(CreateWebFrameTestProxy); } void FetchManifest(blink::WebView* view, FetchManifestCallback callback) { @@ -457,33 +406,12 @@ } std::unique_ptr<blink::WebInputEvent> TransformScreenToWidgetCoordinates( - test_runner::WebWidgetTestProxyBase* web_widget_test_proxy_base, + test_runner::WebWidgetTestProxy* web_widget_test_proxy, const blink::WebInputEvent& event) { - DCHECK(web_widget_test_proxy_base); + DCHECK(web_widget_test_proxy); - // Two possible inheritance stories. - // A main frame: - // RenderWidget WebWidgetTestProxyBase - // \*\*\ (private) /*/*/ (private) - // RenderViewImpl WebViewTestProxyBase - // \\ // - // WebViewTestProxy - // - // And a sub frame: - // RenderWidget WebWidgetTestProxyBase - // \\ // - // WebWidgetTestProxy - RenderWidget* render_widget; - if (web_widget_test_proxy_base->main_frame_widget()) { - auto* proxy_base = web_widget_test_proxy_base->web_view_test_proxy_base(); - auto* proxy = static_cast<test_runner::WebViewTestProxy*>(proxy_base); - auto* view = static_cast<RenderViewImpl*>(proxy); - render_widget = view->GetWidget(); - } else { - auto* proxy = static_cast<test_runner::WebWidgetTestProxy*>( - web_widget_test_proxy_base); - render_widget = static_cast<RenderWidget*>(proxy); - } + RenderWidget* render_widget = + static_cast<RenderWidget*>(web_widget_test_proxy); blink::WebRect view_rect = render_widget->ViewRect(); float scale = GetWindowToViewportScale(render_widget);
diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..b44a1a7 --- /dev/null +++ b/docs/configuration.md
@@ -0,0 +1,144 @@ +# Configuration: Prefs, Settings, Features, Switches & Flags + +This document outlines all the runtime configuration surfaces of Chromium, +and discusses appropriate uses and standard patterns for each of them. Some of +these are intended for use by users, some by developers, and some by system +administrators. + +## Prefs + +Example: prefs::kAllowDinosaurEasterEgg aka "allow_dinosaur_easter_egg" + +Prefs are implemented by registering them with a central pref service, usually +via [Profile::RegisterProfilePrefs][profile-register]. They store typed values, +which persist across restarts and may be synced between browser instances via +the Sync service. There are several pref stores, which are documented in detail +in the [prefs docs][prefs]. They can be directly configured via enterprise +policy. + +Prefs: + +* *Are not* directly surfaced to the user +* *Are not* localized into the user's language +* *Are* configurable via enterprise policy +* *Are not* reported via UMA when in use +* *Are not* included in chrome://version +* *Are* automatically persistent across restarts (usually) + +## Features + +Example: base::kDCheckIsFatalFeature + +These are implemented via creating a [base::Feature][base-feature] anywhere. +These can be enabled via server-side experimentation or via the command-line +using --enable-feature. Which features are in use is tracked by UMA metrics, +and is visible in chrome://version as the "Variations" field. Do note that in +release builds, only a series of hashes show up in chrome://version rather than +the string names of the variations, but these hashes can be turned back into +string names if needed. This is done by consulting [the testing +config][fieldtrial-config] for Chromium builds, or a Google-internal tool for +Chrome builds. + +*Features are the best way to add runtime conditional behavior.* + +Features: + +* *Are not* directly surfaced to the user +* *Are not* localized into the user's language +* *Are not* configurable via enterprise policy +* *Are* reported via UMA/crash when in use +* *Are* included in chrome://version +* *Are not* automatically persistent across restarts + +## Switches + +Example: switches::kIncognito aka "--incognito" + +These are implemented by testing anywhere in the codebase for the presence or +value of a switch in [base::CommandLine::ForCurrentProcess][base-commandline]. +There is no centralized registry of switches and they can be used for +essentially any purpose. + +Switches: + +* *Are not* directly surfaced to the user +* *Are not* localized into the user's language +* *Are* configurable via enterprise policy +* *Are not* reported via UMA when in use +* *Are* included in chrome://version +* *Are not* automatically persistent across restarts + +In general, switches are inferior to use of base::Feature, which has the same +capabilities and low engineering overhead but ties into UMA reporting. New code +should use base::Feature instead of switches. An exception to this is when the +configuration value is a string, since features can't take an arbitrary string +value. + +## Flags + +Example: chrome://flags/#ignore-gpu-blacklist + +These are implemented by adding an entry in [about_flags.cc][about-flags] +describing the flag, as well as metadata in [flag-metadata][flag-metadata]. +Flags have a name and description, and show up in chrome://flags. Flags also +have an expiration milestone, after which they will be hidden from that UI and +disabled, then later removed. Flags are backed by either a feature or a set of +switches, which they enable at browser startup depending on the value of the +flag. + +Flags should usually be temporary, to allow for pre-launch testing of a feature. +Permanent flags (those with expiration -1) should only be used when either: + +* The flag is regularly used for support/debugging purposes, by asking users to + flip it to eliminate a possible problem (such as ignore-gpu-blacklist) +* The flag is used for ongoing QA/test purposes in environments where command-line + switches can't be used (e.g. on mobile) + +"Users might need to turn the feature on/off" is not a sufficient justification +for a permanent flag. If at all possible, we should design features such that +users don't want or need to turn them off, but if we need to retain that choice, +we should promote it to a full setting (see below) with translations and +support. "Developers/QA might need to turn the feature on/off", on the other +hand, is justification for a permanent flag. + +Flags: + +* *Are* directly surfaced to the user +* *Are not* localized into the user's language +* *Are* configurable via enterprise policy +* *Are* reported via UMA when in use (via Launch.FlagsAtStartup) +* *Are not* included in chrome://version +* *Are* automatically persistent across restarts + +## Settings + +Example: "Show home button" + +Settings are implemented in WebUI, and show up in chrome://settings or one of +its subpages. They generally are bound to a pref which stores the value of that +setting. These are comparatively expensive to add, since they require +localization and some amount of UX involvement to figure out how to fit them +into chrome://settings, plus documentation and support material. Many settings +are implemented via prefs, but not all prefs correspond to settings; some are +used for tracking internal browser state across restarts. + +Settings: + +* *Are* directly surfaced to the user +* *Are* localized into the user's language +* *Are not* configurable via enterprise policy (but their backing prefs may be) +* *Are not* reported via UMA when in use +* *Are not* included in chrome://version +* *Are* automatically persistent across restarts (via their backing prefs) + +You should add a setting if end-users might want to change this behavior. A +decent litmus test for whether something should be a flag or a setting is: "will +someone who can't read or write code want to change this?" + +[base-commandline]: https://cs.chromium.org/chromium/src/base/command_line.h?type=cs&l=98 +[base-feature]: https://cs.chromium.org/chromium/src/base/feature_list.h?sq=package:chromium&g=0&l=53 +[about-flags]: https://cs.chromium.org/chromium/src/chrome/browser/about_flags.cc +[fieldtrial-config]: https://cs.chromium.org/chromium/src/testing/variations/fieldtrial_testing_config.json +[flag-metadata]: https://cs.chromium.org/chromium/src/chrome/browser/flag-metadata.json +[prefs]: https://www.chromium.org/developers/design-documents/preferences +[profile-register]: https://cs.chromium.org/chromium/src/chrome/browser/profiles/profile.cc?type=cs&g=0&l=138
diff --git a/infra/config/luci-milo.cfg b/infra/config/luci-milo.cfg index 2ff8877e..7196200 100644 --- a/infra/config/luci-milo.cfg +++ b/infra/config/luci-milo.cfg
@@ -1793,12 +1793,6 @@ short_name: "low" } builders { - name: "buildbot/chromium.android.fyi/Nougat Phone Tester" - name: "buildbucket/luci.chromium.ci/Nougat Phone Tester" - category: "Testers" - short_name: "N" - } - builders { name: "buildbot/chromium.android.fyi/Memory Infra Tester" name: "buildbucket/luci.chromium.ci/Memory Infra Tester" category: "Memory"
diff --git a/infra/config/luci-notify.cfg b/infra/config/luci-notify.cfg index d2993303..ed9923b 100644 --- a/infra/config/luci-notify.cfg +++ b/infra/config/luci-notify.cfg
@@ -148,6 +148,23 @@ } notifiers { + name: "chrome-memory-sheriffs" + notifications { + on_change: true + on_success: false + on_failure: false + on_new_failure: false + email { + recipients: "chrome-memory-sheriffs+bots@google.com" + } + } + builders { + name: "Memory Infra tester" + bucket: "ci" + } +} + +notifiers { name: "cr-fuchsia" notifications { on_change: true
diff --git a/ios/chrome/browser/autofill/form_input_accessory_view_controller.mm b/ios/chrome/browser/autofill/form_input_accessory_view_controller.mm index c8d9be0..b539b04 100644 --- a/ios/chrome/browser/autofill/form_input_accessory_view_controller.mm +++ b/ios/chrome/browser/autofill/form_input_accessory_view_controller.mm
@@ -188,12 +188,12 @@ if (!self.inputAccessoryView) { self.inputAccessoryView = [[FormInputAccessoryView alloc] init]; - self.inputAccessoryView.accessibilityViewIsModal = YES; if (IsIPadIdiom()) { [self.inputAccessoryView setUpWithLeadingView:self.formSuggestionView customTrailingView:self.manualFillAccessoryViewController.view]; } else { + self.inputAccessoryView.accessibilityViewIsModal = YES; self.formSuggestionView.trailingView = self.manualFillAccessoryViewController.view; [self.inputAccessoryView setUpWithLeadingView:self.formSuggestionView
diff --git a/ios/chrome/browser/tabs/tab.mm b/ios/chrome/browser/tabs/tab.mm index 2f4cf1c..2fbb3cb 100644 --- a/ios/chrome/browser/tabs/tab.mm +++ b/ios/chrome/browser/tabs/tab.mm
@@ -362,7 +362,9 @@ headers->GetNormalizedHeader("content-disposition", &contentDisposition); std::string defaultFilename = l10n_util::GetStringUTF8(IDS_IOS_OPEN_IN_FILE_DEFAULT_TITLE); - const GURL& lastCommittedURL = self.webState->GetLastCommittedURL(); + web::NavigationItem* item = + self.webState->GetNavigationManager()->GetLastCommittedItem(); + const GURL& lastCommittedURL = item ? item->GetURL() : GURL::EmptyGURL(); base::string16 filename = net::GetSuggestedFilename(lastCommittedURL, contentDisposition, "", // referrer-charset
diff --git a/ios/chrome/browser/ui/location_bar/BUILD.gn b/ios/chrome/browser/ui/location_bar/BUILD.gn index e19fd557..19258e4 100644 --- a/ios/chrome/browser/ui/location_bar/BUILD.gn +++ b/ios/chrome/browser/ui/location_bar/BUILD.gn
@@ -40,6 +40,7 @@ "//ios/chrome/browser/autocomplete", "//ios/chrome/browser/browser_state:browser_state", "//ios/chrome/browser/geolocation:geolocation_internal", + "//ios/chrome/browser/ntp", "//ios/chrome/browser/search_engines", "//ios/chrome/browser/ssl", "//ios/chrome/browser/ui",
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm b/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm index bb8441a..efd5abd994 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm +++ b/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm
@@ -18,6 +18,7 @@ #include "ios/chrome/browser/autocomplete/autocomplete_scheme_classifier_impl.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #import "ios/chrome/browser/geolocation/omnibox_geolocation_controller.h" +#import "ios/chrome/browser/ntp/new_tab_page_tab_helper.h" #include "ios/chrome/browser/search_engines/template_url_service_factory.h" #include "ios/chrome/browser/ui/commands/browser_commands.h" #import "ios/chrome/browser/ui/commands/command_dispatcher.h" @@ -266,6 +267,13 @@ #pragma mark - OmniboxFocuser - (void)focusOmniboxFromSearchButton { + // TODO(crbug.com/931284): Temporary workaround for intermediate broken state + // in the NTP. Remove this once crbug.com/899827 is fixed. + NewTabPageTabHelper* NTPHelper = + NewTabPageTabHelper::FromWebState(self.webState); + if (NTPHelper && NTPHelper->IgnoreLoadRequests()) { + return; + } [self.omniboxCoordinator setNextFocusSourceAsSearchButton]; [self focusOmnibox]; }
diff --git a/net/android/http_auth_negotiate_android.cc b/net/android/http_auth_negotiate_android.cc index 836b0f4..50f9eb2 100644 --- a/net/android/http_auth_negotiate_android.cc +++ b/net/android/http_auth_negotiate_android.cc
@@ -51,7 +51,7 @@ // simplifies the logic. In practice the result will only ever come back on // the original thread in an obscure error case. callback_task_runner_->PostTask( - FROM_HERE, base::Bind(thread_safe_callback_, result, raw_token)); + FROM_HERE, base::BindOnce(thread_safe_callback_, result, raw_token)); // We will always get precisely one call to set result for each call to // getNextAuthToken, so we can now delete the callback object, and must // do so to avoid a memory leak.
diff --git a/net/base/directory_lister.cc b/net/base/directory_lister.cc index aec3125..c898aaa 100644 --- a/net/base/directory_lister.cc +++ b/net/base/directory_lister.cc
@@ -118,9 +118,9 @@ if (!base::DirectoryExists(dir_)) { origin_task_runner_->PostTask( - FROM_HERE, base::Bind(&Core::DoneOnOriginSequence, this, - base::Passed(std::move(directory_list)), - ERR_FILE_NOT_FOUND)); + FROM_HERE, base::BindOnce(&Core::DoneOnOriginSequence, this, + base::Passed(std::move(directory_list)), + ERR_FILE_NOT_FOUND)); return; } @@ -158,7 +158,7 @@ origin_loop_->PostTask( FROM_HERE, - base::Bind(&DirectoryLister::Core::SendData, file_data)); + base::BindOnce(&DirectoryLister::Core::SendData, file_data)); file_data.clear(); */ } @@ -166,8 +166,8 @@ SortData(directory_list.get(), type_); origin_task_runner_->PostTask( - FROM_HERE, base::Bind(&Core::DoneOnOriginSequence, this, - base::Passed(std::move(directory_list)), OK)); + FROM_HERE, base::BindOnce(&Core::DoneOnOriginSequence, this, + base::Passed(std::move(directory_list)), OK)); } bool DirectoryLister::Core::IsCancelled() const {
diff --git a/net/base/file_stream_context_win.cc b/net/base/file_stream_context_win.cc index f16f94ba..38571a4 100644 --- a/net/base/file_stream_context_win.cc +++ b/net/base/file_stream_context_win.cc
@@ -82,9 +82,10 @@ task_runner_->PostTask( FROM_HERE, - base::Bind(&FileStream::Context::ReadAsync, base::Unretained(this), - file_.GetPlatformFile(), base::WrapRefCounted(buf), buf_len, - &io_context_.overlapped, base::ThreadTaskRunnerHandle::Get())); + base::BindOnce(&FileStream::Context::ReadAsync, base::Unretained(this), + file_.GetPlatformFile(), base::WrapRefCounted(buf), + buf_len, &io_context_.overlapped, + base::ThreadTaskRunnerHandle::Get())); return ERR_IO_PENDING; } @@ -208,9 +209,9 @@ DWORD bytes_read = 0; BOOL ret = ::ReadFile(file, buf->data(), buf_len, &bytes_read, overlapped); origin_thread_task_runner->PostTask( - FROM_HERE, - base::Bind(&FileStream::Context::ReadAsyncResult, - base::Unretained(context), ret, bytes_read, ::GetLastError())); + FROM_HERE, base::BindOnce(&FileStream::Context::ReadAsyncResult, + base::Unretained(context), ret, bytes_read, + ::GetLastError())); } void FileStream::Context::ReadAsyncResult(BOOL read_file_ret,
diff --git a/net/base/network_activity_monitor_unittest.cc b/net/base/network_activity_monitor_unittest.cc index 3221ddab..d7b6ceaa 100644 --- a/net/base/network_activity_monitor_unittest.cc +++ b/net/base/network_activity_monitor_unittest.cc
@@ -107,17 +107,14 @@ for (size_t i = 0; i < num_increments; ++i) { size_t thread_num = i % threads.size(); threads[thread_num]->task_runner()->PostTask( - FROM_HERE, - base::Bind(&IncrementBytesReceived, bytes_received)); + FROM_HERE, base::BindOnce(&IncrementBytesReceived, bytes_received)); + threads[thread_num]->task_runner()->PostTask( + FROM_HERE, base::BindOnce(&IncrementBytesSent, bytes_sent)); + threads[thread_num]->task_runner()->PostTask( + FROM_HERE, base::BindOnce(&VerifyBytesSentIsMultipleOf, bytes_sent)); threads[thread_num]->task_runner()->PostTask( FROM_HERE, - base::Bind(&IncrementBytesSent, bytes_sent)); - threads[thread_num]->task_runner()->PostTask( - FROM_HERE, - base::Bind(&VerifyBytesSentIsMultipleOf, bytes_sent)); - threads[thread_num]->task_runner()->PostTask( - FROM_HERE, - base::Bind(&VerifyBytesReceivedIsMultipleOf, bytes_received)); + base::BindOnce(&VerifyBytesReceivedIsMultipleOf, bytes_received)); } threads.clear();
diff --git a/net/base/network_change_notifier_win.cc b/net/base/network_change_notifier_win.cc index 882a71b..4031e87d 100644 --- a/net/base/network_change_notifier_win.cc +++ b/net/base/network_change_notifier_win.cc
@@ -275,8 +275,9 @@ } base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, base::Bind(&NetworkChangeNotifierWin::WatchForAddressChange, - weak_factory_.GetWeakPtr()), + FROM_HERE, + base::BindOnce(&NetworkChangeNotifierWin::WatchForAddressChange, + weak_factory_.GetWeakPtr()), base::TimeDelta::FromMilliseconds( kWatchForAddressChangeRetryIntervalMs)); return;
diff --git a/net/base/network_change_notifier_win_unittest.cc b/net/base/network_change_notifier_win_unittest.cc index 8d50f8ae..a89b3c7 100644 --- a/net/base/network_change_notifier_win_unittest.cc +++ b/net/base/network_change_notifier_win_unittest.cc
@@ -45,8 +45,8 @@ void RecomputeCurrentConnectionTypeOnDnsThread( base::Callback<void(ConnectionType)> reply_callback) const override { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(reply_callback, NetworkChangeNotifier::CONNECTION_UNKNOWN)); + FROM_HERE, base::BindOnce(reply_callback, + NetworkChangeNotifier::CONNECTION_UNKNOWN)); } // From NetworkChangeNotifierWin.
diff --git a/net/base/network_config_watcher_mac.cc b/net/base/network_config_watcher_mac.cc index f324969a..5aef19f 100644 --- a/net/base/network_config_watcher_mac.cc +++ b/net/base/network_config_watcher_mac.cc
@@ -169,8 +169,9 @@ // initialize this, rather than just delaying it by a fixed time. const base::TimeDelta kInitializationDelay = base::TimeDelta::FromSeconds(1); task_runner()->PostDelayedTask( - FROM_HERE, base::Bind(&NetworkConfigWatcherMacThread::InitNotifications, - weak_factory_.GetWeakPtr()), + FROM_HERE, + base::BindOnce(&NetworkConfigWatcherMacThread::InitNotifications, + weak_factory_.GetWeakPtr()), kInitializationDelay); }
diff --git a/net/base/network_throttle_manager_impl.cc b/net/base/network_throttle_manager_impl.cc index 5494531..d5043bc 100644 --- a/net/base/network_throttle_manager_impl.cc +++ b/net/base/network_throttle_manager_impl.cc
@@ -250,8 +250,8 @@ // Via PostTask so there aren't upcalls from within destructors. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&NetworkThrottleManagerImpl::MaybeUnblockThrottles, - weak_ptr_factory_.GetWeakPtr())); + base::BindOnce(&NetworkThrottleManagerImpl::MaybeUnblockThrottles, + weak_ptr_factory_.GetWeakPtr())); } }
diff --git a/net/base/test_completion_callback_unittest.cc b/net/base/test_completion_callback_unittest.cc index 5a0242d..8ee06e0b1 100644 --- a/net/base/test_completion_callback_unittest.cc +++ b/net/base/test_completion_callback_unittest.cc
@@ -74,8 +74,8 @@ void ExampleEmployer::ExampleWorker::DoWork() { // In a real worker thread, some work would be done here. // Pretend it is, and send the completion callback. - origin_task_runner_->PostTask(FROM_HERE, - base::Bind(&ExampleWorker::DoCallback, this)); + origin_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&ExampleWorker::DoCallback, this)); } void ExampleEmployer::ExampleWorker::DoCallback() { @@ -99,7 +99,7 @@ request_ = new ExampleWorker(this, std::move(callback)); if (!base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&ExampleWorker::DoWork, request_))) { + FROM_HERE, base::BindOnce(&ExampleWorker::DoWork, request_))) { NOTREACHED(); request_ = NULL; return false;
diff --git a/net/cert/cert_database_mac.cc b/net/cert/cert_database_mac.cc index b363f59..8e7ffc4 100644 --- a/net/cert/cert_database_mac.cc +++ b/net/cert/cert_database_mac.cc
@@ -38,9 +38,8 @@ // Ensure an associated CFRunLoop. DCHECK(base::MessageLoopCurrentForUI::IsSet()); DCHECK(task_runner_->BelongsToCurrentThread()); - task_runner_->PostTask(FROM_HERE, - base::Bind(&Notifier::Init, - base::Unretained(this))); + task_runner_->PostTask( + FROM_HERE, base::BindOnce(&Notifier::Init, base::Unretained(this))); } // Should be called from the |task_runner_|'s sequence. Use Shutdown()
diff --git a/net/cert_net/cert_net_fetcher_impl.cc b/net/cert_net/cert_net_fetcher_impl.cc index 48cf1ca..e2f2083 100644 --- a/net/cert_net/cert_net_fetcher_impl.cc +++ b/net/cert_net/cert_net_fetcher_impl.cc
@@ -387,7 +387,7 @@ void RequestCore::CancelJob() { if (!task_runner_->RunsTasksInCurrentSequence()) { task_runner_->PostTask(FROM_HERE, - base::Bind(&RequestCore::CancelJob, this)); + base::BindOnce(&RequestCore::CancelJob, this)); return; } @@ -799,8 +799,8 @@ // then the request will hang (that is, WaitForResult will not return). if (!task_runner_->PostTask( FROM_HERE, - base::Bind(&CertNetFetcherImpl::DoFetchOnNetworkSequence, this, - base::Passed(&request_params), request_core))) { + base::BindOnce(&CertNetFetcherImpl::DoFetchOnNetworkSequence, this, + std::move(request_params), request_core))) { request_core->SignalImmediateError(); }
diff --git a/net/cert_net/cert_net_fetcher_impl_unittest.cc b/net/cert_net/cert_net_fetcher_impl_unittest.cc index 5b31dc0..87bfddf 100644 --- a/net/cert_net/cert_net_fetcher_impl_unittest.cc +++ b/net/cert_net/cert_net_fetcher_impl_unittest.cc
@@ -124,8 +124,9 @@ if (!network_thread_) return; network_thread_->task_runner()->PostTask( - FROM_HERE, base::Bind(&CertNetFetcherImplTest::TeardownOnNetworkThread, - base::Unretained(this))); + FROM_HERE, + base::BindOnce(&CertNetFetcherImplTest::TeardownOnNetworkThread, + base::Unretained(this))); network_thread_->Stop(); } @@ -142,8 +143,8 @@ base::WaitableEvent::InitialState::NOT_SIGNALED); network_thread_->task_runner()->PostTask( FROM_HERE, - base::Bind(&CertNetFetcherImplTest::CreateFetcherOnNetworkThread, - base::Unretained(this), &done)); + base::BindOnce(&CertNetFetcherImplTest::CreateFetcherOnNetworkThread, + base::Unretained(this), &done)); done.Wait(); } @@ -157,8 +158,8 @@ base::WaitableEvent::InitialState::NOT_SIGNALED); network_thread_->task_runner()->PostTask( FROM_HERE, - base::Bind(&CertNetFetcherImplTest::ShutDownFetcherOnNetworkThread, - base::Unretained(this), &done)); + base::BindOnce(&CertNetFetcherImplTest::ShutDownFetcherOnNetworkThread, + base::Unretained(this), &done)); done.Wait(); } @@ -167,8 +168,8 @@ base::WaitableEvent done(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); network_thread_->task_runner()->PostTask( - FROM_HERE, base::Bind(&CertNetFetcherImplTest::CountCreatedRequests, - base::Unretained(this), &count, &done)); + FROM_HERE, base::BindOnce(&CertNetFetcherImplTest::CountCreatedRequests, + base::Unretained(this), &count, &done)); done.Wait(); return count; } @@ -183,8 +184,8 @@ base::WaitableEvent done(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); network_thread_->task_runner()->PostTask( - FROM_HERE, base::Bind(&CertNetFetcherImplTest::InitOnNetworkThread, - base::Unretained(this), &done)); + FROM_HERE, base::BindOnce(&CertNetFetcherImplTest::InitOnNetworkThread, + base::Unretained(this), &done)); done.Wait(); } @@ -204,8 +205,8 @@ base::WaitableEvent::InitialState::NOT_SIGNALED); network_thread_->task_runner()->PostTask( FROM_HERE, - base::Bind(&CertNetFetcherImplTest::ResetStateOnNetworkThread, - base::Unretained(this), &done)); + base::BindOnce(&CertNetFetcherImplTest::ResetStateOnNetworkThread, + base::Unretained(this), &done)); done.Wait(); }
diff --git a/net/cert_net/nss_ocsp.cc b/net/cert_net/nss_ocsp.cc index e8f0a53..9fa92efec 100644 --- a/net/cert_net/nss_ocsp.cc +++ b/net/cert_net/nss_ocsp.cc
@@ -353,7 +353,8 @@ lock_.AssertAcquired(); if (io_task_runner_) { io_task_runner_->PostTask( - FROM_HERE, base::Bind(&OCSPRequestSession::CancelURLRequest, this)); + FROM_HERE, + base::BindOnce(&OCSPRequestSession::CancelURLRequest, this)); } }
diff --git a/net/cookies/cookie_monster_store_test.cc b/net/cookies/cookie_monster_store_test.cc index ee3e80e6..d31091b9 100644 --- a/net/cookies/cookie_monster_store_test.cc +++ b/net/cookies/cookie_monster_store_test.cc
@@ -55,7 +55,7 @@ loaded_ = true; } base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(loaded_callback, base::Passed(&out_cookies))); + FROM_HERE, base::BindOnce(loaded_callback, std::move(out_cookies))); } void MockPersistentCookieStore::LoadCookiesForKey( @@ -71,7 +71,7 @@ } else { std::vector<std::unique_ptr<CanonicalCookie>> empty_cookies; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(loaded_callback, base::Passed(&empty_cookies))); + FROM_HERE, base::BindOnce(loaded_callback, std::move(empty_cookies))); } } @@ -147,7 +147,7 @@ out_cookies.push_back(std::make_unique<CanonicalCookie>(it->second)); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(loaded_callback, base::Passed(&out_cookies))); + FROM_HERE, base::BindOnce(loaded_callback, std::move(out_cookies))); loaded_ = true; } @@ -159,7 +159,7 @@ } else { std::vector<std::unique_ptr<CanonicalCookie>> empty_cookies; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(loaded_callback, base::Passed(&empty_cookies))); + FROM_HERE, base::BindOnce(loaded_callback, std::move(empty_cookies))); } }
diff --git a/net/disk_cache/blockfile/eviction.cc b/net/disk_cache/blockfile/eviction.cc index 63e018a..be71609 100644 --- a/net/disk_cache/blockfile/eviction.cc +++ b/net/disk_cache/blockfile/eviction.cc
@@ -154,8 +154,8 @@ if (!empty && (deleted_entries > 20 || (TimeTicks::Now() - start).InMilliseconds() > 20)) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&Eviction::TrimCache, ptr_factory_.GetWeakPtr(), false)); + FROM_HERE, base::BindOnce(&Eviction::TrimCache, + ptr_factory_.GetWeakPtr(), false)); break; } } @@ -222,7 +222,8 @@ delay_trim_ = true; trim_delays_++; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, base::Bind(&Eviction::DelayedTrim, ptr_factory_.GetWeakPtr()), + FROM_HERE, + base::BindOnce(&Eviction::DelayedTrim, ptr_factory_.GetWeakPtr()), base::TimeDelta::FromMilliseconds(1000)); } @@ -370,8 +371,8 @@ if (!empty && (deleted_entries > 20 || (TimeTicks::Now() - start).InMilliseconds() > 20)) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&Eviction::TrimCache, ptr_factory_.GetWeakPtr(), false)); + FROM_HERE, base::BindOnce(&Eviction::TrimCache, + ptr_factory_.GetWeakPtr(), false)); break; } } @@ -383,8 +384,8 @@ TrimDeleted(true); } else if (ShouldTrimDeleted()) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&Eviction::TrimDeleted, ptr_factory_.GetWeakPtr(), empty)); + FROM_HERE, base::BindOnce(&Eviction::TrimDeleted, + ptr_factory_.GetWeakPtr(), empty)); } if (empty) { @@ -516,8 +517,8 @@ if (deleted_entries && !empty && ShouldTrimDeleted()) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&Eviction::TrimDeleted, ptr_factory_.GetWeakPtr(), false)); + FROM_HERE, base::BindOnce(&Eviction::TrimDeleted, + ptr_factory_.GetWeakPtr(), false)); } CACHE_UMA(AGE_MS, "TotalTrimDeletedTime", 0, start);
diff --git a/net/disk_cache/blockfile/in_flight_io.cc b/net/disk_cache/blockfile/in_flight_io.cc index 2471b35..e32a6b49 100644 --- a/net/disk_cache/blockfile/in_flight_io.cc +++ b/net/disk_cache/blockfile/in_flight_io.cc
@@ -77,7 +77,7 @@ #endif callback_task_runner_->PostTask( - FROM_HERE, base::Bind(&BackgroundIO::OnIOSignalled, operation)); + FROM_HERE, base::BindOnce(&BackgroundIO::OnIOSignalled, operation)); operation->io_completed()->Signal(); }
diff --git a/net/disk_cache/blockfile/sparse_control.cc b/net/disk_cache/blockfile/sparse_control.cc index 21969c4..105ce54 100644 --- a/net/disk_cache/blockfile/sparse_control.cc +++ b/net/disk_cache/blockfile/sparse_control.cc
@@ -147,7 +147,7 @@ // Post a task to delete the next child. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&ChildrenDeleter::DeleteChildren, this)); + FROM_HERE, base::BindOnce(&ChildrenDeleter::DeleteChildren, this)); } // Returns the NetLog event type corresponding to a SparseOperation. @@ -375,11 +375,11 @@ if (buffer) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&ChildrenDeleter::Start, deleter, buffer, data_len)); + base::BindOnce(&ChildrenDeleter::Start, deleter, buffer, data_len)); } else { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&ChildrenDeleter::ReadData, deleter, address, data_len)); + base::BindOnce(&ChildrenDeleter::ReadData, deleter, address, data_len)); } }
diff --git a/net/dns/dns_config_service_posix.cc b/net/dns/dns_config_service_posix.cc index 31c564fa..061a011 100644 --- a/net/dns/dns_config_service_posix.cc +++ b/net/dns/dns_config_service_posix.cc
@@ -273,8 +273,9 @@ // Ignore transient flutter of resolv.conf by delaying the signal a bit. const base::TimeDelta kDelay = base::TimeDelta::FromMilliseconds(50); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, base::Bind(&Watcher::OnConfigChangedDelayed, - weak_factory_.GetWeakPtr(), succeeded), + FROM_HERE, + base::BindOnce(&Watcher::OnConfigChangedDelayed, + weak_factory_.GetWeakPtr(), succeeded), kDelay); }
diff --git a/net/dns/dns_config_service_win.cc b/net/dns/dns_config_service_win.cc index 860aa27..c9ec3e4d 100644 --- a/net/dns/dns_config_service_win.cc +++ b/net/dns/dns_config_service_win.cc
@@ -672,7 +672,7 @@ LOG(WARNING) << "Failed to read DnsConfig."; // Try again in a while in case DnsConfigWatcher missed the signal. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, base::Bind(&ConfigReader::WorkNow, this), + FROM_HERE, base::BindOnce(&ConfigReader::WorkNow, this), base::TimeDelta::FromSeconds(kRetryIntervalSeconds)); } }
diff --git a/net/dns/dns_test_util.cc b/net/dns/dns_test_util.cc index e6a78a32..285a2d5 100644 --- a/net/dns/dns_test_util.cc +++ b/net/dns/dns_test_util.cc
@@ -268,7 +268,7 @@ return; // Using WeakPtr to cleanly cancel when transaction is destroyed. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&MockTransaction::Finish, AsWeakPtr())); + FROM_HERE, base::BindOnce(&MockTransaction::Finish, AsWeakPtr())); } void FinishDelayedTransaction() {
diff --git a/net/dns/dns_transaction_unittest.cc b/net/dns/dns_transaction_unittest.cc index cfb46e3..150b2c07 100644 --- a/net/dns/dns_transaction_unittest.cc +++ b/net/dns/dns_transaction_unittest.cc
@@ -465,8 +465,8 @@ // Start reading asynchronously so that all error reporting and data // callbacks happen as they would for network requests. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&URLRequestMockDohJob::StartAsync, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&URLRequestMockDohJob::StartAsync, + weak_factory_.GetWeakPtr())); } ~URLRequestMockDohJob() override {
diff --git a/net/dns/mdns_client_impl.cc b/net/dns/mdns_client_impl.cc index 967ca35..cfcd6d3 100644 --- a/net/dns/mdns_client_impl.cc +++ b/net/dns/mdns_client_impl.cc
@@ -213,8 +213,8 @@ VLOG(1) << "Socket error. id=" << id << ", error=" << rv; // Post to allow deletion of this object by delegate. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&MDnsConnection::OnError, weak_ptr_factory_.GetWeakPtr(), rv)); + FROM_HERE, base::BindOnce(&MDnsConnection::OnError, + weak_ptr_factory_.GetWeakPtr(), rv)); } void MDnsConnection::OnError(int rv) { @@ -395,8 +395,8 @@ // Schedule the actual removal for later in case the listener removal // happens while iterating over the observer list. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&MDnsClientImpl::Core::CleanupObserverList, - AsWeakPtr(), key)); + FROM_HERE, base::BindOnce(&MDnsClientImpl::Core::CleanupObserverList, + AsWeakPtr(), key)); } }
diff --git a/net/dns/mock_host_resolver.cc b/net/dns/mock_host_resolver.cc index dbb22b3..0811064 100644 --- a/net/dns/mock_host_resolver.cc +++ b/net/dns/mock_host_resolver.cc
@@ -357,8 +357,8 @@ DCHECK(ondemand_mode_); for (auto i = requests_.begin(); i != requests_.end(); ++i) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&MockHostResolverBase::ResolveNow, AsWeakPtr(), i->first)); + FROM_HERE, base::BindOnce(&MockHostResolverBase::ResolveNow, + AsWeakPtr(), i->first)); } }
diff --git a/net/dns/serial_worker_unittest.cc b/net/dns/serial_worker_unittest.cc index 7175af5..a9562f9c 100644 --- a/net/dns/serial_worker_unittest.cc +++ b/net/dns/serial_worker_unittest.cc
@@ -77,8 +77,8 @@ void BreakNow(const std::string& b) { task_runner_->PostTask(FROM_HERE, - base::Bind(&SerialWorkerTest::BreakCallback, - base::Unretained(this), b)); + base::BindOnce(&SerialWorkerTest::BreakCallback, + base::Unretained(this), b)); } void RunUntilBreak(const std::string& b) {
diff --git a/net/extras/sqlite/sqlite_channel_id_store.cc b/net/extras/sqlite/sqlite_channel_id_store.cc index b67d23f..865fb63 100644 --- a/net/extras/sqlite/sqlite_channel_id_store.cc +++ b/net/extras/sqlite/sqlite_channel_id_store.cc
@@ -355,8 +355,8 @@ // TODO(shess): Consider just calling RazeAndClose() immediately. // db_ may not be safe to reset at this point, but RazeAndClose() // would cause the stack to unwind safely with errors. - background_task_runner_->PostTask(FROM_HERE, - base::Bind(&Backend::KillDatabase, this)); + background_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&Backend::KillDatabase, this)); } void SQLiteChannelIDStore::Backend::KillDatabase() { @@ -388,9 +388,8 @@ return; // Perform deletion on background task runner. background_task_runner_->PostTask( - FROM_HERE, - base::Bind( - &Backend::BackgroundDeleteAllInList, this, server_identifiers)); + FROM_HERE, base::BindOnce(&Backend::BackgroundDeleteAllInList, this, + server_identifiers)); } void SQLiteChannelIDStore::Backend::BatchOperation( @@ -421,13 +420,12 @@ if (num_pending == 1) { // We've gotten our first entry for this batch, fire off the timer. background_task_runner_->PostDelayedTask( - FROM_HERE, - base::Bind(&Backend::Commit, this), + FROM_HERE, base::BindOnce(&Backend::Commit, this), base::TimeDelta::FromMilliseconds(kCommitIntervalMs)); } else if (num_pending == kCommitAfterBatchSize) { // We've reached a big enough batch, fire off a commit now. background_task_runner_->PostTask(FROM_HERE, - base::Bind(&Backend::Commit, this)); + base::BindOnce(&Backend::Commit, this)); } } @@ -453,7 +451,7 @@ Commit(); } else { background_task_runner_->PostTask(FROM_HERE, - base::Bind(&Backend::Commit, this)); + base::BindOnce(&Backend::Commit, this)); } } @@ -526,7 +524,7 @@ void SQLiteChannelIDStore::Backend::Close() { // Must close the backend on the background task runner. background_task_runner_->PostTask( - FROM_HERE, base::Bind(&Backend::InternalBackgroundClose, this)); + FROM_HERE, base::BindOnce(&Backend::InternalBackgroundClose, this)); } void SQLiteChannelIDStore::Backend::InternalBackgroundClose() {
diff --git a/net/extras/sqlite/sqlite_persistent_cookie_store.cc b/net/extras/sqlite/sqlite_persistent_cookie_store.cc index 65a5308..fb891be 100644 --- a/net/extras/sqlite/sqlite_persistent_cookie_store.cc +++ b/net/extras/sqlite/sqlite_persistent_cookie_store.cc
@@ -866,7 +866,7 @@ if (load_success && keys_to_load_.size() > 0) { bool success = background_task_runner_->PostDelayedTask( FROM_HERE, - base::Bind(&Backend::ChainLoadCookies, this, loaded_callback), + base::BindOnce(&Backend::ChainLoadCookies, this, loaded_callback), base::TimeDelta::FromMilliseconds(kLoadDelayMilliseconds)); if (!success) { LOG(WARNING) << "Failed to post task from " << FROM_HERE.ToString() @@ -1310,7 +1310,7 @@ if (num_pending == 1) { // We've gotten our first entry for this batch, fire off the timer. if (!background_task_runner_->PostDelayedTask( - FROM_HERE, base::Bind(&Backend::Commit, this), + FROM_HERE, base::BindOnce(&Backend::Commit, this), base::TimeDelta::FromMilliseconds(kCommitIntervalMs))) { NOTREACHED() << "background_task_runner_ is not running."; }
diff --git a/net/extras/sqlite/sqlite_persistent_cookie_store_unittest.cc b/net/extras/sqlite/sqlite_persistent_cookie_store_unittest.cc index 84636fb..6f673ab9 100644 --- a/net/extras/sqlite/sqlite_persistent_cookie_store_unittest.cc +++ b/net/extras/sqlite/sqlite_persistent_cookie_store_unittest.cc
@@ -320,8 +320,8 @@ // Posting a blocking task to db_thread_ makes sure that the DB thread waits // until both Load and Flush have been posted to its task queue. background_task_runner_->PostTask( - FROM_HERE, base::Bind(&SQLitePersistentCookieStoreTest::WaitOnDBEvent, - base::Unretained(this))); + FROM_HERE, base::BindOnce(&SQLitePersistentCookieStoreTest::WaitOnDBEvent, + base::Unretained(this))); store_->Load(base::Bind(&SQLitePersistentCookieStoreTest::OnLoaded, base::Unretained(this)), NetLogWithSource()); @@ -385,8 +385,8 @@ // Posting a blocking task to db_thread_ makes sure that the DB thread waits // until both Load and LoadCookiesForKey have been posted to its task queue. background_task_runner_->PostTask( - FROM_HERE, base::Bind(&SQLitePersistentCookieStoreTest::WaitOnDBEvent, - base::Unretained(this))); + FROM_HERE, base::BindOnce(&SQLitePersistentCookieStoreTest::WaitOnDBEvent, + base::Unretained(this))); BoundTestNetLog net_log; store_->Load(base::Bind(&SQLitePersistentCookieStoreTest::OnLoaded, base::Unretained(this)), @@ -397,8 +397,8 @@ "aaa.com", base::Bind(&SQLitePersistentCookieStoreTest::OnKeyLoaded, base::Unretained(this), run_loop.QuitClosure())); background_task_runner_->PostTask( - FROM_HERE, base::Bind(&SQLitePersistentCookieStoreTest::WaitOnDBEvent, - base::Unretained(this))); + FROM_HERE, base::BindOnce(&SQLitePersistentCookieStoreTest::WaitOnDBEvent, + base::Unretained(this))); // Now the DB-thread queue contains: // (active:)
diff --git a/net/http/bidirectional_stream.cc b/net/http/bidirectional_stream.cc index 404602b..3530487 100644 --- a/net/http/bidirectional_stream.cc +++ b/net/http/bidirectional_stream.cc
@@ -107,8 +107,8 @@ if (!request_info_->url.SchemeIs(url::kHttpsScheme)) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&BidirectionalStream::NotifyFailed, - weak_factory_.GetWeakPtr(), ERR_DISALLOWED_URL_SCHEME)); + base::BindOnce(&BidirectionalStream::NotifyFailed, + weak_factory_.GetWeakPtr(), ERR_DISALLOWED_URL_SCHEME)); return; }
diff --git a/net/http/http_auth_handler_mock.cc b/net/http/http_auth_handler_mock.cc index 0ac30e1..fa245cb 100644 --- a/net/http/http_auth_handler_mock.cc +++ b/net/http/http_auth_handler_mock.cc
@@ -115,8 +115,8 @@ callback_ = std::move(callback); auth_token_ = auth_token; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&HttpAuthHandlerMock::OnGenerateAuthToken, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&HttpAuthHandlerMock::OnGenerateAuthToken, + weak_factory_.GetWeakPtr())); state_ = State::TOKEN_PENDING; return ERR_IO_PENDING; } else {
diff --git a/net/http/http_cache.cc b/net/http/http_cache.cc index 45ac482..3e544cb 100644 --- a/net/http/http_cache.cc +++ b/net/http/http_cache.cc
@@ -1013,7 +1013,8 @@ for (auto* transaction : entry->add_to_entry_queue) { transaction->ResetCachePendingState(); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(transaction->io_callback(), net::ERR_CACHE_RACE)); + FROM_HERE, + base::BindOnce(transaction->io_callback(), net::ERR_CACHE_RACE)); } entry->add_to_entry_queue.clear(); } @@ -1082,8 +1083,8 @@ // Post a task instead of invoking the io callback of another transaction here // to avoid re-entrancy. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&HttpCache::OnProcessQueuedTransactions, GetWeakPtr(), entry)); + FROM_HERE, base::BindOnce(&HttpCache::OnProcessQueuedTransactions, + GetWeakPtr(), entry)); } void HttpCache::ProcessAddToEntryQueue(ActiveEntry* entry) { @@ -1474,8 +1475,8 @@ pending_op->writer = std::move(pending_item); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&HttpCache::OnBackendCreated, GetWeakPtr(), - result, pending_op)); + FROM_HERE, base::BindOnce(&HttpCache::OnBackendCreated, GetWeakPtr(), + result, pending_op)); } else { building_backend_ = false; DeletePendingOp(pending_op);
diff --git a/net/http/http_cache_transaction.cc b/net/http/http_cache_transaction.cc index 8b20caa4..e1bcd20 100644 --- a/net/http/http_cache_transaction.cc +++ b/net/http/http_cache_transaction.cc
@@ -1329,8 +1329,8 @@ next_state_ == STATE_FINISH_HEADERS_COMPLETE)) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&HttpCache::Transaction::OnCacheLockTimeout, - weak_factory_.GetWeakPtr(), entry_lock_waiting_since_)); + base::BindOnce(&HttpCache::Transaction::OnCacheLockTimeout, + weak_factory_.GetWeakPtr(), entry_lock_waiting_since_)); } else { int timeout_milliseconds = 20 * 1000; if (partial_ && entry->writers && !entry->writers->IsEmpty() && @@ -1356,8 +1356,8 @@ } base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&HttpCache::Transaction::OnCacheLockTimeout, - weak_factory_.GetWeakPtr(), entry_lock_waiting_since_), + base::BindOnce(&HttpCache::Transaction::OnCacheLockTimeout, + weak_factory_.GetWeakPtr(), entry_lock_waiting_since_), TimeDelta::FromMilliseconds(timeout_milliseconds)); } }
diff --git a/net/http/http_network_session.cc b/net/http/http_network_session.cc index 1215589..667a6ff 100644 --- a/net/http/http_network_session.cc +++ b/net/http/http_network_session.cc
@@ -45,6 +45,7 @@ HttpNetworkSession::SocketPoolType pool_type, const HttpNetworkSession::Context& context, SSLClientSessionCache* ssl_client_session_cache, + SSLClientSessionCache* ssl_client_session_cache_privacy_mode, WebSocketEndpointLockManager* websocket_endpoint_lock_manager) { // TODO(yutak): Differentiate WebSocket pool manager and allow more // simultaneous connections for WebSockets. @@ -57,8 +58,8 @@ context.cert_verifier, context.channel_id_service, context.transport_security_state, context.cert_transparency_verifier, context.ct_policy_enforcer, ssl_client_session_cache, - context.ssl_config_service, websocket_endpoint_lock_manager, - context.proxy_delegate, pool_type); + ssl_client_session_cache_privacy_mode, context.ssl_config_service, + websocket_endpoint_lock_manager, context.proxy_delegate, pool_type); } } // unnamed namespace @@ -194,6 +195,7 @@ proxy_resolution_service_(context.proxy_resolution_service), ssl_config_service_(context.ssl_config_service), ssl_client_session_cache_(SSLClientSessionCache::Config()), + ssl_client_session_cache_privacy_mode_(SSLClientSessionCache::Config()), push_delegate_(nullptr), quic_stream_factory_( context.net_log, @@ -260,9 +262,11 @@ normal_socket_pool_manager_ = CreateSocketPoolManager( NORMAL_SOCKET_POOL, context, &ssl_client_session_cache_, + &ssl_client_session_cache_privacy_mode_, &websocket_endpoint_lock_manager_); websocket_socket_pool_manager_ = CreateSocketPoolManager( WEBSOCKET_SOCKET_POOL, context, &ssl_client_session_cache_, + &ssl_client_session_cache_privacy_mode_, &websocket_endpoint_lock_manager_); if (params_.enable_http2) { @@ -507,6 +511,7 @@ void HttpNetworkSession::ClearSSLSessionCache() { ssl_client_session_cache_.Flush(); + ssl_client_session_cache_privacy_mode_.Flush(); } ClientSocketPoolManager* HttpNetworkSession::GetSocketPoolManager(
diff --git a/net/http/http_network_session.h b/net/http/http_network_session.h index 6345b86..cdc00e0 100644 --- a/net/http/http_network_session.h +++ b/net/http/http_network_session.h
@@ -375,6 +375,7 @@ // Clear the SSL session cache. void ClearSSLSessionCache(); + void ClearSSLSessionCachePrivacyMode(); private: friend class HttpNetworkSessionPeer; @@ -400,6 +401,7 @@ HttpAuthCache http_auth_cache_; SSLClientAuthCache ssl_client_auth_cache_; SSLClientSessionCache ssl_client_session_cache_; + SSLClientSessionCache ssl_client_session_cache_privacy_mode_; WebSocketEndpointLockManager websocket_endpoint_lock_manager_; std::unique_ptr<ClientSocketPoolManager> normal_socket_pool_manager_; std::unique_ptr<ClientSocketPoolManager> websocket_socket_pool_manager_;
diff --git a/net/http/http_network_transaction_unittest.cc b/net/http/http_network_transaction_unittest.cc index b74f01b..53e1a856 100644 --- a/net/http/http_network_transaction_unittest.cc +++ b/net/http/http_network_transaction_unittest.cc
@@ -695,7 +695,7 @@ NULL, NULL, NULL, - "", + NULL, NULL, NULL, NULL, @@ -14284,7 +14284,7 @@ session_deps_.cert_transparency_verifier.get(), session_deps_.ct_policy_enforcer.get(), nullptr /* ssl_client_session_cache */, - std::string() /* ssl_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, session_deps_.ssl_config_service.get(), nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */, session_deps_.net_log);
diff --git a/net/http/http_proxy_client_socket_pool_unittest.cc b/net/http/http_proxy_client_socket_pool_unittest.cc index 46092912..0ade6427 100644 --- a/net/http/http_proxy_client_socket_pool_unittest.cc +++ b/net/http/http_proxy_client_socket_pool_unittest.cc
@@ -82,7 +82,7 @@ session_deps_.cert_transparency_verifier.get(), session_deps_.ct_policy_enforcer.get(), nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, session_deps_.ssl_config_service.get(), nullptr /* socket_performance_watcher_factory */, &estimator_, @@ -103,7 +103,7 @@ session_deps_.cert_transparency_verifier.get(), session_deps_.ct_policy_enforcer.get(), nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, session_deps_.ssl_config_service.get(), nullptr /* socket_performance_watcher_factory */, &estimator_, nullptr /* net_log */);
diff --git a/net/http/http_proxy_client_socket_wrapper_unittest.cc b/net/http/http_proxy_client_socket_wrapper_unittest.cc index 123608a..b132611b 100644 --- a/net/http/http_proxy_client_socket_wrapper_unittest.cc +++ b/net/http/http_proxy_client_socket_wrapper_unittest.cc
@@ -293,16 +293,17 @@ /*request_priority=*/DEFAULT_PRIORITY, /*connect_timeout_duration=*/base::TimeDelta::FromHours(1), /*proxy_negotiation_timeout_duration=*/base::TimeDelta::FromHours(1), - CommonConnectJobParams( - "group_name", - /*socket_tag=*/SocketTag(), - /*respect_limits=*/true, - /*client_socket_factory=*/nullptr, - /*host_resolver=*/nullptr, - /*proxy_delegate=*/nullptr, SSLClientSocketContext(), - /*socket_performance_watcher_factory=*/nullptr, - /*network_quality_estimator=*/nullptr, net_log_.net_log(), - /*websocket_endpoint_lock_manager=*/nullptr), + CommonConnectJobParams("group_name", + /*socket_tag=*/SocketTag(), + /*respect_limits=*/true, + /*client_socket_factory=*/nullptr, + /*host_resolver=*/nullptr, + /*proxy_delegate=*/nullptr, + SSLClientSocketContext(), SSLClientSocketContext(), + /*socket_performance_watcher_factory=*/nullptr, + /*network_quality_estimator=*/nullptr, + net_log_.net_log(), + /*websocket_endpoint_lock_manager=*/nullptr), /*transport_params=*/nullptr, ssl_params, quic_version_, kUserAgent, endpoint_host_port_, &http_auth_cache_, http_auth_handler_factory_.get(), /*spdy_session_pool=*/nullptr, quic_stream_factory_.get(), @@ -365,6 +366,7 @@ /*client_socket_factory=*/nullptr, /*host_resolver=*/nullptr, /*proxy_delegate=*/nullptr, SSLClientSocketContext(), + SSLClientSocketContext(), /*socket_performance_watcher_factory=*/nullptr, /*network_quality_estimator=*/nullptr, net_log_.net_log(), /*websocket_endpoint_lock_manager=*/nullptr),
diff --git a/net/http/http_proxy_connect_job_unittest.cc b/net/http/http_proxy_connect_job_unittest.cc index a8c768c..1627942 100644 --- a/net/http/http_proxy_connect_job_unittest.cc +++ b/net/http/http_proxy_connect_job_unittest.cc
@@ -53,22 +53,23 @@ public WithScopedTaskEnvironment { protected: HttpProxyConnectJobTest() - : transport_socket_pool_(32 /* max_sockets */, - 6 /* max_sockets_pre_group */, - &socket_factory_, - session_deps_.host_resolver.get(), - nullptr /* proxy_delegate */, - session_deps_.cert_verifier.get(), - session_deps_.channel_id_service.get(), - session_deps_.transport_security_state.get(), - session_deps_.cert_transparency_verifier.get(), - session_deps_.ct_policy_enforcer.get(), - nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, - session_deps_.ssl_config_service.get(), - nullptr /* socket_performance_watcher_factory */, - nullptr /* network_quality_estimator */, - nullptr /* net_log */), + : transport_socket_pool_( + 32 /* max_sockets */, + 6 /* max_sockets_pre_group */, + &socket_factory_, + session_deps_.host_resolver.get(), + nullptr /* proxy_delegate */, + session_deps_.cert_verifier.get(), + session_deps_.channel_id_service.get(), + session_deps_.transport_security_state.get(), + session_deps_.cert_transparency_verifier.get(), + session_deps_.ct_policy_enforcer.get(), + nullptr /* ssl_client_session_cache */, + nullptr /* ssl_client_session_cache_privacy_mode */, + session_deps_.ssl_config_service.get(), + nullptr /* socket_performance_watcher_factory */, + nullptr /* network_quality_estimator */, + nullptr /* net_log */), ssl_socket_pool_(32 /* max_sockets */, 6 /* max_sockets_pre_group */, &socket_factory_, @@ -80,7 +81,7 @@ session_deps_.cert_transparency_verifier.get(), session_deps_.ct_policy_enforcer.get(), nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, session_deps_.ssl_config_service.get(), nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */, @@ -186,8 +187,14 @@ session_deps_.transport_security_state.get(), session_deps_.cert_transparency_verifier.get(), session_deps_.ct_policy_enforcer.get(), - nullptr /* ssl_session_cache_arg */, - std::string() /* ssl_session_cache_shart_arg */), + nullptr /* ssl_session_cache_arg */), + SSLClientSocketContext( + session_deps_.cert_verifier.get(), + session_deps_.channel_id_service.get(), + session_deps_.transport_security_state.get(), + session_deps_.cert_transparency_verifier.get(), + session_deps_.ct_policy_enforcer.get(), + nullptr /* ssl_session_cache_arg */), nullptr /* socket_performance_watcher_factory */, &network_quality_estimator_, nullptr /* net_log */, nullptr /* websocket_endpoint_lock_manager */),
diff --git a/net/http/http_stream_factory_job.cc b/net/http/http_stream_factory_job.cc index aeded63..f7158e1 100644 --- a/net/http/http_stream_factory_job.cc +++ b/net/http/http_stream_factory_job.cc
@@ -584,8 +584,9 @@ if (job_type_ == PRECONNECT) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&HttpStreamFactory::Job::OnPreconnectsComplete, - ptr_factory_.GetWeakPtr())); + FROM_HERE, + base::BindOnce(&HttpStreamFactory::Job::OnPreconnectsComplete, + ptr_factory_.GetWeakPtr())); return; } @@ -597,8 +598,8 @@ next_state_ = STATE_WAITING_USER_ACTION; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&HttpStreamFactory::Job::OnCertificateErrorCallback, - ptr_factory_.GetWeakPtr(), result, ssl_info)); + base::BindOnce(&HttpStreamFactory::Job::OnCertificateErrorCallback, + ptr_factory_.GetWeakPtr(), result, ssl_info)); return; } @@ -609,8 +610,9 @@ if (!connection_.get()) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&Job::OnStreamFailedCallback, ptr_factory_.GetWeakPtr(), - ERR_PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION)); + base::BindOnce(&Job::OnStreamFailedCallback, + ptr_factory_.GetWeakPtr(), + ERR_PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION)); return; } CHECK(connection_->socket()); @@ -621,16 +623,17 @@ static_cast<ProxyClientSocket*>(connection_->socket()); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&Job::OnNeedsProxyAuthCallback, ptr_factory_.GetWeakPtr(), - *proxy_socket->GetConnectResponseInfo(), - base::RetainedRef(proxy_socket->GetAuthController()))); + base::BindOnce(&Job::OnNeedsProxyAuthCallback, + ptr_factory_.GetWeakPtr(), + *proxy_socket->GetConnectResponseInfo(), + base::RetainedRef(proxy_socket->GetAuthController()))); return; } case ERR_SSL_CLIENT_AUTH_CERT_NEEDED: base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind( + base::BindOnce( &Job::OnNeedsClientAuthCallback, ptr_factory_.GetWeakPtr(), base::RetainedRef( connection_->ssl_error_response_info().cert_request_info))); @@ -661,36 +664,37 @@ next_state_ = STATE_DONE; if (new_spdy_session_.get()) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&Job::OnNewSpdySessionReadyCallback, - ptr_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&Job::OnNewSpdySessionReadyCallback, + ptr_factory_.GetWeakPtr())); } else if (is_websocket_) { DCHECK(websocket_stream_); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&Job::OnWebSocketHandshakeStreamReadyCallback, - ptr_factory_.GetWeakPtr())); + FROM_HERE, + base::BindOnce(&Job::OnWebSocketHandshakeStreamReadyCallback, + ptr_factory_.GetWeakPtr())); } else if (stream_type_ == HttpStreamRequest::BIDIRECTIONAL_STREAM) { if (!bidirectional_stream_impl_) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&Job::OnStreamFailedCallback, - ptr_factory_.GetWeakPtr(), ERR_FAILED)); + FROM_HERE, base::BindOnce(&Job::OnStreamFailedCallback, + ptr_factory_.GetWeakPtr(), ERR_FAILED)); } else { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&Job::OnBidirectionalStreamImplReadyCallback, - ptr_factory_.GetWeakPtr())); + base::BindOnce(&Job::OnBidirectionalStreamImplReadyCallback, + ptr_factory_.GetWeakPtr())); } } else { DCHECK(stream_.get()); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&Job::OnStreamReadyCallback, ptr_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&Job::OnStreamReadyCallback, + ptr_factory_.GetWeakPtr())); } return; default: base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&Job::OnStreamFailedCallback, - ptr_factory_.GetWeakPtr(), result)); + FROM_HERE, base::BindOnce(&Job::OnStreamFailedCallback, + ptr_factory_.GetWeakPtr(), result)); return; } }
diff --git a/net/http/http_stream_factory_job_controller.cc b/net/http/http_stream_factory_job_controller.cc index aee6810..333031e 100644 --- a/net/http/http_stream_factory_job_controller.cc +++ b/net/http/http_stream_factory_job_controller.cc
@@ -736,8 +736,8 @@ DCHECK(!alternative_job_); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&HttpStreamFactory::JobController::NotifyRequestFailed, - ptr_factory_.GetWeakPtr(), rv)); + base::BindOnce(&HttpStreamFactory::JobController::NotifyRequestFailed, + ptr_factory_.GetWeakPtr(), rv)); } }
diff --git a/net/http/http_stream_factory_unittest.cc b/net/http/http_stream_factory_unittest.cc index 3bb6fc39..388333e 100644 --- a/net/http/http_stream_factory_unittest.cc +++ b/net/http/http_stream_factory_unittest.cc
@@ -479,7 +479,7 @@ nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */,
diff --git a/net/http/http_stream_parser_unittest.cc b/net/http/http_stream_parser_unittest.cc index be70ac2..1125d556 100644 --- a/net/http/http_stream_parser_unittest.cc +++ b/net/http/http_stream_parser_unittest.cc
@@ -82,8 +82,8 @@ int ReadInternal(IOBuffer* buf, int buf_len) override { if (async_ == FailureMode::ASYNC) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&ReadErrorUploadDataStream::CompleteRead, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&ReadErrorUploadDataStream::CompleteRead, + weak_factory_.GetWeakPtr())); return ERR_IO_PENDING; } return ERR_FAILED; @@ -207,8 +207,8 @@ int InitInternal(const NetLogWithSource& net_log) override { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&InitAsyncUploadDataStream::CompleteInit, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&InitAsyncUploadDataStream::CompleteInit, + weak_factory_.GetWeakPtr())); return ERR_IO_PENDING; }
diff --git a/net/log/file_net_log_observer.cc b/net/log/file_net_log_observer.cc index f31acf28..1b1b7e40 100644 --- a/net/log/file_net_log_observer.cc +++ b/net/log/file_net_log_observer.cc
@@ -368,8 +368,9 @@ // StopObserving was not called. net_log()->RemoveObserver(this); file_task_runner_->PostTask( - FROM_HERE, base::Bind(&FileNetLogObserver::FileWriter::DeleteAllFiles, - base::Unretained(file_writer_.get()))); + FROM_HERE, + base::BindOnce(&FileNetLogObserver::FileWriter::DeleteAllFiles, + base::Unretained(file_writer_.get()))); } file_task_runner_->DeleteSoon(FROM_HERE, file_writer_.release()); } @@ -412,8 +413,8 @@ if (queue_size == kNumWriteQueueEvents) { file_task_runner_->PostTask( FROM_HERE, - base::Bind(&FileNetLogObserver::FileWriter::Flush, - base::Unretained(file_writer_.get()), write_queue_)); + base::BindOnce(&FileNetLogObserver::FileWriter::Flush, + base::Unretained(file_writer_.get()), write_queue_)); } } @@ -477,9 +478,9 @@ if (!constants) constants = GetNetConstants(); file_task_runner_->PostTask( - FROM_HERE, base::Bind(&FileNetLogObserver::FileWriter::Initialize, - base::Unretained(file_writer_.get()), - base::Passed(&constants))); + FROM_HERE, base::BindOnce(&FileNetLogObserver::FileWriter::Initialize, + base::Unretained(file_writer_.get()), + std::move(constants))); } FileNetLogObserver::WriteQueue::WriteQueue(uint64_t memory_max)
diff --git a/net/log/file_net_log_observer_unittest.cc b/net/log/file_net_log_observer_unittest.cc index 64ea6b4..ce841283 100644 --- a/net/log/file_net_log_observer_unittest.cc +++ b/net/log/file_net_log_observer_unittest.cc
@@ -578,8 +578,8 @@ // Add events in parallel from all the threads. for (size_t i = 0; i < kNumThreads; ++i) { threads[i]->task_runner()->PostTask( - FROM_HERE, base::Bind(&AddEntries, base::Unretained(logger_.get()), - kNumEventsAddedPerThread, kDummyEventSize)); + FROM_HERE, base::BindOnce(&AddEntries, base::Unretained(logger_.get()), + kNumEventsAddedPerThread, kDummyEventSize)); } // Join all the threads. @@ -963,8 +963,9 @@ // Add events in parallel from all the threads. for (size_t i = 0; i < kNumThreads; ++i) { threads[i]->task_runner()->PostTask( - FROM_HERE, base::Bind(&AddEntriesViaNetLog, base::Unretained(&net_log_), - kNumEventsAddedPerThread)); + FROM_HERE, + base::BindOnce(&AddEntriesViaNetLog, base::Unretained(&net_log_), + kNumEventsAddedPerThread)); } // Stop observing. @@ -998,8 +999,9 @@ // Add events in parallel from all the threads. for (size_t i = 0; i < kNumThreads; ++i) { threads[i]->task_runner()->PostTask( - FROM_HERE, base::Bind(&AddEntriesViaNetLog, base::Unretained(&net_log_), - kNumEventsAddedPerThread)); + FROM_HERE, + base::BindOnce(&AddEntriesViaNetLog, base::Unretained(&net_log_), + kNumEventsAddedPerThread)); } // Destroy logger.
diff --git a/net/nqe/network_quality_estimator.cc b/net/nqe/network_quality_estimator.cc index a46ce25..66f2871 100644 --- a/net/nqe/network_quality_estimator.cc +++ b/net/nqe/network_quality_estimator.cc
@@ -1055,9 +1055,10 @@ // Notify the |observer| on the next message pump since |observer| may not // be completely set up for receiving the callbacks. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&NetworkQualityEstimator:: - NotifyEffectiveConnectionTypeObserverIfPresent, - weak_ptr_factory_.GetWeakPtr(), observer)); + FROM_HERE, + base::BindOnce(&NetworkQualityEstimator:: + NotifyEffectiveConnectionTypeObserverIfPresent, + weak_ptr_factory_.GetWeakPtr(), observer)); } void NetworkQualityEstimator::RemoveEffectiveConnectionTypeObserver( @@ -1076,9 +1077,9 @@ // be completely set up for receiving the callbacks. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&NetworkQualityEstimator:: - NotifyRTTAndThroughputEstimatesObserverIfPresent, - weak_ptr_factory_.GetWeakPtr(), observer)); + base::BindOnce(&NetworkQualityEstimator:: + NotifyRTTAndThroughputEstimatesObserverIfPresent, + weak_ptr_factory_.GetWeakPtr(), observer)); } void NetworkQualityEstimator::RemoveRTTAndThroughputEstimatesObserver(
diff --git a/net/nqe/network_quality_store.cc b/net/nqe/network_quality_store.cc index 905162c..aa444b0 100644 --- a/net/nqe/network_quality_store.cc +++ b/net/nqe/network_quality_store.cc
@@ -175,8 +175,9 @@ // Notify the |observer| on the next message pump since |observer| may not // be completely set up for receiving the callbacks. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&NetworkQualityStore::NotifyCacheObserverIfPresent, - weak_ptr_factory_.GetWeakPtr(), observer)); + FROM_HERE, + base::BindOnce(&NetworkQualityStore::NotifyCacheObserverIfPresent, + weak_ptr_factory_.GetWeakPtr(), observer)); } void NetworkQualityStore::RemoveNetworkQualitiesCacheObserver(
diff --git a/net/nqe/socket_watcher.cc b/net/nqe/socket_watcher.cc index 096a5c14..1c559e7 100644 --- a/net/nqe/socket_watcher.cc +++ b/net/nqe/socket_watcher.cc
@@ -120,7 +120,7 @@ last_rtt_notification_ = tick_clock_->NowTicks(); task_runner_->PostTask( FROM_HERE, - base::Bind(updated_rtt_observation_callback_, protocol_, rtt, host_)); + base::BindOnce(updated_rtt_observation_callback_, protocol_, rtt, host_)); } void SocketWatcher::OnConnectionChanged() {
diff --git a/net/nqe/throughput_analyzer.cc b/net/nqe/throughput_analyzer.cc index 3632b6ae..2e9e2352 100644 --- a/net/nqe/throughput_analyzer.cc +++ b/net/nqe/throughput_analyzer.cc
@@ -191,7 +191,7 @@ // Notify the provided callback. task_runner_->PostTask( FROM_HERE, - base::Bind(throughput_observation_callback_, downstream_kbps)); + base::BindOnce(throughput_observation_callback_, downstream_kbps)); } // Try to remove the request from either |accuracy_degrading_requests_| or
diff --git a/net/proxy_resolution/multi_threaded_proxy_resolver.cc b/net/proxy_resolution/multi_threaded_proxy_resolver.cc index ae41f4f..b48196c 100644 --- a/net/proxy_resolution/multi_threaded_proxy_resolver.cc +++ b/net/proxy_resolution/multi_threaded_proxy_resolver.cc
@@ -239,7 +239,8 @@ DCHECK_NE(rv, ERR_IO_PENDING); origin_runner->PostTask( - FROM_HERE, base::Bind(&CreateResolverJob::RequestComplete, this, rv)); + FROM_HERE, + base::BindOnce(&CreateResolverJob::RequestComplete, this, rv)); } protected: @@ -307,7 +308,7 @@ DCHECK_NE(rv, ERR_IO_PENDING); origin_runner->PostTask( - FROM_HERE, base::Bind(&GetProxyForURLJob::QueryComplete, this, rv)); + FROM_HERE, base::BindOnce(&GetProxyForURLJob::QueryComplete, this, rv)); } protected: @@ -362,7 +363,7 @@ job->FinishedWaitingForThread(); thread_->task_runner()->PostTask( FROM_HERE, - base::Bind(&Job::Run, job, base::ThreadTaskRunnerHandle::Get())); + base::BindOnce(&Job::Run, job, base::ThreadTaskRunnerHandle::Get())); } void Executor::OnJobCompleted(Job* job) {
diff --git a/net/proxy_resolution/network_delegate_error_observer.cc b/net/proxy_resolution/network_delegate_error_observer.cc index a588161..a898cb6 100644 --- a/net/proxy_resolution/network_delegate_error_observer.cc +++ b/net/proxy_resolution/network_delegate_error_observer.cc
@@ -49,8 +49,9 @@ int line_number, const base::string16& error) { if (!origin_runner_->BelongsToCurrentThread()) { - origin_runner_->PostTask(FROM_HERE, base::Bind(&Core::NotifyPACScriptError, - this, line_number, error)); + origin_runner_->PostTask( + FROM_HERE, + base::BindOnce(&Core::NotifyPACScriptError, this, line_number, error)); return; } if (network_delegate_)
diff --git a/net/proxy_resolution/network_delegate_error_observer_unittest.cc b/net/proxy_resolution/network_delegate_error_observer_unittest.cc index bfb0867..0a13cab02 100644 --- a/net/proxy_resolution/network_delegate_error_observer_unittest.cc +++ b/net/proxy_resolution/network_delegate_error_observer_unittest.cc
@@ -94,8 +94,9 @@ NetworkDelegateErrorObserver observer( &network_delegate, base::ThreadTaskRunnerHandle::Get().get()); thread.task_runner()->PostTask( - FROM_HERE, base::Bind(&NetworkDelegateErrorObserver::OnPACScriptError, - base::Unretained(&observer), 42, base::string16())); + FROM_HERE, + base::BindOnce(&NetworkDelegateErrorObserver::OnPACScriptError, + base::Unretained(&observer), 42, base::string16())); thread.Stop(); base::RunLoop().RunUntilIdle(); ASSERT_TRUE(network_delegate.got_pac_error()); @@ -109,8 +110,9 @@ NetworkDelegateErrorObserver observer( NULL, base::ThreadTaskRunnerHandle::Get().get()); thread.task_runner()->PostTask( - FROM_HERE, base::Bind(&NetworkDelegateErrorObserver::OnPACScriptError, - base::Unretained(&observer), 42, base::string16())); + FROM_HERE, + base::BindOnce(&NetworkDelegateErrorObserver::OnPACScriptError, + base::Unretained(&observer), 42, base::string16())); thread.Stop(); base::RunLoop().RunUntilIdle(); // Shouldn't have crashed until here...
diff --git a/net/proxy_resolution/pac_file_decider_unittest.cc b/net/proxy_resolution/pac_file_decider_unittest.cc index fd10db4..216d3ba 100644 --- a/net/proxy_resolution/pac_file_decider_unittest.cc +++ b/net/proxy_resolution/pac_file_decider_unittest.cc
@@ -797,8 +797,8 @@ const NetworkTrafficAnnotationTag traffic_annotation) override { callback_ = std::move(callback); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&AsyncFailDhcpFetcher::CallbackWithFailure, AsWeakPtr())); + FROM_HERE, base::BindOnce(&AsyncFailDhcpFetcher::CallbackWithFailure, + AsWeakPtr())); return ERR_IO_PENDING; }
diff --git a/net/proxy_resolution/pac_file_fetcher_impl.cc b/net/proxy_resolution/pac_file_fetcher_impl.cc index 3a5b956..e9e919b 100644 --- a/net/proxy_resolution/pac_file_fetcher_impl.cc +++ b/net/proxy_resolution/pac_file_fetcher_impl.cc
@@ -206,8 +206,8 @@ base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&PacFileFetcherImpl::OnTimeout, weak_factory_.GetWeakPtr(), - cur_request_id_), + base::BindOnce(&PacFileFetcherImpl::OnTimeout, weak_factory_.GetWeakPtr(), + cur_request_id_), max_duration_); // Start the request.
diff --git a/net/proxy_resolution/polling_proxy_config_service.cc b/net/proxy_resolution/polling_proxy_config_service.cc index dc1a86d..793fd875 100644 --- a/net/proxy_resolution/polling_proxy_config_service.cc +++ b/net/proxy_resolution/polling_proxy_config_service.cc
@@ -110,7 +110,7 @@ base::AutoLock lock(lock_); if (origin_task_runner_.get()) { origin_task_runner_->PostTask( - FROM_HERE, base::Bind(&Core::GetConfigCompleted, this, config)); + FROM_HERE, base::BindOnce(&Core::GetConfigCompleted, this, config)); } }
diff --git a/net/proxy_resolution/proxy_config_service_android.cc b/net/proxy_resolution/proxy_config_service_android.cc index 6134fd88..b55e5ee 100644 --- a/net/proxy_resolution/proxy_config_service_android.cc +++ b/net/proxy_resolution/proxy_config_service_android.cc
@@ -307,7 +307,7 @@ ShutdownInJNISequence(); } else { jni_task_runner_->PostTask( - FROM_HERE, base::Bind(&Delegate::ShutdownInJNISequence, this)); + FROM_HERE, base::BindOnce(&Delegate::ShutdownInJNISequence, this)); } }
diff --git a/net/proxy_resolution/proxy_config_service_linux.cc b/net/proxy_resolution/proxy_config_service_linux.cc index 72a81e5..e2ae592 100644 --- a/net/proxy_resolution/proxy_config_service_linux.cc +++ b/net/proxy_resolution/proxy_config_service_linux.cc
@@ -1268,8 +1268,10 @@ SetUpNotifications(); } else { // Post a task to set up notifications. We don't wait for success. - required_loop->PostTask(FROM_HERE, base::Bind( - &ProxyConfigServiceLinux::Delegate::SetUpNotifications, this)); + required_loop->PostTask( + FROM_HERE, + base::BindOnce( + &ProxyConfigServiceLinux::Delegate::SetUpNotifications, this)); } } } @@ -1340,8 +1342,8 @@ // update |cached_config_|. main_task_runner_->PostTask( FROM_HERE, - base::Bind(&ProxyConfigServiceLinux::Delegate::SetNewProxyConfig, this, - new_config)); + base::BindOnce(&ProxyConfigServiceLinux::Delegate::SetNewProxyConfig, + this, new_config)); // Update the thread-private copy in |reference_config_| as well. reference_config_ = new_config; } else { @@ -1373,8 +1375,9 @@ } else { // Post to shutdown thread. Note that on browser shutdown, we may quit // this MessageLoop and exit the program before ever running this. - shutdown_loop->PostTask(FROM_HERE, base::Bind( - &ProxyConfigServiceLinux::Delegate::OnDestroy, this)); + shutdown_loop->PostTask( + FROM_HERE, + base::BindOnce(&ProxyConfigServiceLinux::Delegate::OnDestroy, this)); } } void ProxyConfigServiceLinux::Delegate::OnDestroy() {
diff --git a/net/proxy_resolution/proxy_config_service_linux_unittest.cc b/net/proxy_resolution/proxy_config_service_linux_unittest.cc index cc63ce6..160c579 100644 --- a/net/proxy_resolution/proxy_config_service_linux_unittest.cc +++ b/net/proxy_resolution/proxy_config_service_linux_unittest.cc
@@ -292,7 +292,8 @@ // Make sure the thread started. main_thread_.task_runner()->PostTask( - FROM_HERE, base::Bind(&SyncConfigGetter::Init, base::Unretained(this))); + FROM_HERE, + base::BindOnce(&SyncConfigGetter::Init, base::Unretained(this))); Wait(); } @@ -300,7 +301,7 @@ // Clean up the main thread. main_thread_.task_runner()->PostTask( FROM_HERE, - base::Bind(&SyncConfigGetter::CleanUp, base::Unretained(this))); + base::BindOnce(&SyncConfigGetter::CleanUp, base::Unretained(this))); Wait(); } @@ -316,8 +317,8 @@ ProxyConfigService::ConfigAvailability SyncGetLatestProxyConfig( ProxyConfigWithAnnotation* config) { main_thread_.task_runner()->PostTask( - FROM_HERE, base::Bind(&SyncConfigGetter::GetLatestConfigOnIOThread, - base::Unretained(this))); + FROM_HERE, base::BindOnce(&SyncConfigGetter::GetLatestConfigOnIOThread, + base::Unretained(this))); Wait(); *config = proxy_config_; return get_latest_config_result_;
diff --git a/net/proxy_resolution/proxy_config_service_mac.cc b/net/proxy_resolution/proxy_config_service_mac.cc index 3409321..1b81b26 100644 --- a/net/proxy_resolution/proxy_config_service_mac.cc +++ b/net/proxy_resolution/proxy_config_service_mac.cc
@@ -269,7 +269,7 @@ // Call OnProxyConfigChanged() on the TakeRunner to notify our observers. sequenced_task_runner_->PostTask( FROM_HERE, - base::Bind(&Helper::OnProxyConfigChanged, helper_.get(), new_config)); + base::BindOnce(&Helper::OnProxyConfigChanged, helper_.get(), new_config)); } void ProxyConfigServiceMac::OnProxyConfigChanged(
diff --git a/net/proxy_resolution/proxy_resolution_service.cc b/net/proxy_resolution/proxy_resolution_service.cc index cf2a962..5aff9e25 100644 --- a/net/proxy_resolution/proxy_resolution_service.cc +++ b/net/proxy_resolution/proxy_resolution_service.cc
@@ -704,7 +704,8 @@ base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&PacFileDeciderPoller::DoPoll, weak_factory_.GetWeakPtr()), + base::BindOnce(&PacFileDeciderPoller::DoPoll, + weak_factory_.GetWeakPtr()), next_poll_delay_); } @@ -751,7 +752,7 @@ // the notification. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind( + base::BindOnce( &PacFileDeciderPoller::NotifyProxyResolutionServiceOfChange, weak_factory_.GetWeakPtr(), result, decider_->script_data(), decider_->effective_config()));
diff --git a/net/proxy_resolution/proxy_resolver_v8_tracing.cc b/net/proxy_resolution/proxy_resolver_v8_tracing.cc index d6f984b..8e16acc 100644 --- a/net/proxy_resolution/proxy_resolver_v8_tracing.cc +++ b/net/proxy_resolution/proxy_resolver_v8_tracing.cc
@@ -471,7 +471,7 @@ CheckIsOnWorkerThread(); origin_runner_->PostTask( - FROM_HERE, base::Bind(&Job::NotifyCallerOnOriginLoop, this, result)); + FROM_HERE, base::BindOnce(&Job::NotifyCallerOnOriginLoop, this, result)); } void Job::NotifyCallerOnOriginLoop(int result) { @@ -699,7 +699,8 @@ DCHECK(!pending_dns_); pending_dns_host_ = host; pending_dns_op_ = op; - origin_runner_->PostTask(FROM_HERE, base::Bind(&Job::DoDnsOperation, this)); + origin_runner_->PostTask(FROM_HERE, + base::BindOnce(&Job::DoDnsOperation, this)); event_.Wait(); event_.Reset(); @@ -766,8 +767,8 @@ if (!blocking_dns_ && !pending_dns_completed_synchronously_) { // Restart. This time it should make more progress due to having // cached items. - worker_task_runner()->PostTask(FROM_HERE, - base::Bind(&Job::ExecuteNonBlocking, this)); + worker_task_runner()->PostTask( + FROM_HERE, base::BindOnce(&Job::ExecuteNonBlocking, this)); } } @@ -842,8 +843,8 @@ if (blocking_dns_) { // In blocking DNS mode the events can be dispatched immediately. origin_runner_->PostTask( - FROM_HERE, base::Bind(&Job::DispatchAlertOrErrorOnOriginThread, this, - is_alert, line_number, message)); + FROM_HERE, base::BindOnce(&Job::DispatchAlertOrErrorOnOriginThread, + this, is_alert, line_number, message)); return; }
diff --git a/net/quic/bidirectional_stream_quic_impl.cc b/net/quic/bidirectional_stream_quic_impl.cc index 68d2f64..9725e10 100644 --- a/net/quic/bidirectional_stream_quic_impl.cc +++ b/net/quic/bidirectional_stream_quic_impl.cc
@@ -95,17 +95,17 @@ if (rv != OK) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&BidirectionalStreamQuicImpl::NotifyError, - weak_factory_.GetWeakPtr(), - session_->IsCryptoHandshakeConfirmed() - ? rv - : ERR_QUIC_HANDSHAKE_FAILED)); + FROM_HERE, base::BindOnce(&BidirectionalStreamQuicImpl::NotifyError, + weak_factory_.GetWeakPtr(), + session_->IsCryptoHandshakeConfirmed() + ? rv + : ERR_QUIC_HANDSHAKE_FAILED)); return; } base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&BidirectionalStreamQuicImpl::OnStreamReady, - weak_factory_.GetWeakPtr(), rv)); + FROM_HERE, base::BindOnce(&BidirectionalStreamQuicImpl::OnStreamReady, + weak_factory_.GetWeakPtr(), rv)); } void BidirectionalStreamQuicImpl::SendRequestHeaders() { @@ -113,8 +113,8 @@ int rv = WriteHeaders(); if (rv < 0) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&BidirectionalStreamQuicImpl::NotifyError, - weak_factory_.GetWeakPtr(), rv)); + FROM_HERE, base::BindOnce(&BidirectionalStreamQuicImpl::NotifyError, + weak_factory_.GetWeakPtr(), rv)); } } @@ -174,8 +174,8 @@ if (!stream_->IsOpen()) { LOG(ERROR) << "Trying to send data after stream has been closed."; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&BidirectionalStreamQuicImpl::NotifyError, - weak_factory_.GetWeakPtr(), ERR_UNEXPECTED)); + FROM_HERE, base::BindOnce(&BidirectionalStreamQuicImpl::NotifyError, + weak_factory_.GetWeakPtr(), ERR_UNEXPECTED)); return; } @@ -186,8 +186,8 @@ int rv = WriteHeaders(); if (rv < 0) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&BidirectionalStreamQuicImpl::NotifyError, - weak_factory_.GetWeakPtr(), rv)); + FROM_HERE, base::BindOnce(&BidirectionalStreamQuicImpl::NotifyError, + weak_factory_.GetWeakPtr(), rv)); return; } } @@ -199,8 +199,9 @@ if (rv != ERR_IO_PENDING) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&BidirectionalStreamQuicImpl::OnSendDataComplete, - weak_factory_.GetWeakPtr(), rv)); + FROM_HERE, + base::BindOnce(&BidirectionalStreamQuicImpl::OnSendDataComplete, + weak_factory_.GetWeakPtr(), rv)); } } @@ -261,8 +262,9 @@ } base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&BidirectionalStreamQuicImpl::ReadInitialHeaders, - weak_factory_.GetWeakPtr())); + FROM_HERE, + base::BindOnce(&BidirectionalStreamQuicImpl::ReadInitialHeaders, + weak_factory_.GetWeakPtr())); NotifyStreamReady(); } @@ -291,8 +293,9 @@ negotiated_protocol_ = kProtoQUIC; connect_timing_ = session_->GetConnectTiming(); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&BidirectionalStreamQuicImpl::ReadTrailingHeaders, - weak_factory_.GetWeakPtr())); + FROM_HERE, + base::BindOnce(&BidirectionalStreamQuicImpl::ReadTrailingHeaders, + weak_factory_.GetWeakPtr())); if (delegate_) delegate_->OnHeadersReceived(initial_headers_); } @@ -369,8 +372,9 @@ weak_factory_.InvalidateWeakPtrs(); if (notify_delegate_later) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&BidirectionalStreamQuicImpl::NotifyFailure, - weak_factory_.GetWeakPtr(), delegate, error)); + FROM_HERE, + base::BindOnce(&BidirectionalStreamQuicImpl::NotifyFailure, + weak_factory_.GetWeakPtr(), delegate, error)); } else { NotifyFailure(delegate, error); // |this| might be destroyed at this point. @@ -392,8 +396,8 @@ int rv = WriteHeaders(); if (rv < 0) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&BidirectionalStreamQuicImpl::NotifyError, - weak_factory_.GetWeakPtr(), rv)); + FROM_HERE, base::BindOnce(&BidirectionalStreamQuicImpl::NotifyError, + weak_factory_.GetWeakPtr(), rv)); return; } }
diff --git a/net/quic/quic_chromium_alarm_factory.cc b/net/quic/quic_chromium_alarm_factory.cc index 5475bfb..9124fb0 100644 --- a/net/quic/quic_chromium_alarm_factory.cc +++ b/net/quic/quic_chromium_alarm_factory.cc
@@ -47,7 +47,7 @@ } task_runner_->PostDelayedTask( FROM_HERE, - base::Bind(&QuicChromeAlarm::OnAlarm, weak_factory_.GetWeakPtr()), + base::BindOnce(&QuicChromeAlarm::OnAlarm, weak_factory_.GetWeakPtr()), base::TimeDelta::FromMicroseconds(delay_us)); task_deadline_ = deadline(); }
diff --git a/net/quic/quic_chromium_client_session.cc b/net/quic/quic_chromium_client_session.cc index f70d555..2436487a 100644 --- a/net/quic/quic_chromium_client_session.cc +++ b/net/quic/quic_chromium_client_session.cc
@@ -587,8 +587,8 @@ // Avoid re-entrancy if the callback calls into the session. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&QuicChromiumClientSession::StreamRequest::DoCallback, - weak_factory_.GetWeakPtr(), rv)); + base::BindOnce(&QuicChromiumClientSession::StreamRequest::DoCallback, + weak_factory_.GetWeakPtr(), rv)); } } @@ -1773,9 +1773,9 @@ // Post a task to migrate the session onto a new network. task_runner_->PostTask( FROM_HERE, - base::Bind(&QuicChromiumClientSession::MigrateSessionOnWriteError, - weak_factory_.GetWeakPtr(), error_code, - connection()->writer())); + base::BindOnce(&QuicChromiumClientSession::MigrateSessionOnWriteError, + weak_factory_.GetWeakPtr(), error_code, + connection()->writer())); // Store packet in the session since the actual migration and packet rewrite // can happen via this posted task or via an async network notification. @@ -1893,8 +1893,8 @@ // Post a task to maybe close the session if the alarm fires. task_runner_->PostDelayedTask( FROM_HERE, - base::Bind(&QuicChromiumClientSession::OnMigrationTimeout, - weak_factory_.GetWeakPtr(), sockets_.size()), + base::BindOnce(&QuicChromiumClientSession::OnMigrationTimeout, + weak_factory_.GetWeakPtr(), sockets_.size()), base::TimeDelta::FromSeconds(kWaitTimeForNewNetworkSecs)); } @@ -2801,8 +2801,8 @@ DCHECK(!connection()->connected()); task_runner_->PostTask( FROM_HERE, - base::Bind(&QuicChromiumClientSession::NotifyFactoryOfSessionClosed, - weak_factory_.GetWeakPtr())); + base::BindOnce(&QuicChromiumClientSession::NotifyFactoryOfSessionClosed, + weak_factory_.GetWeakPtr())); } void QuicChromiumClientSession::NotifyFactoryOfSessionClosed() { @@ -2918,8 +2918,8 @@ // socket. This avoids reentrancy issues if there is a write error // on the write to the new socket. task_runner_->PostTask( - FROM_HERE, base::Bind(&QuicChromiumClientSession::WriteToNewSocket, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&QuicChromiumClientSession::WriteToNewSocket, + weak_factory_.GetWeakPtr())); return true; }
diff --git a/net/quic/quic_chromium_client_stream.cc b/net/quic/quic_chromium_client_stream.cc index 01ef6d1..3fc5eca5 100644 --- a/net/quic/quic_chromium_client_stream.cc +++ b/net/quic/quic_chromium_client_stream.cc
@@ -126,8 +126,8 @@ // the call stack of the owner of the handle. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&QuicChromiumClientStream::Handle::InvokeCallbacksOnClose, - weak_factory_.GetWeakPtr(), error)); + base::BindOnce(&QuicChromiumClientStream::Handle::InvokeCallbacksOnClose, + weak_factory_.GetWeakPtr(), error)); } void QuicChromiumClientStream::Handle::InvokeCallbacksOnClose(int error) { @@ -620,7 +620,7 @@ DCHECK(handle_); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind( + base::BindOnce( &QuicChromiumClientStream::NotifyHandleOfInitialHeadersAvailable, weak_factory_.GetWeakPtr())); } @@ -637,7 +637,7 @@ DCHECK(handle_); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind( + base::BindOnce( &QuicChromiumClientStream::NotifyHandleOfTrailingHeadersAvailable, weak_factory_.GetWeakPtr())); } @@ -689,8 +689,8 @@ DCHECK(handle_); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&QuicChromiumClientStream::NotifyHandleOfDataAvailable, - weak_factory_.GetWeakPtr())); + base::BindOnce(&QuicChromiumClientStream::NotifyHandleOfDataAvailable, + weak_factory_.GetWeakPtr())); } void QuicChromiumClientStream::NotifyHandleOfDataAvailable() {
diff --git a/net/quic/quic_chromium_packet_reader.cc b/net/quic/quic_chromium_packet_reader.cc index 49584bc..0f4c8cd6 100644 --- a/net/quic/quic_chromium_packet_reader.cc +++ b/net/quic/quic_chromium_packet_reader.cc
@@ -63,8 +63,8 @@ // Schedule the work through the message loop to 1) prevent infinite // recursion and 2) avoid blocking the thread for too long. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&QuicChromiumPacketReader::OnReadComplete, - weak_factory_.GetWeakPtr(), rv)); + FROM_HERE, base::BindOnce(&QuicChromiumPacketReader::OnReadComplete, + weak_factory_.GetWeakPtr(), rv)); } else { if (!ProcessReadResult(rv)) { return;
diff --git a/net/quic/quic_connectivity_probing_manager.cc b/net/quic/quic_connectivity_probing_manager.cc index 98c6ea8b..78e8461 100644 --- a/net/quic/quic_connectivity_probing_manager.cc +++ b/net/quic/quic_connectivity_probing_manager.cc
@@ -80,8 +80,8 @@ // undergoing probing, which will delete the packet writer. task_runner_->PostTask( FROM_HERE, - base::Bind(&QuicConnectivityProbingManager::NotifyDelegateProbeFailed, - weak_factory_.GetWeakPtr())); + base::BindOnce(&QuicConnectivityProbingManager::NotifyDelegateProbeFailed, + weak_factory_.GetWeakPtr())); return error_code; }
diff --git a/net/quic/quic_http_stream_test.cc b/net/quic/quic_http_stream_test.cc index 3675488..734c258 100644 --- a/net/quic/quic_http_stream_test.cc +++ b/net/quic/quic_http_stream_test.cc
@@ -123,8 +123,8 @@ int ReadInternal(IOBuffer* buf, int buf_len) override { if (async_ == FailureMode::ASYNC) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&ReadErrorUploadDataStream::CompleteRead, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&ReadErrorUploadDataStream::CompleteRead, + weak_factory_.GetWeakPtr())); return ERR_IO_PENDING; } return ERR_FAILED;
diff --git a/net/server/http_server.cc b/net/server/http_server.cc index 49a3196..4c84b5d 100644 --- a/net/server/http_server.cc +++ b/net/server/http_server.cc
@@ -62,8 +62,8 @@ // Start accepting connections in next run loop in case when delegate is not // ready to get callbacks. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&HttpServer::DoAcceptLoop, weak_ptr_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&HttpServer::DoAcceptLoop, + weak_ptr_factory_.GetWeakPtr())); } HttpServer::~HttpServer() = default;
diff --git a/net/socket/client_socket_pool_base.cc b/net/socket/client_socket_pool_base.cc index d391c3a..77bbb4a6 100644 --- a/net/socket/client_socket_pool_base.cc +++ b/net/socket/client_socket_pool_base.cc
@@ -225,7 +225,7 @@ if (group->CanUseAdditionalSocketSlot(max_sockets_per_group_)) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind( + base::BindOnce( &ClientSocketPoolBaseHelper::TryToCloseSocketsInLayeredPools, weak_factory_.GetWeakPtr())); } @@ -1129,8 +1129,8 @@ handle->socket()->ApplySocketTag(socket_tag); } base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&ClientSocketPoolBaseHelper::InvokeUserCallback, - weak_factory_.GetWeakPtr(), handle)); + FROM_HERE, base::BindOnce(&ClientSocketPoolBaseHelper::InvokeUserCallback, + weak_factory_.GetWeakPtr(), handle)); } void ClientSocketPoolBaseHelper::InvokeUserCallback(
diff --git a/net/socket/client_socket_pool_base_unittest.cc b/net/socket/client_socket_pool_base_unittest.cc index 3a7a3d0..157503a 100644 --- a/net/socket/client_socket_pool_base_unittest.cc +++ b/net/socket/client_socket_pool_base_unittest.cc
@@ -339,6 +339,7 @@ nullptr /* host_resolver */, nullptr /* proxy_delegate */, SSLClientSocketContext(), + SSLClientSocketContext(), nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */, net_log, @@ -414,18 +415,18 @@ // time functions, so this change would be rather invasive. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(base::IgnoreResult(&TestConnectJob::DoConnect), - weak_factory_.GetWeakPtr(), true /* successful */, - true /* async */, false /* recoverable */), + base::BindOnce(base::IgnoreResult(&TestConnectJob::DoConnect), + weak_factory_.GetWeakPtr(), true /* successful */, + true /* async */, false /* recoverable */), base::TimeDelta::FromMilliseconds(kPendingConnectDelay)); return ERR_IO_PENDING; case kMockPendingFailingJob: set_load_state(LOAD_STATE_CONNECTING); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(base::IgnoreResult(&TestConnectJob::DoConnect), - weak_factory_.GetWeakPtr(), false /* error */, - true /* async */, false /* recoverable */), + base::BindOnce(base::IgnoreResult(&TestConnectJob::DoConnect), + weak_factory_.GetWeakPtr(), false /* error */, + true /* async */, false /* recoverable */), base::TimeDelta::FromMilliseconds(2)); return ERR_IO_PENDING; case kMockWaitingJob: @@ -440,9 +441,9 @@ set_load_state(LOAD_STATE_CONNECTING); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(base::IgnoreResult(&TestConnectJob::DoConnect), - weak_factory_.GetWeakPtr(), false /* error */, - true /* async */, true /* recoverable */), + base::BindOnce(base::IgnoreResult(&TestConnectJob::DoConnect), + weak_factory_.GetWeakPtr(), false /* error */, + true /* async */, true /* recoverable */), base::TimeDelta::FromMilliseconds(2)); return ERR_IO_PENDING; case kMockAdditionalErrorStateJob: @@ -454,9 +455,9 @@ store_additional_error_state_ = true; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(base::IgnoreResult(&TestConnectJob::DoConnect), - weak_factory_.GetWeakPtr(), false /* error */, - true /* async */, false /* recoverable */), + base::BindOnce(base::IgnoreResult(&TestConnectJob::DoConnect), + weak_factory_.GetWeakPtr(), false /* error */, + true /* async */, false /* recoverable */), base::TimeDelta::FromMilliseconds(2)); return ERR_IO_PENDING; case kMockUnreadDataJob: {
diff --git a/net/socket/client_socket_pool_manager_impl.cc b/net/socket/client_socket_pool_manager_impl.cc index f9cb8a84..288dfd8 100644 --- a/net/socket/client_socket_pool_manager_impl.cc +++ b/net/socket/client_socket_pool_manager_impl.cc
@@ -50,6 +50,7 @@ CTVerifier* cert_transparency_verifier, CTPolicyEnforcer* ct_policy_enforcer, SSLClientSessionCache* ssl_client_session_cache, + SSLClientSessionCache* ssl_client_session_cache_privacy_mode, SSLConfigService* ssl_config_service, WebSocketEndpointLockManager* websocket_endpoint_lock_manager, ProxyDelegate* proxy_delegate, @@ -65,6 +66,8 @@ cert_transparency_verifier_(cert_transparency_verifier), ct_policy_enforcer_(ct_policy_enforcer), ssl_client_session_cache_(ssl_client_session_cache), + ssl_client_session_cache_privacy_mode_( + ssl_client_session_cache_privacy_mode), ssl_config_service_(ssl_config_service), proxy_delegate_(proxy_delegate), pool_type_(pool_type), @@ -82,7 +85,7 @@ cert_transparency_verifier, ct_policy_enforcer, ssl_client_session_cache, - ssl_session_cache_shard_, + ssl_client_session_cache_privacy_mode, ssl_config_service, network_quality_estimator, websocket_endpoint_lock_manager, @@ -202,7 +205,7 @@ host_resolver_, proxy_delegate_, cert_verifier_, channel_id_service_, transport_security_state_, cert_transparency_verifier_, ct_policy_enforcer_, - ssl_client_session_cache_, ssl_session_cache_shard_, + ssl_client_session_cache_, ssl_client_session_cache_privacy_mode_, ssl_config_service_, socket_performance_watcher_factory_, network_quality_estimator_, net_log_, proxy_server.is_http_like() @@ -259,8 +262,8 @@ sockets_per_proxy_server, sockets_per_group, socket_factory_, host_resolver_, proxy_delegate_, cert_verifier_, channel_id_service_, transport_security_state_, cert_transparency_verifier_, - ct_policy_enforcer_, ssl_client_session_cache_, ssl_session_cache_shard_, - ssl_config_service_, + ct_policy_enforcer_, ssl_client_session_cache_, + ssl_client_session_cache_privacy_mode_, ssl_config_service_, use_socket_performance_watcher_factory ? socket_performance_watcher_factory_ : nullptr,
diff --git a/net/socket/client_socket_pool_manager_impl.h b/net/socket/client_socket_pool_manager_impl.h index adbaf727cc..11a4d2b 100644 --- a/net/socket/client_socket_pool_manager_impl.h +++ b/net/socket/client_socket_pool_manager_impl.h
@@ -59,6 +59,7 @@ CTVerifier* cert_transparency_verifier, CTPolicyEnforcer* ct_policy_enforcer, SSLClientSessionCache* ssl_client_session_cache, + SSLClientSessionCache* ssl_client_session_cache_privacy_mode, SSLConfigService* ssl_config_service, WebSocketEndpointLockManager* websocket_endpoint_lock_manager, ProxyDelegate* proxy_delegate, @@ -111,6 +112,7 @@ CTVerifier* const cert_transparency_verifier_; CTPolicyEnforcer* const ct_policy_enforcer_; SSLClientSessionCache* const ssl_client_session_cache_; + SSLClientSessionCache* const ssl_client_session_cache_privacy_mode_; const std::string ssl_session_cache_shard_; SSLConfigService* const ssl_config_service_; ProxyDelegate* const proxy_delegate_;
diff --git a/net/socket/connect_job.cc b/net/socket/connect_job.cc index c9f4e89..c49e228 100644 --- a/net/socket/connect_job.cc +++ b/net/socket/connect_job.cc
@@ -22,6 +22,7 @@ HostResolver* host_resolver, ProxyDelegate* proxy_delegate, const SSLClientSocketContext& ssl_client_socket_context, + const SSLClientSocketContext& ssl_client_socket_context_privacy_mode, SocketPerformanceWatcherFactory* socket_performance_watcher_factory, NetworkQualityEstimator* network_quality_estimator, NetLog* net_log, @@ -33,6 +34,8 @@ host_resolver(host_resolver), proxy_delegate(proxy_delegate), ssl_client_socket_context(ssl_client_socket_context), + ssl_client_socket_context_privacy_mode( + ssl_client_socket_context_privacy_mode), socket_performance_watcher_factory(socket_performance_watcher_factory), network_quality_estimator(network_quality_estimator), net_log(net_log),
diff --git a/net/socket/connect_job.h b/net/socket/connect_job.h index d35ecdd6..d8cfac6 100644 --- a/net/socket/connect_job.h +++ b/net/socket/connect_job.h
@@ -46,6 +46,7 @@ HostResolver* host_resolver, ProxyDelegate* proxy_delegate, const SSLClientSocketContext& ssl_client_socket_context, + const SSLClientSocketContext& ssl_client_socket_context_privacy_mode, SocketPerformanceWatcherFactory* socket_performance_watcher_factory, NetworkQualityEstimator* network_quality_estimator, NetLog* net_log, @@ -72,6 +73,7 @@ HostResolver* host_resolver; ProxyDelegate* proxy_delegate; SSLClientSocketContext ssl_client_socket_context; + SSLClientSocketContext ssl_client_socket_context_privacy_mode; SocketPerformanceWatcherFactory* socket_performance_watcher_factory; NetworkQualityEstimator* network_quality_estimator; NetLog* net_log; @@ -187,6 +189,9 @@ const SSLClientSocketContext& ssl_client_socket_context() { return common_connect_job_params_.ssl_client_socket_context; } + const SSLClientSocketContext& ssl_client_socket_context_privacy_mode() { + return common_connect_job_params_.ssl_client_socket_context_privacy_mode; + } SocketPerformanceWatcherFactory* socket_performance_watcher_factory() { return common_connect_job_params_.socket_performance_watcher_factory; }
diff --git a/net/socket/connect_job_unittest.cc b/net/socket/connect_job_unittest.cc index 3cab0f5..0c03c97 100644 --- a/net/socket/connect_job_unittest.cc +++ b/net/socket/connect_job_unittest.cc
@@ -47,6 +47,7 @@ nullptr /* host_resolver */, nullptr /* proxy_delegate */, SSLClientSocketContext(), + SSLClientSocketContext(), nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */, nullptr /* net_log */,
diff --git a/net/socket/socket_bio_adapter.cc b/net/socket/socket_bio_adapter.cc index 09b7eb4..f7975b8a 100644 --- a/net/socket/socket_bio_adapter.cc +++ b/net/socket/socket_bio_adapter.cc
@@ -270,8 +270,8 @@ if (write_error_ != OK && write_error_ != ERR_IO_PENDING && read_result_ == ERR_IO_PENDING) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&SocketBIOAdapter::CallOnReadReady, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&SocketBIOAdapter::CallOnReadReady, + weak_factory_.GetWeakPtr())); } return bytes_copied;
diff --git a/net/socket/socket_test_util.cc b/net/socket/socket_test_util.cc index bbf9c8d..8379d114 100644 --- a/net/socket/socket_test_util.cc +++ b/net/socket/socket_test_util.cc
@@ -453,8 +453,8 @@ return MockRead(SYNCHRONOUS, ERR_IO_PENDING); } base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&SequencedSocketData::OnReadComplete, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&SequencedSocketData::OnReadComplete, + weak_factory_.GetWeakPtr())); CHECK_NE(COMPLETING, write_state_); read_state_ = COMPLETING; } else if (next_read.mode == SYNCHRONOUS) { @@ -506,8 +506,8 @@ NET_TRACE(1, " *** ") << "Posting task to complete write"; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&SequencedSocketData::OnWriteComplete, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&SequencedSocketData::OnWriteComplete, + weak_factory_.GetWeakPtr())); CHECK_NE(COMPLETING, read_state_); write_state_ = COMPLETING; } else if (next_write.mode == SYNCHRONOUS) { @@ -624,8 +624,8 @@ NET_TRACE(1, " ****** ") << "Posting task to complete read: " << sequence_number_; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&SequencedSocketData::OnReadComplete, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&SequencedSocketData::OnReadComplete, + weak_factory_.GetWeakPtr())); CHECK_NE(COMPLETING, write_state_); read_state_ = COMPLETING; } @@ -651,8 +651,8 @@ NET_TRACE(1, " ****** ") << "Posting task to complete write: " << sequence_number_; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&SequencedSocketData::OnWriteComplete, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&SequencedSocketData::OnWriteComplete, + weak_factory_.GetWeakPtr())); CHECK_NE(COMPLETING, read_state_); write_state_ = COMPLETING; } @@ -2157,7 +2157,7 @@ nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_client_session_cache */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */,
diff --git a/net/socket/socks_connect_job_unittest.cc b/net/socket/socks_connect_job_unittest.cc index 831a1d24..df41f3a 100644 --- a/net/socket/socks_connect_job_unittest.cc +++ b/net/socket/socks_connect_job_unittest.cc
@@ -75,7 +75,7 @@ return CommonConnectJobParams( "group_name", SocketTag(), true /* respect_limits */, &client_socket_factory_, &host_resolver_, nullptr /* proxy_delegate */, - SSLClientSocketContext(), + SSLClientSocketContext(), SSLClientSocketContext(), nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */, &net_log_, nullptr /* websocket_endpoint_lock_manager */);
diff --git a/net/socket/ssl_client_socket.h b/net/socket/ssl_client_socket.h index c514674..6e32c8d 100644 --- a/net/socket/ssl_client_socket.h +++ b/net/socket/ssl_client_socket.h
@@ -38,15 +38,13 @@ TransportSecurityState* transport_security_state_arg, CTVerifier* cert_transparency_verifier_arg, CTPolicyEnforcer* ct_policy_enforcer_arg, - SSLClientSessionCache* ssl_client_session_cache_arg, - const std::string& ssl_session_cache_shard_arg) + SSLClientSessionCache* ssl_client_session_cache_arg) : cert_verifier(cert_verifier_arg), channel_id_service(channel_id_service_arg), transport_security_state(transport_security_state_arg), cert_transparency_verifier(cert_transparency_verifier_arg), ct_policy_enforcer(ct_policy_enforcer_arg), - ssl_client_session_cache(ssl_client_session_cache_arg), - ssl_session_cache_shard(ssl_session_cache_shard_arg) {} + ssl_client_session_cache(ssl_client_session_cache_arg) {} CertVerifier* cert_verifier = nullptr; ChannelIDService* channel_id_service = nullptr; @@ -54,10 +52,6 @@ CTVerifier* cert_transparency_verifier = nullptr; CTPolicyEnforcer* ct_policy_enforcer = nullptr; SSLClientSessionCache* ssl_client_session_cache = nullptr; - // ssl_session_cache_shard is an opaque string that identifies a shard of the - // SSL session cache. SSL sockets with the same ssl_session_cache_shard may - // resume each other's SSL sessions but we'll never sessions between shards. - std::string ssl_session_cache_shard; }; // A client socket that uses SSL as the transport layer.
diff --git a/net/socket/ssl_client_socket_impl.cc b/net/socket/ssl_client_socket_impl.cc index e179c775..627807e 100644 --- a/net/socket/ssl_client_socket_impl.cc +++ b/net/socket/ssl_client_socket_impl.cc
@@ -419,7 +419,6 @@ host_and_port_(host_and_port), ssl_config_(ssl_config), ssl_client_session_cache_(context.ssl_client_session_cache), - ssl_session_cache_shard_(context.ssl_session_cache_shard), next_handshake_state_(STATE_NONE), in_confirm_handshake_(false), disconnected_(false), @@ -455,7 +454,6 @@ host_and_port_(host_and_port), ssl_config_(ssl_config), ssl_client_session_cache_(context.ssl_client_session_cache), - ssl_session_cache_shard_(context.ssl_session_cache_shard), next_handshake_state_(STATE_NONE), in_confirm_handshake_(false), disconnected_(false), @@ -1655,8 +1653,6 @@ std::string SSLClientSocketImpl::GetSessionCacheKey() const { std::string result = host_and_port_.ToString(); - result.push_back('/'); - result.append(ssl_session_cache_shard_); result.push_back('/'); result.push_back(ssl_config_.version_interference_probe ? '1' : '0');
diff --git a/net/socket/ssl_client_socket_impl.h b/net/socket/ssl_client_socket_impl.h index 3148190..8cb0975 100644 --- a/net/socket/ssl_client_socket_impl.h +++ b/net/socket/ssl_client_socket_impl.h
@@ -70,9 +70,6 @@ ~SSLClientSocketImpl() override; const HostPortPair& host_and_port() const { return host_and_port_; } - const std::string& ssl_session_cache_shard() const { - return ssl_session_cache_shard_; - } // Log SSL key material to |logger|. Must be called before any // SSLClientSockets are created. @@ -176,8 +173,7 @@ // the |ssl_info|.signed_certificate_timestamps list. void AddCTInfoToSSLInfo(SSLInfo* ssl_info) const; - // Returns a unique key string for the SSL session cache for this socket. This - // must not be called if |ssl_session_cache_shard_| is empty. + // Returns a unique key string for the SSL session cache for this socket. std::string GetSessionCacheKey() const; // Returns true if renegotiations are allowed. @@ -281,10 +277,6 @@ SSLConfig ssl_config_; // ssl_client_session_cache_ is a non-owning pointer to session cache SSLClientSessionCache* ssl_client_session_cache_; - // ssl_session_cache_shard_ is an opaque string that partitions the SSL - // session cache. i.e. sessions created with one value will not attempt to - // resume on the socket with a different value. - const std::string ssl_session_cache_shard_; enum State { STATE_NONE,
diff --git a/net/socket/ssl_client_socket_pool_unittest.cc b/net/socket/ssl_client_socket_pool_unittest.cc index 32d259f..31508ed 100644 --- a/net/socket/ssl_client_socket_pool_unittest.cc +++ b/net/socket/ssl_client_socket_pool_unittest.cc
@@ -101,7 +101,7 @@ nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */, @@ -116,7 +116,7 @@ NULL /* channel_id_service */, transport_security_state_.get(), &ct_verifier_, &ct_policy_enforcer_, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */, nullptr /* net_log */,
diff --git a/net/socket/ssl_client_socket_unittest.cc b/net/socket/ssl_client_socket_unittest.cc index 7a2460e..78d9b70e 100644 --- a/net/socket/ssl_client_socket_unittest.cc +++ b/net/socket/ssl_client_socket_unittest.cc
@@ -18,6 +18,7 @@ #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" +#include "base/strings/stringprintf.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "base/threading/thread_task_runner_handle.h" @@ -794,15 +795,14 @@ ct_verifier_(new DoNothingCTVerifier), ct_policy_enforcer_(new MockCTPolicyEnforcer), ssl_client_session_cache_( - new SSLClientSessionCache(SSLClientSessionCache::Config())) { + new SSLClientSessionCache(SSLClientSessionCache::Config())), + context_(cert_verifier_.get(), + nullptr /* channel_id_service */, + transport_security_state_.get(), + ct_verifier_.get(), + ct_policy_enforcer_.get(), + ssl_client_session_cache_.get()) { cert_verifier_->set_default_result(OK); - context_.cert_verifier = cert_verifier_.get(); - context_.transport_security_state = transport_security_state_.get(); - context_.cert_transparency_verifier = ct_verifier_.get(); - context_.ct_policy_enforcer = ct_policy_enforcer_.get(); - // Set a dummy session cache (and shard) to enable session caching. - context_.ssl_client_session_cache = ssl_client_session_cache_.get(); - context_.ssl_session_cache_shard = "shard"; EXPECT_CALL(*ct_policy_enforcer_, CheckCompliance(_, _, _)) .WillRepeatedly( @@ -4790,40 +4790,6 @@ EXPECT_EQ(stats.cert_size, stats.total_size); } -// Test that session caches are properly sharded. -TEST_F(SSLClientSocketTest, SessionCacheShard) { - ASSERT_TRUE(StartTestServer(SpawnedTestServer::SSLOptions())); - - // Perform a full handshake. - context_.ssl_session_cache_shard = "A"; - int rv; - ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv)); - ASSERT_THAT(rv, IsOk()); - SSLInfo ssl_info; - ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info)); - EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type); - - // The next connection resumes the session. - ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv)); - ASSERT_THAT(rv, IsOk()); - ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info)); - EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type); - - // A different shard does not resume. - context_.ssl_session_cache_shard = "B"; - ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv)); - ASSERT_THAT(rv, IsOk()); - ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info)); - EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type); - - // The original shard still resumes. - context_.ssl_session_cache_shard = "A"; - ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv)); - ASSERT_THAT(rv, IsOk()); - ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info)); - EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type); -} - TEST_F(SSLClientSocketTest, Tag) { ASSERT_TRUE(StartTestServer(SpawnedTestServer::SSLOptions()));
diff --git a/net/socket/ssl_connect_job.cc b/net/socket/ssl_connect_job.cc index 677638d5..8498ea2 100644 --- a/net/socket/ssl_connect_job.cc +++ b/net/socket/ssl_connect_job.cc
@@ -353,29 +353,23 @@ connect_timing_.ssl_start = base::TimeTicks::Now(); - // If privacy mode is enabled and the session shard is non-empty, prefix the - // SSL session shard with "pm/". Otherwise, prefix with "nopm/". - // TODO(https://crbug.com/927084): Consider moving this up to the socket pool - // layer, after giving socket pools knowledge of privacy mode. - SSLClientSocketContext context_with_privacy_mode( - ssl_client_socket_context().cert_verifier, - ssl_client_socket_context().channel_id_service, - ssl_client_socket_context().transport_security_state, - ssl_client_socket_context().cert_transparency_verifier, - ssl_client_socket_context().ct_policy_enforcer, - ssl_client_socket_context().ssl_client_session_cache, - (params_->privacy_mode() == PRIVACY_MODE_ENABLED ? "pm/" : "nopm/") + - ssl_client_socket_context().ssl_session_cache_shard); + // TODO(mmenke): Consider moving this up to the socket pool layer, after + // giving socket pools knowledge of privacy mode. + const SSLClientSocketContext& context = + params_->privacy_mode() == PRIVACY_MODE_ENABLED + ? ssl_client_socket_context_privacy_mode() + : ssl_client_socket_context(); + if (nested_socket_.get()) { DCHECK(!transport_socket_handle_); ssl_socket_ = client_socket_factory()->CreateSSLClientSocket( std::move(nested_socket_), params_->host_and_port(), - params_->ssl_config(), context_with_privacy_mode); + params_->ssl_config(), context); nested_connect_job_.reset(); } else { ssl_socket_ = client_socket_factory()->CreateSSLClientSocket( std::move(transport_socket_handle_), params_->host_and_port(), - params_->ssl_config(), context_with_privacy_mode); + params_->ssl_config(), context); } return ssl_socket_->Connect(callback_); }
diff --git a/net/socket/ssl_connect_job_unittest.cc b/net/socket/ssl_connect_job_unittest.cc index b6305b1..3ac937a 100644 --- a/net/socket/ssl_connect_job_unittest.cc +++ b/net/socket/ssl_connect_job_unittest.cc
@@ -95,8 +95,7 @@ &transport_security_state_, &ct_verifier_, &ct_policy_enforcer_, - nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */), + nullptr /* ssl_client_session_cache */), direct_transport_socket_params_( new TransportSocketParams(HostPortPair("host", 443), false, @@ -135,7 +134,7 @@ nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */, @@ -158,7 +157,7 @@ CommonConnectJobParams( kGroupName, SocketTag(), true /* respect_limits */, &socket_factory_, &host_resolver_, nullptr /* proxy_delegate */, - ssl_client_socket_context_, + ssl_client_socket_context_, ssl_client_socket_context_, nullptr /* socket_performance_watcher */, nullptr /* network_quality_estimator */, nullptr /* net_log */, nullptr /* websocket_lock_endpoint_manager */),
diff --git a/net/socket/ssl_server_socket_unittest.cc b/net/socket/ssl_server_socket_unittest.cc index 48352a7..78bb3ca7 100644 --- a/net/socket/ssl_server_socket_unittest.cc +++ b/net/socket/ssl_server_socket_unittest.cc
@@ -134,8 +134,8 @@ write_called_after_close_ = true; write_callback_ = std::move(callback); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&FakeDataChannel::DoWriteCallback, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&FakeDataChannel::DoWriteCallback, + weak_factory_.GetWeakPtr())); return ERR_IO_PENDING; } // This function returns synchronously, so make a copy of the buffer. @@ -143,8 +143,8 @@ base::MakeRefCounted<StringIOBuffer>(std::string(buf->data(), buf_len)), buf_len)); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&FakeDataChannel::DoReadCallback, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&FakeDataChannel::DoReadCallback, + weak_factory_.GetWeakPtr())); return buf_len; } @@ -156,8 +156,8 @@ closed_ = true; if (!read_callback_.is_null()) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&FakeDataChannel::DoReadCallback, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&FakeDataChannel::DoReadCallback, + weak_factory_.GetWeakPtr())); } } @@ -425,14 +425,10 @@ new FakeSocket(channel_2_.get(), channel_1_.get())); HostPortPair host_and_pair("unittest", 0); - SSLClientSocketContext context; - context.cert_verifier = cert_verifier_.get(); - context.transport_security_state = transport_security_state_.get(); - context.cert_transparency_verifier = ct_verifier_.get(); - context.ct_policy_enforcer = ct_policy_enforcer_.get(); - // Set a dummy session cache (and shard) to enable session caching. - context.ssl_client_session_cache = ssl_client_session_cache_.get(); - context.ssl_session_cache_shard = "shard"; + SSLClientSocketContext context( + cert_verifier_.get(), nullptr, transport_security_state_.get(), + ct_verifier_.get(), ct_policy_enforcer_.get(), + ssl_client_session_cache_.get()); client_socket_ = socket_factory_->CreateSSLClientSocket( std::move(client_connection), host_and_pair, client_ssl_config_,
diff --git a/net/socket/transport_client_socket_pool.cc b/net/socket/transport_client_socket_pool.cc index 72411d6..ef760d3 100644 --- a/net/socket/transport_client_socket_pool.cc +++ b/net/socket/transport_client_socket_pool.cc
@@ -126,6 +126,7 @@ HostResolver* host_resolver, ProxyDelegate* proxy_delegate, const SSLClientSocketContext& ssl_client_socket_context, + const SSLClientSocketContext& ssl_client_socket_context_privacy_mode, SocketPerformanceWatcherFactory* socket_performance_watcher_factory, NetworkQualityEstimator* network_quality_estimator, NetLog* net_log, @@ -134,6 +135,8 @@ host_resolver_(host_resolver), proxy_delegate_(proxy_delegate), ssl_client_socket_context_(ssl_client_socket_context), + ssl_client_socket_context_privacy_mode_( + ssl_client_socket_context_privacy_mode), socket_performance_watcher_factory_(socket_performance_watcher_factory), network_quality_estimator_(network_quality_estimator), net_log_(net_log), @@ -153,9 +156,9 @@ group_name, request.socket_tag(), request.respect_limits() == ClientSocketPool::RespectLimits::ENABLED, client_socket_factory_, host_resolver_, proxy_delegate_, - ssl_client_socket_context_, socket_performance_watcher_factory_, - network_quality_estimator_, net_log_, - nullptr /* websocket_endpoint_lock_manager */), + ssl_client_socket_context_, ssl_client_socket_context_privacy_mode_, + socket_performance_watcher_factory_, network_quality_estimator_, + net_log_, nullptr /* websocket_endpoint_lock_manager */), delegate, http_proxy_pool_for_ssl_pool_); } @@ -171,7 +174,7 @@ CTVerifier* cert_transparency_verifier, CTPolicyEnforcer* ct_policy_enforcer, SSLClientSessionCache* ssl_client_session_cache, - const std::string& ssl_session_cache_shard, + SSLClientSessionCache* ssl_client_session_cache_privacy_mode, SSLConfigService* ssl_config_service, SocketPerformanceWatcherFactory* socket_performance_watcher_factory, NetworkQualityEstimator* network_quality_estimator, @@ -191,8 +194,13 @@ transport_security_state, cert_transparency_verifier, ct_policy_enforcer, - ssl_client_session_cache, - ssl_session_cache_shard), + ssl_client_session_cache), + SSLClientSocketContext(cert_verifier, + channel_id_service, + transport_security_state, + cert_transparency_verifier, + ct_policy_enforcer, + ssl_client_session_cache_privacy_mode), socket_performance_watcher_factory, network_quality_estimator, net_log,
diff --git a/net/socket/transport_client_socket_pool.h b/net/socket/transport_client_socket_pool.h index 143d31f..29031d7 100644 --- a/net/socket/transport_client_socket_pool.h +++ b/net/socket/transport_client_socket_pool.h
@@ -114,7 +114,7 @@ CTVerifier* cert_transparency_verifier, CTPolicyEnforcer* ct_policy_enforcer, SSLClientSessionCache* ssl_client_session_cache, - const std::string& ssl_session_cache_shard, + SSLClientSessionCache* ssl_client_session_cache_privacy_mode, SSLConfigService* ssl_config_service, SocketPerformanceWatcherFactory* socket_performance_watcher_factory, NetworkQualityEstimator* network_quality_estimator, @@ -188,6 +188,7 @@ HostResolver* host_resolver, ProxyDelegate* proxy_delegate, const SSLClientSocketContext& ssl_client_socket_context, + const SSLClientSocketContext& ssl_client_socket_context_privacy_mode, SocketPerformanceWatcherFactory* socket_performance_watcher_factory, NetworkQualityEstimator* network_quality_estimator, NetLog* net_log, @@ -206,6 +207,7 @@ HostResolver* const host_resolver_; ProxyDelegate* const proxy_delegate_; const SSLClientSocketContext ssl_client_socket_context_; + const SSLClientSocketContext ssl_client_socket_context_privacy_mode_; SocketPerformanceWatcherFactory* const socket_performance_watcher_factory_; NetworkQualityEstimator* const network_quality_estimator_; NetLog* const net_log_;
diff --git a/net/socket/transport_client_socket_pool_unittest.cc b/net/socket/transport_client_socket_pool_unittest.cc index 8b6c276..806013d4 100644 --- a/net/socket/transport_client_socket_pool_unittest.cc +++ b/net/socket/transport_client_socket_pool_unittest.cc
@@ -105,27 +105,28 @@ &ct_verifier_, &ct_policy_enforcer_, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, ssl_config_service_.get(), nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */, nullptr /* net_log */), - pool_for_real_sockets_(kMaxSockets, - kMaxSocketsPerGroup, - ClientSocketFactory::GetDefaultFactory(), - host_resolver_.get(), - nullptr /* proxy_delegate */, - &cert_verifier_, - nullptr /* channel_id_server */, - &transport_security_state_, - &ct_verifier_, - &ct_policy_enforcer_, - nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, - ssl_config_service_.get(), - nullptr /* socket_performance_watcher_factory */, - nullptr /* network_quality_estimator */, - nullptr /* net_log */) {} + pool_for_real_sockets_( + kMaxSockets, + kMaxSocketsPerGroup, + ClientSocketFactory::GetDefaultFactory(), + host_resolver_.get(), + nullptr /* proxy_delegate */, + &cert_verifier_, + nullptr /* channel_id_server */, + &transport_security_state_, + &ct_verifier_, + &ct_policy_enforcer_, + nullptr /* ssl_client_session_cache */, + nullptr /* ssl_client_session_cache_privacy_mode */, + ssl_config_service_.get(), + nullptr /* socket_performance_watcher_factory */, + nullptr /* network_quality_estimator */, + nullptr /* net_log */) {} ~TransportClientSocketPoolTest() override { internal::ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled( @@ -451,7 +452,7 @@ nullptr /* channel_id_server */, nullptr /* transport_security_state */, nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */, nullptr /* net_log */); @@ -1165,7 +1166,7 @@ nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */, nullptr /* netlog */); @@ -1216,7 +1217,7 @@ nullptr /* channel_id_server */, nullptr /* transport_security_state */, nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */, nullptr /* netlog */); @@ -1341,7 +1342,7 @@ nullptr /* channel_id_server */, nullptr /* transport_security_state */, nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */, nullptr /* netlog */);
diff --git a/net/socket/transport_connect_job_unittest.cc b/net/socket/transport_connect_job_unittest.cc index c2e35f4f..90b4bf3 100644 --- a/net/socket/transport_connect_job_unittest.cc +++ b/net/socket/transport_connect_job_unittest.cc
@@ -44,7 +44,7 @@ return CommonConnectJobParams( kHostName /* group_name */, SocketTag(), true /* respect_limits */, &client_socket_factory_, &host_resolver_, nullptr /* proxy_delegate */, - SSLClientSocketContext(), + SSLClientSocketContext(), SSLClientSocketContext(), nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */, &net_log_, nullptr /* websocket_endpoint_lock_manager */);
diff --git a/net/socket/udp_socket_unittest.cc b/net/socket/udp_socket_unittest.cc index 5a06304..6a994d3 100644 --- a/net/socket/udp_socket_unittest.cc +++ b/net/socket/udp_socket_unittest.cc
@@ -207,8 +207,8 @@ // Client sends to the server. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&UDPSocketTest::WriteSocketIgnoreResult, - base::Unretained(this), client.get(), simple_message)); + base::BindOnce(&UDPSocketTest::WriteSocketIgnoreResult, + base::Unretained(this), client.get(), simple_message)); run_loop.Run(); EXPECT_EQ(simple_message.length(), static_cast<size_t>(read_result)); EXPECT_EQ(simple_message, std::string(buffer_->data(), read_result));
diff --git a/net/socket/websocket_endpoint_lock_manager.cc b/net/socket/websocket_endpoint_lock_manager.cc index 9acdaa8..cdf90aa 100644 --- a/net/socket/websocket_endpoint_lock_manager.cc +++ b/net/socket/websocket_endpoint_lock_manager.cc
@@ -122,8 +122,8 @@ ++pending_unlock_count_; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&WebSocketEndpointLockManager::DelayedUnlockEndpoint, - weak_factory_.GetWeakPtr(), endpoint), + base::BindOnce(&WebSocketEndpointLockManager::DelayedUnlockEndpoint, + weak_factory_.GetWeakPtr(), endpoint), unlock_delay_); }
diff --git a/net/socket/websocket_transport_client_socket_pool.cc b/net/socket/websocket_transport_client_socket_pool.cc index ad96a7b..113c2d1f 100644 --- a/net/socket/websocket_transport_client_socket_pool.cc +++ b/net/socket/websocket_transport_client_socket_pool.cc
@@ -38,7 +38,7 @@ CTVerifier* cert_transparency_verifier, CTPolicyEnforcer* ct_policy_enforcer, SSLClientSessionCache* ssl_client_session_cache, - const std::string& ssl_session_cache_shard, + SSLClientSessionCache* ssl_client_session_cache_privacy_mode, SSLConfigService* ssl_config_service, NetworkQualityEstimator* network_quality_estimator, WebSocketEndpointLockManager* websocket_endpoint_lock_manager, @@ -55,7 +55,7 @@ cert_transparency_verifier, ct_policy_enforcer, ssl_client_session_cache, - ssl_session_cache_shard, + ssl_client_session_cache_privacy_mode, ssl_config_service, nullptr /* socket_performance_watcher_factory */, network_quality_estimator, @@ -69,8 +69,14 @@ transport_security_state, cert_transparency_verifier, ct_policy_enforcer, - ssl_client_session_cache, - ssl_session_cache_shard), + ssl_client_session_cache), + ssl_client_socket_context_privacy_mode_( + cert_verifier, + channel_id_service, + transport_security_state, + cert_transparency_verifier, + ct_policy_enforcer, + ssl_client_session_cache_privacy_mode), network_quality_estimator_(network_quality_estimator), websocket_endpoint_lock_manager_(websocket_endpoint_lock_manager), max_sockets_(max_sockets), @@ -151,6 +157,7 @@ respect_limits == RespectLimits::ENABLED, client_socket_factory_, host_resolver_, proxy_delegate_, ssl_client_socket_context_, + ssl_client_socket_context_privacy_mode_, nullptr /* SocketPerformanceWatcherFactory */, network_quality_estimator_, pool_net_log_, websocket_endpoint_lock_manager_),
diff --git a/net/socket/websocket_transport_client_socket_pool.h b/net/socket/websocket_transport_client_socket_pool.h index 5e01c39..56d9c50 100644 --- a/net/socket/websocket_transport_client_socket_pool.h +++ b/net/socket/websocket_transport_client_socket_pool.h
@@ -54,7 +54,7 @@ CTVerifier* cert_transparency_verifier, CTPolicyEnforcer* ct_policy_enforcer, SSLClientSessionCache* ssl_client_session_cache, - const std::string& ssl_session_cache_shard, + SSLClientSessionCache* ssl_client_session_cache_privacy_mode, SSLConfigService* ssl_config_service, NetworkQualityEstimator* network_quality_estimator, WebSocketEndpointLockManager* websocket_endpoint_lock_manager, @@ -202,6 +202,7 @@ HostResolver* const host_resolver_; ProxyDelegate* const proxy_delegate_; const SSLClientSocketContext ssl_client_socket_context_; + const SSLClientSocketContext ssl_client_socket_context_privacy_mode_; NetworkQualityEstimator* const network_quality_estimator_; WebSocketEndpointLockManager* websocket_endpoint_lock_manager_; const int max_sockets_;
diff --git a/net/socket/websocket_transport_client_socket_pool_unittest.cc b/net/socket/websocket_transport_client_socket_pool_unittest.cc index 9801f79..8a2624d 100644 --- a/net/socket/websocket_transport_client_socket_pool_unittest.cc +++ b/net/socket/websocket_transport_client_socket_pool_unittest.cc
@@ -78,7 +78,7 @@ nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* network_quality_estimator */, &websocket_endpoint_lock_manager_, @@ -545,7 +545,7 @@ nullptr /* transport_security_state */, nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* network_quality_estimator */, &websocket_endpoint_lock_manager_, nullptr /* netlog */); @@ -591,7 +591,7 @@ nullptr /* transport_security_state */, nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* network_quality_estimator */, &websocket_endpoint_lock_manager_, nullptr /* netlog */); @@ -636,7 +636,7 @@ nullptr /* transport_security_state */, nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* network_quality_estimator */, &websocket_endpoint_lock_manager_, nullptr /* netlog */); @@ -673,7 +673,7 @@ nullptr /* transport_security_state */, nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* network_quality_estimator */, &websocket_endpoint_lock_manager_, nullptr /* netlog */); @@ -711,7 +711,7 @@ nullptr /* transport_security_state */, nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* network_quality_estimator */, &websocket_endpoint_lock_manager_, nullptr /* netlog */); @@ -753,7 +753,7 @@ nullptr /* transport_security_state */, nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* network_quality_estimator */, &websocket_endpoint_lock_manager_, nullptr /* netlog */); @@ -803,7 +803,7 @@ nullptr /* transport_security_state */, nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* network_quality_estimator */, &websocket_endpoint_lock_manager_, nullptr /* netlog */); @@ -847,7 +847,7 @@ nullptr /* transport_security_state */, nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* network_quality_estimator */, &websocket_endpoint_lock_manager_, nullptr /* netlog */); @@ -895,7 +895,7 @@ nullptr /* transport_security_state */, nullptr /* cert_transparency_verifier */, nullptr /* ct_policy_enforcer */, nullptr /* ssl_client_session_cache */, - std::string() /* ssl_session_cache_shard */, + nullptr /* ssl_client_session_cache_privacy_mode */, nullptr /* ssl_config_service */, nullptr /* network_quality_estimator */, &websocket_endpoint_lock_manager_, nullptr /* netlog */); const base::TimeDelta connect_job_timeout =
diff --git a/net/spdy/bidirectional_stream_spdy_impl.cc b/net/spdy/bidirectional_stream_spdy_impl.cc index 89f217a..f1281455 100644 --- a/net/spdy/bidirectional_stream_spdy_impl.cc +++ b/net/spdy/bidirectional_stream_spdy_impl.cc
@@ -69,8 +69,8 @@ if (!spdy_session_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&BidirectionalStreamSpdyImpl::NotifyError, - weak_factory_.GetWeakPtr(), ERR_CONNECTION_CLOSED)); + base::BindOnce(&BidirectionalStreamSpdyImpl::NotifyError, + weak_factory_.GetWeakPtr(), ERR_CONNECTION_CLOSED)); return; } @@ -122,8 +122,8 @@ if (written_end_of_stream_) { LOG(ERROR) << "Writing after end of stream is written."; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&BidirectionalStreamSpdyImpl::NotifyError, - weak_factory_.GetWeakPtr(), ERR_UNEXPECTED)); + FROM_HERE, base::BindOnce(&BidirectionalStreamSpdyImpl::NotifyError, + weak_factory_.GetWeakPtr(), ERR_UNEXPECTED)); return; } @@ -397,14 +397,14 @@ // blackhole any pending write data. crbug.com/650438. if (stream_closed_ && closed_stream_status_ == OK) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&BidirectionalStreamSpdyImpl::OnDataSent, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&BidirectionalStreamSpdyImpl::OnDataSent, + weak_factory_.GetWeakPtr())); return true; } LOG(ERROR) << "Trying to send data after stream has been destroyed."; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&BidirectionalStreamSpdyImpl::NotifyError, - weak_factory_.GetWeakPtr(), ERR_UNEXPECTED)); + FROM_HERE, base::BindOnce(&BidirectionalStreamSpdyImpl::NotifyError, + weak_factory_.GetWeakPtr(), ERR_UNEXPECTED)); return true; }
diff --git a/net/spdy/spdy_proxy_client_socket_unittest.cc b/net/spdy/spdy_proxy_client_socket_unittest.cc index 3a357f79b..75d7f9ff 100644 --- a/net/spdy/spdy_proxy_client_socket_unittest.cc +++ b/net/spdy/spdy_proxy_client_socket_unittest.cc
@@ -111,9 +111,13 @@ session_deps->transport_security_state.get(), session_deps->cert_transparency_verifier.get(), session_deps->ct_policy_enforcer.get(), - nullptr /* ssl_client_session_cache_arg */, - std::string() /* ssl_session_cache_shard_arg */ - ), + nullptr /* ssl_client_session_cache_arg */), + SSLClientSocketContext(session_deps->cert_verifier.get(), + session_deps->channel_id_service.get(), + session_deps->transport_security_state.get(), + session_deps->cert_transparency_verifier.get(), + session_deps->ct_policy_enforcer.get(), + nullptr /* ssl_client_session_cache_arg */), nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */, session_deps->net_log, nullptr /* websocket_endpoint_lock_manager */),
diff --git a/net/spdy/spdy_session.cc b/net/spdy/spdy_session.cc index b8648e48..f63c127 100644 --- a/net/spdy/spdy_session.cc +++ b/net/spdy/spdy_session.cc
@@ -1761,8 +1761,8 @@ // possible that the un-stalled stream will be stalled again if it loses. // TODO(jgraettinger): Provide stronger ordering guarantees. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&SpdySession::CompleteStreamRequest, - weak_factory_.GetWeakPtr(), pending_request)); + FROM_HERE, base::BindOnce(&SpdySession::CompleteStreamRequest, + weak_factory_.GetWeakPtr(), pending_request)); } } @@ -1917,8 +1917,8 @@ base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, - base::Bind(&SpdySession::CancelPushedStreamIfUnclaimed, GetWeakPtr(), - stream_id), + base::BindOnce(&SpdySession::CancelPushedStreamIfUnclaimed, GetWeakPtr(), + stream_id), base::TimeDelta::FromSeconds(kPushedStreamLifetimeSeconds)); net::NetworkTrafficAnnotationTag traffic_annotation = @@ -2146,8 +2146,8 @@ time_func_() > yield_after_time)) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&SpdySession::PumpReadLoop, weak_factory_.GetWeakPtr(), - READ_STATE_DO_READ, OK)); + base::BindOnce(&SpdySession::PumpReadLoop, weak_factory_.GetWeakPtr(), + READ_STATE_DO_READ, OK)); result = ERR_IO_PENDING; break; } @@ -2251,8 +2251,8 @@ write_state_ = WRITE_STATE_DO_WRITE; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&SpdySession::PumpWriteLoop, weak_factory_.GetWeakPtr(), - WRITE_STATE_DO_WRITE, OK)); + base::BindOnce(&SpdySession::PumpWriteLoop, weak_factory_.GetWeakPtr(), + WRITE_STATE_DO_WRITE, OK)); } } @@ -2603,8 +2603,9 @@ check_ping_status_pending_ = true; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, base::Bind(&SpdySession::CheckPingStatus, - weak_factory_.GetWeakPtr(), time_func_()), + FROM_HERE, + base::BindOnce(&SpdySession::CheckPingStatus, weak_factory_.GetWeakPtr(), + time_func_()), hung_interval_); } @@ -2629,8 +2630,9 @@ // Check the status of connection after a delay. const base::TimeDelta delay = last_read_time_ + hung_interval_ - now; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, base::Bind(&SpdySession::CheckPingStatus, - weak_factory_.GetWeakPtr(), now), + FROM_HERE, + base::BindOnce(&SpdySession::CheckPingStatus, weak_factory_.GetWeakPtr(), + now), delay); }
diff --git a/net/spdy/spdy_stream.cc b/net/spdy/spdy_stream.cc index e47e582..ccb43198 100644 --- a/net/spdy/spdy_stream.cc +++ b/net/spdy/spdy_stream.cc
@@ -139,7 +139,8 @@ if (io_state_ == STATE_HALF_CLOSED_LOCAL_UNCLAIMED) { DCHECK_EQ(type_, SPDY_PUSH_STREAM); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&SpdyStream::PushedStreamReplay, GetWeakPtr())); + FROM_HERE, + base::BindOnce(&SpdyStream::PushedStreamReplay, GetWeakPtr())); } }
diff --git a/net/ssl/default_channel_id_store_unittest.cc b/net/ssl/default_channel_id_store_unittest.cc index 4955c9c71..3f3ecb30 100644 --- a/net/ssl/default_channel_id_store_unittest.cc +++ b/net/ssl/default_channel_id_store_unittest.cc
@@ -106,7 +106,7 @@ } base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(loaded_callback, base::Passed(&channel_ids))); + FROM_HERE, base::BindOnce(loaded_callback, std::move(channel_ids))); } void MockPersistentStore::AddChannelID(
diff --git a/net/test/embedded_test_server/embedded_test_server.cc b/net/test/embedded_test_server/embedded_test_server.cc index 6578877c..dc86941 100644 --- a/net/test/embedded_test_server/embedded_test_server.cc +++ b/net/test/embedded_test_server/embedded_test_server.cc
@@ -180,8 +180,8 @@ CHECK(io_thread_->WaitUntilThreadStarted()); io_thread_->task_runner()->PostTask( - FROM_HERE, - base::Bind(&EmbeddedTestServer::DoAcceptLoop, base::Unretained(this))); + FROM_HERE, base::BindOnce(&EmbeddedTestServer::DoAcceptLoop, + base::Unretained(this))); } bool EmbeddedTestServer::ShutdownAndWaitUntilComplete() {
diff --git a/net/test/embedded_test_server/embedded_test_server_unittest.cc b/net/test/embedded_test_server/embedded_test_server_unittest.cc index e117096..318fd6e4 100644 --- a/net/test/embedded_test_server/embedded_test_server_unittest.cc +++ b/net/test/embedded_test_server/embedded_test_server_unittest.cc
@@ -425,9 +425,9 @@ void SendInfinite(const SendBytesCallback& send) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(send, "echo", - base::Bind(&InfiniteResponse::SendInfinite, - weak_ptr_factory_.GetWeakPtr(), send))); + base::BindOnce(send, "echo", + base::Bind(&InfiniteResponse::SendInfinite, + weak_ptr_factory_.GetWeakPtr(), send))); } base::WeakPtrFactory<InfiniteResponse> weak_ptr_factory_;
diff --git a/net/test/spawned_test_server/local_test_server_win.cc b/net/test/spawned_test_server/local_test_server_win.cc index c117d62..06a9401e 100644 --- a/net/test/spawned_test_server/local_test_server_win.cc +++ b/net/test/spawned_test_server/local_test_server_win.cc
@@ -54,7 +54,7 @@ // Prepare a timeout in case the server fails to start. bool unblocked = false; thread.task_runner()->PostDelayedTask( - FROM_HERE, base::Bind(UnblockPipe, write_fd, bytes_max, &unblocked), + FROM_HERE, base::BindOnce(UnblockPipe, write_fd, bytes_max, &unblocked), TestTimeouts::action_max_timeout()); DWORD bytes_read = 0;
diff --git a/net/test/url_request/ssl_certificate_error_job.cc b/net/test/url_request/ssl_certificate_error_job.cc index d23f9ced..6391825 100644 --- a/net/test/url_request/ssl_certificate_error_job.cc +++ b/net/test/url_request/ssl_certificate_error_job.cc
@@ -47,8 +47,8 @@ void SSLCertificateErrorJob::Start() { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&SSLCertificateErrorJob::NotifyError, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&SSLCertificateErrorJob::NotifyError, + weak_factory_.GetWeakPtr())); } void SSLCertificateErrorJob::AddUrlHandler() {
diff --git a/net/test/url_request/url_request_failed_job.cc b/net/test/url_request/url_request_failed_job.cc index 71b7b462..a893f72 100644 --- a/net/test/url_request/url_request_failed_job.cc +++ b/net/test/url_request/url_request_failed_job.cc
@@ -99,8 +99,8 @@ void URLRequestFailedJob::Start() { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&URLRequestFailedJob::StartAsync, weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&URLRequestFailedJob::StartAsync, + weak_factory_.GetWeakPtr())); } int URLRequestFailedJob::ReadRawData(IOBuffer* buf, int buf_size) { @@ -109,8 +109,8 @@ return net_error_; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&URLRequestFailedJob::ReadRawDataComplete, - weak_factory_.GetWeakPtr(), net_error_)); + FROM_HERE, base::BindOnce(&URLRequestFailedJob::ReadRawDataComplete, + weak_factory_.GetWeakPtr(), net_error_)); return ERR_IO_PENDING; }
diff --git a/net/test/url_request/url_request_hanging_read_job.cc b/net/test/url_request/url_request_hanging_read_job.cc index 006e7bab..6790f6c 100644 --- a/net/test/url_request/url_request_hanging_read_job.cc +++ b/net/test/url_request/url_request_hanging_read_job.cc
@@ -54,8 +54,8 @@ // Start reading asynchronously so that all error reporting and data // callbacks happen as they would for network requests. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&URLRequestHangingReadJob::StartAsync, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&URLRequestHangingReadJob::StartAsync, + weak_factory_.GetWeakPtr())); } URLRequestHangingReadJob::~URLRequestHangingReadJob() = default;
diff --git a/net/test/url_request/url_request_mock_data_job.cc b/net/test/url_request/url_request_mock_data_job.cc index 9cef3e9..b6d5471 100644 --- a/net/test/url_request/url_request_mock_data_job.cc +++ b/net/test/url_request/url_request_mock_data_job.cc
@@ -118,8 +118,8 @@ // Start reading asynchronously so that all error reporting and data // callbacks happen as they would for network requests. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&URLRequestMockDataJob::StartAsync, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&URLRequestMockDataJob::StartAsync, + weak_factory_.GetWeakPtr())); } URLRequestMockDataJob::~URLRequestMockDataJob() = default;
diff --git a/net/test/url_request/url_request_slow_download_job.cc b/net/test/url_request/url_request_slow_download_job.cc index 72a2b5a..efce74d7 100644 --- a/net/test/url_request/url_request_slow_download_job.cc +++ b/net/test/url_request/url_request_slow_download_job.cc
@@ -63,8 +63,8 @@ void URLRequestSlowDownloadJob::Start() { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&URLRequestSlowDownloadJob::StartAsync, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&URLRequestSlowDownloadJob::StartAsync, + weak_factory_.GetWeakPtr())); } int64_t URLRequestSlowDownloadJob::GetTotalReceivedBytes() const { @@ -203,8 +203,9 @@ buffer_ = buf; buffer_size_ = buf_size; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, base::Bind(&URLRequestSlowDownloadJob::CheckDoneStatus, - weak_factory_.GetWeakPtr()), + FROM_HERE, + base::BindOnce(&URLRequestSlowDownloadJob::CheckDoneStatus, + weak_factory_.GetWeakPtr()), base::TimeDelta::FromMilliseconds(100)); return ERR_IO_PENDING; } @@ -227,8 +228,9 @@ ReadRawDataComplete(ERR_CONNECTION_RESET); } else { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, base::Bind(&URLRequestSlowDownloadJob::CheckDoneStatus, - weak_factory_.GetWeakPtr()), + FROM_HERE, + base::BindOnce(&URLRequestSlowDownloadJob::CheckDoneStatus, + weak_factory_.GetWeakPtr()), base::TimeDelta::FromMilliseconds(100)); } }
diff --git a/net/tools/quic/quic_simple_server.cc b/net/tools/quic/quic_simple_server.cc index 405c2dc9..6fd3830b 100644 --- a/net/tools/quic/quic_simple_server.cc +++ b/net/tools/quic/quic_simple_server.cc
@@ -180,8 +180,8 @@ if (dispatcher_->HasChlosBuffered()) { // No more packets to read, so yield before processing buffered packets. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&QuicSimpleServer::StartReading, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&QuicSimpleServer::StartReading, + weak_factory_.GetWeakPtr())); } return; } @@ -191,8 +191,8 @@ // Schedule the processing through the message loop to 1) prevent infinite // recursion and 2) avoid blocking the thread for too long. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&QuicSimpleServer::OnReadComplete, - weak_factory_.GetWeakPtr(), result)); + FROM_HERE, base::BindOnce(&QuicSimpleServer::OnReadComplete, + weak_factory_.GetWeakPtr(), result)); } else { OnReadComplete(result); }
diff --git a/net/tools/stress_cache/stress_cache.cc b/net/tools/stress_cache/stress_cache.cc index 879c3fbf..2483cebe 100644 --- a/net/tools/stress_cache/stress_cache.cc +++ b/net/tools/stress_cache/stress_cache.cc
@@ -269,7 +269,7 @@ g_data->pendig_operations--; DCHECK(g_data->pendig_operations); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, - base::Bind(&LoopTask)); + base::BindOnce(&LoopTask)); } // The task that keeps the main thread busy. Whenever an entry becomes idle this @@ -290,7 +290,7 @@ } base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, - base::Bind(&LoopTask)); + base::BindOnce(&LoopTask)); } // This thread will loop forever, adding and removing entries from the cache. @@ -333,7 +333,7 @@ g_data->keys[i] = GenerateStressKey(); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, - base::Bind(&LoopTask)); + base::BindOnce(&LoopTask)); base::RunLoop().Run(); } @@ -361,7 +361,7 @@ void RunSoon(scoped_refptr<base::SingleThreadTaskRunner> task_runner) { const base::TimeDelta kTaskDelay = base::TimeDelta::FromSeconds(10); - task_runner->PostDelayedTask(FROM_HERE, base::Bind(&CrashCallback), + task_runner->PostDelayedTask(FROM_HERE, base::BindOnce(&CrashCallback), kTaskDelay); }
diff --git a/net/url_request/test_url_fetcher_factory.cc b/net/url_request/test_url_fetcher_factory.cc index 916190f..c1d1ec1 100644 --- a/net/url_request/test_url_fetcher_factory.cc +++ b/net/url_request/test_url_fetcher_factory.cc
@@ -399,7 +399,7 @@ TestURLFetcher::Start(); base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&FakeURLFetcher::RunDelegate, weak_factory_.GetWeakPtr())); + base::BindOnce(&FakeURLFetcher::RunDelegate, weak_factory_.GetWeakPtr())); } void FakeURLFetcher::RunDelegate() {
diff --git a/net/url_request/test_url_request_interceptor.cc b/net/url_request/test_url_request_interceptor.cc index ae26295..6644369 100644 --- a/net/url_request/test_url_request_interceptor.cc +++ b/net/url_request/test_url_request_interceptor.cc
@@ -155,24 +155,22 @@ network_task_runner_, worker_task_runner)) { network_task_runner_->PostTask( - FROM_HERE, base::Bind(&Delegate::Register, base::Unretained(delegate_))); + FROM_HERE, + base::BindOnce(&Delegate::Register, base::Unretained(delegate_))); } TestURLRequestInterceptor::~TestURLRequestInterceptor() { network_task_runner_->PostTask( - FROM_HERE, base::Bind(&Delegate::Unregister, scheme_, hostname_)); + FROM_HERE, base::BindOnce(&Delegate::Unregister, scheme_, hostname_)); } void TestURLRequestInterceptor::SetResponse(const GURL& url, const base::FilePath& path) { CHECK_EQ(scheme_, url.scheme()); CHECK_EQ(hostname_, url.host()); - network_task_runner_->PostTask(FROM_HERE, - base::Bind(&Delegate::SetResponse, - base::Unretained(delegate_), - url, - path, - false)); + network_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&Delegate::SetResponse, + base::Unretained(delegate_), url, path, false)); } void TestURLRequestInterceptor::SetResponseIgnoreQuery( @@ -180,12 +178,9 @@ const base::FilePath& path) { CHECK_EQ(scheme_, url.scheme()); CHECK_EQ(hostname_, url.host()); - network_task_runner_->PostTask(FROM_HERE, - base::Bind(&Delegate::SetResponse, - base::Unretained(delegate_), - url, - path, - true)); + network_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&Delegate::SetResponse, + base::Unretained(delegate_), url, path, true)); } int TestURLRequestInterceptor::GetHitCount() {
diff --git a/net/url_request/url_fetcher_core.cc b/net/url_request/url_fetcher_core.cc index 97a7e3c8..1759ff54 100644 --- a/net/url_request/url_fetcher_core.cc +++ b/net/url_request/url_fetcher_core.cc
@@ -119,7 +119,7 @@ DCHECK(network_task_runner_.get()) << "We need an IO task runner"; network_task_runner_->PostTask( - FROM_HERE, base::Bind(&URLFetcherCore::StartOnIOThread, this)); + FROM_HERE, base::BindOnce(&URLFetcherCore::StartOnIOThread, this)); } void URLFetcherCore::Stop() { @@ -135,7 +135,7 @@ } else { network_task_runner_->PostTask( FROM_HERE, - base::Bind(&URLFetcherCore::CancelURLRequest, this, ERR_ABORTED)); + base::BindOnce(&URLFetcherCore::CancelURLRequest, this, ERR_ABORTED)); } } @@ -207,9 +207,8 @@ DCHECK(network_task_runner_.get()); DCHECK(is_chunked_upload_); network_task_runner_->PostTask( - FROM_HERE, - base::Bind(&URLFetcherCore::CompleteAddingUploadDataChunk, this, content, - is_last_chunk)); + FROM_HERE, base::BindOnce(&URLFetcherCore::CompleteAddingUploadDataChunk, + this, content, is_last_chunk)); } void URLFetcherCore::SetLoadFlags(int load_flags) { @@ -361,7 +360,8 @@ DCHECK(delegate_task_runner_->RunsTasksInCurrentSequence()); if (network_task_runner_.get()) { network_task_runner_->PostTask( - FROM_HERE, base::Bind(&URLFetcherCore::NotifyMalformedContent, this)); + FROM_HERE, + base::BindOnce(&URLFetcherCore::NotifyMalformedContent, this)); } } @@ -684,7 +684,7 @@ GetBackoffReleaseTime()); if (delay != 0) { network_task_runner_->PostDelayedTask( - FROM_HERE, base::Bind(&URLFetcherCore::StartURLRequest, this), + FROM_HERE, base::BindOnce(&URLFetcherCore::StartURLRequest, this), base::TimeDelta::FromMilliseconds(delay)); return; } @@ -801,7 +801,7 @@ // Retry soon, after flushing all the current tasks which may include // further network change observers. network_task_runner_->PostTask( - FROM_HERE, base::Bind(&URLFetcherCore::StartOnIOThread, this)); + FROM_HERE, base::BindOnce(&URLFetcherCore::StartOnIOThread, this)); return; } @@ -810,8 +810,8 @@ url_request_data_key_ = NULL; url_request_create_data_callback_.Reset(); bool posted = delegate_task_runner_->PostTask( - FROM_HERE, - base::Bind(&URLFetcherCore::OnCompletedURLRequest, this, backoff_delay)); + FROM_HERE, base::BindOnce(&URLFetcherCore::OnCompletedURLRequest, this, + backoff_delay)); // If the delegate message loop does not exist any more, then the delegate // should be gone too. @@ -822,7 +822,7 @@ CancelURLRequest(result); delegate_task_runner_->PostTask( FROM_HERE, - base::Bind(&URLFetcherCore::InformDelegateFetchIsComplete, this)); + base::BindOnce(&URLFetcherCore::InformDelegateFetchIsComplete, this)); } void URLFetcherCore::ReleaseRequest() { @@ -924,7 +924,7 @@ } delegate_task_runner_->PostTask( FROM_HERE, - base::Bind( + base::BindOnce( &URLFetcherCore::InformDelegateUploadProgressInDelegateSequence, this, current, total)); } @@ -943,7 +943,7 @@ DCHECK(network_task_runner_->BelongsToCurrentThread()); delegate_task_runner_->PostTask( FROM_HERE, - base::Bind( + base::BindOnce( &URLFetcherCore::InformDelegateDownloadProgressInDelegateSequence, this, current_response_bytes_, total_response_bytes_, request_->GetTotalReceivedBytes()));
diff --git a/net/url_request/url_fetcher_impl_unittest.cc b/net/url_request/url_fetcher_impl_unittest.cc index eb3e20c..8c7283fa 100644 --- a/net/url_request/url_fetcher_impl_unittest.cc +++ b/net/url_request/url_fetcher_impl_unittest.cc
@@ -264,11 +264,11 @@ if (!network_task_runner_->RunsTasksInCurrentSequence()) { network_task_runner_->PostTask( FROM_HERE, - base::Bind(&FetcherTestURLRequestContextGetter::AddThrottlerEntry, - this, url, url_id, sliding_window_period_ms, - max_send_threshold, initial_backoff_ms, multiply_factor, - jitter_factor, maximum_backoff_ms, - reserve_sending_time_for_next_request)); + base::BindOnce(&FetcherTestURLRequestContextGetter::AddThrottlerEntry, + this, url, url_id, sliding_window_period_ms, + max_send_threshold, initial_backoff_ms, + multiply_factor, jitter_factor, maximum_backoff_ms, + reserve_sending_time_for_next_request)); return; } scoped_refptr<URLRequestThrottlerEntry> entry(new URLRequestThrottlerEntry( @@ -289,7 +289,7 @@ if (!network_task_runner_->RunsTasksInCurrentSequence()) { network_task_runner_->PostTask( FROM_HERE, - base::Bind(&FetcherTestURLRequestContextGetter::Shutdown, this)); + base::BindOnce(&FetcherTestURLRequestContextGetter::Shutdown, this)); return; }
diff --git a/net/url_request/url_fetcher_response_writer.cc b/net/url_request/url_fetcher_response_writer.cc index ecd81fef0..ca0e9f9 100644 --- a/net/url_request/url_fetcher_response_writer.cc +++ b/net/url_request/url_fetcher_response_writer.cc
@@ -166,10 +166,9 @@ file_stream_.reset(); DisownFile(); - file_task_runner_->PostTask(FROM_HERE, - base::Bind(base::IgnoreResult(&base::DeleteFile), - file_path_, - false /* recursive */)); + file_task_runner_->PostTask( + FROM_HERE, base::BindOnce(base::IgnoreResult(&base::DeleteFile), + file_path_, false /* recursive */)); } void URLFetcherFileWriter::DidCreateTempFile(base::FilePath* temp_file_path,
diff --git a/net/url_request/url_request_error_job.cc b/net/url_request/url_request_error_job.cc index 85ab61f2..0eda199 100644 --- a/net/url_request/url_request_error_job.cc +++ b/net/url_request/url_request_error_job.cc
@@ -24,8 +24,8 @@ void URLRequestErrorJob::Start() { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&URLRequestErrorJob::StartAsync, weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&URLRequestErrorJob::StartAsync, + weak_factory_.GetWeakPtr())); } void URLRequestErrorJob::Kill() {
diff --git a/net/url_request/url_request_file_dir_job.cc b/net/url_request/url_request_file_dir_job.cc index cb630a59..ca05b6c3 100644 --- a/net/url_request/url_request_file_dir_job.cc +++ b/net/url_request/url_request_file_dir_job.cc
@@ -52,8 +52,8 @@ // Start reading asynchronously so that all error reporting and data // callbacks happen as they would for network requests. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&URLRequestFileDirJob::StartAsync, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&URLRequestFileDirJob::StartAsync, + weak_factory_.GetWeakPtr())); } void URLRequestFileDirJob::Kill() {
diff --git a/net/url_request/url_request_ftp_job.cc b/net/url_request/url_request_ftp_job.cc index b62f09d..d1fb951 100644 --- a/net/url_request/url_request_ftp_job.cc +++ b/net/url_request/url_request_ftp_job.cc
@@ -255,8 +255,8 @@ void URLRequestFtpJob::OnStartCompletedAsync(int result) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&URLRequestFtpJob::OnStartCompleted, - weak_factory_.GetWeakPtr(), result)); + FROM_HERE, base::BindOnce(&URLRequestFtpJob::OnStartCompleted, + weak_factory_.GetWeakPtr(), result)); } void URLRequestFtpJob::OnReadCompleted(int result) {
diff --git a/net/url_request/url_request_http_job.cc b/net/url_request/url_request_http_job.cc index 884edf75..6c00978 100644 --- a/net/url_request/url_request_http_job.cc +++ b/net/url_request/url_request_http_job.cc
@@ -559,9 +559,9 @@ // Don't call back synchronously to the delegate. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&URLRequestHttpJob::NotifyStartError, - weak_factory_.GetWeakPtr(), - URLRequestStatus(URLRequestStatus::FAILED, result))); + base::BindOnce(&URLRequestHttpJob::NotifyStartError, + weak_factory_.GetWeakPtr(), + URLRequestStatus(URLRequestStatus::FAILED, result))); } } @@ -637,8 +637,8 @@ // The transaction started synchronously, but we need to notify the // URLRequest delegate via the message loop. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&URLRequestHttpJob::OnStartCompleted, - weak_factory_.GetWeakPtr(), rv)); + FROM_HERE, base::BindOnce(&URLRequestHttpJob::OnStartCompleted, + weak_factory_.GetWeakPtr(), rv)); } void URLRequestHttpJob::AddExtraHeaders() { @@ -1233,8 +1233,8 @@ // We have to do this via InvokeLater to avoid "recursing" the consumer. // base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&URLRequestHttpJob::OnStartCompleted, - weak_factory_.GetWeakPtr(), OK)); + FROM_HERE, base::BindOnce(&URLRequestHttpJob::OnStartCompleted, + weak_factory_.GetWeakPtr(), OK)); } void URLRequestHttpJob::ContinueWithCertificate( @@ -1257,8 +1257,8 @@ // The transaction started synchronously, but we need to notify the // URLRequest delegate via the message loop. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&URLRequestHttpJob::OnStartCompleted, - weak_factory_.GetWeakPtr(), rv)); + FROM_HERE, base::BindOnce(&URLRequestHttpJob::OnStartCompleted, + weak_factory_.GetWeakPtr(), rv)); } void URLRequestHttpJob::ContinueDespiteLastError() { @@ -1280,8 +1280,8 @@ // The transaction started synchronously, but we need to notify the // URLRequest delegate via the message loop. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&URLRequestHttpJob::OnStartCompleted, - weak_factory_.GetWeakPtr(), rv)); + FROM_HERE, base::BindOnce(&URLRequestHttpJob::OnStartCompleted, + weak_factory_.GetWeakPtr(), rv)); } bool URLRequestHttpJob::ShouldFixMismatchedContentLength(int rv) const {
diff --git a/net/url_request/url_request_job.cc b/net/url_request/url_request_job.cc index dc7c3d2..b24a0bc 100644 --- a/net/url_request/url_request_job.cc +++ b/net/url_request/url_request_job.cc
@@ -568,7 +568,7 @@ // delegate if we're done because of a synchronous call. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&URLRequestJob::NotifyDone, weak_factory_.GetWeakPtr())); + base::BindOnce(&URLRequestJob::NotifyDone, weak_factory_.GetWeakPtr())); } }
diff --git a/net/url_request/url_request_job_factory_impl_unittest.cc b/net/url_request/url_request_job_factory_impl_unittest.cc index efbccd9..7f887ea 100644 --- a/net/url_request/url_request_job_factory_impl_unittest.cc +++ b/net/url_request/url_request_job_factory_impl_unittest.cc
@@ -36,8 +36,8 @@ // Start reading asynchronously so that all error reporting and data // callbacks happen as they would for network requests. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&MockURLRequestJob::StartAsync, weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&MockURLRequestJob::StartAsync, + weak_factory_.GetWeakPtr())); } protected:
diff --git a/net/url_request/url_request_redirect_job.cc b/net/url_request/url_request_redirect_job.cc index 9950fe6..6a2c2c60 100644 --- a/net/url_request/url_request_redirect_job.cc +++ b/net/url_request/url_request_redirect_job.cc
@@ -66,8 +66,8 @@ NetLogEventType::URL_REQUEST_REDIRECT_JOB, NetLog::StringCallback("reason", &redirect_reason_)); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&URLRequestRedirectJob::StartAsync, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&URLRequestRedirectJob::StartAsync, + weak_factory_.GetWeakPtr())); } void URLRequestRedirectJob::Kill() {
diff --git a/net/url_request/url_request_simple_job.cc b/net/url_request/url_request_simple_job.cc index 77acb7d..6b5b585 100644 --- a/net/url_request/url_request_simple_job.cc +++ b/net/url_request/url_request_simple_job.cc
@@ -44,8 +44,8 @@ // Start reading asynchronously so that all error reporting and data // callbacks happen as they would for network requests. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&URLRequestSimpleJob::StartAsync, weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&URLRequestSimpleJob::StartAsync, + weak_factory_.GetWeakPtr())); } void URLRequestSimpleJob::Kill() {
diff --git a/net/url_request/url_request_test_job.cc b/net/url_request/url_request_test_job.cc index 5353577..6e7c1b7 100644 --- a/net/url_request/url_request_test_job.cc +++ b/net/url_request/url_request_test_job.cc
@@ -199,8 +199,8 @@ // Start reading asynchronously so that all error reporting and data // callbacks happen as they would for network requests. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&URLRequestTestJob::StartAsync, weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&URLRequestTestJob::StartAsync, + weak_factory_.GetWeakPtr())); } void URLRequestTestJob::StartAsync() { @@ -269,8 +269,8 @@ if (stage_ != WAITING) { stage_ = WAITING; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&URLRequestTestJob::ProcessNextOperation, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&URLRequestTestJob::ProcessNextOperation, + weak_factory_.GetWeakPtr())); } return ERR_IO_PENDING; } @@ -363,8 +363,8 @@ void URLRequestTestJob::AdvanceJob() { if (auto_advance_) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&URLRequestTestJob::ProcessNextOperation, - weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&URLRequestTestJob::ProcessNextOperation, + weak_factory_.GetWeakPtr())); return; } g_pending_jobs.Get().push_back(this);
diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc index 3282281c..57ac044 100644 --- a/net/url_request/url_request_unittest.cc +++ b/net/url_request/url_request_unittest.cc
@@ -10134,6 +10134,56 @@ } } +// Test that sessions started with privacy mode enabled cannot be resumed when +// it is disabled, and vice versa. +TEST_F(HTTPSRequestTest, NoSessionResumptionBetweenPrivacyModes) { + // Start a server. + SpawnedTestServer test_server( + SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::SSLOptions(), + base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))); + ASSERT_TRUE(test_server.Start()); + const auto url = test_server.GetURL("/"); + + auto ConnectAndCheckHandshake = [this, url](bool allow_credentials, + auto expected_handshake) { + // Construct request and indirectly set the privacy mode. + TestDelegate d; + std::unique_ptr<URLRequest> r(default_context_.CreateRequest( + url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS)); + r->set_allow_credentials(allow_credentials); + + // Start the request and check the SSL handshake type. + r->Start(); + EXPECT_TRUE(r->is_pending()); + d.RunUntilComplete(); + EXPECT_EQ(1, d.response_started_count()); + EXPECT_EQ(expected_handshake, r->ssl_info().handshake_type); + }; + + // Exhaustively check all pairs of privacy mode values. Note that we are using + // allow_credentials to indirectly enable/disable privacy mode. + const bool kAllowCredentialsValues[] = {false, true}; + for (const auto allow_creds_1 : kAllowCredentialsValues) { + for (const auto allow_creds_2 : kAllowCredentialsValues) { + SCOPED_TRACE(base::StringPrintf("allow_creds_1=%d, allow_creds_2=%d", + allow_creds_1, allow_creds_2)); + + // The session cache starts off empty, so we expect a full handshake. + ConnectAndCheckHandshake(allow_creds_1, SSLInfo::HANDSHAKE_FULL); + + // The second handshake depends on whether we are using the same session + // cache as the first request. + ConnectAndCheckHandshake(allow_creds_2, allow_creds_1 == allow_creds_2 + ? SSLInfo::HANDSHAKE_RESUME + : SSLInfo::HANDSHAKE_FULL); + // Flush both session caches. + auto* network_session = + default_context_.http_transaction_factory()->GetSession(); + network_session->ClearSSLSessionCache(); + } + } +} + class HTTPSFallbackTest : public TestWithScopedTaskEnvironment { public: HTTPSFallbackTest() : context_(true) {
diff --git a/net/websockets/websocket_basic_stream_adapters_test.cc b/net/websockets/websocket_basic_stream_adapters_test.cc index c929d8ff..610b884 100644 --- a/net/websockets/websocket_basic_stream_adapters_test.cc +++ b/net/websockets/websocket_basic_stream_adapters_test.cc
@@ -72,6 +72,7 @@ nullptr, nullptr, nullptr, + nullptr, &websocket_endpoint_lock_manager_, nullptr, HttpNetworkSession::NORMAL_SOCKET_POOL)),
diff --git a/net/websockets/websocket_channel_test.cc b/net/websockets/websocket_channel_test.cc index c7fbb58a0..b6fa071 100644 --- a/net/websockets/websocket_channel_test.cc +++ b/net/websockets/websocket_channel_test.cc
@@ -611,8 +611,8 @@ private: void PostCallback() { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&EchoeyFakeWebSocketStream::DoCallback, - base::Unretained(this))); + FROM_HERE, base::BindOnce(&EchoeyFakeWebSocketStream::DoCallback, + base::Unretained(this))); } void DoCallback() {
diff --git a/net/websockets/websocket_end_to_end_test.cc b/net/websockets/websocket_end_to_end_test.cc index 0d729a0..b1ad596 100644 --- a/net/websockets/websocket_end_to_end_test.cc +++ b/net/websockets/websocket_end_to_end_test.cc
@@ -202,9 +202,9 @@ const SSLInfo& ssl_info, bool fatal) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&SSLErrorCallbacks::CancelSSLRequest, - base::Owned(ssl_error_callbacks.release()), - ERR_SSL_PROTOCOL_ERROR, &ssl_info)); + FROM_HERE, base::BindOnce(&SSLErrorCallbacks::CancelSSLRequest, + base::Owned(ssl_error_callbacks.release()), + ERR_SSL_PROTOCOL_ERROR, &ssl_info)); } int ConnectTestingEventInterface::OnAuthRequired(
diff --git a/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions_unittests.cc b/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions_unittests.cc index 327da2b..8fff3f1 100644 --- a/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions_unittests.cc +++ b/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions_unittests.cc
@@ -171,7 +171,7 @@ base::Thread getparam_thread("sched_getparam_thread"); BPF_ASSERT(getparam_thread.Start()); getparam_thread.task_runner()->PostTask( - FROM_HERE, base::Bind(&SchedGetParamThread, &thread_run)); + FROM_HERE, base::BindOnce(&SchedGetParamThread, &thread_run)); BPF_ASSERT(thread_run.TimedWait(base::TimeDelta::FromMilliseconds(5000))); getparam_thread.Stop(); }
diff --git a/services/identity/public/cpp/accounts_cookie_mutator.h b/services/identity/public/cpp/accounts_cookie_mutator.h index de813d5..71b473d 100644 --- a/services/identity/public/cpp/accounts_cookie_mutator.h +++ b/services/identity/public/cpp/accounts_cookie_mutator.h
@@ -51,14 +51,6 @@ // know that the contents of the Gaia cookie might have changed. virtual void TriggerCookieJarUpdate() = 0; - // Notifies observers that |account_id| has been added to the Gaia cookie. - // Should only be invoked manually in cases where clients have detected that - // an account is in the Gaia cookie and want to ensure that observers are - // notified. - virtual void ForceTriggerOnAddAccountToCookieCompleted( - const std::string& account_id, - const GoogleServiceAuthError& error) = 0; - private: DISALLOW_COPY_AND_ASSIGN(AccountsCookieMutator); };
diff --git a/services/identity/public/cpp/accounts_cookie_mutator_impl.cc b/services/identity/public/cpp/accounts_cookie_mutator_impl.cc index 5d6be8bd..f7870e03 100644 --- a/services/identity/public/cpp/accounts_cookie_mutator_impl.cc +++ b/services/identity/public/cpp/accounts_cookie_mutator_impl.cc
@@ -46,10 +46,4 @@ gaia_cookie_manager_service_->TriggerListAccounts(); } -void AccountsCookieMutatorImpl::ForceTriggerOnAddAccountToCookieCompleted( - const std::string& account_id, - const GoogleServiceAuthError& error) { - gaia_cookie_manager_service_->SignalComplete(account_id, error); -} - } // namespace identity
diff --git a/services/identity/public/cpp/accounts_cookie_mutator_impl.h b/services/identity/public/cpp/accounts_cookie_mutator_impl.h index efa68af..1dad58d 100644 --- a/services/identity/public/cpp/accounts_cookie_mutator_impl.h +++ b/services/identity/public/cpp/accounts_cookie_mutator_impl.h
@@ -42,10 +42,6 @@ void TriggerCookieJarUpdate() override; - void ForceTriggerOnAddAccountToCookieCompleted( - const std::string& account_id, - const GoogleServiceAuthError& error) override; - private: GaiaCookieManagerService* gaia_cookie_manager_service_;
diff --git a/services/identity/public/cpp/accounts_cookie_mutator_unittest.cc b/services/identity/public/cpp/accounts_cookie_mutator_unittest.cc index 1279cdf..8880177 100644 --- a/services/identity/public/cpp/accounts_cookie_mutator_unittest.cc +++ b/services/identity/public/cpp/accounts_cookie_mutator_unittest.cc
@@ -57,9 +57,7 @@ namespace identity { class AccountsCookieMutatorTest : public testing::Test { public: - AccountsCookieMutatorTest() - : identity_test_env_(&test_url_loader_factory_), - identity_manager_observer_(identity_test_env_.identity_manager()) {} + AccountsCookieMutatorTest() : identity_test_env_(&test_url_loader_factory_) {} ~AccountsCookieMutatorTest() override {} @@ -121,7 +119,7 @@ } TestIdentityManagerObserver* identity_manager_observer() { - return &identity_manager_observer_; + return identity_test_env_.identity_manager_observer(); } AccountsCookieMutator* accounts_cookie_mutator() { @@ -132,7 +130,6 @@ base::test::ScopedTaskEnvironment task_environment_; network::TestURLLoaderFactory test_url_loader_factory_; identity::IdentityTestEnvironment identity_test_env_; - TestIdentityManagerObserver identity_manager_observer_; DISALLOW_COPY_AND_ASSIGN(AccountsCookieMutatorTest); }; @@ -327,7 +324,7 @@ EXPECT_TRUE(accounts_in_jar_info.accounts_are_fresh); EXPECT_EQ(identity_manager_observer() - ->ErrorFromAddAccountToCookieCompletedCallback() + ->ErrorFromAccountsInCookieUpdatedCallback() .state(), GoogleServiceAuthError::NONE); } @@ -357,29 +354,9 @@ EXPECT_TRUE(accounts_in_jar_info.accounts_are_fresh); EXPECT_EQ(identity_manager_observer() - ->ErrorFromAddAccountToCookieCompletedCallback() + ->ErrorFromAccountsInCookieUpdatedCallback() .state(), GoogleServiceAuthError::NONE); } -// Test that calling ForceTriggerOnAddAccountToCookieCompleted() with an account -// ID and a valid error runs the callback with that data passed through. -TEST_F(AccountsCookieMutatorTest, ForceTriggerOnAddAccountToCookieCompleted) { - base::RunLoop run_loop; - identity_manager_observer()->SetOnAddAccountToCookieCompletedCallback( - run_loop.QuitClosure()); - accounts_cookie_mutator()->ForceTriggerOnAddAccountToCookieCompleted( - kTestUnavailableAccountId, - GoogleServiceAuthError(GoogleServiceAuthError::TWO_FACTOR)); - run_loop.Run(); - - EXPECT_EQ(identity_manager_observer() - ->AccountFromAddAccountToCookieCompletedCallback(), - kTestUnavailableAccountId); - EXPECT_EQ(identity_manager_observer() - ->ErrorFromAddAccountToCookieCompletedCallback() - .state(), - GoogleServiceAuthError::TWO_FACTOR); -} - } // namespace identity
diff --git a/services/identity/public/cpp/accounts_mutator_unittest.cc b/services/identity/public/cpp/accounts_mutator_unittest.cc index fd5b9983..2c1646a5 100644 --- a/services/identity/public/cpp/accounts_mutator_unittest.cc +++ b/services/identity/public/cpp/accounts_mutator_unittest.cc
@@ -87,7 +87,6 @@ public: AccountsMutatorTest() : identity_test_env_(&test_url_loader_factory_, &prefs_), - identity_manager_observer_(identity_manager()), identity_manager_diagnostics_observer_(identity_manager()) {} ~AccountsMutatorTest() override {} @@ -99,7 +98,7 @@ } TestIdentityManagerObserver* identity_manager_observer() { - return &identity_manager_observer_; + return identity_test_env_.identity_manager_observer(); } TestIdentityManagerDiagnosticsObserver* @@ -116,7 +115,6 @@ sync_preferences::TestingPrefServiceSyncable prefs_; network::TestURLLoaderFactory test_url_loader_factory_; identity::IdentityTestEnvironment identity_test_env_; - TestIdentityManagerObserver identity_manager_observer_; TestIdentityManagerDiagnosticsObserver identity_manager_diagnostics_observer_; DISALLOW_COPY_AND_ASSIGN(AccountsMutatorTest);
diff --git a/services/identity/public/cpp/identity_test_environment.cc b/services/identity/public/cpp/identity_test_environment.cc index 914295c..82a14e5 100644 --- a/services/identity/public/cpp/identity_test_environment.cc +++ b/services/identity/public/cpp/identity_test_environment.cc
@@ -18,6 +18,7 @@ #include "services/identity/public/cpp/accounts_mutator.h" #include "services/identity/public/cpp/identity_test_utils.h" #include "services/identity/public/cpp/primary_account_mutator.h" +#include "services/identity/public/cpp/test_identity_manager_observer.h" #if !defined(OS_CHROMEOS) #include "services/identity/public/cpp/primary_account_mutator_impl.h" @@ -281,6 +282,9 @@ std::move(accounts_mutator), std::move(accounts_cookie_mutator)); } + test_identity_manager_observer_ = + std::make_unique<TestIdentityManagerObserver>(this->identity_manager()); + this->identity_manager()->AddDiagnosticsObserver(this); } @@ -296,6 +300,11 @@ : owned_identity_manager_.get(); } +TestIdentityManagerObserver* +IdentityTestEnvironment::identity_manager_observer() { + return test_identity_manager_observer_.get(); +} + CoreAccountInfo IdentityTestEnvironment::SetPrimaryAccount( const std::string& email) { return identity::SetPrimaryAccount(identity_manager(), email);
diff --git a/services/identity/public/cpp/identity_test_environment.h b/services/identity/public/cpp/identity_test_environment.h index 9e43e53..2f6d88a 100644 --- a/services/identity/public/cpp/identity_test_environment.h +++ b/services/identity/public/cpp/identity_test_environment.h
@@ -35,9 +35,8 @@ #endif // OS_CHROMEOS } // namespace -// Internal class that creates and owns dependencies of IdentityManager -// when those dependencies are not passed in externally. class IdentityManagerDependenciesOwner; +class TestIdentityManagerObserver; // Class that creates an IdentityManager for use in testing contexts and // provides facilities for driving that IdentityManager. The IdentityManager @@ -95,6 +94,9 @@ // The IdentityManager instance associated with this instance. IdentityManager* identity_manager(); + // Returns the |TestIdentityManagerObserver| watching the IdentityManager. + TestIdentityManagerObserver* identity_manager_observer(); + // Sets the primary account for the given email address, generating a GAIA ID // that corresponds uniquely to that email address. On non-ChromeOS, results // in the firing of the IdentityManager and SigninManager callbacks for signin @@ -380,6 +382,8 @@ std::unique_ptr<IdentityManager> owned_identity_manager_; IdentityManager* raw_identity_manager_ = nullptr; + std::unique_ptr<TestIdentityManagerObserver> test_identity_manager_observer_; + base::OnceClosure on_access_token_requested_callback_; std::vector<AccessTokenRequestState> requesters_;
diff --git a/services/identity/public/cpp/test_identity_manager_observer.cc b/services/identity/public/cpp/test_identity_manager_observer.cc index c76d493..5c485d0 100644 --- a/services/identity/public/cpp/test_identity_manager_observer.cc +++ b/services/identity/public/cpp/test_identity_manager_observer.cc
@@ -100,6 +100,11 @@ return accounts_info_from_cookie_change_callback_; } +const GoogleServiceAuthError& +TestIdentityManagerObserver::ErrorFromAccountsInCookieUpdatedCallback() const { + return error_from_cookie_change_callback_; +} + void TestIdentityManagerObserver::SetOnAddAccountToCookieCompletedCallback( base::OnceClosure callback) { on_add_account_to_cookie_completed_callback_ = std::move(callback); @@ -205,6 +210,7 @@ const AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) { accounts_info_from_cookie_change_callback_ = accounts_in_cookie_jar_info; + error_from_cookie_change_callback_ = error; if (on_accounts_in_cookie_updated_callback_) std::move(on_accounts_in_cookie_updated_callback_).Run(); }
diff --git a/services/identity/public/cpp/test_identity_manager_observer.h b/services/identity/public/cpp/test_identity_manager_observer.h index 7fccd33..28a4b9d 100644 --- a/services/identity/public/cpp/test_identity_manager_observer.h +++ b/services/identity/public/cpp/test_identity_manager_observer.h
@@ -49,6 +49,8 @@ void SetOnAccountsInCookieUpdatedCallback(base::OnceClosure callback); const AccountsInCookieJarInfo& AccountsInfoFromAccountsInCookieUpdatedCallback(); + const GoogleServiceAuthError& ErrorFromAccountsInCookieUpdatedCallback() + const; void SetOnAddAccountToCookieCompletedCallback(base::OnceClosure callback); const std::string& AccountFromAddAccountToCookieCompletedCallback() const; @@ -122,6 +124,7 @@ base::OnceClosure on_accounts_in_cookie_updated_callback_; AccountsInCookieJarInfo accounts_info_from_cookie_change_callback_; + GoogleServiceAuthError error_from_cookie_change_callback_; base::OnceClosure on_add_account_to_cookie_completed_callback_; std::string account_from_add_account_to_cookie_completed_callback_;
diff --git a/services/media_session/audio_focus_manager.cc b/services/media_session/audio_focus_manager.cc index 9981964f8..09b8b7b 100644 --- a/services/media_session/audio_focus_manager.cc +++ b/services/media_session/audio_focus_manager.cc
@@ -99,7 +99,17 @@ } void MediaSessionInfoChanged(mojom::MediaSessionInfoPtr info) override { + bool suspended_change = + (info->state == mojom::MediaSessionInfo::SessionState::kSuspended || + IsSuspended()) && + info->state != session_info_->state; + SetSessionInfo(std::move(info)); + + // If we have transitioned to/from a suspended state then we should + // re-enforce audio focus. + if (suspended_change) + owner_->EnforceAudioFocus(); } void GetRequestId(GetRequestIdCallback callback) override { @@ -119,6 +129,11 @@ mojom::MediaSessionInfo::SessionState::kActive; } + bool IsSuspended() const { + return session_info_->state == + mojom::MediaSessionInfo::SessionState::kSuspended; + } + RequestId id() const { return id_; } const std::string& source_name() const { return source_name_; } @@ -432,16 +447,20 @@ for (auto& session : base::Reversed(audio_focus_stack_)) { EnforceSingleSession(session.get(), state); - // Update the flags based on the audio focus type of this session. + // Update the flags based on the audio focus type of this session. If the + // session is suspended then any transient audio focus type should not have + // an effect. switch (session->audio_focus_type()) { case mojom::AudioFocusType::kGain: state.should_stop = true; break; case mojom::AudioFocusType::kGainTransient: - state.should_suspend = true; + if (!session->IsSuspended()) + state.should_suspend = true; break; case mojom::AudioFocusType::kGainTransientMayDuck: - state.should_duck = true; + if (!session->IsSuspended()) + state.should_duck = true; break; } }
diff --git a/services/media_session/audio_focus_manager_unittest.cc b/services/media_session/audio_focus_manager_unittest.cc index ffb4d1f9..8fbe988 100644 --- a/services/media_session/audio_focus_manager_unittest.cc +++ b/services/media_session/audio_focus_manager_unittest.cc
@@ -123,9 +123,8 @@ mojom::MediaSessionInfo::SessionState state = session->GetState(); if (!IsEnforcementEnabled()) { - // If audio focus enforcement is disabled then we should never see these - // states in the tests. - EXPECT_NE(mojom::MediaSessionInfo::SessionState::kSuspended, state); + // If audio focus enforcement is disabled then we should never see ducking + // in the tests. EXPECT_NE(mojom::MediaSessionInfo::SessionState::kDucking, state); } @@ -1062,7 +1061,7 @@ } } -TEST_P(AudioFocusManagerTest, AudioFocusGrouping_AllowDucking) { +TEST_P(AudioFocusManagerTest, AudioFocusGrouping_LayeredFocus) { test::MockMediaSession media_session_1; test::MockMediaSession media_session_2; test::MockMediaSession media_session_3; @@ -1079,11 +1078,20 @@ EXPECT_EQ(GetStateFromParam(mojom::MediaSessionInfo::SessionState::kDucking), GetState(&media_session_1)); - RequestGroupedAudioFocus(&media_session_3, mojom::AudioFocusType::kGain, - group_id); + // When we request audio focus for media_session_3 the group will take audio + // focus and we suspend the ducking session. + RequestGroupedAudioFocus(&media_session_3, + mojom::AudioFocusType::kGainTransient, group_id); EXPECT_EQ(mojom::MediaSessionInfo::SessionState::kActive, GetState(&media_session_3)); - EXPECT_EQ(GetStateFromParam(mojom::MediaSessionInfo::SessionState::kDucking), + + EXPECT_EQ( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended), + GetState(&media_session_2)); + EXPECT_EQ(GetStateFromParam( + IsGroupingEnabled() + ? mojom::MediaSessionInfo::SessionState::kActive + : mojom::MediaSessionInfo::SessionState::kSuspended), GetState(&media_session_1)); } @@ -1235,4 +1243,218 @@ GetState(&media_session_1)); } +TEST_P(AudioFocusManagerTest, GainFocusTypeHasEffectEvenIfSuspended) { + test::MockMediaSession media_session_1; + test::MockMediaSession media_session_2; + test::MockMediaSession media_session_3; + + AudioFocusManager::RequestId request_id_1 = + RequestAudioFocus(&media_session_1, mojom::AudioFocusType::kGain); + EXPECT_EQ(request_id_1, GetAudioFocusedSession()); + + RequestAudioFocus(&media_session_2, mojom::AudioFocusType::kGain); + EXPECT_EQ( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended), + GetState(&media_session_1)); + + // When the second session becomes suspended and that event originated from + // the session itself then we should keep the other session suspended. + media_session_2.Suspend(mojom::MediaSession::SuspendType::kUI); + EXPECT_EQ(mojom::MediaSessionInfo::SessionState::kSuspended, + GetState(&media_session_2)); + + { + test::MockMediaSessionMojoObserver observer(media_session_1); + observer.WaitForState( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended)); + } + + // When the second session is resumed then we should still keep the other + // session suspended. + media_session_2.Resume(mojom::MediaSession::SuspendType::kUI); + EXPECT_EQ(mojom::MediaSessionInfo::SessionState::kActive, + GetState(&media_session_2)); + + { + test::MockMediaSessionMojoObserver observer(media_session_1); + observer.WaitForState( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended)); + } + + // If a new session takes focus then this should suspend all sessions. + RequestAudioFocus(&media_session_3, mojom::AudioFocusType::kGainTransient); + + { + test::MockMediaSessionMojoObserver observer(media_session_2); + observer.WaitForState( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended)); + } + + { + test::MockMediaSessionMojoObserver observer(media_session_1); + observer.WaitForState( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended)); + } + + // If the second session regains focus then it should suspend all sessions. + RequestAudioFocus(&media_session_2, mojom::AudioFocusType::kGain); + EXPECT_EQ(mojom::MediaSessionInfo::SessionState::kActive, + GetState(&media_session_2)); + + { + test::MockMediaSessionMojoObserver observer(media_session_1); + observer.WaitForState( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended)); + } + + { + test::MockMediaSessionMojoObserver observer(media_session_3); + observer.WaitForState( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended)); + } +} + +TEST_P(AudioFocusManagerTest, TransientFocusTypeHasNoEffectIfSuspended) { + test::MockMediaSession media_session_1; + test::MockMediaSession media_session_2; + test::MockMediaSession media_session_3; + + AudioFocusManager::RequestId request_id_1 = + RequestAudioFocus(&media_session_1, mojom::AudioFocusType::kGain); + EXPECT_EQ(request_id_1, GetAudioFocusedSession()); + + RequestAudioFocus(&media_session_2, mojom::AudioFocusType::kGainTransient); + EXPECT_EQ( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended), + GetState(&media_session_1)); + + // When the transient session becomes suspended and that event originates from + // the session itself then we should stop pausing the other session. + media_session_2.Suspend(mojom::MediaSession::SuspendType::kUI); + EXPECT_EQ(mojom::MediaSessionInfo::SessionState::kSuspended, + GetState(&media_session_2)); + + { + test::MockMediaSessionMojoObserver observer(media_session_1); + observer.WaitForState(mojom::MediaSessionInfo::SessionState::kActive); + } + + // When the transient session is resumed then we should pause the other + // session again. + media_session_2.Resume(mojom::MediaSession::SuspendType::kUI); + EXPECT_EQ(mojom::MediaSessionInfo::SessionState::kActive, + GetState(&media_session_2)); + + { + test::MockMediaSessionMojoObserver observer(media_session_1); + observer.WaitForState( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended)); + } + + // If we have a new session take focus then this should suspend all the other + // sessions and the transient session should have no effect. + RequestAudioFocus(&media_session_3, mojom::AudioFocusType::kGainTransient); + + { + test::MockMediaSessionMojoObserver observer(media_session_2); + observer.WaitForState( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended)); + } + + { + test::MockMediaSessionMojoObserver observer(media_session_1); + observer.WaitForState( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended)); + } + + // If the second session regains focus then it should start pausing again. + RequestAudioFocus(&media_session_2, mojom::AudioFocusType::kGainTransient); + EXPECT_EQ(mojom::MediaSessionInfo::SessionState::kActive, + GetState(&media_session_2)); + + { + test::MockMediaSessionMojoObserver observer(media_session_1); + observer.WaitForState( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended)); + } + + { + test::MockMediaSessionMojoObserver observer(media_session_3); + observer.WaitForState( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended)); + } +} + +TEST_P(AudioFocusManagerTest, TransientDuckFocusTypeHasNoEffectIfSuspended) { + test::MockMediaSession media_session_1; + test::MockMediaSession media_session_2; + test::MockMediaSession media_session_3; + + AudioFocusManager::RequestId request_id_1 = + RequestAudioFocus(&media_session_1, mojom::AudioFocusType::kGain); + EXPECT_EQ(request_id_1, GetAudioFocusedSession()); + + RequestAudioFocus(&media_session_2, + mojom::AudioFocusType::kGainTransientMayDuck); + EXPECT_EQ(GetStateFromParam(mojom::MediaSessionInfo::SessionState::kDucking), + GetState(&media_session_1)); + + // When the ducking session becomes suspended and that event originates from + // the session itself then we should stop ducking. + media_session_2.Suspend(mojom::MediaSession::SuspendType::kUI); + EXPECT_EQ(mojom::MediaSessionInfo::SessionState::kSuspended, + GetState(&media_session_2)); + + { + test::MockMediaSessionMojoObserver observer(media_session_1); + observer.WaitForState(mojom::MediaSessionInfo::SessionState::kActive); + } + + // When the ducking session is resumed then we should resume ducking. + media_session_2.Resume(mojom::MediaSession::SuspendType::kUI); + EXPECT_EQ(mojom::MediaSessionInfo::SessionState::kActive, + GetState(&media_session_2)); + + { + test::MockMediaSessionMojoObserver observer(media_session_1); + observer.WaitForState( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kDucking)); + } + + // If we have a new session take focus then this should suspend all the other + // sessions and we should not have any ducking from the ducking session (since + // it is suspended). + RequestAudioFocus(&media_session_3, mojom::AudioFocusType::kGainTransient); + + { + test::MockMediaSessionMojoObserver observer(media_session_2); + observer.WaitForState( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended)); + } + + { + test::MockMediaSessionMojoObserver observer(media_session_1); + observer.WaitForState( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended)); + } + + // If the ducking session regains focus then it should start ducking again. + RequestAudioFocus(&media_session_2, + mojom::AudioFocusType::kGainTransientMayDuck); + EXPECT_EQ(mojom::MediaSessionInfo::SessionState::kActive, + GetState(&media_session_2)); + + { + test::MockMediaSessionMojoObserver observer(media_session_1); + observer.WaitForState( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kDucking)); + } + + { + test::MockMediaSessionMojoObserver observer(media_session_3); + observer.WaitForState( + GetStateFromParam(mojom::MediaSessionInfo::SessionState::kDucking)); + } +} + } // namespace media_session
diff --git a/services/network/tls_socket_factory.cc b/services/network/tls_socket_factory.cc index a401acb..2f9ffc19 100644 --- a/services/network/tls_socket_factory.cc +++ b/services/network/tls_socket_factory.cc
@@ -53,8 +53,7 @@ url_request_context->transport_security_state(), url_request_context->cert_transparency_verifier(), url_request_context->ct_policy_enforcer(), - nullptr /* Disables SSL session caching */, - std::string()), + nullptr /* Disables SSL session caching */), client_socket_factory_(nullptr), ssl_config_service_(url_request_context->ssl_config_service()) { if (http_context) {
diff --git a/services/ws/client_root.cc b/services/ws/client_root.cc index 4e4d284..394392b 100644 --- a/services/ws/client_root.cc +++ b/services/ws/client_root.cc
@@ -252,6 +252,12 @@ window_->GetFrameSinkId(), proxy_window->local_surface_id_allocation()->local_surface_id()); client_surface_embedder_->SetSurfaceId(surface_id); + + // This triggers holding events until the frame has been activated. This + // ensures smooth resizes. + if (ShouldAssignLocalSurfaceId() && window_->GetHost()) + window_->GetHost()->compositor()->OnChildResizing(); + if (fallback_surface_info_) { client_surface_embedder_->SetFallbackSurfaceInfo(*fallback_surface_info_); fallback_surface_info_.reset(); @@ -408,6 +414,8 @@ void ClientRoot::OnFirstSurfaceActivation( const viz::SurfaceInfo& surface_info) { + // TODO(sky): saman says the SetFallbackSurfaceInfo() should not be needed + // anymore. ProxyWindow* proxy_window = ProxyWindow::GetMayBeNull(window_); if (proxy_window->local_surface_id_allocation().has_value()) { DCHECK(!fallback_surface_info_);
diff --git a/services/ws/window_service_test_setup.cc b/services/ws/window_service_test_setup.cc index f85658b..e5bc89c4 100644 --- a/services/ws/window_service_test_setup.cc +++ b/services/ws/window_service_test_setup.cc
@@ -140,6 +140,9 @@ ui::InitializeContextFactoryForTests(enable_pixel_output, &context_factory, &context_factory_private); aura_test_helper_.SetUp(context_factory, context_factory_private); + // The resize throttle may interfere with tests, so disable it. If specific + // tests want the throttle, they can enable it. + aura::Env::GetInstance()->set_throttle_input_on_resize_for_testing(false); scoped_capture_client_ = std::make_unique<wm::ScopedCaptureClient>( aura_test_helper_.root_window()); service_ =
diff --git a/testing/buildbot/filters/mojo.fyi.network_webview_instrumentation_test_apk.filter b/testing/buildbot/filters/mojo.fyi.network_webview_instrumentation_test_apk.filter index a817505..4107fe1 100644 --- a/testing/buildbot/filters/mojo.fyi.network_webview_instrumentation_test_apk.filter +++ b/testing/buildbot/filters/mojo.fyi.network_webview_instrumentation_test_apk.filter
@@ -29,7 +29,6 @@ # https://crbug.com/893576 -org.chromium.android_webview.test.CookieManagerTest.testAcceptCookie_falseWontSetCookies --org.chromium.android_webview.test.CookieManagerTest.testAcceptCookie_trueWillSetCookies -org.chromium.android_webview.test.CookieManagerTest.testAcceptFileSchemeCookies -org.chromium.android_webview.test.CookieManagerTest.testEmbedderCanSeeRestrictedCookies -org.chromium.android_webview.test.CookieManagerTest.testRejectFileSchemeCookies @@ -38,9 +37,21 @@ -org.chromium.android_webview.test.CookieManagerTest.testThirdPartyCookiesArePerWebview -org.chromium.android_webview.test.CookieManagerTest.testThirdPartyJavascriptCookie +# https://crbug.com/931641 +-org.chromium.android_webview.test.CookieManagerTest.testRemoveSessionCookiesNullCallback +-org.chromium.android_webview.test.CookieManagerTest.testSetSecureCookieForHttpUrl +-org.chromium.android_webview.test.CookieManagerTest.testSetCookie +-org.chromium.android_webview.test.CookieManagerTest.testThirdPartyCookieForWebSocketDisabledCase +-org.chromium.android_webview.test.CookieManagerTest.testSetCookieWithDomainForUrlWithTrailingSemicolonInCookie +-org.chromium.android_webview.test.CookieManagerTest.testSetCookieWithDomainForUrl +-org.chromium.android_webview.test.CookieManagerTest.testRemoveSessionCookies +-org.chromium.android_webview.test.CookieManagerTest.testSetCookieCallback +-org.chromium.android_webview.test.CookieManagerTest.testRemoveSessionCookiesCallback +-org.chromium.android_webview.test.CookieManagerTest.testSetCookieWithDomainForUrlAndExistingDomainAttribute +-org.chromium.android_webview.test.CookieManagerTest.testCookieExpiration + # https://crbug.com/893580 -org.chromium.android_webview.test.LoadDataWithBaseUrlTest.testLoadDataWithBaseUrlAccessingFile --org.chromium.android_webview.test.LoadDataWithBaseUrlTest.testSetCookieInIframe -org.chromium.android_webview.test.LoadDataWithBaseUrlTest.testThirdPartyCookieInIframe # https://crbug.com/893582
diff --git a/testing/buildbot/gn_isolate_map.pyl b/testing/buildbot/gn_isolate_map.pyl index fad0255..854b6db2 100644 --- a/testing/buildbot/gn_isolate_map.pyl +++ b/testing/buildbot/gn_isolate_map.pyl
@@ -620,6 +620,7 @@ "script": "//testing/xvfb.py", "args": [ "../../chrome/test/chromedriver/test/run_webdriver_tests.py", + "-v", "--chromedriver=chromedriver", "--isolated-script-test-output=${ISOLATED_OUTDIR}/results.json", "--test-path=../../third_party/blink/web_tests/external/wpt/webdriver/tests/navigate_to/navigate.py",
diff --git a/third_party/blink/common/features.cc b/third_party/blink/common/features.cc index c54fa31..06ec555 100644 --- a/third_party/blink/common/features.cc +++ b/third_party/blink/common/features.cc
@@ -98,6 +98,10 @@ "PreviewsResourceLoadingHintsSpecificResourceTypes", base::FEATURE_DISABLED_BY_DEFAULT}; +// Purge memory when freezing only if the renderer is backgrounded. +const base::Feature kPurgeMemoryOnlyForBackgroundedProcesses{ + "FreezePurgeMemoryBackgroundedOnly", base::FEATURE_DISABLED_BY_DEFAULT}; + // Enable Implicit Root Scroller. https://crbug.com/903260. const base::Feature kImplicitRootScroller{"ImplicitRootScroller", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/third_party/blink/public/common/features.h b/third_party/blink/public/common/features.h index 11c8319..c59f114 100644 --- a/third_party/blink/public/common/features.h +++ b/third_party/blink/public/common/features.h
@@ -36,6 +36,8 @@ BLINK_COMMON_EXPORT extern const base::Feature kPortals; BLINK_COMMON_EXPORT extern const base::Feature kPreviewsResourceLoadingHintsSpecificResourceTypes; +BLINK_COMMON_EXPORT extern const base::Feature + kPurgeMemoryOnlyForBackgroundedProcesses; BLINK_COMMON_EXPORT extern const base::Feature kRTCGetDisplayMedia; BLINK_COMMON_EXPORT extern const base::Feature kRTCUnifiedPlanByDefault; BLINK_COMMON_EXPORT extern const base::Feature kRTCOfferExtmapAllowMixed;
diff --git a/third_party/blink/public/platform/platform.h b/third_party/blink/public/platform/platform.h index 55bd97c..e89fff83 100644 --- a/third_party/blink/public/platform/platform.h +++ b/third_party/blink/public/platform/platform.h
@@ -717,14 +717,6 @@ return nullptr; } - // Memory ------------------------------------------------------------ - - // Requests purging memory. The platform may or may not purge memory, - // depending on memory pressure. - virtual void RequestPurgeMemory() {} - - virtual void SetMemoryPressureNotificationsSuppressed(bool suppressed) {} - // V8 Context Snapshot -------------------------------------------------- // This method returns true only when
diff --git a/third_party/blink/renderer/core/css/css_identifier_value.cc b/third_party/blink/renderer/core/css/css_identifier_value.cc index 63f0c70..1e19201 100644 --- a/third_party/blink/renderer/core/css/css_identifier_value.cc +++ b/third_party/blink/renderer/core/css/css_identifier_value.cc
@@ -34,30 +34,30 @@ CSSIdentifierValue::CSSIdentifierValue(const Length& length) : CSSValue(kIdentifierClass) { switch (length.GetType()) { - case kAuto: + case Length::kAuto: value_id_ = CSSValueAuto; break; - case kMinContent: + case Length::kMinContent: value_id_ = CSSValueMinContent; break; - case kMaxContent: + case Length::kMaxContent: value_id_ = CSSValueMaxContent; break; - case kFillAvailable: + case Length::kFillAvailable: value_id_ = CSSValueWebkitFillAvailable; break; - case kFitContent: + case Length::kFitContent: value_id_ = CSSValueFitContent; break; - case kExtendToZoom: + case Length::kExtendToZoom: value_id_ = CSSValueInternalExtendToZoom; break; - case kPercent: - case kFixed: - case kCalculated: - case kDeviceWidth: - case kDeviceHeight: - case kMaxSizeNone: + case Length::kPercent: + case Length::kFixed: + case Length::kCalculated: + case Length::kDeviceWidth: + case Length::kDeviceHeight: + case Length::kMaxSizeNone: NOTREACHED(); break; }
diff --git a/third_party/blink/renderer/core/css/css_primitive_value.cc b/third_party/blink/renderer/core/css/css_primitive_value.cc index fa435f0..58b5860 100644 --- a/third_party/blink/renderer/core/css/css_primitive_value.cc +++ b/third_party/blink/renderer/core/css/css_primitive_value.cc
@@ -172,16 +172,16 @@ CSSPrimitiveValue::CSSPrimitiveValue(const Length& length, float zoom) : CSSValue(kPrimitiveClass) { switch (length.GetType()) { - case kPercent: + case Length::kPercent: Init(UnitType::kPercentage); DCHECK(std::isfinite(length.Percent())); value_.num = length.Percent(); break; - case kFixed: + case Length::kFixed: Init(UnitType::kPixels); value_.num = length.Value() / zoom; break; - case kCalculated: { + case Length::kCalculated: { const CalculationValue& calc = length.GetCalculationValue(); if (calc.Pixels() && calc.Percent()) { Init(CSSCalcValue::Create(CSSCalcValue::CreateExpressionNode( @@ -200,15 +200,15 @@ value_.num = 0; break; } - case kAuto: - case kMinContent: - case kMaxContent: - case kFillAvailable: - case kFitContent: - case kExtendToZoom: - case kDeviceWidth: - case kDeviceHeight: - case kMaxSizeNone: + case Length::kAuto: + case Length::kMinContent: + case Length::kMaxContent: + case Length::kFillAvailable: + case Length::kFitContent: + case Length::kExtendToZoom: + case Length::kDeviceWidth: + case Length::kDeviceHeight: + case Length::kMaxSizeNone: NOTREACHED(); break; }
diff --git a/third_party/blink/renderer/core/css/css_selector.cc b/third_party/blink/renderer/core/css/css_selector.cc index e07bcc4..eefc6d1 100644 --- a/third_party/blink/renderer/core/css/css_selector.cc +++ b/third_party/blink/renderer/core/css/css_selector.cc
@@ -281,6 +281,7 @@ case kPseudoFullScreenAncestor: case kPseudoFullscreen: case kPseudoSpatialNavigationFocus: + case kPseudoSpatialNavigationInterest: case kPseudoIsHtml: case kPseudoListBox: case kPseudoHostHasAppearance: @@ -314,6 +315,8 @@ CSSSelector::kPseudoHostHasAppearance}, {"-internal-spatial-navigation-focus", CSSSelector::kPseudoSpatialNavigationFocus}, + {"-internal-spatial-navigation-interest", + CSSSelector::kPseudoSpatialNavigationInterest}, {"-internal-video-persistent", CSSSelector::kPseudoVideoPersistent}, {"-internal-video-persistent-ancestor", CSSSelector::kPseudoVideoPersistentAncestor}, @@ -565,6 +568,7 @@ case kPseudoIsHtml: case kPseudoListBox: case kPseudoSpatialNavigationFocus: + case kPseudoSpatialNavigationInterest: case kPseudoVideoPersistent: case kPseudoVideoPersistentAncestor: if (mode != kUASheetMode) { @@ -938,6 +942,7 @@ case CSSSelector::kPseudoHostContext: case CSSSelector::kPseudoNot: case CSSSelector::kPseudoSpatialNavigationFocus: + case CSSSelector::kPseudoSpatialNavigationInterest: case CSSSelector::kPseudoIsHtml: case CSSSelector::kPseudoListBox: case CSSSelector::kPseudoHostHasAppearance:
diff --git a/third_party/blink/renderer/core/css/css_selector.h b/third_party/blink/renderer/core/css/css_selector.h index 619f661..36d9eff 100644 --- a/third_party/blink/renderer/core/css/css_selector.h +++ b/third_party/blink/renderer/core/css/css_selector.h
@@ -242,6 +242,7 @@ kPseudoHostContext, kPseudoShadow, kPseudoSpatialNavigationFocus, + kPseudoSpatialNavigationInterest, kPseudoIsHtml, kPseudoListBox, kPseudoHostHasAppearance,
diff --git a/third_party/blink/renderer/core/css/css_value.cc b/third_party/blink/renderer/core/css/css_value.cc index 5f0fb56..081b3ae1 100644 --- a/third_party/blink/renderer/core/css/css_value.cc +++ b/third_party/blink/renderer/core/css/css_value.cc
@@ -84,20 +84,20 @@ CSSValue* CSSValue::Create(const Length& value, float zoom) { switch (value.GetType()) { - case kAuto: - case kMinContent: - case kMaxContent: - case kFillAvailable: - case kFitContent: - case kExtendToZoom: + case Length::kAuto: + case Length::kMinContent: + case Length::kMaxContent: + case Length::kFillAvailable: + case Length::kFitContent: + case Length::kExtendToZoom: return CSSIdentifierValue::Create(value); - case kPercent: - case kFixed: - case kCalculated: + case Length::kPercent: + case Length::kFixed: + case Length::kCalculated: return CSSPrimitiveValue::Create(value, zoom); - case kDeviceWidth: - case kDeviceHeight: - case kMaxSizeNone: + case Length::kDeviceWidth: + case Length::kDeviceHeight: + case Length::kMaxSizeNone: NOTREACHED(); break; }
diff --git a/third_party/blink/renderer/core/css/element_rule_collector.cc b/third_party/blink/renderer/core/css/element_rule_collector.cc index 59008329..5ae166e 100644 --- a/third_party/blink/renderer/core/css/element_rule_collector.cc +++ b/third_party/blink/renderer/core/css/element_rule_collector.cc
@@ -235,9 +235,9 @@ if (SelectorChecker::MatchesFocusPseudoClass(element)) CollectMatchingRulesForList(match_request.rule_set->FocusPseudoClassRules(), cascade_order, match_request); - if (SelectorChecker::MatchesSpatialNavigationFocusPseudoClass(element)) { + if (SelectorChecker::MatchesSpatialNavigationInterestPseudoClass(element)) { CollectMatchingRulesForList( - match_request.rule_set->SpatialNavigationFocusPseudoClassRules(), + match_request.rule_set->SpatialNavigationInterestPseudoClassRules(), cascade_order, match_request); } AtomicString element_name = matching_ua_rules_
diff --git a/third_party/blink/renderer/core/css/parser/css_selector_parser_test.cc b/third_party/blink/renderer/core/css/parser/css_selector_parser_test.cc index c588c50..fb4445cf 100644 --- a/third_party/blink/renderer/core/css/parser/css_selector_parser_test.cc +++ b/third_party/blink/renderer/core/css/parser/css_selector_parser_test.cc
@@ -340,6 +340,7 @@ ":-internal-list-box", ":-internal-shadow-host-has-appearance", ":-internal-spatial-navigation-focus", + ":-internal-spatial-navigation-interest", ":-internal-video-persistent", ":-internal-video-persistent-ancestor"}; for (auto* test_case : test_cases) {
diff --git a/third_party/blink/renderer/core/css/rule_feature_set.cc b/third_party/blink/renderer/core/css/rule_feature_set.cc index 4db33d50..9d4db03 100644 --- a/third_party/blink/renderer/core/css/rule_feature_set.cc +++ b/third_party/blink/renderer/core/css/rule_feature_set.cc
@@ -160,6 +160,7 @@ case CSSSelector::kPseudoHost: case CSSSelector::kPseudoShadow: case CSSSelector::kPseudoSpatialNavigationFocus: + case CSSSelector::kPseudoSpatialNavigationInterest: case CSSSelector::kPseudoIsHtml: case CSSSelector::kPseudoListBox: case CSSSelector::kPseudoHostHasAppearance: @@ -539,7 +540,7 @@ case CSSSelector::kPseudoDefined: case CSSSelector::kPseudoVideoPersistent: case CSSSelector::kPseudoVideoPersistentAncestor: - case CSSSelector::kPseudoSpatialNavigationFocus: + case CSSSelector::kPseudoSpatialNavigationInterest: return &EnsurePseudoInvalidationSet(selector.GetPseudoType(), type, position); case CSSSelector::kPseudoFirstOfType:
diff --git a/third_party/blink/renderer/core/css/rule_set.cc b/third_party/blink/renderer/core/css/rule_set.cc index dcdca93..6421b53 100644 --- a/third_party/blink/renderer/core/css/rule_set.cc +++ b/third_party/blink/renderer/core/css/rule_set.cc
@@ -135,7 +135,7 @@ case CSSSelector::kPseudoPart: case CSSSelector::kPseudoHost: case CSSSelector::kPseudoHostContext: - case CSSSelector::kPseudoSpatialNavigationFocus: + case CSSSelector::kPseudoSpatialNavigationInterest: pseudo_type = selector->GetPseudoType(); break; case CSSSelector::kPseudoWebKitCustomElement: @@ -207,8 +207,8 @@ case CSSSelector::kPseudoWebkitAnyLink: link_pseudo_class_rules_.push_back(rule_data); return true; - case CSSSelector::kPseudoSpatialNavigationFocus: - spatial_navigation_focus_class_rules_.push_back(rule_data); + case CSSSelector::kPseudoSpatialNavigationInterest: + spatial_navigation_interest_class_rules_.push_back(rule_data); return true; case CSSSelector::kPseudoFocus: focus_pseudo_class_rules_.push_back(rule_data); @@ -395,7 +395,7 @@ link_pseudo_class_rules_.ShrinkToFit(); cue_pseudo_rules_.ShrinkToFit(); focus_pseudo_class_rules_.ShrinkToFit(); - spatial_navigation_focus_class_rules_.ShrinkToFit(); + spatial_navigation_interest_class_rules_.ShrinkToFit(); universal_rules_.ShrinkToFit(); shadow_host_rules_.ShrinkToFit(); page_rules_.ShrinkToFit(); @@ -431,7 +431,7 @@ visitor->Trace(link_pseudo_class_rules_); visitor->Trace(cue_pseudo_rules_); visitor->Trace(focus_pseudo_class_rules_); - visitor->Trace(spatial_navigation_focus_class_rules_); + visitor->Trace(spatial_navigation_interest_class_rules_); visitor->Trace(universal_rules_); visitor->Trace(shadow_host_rules_); visitor->Trace(page_rules_);
diff --git a/third_party/blink/renderer/core/css/rule_set.h b/third_party/blink/renderer/core/css/rule_set.h index c4eac93..7ecde471 100644 --- a/third_party/blink/renderer/core/css/rule_set.h +++ b/third_party/blink/renderer/core/css/rule_set.h
@@ -215,9 +215,9 @@ return &focus_pseudo_class_rules_; } const HeapVector<Member<const RuleData>>* - SpatialNavigationFocusPseudoClassRules() const { + SpatialNavigationInterestPseudoClassRules() const { DCHECK(!pending_rules_); - return &spatial_navigation_focus_class_rules_; + return &spatial_navigation_interest_class_rules_; } const HeapVector<Member<const RuleData>>* UniversalRules() const { DCHECK(!pending_rules_); @@ -334,7 +334,7 @@ HeapVector<Member<const RuleData>> link_pseudo_class_rules_; HeapVector<Member<const RuleData>> cue_pseudo_rules_; HeapVector<Member<const RuleData>> focus_pseudo_class_rules_; - HeapVector<Member<const RuleData>> spatial_navigation_focus_class_rules_; + HeapVector<Member<const RuleData>> spatial_navigation_interest_class_rules_; HeapVector<Member<const RuleData>> universal_rules_; HeapVector<Member<const RuleData>> shadow_host_rules_; HeapVector<Member<const RuleData>> part_pseudo_rules_;
diff --git a/third_party/blink/renderer/core/css/selector_checker.cc b/third_party/blink/renderer/core/css/selector_checker.cc index 8eec220..c45c40e 100644 --- a/third_party/blink/renderer/core/css/selector_checker.cc +++ b/third_party/blink/renderer/core/css/selector_checker.cc
@@ -75,6 +75,12 @@ .FrameIsFocusedAndActive(); } +static bool MatchesSpatialNavigationFocusPseudoClass(const Element& element) { + return IsHTMLOptionElement(element) && + ToHTMLOptionElement(element).SpatialNavigationFocused() && + IsFrameFocused(element); +} + static bool MatchesListBoxPseudoClass(const Element& element) { return IsHTMLSelectElement(element) && !ToHTMLSelectElement(element).UsesMenuList(); @@ -1072,6 +1078,9 @@ case CSSSelector::kPseudoSpatialNavigationFocus: DCHECK(is_ua_rule_); return MatchesSpatialNavigationFocusPseudoClass(element); + case CSSSelector::kPseudoSpatialNavigationInterest: + DCHECK(is_ua_rule_); + return MatchesSpatialNavigationInterestPseudoClass(element); case CSSSelector::kPseudoIsHtml: DCHECK(is_ua_rule_); return element.GetDocument().IsHTMLDocument(); @@ -1395,27 +1404,20 @@ } // static -bool SelectorChecker::MatchesSpatialNavigationFocusPseudoClass( +bool SelectorChecker::MatchesSpatialNavigationInterestPseudoClass( const Element& element) { if (!IsSpatialNavigationEnabled(element.GetDocument().GetFrame())) return false; - if (RuntimeEnabledFeatures::FocuslessSpatialNavigationEnabled()) { - DCHECK(element.GetDocument().GetPage()); - Element* interested_element = element.GetDocument() - .GetPage() - ->GetSpatialNavigationController() - .GetInterestedElement(); - return interested_element && *interested_element == element; - } - if (RuntimeEnabledFeatures::SpatialNavigationForcesOutlineEnabled()) { - // TODO(mthiesse): Decouple spatial navigation target from focus, so that - // if spat nav is enabled, but not used, we don't override focus ring - // behavior on that element. - return element.IsFocused() && IsFrameFocused(element); - } - return IsHTMLOptionElement(element) && - ToHTMLOptionElement(element).SpatialNavigationFocused() && - IsFrameFocused(element); + + if (!RuntimeEnabledFeatures::FocuslessSpatialNavigationEnabled()) + return false; + + DCHECK(element.GetDocument().GetPage()); + Element* interested_element = element.GetDocument() + .GetPage() + ->GetSpatialNavigationController() + .GetInterestedElement(); + return interested_element && *interested_element == element; } } // namespace blink
diff --git a/third_party/blink/renderer/core/css/selector_checker.h b/third_party/blink/renderer/core/css/selector_checker.h index c657a9e..39d30f3d 100644 --- a/third_party/blink/renderer/core/css/selector_checker.h +++ b/third_party/blink/renderer/core/css/selector_checker.h
@@ -153,7 +153,7 @@ static bool MatchesFocusPseudoClass(const Element&); static bool MatchesFocusVisiblePseudoClass(const Element&); - static bool MatchesSpatialNavigationFocusPseudoClass(const Element&); + static bool MatchesSpatialNavigationInterestPseudoClass(const Element&); private: // Does the work of checking whether the simple selector and element pointed
diff --git a/third_party/blink/renderer/core/dom/events/event.cc b/third_party/blink/renderer/core/dom/events/event.cc index a1e0e64c..8c0a14a 100644 --- a/third_party/blink/renderer/core/dom/events/event.cc +++ b/third_party/blink/renderer/core/dom/events/event.cc
@@ -98,7 +98,6 @@ default_handled_(false), was_initialized_(true), is_trusted_(false), - executed_listener_or_default_action_(false), prevent_default_called_on_uncancelable_event_(false), legacy_did_listeners_throw_flag_(false), fire_only_capture_listeners_at_target_(false), @@ -273,10 +272,6 @@ ReceivedTarget(); } -void Event::DoneDispatchingEventAtCurrentTarget() { - SetExecutedListenerOrDefaultAction(); -} - void Event::SetRelatedTargetIfExists(EventTarget* related_target) { if (IsMouseEvent()) { ToMouseEvent(this)->SetRelatedTarget(related_target);
diff --git a/third_party/blink/renderer/core/dom/events/event.h b/third_party/blink/renderer/core/dom/events/event.h index 8c35bc5..033ae87 100644 --- a/third_party/blink/renderer/core/dom/events/event.h +++ b/third_party/blink/renderer/core/dom/events/event.h
@@ -148,7 +148,7 @@ // at the current target. It should only be used to influence UMA metrics // and not change functionality since observing the presence of listeners // is dangerous. - virtual void DoneDispatchingEventAtCurrentTarget(); + virtual void DoneDispatchingEventAtCurrentTarget() {} void SetRelatedTargetIfExists(EventTarget* related_target); @@ -292,14 +292,6 @@ return prevent_default_called_on_uncancelable_event_; } - bool executedListenerOrDefaultAction() const { - return executed_listener_or_default_action_; - } - - void SetExecutedListenerOrDefaultAction() { - executed_listener_or_default_action_ = true; - } - bool LegacyDidListenersThrow() const { return legacy_did_listeners_throw_flag_; } @@ -344,9 +336,6 @@ unsigned default_handled_ : 1; unsigned was_initialized_ : 1; unsigned is_trusted_ : 1; - // Only if at least one listeners or default actions are executed on an event - // does Event Timing report it. - unsigned executed_listener_or_default_action_ : 1; // Whether preventDefault was called when |handling_passive_| is // true. This field is reset on each call to SetHandlingPassive.
diff --git a/third_party/blink/renderer/core/dom/events/event_target.cc b/third_party/blink/renderer/core/dom/events/event_target.cc index a14c537..599872c 100644 --- a/third_party/blink/renderer/core/dom/events/event_target.cc +++ b/third_party/blink/renderer/core/dom/events/event_target.cc
@@ -729,7 +729,6 @@ // Only invoke the callback if event listeners were fired for this phase. if (fired_event_listeners) { event.DoneDispatchingEventAtCurrentTarget(); - event.SetExecutedListenerOrDefaultAction(); // Only count uma metrics if we really fired an event listener. Editor::CountEvent(GetExecutionContext(), event);
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.cc b/third_party/blink/renderer/core/frame/local_frame_view.cc index 73a5ea3..5f4e0bd0 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.cc +++ b/third_party/blink/renderer/core/frame/local_frame_view.cc
@@ -2171,8 +2171,10 @@ return Lifecycle().GetState() == target_state; } - for (auto& observer : lifecycle_observers_) - observer->WillStartLifecycleUpdate(); + ForAllNonThrottledLocalFrameViews([](LocalFrameView& frame_view) { + for (auto& observer : frame_view.lifecycle_observers_) + observer->WillStartLifecycleUpdate(); + }); // If we're in PrintBrowser mode, setup a print context. // TODO(vmpstr): It doesn't seem like we need to do this every lifecycle @@ -2196,8 +2198,10 @@ UpdateThrottlingStatusForSubtree(); - for (auto& observer : lifecycle_observers_) - observer->DidFinishLifecycleUpdate(); + ForAllNonThrottledLocalFrameViews([](LocalFrameView& frame_view) { + for (auto& observer : frame_view.lifecycle_observers_) + observer->DidFinishLifecycleUpdate(); + }); return Lifecycle().GetState() == target_state; }
diff --git a/third_party/blink/renderer/core/html/resources/html.css b/third_party/blink/renderer/core/html/resources/html.css index cde04b69..fbcb428 100644 --- a/third_party/blink/renderer/core/html/resources/html.css +++ b/third_party/blink/renderer/core/html/resources/html.css
@@ -645,8 +645,8 @@ } option:-internal-spatial-navigation-focus { - outline: black dashed 1px !important; - outline-offset: -1px !important; + outline: black dashed 1px; + outline-offset: -1px; } datalist { @@ -989,9 +989,9 @@ /* states */ -:-internal-spatial-navigation-focus { - outline: auto 5px -webkit-focus-ring-color !important; - box-shadow: none !important +:-internal-spatial-navigation-interest { + outline: auto 5px -webkit-focus-ring-color !important; + box-shadow: none !important } :focus {
diff --git a/third_party/blink/renderer/core/inspector/inspector_trace_events.cc b/third_party/blink/renderer/core/inspector/inspector_trace_events.cc index 55f058c..60912f7 100644 --- a/third_party/blink/renderer/core/inspector/inspector_trace_events.cc +++ b/third_party/blink/renderer/core/inspector/inspector_trace_events.cc
@@ -340,6 +340,7 @@ DEFINE_STRING_MAPPING(PseudoShadow) DEFINE_STRING_MAPPING(PseudoSlotted) DEFINE_STRING_MAPPING(PseudoSpatialNavigationFocus) + DEFINE_STRING_MAPPING(PseudoSpatialNavigationInterest) DEFINE_STRING_MAPPING(PseudoIsHtml) DEFINE_STRING_MAPPING(PseudoListBox) DEFINE_STRING_MAPPING(PseudoHostHasAppearance)
diff --git a/third_party/blink/renderer/core/layout/layout_box.cc b/third_party/blink/renderer/core/layout/layout_box.cc index 4c08a81..3e0a94e 100644 --- a/third_party/blink/renderer/core/layout/layout_box.cc +++ b/third_party/blink/renderer/core/layout/layout_box.cc
@@ -3638,10 +3638,10 @@ return AdjustContentBoxLogicalWidthForBoxSizing(LayoutUnit()); switch (logical_width.GetType()) { - case kFixed: + case Length::kFixed: return AdjustContentBoxLogicalWidthForBoxSizing(logical_width.Value()); - case kMinContent: - case kMaxContent: { + case Length::kMinContent: + case Length::kMaxContent: { // MinContent/MaxContent don't need the availableLogicalWidth argument. LayoutUnit available_logical_width; return ComputeIntrinsicLogicalWidthUsing(logical_width, @@ -3649,10 +3649,10 @@ BorderAndPaddingLogicalWidth()) - BorderAndPaddingLogicalWidth(); } - case kFitContent: - case kFillAvailable: - case kPercent: - case kCalculated: { + case Length::kFitContent: + case Length::kFillAvailable: + case Length::kPercent: + case Length::kCalculated: { LayoutUnit cw; if (IsOutOfFlowPositioned()) { cw = ContainingBlockLogicalWidthForPositioned( @@ -3677,12 +3677,12 @@ MinimumValueForLength(logical_width, cw)); return LayoutUnit(); } - case kAuto: - case kMaxSizeNone: + case Length::kAuto: + case Length::kMaxSizeNone: return IntrinsicLogicalWidth(); - case kExtendToZoom: - case kDeviceWidth: - case kDeviceHeight: + case Length::kExtendToZoom: + case Length::kDeviceWidth: + case Length::kDeviceHeight: break; } @@ -3748,10 +3748,10 @@ return AdjustContentBoxLogicalHeightForBoxSizing(LayoutUnit()); switch (logical_height.GetType()) { - case kFixed: + case Length::kFixed: return AdjustContentBoxLogicalHeightForBoxSizing(logical_height.Value()); - case kPercent: - case kCalculated: { + case Length::kPercent: + case Length::kCalculated: { // TODO(rego): Check if we can somehow reuse // LayoutBox::computePercentageLogicalHeight() and/or // LayoutBlock::availableLogicalHeightForPercentageComputation() (see @@ -3817,10 +3817,10 @@ return AdjustContentBoxLogicalHeightForBoxSizing( ValueForLength(logical_height, available_height)); } - case kMinContent: - case kMaxContent: - case kFitContent: - case kFillAvailable: + case Length::kMinContent: + case Length::kMaxContent: + case Length::kFitContent: + case Length::kFillAvailable: return AdjustContentBoxLogicalHeightForBoxSizing( ComputeIntrinsicLogicalContentHeightUsing(logical_height, IntrinsicLogicalHeight(),
diff --git a/third_party/blink/renderer/core/layout/layout_table_section.cc b/third_party/blink/renderer/core/layout/layout_table_section.cc index f336a5e..b37ed0a 100644 --- a/third_party/blink/renderer/core/layout/layout_table_section.cc +++ b/third_party/blink/renderer/core/layout/layout_table_section.cc
@@ -58,14 +58,14 @@ const Length& cell_logical_height = cell->StyleRef().LogicalHeight(); if (cell_logical_height.IsPositive()) { switch (cell_logical_height.GetType()) { - case kPercent: + case Length::kPercent: // TODO(alancutter): Make this work correctly for calc lengths. if (!(logical_height.IsPercentOrCalc()) || (logical_height.IsPercent() && logical_height.Percent() < cell_logical_height.Percent())) logical_height = cell_logical_height; break; - case kFixed: + case Length::kFixed: if (logical_height.IsAuto() || (logical_height.IsFixed() && logical_height.Value() < cell_logical_height.Value()))
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_node.cc b/third_party/blink/renderer/core/layout/ng/ng_block_node.cc index 32d6b73..88b1411b 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_node.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_node.cc
@@ -222,12 +222,6 @@ UpdateShapeOutsideInfoIfNeeded( *layout_result, constraint_space.PercentageResolutionInlineSize()); - // We have to re-set the cached result here, because it is used for - // LayoutNGMixin::CurrentFragment and therefore has to be up-to-date. - // In particular, that fragment would have an incorrect offset if we - // don't re-set the result here. - block_flow->SetCachedLayoutResult(constraint_space, break_token, - *layout_result); return layout_result; } }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc b/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc index d6ce84a..e0f2907 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc
@@ -140,16 +140,16 @@ } switch (length.GetType()) { - case kAuto: - case kFillAvailable: { + case Length::kAuto: + case Length::kFillAvailable: { LayoutUnit content_size = constraint_space.AvailableSize().inline_size; NGBoxStrut margins = ComputeMarginsForSelf(constraint_space, style); return std::max(border_padding.InlineSum(), content_size - margins.InlineSum()); } - case kPercent: - case kFixed: - case kCalculated: { + case Length::kPercent: + case Length::kFixed: + case Length::kCalculated: { LayoutUnit percentage_resolution_size = constraint_space.PercentageResolutionInlineSize(); LayoutUnit value = ValueForLength(length, percentage_resolution_size); @@ -160,9 +160,9 @@ } return value; } - case kMinContent: - case kMaxContent: - case kFitContent: { + case Length::kMinContent: + case Length::kMaxContent: + case Length::kFitContent: { DCHECK(min_and_max.has_value()); LayoutUnit available_size = constraint_space.AvailableSize().inline_size; LayoutUnit value; @@ -180,12 +180,12 @@ } return value; } - case kDeviceWidth: - case kDeviceHeight: - case kExtendToZoom: + case Length::kDeviceWidth: + case Length::kDeviceHeight: + case Length::kExtendToZoom: NOTREACHED() << "These should only be used for viewport definitions"; FALLTHROUGH; - case kMaxSizeNone: + case Length::kMaxSizeNone: default: NOTREACHED(); return border_padding.InlineSum(); @@ -254,15 +254,15 @@ } switch (length.GetType()) { - case kFillAvailable: { + case Length::kFillAvailable: { LayoutUnit content_size = constraint_space.AvailableSize().block_size; NGBoxStrut margins = ComputeMarginsForSelf(constraint_space, style); return std::max(border_padding.BlockSum(), content_size - margins.BlockSum()); } - case kPercent: - case kFixed: - case kCalculated: { + case Length::kPercent: + case Length::kFixed: + case Length::kCalculated: { LayoutUnit percentage_resolution_block_size = opt_percentage_resolution_block_size_for_min_max ? *opt_percentage_resolution_block_size_for_min_max @@ -284,10 +284,10 @@ } return value; } - case kAuto: - case kMinContent: - case kMaxContent: - case kFitContent: + case Length::kAuto: + case Length::kMinContent: + case Length::kMaxContent: + case Length::kFitContent: #if DCHECK_IS_ON() // Due to how content_size is calculated, it should always include border // and padding. We cannot check for this if we are block-fragmented, @@ -298,12 +298,12 @@ DCHECK_GE(content_size, border_padding.BlockSum()); #endif // DCHECK_IS_ON() return content_size; - case kDeviceWidth: - case kDeviceHeight: - case kExtendToZoom: + case Length::kDeviceWidth: + case Length::kDeviceHeight: + case Length::kExtendToZoom: NOTREACHED() << "These should only be used for viewport definitions"; FALLTHROUGH; - case kMaxSizeNone: + case Length::kMaxSizeNone: default: NOTREACHED(); return border_padding.BlockSum(); @@ -318,20 +318,20 @@ // https://www.w3.org/TR/CSS2/box.html#value-def-margin-width // https://www.w3.org/TR/CSS2/box.html#value-def-padding-width switch (length.GetType()) { - case kAuto: + case Length::kAuto: return LayoutUnit(); - case kPercent: - case kFixed: - case kCalculated: + case Length::kPercent: + case Length::kFixed: + case Length::kCalculated: return ValueForLength(length, percentage_resolution_size); - case kMinContent: - case kMaxContent: - case kFillAvailable: - case kFitContent: - case kExtendToZoom: - case kDeviceWidth: - case kDeviceHeight: - case kMaxSizeNone: + case Length::kMinContent: + case Length::kMaxContent: + case Length::kFillAvailable: + case Length::kFitContent: + case Length::kExtendToZoom: + case Length::kDeviceWidth: + case Length::kDeviceHeight: + case Length::kMaxSizeNone: FALLTHROUGH; default: NOTREACHED();
diff --git a/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.cc b/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.cc index 9612baa..e95bdd8 100644 --- a/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.cc +++ b/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.cc
@@ -93,7 +93,7 @@ if (cell_logical_width.IsNegative()) cell_logical_width = Length::Fixed(0); switch (cell_logical_width.GetType()) { - case kFixed: + case Length::kFixed: // ignore width=0 if (cell_logical_width.IsPositive() && !column_layout.logical_width.IsPercentOrCalc()) { @@ -115,7 +115,7 @@ } } break; - case kPercent: + case Length::kPercent: has_percent_ = true; // TODO(alancutter): Make this work correctly for calc lengths. if (cell_logical_width.IsPositive() && @@ -401,11 +401,11 @@ while (last_col < n_eff_cols && span > 0) { Layout& column_layout = layout_struct_[last_col]; switch (column_layout.logical_width.GetType()) { - case kPercent: + case Length::kPercent: total_percent += column_layout.logical_width.Percent(); all_cols_are_fixed = false; break; - case kFixed: + case Length::kFixed: if (column_layout.logical_width.Value() > 0) { fixed_width += column_layout.logical_width.Value(); all_cols_are_percent = false; @@ -415,7 +415,7 @@ break; } FALLTHROUGH; - case kAuto: + case Length::kAuto: have_auto = true; FALLTHROUGH; default: @@ -686,16 +686,16 @@ available -= cell_logical_width; Length& logical_width = layout_struct_[i].effective_logical_width; switch (logical_width.GetType()) { - case kPercent: + case Length::kPercent: have_percent = true; total_percent += logical_width.Percent(); break; - case kFixed: + case Length::kFixed: num_fixed++; total_fixed += layout_struct_[i].ClampedEffectiveMaxLogicalWidth(); // fall through break; - case kAuto: + case Length::kAuto: if (layout_struct_[i].empty_cells_only) { num_auto_empty_cells_only++; } else { @@ -764,25 +764,26 @@ if (available > 0 && (num_auto || num_auto_empty_cells_only)) { available += alloc_auto; if (num_auto) { - DistributeWidthToColumns<float, kAuto, kNonEmptyCells, kInitialWidth, - kStartToEnd>(available, total_auto); + DistributeWidthToColumns<float, Length::kAuto, kNonEmptyCells, + kInitialWidth, kStartToEnd>(available, + total_auto); } if (num_auto_empty_cells_only) { - DistributeWidthToColumns<unsigned, kAuto, kEmptyCells, kInitialWidth, - kStartToEnd>(available, - num_auto_empty_cells_only); + DistributeWidthToColumns<unsigned, Length::kAuto, kEmptyCells, + kInitialWidth, kStartToEnd>( + available, num_auto_empty_cells_only); } } // Any remaining available width expands fixed width, percent width, and // non-empty auto width columns, in that order. if (available > 0 && num_fixed) { - DistributeWidthToColumns<float, kFixed, kAllCells, kExtraWidth, + DistributeWidthToColumns<float, Length::kFixed, kAllCells, kExtraWidth, kStartToEnd>(available, total_fixed); } if (available > 0 && has_percent_ && total_percent < 100) { - DistributeWidthToColumns<float, kPercent, kAllCells, kExtraWidth, + DistributeWidthToColumns<float, Length::kPercent, kAllCells, kExtraWidth, kStartToEnd>(available, total_percent); } @@ -790,8 +791,8 @@ unsigned total = n_eff_cols - num_auto_empty_cells_only; // Starting from the last cell is for compatibility with FF/IE - it isn't // specified anywhere. - DistributeWidthToColumns<unsigned, kAuto, kNonEmptyCells, kLeftoverWidth, - kEndToStart>(available, total); + DistributeWidthToColumns<unsigned, Length::kAuto, kNonEmptyCells, + kLeftoverWidth, kEndToStart>(available, total); } // If we have overallocated, reduce every cell according to the difference @@ -799,11 +800,11 @@ // exact results with IE. Wonder is some of this also holds for width // distributing. This is basically the reverse of how we grew the cells. if (available < 0) - ShrinkColumnWidth(kAuto, available); + ShrinkColumnWidth(Length::kAuto, available); if (available < 0) - ShrinkColumnWidth(kFixed, available); + ShrinkColumnWidth(Length::kFixed, available); if (available < 0) - ShrinkColumnWidth(kPercent, available); + ShrinkColumnWidth(Length::kPercent, available); DCHECK_EQ(table_->EffectiveColumnPositions().size(), n_eff_cols + 1); int pos = 0; @@ -816,7 +817,7 @@ } template <typename Total, - LengthType lengthType, + Length::Type lengthType, CellsToProcess cellsToProcess, DistributionMode distributionMode, DistributionDirection distributionDirection> @@ -843,9 +844,9 @@ float factor = 1; if (distributionMode != kLeftoverWidth) { - if (lengthType == kPercent) + if (lengthType == Length::kPercent) factor = logical_width.Percent(); - else if (lengthType == kAuto || lengthType == kFixed) + else if (lengthType == Length::kAuto || lengthType == Length::kFixed) factor = layout_struct_[i].ClampedEffectiveMaxLogicalWidth(); } @@ -863,15 +864,16 @@ // If we have run out of width to allocate we're done. // TODO(rhogan): Extend this to Fixed as well. - if (lengthType == kPercent && (!available || !total)) + if (lengthType == Length::kPercent && (!available || !total)) return; - if (lengthType == kAuto && !total) + if (lengthType == Length::kAuto && !total) return; } } -void TableLayoutAlgorithmAuto::ShrinkColumnWidth(const LengthType& length_type, - int& available) { +void TableLayoutAlgorithmAuto::ShrinkColumnWidth( + const Length::Type& length_type, + int& available) { unsigned n_eff_cols = table_->NumEffectiveColumns(); int logical_width_beyond_min = 0; for (unsigned i = n_eff_cols; i;) {
diff --git a/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.h b/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.h index 0169f1e..3f72254 100644 --- a/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.h +++ b/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.h
@@ -57,9 +57,9 @@ void RecalcColumn(unsigned eff_col); int CalcEffectiveLogicalWidth(); - void ShrinkColumnWidth(const LengthType&, int& available); + void ShrinkColumnWidth(const Length::Type&, int& available); template <typename Total, - LengthType, + Length::Type, CellsToProcess, DistributionMode, DistributionDirection>
diff --git a/third_party/blink/renderer/core/paint/ellipsis_box_painter.cc b/third_party/blink/renderer/core/paint/ellipsis_box_painter.cc index c1f28b7..beb88cb4 100644 --- a/third_party/blink/renderer/core/paint/ellipsis_box_painter.cc +++ b/third_party/blink/renderer/core/paint/ellipsis_box_painter.cc
@@ -9,6 +9,7 @@ #include "third_party/blink/renderer/core/layout/line/root_inline_box.h" #include "third_party/blink/renderer/core/layout/text_run_constructor.h" #include "third_party/blink/renderer/core/paint/paint_info.h" +#include "third_party/blink/renderer/core/paint/paint_timing_detector.h" #include "third_party/blink/renderer/core/paint/text_painter.h" #include "third_party/blink/renderer/platform/graphics/graphics_context_state_saver.h" #include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h" @@ -69,6 +70,13 @@ // TODO(npm): Check that there are non-whitespace characters. See // crbug.com/788444. context.GetPaintController().SetTextPainted(); + if (RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled()) { + // We should consider using the text node as the tracking node, instead of + // the line layout item. + PaintTimingDetector::NotifyTextPaint( + ellipsis_box_.GetLineLayoutItem().GetNode(), + paint_info.context.GetPaintController().CurrentPaintChunkProperties()); + } } } // namespace blink
diff --git a/third_party/blink/renderer/core/paint/file_upload_control_painter.cc b/third_party/blink/renderer/core/paint/file_upload_control_painter.cc index 5dfade7..91f25ce 100644 --- a/third_party/blink/renderer/core/paint/file_upload_control_painter.cc +++ b/third_party/blink/renderer/core/paint/file_upload_control_painter.cc
@@ -9,6 +9,7 @@ #include "third_party/blink/renderer/core/layout/layout_file_upload_control.h" #include "third_party/blink/renderer/core/layout/text_run_constructor.h" #include "third_party/blink/renderer/core/paint/paint_info.h" +#include "third_party/blink/renderer/core/paint/paint_timing_detector.h" #include "third_party/blink/renderer/platform/fonts/text_run_paint_info.h" #include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h" @@ -77,6 +78,11 @@ paint_info.context.DrawBidiText( font, text_run_paint_info, FloatPoint(RoundToInt(text_x), RoundToInt(text_y))); + if (RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled()) { + PaintTimingDetector::NotifyTextPaint( + layout_file_upload_control_, paint_info.context.GetPaintController() + .CurrentPaintChunkProperties()); + } } // Paint the children.
diff --git a/third_party/blink/renderer/core/paint/inline_text_box_painter.cc b/third_party/blink/renderer/core/paint/inline_text_box_painter.cc index f948711..9d7f30c96 100644 --- a/third_party/blink/renderer/core/paint/inline_text_box_painter.cc +++ b/third_party/blink/renderer/core/paint/inline_text_box_painter.cc
@@ -20,6 +20,7 @@ #include "third_party/blink/renderer/core/paint/decoration_info.h" #include "third_party/blink/renderer/core/paint/document_marker_painter.h" #include "third_party/blink/renderer/core/paint/paint_info.h" +#include "third_party/blink/renderer/core/paint/paint_timing_detector.h" #include "third_party/blink/renderer/core/paint/selection_painting_utils.h" #include "third_party/blink/renderer/core/paint/text_painter.h" #include "third_party/blink/renderer/platform/graphics/graphics_context_state_saver.h" @@ -413,6 +414,11 @@ context.ConcatCTM(TextPainterBase::Rotation( box_rect, TextPainterBase::kCounterclockwise)); } + if (RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled()) { + PaintTimingDetector::NotifyTextPaint( + InlineLayoutObject(), + paint_info.context.GetPaintController().CurrentPaintChunkProperties()); + } } bool InlineTextBoxPainter::ShouldPaintTextBox(const PaintInfo& paint_info) {
diff --git a/third_party/blink/renderer/core/paint/ng/ng_text_painter.cc b/third_party/blink/renderer/core/paint/ng/ng_text_painter.cc index d0588ee7..67c36b1 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_text_painter.cc +++ b/third_party/blink/renderer/core/paint/ng/ng_text_painter.cc
@@ -10,6 +10,7 @@ #include "third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h" #include "third_party/blink/renderer/core/paint/box_painter.h" #include "third_party/blink/renderer/core/paint/paint_info.h" +#include "third_party/blink/renderer/core/paint/paint_timing_detector.h" #include "third_party/blink/renderer/core/style/computed_style.h" #include "third_party/blink/renderer/core/style/shadow_list.h" #include "third_party/blink/renderer/platform/fonts/font.h" @@ -60,6 +61,11 @@ // TODO(npm): Check that there are non-whitespace characters. See // crbug.com/788444. graphics_context_.GetPaintController().SetTextPainted(); + if (RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled()) { + PaintTimingDetector::NotifyTextPaint( + *fragment_.GetLayoutObject(), + graphics_context_.GetPaintController().CurrentPaintChunkProperties()); + } } }
diff --git a/third_party/blink/renderer/core/paint/paint_timing_detector.cc b/third_party/blink/renderer/core/paint/paint_timing_detector.cc index cbba734a..942f0271 100644 --- a/third_party/blink/renderer/core/paint/paint_timing_detector.cc +++ b/third_party/blink/renderer/core/paint/paint_timing_detector.cc
@@ -13,6 +13,10 @@ #include "third_party/blink/renderer/core/paint/paint_layer.h" #include "third_party/blink/renderer/core/paint/text_paint_timing_detector.h" #include "third_party/blink/renderer/platform/geometry/int_rect.h" +#include "third_party/blink/renderer/platform/graphics/paint/float_clip_rect.h" +#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h" +#include "third_party/blink/renderer/platform/graphics/paint/property_tree_state.h" +#include "third_party/blink/renderer/platform/graphics/paint/scoped_paint_chunk_properties.h" namespace blink { @@ -35,9 +39,6 @@ if (!frame_view_->GetFrame().IsMainFrame()) return; - if (object.IsText()) { - text_paint_timing_detector_->RecordText(object, painting_layer); - } if (object.IsLayoutImage() || object.IsVideo() || object.IsSVGImage() || ImagePaintTimingDetector::HasContentfulBackgroundImage(object)) { image_paint_timing_detector_->RecordImage(object, painting_layer); @@ -45,6 +46,28 @@ // Todo(maxlg): add other detectors here. } +void PaintTimingDetector::NotifyTextPaint( + const Node* node, + const PropertyTreeState& current_paint_chunk_properties) { + if (!node) + return; + LayoutObject* object = node->GetLayoutObject(); + if (!object) + return; + NotifyTextPaint(*object, current_paint_chunk_properties); +} + +void PaintTimingDetector::NotifyTextPaint( + const LayoutObject& object, + const PropertyTreeState& current_paint_chunk_properties) { + LocalFrameView* frame_view = object.GetFrameView(); + if (!frame_view || !frame_view->GetFrame().IsMainFrame()) + return; + PaintTimingDetector& detector = frame_view->GetPaintTimingDetector(); + detector.GetTextPaintTimingDetector().RecordText( + object, current_paint_chunk_properties); +} + void PaintTimingDetector::NotifyNodeRemoved(const LayoutObject& object) { if (!object.GetNode()) return; @@ -89,14 +112,23 @@ uint64_t PaintTimingDetector::CalculateVisualSize( const LayoutRect& invalidated_rect, const PaintLayer& painting_layer) const { + return CalculateVisualSize(invalidated_rect, painting_layer.GetLayoutObject() + .FirstFragment() + .LocalBorderBoxProperties()); +} + +uint64_t PaintTimingDetector::CalculateVisualSize( + const LayoutRect& invalidated_rect, + const PropertyTreeState& current_paint_chunk_properties) const { // This case should be dealt with outside the function. DCHECK(!invalidated_rect.IsEmpty()); // As Layout objects live in different transform spaces, the object's rect // should be projected to the viewport's transform space. - IntRect visual_rect = SaturatedRect(EnclosedIntRect(invalidated_rect)); - painting_layer.GetLayoutObject().FirstFragment().MapRectToFragment( - painting_layer.GetLayoutObject().View()->FirstFragment(), visual_rect); + FloatClipRect visual_rect = FloatClipRect(FloatRect(invalidated_rect)); + GeometryMapper::LocalToAncestorVisualRect( + current_paint_chunk_properties, PropertyTreeState::Root(), visual_rect); + FloatRect& visual_rect_float = visual_rect.Rect(); // A visual rect means the part of the rect that's visible within // the viewport. We define the size of it as visual size. @@ -104,8 +136,9 @@ DCHECK(scrollable_area); IntRect viewport = scrollable_area->VisibleContentRect(); // Use saturated rect to avoid integer-overflow. - visual_rect.Intersect(SaturatedRect(viewport)); - return visual_rect.Size().Area(); + + visual_rect_float.Intersect(SaturatedRect(viewport)); + return visual_rect_float.Size().Area(); } void PaintTimingDetector::Dispose() {
diff --git a/third_party/blink/renderer/core/paint/paint_timing_detector.h b/third_party/blink/renderer/core/paint/paint_timing_detector.h index 78e24f28..c8b0c0e 100644 --- a/third_party/blink/renderer/core/paint/paint_timing_detector.h +++ b/third_party/blink/renderer/core/paint/paint_timing_detector.h
@@ -18,6 +18,7 @@ class LayoutRect; class TextPaintTimingDetector; class ImagePaintTimingDetector; +class PropertyTreeState; // PaintTimingDetector contains some of paint metric detectors, // providing common infrastructure for these detectors. @@ -32,6 +33,9 @@ PaintTimingDetector(LocalFrameView*); void NotifyObjectPrePaint(const LayoutObject& object, const PaintLayer& painting_layer); + static void NotifyTextPaint(const Node* node, const PropertyTreeState&); + static void NotifyTextPaint(const LayoutObject& object, + const PropertyTreeState&); void NotifyNodeRemoved(const LayoutObject& object); void NotifyPrePaintFinished(); void NotifyInputEvent(WebInputEvent::Type); @@ -40,6 +44,8 @@ void DidChangePerformanceTiming(); uint64_t CalculateVisualSize(const LayoutRect& invalidated_rect, const PaintLayer& painting_layer) const; + uint64_t CalculateVisualSize(const LayoutRect& invalidated_rect, + const PropertyTreeState&) const; void Dispose(); TextPaintTimingDetector& GetTextPaintTimingDetector() {
diff --git a/third_party/blink/renderer/core/paint/svg_inline_text_box_painter.cc b/third_party/blink/renderer/core/paint/svg_inline_text_box_painter.cc index d8ae713eb..67ac3293 100644 --- a/third_party/blink/renderer/core/paint/svg_inline_text_box_painter.cc +++ b/third_party/blink/renderer/core/paint/svg_inline_text_box_painter.cc
@@ -19,6 +19,7 @@ #include "third_party/blink/renderer/core/layout/svg/svg_resources_cache.h" #include "third_party/blink/renderer/core/paint/inline_text_box_painter.h" #include "third_party/blink/renderer/core/paint/paint_info.h" +#include "third_party/blink/renderer/core/paint/paint_timing_detector.h" #include "third_party/blink/renderer/core/paint/selection_painting_utils.h" #include "third_party/blink/renderer/core/paint/svg_object_painter.h" #include "third_party/blink/renderer/core/style/applied_text_decoration.h" @@ -468,6 +469,11 @@ // TODO(npm): Check that there are non-whitespace characters. See // crbug.com/788444. context.GetPaintController().SetTextPainted(); + if (RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled()) { + PaintTimingDetector::NotifyTextPaint( + InlineLayoutObject(), + paint_info.context.GetPaintController().CurrentPaintChunkProperties()); + } } void SVGInlineTextBoxPainter::PaintText(
diff --git a/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc b/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc index c5baafdb..78b7618 100644 --- a/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc +++ b/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc
@@ -6,6 +6,7 @@ #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" #include "third_party/blink/renderer/core/inspector/identifiers_factory.h" +#include "third_party/blink/renderer/core/layout/layout_file_upload_control.h" #include "third_party/blink/renderer/core/layout/layout_text.h" #include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/page/chrome_client.h" @@ -185,14 +186,16 @@ awaiting_swap_promise_ = false; } -void TextPaintTimingDetector::RecordText(const LayoutObject& object, - const PaintLayer& painting_layer) { +void TextPaintTimingDetector::RecordText( + const LayoutObject& object, + const PropertyTreeState& current_paint_chunk_properties) { if (!is_recording_) return; Node* node = object.GetNode(); if (!node) return; DOMNodeId node_id = DOMNodeIds::IdForNode(node); + DCHECK_NE(node_id, kInvalidDOMNodeId); // This metric defines the size of a text by its first size. So it // early-returns if the text has been recorded. @@ -204,10 +207,12 @@ // the text's first invalidation. uint64_t rect_size = 0; - LayoutRect invalidated_rect = object.FirstFragment().VisualRect(); - if (!invalidated_rect.IsEmpty()) { + // Compared to object.FirstFragment().VisualRect(), this will include other + // fragments of the object. + LayoutRect visual_rect = object.FragmentsVisualRectBoundingBox(); + if (!visual_rect.IsEmpty()) { rect_size = frame_view_->GetPaintTimingDetector().CalculateVisualSize( - invalidated_rect, painting_layer); + visual_rect, current_paint_chunk_properties); } // When rect_size == 0, it either means the text size is 0 or the text is out @@ -220,7 +225,13 @@ record.node_id = node_id; record.first_size = rect_size; #ifndef NDEBUG - record.text = ToLayoutText(&object)->GetText(); + if (object.IsText()) { + record.text = ToLayoutText(&object)->GetText(); + } else if (object.IsFileUploadControl()) { + record.text = ToLayoutFileUploadControl(&object)->FileTextValue(); + } else { + record.text = String("NON-TEXT_OBJECT"); + } #endif texts_to_record_swap_time_.push_back(record); }
diff --git a/third_party/blink/renderer/core/paint/text_paint_timing_detector.h b/third_party/blink/renderer/core/paint/text_paint_timing_detector.h index 8403420..835e608 100644 --- a/third_party/blink/renderer/core/paint/text_paint_timing_detector.h +++ b/third_party/blink/renderer/core/paint/text_paint_timing_detector.h
@@ -13,10 +13,10 @@ #include "third_party/blink/renderer/platform/wtf/time.h" namespace blink { -class PaintLayer; class LayoutObject; class TracedValue; class LocalFrameView; +class PropertyTreeState; struct TextRecord { DOMNodeId node_id = kInvalidDOMNodeId; @@ -57,7 +57,7 @@ public: TextPaintTimingDetector(LocalFrameView* frame_view); - void RecordText(const LayoutObject& object, const PaintLayer& painting_layer); + void RecordText(const LayoutObject& object, const PropertyTreeState&); TextRecord* FindLargestPaintCandidate(); TextRecord* FindLastPaintCandidate(); void OnPrePaintFinished();
diff --git a/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc b/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc index 496c9a7..b78708c 100644 --- a/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc +++ b/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/core/paint/text_paint_timing_detector.h" #include "third_party/blink/renderer/core/paint/paint_timing_detector.h" +#include "third_party/blink/renderer/core/svg/svg_text_content_element.h" #include "third_party/blink/renderer/core/testing/core_unit_test_helper.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" @@ -16,7 +17,10 @@ public: TextPaintTimingDetectorTest() : ScopedFirstContentfulPaintPlusPlusForTest(true) {} - void SetUp() override { RenderingTest::SetUp(); } + void SetUp() override { + RenderingTest::SetUp(); + RenderingTest::EnableCompositing(); + } protected: LocalFrameView& GetFrameView() { return *GetFrame().View(); } @@ -118,7 +122,6 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_NoText) { SetBodyInnerHTML(R"HTML( - <body></body> )HTML"); UpdateAllLifecyclePhasesAndSimulateSwapTime(); EXPECT_FALSE(TextRecordOfLargestTextPaint()); @@ -126,7 +129,6 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_OneText) { SetBodyInnerHTML(R"HTML( - <body></body> )HTML"); Element* only_text = AppendDivElementToBody("The only text"); UpdateAllLifecyclePhasesAndSimulateSwapTime(); @@ -148,7 +150,6 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_LargestText) { SetBodyInnerHTML(R"HTML( - <body></body> )HTML"); AppendDivElementToBody("medium text"); UpdateAllLifecyclePhasesAndSimulateSwapTime(); @@ -193,7 +194,6 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_ReportFirstPaintTime) { TimeTicks time1 = CurrentTimeTicks(); SetBodyInnerHTML(R"HTML( - <body></body> )HTML"); Element* size_changing_text = AppendFontElementToBody("size-changing text"); Element* long_text = @@ -238,7 +238,6 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_IgnoreRemovedText) { SetBodyInnerHTML(R"HTML( - <body></body> )HTML"); Element* large_text = AppendDivElementToBody( "(large text)(large text)(large text)(large text)(large text)(large " @@ -254,7 +253,6 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_ReportLastNullCandidate) { SetBodyInnerHTML(R"HTML( - <body></body> )HTML"); Element* text = AppendDivElementToBody("text to remove"); UpdateAllLifecyclePhasesAndSimulateSwapTime(); @@ -272,7 +270,6 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_CompareVisualSizeNotActualSize) { SetBodyInnerHTML(R"HTML( - <body></body> )HTML"); AppendDivElementToBody("a long text", "position:fixed;left:-10px"); Element* short_text = AppendDivElementToBody("short"); @@ -283,7 +280,6 @@ // Depite that the l TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_CompareSizesAtFirstPaint) { SetBodyInnerHTML(R"HTML( - <body></body> )HTML"); Element* shortening_long_text = AppendDivElementToBody("123456789"); AppendDivElementToBody("12345678"); // 1 letter shorter than the above. @@ -309,7 +305,6 @@ TEST_F(TextPaintTimingDetectorTest, LastTextPaint_OneText) { SetBodyInnerHTML(R"HTML( - <body></body> )HTML"); Element* text = AppendDivElementToBody("The only text"); UpdateAllLifecyclePhasesAndSimulateSwapTime(); @@ -334,7 +329,6 @@ TEST_F(TextPaintTimingDetectorTest, LastTextPaint_ReportFirstPaintTime) { SetBodyInnerHTML(R"HTML( - <body></body> )HTML"); AppendDivElementToBody("a loooooooooooooooooooong text"); UpdateAllLifecyclePhasesAndSimulateSwapTime(); @@ -357,9 +351,68 @@ EXPECT_GE(time2, firing_time); } +TEST_F(TextPaintTimingDetectorTest, TreatEllipsisAsText) { + LoadAhem(); + SetBodyInnerHTML(R"HTML( + <div style="font:10px Ahem;white-space:nowrap;width:50px;overflow:hidden;text-overflow:ellipsis;"> + 00000000000000000000000000000000000000000000000000000000000000000000000000 + 00000000000000000000000000000000000000000000000000000000000000000000000000 + </div> + )HTML"); + UpdateAllLifecyclePhasesAndSimulateSwapTime(); + + // The FCP++ hook in ellipsis box painter is using the line layout item as the + // tracking node while layout ng is using the layout text as the tracking + // node. + if (RuntimeEnabledFeatures::LayoutNGEnabled()) { + EXPECT_EQ(CountRecords(), 1u); + } else { + // The text and the elllipsis are recorded. + EXPECT_EQ(CountRecords(), 2u); + } +} + +TEST_F(TextPaintTimingDetectorTest, CaptureFileUploadController) { + SetBodyInnerHTML("<input type='file'>"); + Element* element = GetDocument().QuerySelector("input"); + UpdateAllLifecyclePhasesAndSimulateSwapTime(); + + EXPECT_EQ(CountRecords(), 1u); + EXPECT_EQ(TextRecordOfLargestTextPaint()->node_id, + DOMNodeIds::IdForNode(element)); +} + +TEST_F(TextPaintTimingDetectorTest, NotCapturingListMarkers) { + SetBodyInnerHTML(R"HTML( + <ul> + <li></li> + </ul> + <ol> + <li></li> + </ol> + )HTML"); + UpdateAllLifecyclePhasesAndSimulateSwapTime(); + + EXPECT_EQ(CountRecords(), 0u); +} + +TEST_F(TextPaintTimingDetectorTest, CaptureSVGText) { + SetBodyInnerHTML(R"HTML( + <svg height="40" width="300"> + <text x="0" y="15">A SVG text.</text> + </svg> + )HTML"); + + SVGTextContentElement* elem = + ToSVGTextContentElement(GetDocument().QuerySelector("text")); + UpdateAllLifecyclePhasesAndSimulateSwapTime(); + + EXPECT_EQ(CountRecords(), 1u); + EXPECT_EQ(TextRecordOfLargestTextPaint()->node_id, NodeIdOfText(elem)); +} + TEST_F(TextPaintTimingDetectorTest, LastTextPaint_IgnoreRemovedText) { SetBodyInnerHTML(R"HTML( - <body></body> )HTML"); Element* first_text = AppendDivElementToBody("1st text"); UpdateAllLifecyclePhasesAndSimulateSwapTime(); @@ -374,7 +427,6 @@ TEST_F(TextPaintTimingDetectorTest, LastTextPaint_StopRecordingOverNodeLimit) { SetBodyInnerHTML(R"HTML( - <body></body> )HTML"); UpdateAllLifecyclePhasesAndSimulateSwapTime(); @@ -394,7 +446,6 @@ TEST_F(TextPaintTimingDetectorTest, LastTextPaint_ReportLastNullCandidate) { SetBodyInnerHTML(R"HTML( - <body></body> )HTML"); Element* text = AppendDivElementToBody("text"); UpdateAllLifecyclePhasesAndSimulateSwapTime();
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/kv-storage/index.js b/third_party/blink/renderer/core/script/resources/layered_api/kv-storage/index.js index b35752d..b2cf033e 100644 --- a/third_party/blink/renderer/core/script/resources/layered_api/kv-storage/index.js +++ b/third_party/blink/renderer/core/script/resources/layered_api/kv-storage/index.js
@@ -20,6 +20,7 @@ const _databaseName = new WeakMap(); const _databasePromise = new WeakMap(); +const _backingStoreObject = new WeakMap(); const DEFAULT_STORAGE_AREA_NAME = 'default'; const DEFAULT_IDB_STORE_NAME = 'store'; @@ -120,11 +121,15 @@ throw new TypeError('Invalid this value'); } - return { - database: _databaseName.get(this), - store: DEFAULT_IDB_STORE_NAME, - version: 1, - }; + if (!_backingStoreObject.has(this)) { + _backingStoreObject.set(this, Object.freeze({ + database: _databaseName.get(this), + store: DEFAULT_IDB_STORE_NAME, + version: 1, + })); + } + + return _backingStoreObject.get(this); } } @@ -149,12 +154,19 @@ } function initializeDatabasePromise(area) { + const databaseName = _databaseName.get(area); + _databasePromise.set( area, new Promise((resolve, reject) => { - const request = self.indexedDB.open(_databaseName.get(area), 1); + const request = self.indexedDB.open(databaseName, 1); request.onsuccess = () => { const database = request.result; + + if (!checkDatabaseSchema(database, databaseName, reject)) { + return; + } + database.onclose = () => _databasePromise.set(area, null); database.onversionchange = () => { database.close(); @@ -174,3 +186,38 @@ }; })); } + +function checkDatabaseSchema(database, databaseName, reject) { + if (database.objectStoreNames.length !== 1) { + reject(new DOMException( + `KV storage database "${databaseName}" corrupted: there are ` + + `${database.objectStoreNames.length} object stores, instead of ` + + `the expected 1.`, + 'InvalidStateError')); + return false; + } + + if (database.objectStoreNames[0] !== DEFAULT_IDB_STORE_NAME) { + reject(new DOMException( + `KV storage database "${databaseName}" corrupted: the object store ` + + `is named "${database.objectStoreNames[0]}" instead of the ` + + `expected "${DEFAULT_IDB_STORE_NAME}".`, + 'InvalidStateError')); + return false; + } + + const transaction = database.transaction(DEFAULT_IDB_STORE_NAME, 'readonly'); + const store = transaction.objectStore(DEFAULT_IDB_STORE_NAME); + + if (store.autoIncrement !== false || store.keyPath !== null || + store.indexNames.length !== 0) { + reject(new DOMException( + `KV storage database "${databaseName}" corrupted: the ` + + `"${DEFAULT_IDB_STORE_NAME}" object store has a non-default ` + + `schema.`, + 'InvalidStateError')); + return false; + } + + return true; +}
diff --git a/third_party/blink/renderer/core/style/filter_operation.cc b/third_party/blink/renderer/core/style/filter_operation.cc index 7c077b20..b7f77234 100644 --- a/third_party/blink/renderer/core/style/filter_operation.cc +++ b/third_party/blink/renderer/core/style/filter_operation.cc
@@ -165,7 +165,7 @@ FilterOperation* BlurFilterOperation::Blend(const FilterOperation* from, double progress) const { - LengthType length_type = std_deviation_.GetType(); + Length::Type length_type = std_deviation_.GetType(); if (!from) return BlurFilterOperation::Create(std_deviation_.Blend( Length(length_type), progress, kValueRangeNonNegative));
diff --git a/third_party/blink/renderer/modules/device_orientation/BUILD.gn b/third_party/blink/renderer/modules/device_orientation/BUILD.gn index ff8e1f17..40a0c8b 100644 --- a/third_party/blink/renderer/modules/device_orientation/BUILD.gn +++ b/third_party/blink/renderer/modules/device_orientation/BUILD.gn
@@ -6,16 +6,18 @@ blink_modules_sources("device_orientation") { sources = [ - "device_acceleration.cc", - "device_acceleration.h", "device_motion_controller.cc", "device_motion_controller.h", "device_motion_data.cc", "device_motion_data.h", "device_motion_event.cc", "device_motion_event.h", + "device_motion_event_acceleration.cc", + "device_motion_event_acceleration.h", "device_motion_event_pump.cc", "device_motion_event_pump.h", + "device_motion_event_rotation_rate.cc", + "device_motion_event_rotation_rate.h", "device_orientation_absolute_controller.cc", "device_orientation_absolute_controller.h", "device_orientation_controller.cc", @@ -28,8 +30,6 @@ "device_orientation_event_pump.h", "device_orientation_inspector_agent.cc", "device_orientation_inspector_agent.h", - "device_rotation_rate.cc", - "device_rotation_rate.h", "device_sensor_entry.cc", "device_sensor_entry.h", "device_sensor_event_pump.cc",
diff --git a/third_party/blink/renderer/modules/device_orientation/device_motion_data.cc b/third_party/blink/renderer/modules/device_orientation/device_motion_data.cc index b44ce0f..6a894f1 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_motion_data.cc +++ b/third_party/blink/renderer/modules/device_orientation/device_motion_data.cc
@@ -24,18 +24,16 @@ */ #include "third_party/blink/renderer/modules/device_orientation/device_motion_data.h" -#include "third_party/blink/renderer/modules/device_orientation/device_acceleration.h" -#include "third_party/blink/renderer/modules/device_orientation/device_acceleration_init.h" +#include "third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration.h" #include "third_party/blink/renderer/modules/device_orientation/device_motion_event_init.h" -#include "third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h" -#include "third_party/blink/renderer/modules/device_orientation/device_rotation_rate_init.h" +#include "third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate.h" namespace blink { DeviceMotionData* DeviceMotionData::Create( - DeviceAcceleration* acceleration, - DeviceAcceleration* acceleration_including_gravity, - DeviceRotationRate* rotation_rate, + DeviceMotionEventAcceleration* acceleration, + DeviceMotionEventAcceleration* acceleration_including_gravity, + DeviceMotionEventRotationRate* rotation_rate, double interval) { return MakeGarbageCollected<DeviceMotionData>( acceleration, acceleration_including_gravity, rotation_rate, interval); @@ -43,13 +41,16 @@ DeviceMotionData* DeviceMotionData::Create(const DeviceMotionEventInit* init) { return DeviceMotionData::Create( - init->hasAcceleration() ? DeviceAcceleration::Create(init->acceleration()) - : nullptr, - init->hasAccelerationIncludingGravity() - ? DeviceAcceleration::Create(init->accelerationIncludingGravity()) + init->hasAcceleration() + ? DeviceMotionEventAcceleration::Create(init->acceleration()) : nullptr, - init->hasRotationRate() ? DeviceRotationRate::Create(init->rotationRate()) - : nullptr, + init->hasAccelerationIncludingGravity() + ? DeviceMotionEventAcceleration::Create( + init->accelerationIncludingGravity()) + : nullptr, + init->hasRotationRate() + ? DeviceMotionEventRotationRate::Create(init->rotationRate()) + : nullptr, init->interval()); } @@ -60,9 +61,9 @@ DeviceMotionData::DeviceMotionData() : interval_(0) {} DeviceMotionData::DeviceMotionData( - DeviceAcceleration* acceleration, - DeviceAcceleration* acceleration_including_gravity, - DeviceRotationRate* rotation_rate, + DeviceMotionEventAcceleration* acceleration, + DeviceMotionEventAcceleration* acceleration_including_gravity, + DeviceMotionEventRotationRate* rotation_rate, double interval) : acceleration_(acceleration), acceleration_including_gravity_(acceleration_including_gravity),
diff --git a/third_party/blink/renderer/modules/device_orientation/device_motion_data.h b/third_party/blink/renderer/modules/device_orientation/device_motion_data.h index 57e8453..2977b28 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_motion_data.h +++ b/third_party/blink/renderer/modules/device_orientation/device_motion_data.h
@@ -31,8 +31,8 @@ namespace blink { -class DeviceAcceleration; -class DeviceRotationRate; +class DeviceMotionEventAcceleration; +class DeviceMotionEventRotationRate; class DeviceMotionEventInit; class MODULES_EXPORT DeviceMotionData final @@ -40,34 +40,39 @@ public: static DeviceMotionData* Create(); static DeviceMotionData* Create( - DeviceAcceleration*, - DeviceAcceleration* acceleration_including_gravity, - DeviceRotationRate*, + DeviceMotionEventAcceleration*, + DeviceMotionEventAcceleration* acceleration_including_gravity, + DeviceMotionEventRotationRate*, double interval); static DeviceMotionData* Create(const DeviceMotionEventInit*); DeviceMotionData(); - DeviceMotionData(DeviceAcceleration*, - DeviceAcceleration* acceleration_including_gravity, - DeviceRotationRate*, - double interval); + DeviceMotionData( + DeviceMotionEventAcceleration*, + DeviceMotionEventAcceleration* acceleration_including_gravity, + DeviceMotionEventRotationRate*, + double interval); void Trace(blink::Visitor*); - DeviceAcceleration* GetAcceleration() const { return acceleration_.Get(); } - DeviceAcceleration* GetAccelerationIncludingGravity() const { + DeviceMotionEventAcceleration* GetAcceleration() const { + return acceleration_.Get(); + } + DeviceMotionEventAcceleration* GetAccelerationIncludingGravity() const { return acceleration_including_gravity_.Get(); } - DeviceRotationRate* GetRotationRate() const { return rotation_rate_.Get(); } + DeviceMotionEventRotationRate* GetRotationRate() const { + return rotation_rate_.Get(); + } double Interval() const { return interval_; } bool CanProvideEventData() const; private: - Member<DeviceAcceleration> acceleration_; - Member<DeviceAcceleration> acceleration_including_gravity_; - Member<DeviceRotationRate> rotation_rate_; + Member<DeviceMotionEventAcceleration> acceleration_; + Member<DeviceMotionEventAcceleration> acceleration_including_gravity_; + Member<DeviceMotionEventRotationRate> rotation_rate_; double interval_; };
diff --git a/third_party/blink/renderer/modules/device_orientation/device_motion_event.cc b/third_party/blink/renderer/modules/device_orientation/device_motion_event.cc index ff7f834..136cf41 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_motion_event.cc +++ b/third_party/blink/renderer/modules/device_orientation/device_motion_event.cc
@@ -25,10 +25,10 @@ #include "third_party/blink/renderer/modules/device_orientation/device_motion_event.h" -#include "third_party/blink/renderer/modules/device_orientation/device_acceleration.h" #include "third_party/blink/renderer/modules/device_orientation/device_motion_data.h" +#include "third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration.h" #include "third_party/blink/renderer/modules/device_orientation/device_motion_event_init.h" -#include "third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h" +#include "third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate.h" namespace blink { @@ -47,15 +47,16 @@ : Event(event_type, Bubbles::kNo, Cancelable::kNo), device_motion_data_(device_motion_data) {} -DeviceAcceleration* DeviceMotionEvent::acceleration() { +DeviceMotionEventAcceleration* DeviceMotionEvent::acceleration() { return device_motion_data_->GetAcceleration(); } -DeviceAcceleration* DeviceMotionEvent::accelerationIncludingGravity() { +DeviceMotionEventAcceleration* +DeviceMotionEvent::accelerationIncludingGravity() { return device_motion_data_->GetAccelerationIncludingGravity(); } -DeviceRotationRate* DeviceMotionEvent::rotationRate() { +DeviceMotionEventRotationRate* DeviceMotionEvent::rotationRate() { return device_motion_data_->GetRotationRate(); }
diff --git a/third_party/blink/renderer/modules/device_orientation/device_motion_event.h b/third_party/blink/renderer/modules/device_orientation/device_motion_event.h index adcc872..9ef6ccd 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_motion_event.h +++ b/third_party/blink/renderer/modules/device_orientation/device_motion_event.h
@@ -31,10 +31,10 @@ namespace blink { -class DeviceAcceleration; +class DeviceMotionEventAcceleration; class DeviceMotionData; class DeviceMotionEventInit; -class DeviceRotationRate; +class DeviceMotionEventRotationRate; class DeviceMotionEvent final : public Event { DEFINE_WRAPPERTYPEINFO(); @@ -62,9 +62,9 @@ return device_motion_data_.Get(); } - DeviceAcceleration* acceleration(); - DeviceAcceleration* accelerationIncludingGravity(); - DeviceRotationRate* rotationRate(); + DeviceMotionEventAcceleration* acceleration(); + DeviceMotionEventAcceleration* accelerationIncludingGravity(); + DeviceMotionEventRotationRate* rotationRate(); double interval() const; const AtomicString& InterfaceName() const override;
diff --git a/third_party/blink/renderer/modules/device_orientation/device_motion_event.idl b/third_party/blink/renderer/modules/device_orientation/device_motion_event.idl index 234eef91..5ee0c7a 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_motion_event.idl +++ b/third_party/blink/renderer/modules/device_orientation/device_motion_event.idl
@@ -29,8 +29,8 @@ Constructor(DOMString type, optional DeviceMotionEventInit eventInitDict), Exposed=Window ] interface DeviceMotionEvent : Event { - readonly attribute DeviceAcceleration? acceleration; - readonly attribute DeviceAcceleration? accelerationIncludingGravity; - readonly attribute DeviceRotationRate? rotationRate; + readonly attribute DeviceMotionEventAcceleration? acceleration; + readonly attribute DeviceMotionEventAcceleration? accelerationIncludingGravity; + readonly attribute DeviceMotionEventRotationRate? rotationRate; readonly attribute double interval; };
diff --git a/third_party/blink/renderer/modules/device_orientation/device_acceleration.cc b/third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration.cc similarity index 64% rename from third_party/blink/renderer/modules/device_orientation/device_acceleration.cc rename to third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration.cc index 8d66a6deb6c..a72b9ac 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_acceleration.cc +++ b/third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration.cc
@@ -23,41 +23,45 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "third_party/blink/renderer/modules/device_orientation/device_acceleration.h" -#include "third_party/blink/renderer/modules/device_orientation/device_acceleration_init.h" +#include "third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration.h" +#include "third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration_init.h" namespace blink { -DeviceAcceleration* DeviceAcceleration::Create(double x, double y, double z) { - return MakeGarbageCollected<DeviceAcceleration>(x, y, z); +DeviceMotionEventAcceleration* DeviceMotionEventAcceleration::Create(double x, + double y, + double z) { + return MakeGarbageCollected<DeviceMotionEventAcceleration>(x, y, z); } -DeviceAcceleration* DeviceAcceleration::Create( - const DeviceAccelerationInit* init) { +DeviceMotionEventAcceleration* DeviceMotionEventAcceleration::Create( + const DeviceMotionEventAccelerationInit* init) { double x = init->hasX() ? init->x() : NAN; double y = init->hasY() ? init->y() : NAN; double z = init->hasZ() ? init->z() : NAN; - return DeviceAcceleration::Create(x, y, z); + return DeviceMotionEventAcceleration::Create(x, y, z); } -DeviceAcceleration::DeviceAcceleration(double x, double y, double z) +DeviceMotionEventAcceleration::DeviceMotionEventAcceleration(double x, + double y, + double z) : x_(x), y_(y), z_(z) {} -bool DeviceAcceleration::HasAccelerationData() const { +bool DeviceMotionEventAcceleration::HasAccelerationData() const { return !std::isnan(x_) || !std::isnan(y_) || !std::isnan(z_); } -double DeviceAcceleration::x(bool& is_null) const { +double DeviceMotionEventAcceleration::x(bool& is_null) const { is_null = std::isnan(x_); return x_; } -double DeviceAcceleration::y(bool& is_null) const { +double DeviceMotionEventAcceleration::y(bool& is_null) const { is_null = std::isnan(y_); return y_; } -double DeviceAcceleration::z(bool& is_null) const { +double DeviceMotionEventAcceleration::z(bool& is_null) const { is_null = std::isnan(z_); return z_; }
diff --git a/third_party/blink/renderer/modules/device_orientation/device_acceleration.h b/third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration.h similarity index 79% rename from third_party/blink/renderer/modules/device_orientation/device_acceleration.h rename to third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration.h index e24568a0..1282e28 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_acceleration.h +++ b/third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration.h
@@ -23,26 +23,26 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_DEVICE_ORIENTATION_DEVICE_ACCELERATION_H_ -#define THIRD_PARTY_BLINK_RENDERER_MODULES_DEVICE_ORIENTATION_DEVICE_ACCELERATION_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_DEVICE_ORIENTATION_DEVICE_MOTION_EVENT_ACCELERATION_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_DEVICE_ORIENTATION_DEVICE_MOTION_EVENT_ACCELERATION_H_ -#include "third_party/blink/renderer/modules/device_orientation/device_motion_data.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" -#include "third_party/blink/renderer/platform/heap/handle.h" namespace blink { -class DeviceAccelerationInit; +class DeviceMotionEventAccelerationInit; -class MODULES_EXPORT DeviceAcceleration final : public ScriptWrappable { +class MODULES_EXPORT DeviceMotionEventAcceleration final + : public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public: - static DeviceAcceleration* Create(double x, double y, double z); - static DeviceAcceleration* Create(const DeviceAccelerationInit*); + static DeviceMotionEventAcceleration* Create(double x, double y, double z); + static DeviceMotionEventAcceleration* Create( + const DeviceMotionEventAccelerationInit*); - DeviceAcceleration(double x, double y, double z); + DeviceMotionEventAcceleration(double x, double y, double z); bool HasAccelerationData() const; @@ -58,4 +58,4 @@ } // namespace blink -#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_DEVICE_ORIENTATION_DEVICE_ACCELERATION_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_DEVICE_ORIENTATION_DEVICE_MOTION_EVENT_ACCELERATION_H_
diff --git a/third_party/blink/renderer/modules/device_orientation/device_acceleration.idl b/third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration.idl similarity index 96% rename from third_party/blink/renderer/modules/device_orientation/device_acceleration.idl rename to third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration.idl index f1bc23df..a613c2e 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_acceleration.idl +++ b/third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration.idl
@@ -25,9 +25,7 @@ // https://w3c.github.io/deviceorientation/spec-source-orientation.html#devicemotion -[ - NoInterfaceObject -] interface DeviceAcceleration { +interface DeviceMotionEventAcceleration { readonly attribute double? x; readonly attribute double? y; readonly attribute double? z;
diff --git a/third_party/blink/renderer/modules/device_orientation/device_acceleration_init.idl b/third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration_init.idl similarity index 86% rename from third_party/blink/renderer/modules/device_orientation/device_acceleration_init.idl rename to third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration_init.idl index 85ece50..8836b79 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_acceleration_init.idl +++ b/third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration_init.idl
@@ -4,7 +4,7 @@ // https://w3c.github.io/deviceorientation/spec-source-orientation.html#devicemotion -dictionary DeviceAccelerationInit { +dictionary DeviceMotionEventAccelerationInit { double? x = null; double? y = null; double? z = null;
diff --git a/third_party/blink/renderer/modules/device_orientation/device_motion_event_init.idl b/third_party/blink/renderer/modules/device_orientation/device_motion_event_init.idl index 8e5e65c..87d56d1 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_motion_event_init.idl +++ b/third_party/blink/renderer/modules/device_orientation/device_motion_event_init.idl
@@ -5,8 +5,8 @@ // https://w3c.github.io/deviceorientation/spec-source-orientation.html#devicemotion dictionary DeviceMotionEventInit : EventInit { - DeviceAccelerationInit acceleration; - DeviceAccelerationInit accelerationIncludingGravity; - DeviceRotationRateInit rotationRate; + DeviceMotionEventAccelerationInit acceleration; + DeviceMotionEventAccelerationInit accelerationIncludingGravity; + DeviceMotionEventRotationRateInit rotationRate; double interval = 0; };
diff --git a/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump.cc b/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump.cc index 14f250d..8bc0654 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump.cc +++ b/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump.cc
@@ -12,9 +12,10 @@ #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/platform_event_controller.h" -#include "third_party/blink/renderer/modules/device_orientation/device_acceleration.h" #include "third_party/blink/renderer/modules/device_orientation/device_motion_data.h" -#include "third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h" +#include "third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration.h" +#include "third_party/blink/renderer/modules/device_orientation/device_motion_event_pump.h" +#include "third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate.h" #include "third_party/blink/renderer/modules/device_orientation/device_sensor_entry.h" #include "third_party/blink/renderer/platform/wtf/functional.h" #include "ui/gfx/geometry/angle_conversions.h" @@ -130,20 +131,21 @@ } DeviceMotionData* DeviceMotionEventPump::GetDataFromSharedMemory() { - DeviceAcceleration* acceleration = nullptr; - DeviceAcceleration* acceleration_including_gravity = nullptr; - DeviceRotationRate* rotation_rate = nullptr; + DeviceMotionEventAcceleration* acceleration = nullptr; + DeviceMotionEventAcceleration* acceleration_including_gravity = nullptr; + DeviceMotionEventRotationRate* rotation_rate = nullptr; device::SensorReading accelerometer_reading; if (accelerometer_->GetReading(&accelerometer_reading)) { if (accelerometer_reading.timestamp() == 0.0) return nullptr; - acceleration_including_gravity = DeviceAcceleration::Create( + acceleration_including_gravity = DeviceMotionEventAcceleration::Create( accelerometer_reading.accel.x, accelerometer_reading.accel.y, accelerometer_reading.accel.z); } else { - acceleration_including_gravity = DeviceAcceleration::Create(NAN, NAN, NAN); + acceleration_including_gravity = + DeviceMotionEventAcceleration::Create(NAN, NAN, NAN); } device::SensorReading linear_acceleration_sensor_reading; @@ -152,12 +154,12 @@ if (linear_acceleration_sensor_reading.timestamp() == 0.0) return nullptr; - acceleration = - DeviceAcceleration::Create(linear_acceleration_sensor_reading.accel.x, - linear_acceleration_sensor_reading.accel.y, - linear_acceleration_sensor_reading.accel.z); + acceleration = DeviceMotionEventAcceleration::Create( + linear_acceleration_sensor_reading.accel.x, + linear_acceleration_sensor_reading.accel.y, + linear_acceleration_sensor_reading.accel.z); } else { - acceleration = DeviceAcceleration::Create(NAN, NAN, NAN); + acceleration = DeviceMotionEventAcceleration::Create(NAN, NAN, NAN); } device::SensorReading gyroscope_reading; @@ -165,12 +167,12 @@ if (gyroscope_reading.timestamp() == 0.0) return nullptr; - rotation_rate = - DeviceRotationRate::Create(gfx::RadToDeg(gyroscope_reading.gyro.x), - gfx::RadToDeg(gyroscope_reading.gyro.y), - gfx::RadToDeg(gyroscope_reading.gyro.z)); + rotation_rate = DeviceMotionEventRotationRate::Create( + gfx::RadToDeg(gyroscope_reading.gyro.x), + gfx::RadToDeg(gyroscope_reading.gyro.y), + gfx::RadToDeg(gyroscope_reading.gyro.z)); } else { - rotation_rate = DeviceRotationRate::Create(NAN, NAN, NAN); + rotation_rate = DeviceMotionEventRotationRate::Create(NAN, NAN, NAN); } // The device orientation spec states that interval should be in
diff --git a/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump_unittest.cc b/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump_unittest.cc index c5e9835..00ea877 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump_unittest.cc +++ b/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump_unittest.cc
@@ -11,10 +11,10 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" #include "third_party/blink/renderer/core/frame/platform_event_controller.h" -#include "third_party/blink/renderer/modules/device_orientation/device_acceleration.h" #include "third_party/blink/renderer/modules/device_orientation/device_motion_data.h" +#include "third_party/blink/renderer/modules/device_orientation/device_motion_event_acceleration.h" #include "third_party/blink/renderer/modules/device_orientation/device_motion_event_pump.h" -#include "third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h" +#include "third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate.h" #include "third_party/blink/renderer/modules/device_orientation/device_sensor_entry.h" #include "third_party/blink/renderer/platform/heap/persistent.h" #include "ui/gfx/geometry/angle_conversions.h"
diff --git a/third_party/blink/renderer/modules/device_orientation/device_rotation_rate.cc b/third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate.cc similarity index 66% rename from third_party/blink/renderer/modules/device_orientation/device_rotation_rate.cc rename to third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate.cc index 4c2d754..4ce1039 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_rotation_rate.cc +++ b/third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate.cc
@@ -23,43 +23,45 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h" -#include "third_party/blink/renderer/modules/device_orientation/device_rotation_rate_init.h" +#include "third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate.h" +#include "third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate_init.h" namespace blink { -DeviceRotationRate* DeviceRotationRate::Create(double alpha, - double beta, - double gamma) { - return MakeGarbageCollected<DeviceRotationRate>(alpha, beta, gamma); +DeviceMotionEventRotationRate* +DeviceMotionEventRotationRate::Create(double alpha, double beta, double gamma) { + return MakeGarbageCollected<DeviceMotionEventRotationRate>(alpha, beta, + gamma); } -DeviceRotationRate* DeviceRotationRate::Create( - const DeviceRotationRateInit* init) { +DeviceMotionEventRotationRate* DeviceMotionEventRotationRate::Create( + const DeviceMotionEventRotationRateInit* init) { double alpha = init->hasAlpha() ? init->alpha() : NAN; double beta = init->hasBeta() ? init->beta() : NAN; double gamma = init->hasGamma() ? init->gamma() : NAN; - return DeviceRotationRate::Create(alpha, beta, gamma); + return DeviceMotionEventRotationRate::Create(alpha, beta, gamma); } -DeviceRotationRate::DeviceRotationRate(double alpha, double beta, double gamma) +DeviceMotionEventRotationRate::DeviceMotionEventRotationRate(double alpha, + double beta, + double gamma) : alpha_(alpha), beta_(beta), gamma_(gamma) {} -bool DeviceRotationRate::HasRotationData() const { +bool DeviceMotionEventRotationRate::HasRotationData() const { return !std::isnan(alpha_) || !std::isnan(beta_) || !std::isnan(gamma_); } -double DeviceRotationRate::alpha(bool& is_null) const { +double DeviceMotionEventRotationRate::alpha(bool& is_null) const { is_null = std::isnan(alpha_); return alpha_; } -double DeviceRotationRate::beta(bool& is_null) const { +double DeviceMotionEventRotationRate::beta(bool& is_null) const { is_null = std::isnan(beta_); return beta_; } -double DeviceRotationRate::gamma(bool& is_null) const { +double DeviceMotionEventRotationRate::gamma(bool& is_null) const { is_null = std::isnan(gamma_); return gamma_; }
diff --git a/third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h b/third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate.h similarity index 77% rename from third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h rename to third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate.h index 8bd90aa..2639e0c 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h +++ b/third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate.h
@@ -23,26 +23,28 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_DEVICE_ORIENTATION_DEVICE_ROTATION_RATE_H_ -#define THIRD_PARTY_BLINK_RENDERER_MODULES_DEVICE_ORIENTATION_DEVICE_ROTATION_RATE_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_DEVICE_ORIENTATION_DEVICE_MOTION_EVENT_ROTATION_RATE_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_DEVICE_ORIENTATION_DEVICE_MOTION_EVENT_ROTATION_RATE_H_ -#include "third_party/blink/renderer/modules/device_orientation/device_motion_data.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" -#include "third_party/blink/renderer/platform/heap/handle.h" namespace blink { -class DeviceRotationRateInit; +class DeviceMotionEventRotationRateInit; -class MODULES_EXPORT DeviceRotationRate final : public ScriptWrappable { +class MODULES_EXPORT DeviceMotionEventRotationRate final + : public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public: - static DeviceRotationRate* Create(double alpha, double beta, double gamma); - static DeviceRotationRate* Create(const DeviceRotationRateInit*); + static DeviceMotionEventRotationRate* Create(double alpha, + double beta, + double gamma); + static DeviceMotionEventRotationRate* Create( + const DeviceMotionEventRotationRateInit*); - DeviceRotationRate(double alpha, double beta, double gamma); + DeviceMotionEventRotationRate(double alpha, double beta, double gamma); bool HasRotationData() const; @@ -58,4 +60,4 @@ } // namespace blink -#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_DEVICE_ORIENTATION_DEVICE_ROTATION_RATE_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_DEVICE_ORIENTATION_DEVICE_MOTION_EVENT_ROTATION_RATE_H_
diff --git a/third_party/blink/renderer/modules/device_orientation/device_rotation_rate.idl b/third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate.idl similarity index 96% rename from third_party/blink/renderer/modules/device_orientation/device_rotation_rate.idl rename to third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate.idl index 78ea0b62..1d0890a 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_rotation_rate.idl +++ b/third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate.idl
@@ -25,9 +25,7 @@ // https://w3c.github.io/deviceorientation/spec-source-orientation.html#devicemotion -[ - NoInterfaceObject -] interface DeviceRotationRate { +interface DeviceMotionEventRotationRate { readonly attribute double? alpha; readonly attribute double? beta; readonly attribute double? gamma;
diff --git a/third_party/blink/renderer/modules/device_orientation/device_rotation_rate_init.idl b/third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate_init.idl similarity index 87% rename from third_party/blink/renderer/modules/device_orientation/device_rotation_rate_init.idl rename to third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate_init.idl index e08ef7e9..16f5a93 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_rotation_rate_init.idl +++ b/third_party/blink/renderer/modules/device_orientation/device_motion_event_rotation_rate_init.idl
@@ -4,7 +4,7 @@ // https://w3c.github.io/deviceorientation/spec-source-orientation.html#deviceorientation -dictionary DeviceRotationRateInit { +dictionary DeviceMotionEventRotationRateInit { double? alpha = null; double? beta = null; double? gamma = null;
diff --git a/third_party/blink/renderer/modules/modules_idl_files.gni b/third_party/blink/renderer/modules/modules_idl_files.gni index 9b6ff8f..73045f9 100644 --- a/third_party/blink/renderer/modules/modules_idl_files.gni +++ b/third_party/blink/renderer/modules/modules_idl_files.gni
@@ -114,10 +114,10 @@ "csspaint/paint_rendering_context_2d.idl", "csspaint/paint_size.idl", "csspaint/paint_worklet_global_scope.idl", - "device_orientation/device_acceleration.idl", "device_orientation/device_motion_event.idl", + "device_orientation/device_motion_event_acceleration.idl", + "device_orientation/device_motion_event_rotation_rate.idl", "device_orientation/device_orientation_event.idl", - "device_orientation/device_rotation_rate.idl", "encoding/text_decoder.idl", "encoding/text_decoder_stream.idl", "encoding/text_encoder.idl", @@ -536,10 +536,10 @@ "credentialmanager/public_key_credential_rp_entity.idl", "credentialmanager/public_key_credential_user_entity.idl", "csspaint/paint_rendering_context_2d_settings.idl", - "device_orientation/device_acceleration_init.idl", + "device_orientation/device_motion_event_acceleration_init.idl", "device_orientation/device_motion_event_init.idl", + "device_orientation/device_motion_event_rotation_rate_init.idl", "device_orientation/device_orientation_event_init.idl", - "device_orientation/device_rotation_rate_init.idl", "encoding/text_decode_options.idl", "encoding/text_decoder_options.idl", "encoding/text_encoder_encode_into_result.idl",
diff --git a/third_party/blink/renderer/modules/webaudio/base_audio_context.cc b/third_party/blink/renderer/modules/webaudio/base_audio_context.cc index f2e8e91b..6f9a2593c 100644 --- a/third_party/blink/renderer/modules/webaudio/base_audio_context.cc +++ b/third_party/blink/renderer/modules/webaudio/base_audio_context.cc
@@ -75,6 +75,8 @@ #include "third_party/blink/renderer/platform/uuid.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" +#include <algorithm> + namespace blink { BaseAudioContext* BaseAudioContext::Create( @@ -171,7 +173,6 @@ DCHECK(!is_resolving_resume_promises_); DCHECK_EQ(resume_resolvers_.size(), 0u); - DCHECK_EQ(active_source_nodes_.size(), 0u); } void BaseAudioContext::ContextLifecycleStateChanged( @@ -655,16 +656,17 @@ DCHECK(IsMainThread()); GraphAutoLocker locker(this); - active_source_nodes_.push_back(node); + GetDeferredTaskHandler().GetActiveSourceHandlers()->push_back( + &node->Handler()); node->Handler().MakeConnection(); } void BaseAudioContext::ReleaseActiveSourceNodes() { DCHECK(IsMainThread()); - for (auto& source_node : active_source_nodes_) - source_node->Handler().BreakConnection(); - - active_source_nodes_.clear(); + for (auto source_handler : + *GetDeferredTaskHandler().GetActiveSourceHandlers()) { + source_handler->BreakConnection(); + } } void BaseAudioContext::HandleStoppableSourceNodes() { @@ -694,14 +696,15 @@ is_resolving_resume_promises_ = false; } - if (active_source_nodes_.size()) { + Vector<scoped_refptr<AudioHandler>>* active_source_handlers = + GetDeferredTaskHandler().GetActiveSourceHandlers(); + if (active_source_handlers->size()) { // Find AudioBufferSourceNodes to see if we can stop playing them. - for (AudioNode* node : active_source_nodes_) { - if (node->Handler().GetNodeType() == - AudioHandler::kNodeTypeAudioBufferSource) { - AudioBufferSourceNode* source_node = - static_cast<AudioBufferSourceNode*>(node); - source_node->GetAudioBufferSourceHandler().HandleStoppableSourceNode(); + for (auto handler : *active_source_handlers) { + if (handler->GetNodeType() == AudioHandler::kNodeTypeAudioBufferSource) { + AudioBufferSourceHandler* source_handler = + static_cast<AudioBufferSourceHandler*>(handler.get()); + source_handler->HandleStoppableSourceNode(); } } @@ -714,10 +717,10 @@ // playing. wtf_size_t remove_count = 0; Vector<bool> removables; - removables.resize(active_source_nodes_.size()); + removables.resize(active_source_handlers->size()); for (AudioHandler* handler : finished_handlers) { - for (wtf_size_t i = 0; i < active_source_nodes_.size(); ++i) { - if (handler == &active_source_nodes_[i]->Handler()) { + for (wtf_size_t i = 0; i < active_source_handlers->size(); ++i) { + if (handler == active_source_handlers->at(i).get()) { handler->BreakConnectionWithLock(); removables[i] = true; remove_count++; @@ -728,17 +731,18 @@ // Copy over the surviving active nodes after removal. if (remove_count > 0) { - HeapVector<Member<AudioNode>> actives; - DCHECK_GE(active_source_nodes_.size(), remove_count); + Vector<scoped_refptr<AudioHandler>> actives; + DCHECK_GE(active_source_handlers->size(), remove_count); wtf_size_t initial_capacity = - std::min(active_source_nodes_.size() - remove_count, - active_source_nodes_.size()); + std::min(active_source_handlers->size() - remove_count, + active_source_handlers->size()); actives.ReserveInitialCapacity(initial_capacity); for (wtf_size_t i = 0; i < removables.size(); ++i) { - if (!removables[i]) - actives.push_back(active_source_nodes_[i]); + if (!removables[i]) { + actives.push_back(active_source_handlers->at(i)); + } } - active_source_nodes_.swap(actives); + active_source_handlers->swap(actives); } } @@ -803,7 +807,6 @@ void BaseAudioContext::Trace(blink::Visitor* visitor) { visitor->Trace(destination_node_); visitor->Trace(listener_); - visitor->Trace(active_source_nodes_); visitor->Trace(resume_resolvers_); visitor->Trace(decode_audio_resolvers_); visitor->Trace(periodic_wave_sine_);
diff --git a/third_party/blink/renderer/modules/webaudio/base_audio_context.h b/third_party/blink/renderer/modules/webaudio/base_audio_context.h index ce9434b..a89d104 100644 --- a/third_party/blink/renderer/modules/webaudio/base_audio_context.h +++ b/third_party/blink/renderer/modules/webaudio/base_audio_context.h
@@ -387,14 +387,6 @@ Mutex finished_source_handlers_mutex_; Vector<AudioHandler*> finished_source_handlers_; - // List of source nodes. This is either accessed when the graph lock is - // held, or on the main thread when the audio thread has finished. - // Oilpan: This Vector holds connection references. We must call - // AudioHandler::makeConnection when we add an AudioNode to this, and must - // call AudioHandler::breakConnection() when we remove an AudioNode from - // this. - HeapVector<Member<AudioNode>> active_source_nodes_; - // When the context is going away, reject any pending script promise // resolvers. virtual void RejectPendingResolvers();
diff --git a/third_party/blink/renderer/modules/webaudio/deferred_task_handler.cc b/third_party/blink/renderer/modules/webaudio/deferred_task_handler.cc index 9b89eb8a..3d82441 100644 --- a/third_party/blink/renderer/modules/webaudio/deferred_task_handler.cc +++ b/third_party/blink/renderer/modules/webaudio/deferred_task_handler.cc
@@ -346,6 +346,7 @@ deletable_orphan_handlers_.clear(); automatic_pull_handlers_.clear(); rendering_automatic_pull_handlers_.clear(); + active_source_handlers_.clear(); } void DeferredTaskHandler::SetAudioThreadToCurrentThread() {
diff --git a/third_party/blink/renderer/modules/webaudio/deferred_task_handler.h b/third_party/blink/renderer/modules/webaudio/deferred_task_handler.h index fdd3f19..1ca7588b 100644 --- a/third_party/blink/renderer/modules/webaudio/deferred_task_handler.h +++ b/third_party/blink/renderer/modules/webaudio/deferred_task_handler.h
@@ -185,6 +185,10 @@ DeferredTaskHandler& handler_; }; + Vector<scoped_refptr<AudioHandler>>* GetActiveSourceHandlers() { + return &active_source_handlers_; + } + private: explicit DeferredTaskHandler(scoped_refptr<base::SingleThreadTaskRunner>); void UpdateAutomaticPullNodes(); @@ -239,6 +243,13 @@ // accepted. bool accepts_tail_processing_ = true; + // When source nodes are started, we place the handlers here to keep track of + // these active sources. This Vector holds connection references. We must + // call AudioHandler::makeConnection when we add an AudioNode to this, and + // must call AudioHandler::breakConnection() when we remove an AudioNode from + // this. + Vector<scoped_refptr<AudioHandler>> active_source_handlers_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; // Graph locking.
diff --git a/third_party/blink/renderer/platform/geometry/length.cc b/third_party/blink/renderer/platform/geometry/length.cc index daa3501f..bb079d9d 100644 --- a/third_party/blink/renderer/platform/geometry/length.cc +++ b/third_party/blink/renderer/platform/geometry/length.cc
@@ -109,7 +109,7 @@ Length Length::BlendSameTypes(const Length& from, double progress, ValueRange range) const { - LengthType result_type = GetType(); + Length::Type result_type = GetType(); if (IsZero()) result_type = from.GetType();
diff --git a/third_party/blink/renderer/platform/geometry/length.h b/third_party/blink/renderer/platform/geometry/length.h index 0ed49fed..78aaea0 100644 --- a/third_party/blink/renderer/platform/geometry/length.h +++ b/third_party/blink/renderer/platform/geometry/length.h
@@ -29,23 +29,6 @@ namespace blink { -// FIXME: This enum makes it hard to tell in general what values may be -// appropriate for any given Length. -enum LengthType { - kAuto, - kPercent, - kFixed, - kMinContent, - kMaxContent, - kFillAvailable, - kFitContent, - kCalculated, - kExtendToZoom, - kDeviceWidth, - kDeviceHeight, - kMaxSizeNone -}; - enum ValueRange { kValueRangeAll, kValueRangeNonNegative }; struct PixelsAndPercent { @@ -62,29 +45,46 @@ DISALLOW_NEW(); public: + // FIXME: This enum makes it hard to tell in general what values may be + // appropriate for any given Length. + enum Type : unsigned char { + kAuto, + kPercent, + kFixed, + kMinContent, + kMaxContent, + kFillAvailable, + kFitContent, + kCalculated, + kExtendToZoom, + kDeviceWidth, + kDeviceHeight, + kMaxSizeNone + }; + Length() : int_value_(0), quirk_(false), type_(kAuto), is_float_(false) {} - explicit Length(LengthType t) + explicit Length(Length::Type t) : int_value_(0), quirk_(false), type_(t), is_float_(false) { DCHECK_NE(t, kCalculated); } - Length(int v, LengthType t, bool q = false) + Length(int v, Length::Type t, bool q = false) : int_value_(v), quirk_(q), type_(t), is_float_(false) { DCHECK_NE(t, kCalculated); } - Length(LayoutUnit v, LengthType t, bool q = false) + Length(LayoutUnit v, Length::Type t, bool q = false) : float_value_(v.ToFloat()), quirk_(q), type_(t), is_float_(true) { DCHECK_NE(t, kCalculated); } - Length(float v, LengthType t, bool q = false) + Length(float v, Length::Type t, bool q = false) : float_value_(v), quirk_(q), type_(t), is_float_(true) { DCHECK_NE(t, kCalculated); } - Length(double v, LengthType t, bool q = false) + Length(double v, Length::Type t, bool q = false) : quirk_(q), type_(t), is_float_(true) { float_value_ = static_cast<float>(v); } @@ -180,7 +180,7 @@ CalculationValue& GetCalculationValue() const; - LengthType GetType() const { return static_cast<LengthType>(type_); } + Length::Type GetType() const { return static_cast<Length::Type>(type_); } bool Quirk() const { return quirk_; } void SetQuirk(bool quirk) { quirk_ = quirk; }
diff --git a/third_party/blink/renderer/platform/geometry/length_box.h b/third_party/blink/renderer/platform/geometry/length_box.h index b526a0aa..db836550 100644 --- a/third_party/blink/renderer/platform/geometry/length_box.h +++ b/third_party/blink/renderer/platform/geometry/length_box.h
@@ -34,7 +34,7 @@ public: LengthBox() = default; - LengthBox(LengthType t) : left_(t), right_(t), top_(t), bottom_(t) {} + LengthBox(Length::Type t) : left_(t), right_(t), top_(t), bottom_(t) {} LengthBox(int v) : left_(Length::Fixed(v)),
diff --git a/third_party/blink/renderer/platform/geometry/length_functions.cc b/third_party/blink/renderer/platform/geometry/length_functions.cc index 788a86a..ce385e4 100644 --- a/third_party/blink/renderer/platform/geometry/length_functions.cc +++ b/third_party/blink/renderer/platform/geometry/length_functions.cc
@@ -37,22 +37,22 @@ float FloatValueForLength(const Length& length, float maximum_value) { switch (length.GetType()) { - case kFixed: + case Length::kFixed: return length.GetFloatValue(); - case kPercent: + case Length::kPercent: return static_cast<float>(maximum_value * length.Percent() / 100.0f); - case kFillAvailable: - case kAuto: + case Length::kFillAvailable: + case Length::kAuto: return static_cast<float>(maximum_value); - case kCalculated: + case Length::kCalculated: return length.NonNanCalculatedValue(LayoutUnit(maximum_value)); - case kMinContent: - case kMaxContent: - case kFitContent: - case kExtendToZoom: - case kDeviceWidth: - case kDeviceHeight: - case kMaxSizeNone: + case Length::kMinContent: + case Length::kMaxContent: + case Length::kFitContent: + case Length::kExtendToZoom: + case Length::kDeviceWidth: + case Length::kDeviceHeight: + case Length::kMaxSizeNone: NOTREACHED(); return 0; } @@ -63,25 +63,25 @@ LayoutUnit MinimumValueForLength(const Length& length, LayoutUnit maximum_value) { switch (length.GetType()) { - case kFixed: + case Length::kFixed: return LayoutUnit(length.Value()); - case kPercent: + case Length::kPercent: // Don't remove the extra cast to float. It is needed for rounding on // 32-bit Intel machines that use the FPU stack. return LayoutUnit( static_cast<float>(maximum_value * length.Percent() / 100.0f)); - case kCalculated: + case Length::kCalculated: return LayoutUnit(length.NonNanCalculatedValue(maximum_value)); - case kFillAvailable: - case kAuto: + case Length::kFillAvailable: + case Length::kAuto: return LayoutUnit(); - case kMinContent: - case kMaxContent: - case kFitContent: - case kExtendToZoom: - case kDeviceWidth: - case kDeviceHeight: - case kMaxSizeNone: + case Length::kMinContent: + case Length::kMaxContent: + case Length::kFitContent: + case Length::kExtendToZoom: + case Length::kDeviceWidth: + case Length::kDeviceHeight: + case Length::kMaxSizeNone: NOTREACHED(); return LayoutUnit(); } @@ -91,20 +91,20 @@ LayoutUnit ValueForLength(const Length& length, LayoutUnit maximum_value) { switch (length.GetType()) { - case kFixed: - case kPercent: - case kCalculated: + case Length::kFixed: + case Length::kPercent: + case Length::kCalculated: return MinimumValueForLength(length, maximum_value); - case kFillAvailable: - case kAuto: + case Length::kFillAvailable: + case Length::kAuto: return maximum_value; - case kMinContent: - case kMaxContent: - case kFitContent: - case kExtendToZoom: - case kDeviceWidth: - case kDeviceHeight: - case kMaxSizeNone: + case Length::kMinContent: + case Length::kMaxContent: + case Length::kFitContent: + case Length::kExtendToZoom: + case Length::kDeviceWidth: + case Length::kDeviceHeight: + case Length::kMaxSizeNone: NOTREACHED(); return LayoutUnit(); }
diff --git a/third_party/blink/renderer/platform/heap/heap_test.cc b/third_party/blink/renderer/platform/heap/heap_test.cc index 2ab06dda..20aafb1 100644 --- a/third_party/blink/renderer/platform/heap/heap_test.cc +++ b/third_party/blink/renderer/platform/heap/heap_test.cc
@@ -5834,9 +5834,12 @@ kGrowsTowardsLower, }; -NOINLINE NO_SANITIZE_ADDRESS GrowthDirection StackGrowthDirection() { +NOINLINE NO_SANITIZE_ADDRESS NO_SANITIZE_HWADDRESS GrowthDirection +StackGrowthDirection() { // Disable ASan, otherwise its stack checking (use-after-return) will - // confuse the direction check. + // confuse the direction check. Similarly, HWASan will store a random value in + // the top byte of the address of each stack variable, causing the direction + // check to return the wrong answer half of the time. static char* previous = nullptr; char dummy; if (!previous) {
diff --git a/third_party/blink/renderer/platform/heap/thread_state.cc b/third_party/blink/renderer/platform/heap/thread_state.cc index 1c1c5ba..becf1ca 100644 --- a/third_party/blink/renderer/platform/heap/thread_state.cc +++ b/third_party/blink/renderer/platform/heap/thread_state.cc
@@ -315,6 +315,7 @@ // Stack scanning may overrun the bounds of local objects and/or race with // other threads that use this stack. NO_SANITIZE_ADDRESS +NO_SANITIZE_HWADDRESS NO_SANITIZE_THREAD void ThreadState::VisitStack(MarkingVisitor* visitor) { DCHECK_EQ(current_gc_data_.stack_state, BlinkGC::kHeapPointersOnStack);
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index e1ff8729..0798bb1 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -1295,11 +1295,6 @@ name: "SmoothScrollJSIntervention", status: "stable", }, - // When this is enabled (and Spatial Navigation is enabled), overrides of box shadow and outline - // on focused elements will be ignored. - { - name: "SpatialNavigationForcesOutline", - }, // Used as argument in attribute of stable-release functions/interfaces // where a runtime-enabled feature name is required for correct IDL syntax. // This is a global flag; do not change its status.
diff --git a/third_party/blink/renderer/platform/scheduler/BUILD.gn b/third_party/blink/renderer/platform/scheduler/BUILD.gn index 9f9ed92..e5f6a09e 100644 --- a/third_party/blink/renderer/platform/scheduler/BUILD.gn +++ b/third_party/blink/renderer/platform/scheduler/BUILD.gn
@@ -80,6 +80,8 @@ "main_thread/main_thread_scheduler_impl.h", "main_thread/main_thread_task_queue.cc", "main_thread/main_thread_task_queue.h", + "main_thread/memory_purge_manager.cc", + "main_thread/memory_purge_manager.h", "main_thread/page_scheduler_impl.cc", "main_thread/page_scheduler_impl.h", "main_thread/page_visibility_state.cc", @@ -199,6 +201,7 @@ "main_thread/main_thread_metrics_helper_unittest.cc", "main_thread/main_thread_scheduler_impl_unittest.cc", "main_thread/main_thread_unittest.cc", + "main_thread/memory_purge_manager_unittest.cc", "main_thread/page_scheduler_impl_unittest.cc", "main_thread/pending_user_input_unittest.cc", "main_thread/queueing_time_estimator_unittest.cc",
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc index 34148a3..1aa060f 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc
@@ -926,6 +926,7 @@ } ParkableStringManager::Instance().SetRendererBackgrounded(backgrounded); + memory_purge_manager_.SetRendererBackgrounded(backgrounded); } void MainThreadSchedulerImpl::SetSchedulerKeepActive(bool keep_active) { @@ -2270,6 +2271,14 @@ main_thread_only().page_schedulers.erase(page_scheduler); } +void MainThreadSchedulerImpl::OnPageFrozen() { + memory_purge_manager_.PageFrozen(); +} + +void MainThreadSchedulerImpl::OnPageUnfrozen() { + memory_purge_manager_.PageUnfrozen(); +} + void MainThreadSchedulerImpl::BroadcastIntervention( const std::string& message) { helper_.CheckOnValidThread();
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h index 7540bb6..758d738 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h +++ b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h
@@ -37,6 +37,7 @@ #include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.h" #include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_helper.h" #include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.h" +#include "third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager.h" #include "third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.h" #include "third_party/blink/renderer/platform/scheduler/main_thread/pending_user_input.h" #include "third_party/blink/renderer/platform/scheduler/main_thread/prioritize_compositing_after_input_experiment.h" @@ -305,6 +306,10 @@ void AddPageScheduler(PageSchedulerImpl*); void RemovePageScheduler(PageSchedulerImpl*); + // Called by an associated PageScheduler when frozen or unfrozen. + void OnPageFrozen(); + void OnPageUnfrozen(); + void AddTaskTimeObserver(base::sequence_manager::TaskTimeObserver*); void RemoveTaskTimeObserver(base::sequence_manager::TaskTimeObserver*); @@ -748,6 +753,7 @@ IdleMemoryReclaimer idle_memory_reclaimer_; std::unique_ptr<TaskQueueThrottler> task_queue_throttler_; RenderWidgetSignals render_widget_scheduler_signals_; + MemoryPurgeManager memory_purge_manager_; const scoped_refptr<MainThreadTaskQueue> control_task_queue_; const scoped_refptr<MainThreadTaskQueue> compositor_task_queue_;
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager.cc b/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager.cc new file mode 100644 index 0000000..0caf9b7d --- /dev/null +++ b/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager.cc
@@ -0,0 +1,40 @@ +// 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/platform/scheduler/main_thread/memory_purge_manager.h" + +#include "base/memory/memory_pressure_listener.h" +#include "third_party/blink/public/common/features.h" +#include "third_party/blink/public/common/page/launching_process_state.h" + +namespace blink { + +MemoryPurgeManager::MemoryPurgeManager() + : renderer_backgrounded_(kLaunchingProcessIsBackgrounded) {} + +MemoryPurgeManager::~MemoryPurgeManager() = default; + +void MemoryPurgeManager::PageFrozen() { + if (!CanPurge()) + return; + base::MemoryPressureListener::NotifyMemoryPressure( + base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL); + base::MemoryPressureListener::SetNotificationsSuppressed(true); +} + +void MemoryPurgeManager::PageUnfrozen() { + base::MemoryPressureListener::SetNotificationsSuppressed(false); +} + +void MemoryPurgeManager::SetRendererBackgrounded(bool backgrounded) { + renderer_backgrounded_ = backgrounded; +} + +bool MemoryPurgeManager::CanPurge() { + return !base::FeatureList::IsEnabled( + features::kPurgeMemoryOnlyForBackgroundedProcesses) || + renderer_backgrounded_; +} + +} // namespace blink
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager.h b/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager.h new file mode 100644 index 0000000..fa0a8fd --- /dev/null +++ b/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager.h
@@ -0,0 +1,41 @@ +// 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_PLATFORM_SCHEDULER_MAIN_THREAD_MEMORY_PURGE_MANAGER_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_MAIN_THREAD_MEMORY_PURGE_MANAGER_H_ + +#include "base/macros.h" +#include "third_party/blink/renderer/platform/platform_export.h" + +namespace blink { + +// Manages the process-wide memory purging associated with freezing. +class PLATFORM_EXPORT MemoryPurgeManager { + public: + MemoryPurgeManager(); + ~MemoryPurgeManager(); + + // Called when a page is frozen. Simulates a critical memory pressure signal + // to purge memory. If the kPurgeMemoryOnlyForBackgroundedProcesses feature + // is enabled and the renderer is foregrounded, no signal will be sent. + void PageFrozen(); + + // Called when a page is unfrozen. Has the effect of unsuppressing memory + // pressure notifications. + void PageUnfrozen(); + + // Called when the renderer's process priority changes. + void SetRendererBackgrounded(bool backgrounded); + + private: + bool CanPurge(); + + bool renderer_backgrounded_; + + DISALLOW_COPY_AND_ASSIGN(MemoryPurgeManager); +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_MAIN_THREAD_MEMORY_PURGE_MANAGER_H_
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager_unittest.cc b/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager_unittest.cc new file mode 100644 index 0000000..853514d8 --- /dev/null +++ b/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager_unittest.cc
@@ -0,0 +1,126 @@ +// 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/platform/scheduler/main_thread/memory_purge_manager.h" + +#include "base/memory/memory_pressure_listener.h" +#include "base/run_loop.h" +#include "base/test/scoped_feature_list.h" +#include "base/test/scoped_task_environment.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/features.h" + +namespace blink { + +class MemoryPurgeManagerTest : public testing::Test { + public: + MemoryPurgeManagerTest() = default; + + void SetUp() override { + memory_pressure_listener_ = + std::make_unique<base::MemoryPressureListener>(base::BindRepeating( + &MemoryPurgeManagerTest::OnMemoryPressure, base::Unretained(this))); + base::MemoryPressureListener::SetNotificationsSuppressed(false); + } + + void TearDown() override { memory_pressure_listener_.reset(); } + + protected: + void ExpectMemoryPressure( + base::MemoryPressureListener::MemoryPressureLevel level) { + EXPECT_CALL(*this, OnMemoryPressure(level)).Times(1); + base::RunLoop().RunUntilIdle(); + } + + void ExpectNoMemoryPressure() { + EXPECT_CALL(*this, OnMemoryPressure(testing::_)).Times(0); + base::RunLoop().RunUntilIdle(); + } + + base::test::ScopedTaskEnvironment scoped_task_environment_; + std::unique_ptr<base::MemoryPressureListener> memory_pressure_listener_; + + MemoryPurgeManager memory_purge_manager_; + + private: + MOCK_METHOD1(OnMemoryPressure, + void(base::MemoryPressureListener::MemoryPressureLevel)); + DISALLOW_COPY_AND_ASSIGN(MemoryPurgeManagerTest); +}; + +// Verify that PageFrozen() triggers a memory pressure notification +// in a backgrounded renderer when the kPurgeMemoryOnlyForBackgroundedProcesses +// feature is disabled. +TEST_F(MemoryPurgeManagerTest, PageFrozenBackgrounded) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures( + {} /* enabled */, + {features::kPurgeMemoryOnlyForBackgroundedProcesses} /* disabled */); + + memory_purge_manager_.SetRendererBackgrounded(true); + memory_purge_manager_.PageFrozen(); + ExpectMemoryPressure(base::MemoryPressureListener::MemoryPressureLevel:: + MEMORY_PRESSURE_LEVEL_CRITICAL); + EXPECT_TRUE(base::MemoryPressureListener::AreNotificationsSuppressed()); +} + +// Verify that PageFrozen() triggers a memory pressure notification +// in a foregrounded renderer when the kPurgeMemoryOnlyForBackgroundedProcesses +// feature is disabled. +TEST_F(MemoryPurgeManagerTest, PageFrozenForegrounded) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures( + {} /* enabled */, + {features::kPurgeMemoryOnlyForBackgroundedProcesses} /* disabled */); + + memory_purge_manager_.SetRendererBackgrounded(false); + memory_purge_manager_.PageFrozen(); + ExpectMemoryPressure(base::MemoryPressureListener::MemoryPressureLevel:: + MEMORY_PRESSURE_LEVEL_CRITICAL); + EXPECT_TRUE(base::MemoryPressureListener::AreNotificationsSuppressed()); +} + +// Verify that PageFrozen() triggers a memory pressure notification +// in a backgrounded renderer when the kPurgeMemoryOnlyForBackgroundedProcesses +// feature is enabled. +TEST_F(MemoryPurgeManagerTest, + PageFrozenBackgroundedPreventForegroundedRenderer) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures( + {features::kPurgeMemoryOnlyForBackgroundedProcesses} /* enabled */, + {} /* disabled */); + + memory_purge_manager_.SetRendererBackgrounded(true); + memory_purge_manager_.PageFrozen(); + ExpectMemoryPressure(base::MemoryPressureListener::MemoryPressureLevel:: + MEMORY_PRESSURE_LEVEL_CRITICAL); + EXPECT_TRUE(base::MemoryPressureListener::AreNotificationsSuppressed()); +} + +// Verify that PageFrozen() does not trigger a memory pressure +// notification in a foregrounded renderer when the +// kPurgeMemoryOnlyForBackgroundedProcesses feature is enabled. +TEST_F(MemoryPurgeManagerTest, + PageFrozenForegroundedPreventForegroundedRenderer) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures( + {features::kPurgeMemoryOnlyForBackgroundedProcesses} /* enabled */, + {} /* disabled */); + + memory_purge_manager_.SetRendererBackgrounded(false); + memory_purge_manager_.PageFrozen(); + ExpectNoMemoryPressure(); + EXPECT_FALSE(base::MemoryPressureListener::AreNotificationsSuppressed()); +} + +TEST_F(MemoryPurgeManagerTest, PageUnfrozenUndoMemoryPressureSuppression) { + memory_purge_manager_.SetRendererBackgrounded(true); + memory_purge_manager_.PageFrozen(); + EXPECT_TRUE(base::MemoryPressureListener::AreNotificationsSuppressed()); + memory_purge_manager_.PageUnfrozen(); + EXPECT_FALSE(base::MemoryPressureListener::AreNotificationsSuppressed()); +} + +} // namespace blink
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 cc2ef10..7ddb029 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
@@ -238,7 +238,7 @@ if (frozen) { page_lifecycle_state_tracker_->SetPageLifecycleState( PageLifecycleState::kFrozen); - Platform::Current()->RequestPurgeMemory(); + main_thread_scheduler_->OnPageFrozen(); } else { // The new state may have already been set if unfreezing through the // renderer, but that's okay - duplicate state changes won't be recorded. @@ -252,7 +252,7 @@ page_lifecycle_state_tracker_->SetPageLifecycleState( PageLifecycleState::kHiddenForegrounded); } - Platform::Current()->SetMemoryPressureNotificationsSuppressed(false); + main_thread_scheduler_->OnPageUnfrozen(); } }
diff --git a/third_party/blink/renderer/platform/wtf/address_sanitizer.h b/third_party/blink/renderer/platform/wtf/address_sanitizer.h index b8a7b02e..9c816e7 100644 --- a/third_party/blink/renderer/platform/wtf/address_sanitizer.h +++ b/third_party/blink/renderer/platform/wtf/address_sanitizer.h
@@ -37,4 +37,10 @@ #define NO_SANITIZE_THREAD #endif +#if defined(__clang__) +#define NO_SANITIZE_HWADDRESS __attribute__((no_sanitize("hwaddress"))) +#else +#define NO_SANITIZE_HWADDRESS +#endif + #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_ADDRESS_SANITIZER_H_
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 e7c2beb8..e6375a5 100644 --- a/third_party/blink/web_tests/FlagExpectations/enable-blink-features=LayoutNG +++ b/third_party/blink/web_tests/FlagExpectations/enable-blink-features=LayoutNG
@@ -111,7 +111,7 @@ crbug.com/591099 external/wpt/bluetooth/server/disconnect/gc-detach.https.html [ Pass ] crbug.com/591099 external/wpt/bluetooth/server/getPrimaryService/gen-discovery-complete-no-permission-absent-service.https.html [ Pass ] crbug.com/591099 external/wpt/bluetooth/server/getPrimaryService/gen-discovery-complete-service-not-found.https.html [ Pass ] -crbug.com/591099 external/wpt/bluetooth/server/getPrimaryService/two-iframes-from-same-origin.https.html [ Pass ] +crbug.com/591099 external/wpt/bluetooth/server/getPrimaryService/two-iframes-from-same-origin.https.html [ Crash Pass ] crbug.com/591099 external/wpt/bluetooth/server/getPrimaryServices/gen-discovery-complete-no-permission-absent-service-with-uuid.https.html [ Pass ] crbug.com/591099 external/wpt/bluetooth/server/getPrimaryServices/gen-discovery-complete-service-not-found-with-uuid.https.html [ Pass ] crbug.com/591099 external/wpt/bluetooth/service/getCharacteristic/gen-reconnect-during.https.html [ Pass ] @@ -132,7 +132,7 @@ crbug.com/591099 external/wpt/css/CSS2/normal-flow/block-in-inline-remove-006.xht [ Pass ] crbug.com/591099 external/wpt/css/CSS2/text/white-space-mixed-003.xht [ Pass ] crbug.com/591099 external/wpt/css/css-animations/Element-getAnimations-dynamic-changes.tentative.html [ Failure ] -crbug.com/591099 external/wpt/css/css-animations/Element-getAnimations.tentative.html [ Pass ] +crbug.com/591099 external/wpt/css/css-animations/Element-getAnimations.tentative.html [ Failure Pass ] crbug.com/591099 external/wpt/css/css-contain/contain-size-grid-002.html [ Failure ] crbug.com/591099 external/wpt/css/css-contain/contain-size-multicol-001.html [ Failure ] crbug.com/591099 external/wpt/css/css-contain/contain-style-counters-004.html [ Failure ] @@ -148,7 +148,6 @@ crbug.com/591099 external/wpt/css/css-masking/clip-path/clip-path-ellipse-007.html [ Failure ] crbug.com/591099 external/wpt/css/css-masking/clip-path/clip-path-polygon-010.html [ Failure ] crbug.com/591099 external/wpt/css/css-multicol/multicol-span-all-005.html [ Failure ] -crbug.com/921396 external/wpt/css/css-position/position-absolute-container-dynamic.html [ Failure ] crbug.com/591099 external/wpt/css/css-position/position-relative-table-tbody-top-absolute-child.html [ Failure ] crbug.com/591099 external/wpt/css/css-position/position-relative-table-tr-left-absolute-child.html [ Failure ] crbug.com/591099 external/wpt/css/css-position/static-position/htb-ltr-rtl.tentative.html [ Pass ] @@ -333,7 +332,7 @@ crbug.com/591099 external/wpt/dom/events/EventListener-addEventListener.sub.window.html [ Pass ] crbug.com/591099 external/wpt/dom/ranges/Range-insertNode.html [ Pass ] crbug.com/591099 external/wpt/encoding/legacy-mb-korean/euc-kr/euckr-decode-ksc_5601.html [ Pass ] -crbug.com/591099 external/wpt/event-timing/event-timing-bufferbeforeonload.html [ Pass ] +crbug.com/591099 external/wpt/event-timing/event-timing-bufferbeforeonload.html [ Pass Timeout ] crbug.com/591099 external/wpt/fetch/api/abort/general.any.html [ Pass ] crbug.com/591099 external/wpt/fetch/api/cors/cors-redirect-preflight.any.html [ Pass ] crbug.com/591099 external/wpt/fetch/api/redirect/redirect-count.any.html [ Pass ] @@ -344,7 +343,7 @@ crbug.com/591099 external/wpt/fetch/http-cache/cc-request.html [ Pass ] crbug.com/591099 external/wpt/fullscreen/api/element-ready-check-containing-iframe-manual.html [ Pass ] crbug.com/591099 external/wpt/fullscreen/api/element-request-fullscreen-and-remove-manual.html [ Failure Pass ] -crbug.com/591099 external/wpt/geolocation-API/PositionOptions.https.html [ Failure ] +crbug.com/591099 external/wpt/geolocation-API/PositionOptions.https.html [ Failure Pass ] 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 ] @@ -420,26 +419,23 @@ crbug.com/591099 fast/css-grid-layout/grid-baseline.html [ Failure ] crbug.com/591099 fast/css-intrinsic-dimensions/height-css-tables-collapsed.html [ Failure Pass ] crbug.com/591099 fast/css-intrinsic-dimensions/height-positioned.html [ Pass ] -crbug.com/591099 fast/css-intrinsic-dimensions/height-tables.html [ Pass ] +crbug.com/591099 fast/css-intrinsic-dimensions/height-tables.html [ Failure Pass ] crbug.com/591099 fast/css/absolute-inline-alignment-2.html [ Pass ] crbug.com/835484 fast/css/outline-narrowLine.html [ Failure ] crbug.com/855279 fast/css/text-overflow-ellipsis-vertical-hittest.html [ Pass ] crbug.com/591099 fast/css3-text/css3-text-decoration/text-underline-position/text-underline-position-under.html [ Failure ] -crbug.com/591099 fast/dom/HTMLImageElement/image-srcset-w-onerror.html [ Failure Pass ] crbug.com/591099 fast/dom/SelectorAPI/resig-SelectorsAPI-test.xhtml [ Pass ] crbug.com/591099 fast/dom/shadow/focus-controller-recursion-crash.html [ Pass ] crbug.com/591099 fast/dom/shadow/svg-style-in-shadow-tree-crash.html [ Pass ] -crbug.com/591099 fast/events/before-unload-return-value-from-listener.html [ Pass ] -crbug.com/591099 fast/events/keyboard-scroll-use-count.html [ Crash Pass ] +crbug.com/591099 fast/events/before-unload-return-value-from-listener.html [ Pass Timeout ] crbug.com/591099 fast/events/touch/compositor-touch-hit-rects-continuation.html [ Failure ] crbug.com/591099 fast/events/touch/compositor-touch-hit-rects-list-translate.html [ Failure ] crbug.com/591099 fast/events/touch/compositor-touch-hit-rects.html [ Failure ] crbug.com/591099 fast/filesystem/file-writer-abort-depth.html [ Crash Pass ] -crbug.com/591099 fast/filesystem/file-writer-events.html [ Failure Pass ] crbug.com/889721 fast/inline/outline-continuations.html [ Failure ] crbug.com/591099 fast/multicol/border-radius-clipped-layer.html [ Pass ] crbug.com/591099 fast/peerconnection/RTCPeerConnection-many.html [ Pass ] -crbug.com/591099 fast/replaced/replaced-breaking.html [ Failure ] +crbug.com/591099 fast/replaced/replaced-breaking.html [ Failure Pass ] crbug.com/591099 fast/text/descent-clip-in-scaled-page.html [ Failure ] crbug.com/899902 fast/text/ellipsis-with-self-painting-layer.html [ Pass ] crbug.com/591099 fast/text/font-format-support-color-cff2-vertical.html [ Failure ] @@ -451,21 +447,6 @@ crbug.com/591099 fast/writing-mode/table-percent-width-quirk.html [ Pass ] crbug.com/930034 fast/writing-mode/vertical-rl-replaced-selection.html [ Failure ] crbug.com/591099 html/marquee/marquee-destroyed-without-removed-from-crash.html [ Pass ] -crbug.com/591099 http/tests/activedomobject/media.html [ Crash Pass ] -crbug.com/591099 http/tests/appcache/abort-cache-ondownloading.html [ Crash Pass ] -crbug.com/591099 http/tests/appcache/manifest-containing-itself.html [ Crash Pass ] -crbug.com/591099 http/tests/appcache/progress-counter.html [ Crash Pass ] -crbug.com/591099 http/tests/appcache/update-cache.html [ Crash Pass ] -crbug.com/591099 http/tests/appcache/video.html [ Crash Pass ] -crbug.com/591099 http/tests/appcache/xhr-foreign-resource.html [ Crash Pass ] -crbug.com/591099 http/tests/cache/content-type-ignored-during-revalidation.html [ Crash Pass ] -crbug.com/591099 http/tests/cache/history-only-cached-subresource-loads.html [ Crash Pass ] -crbug.com/591099 http/tests/cache/image-with-dpr-header-cached.html [ Crash Pass ] -crbug.com/591099 http/tests/cache/preload-cleared-after-parsing-canceled-by-js.html [ Crash Pass ] -crbug.com/591099 http/tests/cache/subresource-revalidation-referrer.html [ Crash Pass ] -crbug.com/591099 http/tests/cookies/js-get-and-set-http-only-cookie.html [ Crash Pass ] -crbug.com/591099 http/tests/cookies/meta.html [ Crash Pass ] -crbug.com/591099 http/tests/css/object-fit-delayed-img-svg.html [ Crash Pass ] crbug.com/591099 http/tests/csspaint/invalidation-border-image.html [ Pass ] crbug.com/591099 http/tests/devtools/elements/highlight/highlight-css-grid.js [ Failure ] crbug.com/591099 http/tests/devtools/elements/shadow/shadow-distribution.js [ Failure ] @@ -493,36 +474,21 @@ crbug.com/591099 http/tests/media/autoplay/document-user-activation-cross-origin-feature-policy-disabled.html [ Failure Pass ] crbug.com/591099 http/tests/media/video-load-metadata-decode-error.html [ Pass ] crbug.com/591099 http/tests/multipart/multipart-main-resource.html [ Pass ] -crbug.com/591099 http/tests/permissions/chromium/test-change-event-sharedworker.html [ Failure Pass ] -crbug.com/591099 http/tests/plugins/cross-frame-object-access.html [ Failure Pass ] -crbug.com/591099 http/tests/security/isolatedWorld/all-window-prototypes.html [ Crash Pass ] -crbug.com/591099 http/tests/security/isolatedWorld/body-prototype.html [ Crash Pass ] -crbug.com/591099 http/tests/security/isolatedWorld/context-destroy.html [ Crash Pass ] -crbug.com/591099 http/tests/security/isolatedWorld/didClearWindowObject.html [ Crash Pass ] -crbug.com/591099 http/tests/security/isolatedWorld/dispatchEvent.html [ Crash Pass ] -crbug.com/591099 http/tests/security/isolatedWorld/media-query-wrapper-leaks.html [ Crash Failure ] -crbug.com/591099 http/tests/security/isolatedWorld/sandboxed-iframe.html [ Crash Pass ] -crbug.com/591099 http/tests/security/isolatedWorld/top-properties.html [ Crash Pass ] -crbug.com/591099 http/tests/security/isolatedWorld/window-setTimeout-function.html [ Crash Pass ] -crbug.com/591099 http/tests/security/javascriptURL/javascriptURL-execution-context-frame-src-setAttributeNS.html [ Crash Pass ] -crbug.com/591099 http/tests/security/mixedContent/about-blank-iframe-in-main-frame.html [ Crash Pass ] -crbug.com/591099 http/tests/security/mixedContent/insecure-formSubmission-in-main-frame-allowed.html [ Crash Pass ] -crbug.com/591099 http/tests/security/mixedContent/insecure-formSubmission-in-main-frame-blocked.html [ Crash Pass ] -crbug.com/591099 http/tests/security/mixedContent/insecure-script-in-data-iframe-in-main-frame-blocked.html [ Crash Pass ] -crbug.com/591099 http/tests/security/upgrade-insecure-requests/iframe-upgrade.https.html [ Crash Pass ] +crbug.com/591099 http/tests/security/isolatedWorld/media-query-wrapper-leaks.html [ Failure ] +crbug.com/591099 http/tests/security/mixedContent/insecure-plugin-in-iframe.html [ Failure Pass ] +crbug.com/591099 http/tests/security/upgrade-insecure-requests/iframe-upgrade.https.html [ Crash ] crbug.com/591099 http/tests/security/video-poster-cross-origin-crash2.html [ Pass ] crbug.com/591099 http/tests/webfont/crbug-655076.html [ Pass ] crbug.com/591099 images/feature-policy-oversized-images-resize.html [ Pass ] crbug.com/591099 inspector-protocol/dom-snapshot/dom-snapshot-getSnapshot-origin-url.js [ Crash Pass ] crbug.com/591099 inspector-protocol/dom-snapshot/dom-snapshot-getSnapshot-pseudo-element.js [ Failure ] -crbug.com/591099 inspector-protocol/input/dispatchTouchEvent.js [ Failure Pass ] crbug.com/591099 jquery/offset.html [ Pass ] crbug.com/591099 media/autoplay/webaudio-audio-context-resume.html [ Failure Pass ] crbug.com/591099 media_capabilities/encodingInfo-avc1.html [ Failure ] crbug.com/591099 paint/invalidation/flexbox/scrollbars-changed.html [ Failure ] crbug.com/835484 paint/invalidation/outline/inline-focus.html [ Failure ] crbug.com/591099 paint/invalidation/overflow/opacity-change-on-overflow-float.html [ Failure ] -crbug.com/591099 paint/invalidation/scroll/fixed-under-composited-fixed-scrolled.html [ Failure ] +crbug.com/591099 paint/invalidation/scroll/fixed-under-composited-fixed-scrolled.html [ Failure Pass ] crbug.com/930034 paint/invalidation/selection/japanese-rl-selection-clear.html [ Failure ] crbug.com/930034 paint/invalidation/selection/selection-rl.html [ Failure ] crbug.com/591099 paint/invalidation/svg/svg-background-partial-redraw.html [ Failure ] @@ -539,102 +505,49 @@ crbug.com/927467 svg/dom/parent-view-layout-crash.html [ Crash Pass ] crbug.com/591099 svg/zoom/page/zoom-svg-float-border-padding.xml [ Pass ] crbug.com/591099 tables/mozilla/bugs/bug14159-1.html [ Pass ] -crbug.com/591099 virtual/android/frame-size/intersection-observer-root-uses-frame-size.html [ Crash Pass ] -crbug.com/591099 virtual/android/fullscreen/compositor-touch-hit-rects-fullscreen-video-controls.html [ Crash Failure ] -crbug.com/591099 virtual/android/fullscreen/full-screen-detached-document.html [ Crash Pass ] -crbug.com/591099 virtual/android/fullscreen/full-screen-orientation-change.html [ Crash Pass ] -crbug.com/591099 virtual/android/fullscreen/full-screen-prefixed-and-unprefixed.html [ Crash Pass ] -crbug.com/591099 virtual/android/fullscreen/full-screen-twice.html [ Crash Pass ] -crbug.com/591099 virtual/android/fullscreen/notify-paint-crash.html [ Crash Pass ] -crbug.com/591099 virtual/android/fullscreen/video-overlay-scroll.html [ Crash Pass ] -crbug.com/591099 virtual/android/rootscroller/nested-rootscroller-browser-controls-bounds-shown.html [ Crash Failure ] -crbug.com/591099 virtual/android/rootscroller/scroll-non-descendant-of-root-scroller.html [ Crash Pass ] -crbug.com/591099 virtual/android/rootscroller/set-root-scroller.html [ Crash Pass ] +crbug.com/591099 virtual/android/fullscreen/compositor-touch-hit-rects-fullscreen-video-controls.html [ Failure ] +crbug.com/591099 virtual/android/rootscroller/set-root-scroller.html [ Pass ] crbug.com/591099 virtual/android/rootscroller/set-rootscroller-before-load.html [ Pass ] -crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move-by-character-005.html [ Crash Pass ] -crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move-forward-after-line-break.html [ Crash Failure ] -crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_forward_line_mixed_editability.html [ Crash Pass ] -crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_character_01_ltr.html [ Crash Pass ] -crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_character_01_rtl.html [ Crash Pass ] -crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_character_23_ltr.html [ Crash Failure ] -crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_character_30_rtl.html [ Crash Pass ] -crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_right_character_in_mixed_bidi.html [ Crash Pass ] -crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_word_05_ltr_multi_line.html [ Crash Failure ] -crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_word_09_ltr_multi_line.html [ Crash Failure ] -crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_word_09_rtl_multi_line.html [ Crash Failure ] -crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_right_character_09_rtl.html [ Crash Pass ] -crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_right_character_16_ltr.html [ Crash Pass ] -crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_right_character_16_rtl.html [ Crash Pass ] -crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_right_word_01_rtl_multi_line.html [ Crash Failure ] +crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move-forward-after-line-break.html [ Failure ] +crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_character_23_ltr.html [ Failure ] +crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_word_05_ltr_multi_line.html [ Failure ] +crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_word_09_ltr_multi_line.html [ Failure ] +crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_word_09_rtl_multi_line.html [ Failure ] +crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_right_word_01_rtl_multi_line.html [ Failure ] crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_right_word_05_rtl_multi_line.html [ Failure ] -crbug.com/591099 virtual/composite-after-paint/compositing/backface-visibility/backface-visibility-webgl.html [ Crash Pass ] crbug.com/916511 virtual/composite-after-paint/paint/background/scrolling-background-with-negative-z-child.html [ Crash ] -crbug.com/591099 virtual/composite-after-paint/paint/frames/frameset-with-stacking-context-and-not-stacking-context-children.html [ Crash Pass ] crbug.com/591099 virtual/composite-after-paint/paint/invalidation/box/margin.html [ Failure Pass ] -crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/ServiceWorkerGlobalScope/postmessage.https.html [ Crash Pass ] -crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/client-id.https.html [ Crash Pass ] -crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/controller-on-reload.https.html [ Crash Pass ] -crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/fetch-event-redirect.https.html [ Crash Pass ] -crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/fetch-event.https.html [ Crash Pass ] -crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/fetch-request-xhr.https.html [ Crash Pass ] -crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/getregistration.https.html [ Crash Pass ] -crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/multi-globals/url-parsing.https.html [ Crash Pass ] -crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/navigation-preload/chunked-encoding.https.html [ Crash Pass ] -crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/referer.https.html [ Crash Pass ] -crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/serviceworkerobject-scripturl.https.html [ Crash Pass ] +crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/activate-event-after-install-state-change.https.html [ Pass ] +crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/clients-matchall-exact-controller.https.html [ Pass ] +crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/clients-matchall.https.html [ Pass ] +crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/fetch-cors-xhr.https.html [ Pass ] +crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/fetch-event-after-navigation-within-page.https.html [ Pass ] +crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/fetch-event-redirect.https.html [ Pass ] +crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/fetch-request-css-images.https.html [ Pass ] +crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/fetch-request-xhr-sync.https.html [ Pass ] +crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/shared-worker-controlled.https.html [ Pass ] crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/skip-waiting-without-using-registration.https.html [ Pass Timeout ] -crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/uncontrolled-page.https.html [ Crash Pass ] -crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/worker-client-id.https.html [ Crash Failure ] -crbug.com/591099 virtual/display-lock/display-lock/lock-after-append/acquire-immediate-update-and-commit.html [ Crash Pass ] -crbug.com/591099 virtual/display-lock/display-lock/lock-after-append/locked-element-prevents-anchor-links.html [ Crash Pass ] +crbug.com/591099 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/worker-client-id.https.html [ Failure ] crbug.com/591099 virtual/display-lock/display-lock/lock-after-append/measure-forced-layout-after-commit.html [ Failure ] crbug.com/591099 virtual/display-lock/display-lock/lock-after-append/measure-forced-layout.html [ Failure ] -crbug.com/591099 virtual/display-lock/display-lock/lock-after-append/measure-updated-layout.html [ Crash Failure ] +crbug.com/591099 virtual/display-lock/display-lock/lock-after-append/measure-updated-layout.html [ Failure ] crbug.com/926276 virtual/display-lock/display-lock/lock-after-append/nested-update-and-commit.html [ Timeout ] crbug.com/926276 virtual/display-lock/display-lock/lock-after-append/nested-update.html [ Timeout ] -crbug.com/591099 virtual/display-lock/display-lock/lock-before-append/acquire-timeout.html [ Crash Pass ] crbug.com/591099 virtual/display-lock/display-lock/lock-before-append/acquire-update-measure-remove.html [ Failure ] -crbug.com/591099 virtual/display-lock/display-lock/lock-before-append/commit-without-acquire.html [ Crash Pass ] crbug.com/591099 virtual/display-lock/display-lock/lock-before-append/measure-forced-layout.html [ Failure ] crbug.com/591099 virtual/display-lock/display-lock/lock-before-append/measure-updated-layout.html [ Failure ] crbug.com/591099 virtual/exotic-color-space/ [ Skip ] crbug.com/591099 virtual/feature-policy-for-sandbox/http/tests/security/contentSecurityPolicy/sandbox-in-http-header-control.html [ Failure ] crbug.com/591099 virtual/feature-policy-for-sandbox/http/tests/security/mixedContent/insecure-plugin-in-iframe.html [ Failure Pass ] crbug.com/591099 virtual/feature-policy-for-sandbox/http/tests/security/sandbox-iframe-blocks-modals.php [ Failure ] -crbug.com/591099 virtual/feature-policy-for-sandbox/mhtml/page_with_image_unmht.mht [ Crash Pass ] -crbug.com/591099 virtual/feature-policy-for-sandbox/mhtml/transfer_encoding_7bit.mht [ Crash Pass ] -crbug.com/591099 virtual/feature-policy-permissions/external/wpt/mediacapture-streams/MediaStream-finished-add.https.html [ Crash Pass ] -crbug.com/591099 virtual/feature-policy-permissions/external/wpt/mediacapture-streams/MediaStreamTrack-applyConstraints.https.html [ Crash Pass ] -crbug.com/591099 virtual/feature-policy-permissions/external/wpt/mediacapture-streams/MediaStreamTrack-getSettings.https.html [ Crash Pass ] -crbug.com/591099 virtual/feature-policy-permissions/external/wpt/mediacapture-streams/historical.html [ Crash Pass ] -crbug.com/591099 virtual/fractional_scrolling/fast/scrolling/background-paint-composited-scrolled.html [ Crash Pass ] crbug.com/591099 virtual/fractional_scrolling/fast/scrolling/fractional-scroll-offset-fixed-position-non-composited.html [ Failure ] -crbug.com/591099 virtual/fractional_scrolling/fast/scrolling/overflow-scrollability.html [ Failure Pass ] -crbug.com/591099 virtual/fractional_scrolling/fast/scrolling/scroll-clears-fragment-anchor.html [ Crash Pass ] -crbug.com/591099 virtual/fractional_scrolling/fast/scrolling/scroll-into-view-collapsed-div.html [ Crash Pass ] -crbug.com/591099 virtual/fractional_scrolling/fast/scrolling/scroll-to-origin-with-options-no-layout.html [ Crash Pass ] -crbug.com/591099 virtual/fractional_scrolling/fast/scrolling/scrollbar-mousedown-mouseup.html [ Crash Pass ] -crbug.com/591099 virtual/fractional_scrolling/fast/scrolling/scrollbar-prevent-default.html [ Crash Pass ] -crbug.com/591099 virtual/fractional_scrolling/fast/scrolling/unscrollable-layer-subpixel-size-with-negative-overflow.html [ Crash Pass ] -crbug.com/591099 virtual/fractional_scrolling_threaded/fast/scrolling/content-box-smaller-than-scrollbar.html [ Crash Pass ] -crbug.com/591099 virtual/fractional_scrolling_threaded/fast/scrolling/empty-anchor.html [ Crash Pass ] -crbug.com/591099 virtual/fractional_scrolling_threaded/fast/scrolling/events/overscroll-event-fired-to-element-with-overscroll-behavior.html [ Crash Pass ] -crbug.com/591099 virtual/fractional_scrolling_threaded/fast/scrolling/hide-scrollbars.html [ Crash Pass ] -crbug.com/591099 virtual/fractional_scrolling_threaded/fast/scrolling/horizontal-overflow-quirks.html [ Crash Pass ] -crbug.com/591099 virtual/fractional_scrolling_threaded/fast/scrolling/scrollbar-mousedown-move-mouseup.html [ Crash Pass ] crbug.com/591099 virtual/gpu-rasterization/images/color-profile-image-filter-all.html [ Pass ] -crbug.com/591099 virtual/gpu-rasterization/images/cross-fade-tiled.html [ Crash Pass ] -crbug.com/591099 virtual/gpu-rasterization/images/feature-policy-oversized-images-edge-cases.html [ Crash Pass ] -crbug.com/591099 virtual/gpu-rasterization/images/icon-decoding.html [ Crash Pass ] crbug.com/591099 virtual/gpu-rasterization/images/image-page-injected-script-crash.html [ Pass ] -crbug.com/591099 virtual/gpu-rasterization/images/img-dimensions-styled.html [ Crash Pass ] -crbug.com/591099 virtual/gpu-rasterization/images/rgb-jpeg-endian-pixels.html [ Crash Pass ] -crbug.com/591099 virtual/gpu/fast/canvas/2d.fillText.gradient.html [ Crash Pass ] crbug.com/591099 virtual/gpu/fast/canvas/OffscreenCanvas-copyImage.html [ Pass ] crbug.com/591099 virtual/gpu/fast/canvas/OffscreenCanvas-filter.html [ Pass ] crbug.com/591099 virtual/gpu/fast/canvas/canvas-arc-circumference-fill.html [ Failure ] crbug.com/591099 virtual/gpu/fast/canvas/canvas-blend-image.html [ Pass ] -crbug.com/591099 virtual/gpu/fast/canvas/canvas-blending-color-over-pattern.html [ Crash Pass ] +crbug.com/591099 virtual/gpu/fast/canvas/canvas-blending-color-over-pattern.html [ Pass ] crbug.com/591099 virtual/gpu/fast/canvas/canvas-blending-pattern-over-gradient.html [ Pass ] crbug.com/591099 virtual/gpu/fast/canvas/canvas-blending-pattern-over-image.html [ Pass ] crbug.com/591099 virtual/gpu/fast/canvas/canvas-filter-stroke-paint-pattern.html [ Pass ] @@ -643,6 +556,8 @@ crbug.com/591099 virtual/mojo-blob-urls/external/wpt/FileAPI/url/sandboxed-iframe.html [ Pass ] crbug.com/591099 virtual/mojo-blob-urls/external/wpt/FileAPI/url/url-format.any.html [ Pass ] crbug.com/591099 virtual/mouseevent_fractional/fast/events/touch/compositor-touch-hit-rects-continuation.html [ Failure ] +crbug.com/591099 virtual/mouseevent_fractional/fast/events/touch/compositor-touch-hit-rects-list-translate.html [ Failure ] +crbug.com/591099 virtual/mouseevent_fractional/fast/events/touch/compositor-touch-hit-rects.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/omt-worker-fetch/external/wpt/referrer-policy/no-referrer/http-rp/same-origin/http-http/shared-worker/keep-origin-redirect/generic.http.html [ Pass ] @@ -690,13 +605,11 @@ crbug.com/591099 virtual/streaming-preload/http/tests/fetch/serviceworker/thorough/cors-base-https-other-https.html [ Pass ] crbug.com/591099 virtual/streaming-preload/http/tests/fetch/workers/thorough/cors-preflight-base-https-other-https.html [ Pass ] crbug.com/591099 virtual/threaded/ [ Skip ] -crbug.com/591099 virtual/user-activation-v2/fast/events/autoscroll-iframe-no-scrolling.html [ Crash Pass ] -crbug.com/591099 virtual/user-activation-v2/fast/events/click-count.html [ Crash Pass ] -crbug.com/591099 virtual/user-activation-v2/fast/events/message-channel-gc-4.html [ Crash Pass ] -crbug.com/591099 virtual/user-activation-v2/fast/events/mouse-relative-position.html [ Crash Pass ] crbug.com/591099 virtual/user-activation-v2/fast/events/pointerevents/mouse-pointer-haspointercapture.html [ Failure Pass ] crbug.com/591099 virtual/user-activation-v2/fast/events/touch/compositor-touch-hit-rects-continuation.html [ Failure ] -crbug.com/591099 virtual/user-activation-v2/fullscreen/model/fully-exit-fullscreen-nested-iframe.html [ Pass ] +crbug.com/591099 virtual/user-activation-v2/fast/events/touch/compositor-touch-hit-rects-list-translate.html [ Failure ] +crbug.com/591099 virtual/user-activation-v2/fast/events/touch/compositor-touch-hit-rects.html [ Failure ] +crbug.com/591099 virtual/user-activation-v2/fullscreen/model/fully-exit-fullscreen-nested-iframe.html [ Pass Timeout ] crbug.com/591099 virtual/video-surface-layer/media/W3C/video/networkState/networkState_during_progress.html [ Pass ] crbug.com/591099 virtual/video-surface-layer/media/autoplay-when-visible.html [ Pass ] crbug.com/591099 virtual/video-surface-layer/media/color-profile-video-seek-filter.html [ Pass ] @@ -704,5 +617,5 @@ crbug.com/591099 virtual/video-surface-layer/media/video-canvas-draw.html [ Failure ] crbug.com/591099 virtual/video-surface-layer/media/video-controls-hide-on-move-outside-controls.html [ Pass ] crbug.com/591099 virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCIceTransport-extension.https.html [ Failure Pass ] -crbug.com/591099 vr/getFrameData_oneframeupdate.html [ Pass ] +crbug.com/591099 vr/getFrameData_oneframeupdate.html [ Failure Pass ] crbug.com/591099 webexposed/global-interface-listing-shared-worker.html [ Pass ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index bb42a57..0d11d7e8 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -471,7 +471,6 @@ crbug.com/711807 external/wpt/css/CSS2/normal-flow/replaced-intrinsic-002.xht [ Failure ] #### external/wpt/css/css-position -crbug.com/907911 external/wpt/css/css-position/position-absolute-percentage-height.html [ Failure ] crbug.com/752022 external/wpt/css/css-position/position-sticky-offset-overflow.html [ Failure ] crbug.com/702927 external/wpt/css/css-position/position-sticky-table-tr-top.html [ Failure ] crbug.com/702927 external/wpt/css/css-position/position-sticky-table-tr-bottom.html [ Failure ] @@ -3058,6 +3057,10 @@ crbug.com/918664 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/sizing/block-size-with-min-or-max-content-table-1a.html [ Failure Pass ] # ====== New tests from wpt-importer added here ====== +crbug.com/626703 external/wpt/html/semantics/forms/form-submission-target/rel-base-target.html [ Timeout ] +crbug.com/626703 external/wpt/html/semantics/forms/form-submission-target/rel-input-target.html [ Timeout ] +crbug.com/626703 external/wpt/html/semantics/forms/form-submission-target/rel-form-target.html [ Timeout ] +crbug.com/626703 external/wpt/html/semantics/forms/form-submission-target/rel-button-target.html [ Timeout ] crbug.com/626703 [ Linux ] virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/fetch-request-xhr-sync.https.html [ Crash ] crbug.com/626703 [ Linux ] virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/shared-worker-controlled.https.html [ Crash ] crbug.com/626703 [ Retina ] virtual/feature-policy-permissions/external/wpt/mediacapture-streams/MediaStream-default-feature-policy.https.html [ Timeout ]
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites index ee8cc7c6c..c4d61503 100644 --- a/third_party/blink/web_tests/VirtualTestSuites +++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -1025,11 +1025,6 @@ "args": ["--enable-blink-features=StreamsNative", "--enable-features=BlinkHeapUnifiedGarbageCollection"] }, { - "prefix": "spatial-navigation-force-outline", - "base": "fast/spatial-navigation", - "args": ["--enable-blink-features=SpatialNavigationForcesOutline"] - }, - { "prefix": "bidi-caret-affinity", "base": "editing/selection/modify_move", "args": ["--enable-blink-features=BidiCaretAffinity,EditingNG"]
diff --git a/third_party/blink/web_tests/display-lock/lock-after-append/acquire-in-iframe-expected.html b/third_party/blink/web_tests/display-lock/lock-after-append/acquire-in-iframe-expected.html new file mode 100644 index 0000000..53621ec --- /dev/null +++ b/third_party/blink/web_tests/display-lock/lock-after-append/acquire-in-iframe-expected.html
@@ -0,0 +1,4 @@ +<!doctype HTML> + +<div id="log">PASS</div> +<iframe></iframe>
diff --git a/third_party/blink/web_tests/display-lock/lock-after-append/acquire-in-iframe.html b/third_party/blink/web_tests/display-lock/lock-after-append/acquire-in-iframe.html new file mode 100644 index 0000000..e348b10 --- /dev/null +++ b/third_party/blink/web_tests/display-lock/lock-after-append/acquire-in-iframe.html
@@ -0,0 +1,36 @@ +<!doctype HTML> + +<div id="log"></div> +<iframe id="frame" srcdoc=' + <style> + #container { + contain: style layout; + width: 100px; + height: 100px; + background: lightblue; + } + </style> + <div id="container"></div> +'></iframe> + +<script> +// TODO(vmpstr): In WPT this needs to be replaced with reftest-wait. +if (window.testRunner) + window.testRunner.waitUntilDone(); + +function finishTest(status_string) { + if (document.getElementById("log").innerHTML === "") + document.getElementById("log").innerHTML = status_string; + if (window.testRunner) + window.testRunner.notifyDone(); +} + +function runTest() { + let container = document.getElementById("frame").contentDocument.getElementById("container"); + container.displayLock.acquire({ timeout: Infinity }).then( + () => { finishTest("PASS"); }, + (e) => { finishTest("FAIL " + e.message); }); +} + +window.onload = runTest; +</script>
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 26066b1..37af55d52 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
@@ -164261,6 +164261,11 @@ {} ] ], + "html/browsers/windows/nested-browsing-contexts/resources/post-to-parent.html": [ + [ + {} + ] + ], "html/browsers/windows/resources/browsing-context-window.html": [ [ {} @@ -171461,6 +171466,16 @@ {} ] ], + "html/semantics/forms/form-submission-target/resources/endpoint.html": [ + [ + {} + ] + ], + "html/semantics/forms/form-submission-target/resources/reltester.js": [ + [ + {} + ] + ], "html/semantics/forms/introduction-1/contains.json": [ [ {} @@ -171866,6 +171881,11 @@ {} ] ], + "html/semantics/rellist-feature-detection-expected.txt": [ + [ + {} + ] + ], "html/semantics/scripting-1/META.yml": [ [ {} @@ -239440,6 +239460,12 @@ {} ] ], + "html/browsers/windows/nested-browsing-contexts/name-attribute.window.js": [ + [ + "/html/browsers/windows/nested-browsing-contexts/name-attribute.window.html", + {} + ] + ], "html/browsers/windows/nested-browsing-contexts/window-parent-null.html": [ [ "/html/browsers/windows/nested-browsing-contexts/window-parent-null.html", @@ -244494,6 +244520,30 @@ {} ] ], + "html/semantics/forms/form-submission-target/rel-base-target.html": [ + [ + "/html/semantics/forms/form-submission-target/rel-base-target.html", + {} + ] + ], + "html/semantics/forms/form-submission-target/rel-button-target.html": [ + [ + "/html/semantics/forms/form-submission-target/rel-button-target.html", + {} + ] + ], + "html/semantics/forms/form-submission-target/rel-form-target.html": [ + [ + "/html/semantics/forms/form-submission-target/rel-form-target.html", + {} + ] + ], + "html/semantics/forms/form-submission-target/rel-input-target.html": [ + [ + "/html/semantics/forms/form-submission-target/rel-input-target.html", + {} + ] + ], "html/semantics/forms/historical.html": [ [ "/html/semantics/forms/historical.html", @@ -400426,31 +400476,31 @@ "support" ], "fetch/stale-while-revalidate/fetch.tentative.html": [ - "01a991ebfb1cb42288a01da37c76b09fa53f407c", + "5b9b2dc5de2835d1f4a9f49cc63e0b3f03317698", "testharness" ], "fetch/stale-while-revalidate/stale-css.py": [ - "6f3014db5246994383354b139e7900306297dd57", + "425c889ac5ec58527e63ab25a4f70558b7daeef3", "support" ], "fetch/stale-while-revalidate/stale-css.tentative.html": [ - "9b95b891fff2db4a29bd438208ea4274a762977d", + "3459493f28c22011e96def2549f01df1d5e0cbf2", "testharness" ], "fetch/stale-while-revalidate/stale-image.py": [ - "42d0764eb91e7145cfe1638d90421ca7492379db", + "ce7f0fc782613e0a36e3d0aba0521e45f1ca6bf0", "support" ], "fetch/stale-while-revalidate/stale-image.tentative.html": [ - "a5d4e79c54b8fca7a7089efcca0bc5f6f7c1202a", + "8b6a896eb15219e2222d65863c81724959c1ee1a", "testharness" ], "fetch/stale-while-revalidate/stale-script.py": [ - "c17528d8e6314e60407085ca778ba2ff70666985", + "0f91a9b83486678eabd600ecb6336695e5dd6970", "support" ], "fetch/stale-while-revalidate/stale-script.tentative.html": [ - "2e04e3905780add84f3da805a238946256ebda87", + "8cbb54b7dab3bc9b9e8763c5358a9232d24c1e7f", "testharness" ], "fonts/AD.woff": [ @@ -404449,6 +404499,10 @@ "2f5b1c466f8bdaf2555e548f4140abdcc18d79bc", "testharness" ], + "html/browsers/windows/nested-browsing-contexts/name-attribute.window.js": [ + "69908af71b7239d72e33d33be79edd1f344a1870", + "testharness" + ], "html/browsers/windows/nested-browsing-contexts/resources/frameElement-nested-frame.html": [ "d066b8d4cb2dc76e85fa53f28c2053f9acbfbd72", "support" @@ -404461,6 +404515,10 @@ "65a825f5737468d64c34d1399d0d0875c2dfe983", "support" ], + "html/browsers/windows/nested-browsing-contexts/resources/post-to-parent.html": [ + "302e9d9cc12b347da03c20e288f7dad12598d179", + "support" + ], "html/browsers/windows/nested-browsing-contexts/window-parent-null.html": [ "428312086ecf54e6f04129ffd3b91f4d7073e81f", "testharness" @@ -405670,7 +405728,7 @@ "support" ], "html/dom/interfaces.https_include=HTML._-expected.txt": [ - "099799e7438f61a651fe10012e65140214d466a0", + "826eb52dc05bf982b7cdfc4106cc6d7b396e72cd", "support" ], "html/dom/interfaces.worker-expected.txt": [ @@ -414873,6 +414931,30 @@ "f37bc33f6f93ca94940ffeb0066945eb9aa020ee", "testharness" ], + "html/semantics/forms/form-submission-target/rel-base-target.html": [ + "222be95d2e8a9da39525fbf6d8048e6cdfd7a982", + "testharness" + ], + "html/semantics/forms/form-submission-target/rel-button-target.html": [ + "76fa8685905ad233f9312be3f6bf09503158a666", + "testharness" + ], + "html/semantics/forms/form-submission-target/rel-form-target.html": [ + "58611f41a9fdaea1611513e02dad87e017728f9a", + "testharness" + ], + "html/semantics/forms/form-submission-target/rel-input-target.html": [ + "b80e0240bae3802b04118249ec2b94e16a91e9e6", + "testharness" + ], + "html/semantics/forms/form-submission-target/resources/endpoint.html": [ + "be9e7942927dabeea32bf9e17b88d6643bc4ea91", + "support" + ], + "html/semantics/forms/form-submission-target/resources/reltester.js": [ + "0fa9774ce4f15be8909a0aceaa4879e9c5ab39c1", + "support" + ], "html/semantics/forms/historical.html": [ "6873ecd251741fb8436a377081d5a6d3de53b7ab", "testharness" @@ -416137,8 +416219,12 @@ "54b95ac280b492256f1e1c238876caecbcc85e8c", "support" ], + "html/semantics/rellist-feature-detection-expected.txt": [ + "a00858d5f893aa6d6e1bff2e145b72ea2c1fcf4d", + "support" + ], "html/semantics/rellist-feature-detection.html": [ - "f4ce621172ebd5831fe259ab9603162549795dee", + "d290439d8ee647b2f8d95ddc45ac390dccde9843", "testharness" ], "html/semantics/scripting-1/META.yml": [ @@ -421994,7 +422080,7 @@ "support" ], "interfaces/font-metrics-api.idl": [ - "b13def2d74c74b12821b9691f84088e23dc35040", + "b38024e44616599596661fcd72d705424b0debfc", "support" ], "interfaces/fullscreen.idl": [ @@ -422034,7 +422120,7 @@ "support" ], "interfaces/html.idl": [ - "0d6445e7f016b736966e621a414cbe9bc9219e99", + "f530f3559b68af565fc07f4372a1444d5036eac2", "support" ], "interfaces/image-capture.idl": [ @@ -422230,7 +422316,7 @@ "support" ], "interfaces/storage.idl": [ - "29603241222b9c472ca21184d04e1966e2f7198a", + "437bc6dd43c2bd17113c6b823a238e7141fb25bf", "support" ], "interfaces/touch-events.idl": [ @@ -422282,7 +422368,7 @@ "support" ], "interfaces/web-nfc.idl": [ - "5a6d6f8a06b1d7bfbcf5b3cc1b5078ff930cbedc", + "913d1fe808adf50f66fa621eb62d12b1b41a3a05", "support" ], "interfaces/web-share.idl": [ @@ -446194,7 +446280,7 @@ "support" ], "resources/testdriver.js": [ - "ea380dbd3c32def105c1483230e91e9c7e979b27", + "09a15e1bbb93880688f3216415711c7fd295355f", "support" ], "resources/testdriver.js.headers": [ @@ -448278,7 +448364,7 @@ "testharness" ], "service-workers/service-worker/fetch-request-xhr.https-expected.txt": [ - "76e08357b6e2b1edce325a9ebefde287c962681b", + "3de90db5c4ece4734df673d0a066fa7772eb4a33", "support" ], "service-workers/service-worker/fetch-request-xhr.https.html": [
diff --git a/third_party/blink/web_tests/external/wpt/css/css-position/position-absolute-container-dynamic.html b/third_party/blink/web_tests/external/wpt/css/css-position/position-absolute-container-dynamic.html deleted file mode 100644 index 711d3176..0000000 --- a/third_party/blink/web_tests/external/wpt/css/css-position/position-absolute-container-dynamic.html +++ /dev/null
@@ -1,35 +0,0 @@ -<!DOCTYPE html> -<title>CSS Position Absolute: dynamic changes to containing block width</title> -<link rel="author" href="mailto:atotic@google.com"> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<link rel="help" href="https://www.w3.org/TR/css-position-3/#abs-non-replaced-width"> -<meta name="assert" content="abspos descendant responds to containing block size change"> -<style> - -#container { - position: relative; - width: 50px; - height: 100px; - background: red; -} -#target { - position: absolute; - left: 0; - width: 100%; - height: 100%; - background: green; -} -</style> -<div id="container"> - <div style="display:flex;"> - <div id="target"></div> - </div> -</div> -<script> -document.body.offsetTop; -test(() => { - document.getElementById("container").style.width = "100px"; - assert_equals(document.querySelector("#target").offsetWidth, 100); -}, '#target used container width when computing size'); -</script>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-position/position-absolute-percentage-height.html b/third_party/blink/web_tests/external/wpt/css/css-position/position-absolute-percentage-height.html deleted file mode 100644 index 9fffab80..0000000 --- a/third_party/blink/web_tests/external/wpt/css/css-position/position-absolute-percentage-height.html +++ /dev/null
@@ -1,59 +0,0 @@ -<!DOCTYPE html> -<title>CSS Position Absolute: css-position-3</title> -<link rel="author" href="mailto:atotic@google.com"> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<link rel="help" href="https://www.w3.org/TR/css-position-3/"> -<meta name="assert" content="abspos resolves %-ge sizes correctly."> -<style> - -#container { - position: relative; -} - -#image-wrapper { - display: flex; - position: absolute; - height: 100%; - background: green; -} - -#content-wrapper { - margin-left: 30%; -} - -#target { - display: block; - min-height: 100%; - opacity: 0.5; -} -</style> -<!-- IMG height is 100% of image wrapper height. - IMG width is 100% of image wrapper width. - IMG width equals IMG height --> -<div id="container"> - <div id="image-wrapper"> - <!-- 1x1 green pixel --> - <img id="target" src="data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M/wHwAEBgIApD5fRAAAAABJRU5ErkJggg=="> - </div> - <div id="content-wrapper"> - Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. - </div> -</div> -<script> -document.body.offsetTop; -test(() => { - let target = document.querySelector("#target"); - assert_equals(target.offsetWidth, target.offsetHeight); - assert_equals(target.offsetWidth, document.querySelector("#image-wrapper").offsetWidth); - assert_equals(target.offsetHeight, document.querySelector("#content-wrapper").offsetHeight); -}, '#target height matches containing block height, and target parent width matches #target width' ); - -test(() => { - document.body.style.marginLeft = "300px"; - let target = document.querySelector("#target"); - assert_equals(target.offsetWidth, target.offsetHeight); - assert_equals(target.offsetWidth, document.querySelector("#image-wrapper").offsetWidth); - assert_equals(target.offsetHeight, document.querySelector("#content-wrapper").offsetHeight); -}, '#target height matches containing block height, and target parent width matches #target width'); -</script>
diff --git a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/fetch.tentative.html b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/fetch.tentative.html index 01a991eb..5b9b2dc5 100644 --- a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/fetch.tentative.html +++ b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/fetch.tentative.html
@@ -7,11 +7,14 @@ <title>Tests Stale While Revalidate is not executed for fetch API</title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="/common/utils.js"></script> <script> promise_test(async (test) => { - const response = await fetch(`stale-script.py`); - const response2 = await fetch(`stale-script.py`); + var request_token = token(); - assert_not_equals(response.headers.get('Token'), response2.headers.get('Token')); + const response = await fetch(`stale-script.py?token=` + request_token); + const response2 = await fetch(`stale-script.py?token=` + request_token); + + assert_not_equals(response.headers.get('Unique-Id'), response2.headers.get('Unique-Id')); }, 'Second fetch does not return same response'); </script>
diff --git a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-css.py b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-css.py index 6f3014d..425c889 100644 --- a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-css.py +++ b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-css.py
@@ -1,9 +1,10 @@ def main(request, response): - cookie = request.cookies.first("Count", None) + token = request.GET.first("token", None) + value = request.server.stash.take(token) count = 0 - if cookie != None: - count = int(cookie.value) + if value != None: + count = int(value) if request.GET.first("query", None) != None: headers = [("Count", count)] content = "" @@ -15,6 +16,7 @@ content = "body { background: rgb(255, 0, 0); }" headers = [("Content-Type", "text/css"), - ("Set-Cookie", "Count={}".format(count)), - ("Cache-Control", "private, max-age=0, stale-while-revalidate=10")] + ("Cache-Control", "private, max-age=0, stale-while-revalidate=60")] + + request.server.stash.put(token, count) return 200, headers, content
diff --git a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-css.tentative.html b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-css.tentative.html index 9b95b89..3459493f 100644 --- a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-css.tentative.html +++ b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-css.tentative.html
@@ -7,9 +7,11 @@ <title>Tests Stale While Revalidate works for css</title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="/common/utils.js"></script> <body> <script> +var request_token = token(); async_test(t => { window.onload = t.step_func(() => { t.step_timeout(() => { @@ -19,10 +21,10 @@ assert_equals(window.getComputedStyle(document.body).getPropertyValue('background-color'), "rgb(0, 128, 0)"); var checkResult = () => { // We poll because we don't know when the revalidation will occur. - fetch("stale-css.py?query").then(t.step_func((response) => { + fetch("stale-css.py?query&token=" + request_token).then(t.step_func((response) => { var count = response.headers.get("Count"); if (count == '2') { - t.done(); + t.done(); } else { t.step_timeout(checkResult, 25); } @@ -32,7 +34,7 @@ }); link2.rel = "stylesheet"; link2.type = "text/css"; - link2.href = "stale-css.py"; + link2.href = "stale-css.py?token=" + request_token; document.body.appendChild(link2); }, 0); }); @@ -41,7 +43,7 @@ var link = document.createElement("link"); link.rel = "stylesheet"; link.type = "text/css"; -link.href = "stale-css.py"; +link.href = "stale-css.py?token=" + request_token; document.body.appendChild(link); </script> </body>
diff --git a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-image.py b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-image.py index 42d0764..ce7f0fc 100644 --- a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-image.py +++ b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-image.py
@@ -2,10 +2,11 @@ def main(request, response): - cookie = request.cookies.first("Count", None) + token = request.GET.first("token", None) + value = request.server.stash.take(token) count = 0 - if cookie != None: - count = int(cookie.value) + if value != None: + count = int(value) if request.GET.first("query", None) != None: headers = [("Count", count)] content = "" @@ -13,18 +14,18 @@ else: count = count + 1 filename = "green-16x16.png" - if cookie > 1: + if count > 1: filename = "green-256x256.png" path = os.path.join(os.path.dirname(__file__), "../../images", filename) body = open(path, "rb").read() + request.server.stash.put(token, count) response.add_required_headers = False response.writer.write_status(200) response.writer.write_header("content-length", len(body)) - response.writer.write_header("Cache-Control", "private, max-age=0, stale-while-revalidate=10") + response.writer.write_header("Cache-Control", "private, max-age=0, stale-while-revalidate=60") response.writer.write_header("content-type", "image/png") - response.writer.write_header("Set-Cookie", "Count={}".format(count)) response.writer.end_headers() response.writer.write(body)
diff --git a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-image.tentative.html b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-image.tentative.html index a5d4e79..8b6a896e 100644 --- a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-image.tentative.html +++ b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-image.tentative.html
@@ -7,6 +7,7 @@ <title>Tests Stale While Revalidate works for images</title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="/common/utils.js"></script> <body> <!-- Use a child document to load the second stale image into because @@ -16,6 +17,7 @@ <iframe id="child" srcdoc=""></iframe> <script> +var request_token = token(); async_test(t => { window.onload = t.step_func(() => { t.step_timeout(() => { @@ -26,7 +28,7 @@ assert_equals(img2.width, 16, "image dimension"); var checkResult = () => { // We poll because we don't know when the revalidation will occur. - fetch("stale-image.py?query").then(t.step_func((response) => { + fetch("stale-image.py?query&token=" + request_token).then(t.step_func((response) => { var count = response.headers.get("Count"); if (count == '2') { t.done(); @@ -37,14 +39,14 @@ }; t.step_timeout(checkResult, 25); }); - img2.src = "stale-image.py"; + img2.src = "stale-image.py?token=" + request_token; childDocument.body.appendChild(img2); }, 0); }); }, 'Cache returns stale resource'); var img = document.createElement("img"); -img.src = "stale-image.py"; +img.src = "stale-image.py?token=" + request_token; img.id = "firstimage"; document.body.appendChild(img); </script>
diff --git a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-script.py b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-script.py index c17528d8..0f91a9b 100644 --- a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-script.py +++ b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-script.py
@@ -1,14 +1,15 @@ import random, string, datetime -def token(): +def id_token(): letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(20)) def main(request, response): - cookie = request.cookies.first("Count", None) + token = request.GET.first("token", None) + value = request.server.stash.take(token) count = 0 - if cookie != None: - count = int(cookie.value) + if value != None: + count = int(value) if request.GET.first("query", None) != None: headers = [("Count", count)] content = "" @@ -16,10 +17,10 @@ else: count = count + 1 - unique_id = token() + unique_id = id_token() headers = [("Content-Type", "text/javascript"), - ("Cache-Control", "private, max-age=0, stale-while-revalidate=10"), - ("Set-Cookie", "Count={}".format(count)), - ("Token", unique_id)] + ("Cache-Control", "private, max-age=0, stale-while-revalidate=60"), + ("Unique-Id", unique_id)] content = "report('{}')".format(unique_id) + request.server.stash.put(token, count) return 200, headers, content
diff --git a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-script.tentative.html b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-script.tentative.html index 2e04e390..8cbb54b 100644 --- a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-script.tentative.html +++ b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-script.tentative.html
@@ -7,10 +7,12 @@ <title>Tests Stale While Revalidate works for scripts</title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<script src="/common/utils.js"></script> <body> <script> var last_modified; var last_modified_count = 0; +var request_token = token(); // The script will call report via a uniquely generated ID on the subresource. // If it is a cache hit the ID will be the same and the test will pass. @@ -27,13 +29,13 @@ window.onload = t.step_func(() => { step_timeout(() => { var script = document.createElement("script"); - script.src = "stale-script.py"; + script.src = "stale-script.py?token=" + request_token; document.body.appendChild(script); script.onload = t.step_func(() => { assert_equals(last_modified_count, 2, "last modified"); var checkResult = () => { // We poll because we don't know when the revalidation will occur. - fetch("stale-script.py?query").then(t.step_func((response) => { + fetch("stale-script.py?query&token=" + request_token).then(t.step_func((response) => { var count = response.headers.get("Count"); if (count == '2') { t.done(); @@ -49,7 +51,7 @@ }, 'Cache returns stale resource'); var script = document.createElement("script"); -script.src = "stale-script.py"; +script.src = "stale-script.py?token=" + request_token; document.body.appendChild(script); </script> </body>
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/windows/nested-browsing-contexts/name-attribute.window.js b/third_party/blink/web_tests/external/wpt/html/browsers/windows/nested-browsing-contexts/name-attribute.window.js new file mode 100644 index 0000000..69908af7 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/browsers/windows/nested-browsing-contexts/name-attribute.window.js
@@ -0,0 +1,58 @@ +// META: script=/common/get-host-info.sub.js + +[ + "frame", // This works without <frameset>, so great + "iframe", + "object", + "embed", +].forEach(element => { + [ + null, + "", + "initialvalue" + ].forEach(initialNameValue => { + [ + "same-origin", + "cross-origin" + ].forEach(originType => { + async_test(t => { + const ident = element + initialNameValue + originType, + file = `${new URL("resources/post-to-parent.html", location.href).pathname}?ident=${ident}`, + child = originType === "same-origin" ? file : `${get_host_info().HTTP_REMOTE_ORIGIN}${file}`, + frame = document.createElement(element), + expectedNameValue = initialNameValue || ""; + let state = "set"; + const listener = t.step_func(e => { + if (e.data.ident === ident) { + assert_equals(e.data.name, expectedNameValue); // This check is always the same + if (state === "set") { + frame.setAttribute("name", "meh"); + state = "remove" + e.source.postMessage(null, "*"); + return; + } + if (state === "remove") { + frame.removeAttribute("name"); + state = "done"; + e.source.postMessage(null, "*"); + return; + } + if (state === "done") { + t.done(); + } + } + }); + frame.setAttribute(element === "object" ? "data" : "src", child); + if (initialNameValue !== null) { + frame.setAttribute("name", initialNameValue); + } + t.add_cleanup(() => { + self.removeEventListener("message", listener); + frame.remove(); + }); + self.addEventListener("message", listener); + document.body.append(frame); + }, `${originType} <${element}${initialNameValue !== null ? ' name=' + initialNameValue : ''}>`); + }); + }); +});
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/windows/nested-browsing-contexts/resources/post-to-parent.html b/third_party/blink/web_tests/external/wpt/html/browsers/windows/nested-browsing-contexts/resources/post-to-parent.html new file mode 100644 index 0000000..302e9d9 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/browsers/windows/nested-browsing-contexts/resources/post-to-parent.html
@@ -0,0 +1,6 @@ +<script> +const ident = new URL(location).searchParams.get("ident"), + post = () => parent.postMessage({ name: window.name, ident }, "*"); +onmessage = () => post(); +post(); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/dom/interfaces.https_include=HTML._-expected.txt b/third_party/blink/web_tests/external/wpt/html/dom/interfaces.https_include=HTML._-expected.txt index 099799e..826eb52 100644 --- a/third_party/blink/web_tests/external/wpt/html/dom/interfaces.https_include=HTML._-expected.txt +++ b/third_party/blink/web_tests/external/wpt/html/dom/interfaces.https_include=HTML._-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 3589 tests; 3546 PASS, 43 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 3593 tests; 3546 PASS, 47 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS idl_test setup PASS Partial interface Document: original interface defined PASS Partial interface mixin NavigatorID: original interface mixin defined @@ -1460,6 +1460,8 @@ PASS HTMLFormElement interface: attribute name PASS HTMLFormElement interface: attribute noValidate PASS HTMLFormElement interface: attribute target +FAIL HTMLFormElement interface: attribute rel assert_true: The prototype object must have a property "rel" expected true got false +FAIL HTMLFormElement interface: attribute relList assert_true: The prototype object must have a property "relList" expected true got false PASS HTMLFormElement interface: attribute elements PASS HTMLFormElement interface: attribute length PASS HTMLFormElement interface: operation submit() @@ -1477,6 +1479,8 @@ PASS HTMLFormElement interface: document.createElement("form") must inherit property "name" with the proper type PASS HTMLFormElement interface: document.createElement("form") must inherit property "noValidate" with the proper type PASS HTMLFormElement interface: document.createElement("form") must inherit property "target" with the proper type +FAIL HTMLFormElement interface: document.createElement("form") must inherit property "rel" with the proper type assert_inherits: property "rel" not found in prototype chain +FAIL HTMLFormElement interface: document.createElement("form") must inherit property "relList" with the proper type assert_inherits: property "relList" not found in prototype chain PASS HTMLFormElement interface: document.createElement("form") must inherit property "elements" with the proper type PASS HTMLFormElement interface: document.createElement("form") must inherit property "length" with the proper type PASS HTMLFormElement interface: document.createElement("form") must inherit property "submit()" with the proper type
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/rel-base-target.html b/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/rel-base-target.html new file mode 100644 index 0000000..222be95 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/rel-base-target.html
@@ -0,0 +1,13 @@ +<!DOCTYPE html> +<title><form rel> with <base target></title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src=resources/reltester.js></script> +<base target=_blank> +<div id=log></div> +<form action=resources/endpoint.html><input type=hidden name=channelname></form> +<script> +const submitter = document.querySelector("form"), + channelInput = document.querySelector("input"); +relTester(submitter, channelInput, "<base target>"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/rel-button-target.html b/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/rel-button-target.html new file mode 100644 index 0000000..76fa868 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/rel-button-target.html
@@ -0,0 +1,12 @@ +<!DOCTYPE html> +<title><form rel> with <button formtarget></title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src=resources/reltester.js></script> +<div id=log></div> +<form action=resources/endpoint.html><input type=hidden name=channelname><button type=submit formtarget=_blank></form> +<script> +const submitter = document.querySelector("button"), + channelInput = document.querySelector("input"); +relTester(submitter, channelInput, "<button formtarget>"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/rel-form-target.html b/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/rel-form-target.html new file mode 100644 index 0000000..58611f41a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/rel-form-target.html
@@ -0,0 +1,12 @@ +<!DOCTYPE html> +<title><form rel target></title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src=resources/reltester.js></script> +<div id=log></div> +<form action=resources/endpoint.html target=_blank><input type=hidden name=channelname></form> +<script> +const submitter = document.querySelector("form"), + channelInput = document.querySelector("input"); +relTester(submitter, channelInput, "<form target>"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/rel-input-target.html b/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/rel-input-target.html new file mode 100644 index 0000000..b80e0240 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/rel-input-target.html
@@ -0,0 +1,13 @@ +<!DOCTYPE html> +<title><form rel> with <input formtarget></title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src=resources/reltester.js></script> +<base target=_blank> +<div id=log></div> +<form action=resources/endpoint.html><input type=hidden name=channelname><input type=submit formtarget=_blank></form> +<script> +const submitter = document.querySelector("input[type=submit]"), + channelInput = document.querySelector("input"); +relTester(submitter, channelInput, "<input formtarget>"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/resources/endpoint.html b/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/resources/endpoint.html new file mode 100644 index 0000000..be9e794 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/resources/endpoint.html
@@ -0,0 +1,11 @@ +<script> + const channelName = new URL(location).searchParams.get("channelname"), + channel = new BroadcastChannel(channelName); + channel.postMessage({ haveOpener: window.opener !== null, + referrer: document.referrer }); + // Because messages are not delivered synchronously and because closing a + // browsing context prompts the eventual clearing of all task sources, this + // document should not be closed until the opener document has confirmed + // receipt. + channel.onmessage = () => window.close(); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/resources/reltester.js b/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/resources/reltester.js new file mode 100644 index 0000000..0fa9774 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/form-submission-target/resources/reltester.js
@@ -0,0 +1,65 @@ +function relTester(submitter, channelInput, title) { + [ + { + rel: "", + exposed: "all" + }, + { + rel: "noopener", + exposed: "noopener" + }, + { + rel: "noreferrer", + exposed: "noreferrer" + }, + { + rel: "opener", + exposed: "all" + }, + { + rel: "noopener noreferrer", + exposed: "noreferrer" + }, + { + rel: "noreferrer opener", + exposed: "noreferrer" + }, + { + rel: "opener noopener", + exposed: "noopener" + } + ].forEach(relTest => { + // Use promise_test to submit only after one test concluded + promise_test(t => { + return new Promise(resolve => { + const channelName = Date.now() + relTest.rel, + channel = new BroadcastChannel(channelName); + let form = submitter; + if (submitter.localName !== "form") { + form = submitter.form; + } + form.rel = relTest.rel; + channelInput.value = channelName; + if (submitter.localName !== "form") { + submitter.click(); + } else { + submitter.submit(); + } + channel.onmessage = t.step_func(e => { + if (relTest.exposed === "all" || relTest.exposed === "noopener") { + assert_equals(e.data.referrer, window.location.href, "referrer"); + } else { + assert_equals(e.data.referrer, "", "referrer"); + } + if (relTest.exposed === "all") { + assert_true(e.data.haveOpener, "opener"); + } else { + assert_false(e.data.haveOpener, "opener"); + } + resolve(); + }); + t.add_cleanup(() => channel.postMessage(null)); + }); + }, `<form rel="${relTest.rel}"> with ${title}`); + }); +}
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/rellist-feature-detection-expected.txt b/third_party/blink/web_tests/external/wpt/html/semantics/rellist-feature-detection-expected.txt new file mode 100644 index 0000000..a00858d5f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/rellist-feature-detection-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL Make sure that relList based feature detection is working assert_true: tag = A, link type = opener must be supported expected true got false +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/rellist-feature-detection.html b/third_party/blink/web_tests/external/wpt/html/semantics/rellist-feature-detection.html index f4ce621..d290439 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/rellist-feature-detection.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/rellist-feature-detection.html
@@ -15,7 +15,7 @@ 'noreferrer', 'noopener'] }; link_support_table['a'] = { - supported : ['noreferrer', 'noopener'], + supported : ['noreferrer', 'noopener', 'opener'], unsupported : ['author', 'bookmark', 'external', 'help', 'license', 'nofollow', 'pingback', 'prev', 'search', 'tag', 'modulepreload', 'preload', 'preconnect', 'dns-prefetch', @@ -24,6 +24,7 @@ 'apple-touch-icon-precomposed', 'canonical'] }; link_support_table['area'] = link_support_table['a']; +link_support_table['form'] = link_support_table['form']; function test_rellist(tag_name, rel_table) { let element = document.createElement(tag_name); @@ -77,5 +78,6 @@ test_rellist('LINK', link_support_table['link']); test_rellist('A', link_support_table['a']); test_rellist('AREA', link_support_table['area']); + test_rellist('FORM', link_support_table['form']); }, 'Make sure that relList based feature detection is working'); </script>
diff --git a/third_party/blink/web_tests/external/wpt/interfaces/font-metrics-api.idl b/third_party/blink/web_tests/external/wpt/interfaces/font-metrics-api.idl index b13def2d..b38024e 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/font-metrics-api.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/font-metrics-api.idl
@@ -10,7 +10,7 @@ interface FontMetrics { readonly attribute double width; - readonly attribute sequence<double> advances; + readonly attribute FrozenArray<double> advances; readonly attribute double boundingBoxLeft; readonly attribute double boundingBoxRight; @@ -24,8 +24,8 @@ readonly attribute double fontBoundingBoxDescent; readonly attribute Baseline dominantBaseline; - readonly attribute sequence<Baseline> baselines; - readonly attribute sequence<Font> fonts; + readonly attribute FrozenArray<Baseline> baselines; + readonly attribute FrozenArray<Font> fonts; }; interface Baseline {
diff --git a/third_party/blink/web_tests/external/wpt/interfaces/html.idl b/third_party/blink/web_tests/external/wpt/interfaces/html.idl index 0d6445e..f530f355 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/html.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/html.idl
@@ -725,6 +725,8 @@ [CEReactions] attribute DOMString name; [CEReactions] attribute boolean noValidate; [CEReactions] attribute DOMString target; + [CEReactions] attribute DOMString rel; + [SameObject, PutForwards=value] readonly attribute DOMTokenList relList; [SameObject] readonly attribute HTMLFormControlsCollection elements; readonly attribute unsigned long length;
diff --git a/third_party/blink/web_tests/external/wpt/interfaces/storage.idl b/third_party/blink/web_tests/external/wpt/interfaces/storage.idl index 2960324..437bc6d 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/storage.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/storage.idl
@@ -5,7 +5,7 @@ [SecureContext] interface mixin NavigatorStorage { - readonly attribute StorageManager storage; + [SameObject] readonly attribute StorageManager storage; }; Navigator includes NavigatorStorage; WorkerNavigator includes NavigatorStorage;
diff --git a/third_party/blink/web_tests/external/wpt/interfaces/web-nfc.idl b/third_party/blink/web_tests/external/wpt/interfaces/web-nfc.idl index 5a6d6f8..913d1fe8 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/web-nfc.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/web-nfc.idl
@@ -75,10 +75,4 @@ USVString url = ""; NFCRecordType recordType; USVString mediaType = ""; - NFCAccept accept = "web-nfc-only"; -}; - -enum NFCAccept { - "web-nfc-only", - "any" };
diff --git a/third_party/blink/web_tests/external/wpt/kv-storage/backingstore.https.html b/third_party/blink/web_tests/external/wpt/kv-storage/backingstore.https.html new file mode 100644 index 0000000..44e634d8 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/kv-storage/backingstore.https.html
@@ -0,0 +1,33 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>KV Storage: backingStore getter</title> +<!-- See https://github.com/WICG/kv-storage/issues/45 --> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<script type="module"> +import { storage } from "std:kv-storage"; + +test(() => { + assert_equals(storage.backingStore, storage.backingStore); +}, "backingStore must return the same object each time"); + +test(() => { + assert_true(Object.isFrozen(storage.backingStore)); +}, "backingStore must be a frozen object"); + +test(() => { + const { backingStore } = storage; + assert_array_equals(Object.keys(backingStore), ["database", "store", "version"], "property names"); + assert_array_equals(Object.getOwnPropertySymbols(backingStore), [], "no symbols") + assert_own_property(backingStore, "database"); + assert_own_property(backingStore, "store"); + assert_own_property(backingStore, "version"); + assert_equals(Object.getPrototypeOf(backingStore), Object.prototype); + + assert_equals(backingStore.database, "kv-storage:default"); + assert_equals(backingStore.store, "store"); + assert_equals(backingStore.version, 1); +}, "backingStore object must have the right shape"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/kv-storage/cause-errors-via-idb.https.html b/third_party/blink/web_tests/external/wpt/kv-storage/cause-errors-via-idb.https.html index 21fe36b..d77e566 100644 --- a/third_party/blink/web_tests/external/wpt/kv-storage/cause-errors-via-idb.https.html +++ b/third_party/blink/web_tests/external/wpt/kv-storage/cause-errors-via-idb.https.html
@@ -7,7 +7,7 @@ <script src="/IndexedDB/support-promises.js"></script> <script type="module"> -import { testWithArea } from "./helpers/kvs-tests.js"; +import { testWithArea, testWithAreaNoCleanup } from "./helpers/kvs-tests.js"; const mustFail = { "set()": area => area.set(1, "value 1"), @@ -29,7 +29,7 @@ for (const [method, testFn] of Object.entries(mustFail)) { testWithArea(async (area, t) => { - const { database, store, version } = area.backingStore; + const { database, version } = area.backingStore; const db = await migrateNamedDatabase(t, database, version + 1, () => {}); const result = testFn(area); @@ -37,8 +37,8 @@ await promise_rejects(t, "VersionError", result); }, `${method}: upgrading the database must cause a "VersionError" DOMException`); - testWithArea(async (area, t) => { - const { database, store } = area.backingStore; + testWithAreaNoCleanup(async (area, t) => { + const { database } = area.backingStore; // Set up a new database with that name, but with no object stores! // NB: this depends on the fact that createNameDatabase sets the initial version to 1, which is @@ -47,7 +47,69 @@ const result = testFn(area); - await promise_rejects(t, "NotFoundError", result); - }, `${method}: creating a same-named database with no object store must cause a "NotFoundError" DOMException`); + await promise_rejects(t, "InvalidStateError", result); + }, `${method}: creating a same-named database with no object store must cause an "InvalidStateError" DOMException`); + + testWithAreaNoCleanup(async (area, t) => { + const { database } = area.backingStore; + + const db = await createNamedDatabase(t, database, db => { + db.createObjectStore("wrongName"); + }); + + const result = testFn(area); + + await promise_rejects(t, "InvalidStateError", result); + }, `${method}: creating a same-named database with a single object store with the wrong name must cause an "InvalidStateError" DOMException`); + + testWithAreaNoCleanup(async (area, t) => { + const { database, store } = area.backingStore; + + const db = await createNamedDatabase(t, database, db => { + db.createObjectStore(store); + db.createObjectStore("wrongName"); + }); + + const result = testFn(area); + + await promise_rejects(t, "InvalidStateError", result); + }, `${method}: creating a same-named database with more than one object store must cause an "InvalidStateError" DOMException`); + + testWithAreaNoCleanup(async (area, t) => { + const { database, store } = area.backingStore; + + const db = await createNamedDatabase(t, database, db => { + db.createObjectStore(store, { autoIncrement: true }); + }); + + const result = testFn(area); + + await promise_rejects(t, "InvalidStateError", result); + }, `${method}: creating a same-named database the right object store but a bad schema (autoIncrement = true) must cause an "InvalidStateError" DOMException`); + + testWithAreaNoCleanup(async (area, t) => { + const { database, store } = area.backingStore; + + const db = await createNamedDatabase(t, database, db => { + db.createObjectStore(store, { keyPath: "somekey" }); + }); + + const result = testFn(area); + + await promise_rejects(t, "InvalidStateError", result); + }, `${method}: creating a same-named database the right object store but a bad schema (keyPath != null) must cause an "InvalidStateError" DOMException`); + + testWithAreaNoCleanup(async (area, t) => { + const { database, store } = area.backingStore; + + const db = await createNamedDatabase(t, database, db => { + const s = db.createObjectStore(store); + s.createIndex("index", "indexKey"); + }); + + const result = testFn(area); + + await promise_rejects(t, "InvalidStateError", result); + }, `${method}: creating a same-named database the right object store but a bad schema (has indices) must cause an "InvalidStateError" DOMException`); } </script>
diff --git a/third_party/blink/web_tests/external/wpt/kv-storage/helpers/kvs-tests.js b/third_party/blink/web_tests/external/wpt/kv-storage/helpers/kvs-tests.js index a6c4d58..0cf4c2fd 100644 --- a/third_party/blink/web_tests/external/wpt/kv-storage/helpers/kvs-tests.js +++ b/third_party/blink/web_tests/external/wpt/kv-storage/helpers/kvs-tests.js
@@ -1,6 +1,17 @@ import { StorageArea, storage as defaultArea } from "std:kv-storage"; import { assertAsyncIteratorEquals, assertAsyncIteratorCustomEquals } from "./equality-asserters.js"; +// Used when we're manually creating the database, and so the IDB helpers also want to clean it up. +// If we used testWithArea, then the IDB helpers would time out in their cleanup steps when they +// fail to delete the already-deleted database. +export function testWithAreaNoCleanup(testFn, description) { + promise_test(t => { + const area = new StorageArea(description); + + return testFn(area, t); + }, description); +} + export function testWithArea(testFn, description) { promise_test(t => { const area = new StorageArea(description);
diff --git a/third_party/blink/web_tests/external/wpt/kv-storage/storage-smoke-test.https.html b/third_party/blink/web_tests/external/wpt/kv-storage/storage-smoke-test.https.html index df6fd8c..da48dc7 100644 --- a/third_party/blink/web_tests/external/wpt/kv-storage/storage-smoke-test.https.html +++ b/third_party/blink/web_tests/external/wpt/kv-storage/storage-smoke-test.https.html
@@ -9,19 +9,6 @@ import { testVariousMethodsWithDefaultArea } from "./helpers/kvs-tests.js"; import { storage } from "std:kv-storage"; -test(() => { - const { backingStore } = storage; - assert_array_equals(Object.keys(backingStore), ["database", "store", "version"]); - assert_own_property(backingStore, "database"); - assert_own_property(backingStore, "store"); - assert_own_property(backingStore, "version"); - assert_equals(Object.getPrototypeOf(backingStore), Object.prototype); - - assert_equals(backingStore.database, "kv-storage:default"); - assert_equals(backingStore.store, "store"); - assert_equals(backingStore.version, 1); -}, "backingStore returns the correct object"); - testVariousMethodsWithDefaultArea( "Storage methods smoke test with string key and value", "key", "value", assert_equals );
diff --git a/third_party/blink/web_tests/external/wpt/resources/testdriver.js b/third_party/blink/web_tests/external/wpt/resources/testdriver.js index ea380dbd..09a15e1 100644 --- a/third_party/blink/web_tests/external/wpt/resources/testdriver.js +++ b/third_party/blink/web_tests/external/wpt/resources/testdriver.js
@@ -197,27 +197,70 @@ } }; - window.test_driver_internal = { + var manual = { /** - * Triggers a user-initiated click + * This flag should be set to `true` by any code which implements the + * internal methods defined below for automation purposes. Doing so + * allows the library to signal failure immediately when an automated + * implementation of one of the methods is not available. + */ + in_automation: false, + + /** + * Waits for a user-initiated click * * @param {Element} element - element to be clicked * @param {{x: number, y: number} coords - viewport coordinates to click at - * @returns {Promise} fulfilled after click occurs or rejected if click fails + * @returns {Promise} fulfilled after click occurs */ click: function(element, coords) { - return Promise.reject(new Error("unimplemented")); + if (this.in_automation) { + return Promise.reject(new Error('Not implemented')); + } + + return new Promise(function(resolve, reject) { + element.addEventListener("click", resolve); + }); }, /** - * Triggers a user-initiated click + * Waits for an element to receive a series of key presses * - * @param {Element} element - element to be clicked - * @param {String} keys - keys to send to the element - * @returns {Promise} fulfilled after keys are sent or rejected if click fails + * @param {Element} element - element which should receve key presses + * @param {String} keys - keys to expect + * @returns {Promise} fulfilled after keys are received or rejected if + * an incorrect key sequence is received */ send_keys: function(element, keys) { - return Promise.reject(new Error("unimplemented")); + if (this.in_automation) { + return Promise.reject(new Error('Not implemented')); + } + + return new Promise(function(resolve, reject) { + var seen = ""; + + function remove() { + element.removeEventListener("keydown", onKeyDown); + } + + function onKeyDown(event) { + if (event.key.length > 1) { + return; + } + + seen += event.key; + + if (keys.indexOf(seen) !== 0) { + reject(new Error("Unexpected key sequence: " + seen)); + remove(); + } else if (seen === keys) { + resolve(); + remove(); + } + } + + element.addEventListener("keydown", onKeyDown); + }); }, /** @@ -240,4 +283,7 @@ return Promise.reject(new Error("unimplemented")); } }; + + window.test_driver_internal = Object.create(manual); + })();
diff --git a/third_party/blink/web_tests/fast/spatial-navigation/snav-focusless-interested-element-indicated-expected.html b/third_party/blink/web_tests/fast/spatial-navigation/snav-focusless-interested-element-indicated-expected.html index 3b8f796d..83dbcf4 100644 --- a/third_party/blink/web_tests/fast/spatial-navigation/snav-focusless-interested-element-indicated-expected.html +++ b/third_party/blink/web_tests/fast/spatial-navigation/snav-focusless-interested-element-indicated-expected.html
@@ -13,5 +13,5 @@ <div id="third" tabindex="0">Third</div> <script> - document.getElementById("second").focus(); + document.getElementById("second").style.cssText = "outline: auto 5px -webkit-focus-ring-color !important; box-shadow: none !important"; </script>
diff --git a/third_party/blink/web_tests/platform/linux/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-force-focusring-expected.png b/third_party/blink/web_tests/platform/linux/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-force-focusring-expected.png deleted file mode 100644 index e10645c6..0000000 --- a/third_party/blink/web_tests/platform/linux/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-force-focusring-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-multiple-select-focusring-expected.png b/third_party/blink/web_tests/platform/linux/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-multiple-select-focusring-expected.png deleted file mode 100644 index 4a507499..0000000 --- a/third_party/blink/web_tests/platform/linux/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-multiple-select-focusring-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.10/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-multiple-select-focusring-expected.png b/third_party/blink/web_tests/platform/mac-mac10.10/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-multiple-select-focusring-expected.png deleted file mode 100644 index eec4c16..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.10/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-multiple-select-focusring-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.11/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-multiple-select-focusring-expected.png b/third_party/blink/web_tests/platform/mac-mac10.11/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-multiple-select-focusring-expected.png deleted file mode 100644 index 07c87b2..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.11/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-multiple-select-focusring-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-force-focusring-expected.png b/third_party/blink/web_tests/platform/mac/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-force-focusring-expected.png deleted file mode 100644 index a702d67..0000000 --- a/third_party/blink/web_tests/platform/mac/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-force-focusring-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-multiple-select-focusring-expected.png b/third_party/blink/web_tests/platform/mac/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-multiple-select-focusring-expected.png deleted file mode 100644 index d1ffa7e..0000000 --- a/third_party/blink/web_tests/platform/mac/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-multiple-select-focusring-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-force-focusring-expected.png b/third_party/blink/web_tests/platform/win/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-force-focusring-expected.png deleted file mode 100644 index 6cdbe8e6..0000000 --- a/third_party/blink/web_tests/platform/win/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-force-focusring-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-multiple-select-focusring-expected.png b/third_party/blink/web_tests/platform/win/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-multiple-select-focusring-expected.png deleted file mode 100644 index 7538c3c..0000000 --- a/third_party/blink/web_tests/platform/win/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-multiple-select-focusring-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/virtual/spatial-navigation-force-outline/fast/spatial-navigation/README.txt b/third_party/blink/web_tests/virtual/spatial-navigation-force-outline/fast/spatial-navigation/README.txt deleted file mode 100644 index a278f14..0000000 --- a/third_party/blink/web_tests/virtual/spatial-navigation-force-outline/fast/spatial-navigation/README.txt +++ /dev/null
@@ -1,3 +0,0 @@ -# This suite tests modifications to the spatial navigation implementation -# under development. -# It sets "--enable-blink-features=SpatialNavigationForcesOutline"
diff --git a/third_party/blink/web_tests/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-force-focusring.html b/third_party/blink/web_tests/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-force-focusring.html deleted file mode 100644 index 9ecf4b2..0000000 --- a/third_party/blink/web_tests/virtual/spatial-navigation-force-outline/fast/spatial-navigation/snav-force-focusring.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<body> -<style> -:focus { - outline: 0; - box-shadow: 0 0 2px green; -} -</style> -<p><a id="start" href="#link1">Link 1</a></p> -<p><a id="end" href="#link2">Link 2</a></p> - -<script> -if (window.testRunner) { - testRunner.overridePreference("WebKitTabToLinksPreferenceKey", 1); - testRunner.overridePreference("WebKitSpatialNavigationEnabled", 1); -} - -if (window.eventSender) { - // Start at a known place. - document.getElementById("start").focus(); - // Focus should move to the second link, and focus ring should be be the - // default focus ring (not hidden), and without the green box-shadow. - eventSender.keyDown('ArrowDown'); -} - -</script> -</body>
diff --git a/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt index 2f906b0..d57c9c3 100644 --- a/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt
@@ -1138,6 +1138,18 @@ getter interval getter rotationRate method constructor +interface DeviceMotionEventAcceleration + attribute @@toStringTag + getter x + getter y + getter z + method constructor +interface DeviceMotionEventRotationRate + attribute @@toStringTag + getter alpha + getter beta + getter gamma + method constructor interface DeviceOrientationEvent : Event attribute @@toStringTag getter absolute
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt index 7756595..56108888 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt
@@ -1497,6 +1497,18 @@ getter interval getter rotationRate method constructor +interface DeviceMotionEventAcceleration + attribute @@toStringTag + getter x + getter y + getter z + method constructor +interface DeviceMotionEventRotationRate + attribute @@toStringTag + getter alpha + getter beta + getter gamma + method constructor interface DeviceOrientationEvent : Event attribute @@toStringTag getter absolute
diff --git a/third_party/inspector_protocol/README.chromium b/third_party/inspector_protocol/README.chromium index 8eff550..5186ba0 100644 --- a/third_party/inspector_protocol/README.chromium +++ b/third_party/inspector_protocol/README.chromium
@@ -2,7 +2,7 @@ Short Name: inspector_protocol URL: https://chromium.googlesource.com/deps/inspector_protocol/ Version: 0 -Revision: 260f38186f3d6d8475cc10f9373e806764cf21a4 +Revision: b9f19d327ece7e05c74898fbb6fdc551c6d3f344 License: BSD License File: LICENSE Security Critical: no
diff --git a/third_party/inspector_protocol/encoding/cbor.cc b/third_party/inspector_protocol/encoding/cbor.cc index 7e6cfc11..9ff93da 100644 --- a/third_party/inspector_protocol/encoding/cbor.cc +++ b/third_party/inspector_protocol/encoding/cbor.cc
@@ -258,7 +258,7 @@ assert(!envelopes_.empty()); envelopes_.back().EncodeStop(out_); envelopes_.pop_back(); - }; + } void HandleArrayBegin() override { envelopes_.emplace_back(); @@ -271,7 +271,7 @@ assert(!envelopes_.empty()); envelopes_.back().EncodeStop(out_); envelopes_.pop_back(); - }; + } void HandleString16(std::vector<uint16_t> chars) override { for (uint16_t ch : chars) { @@ -290,7 +290,7 @@ EncodeBinary(span<uint8_t>(bytes.data(), bytes.size()), out_); } - void HandleDouble(double value) override { EncodeDouble(value, out_); }; + void HandleDouble(double value) override { EncodeDouble(value, out_); } void HandleInt32(int32_t value) override { EncodeInt32(value, out_); } @@ -722,4 +722,73 @@ status_.error = error; } +#if 0 +void DumpCBOR(span<uint8_t> cbor) { + std::string indent; + CBORTokenizer tokenizer(cbor); + while (true) { + fprintf(stderr, "%s", indent.c_str()); + switch (tokenizer.TokenTag()) { + case CBORTokenTag::ERROR_VALUE: + fprintf(stderr, "ERROR {status.error=%d, status.pos=%ld}\n", + tokenizer.Status().error, tokenizer.Status().pos); + return; + case CBORTokenTag::DONE: + fprintf(stderr, "DONE\n"); + return; + case CBORTokenTag::TRUE_VALUE: + fprintf(stderr, "TRUE_VALUE\n"); + break; + case CBORTokenTag::FALSE_VALUE: + fprintf(stderr, "FALSE_VALUE\n"); + break; + case CBORTokenTag::NULL_VALUE: + fprintf(stderr, "NULL_VALUE\n"); + break; + case CBORTokenTag::INT32: + fprintf(stderr, "INT32 [%d]\n", tokenizer.GetInt32()); + break; + case CBORTokenTag::DOUBLE: + fprintf(stderr, "DOUBLE [%lf]\n", tokenizer.GetDouble()); + break; + case CBORTokenTag::STRING8: { + span<uint8_t> v = tokenizer.GetString8(); + std::string t(v.begin(), v.end()); + fprintf(stderr, "STRING8 [%s]\n", t.c_str()); + break; + } + case CBORTokenTag::STRING16: { + span<uint8_t> v = tokenizer.GetString16WireRep(); + std::string t(v.begin(), v.end()); + fprintf(stderr, "STRING16 [%s]\n", t.c_str()); + break; + } + case CBORTokenTag::BINARY: { + span<uint8_t> v = tokenizer.GetBinary(); + std::string t(v.begin(), v.end()); + fprintf(stderr, "BINARY [%s]\n", t.c_str()); + break; + } + case CBORTokenTag::MAP_START: + fprintf(stderr, "MAP_START\n"); + indent += " "; + break; + case CBORTokenTag::ARRAY_START: + fprintf(stderr, "ARRAY_START\n"); + indent += " "; + break; + case CBORTokenTag::STOP: + fprintf(stderr, "STOP\n"); + indent.erase(0, 2); + break; + case CBORTokenTag::ENVELOPE: + fprintf(stderr, "ENVELOPE\n"); + tokenizer.EnterEnvelope(); + continue; + } + tokenizer.Next(); + } +} +#endif + } // namespace inspector_protocol
diff --git a/third_party/inspector_protocol/encoding/cbor.h b/third_party/inspector_protocol/encoding/cbor.h index 03e8c74..c4b3c30 100644 --- a/third_party/inspector_protocol/encoding/cbor.h +++ b/third_party/inspector_protocol/encoding/cbor.h
@@ -263,5 +263,8 @@ cbor::MajorType token_start_type_; uint64_t token_start_internal_value_; }; + +void DumpCBOR(span<uint8_t> cbor); + } // namespace inspector_protocol #endif // INSPECTOR_PROTOCOL_ENCODING_CBOR_H_
diff --git a/third_party/inspector_protocol/lib/CBOR_cpp.template b/third_party/inspector_protocol/lib/CBOR_cpp.template index 32d1b9b..97ae156b 100644 --- a/third_party/inspector_protocol/lib/CBOR_cpp.template +++ b/third_party/inspector_protocol/lib/CBOR_cpp.template
@@ -728,6 +728,75 @@ status_.error = error; } +#if 0 +void DumpCBOR(span<uint8_t> cbor) { + std::string indent; + CBORTokenizer tokenizer(cbor); + while (true) { + fprintf(stderr, "%s", indent.c_str()); + switch (tokenizer.TokenTag()) { + case CBORTokenTag::ERROR_VALUE: + fprintf(stderr, "ERROR {status.error=%d, status.pos=%ld}\n", + tokenizer.Status().error, tokenizer.Status().pos); + return; + case CBORTokenTag::DONE: + fprintf(stderr, "DONE\n"); + return; + case CBORTokenTag::TRUE_VALUE: + fprintf(stderr, "TRUE_VALUE\n"); + break; + case CBORTokenTag::FALSE_VALUE: + fprintf(stderr, "FALSE_VALUE\n"); + break; + case CBORTokenTag::NULL_VALUE: + fprintf(stderr, "NULL_VALUE\n"); + break; + case CBORTokenTag::INT32: + fprintf(stderr, "INT32 [%d]\n", tokenizer.GetInt32()); + break; + case CBORTokenTag::DOUBLE: + fprintf(stderr, "DOUBLE [%lf]\n", tokenizer.GetDouble()); + break; + case CBORTokenTag::STRING8: { + span<uint8_t> v = tokenizer.GetString8(); + std::string t(v.begin(), v.end()); + fprintf(stderr, "STRING8 [%s]\n", t.c_str()); + break; + } + case CBORTokenTag::STRING16: { + span<uint8_t> v = tokenizer.GetString16WireRep(); + std::string t(v.begin(), v.end()); + fprintf(stderr, "STRING16 [%s]\n", t.c_str()); + break; + } + case CBORTokenTag::BINARY: { + span<uint8_t> v = tokenizer.GetBinary(); + std::string t(v.begin(), v.end()); + fprintf(stderr, "BINARY [%s]\n", t.c_str()); + break; + } + case CBORTokenTag::MAP_START: + fprintf(stderr, "MAP_START\n"); + indent += " "; + break; + case CBORTokenTag::ARRAY_START: + fprintf(stderr, "ARRAY_START\n"); + indent += " "; + break; + case CBORTokenTag::STOP: + fprintf(stderr, "STOP\n"); + indent.erase(0, 2); + break; + case CBORTokenTag::ENVELOPE: + fprintf(stderr, "ENVELOPE\n"); + tokenizer.EnterEnvelope(); + continue; + } + tokenizer.Next(); + } +} +#endif + {% for namespace in config.protocol.namespace %} } // namespace {{namespace}}
diff --git a/third_party/inspector_protocol/lib/CBOR_h.template b/third_party/inspector_protocol/lib/CBOR_h.template index f8d0620..dd637f1 100644 --- a/third_party/inspector_protocol/lib/CBOR_h.template +++ b/third_party/inspector_protocol/lib/CBOR_h.template
@@ -407,6 +407,9 @@ uint64_t token_start_internal_value_; }; +void DumpCBOR(span<uint8_t> cbor); + + {% for namespace in config.protocol.namespace %} } // namespace {{namespace}} {% endfor %}
diff --git a/third_party/inspector_protocol/lib/ValueConversions_h.template b/third_party/inspector_protocol/lib/ValueConversions_h.template index 49ae9e2..2ee5b72 100644 --- a/third_party/inspector_protocol/lib/ValueConversions_h.template +++ b/third_party/inspector_protocol/lib/ValueConversions_h.template
@@ -105,12 +105,17 @@ struct ValueConversions<Binary> { static Binary fromValue(protocol::Value* value, ErrorSupport* errors) { - String result; - bool success = value ? value->asString(&result) : false; - if (!success) { - errors->addError("string value expected"); + if (!value || + (value->type() != Value::TypeBinary && value->type() != Value::TypeString)) { + errors->addError("Either string base64 or binary value expected"); return Binary(); } + Binary binary; + if (value->asBinary(&binary)) + return binary; + String result; + value->asString(&result); + bool success; Binary out = Binary::fromBase64(result, &success); if (!success) errors->addError("base64 decoding error"); @@ -119,7 +124,7 @@ static std::unique_ptr<protocol::Value> toValue(const Binary& value) { - return StringValue::create(value.toBase64()); + return BinaryValue::create(value); } };
diff --git a/third_party/inspector_protocol/lib/Values_cpp.template b/third_party/inspector_protocol/lib/Values_cpp.template index 6b4a7856..4b4ba99 100644 --- a/third_party/inspector_protocol/lib/Values_cpp.template +++ b/third_party/inspector_protocol/lib/Values_cpp.template
@@ -139,6 +139,7 @@ return nullptr; case CBORTokenTag::BINARY: { span<uint8_t> payload = tokenizer->GetBinary(); + tokenizer->Next(); return BinaryValue::create(Binary::fromSpan(payload.data(), payload.size())); } case CBORTokenTag::MAP_START: @@ -169,6 +170,7 @@ if (tokenizer->TokenTag() == CBORTokenTag::STRING8) { span<uint8_t> key_span = tokenizer->GetString8(); key = StringUtil::fromUTF8(key_span.data(), key_span.size()); + tokenizer->Next(); } else if (tokenizer->TokenTag() == CBORTokenTag::STRING16) { return nullptr; // STRING16 not supported yet. } else { @@ -178,6 +180,7 @@ // Parse value. auto value = parseValue(stack_depth, tokenizer); if (!value) return nullptr; + dict->setValue(key, std::move(value)); } tokenizer->Next(); return dict;
diff --git a/third_party/inspector_protocol/lib/Values_h.template b/third_party/inspector_protocol/lib/Values_h.template index 87ec007..4a2e58f4 100644 --- a/third_party/inspector_protocol/lib/Values_h.template +++ b/third_party/inspector_protocol/lib/Values_h.template
@@ -39,7 +39,8 @@ TypeBinary, TypeObject, TypeArray, - TypeSerialized + TypeSerialized, + TypeImported }; ValueType type() const { return m_type; }
diff --git a/third_party/inspector_protocol/templates/Exported_h.template b/third_party/inspector_protocol/templates/Exported_h.template index 4ea9167..765f6c21 100644 --- a/third_party/inspector_protocol/templates/Exported_h.template +++ b/third_party/inspector_protocol/templates/Exported_h.template
@@ -15,6 +15,17 @@ {% for namespace in config.protocol.namespace %} namespace {{namespace}} { {% endfor %} + +#ifndef {{"_".join(config.protocol.namespace)}}_exported_api_h +#define {{"_".join(config.protocol.namespace)}}_exported_api_h +class {{config.exported.export_macro}} Exported { +public: + virtual {{config.exported.string_out}} toJSONString() const = 0; + virtual void writeBinary(std::vector<uint8_t>* out) const = 0; + virtual ~Exported() { } +}; +#endif // !defined({{"_".join(config.protocol.namespace)}}_exported_api_h) + namespace {{domain.domain}} { namespace API { @@ -48,11 +59,8 @@ {% for type in domain.types %} {% if not (type.type == "object") or not ("properties" in type) or not protocol.is_exported(domain.domain, type.id) %}{% continue %}{% endif %} -class {{config.exported.export_macro}} {{type.id}} { +class {{config.exported.export_macro}} {{type.id}} : public Exported { public: - virtual {{config.exported.string_out}} toJSONString() const = 0; - virtual std::vector<uint8_t> toBinary() const = 0; - virtual ~{{type.id}}() { } static std::unique_ptr<protocol::{{domain.domain}}::API::{{type.id}}> fromJSONString(const {{config.exported.string_in}}& json); static std::unique_ptr<protocol::{{domain.domain}}::API::{{type.id}}> fromBinary(const uint8_t* data, size_t length); };
diff --git a/third_party/inspector_protocol/templates/Imported_h.template b/third_party/inspector_protocol/templates/Imported_h.template index 90fe10a..f2e576a9 100644 --- a/third_party/inspector_protocol/templates/Imported_h.template +++ b/third_party/inspector_protocol/templates/Imported_h.template
@@ -17,6 +17,37 @@ {% for namespace in config.protocol.namespace %} namespace {{namespace}} { {% endfor %} + +using Exported = {{"::".join(config.imported.namespace)}}::Exported; + +#ifndef {{"_".join(config.protocol.namespace)}}_imported_imported_h +#define {{"_".join(config.protocol.namespace)}}_imported_imported_h + +class {{config.lib.export_macro}} ImportedValue : public Value { +public: + static std::unique_ptr<ImportedValue> fromExported(const Exported* value) { + return std::unique_ptr<ImportedValue>(new ImportedValue(value)); + } + + void writeJSON(StringBuilder* output) const override { + auto json = m_exported->toJSONString(); + String local_json = ({{config.imported.from_imported_string % "std::move(json)"}}); + StringUtil::builderAppend(*output, local_json); + } + void writeBinary(std::vector<uint8_t>* output) const override { + m_exported->writeBinary(output); + } + std::unique_ptr<Value> clone() const override { + return std::unique_ptr<Value>(new ImportedValue(m_exported)); + } + +private: + explicit ImportedValue(const Exported* exported) : Value(TypeImported), m_exported(exported) { } + const Exported* m_exported; +}; + +#endif // !defined({{"_".join(config.protocol.namespace)}}_imported_imported_h) + {% for type in domain.types %} {% if not (type.type == "object") or not ("properties" in type) or not protocol.is_imported(domain.domain, type.id) %}{% continue %}{% endif %} @@ -29,21 +60,17 @@ return nullptr; } - // TODO(pfeldman): toggle to true and delete the json branch when binary is ready. - std::unique_ptr<{{"::".join(config.imported.namespace)}}::{{domain.domain}}::API::{{type.id}}> result; - String json = value->serializeToJSON(); - result = {{"::".join(config.imported.namespace)}}::{{domain.domain}}::API::{{type.id}}::fromJSONString({{config.imported.to_imported_string % "json"}}); + std::vector<uint8_t> binary; + value->writeBinary(&binary); + auto result = {{"::".join(config.imported.namespace)}}::{{domain.domain}}::API::{{type.id}}::fromBinary(binary.data(), binary.size()); if (!result) errors->addError("cannot parse"); return result; } - static std::unique_ptr<protocol::Value> toValue(const {{"::".join(config.imported.namespace)}}::{{domain.domain}}::API::{{type.id}}* value) + static std::unique_ptr<protocol::Value> toValue(const {{"::".join(config.imported.namespace)}}::{{domain.domain}}::API::{{type.id}}* exported) { - // TODO(pfeldman): toggle to true and delete the json branch when binary is ready. - auto json = value->toJSONString(); - String local_json = ({{config.imported.from_imported_string % "std::move(json)"}}); - return SerializedValue::fromJSON(local_json); + return ImportedValue::fromExported(exported); } static std::unique_ptr<protocol::Value> toValue(const std::unique_ptr<{{"::".join(config.imported.namespace)}}::{{domain.domain}}::API::{{type.id}}>& value) @@ -51,6 +78,7 @@ return toValue(value.get()); } }; + {% endfor %} {% for namespace in config.protocol.namespace %}
diff --git a/third_party/inspector_protocol/templates/TypeBuilder_cpp.template b/third_party/inspector_protocol/templates/TypeBuilder_cpp.template index 07e45a3..4ef60a6 100644 --- a/third_party/inspector_protocol/templates/TypeBuilder_cpp.template +++ b/third_party/inspector_protocol/templates/TypeBuilder_cpp.template
@@ -105,9 +105,9 @@ return {{config.exported.to_string_out % "json"}}; } -std::vector<uint8_t> {{type.id}}::toBinary() const +void {{type.id}}::writeBinary(std::vector<uint8_t>* out) const { - return toValue()->serializeToBinary(); + toValue()->writeBinary(out); } // static
diff --git a/third_party/inspector_protocol/templates/TypeBuilder_h.template b/third_party/inspector_protocol/templates/TypeBuilder_h.template index c5e95d7..c670d65 100644 --- a/third_party/inspector_protocol/templates/TypeBuilder_h.template +++ b/third_party/inspector_protocol/templates/TypeBuilder_h.template
@@ -106,7 +106,7 @@ std::unique_ptr<{{type.id}}> clone() const; {% if protocol.is_exported(domain.domain, type.id) %} {{config.exported.string_out}} toJSONString() const override; - std::vector<uint8_t> toBinary() const override; + void writeBinary(std::vector<uint8_t>* out) const override; {% endif %} template<int STATE>
diff --git a/third_party/zlib/arm_features.c b/third_party/zlib/arm_features.c index a91030d..f91897d 100644 --- a/third_party/zlib/arm_features.c +++ b/third_party/zlib/arm_features.c
@@ -4,14 +4,15 @@ * Use of this source code is governed by a BSD-style license that can be * found in the Chromium source repository LICENSE file. */ -#include "arm_features.h" +#include "arm_features.h" #include "zutil.h" int ZLIB_INTERNAL arm_cpu_enable_crc32 = 0; int ZLIB_INTERNAL arm_cpu_enable_pmull = 0; #if !defined(_MSC_VER) + #include <pthread.h> #include <stdint.h> @@ -21,53 +22,54 @@ #include <asm/hwcap.h> #include <sys/auxv.h> #else -#error ### No ARM CPU features detection in your platform/OS +#error arm_features.c ARM feature detection in not defined for your platform #endif static pthread_once_t cpu_check_inited_once = PTHREAD_ONCE_INIT; -static void init_arm_features(void) -{ - uint64_t flag_crc32 = 0, flag_pmull = 0, capabilities = 0; - -#if defined(ARMV8_OS_ANDROID) - flag_crc32 = ANDROID_CPU_ARM_FEATURE_CRC32; - flag_pmull = ANDROID_CPU_ARM_FEATURE_PMULL; - capabilities = android_getCpuFeatures(); -#elif defined(ARMV8_OS_LINUX) - #if defined(__aarch64__) - flag_crc32 = HWCAP_CRC32; - flag_pmull = HWCAP_PMULL; - capabilities = getauxval(AT_HWCAP); - #elif defined(__ARM_NEON) || defined(__ARM_NEON__) - /* The use of HWCAP2 is for getting features of newer ARMv8-A SoCs - * while running in 32bits mode (i.e. aarch32). - */ - flag_crc32 = HWCAP2_CRC32; - flag_pmull = HWCAP2_PMULL; - capabilities = getauxval(AT_HWCAP2); - #endif -#endif - - if (capabilities & flag_crc32) - arm_cpu_enable_crc32 = 1; - - if (capabilities & flag_pmull) - arm_cpu_enable_pmull = 1; -} +static void _arm_check_features(void); void ZLIB_INTERNAL arm_check_features(void) { - pthread_once(&cpu_check_inited_once, init_arm_features); + pthread_once(&cpu_check_inited_once, _arm_check_features); } -#else + +/* + * See http://bit.ly/2CcoEsr for run-time detection of ARM features and also + * crbug.com/931275 for android_getCpuFeatures() use in the Android sandbox. + */ +static void _arm_check_features(void) +{ +#if defined(ARMV8_OS_ANDROID) && defined(__aarch64__) + uint64_t features = android_getCpuFeatures(); + arm_cpu_enable_crc32 = !!(features & ANDROID_CPU_ARM64_FEATURE_CRC32); + arm_cpu_enable_pmull = !!(features & ANDROID_CPU_ARM64_FEATURE_PMULL); +#elif defined(ARMV8_OS_ANDROID) /* aarch32 */ + uint64_t features = android_getCpuFeatures(); + arm_cpu_enable_crc32 = !!(features & ANDROID_CPU_ARM_FEATURE_CRC32); + arm_cpu_enable_pmull = !!(features & ANDROID_CPU_ARM_FEATURE_PMULL); +#elif defined(ARMV8_OS_LINUX) && defined(__aarch64__) + unsigned long features = getauxval(AT_HWCAP); + arm_cpu_enable_crc32 = !!(features & HWCAP_CRC32); + arm_cpu_enable_pmull = !!(features & HWCAP_PMULL); +#elif defined(ARMV8_OS_LINUX) && (defined(__ARM_NEON) || defined(__ARM_NEON__)) + /* Query HWCAP2 for ARMV8-A SoCs running in aarch32 mode */ + unsigned long features = getauxval(AT_HWCAP2); + arm_cpu_enable_crc32 = !!(features & HWCAP2_CRC32); + arm_cpu_enable_pmull = !!(features & HWCAP2_PMULL); +#endif + /* TODO(crbug.com/810125): add ARMV8_OS_ZIRCON support for fucshia */ +} + +#else /* _MSC_VER */ + #include <windows.h> +static INIT_ONCE cpu_check_inited_once = INIT_ONCE_STATIC_INIT; + static BOOL CALLBACK _arm_check_features(PINIT_ONCE once, PVOID param, PVOID *context); -static INIT_ONCE cpu_check_inited_once = INIT_ONCE_STATIC_INIT; - void ZLIB_INTERNAL arm_check_features(void) { @@ -87,4 +89,5 @@ return TRUE; } + #endif /* _MSC_VER */
diff --git a/tools/android/forwarder2/device_controller.cc b/tools/android/forwarder2/device_controller.cc index 19827a0..6be52be 100644 --- a/tools/android/forwarder2/device_controller.cc +++ b/tools/android/forwarder2/device_controller.cc
@@ -55,8 +55,8 @@ void DeviceController::AcceptHostCommandSoon() { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&DeviceController::AcceptHostCommandInternal, - base::Unretained(this))); + FROM_HERE, base::BindOnce(&DeviceController::AcceptHostCommandInternal, + base::Unretained(this))); } void DeviceController::AcceptHostCommandInternal() {
diff --git a/tools/android/forwarder2/device_forwarder_main.cc b/tools/android/forwarder2/device_forwarder_main.cc index 0efd61b0..2a6c753 100644 --- a/tools/android/forwarder2/device_forwarder_main.cc +++ b/tools/android/forwarder2/device_forwarder_main.cc
@@ -75,8 +75,8 @@ } controller_thread_->task_runner()->PostTask( FROM_HERE, - base::Bind(&ServerDelegate::StartController, base::Unretained(this), - GetExitNotifierFD(), base::Passed(&client_socket))); + base::BindOnce(&ServerDelegate::StartController, base::Unretained(this), + GetExitNotifierFD(), std::move(client_socket))); initialized_ = true; }
diff --git a/tools/android/forwarder2/device_listener.cc b/tools/android/forwarder2/device_listener.cc index b4c7799..415fa22 100644 --- a/tools/android/forwarder2/device_listener.cc +++ b/tools/android/forwarder2/device_listener.cc
@@ -55,8 +55,8 @@ void DeviceListener::SetAdbDataSocket(std::unique_ptr<Socket> adb_data_socket) { thread_.task_runner()->PostTask( FROM_HERE, - base::Bind(&DeviceListener::OnAdbDataSocketReceivedOnInternalThread, - base::Unretained(this), base::Passed(&adb_data_socket))); + base::BindOnce(&DeviceListener::OnAdbDataSocketReceivedOnInternalThread, + base::Unretained(this), std::move(adb_data_socket))); } DeviceListener::DeviceListener(std::unique_ptr<Socket> listener_socket, @@ -77,9 +77,8 @@ void DeviceListener::AcceptNextClientSoon() { thread_.task_runner()->PostTask( - FROM_HERE, - base::Bind(&DeviceListener::AcceptClientOnInternalThread, - base::Unretained(this))); + FROM_HERE, base::BindOnce(&DeviceListener::AcceptClientOnInternalThread, + base::Unretained(this))); } void DeviceListener::AcceptClientOnInternalThread() {
diff --git a/tools/android/forwarder2/forwarders_manager.cc b/tools/android/forwarder2/forwarders_manager.cc index 6ab8ed5..fcb3976 100644 --- a/tools/android/forwarder2/forwarders_manager.cc +++ b/tools/android/forwarder2/forwarders_manager.cc
@@ -39,9 +39,9 @@ // which is the only thread from which it's accessed. thread_.task_runner()->PostTask( FROM_HERE, - base::Bind(&ForwardersManager::CreateNewForwarderOnInternalThread, - base::Unretained(this), base::Passed(&socket1), - base::Passed(&socket2))); + base::BindOnce(&ForwardersManager::CreateNewForwarderOnInternalThread, + base::Unretained(this), std::move(socket1), + std::move(socket2))); // Guarantees that the CreateNewForwarderOnInternalThread callback posted to // the internal thread gets executed immediately. @@ -59,8 +59,8 @@ void ForwardersManager::WaitForEventsOnInternalThreadSoon() { thread_.task_runner()->PostTask( FROM_HERE, - base::Bind(&ForwardersManager::WaitForEventsOnInternalThread, - base::Unretained(this))); + base::BindOnce(&ForwardersManager::WaitForEventsOnInternalThread, + base::Unretained(this))); } void ForwardersManager::WaitForEventsOnInternalThread() {
diff --git a/tools/android/forwarder2/host_controller.cc b/tools/android/forwarder2/host_controller.cc index 316794f43..007f46be 100644 --- a/tools/android/forwarder2/host_controller.cc +++ b/tools/android/forwarder2/host_controller.cc
@@ -87,9 +87,8 @@ void HostController::ReadNextCommandSoon() { thread_.task_runner()->PostTask( - FROM_HERE, - base::Bind(&HostController::ReadCommandOnInternalThread, - base::Unretained(this))); + FROM_HERE, base::BindOnce(&HostController::ReadCommandOnInternalThread, + base::Unretained(this))); } void HostController::ReadCommandOnInternalThread() {
diff --git a/tools/android/forwarder2/host_controllers_manager.cc b/tools/android/forwarder2/host_controllers_manager.cc index 880402c..f024ab8 100644 --- a/tools/android/forwarder2/host_controllers_manager.cc +++ b/tools/android/forwarder2/host_controllers_manager.cc
@@ -38,9 +38,9 @@ InitOnce(); thread_->task_runner()->PostTask( FROM_HERE, - base::Bind(&HostControllersManager::HandleRequestOnInternalThread, - base::Unretained(this), adb_path, device_serial, command, - device_port, host_port, base::Passed(&client_socket))); + base::BindOnce(&HostControllersManager::HandleRequestOnInternalThread, + base::Unretained(this), adb_path, device_serial, command, + device_port, host_port, std::move(client_socket))); } // static
diff --git a/tools/android/forwarder2/self_deleter_helper.h b/tools/android/forwarder2/self_deleter_helper.h index b9ccc33..19c56a2 100644 --- a/tools/android/forwarder2/self_deleter_helper.h +++ b/tools/android/forwarder2/self_deleter_helper.h
@@ -113,9 +113,8 @@ void MaybeSelfDeleteSoon() { DCHECK(!construction_runner_->RunsTasksInCurrentSequence()); construction_runner_->PostTask( - FROM_HERE, - base::Bind(&SelfDeleterHelper::SelfDelete, - weak_ptr_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&SelfDeleterHelper::SelfDelete, + weak_ptr_factory_.GetWeakPtr())); } private:
diff --git a/tools/chrome_proxy/webdriver/https_previews.py b/tools/chrome_proxy/webdriver/https_previews.py index b7ff6409..5d246b4 100644 --- a/tools/chrome_proxy/webdriver/https_previews.py +++ b/tools/chrome_proxy/webdriver/https_previews.py
@@ -2,6 +2,10 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import json +import re +import time +import urllib from common import ParseFlags from common import TestDriver from common import IntegrationTest @@ -139,5 +143,51 @@ histogram = t.GetHistogram('SB2.ResourceTypes2.Unsafe') self.assertEqual(1, histogram['count']) + + # Verifies that a Lite Page is served, an intervention report has been + # sent to the correct reporting endpoint, and the content of this report + # is expected. + @ChromeVersionEqualOrAfterM(72) + def testLitePageWebReport(self): + with TestDriver() as t: + enableLitePageServerPreviews(t) + t.AddChromeArg('--short-reporting-delay') + t.UseNetLog() + + t.LoadURL('https://mobilespeed-test.appspot.com/snapshot-test/') + + # Verify that the request is served by a Lite Page. + lite_page_responses = 0 + lite_page_regexp = re.compile('https://\w+\.litepages\.googlezip\.net/p') + for response in t.GetHTTPResponses(): + if lite_page_regexp.search(response.url) and response.status == 200: + lite_page_responses += 1 + self.assertEqual(1, lite_page_responses) + + # Wait for intervention report to be attempted. + t.SleepUntilHistogramHasEntry("Net.Reporting.ReportDeliveredAttempts", 120) + events = t.StopAndGetNetLog()["events"] + + # Collect IDs of expected reporting requests. + report_request_id = [] + for event in events: + if not "params" in event or not "headers" in event["params"]: + continue + header = event["params"]["headers"] + if ":path: /webreports?u=%s"%(urllib.quote_plus("https://mobilespeed-test.appspot.com/web-reports")) in header and "content-type: application/reports+json" in header: + report_request_id.append(event["source"]["id"]) + self.assertNotEqual(0, len(report_request_id)) + + # Verify that at least one reporting request got 200. + ok_responses = 0 + for id in report_request_id: + for event in events: + if event["source"]["id"] != id or not "params" in event or not "headers" in event["params"]: + continue + for value in event["params"]["headers"]: + if ":status: 200" in value: + ok_responses += 1 + self.assertNotEqual(0, ok_responses) + if __name__ == '__main__': IntegrationTest.RunAllTests()
diff --git a/tools/clang/scripts/update.py b/tools/clang/scripts/update.py index 26e12ad..7aecd95 100755 --- a/tools/clang/scripts/update.py +++ b/tools/clang/scripts/update.py
@@ -521,7 +521,6 @@ AddCMakeToPath(args) AddGnuWinToPath() - SetMacXcodePath() DeleteChromeToolsShim() @@ -1001,6 +1000,12 @@ print 'clang_version in build/toolchain/toolchain.gni is likely outdated.' return 1 + # DEVELOPER_DIR needs to be set when Xcode isn't in a standard location + # and xcode-select wasn't run. This is needed for running clang and ld + # for the build done by this script, but it's also needed for running + # macOS system svn, so this needs to happen before calling functions using svn. + SetMacXcodePath() + global CLANG_REVISION, PACKAGE_VERSION if args.print_revision: if use_head_revision or args.llvm_force_head_revision:
diff --git a/tools/luci-go/.gitignore b/tools/luci-go/.gitignore index 2934681..afa2b1a 100644 --- a/tools/luci-go/.gitignore +++ b/tools/luci-go/.gitignore
@@ -2,9 +2,6 @@ /isolate.exe /isolated /isolated.exe -/linux64/isolate -/mac64/isolate /swarming /swarming.exe -/win64/isolate.exe .versions
diff --git a/tools/luci-go/linux64/isolate.sha1 b/tools/luci-go/linux64/isolate.sha1 deleted file mode 100644 index 1610657..0000000 --- a/tools/luci-go/linux64/isolate.sha1 +++ /dev/null
@@ -1 +0,0 @@ -9734e966a14f9e26f86e38a020fcd7584248d285
diff --git a/tools/luci-go/mac64/isolate.sha1 b/tools/luci-go/mac64/isolate.sha1 deleted file mode 100644 index a61e43ab..0000000 --- a/tools/luci-go/mac64/isolate.sha1 +++ /dev/null
@@ -1 +0,0 @@ -18561de57e944d096521838b4e6cb49e0cc1df23
diff --git a/tools/luci-go/win64/isolate.exe.sha1 b/tools/luci-go/win64/isolate.exe.sha1 deleted file mode 100644 index 5ac52a0..0000000 --- a/tools/luci-go/win64/isolate.exe.sha1 +++ /dev/null
@@ -1 +0,0 @@ -af227603890ea1d8c082b5caf15e46a6bf060a2e
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index de314d1..8831644 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -6323,6 +6323,9 @@ <int value="6" label="Already collecting"> Another profile collection was already active. </int> + <int value="7" label="Failed to start collection"> + Collection could not start due to failing prerequisites. + </int> </enum> <enum name="ChromeOSRecoveryReason"> @@ -21653,6 +21656,18 @@ <int value="2" label="Fetch failure"/> </enum> +<enum name="FeedSchedulerRefreshStatus"> + <int value="0" label="Should refresh"/> + <int value="1" label="Outstanding request"/> + <int value="2" label="Trigger disabled"/> + <int value="3" label="Network offline"/> + <int value="4" label="Eula not accepted"/> + <int value="5" label="Articles Hidden"/> + <int value="6" label="Refresh suppressed"/> + <int value="7" label="Not stale"/> + <int value="8" label="Refresh throttled"/> +</enum> + <enum name="FetchRequestMode"> <int value="0" label="SameOrigin"/> <int value="1" label="NoCORS"/>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index f3b4594..dee9ecb 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -14667,6 +14667,16 @@ </summary> </histogram> +<histogram name="ChromeOS.CWP.CollectHeap" + enum="ChromeOSProfileCollectionStatus" expires_after="2020-02-01"> + <owner>aalexand@google.com</owner> + <owner>gmx@chromium.org</owner> + <summary> + A count of successes and various failure modes related to the collection and + processing of Chrome heap sample profiles on Chrome OS. + </summary> +</histogram> + <histogram name="ChromeOS.CWP.CollectPerf" enum="ChromeOSProfileCollectionStatus"> <owner>aalexand@google.com</owner> @@ -14677,7 +14687,17 @@ </summary> </histogram> -<histogram name="ChromeOS.CWP.UploadPerf" units="count"> +<histogram name="ChromeOS.CWP.UploadHeap" units="reports" + expires_after="2020-02-01"> + <owner>aalexand@google.com</owner> + <owner>gmx@chromium.org</owner> + <summary> + Records the number of "heap" reports included in an UMA upload on + Chrome OS. + </summary> +</histogram> + +<histogram name="ChromeOS.CWP.UploadPerf" units="reports"> <owner>aalexand@google.com</owner> <owner>gmx@chromium.org</owner> <summary> @@ -17503,6 +17523,17 @@ </summary> </histogram> +<histogram name="ContentSuggestions.Feed.Scheduler.ShouldRefreshResult" + enum="FeedSchedulerRefreshStatus" expires_after="2020-02-01"> + <owner>gangwu@chromium.org</owner> + <owner>fgorski@chromium.org</owner> + <summary> + When the Feed scheduler receives a refresh request, the scheduler will + decide to refresh or not depending on the scheduler status. Recorded when + the Feed scheduler receives the request. + </summary> +</histogram> + <histogram name="ContentSuggestions.Feed.Scheduler.TimeSinceLastFetchOnClear" units="ms" expires_after="2019-10-01"> <owner>skym@chromium.org</owner> @@ -80528,7 +80559,7 @@ <histogram name="PasswordManager.AutocompletePopupSuppressedByGeneration" enum="BooleanSuppressed"> <obsolete> - Long removed. + Removed February 2019. </obsolete> <owner>gcasto@chromium.org</owner> <summary> @@ -135945,6 +135976,20 @@ <affected-histogram name="Favicons.DownloadAttempts"/> </histogram_suffixes> +<histogram_suffixes name="FeedSchedulerRequestType" separator="."> + <suffix name="NoRequestWithContent" + label="Do not make request and show current content."/> + <suffix name="NoRequestWithTimeout" + label="Do not make request until timeout."/> + <suffix name="NoRequestWithWait" + label="Do not make request and wait for existing request."/> + <suffix name="RequestByFixedTimer" label="Request by fixed timer."/> + <suffix name="RequestByForegrounded" label="Request by foregrounded."/> + <suffix name="RequestByNtpShown" label="Request by NTP shown."/> + <affected-histogram + name="ContentSuggestions.Feed.Scheduler.ShouldRefreshResult"/> +</histogram_suffixes> + <histogram_suffixes name="FeedStorageType" separator="." ordering="prefix,2"> <suffix name="ContentStorage" label="Database for content storage."/> <suffix name="JournalStorage" label="Database for journal storage."/>
diff --git a/tools/perf/benchmarks/rendering.py b/tools/perf/benchmarks/rendering.py index 8a0cc33..0328b090 100644 --- a/tools/perf/benchmarks/rendering.py +++ b/tools/perf/benchmarks/rendering.py
@@ -37,7 +37,10 @@ def CreateCoreTimelineBasedMeasurementOptions(self): category_filter = chrome_trace_category_filter.CreateLowOverheadFilter() options = timeline_based_measurement.Options(category_filter) - options.SetTimelineBasedMetrics(['renderingMetric']) + options.config.chrome_trace_config.EnableUMAHistograms( + 'Event.Latency.ScrollBegin.Touch.TimeToScrollUpdateSwapBegin4', + 'Event.Latency.ScrollUpdate.Touch.TimeToScrollUpdateSwapBegin4') + options.SetTimelineBasedMetrics(['renderingMetric', 'umaMetric']) return options @@ -70,5 +73,8 @@ category_filter = chrome_trace_category_filter.CreateLowOverheadFilter() options = timeline_based_measurement.Options(category_filter) options.config.enable_platform_display_trace = True - options.SetTimelineBasedMetrics(['renderingMetric']) + options.config.chrome_trace_config.EnableUMAHistograms( + 'Event.Latency.ScrollBegin.Touch.TimeToScrollUpdateSwapBegin4', + 'Event.Latency.ScrollUpdate.Touch.TimeToScrollUpdateSwapBegin4') + options.SetTimelineBasedMetrics(['renderingMetric', 'umaMetric']) return options
diff --git a/tools/perf/process_perf_results.py b/tools/perf/process_perf_results.py index fb92d52..babde10c 100755 --- a/tools/perf/process_perf_results.py +++ b/tools/perf/process_perf_results.py
@@ -107,7 +107,8 @@ if is_luci and _is_gtest(json_to_upload) and ( name in GTEST_CONVERSION_WHITELIST): path_util.AddTracingToPath() - from tracing.value import gtest_json_converter + from tracing.value import ( + gtest_json_converter) # pylint: disable=no-name-in-module gtest_json_converter.ConvertGtestJsonFile(json_to_upload) _data_format_cache[json_to_upload] = DATA_FORMAT_HISTOGRAMS
diff --git a/ui/aura/env.cc b/ui/aura/env.cc index fd82e8f..cbb9935 100644 --- a/ui/aura/env.cc +++ b/ui/aura/env.cc
@@ -325,6 +325,9 @@ if (mode_ == Mode::MUS) { EnableMusOSExchangeDataProvider(); EnableMusOverrideInputInjector(); + // Remote clients should not throttle, only the window-service should + // throttle (which corresponds to Mode::LOCAL). + throttle_input_on_resize_ = false; return; }
diff --git a/ui/aura/window_tree_host.cc b/ui/aura/window_tree_host.cc index 7c2b6f99..b3db18d 100644 --- a/ui/aura/window_tree_host.cc +++ b/ui/aura/window_tree_host.cc
@@ -540,7 +540,7 @@ dispatcher()->OnCursorMovedToRootLocation(root_location); } -void WindowTreeHost::OnCompositingDidCommit(ui::Compositor* compositor) { +void WindowTreeHost::OnCompositingEnded(ui::Compositor* compositor) { if (!holding_pointer_moves_) return;
diff --git a/ui/aura/window_tree_host.h b/ui/aura/window_tree_host.h index ccaeef8d..5a33164 100644 --- a/ui/aura/window_tree_host.h +++ b/ui/aura/window_tree_host.h
@@ -341,7 +341,7 @@ const gfx::Point& host_location); // Overrided from CompositorObserver: - void OnCompositingDidCommit(ui::Compositor* compositor) override; + void OnCompositingEnded(ui::Compositor* compositor) override; void OnCompositingChildResizing(ui::Compositor* compositor) override; void OnCompositingShuttingDown(ui::Compositor* compositor) override;
diff --git a/ui/aura/window_tree_host_unittest.cc b/ui/aura/window_tree_host_unittest.cc index abbe0b8..9404b14 100644 --- a/ui/aura/window_tree_host_unittest.cc +++ b/ui/aura/window_tree_host_unittest.cc
@@ -59,8 +59,8 @@ // effect of prioritizing the resize event above other operations in aura. EXPECT_TRUE(dispatcher_api.HoldingPointerMoves()); - // Wait for a CompositorFrame to be submitted. - ui::DrawWaiterForTest::WaitForCompositingStarted(host()->compositor()); + // Wait for a CompositorFrame to be activated. + ui::DrawWaiterForTest::WaitForCompositingEnded(host()->compositor()); // Pointer moves should be routed normally after commit. EXPECT_FALSE(dispatcher_api.HoldingPointerMoves());
diff --git a/ui/views/controls/button/menu_button.cc b/ui/views/controls/button/menu_button.cc index 23e5987..c58a17d 100644 --- a/ui/views/controls/button/menu_button.cc +++ b/ui/views/controls/button/menu_button.cc
@@ -18,8 +18,9 @@ const int MenuButton::kMenuMarkerPaddingRight = -1; MenuButton::MenuButton(const base::string16& text, - MenuButtonListener* menu_button_listener) - : LabelButton(nullptr, text), + MenuButtonListener* menu_button_listener, + int button_context) + : LabelButton(nullptr, text, button_context), menu_button_event_handler_(this, menu_button_listener) { SetHorizontalAlignment(gfx::ALIGN_LEFT); } @@ -83,4 +84,4 @@ menu_button_event_handler_.NotifyClick(event); } -} // namespace views \ No newline at end of file +} // namespace views
diff --git a/ui/views/controls/button/menu_button.h b/ui/views/controls/button/menu_button.h index 87e8faf..3449f65 100644 --- a/ui/views/controls/button/menu_button.h +++ b/ui/views/controls/button/menu_button.h
@@ -31,7 +31,8 @@ // Create a Button. MenuButton(const base::string16& text, - MenuButtonListener* menu_button_listener); + MenuButtonListener* menu_button_listener, + int button_context = style::CONTEXT_BUTTON); ~MenuButton() override; bool Activate(const ui::Event* event); @@ -57,7 +58,7 @@ void OnMouseMoved(const ui::MouseEvent& event) final; // Protected methods needed for MenuButtonEventHandler. - // TODO (cyan): Move these to a delegate interface. + // TODO(cyan): Move these to a delegate interface. using InkDropHostView::GetInkDrop; using View::InDrag; using View::GetDragOperations; @@ -80,7 +81,7 @@ private: // All events get sent to this handler to be processed. - // TODO (cyan): This will be generalized into a ButtonEventHandler and moved + // TODO(cyan): This will be generalized into a ButtonEventHandler and moved // into the Button class. MenuButtonEventHandler menu_button_event_handler_;