diff --git a/AUTHORS b/AUTHORS index eb66b2cb..f9f475a 100644 --- a/AUTHORS +++ b/AUTHORS
@@ -115,6 +115,7 @@ Ben Fiola <benfiola@gmail.com> Ben Karel <eschew@gmail.com> Ben Noordhuis <ben@strongloop.com> +Benedek Heilig <benecene@gmail.com> Benjamin Dupont <bedupont@cisco.com> Benjamin Jemlich <pcgod99@gmail.com> Bernard Cafarelli <voyageur@gentoo.org>
diff --git a/DEPS b/DEPS index a8004ec..5724b180d 100644 --- a/DEPS +++ b/DEPS
@@ -31,6 +31,7 @@ 'build_with_chromium', 'checkout_android', 'checkout_android_native_support', + 'checkout_ios_webkit', 'checkout_nacl', 'checkout_oculus_sdk', ] @@ -126,11 +127,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': '05ff93c43ea57fd62cd1bc36ab7cd9b6112a7ecf', + 'skia_revision': '969659dbb3137fb3b5c55e5fc46ec071b6fb5b96', # 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': 'fee9be7abb565fc2f2ae7c20e7597bece4fc7144', + 'v8_revision': '43b5c7b043dccc5261adb408ba2d845e52d845e2', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -138,15 +139,15 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '08573730b75a986c88b774fb9ce98bab45ffc1b1', + 'angle_revision': 'b9039bf76bf3a4caba6475ce5d62c1cf8611978a', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. - 'swiftshader_revision': 'c1fd4087ddc9ac99e7ec277cb37175b8158f96bc', + 'swiftshader_revision': 'b607bc8800c1a13d80e4c79be73172fa7d785017', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': 'ce88174adfcfe75bf8760851943a612769f239c8', + 'pdfium_revision': 'd6b7287745c6f60ddb2d91a64e9c91d2f297a76a', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling openmax_dl # and whatever else without interference from each other. @@ -161,7 +162,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling google-toolbox-for-mac # and whatever else without interference from each other. - 'google_toolbox_for_mac_revision': '3c3111d3aefe907c8c0f0e933029608d96ceefeb', + 'google_toolbox_for_mac_revision': 'aa1a3d2d447905999f119efbb70b3786c5eafa13', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling lighttpd # and whatever else without interference from each other. @@ -189,7 +190,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': '3b6663037fd5c1f61087a994df10b0338b4464d6', + 'catapult_revision': 'a74495a2956d6bfb592db832406acc93113ddda7', # 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 +254,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': '203016613717b23f4a54003e62cea8ca8a97f0f7', + 'dawn_revision': 'fda0617505c160153d330d6ab47812a354203728', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -406,7 +407,7 @@ }, 'src/ios/third_party/material_components_ios/src': { - 'url': Var('chromium_git') + '/external/github.com/material-components/material-components-ios.git' + '@' + '63faa33898c3041fcd87ca3abf173b6647e971f3', + 'url': Var('chromium_git') + '/external/github.com/material-components/material-components-ios.git' + '@' + 'b86526c41f4fd9577b6fc24b4d90a707cd8c5389', 'condition': 'checkout_ios', }, @@ -711,7 +712,7 @@ }, 'src/third_party/breakpad/breakpad': - Var('chromium_git') + '/breakpad/breakpad.git' + '@' + '9b06049ed9fdc8f6e2162bde88cbe902b7147735', + Var('chromium_git') + '/breakpad/breakpad.git' + '@' + '37a60998cade967809391d0986aa4af05d18a8ab', 'src/third_party/byte_buddy': { 'packages': [ @@ -733,11 +734,11 @@ }, 'src/third_party/ced/src': - Var('chromium_git') + '/external/github.com/google/compact_enc_det.git' + '@' + '94c367a1fe3a13207f4b22604fcfd1d9f9ddf6d9', + Var('chromium_git') + '/external/github.com/google/compact_enc_det.git' + '@' + 'ba412eaaacd3186085babcd901679a48863c7dd5', # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '611d1fbc1736114e324d2f341180b33fd0938d38', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '12a4eb908a7b6d697bf75af753b9e08b3352ffa2', 'condition': 'checkout_linux', }, @@ -762,7 +763,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '9cf1796ae43818259e6babf341ddf389ddb3f597', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'c0546b9817eea795277e517d5dac382d6b69b778', 'src/third_party/devtools-node-modules': Var('chromium_git') + '/external/github.com/ChromeDevTools/devtools-node-modules' + '@' + Var('devtools_node_modules_revision'), @@ -803,7 +804,7 @@ Var('chromium_git') + '/chromium/deps/flac.git' + '@' + 'af862024c8c8fa0ae07ced05e89013d881b00596', 'src/third_party/flatbuffers/src': - Var('chromium_git') + '/external/github.com/google/flatbuffers.git' + '@' + 'c721009491dc8275052cf33f7334e015ed737927', + Var('chromium_git') + '/external/github.com/google/flatbuffers.git' + '@' + '4f32cbf268a8ad469974b9453924a3582dbf2f30', # Used for embedded builds. CrOS & Linux use the system version. 'src/third_party/fontconfig/src': { @@ -831,7 +832,7 @@ }, 'src/third_party/glslang/src': - Var('chromium_git') + '/external/github.com/KhronosGroup/glslang.git' + '@' + '05d12a9461dd0a76053bdd42f062a37a10d56afb', + Var('chromium_git') + '/external/github.com/KhronosGroup/glslang.git' + '@' + 'a51d3d9f223361165127ded3cd2e59d81e22d91f', 'src/third_party/google_toolbox_for_mac/src': { 'url': Var('chromium_git') + '/external/github.com/google/google-toolbox-for-mac.git' + '@' + Var('google_toolbox_for_mac_revision'), @@ -995,10 +996,10 @@ }, 'src/third_party/libvpx/source/libvpx': - Var('chromium_git') + '/webm/libvpx.git' + '@' + 'e2381829e984c58e54a7ad0580c168cb7432ef92', + Var('chromium_git') + '/webm/libvpx.git' + '@' + '986b2bef7f475543a441cf9aa5a3ca55dd57ccae', 'src/third_party/libwebm/source': - Var('chromium_git') + '/webm/libwebm.git' + '@' + 'e4931ebc0a816458c18a6734e91a4d1b5acd5c56', + Var('chromium_git') + '/webm/libwebm.git' + '@' + '51ca718c3adf0ddedacd7df25fe45f67dc5a9ce1', 'src/third_party/libyuv': Var('chromium_git') + '/libyuv/libyuv.git' + '@' + 'b36c86fdfe746d7be904c3a565b047b24d58087e', # from r1714 @@ -1275,7 +1276,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'a0f51b2e123f39c9ff12e621b0b47dd28dd64424', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '826f2e7f340cc40914ae4561625f7bb6d6e8c87b', + Var('webrtc_git') + '/src.git' + '@' + 'e11b7d2e8087262bc29d41ae3782ed94824cbe3f', 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -1316,7 +1317,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@d55d94e6c8e65105d151f29ccb580bd1fb6312ce', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@4309189029fc996cb710002caab203228b77f8a1', 'condition': 'checkout_src_internal', }, @@ -2384,44 +2385,6 @@ '-d', 'src/chrome/build', ], }, - # Pull luci-go binaries (isolate, swarming) using checked-in hashes. - # TODO(maruel): Remove, https://crbug.com/851596 - { - 'name': 'luci-go_win', - 'pattern': '.', - 'condition': 'host_os == "win"', - 'action': [ 'python', - 'src/third_party/depot_tools/download_from_google_storage.py', - '--no_resume', - '--no_auth', - '--bucket', 'chromium-luci', - '-d', 'src/tools/luci-go/win64', - ], - }, - { - 'name': 'luci-go_mac', - 'pattern': '.', - 'condition': 'host_os == "mac"', - 'action': [ 'python', - 'src/third_party/depot_tools/download_from_google_storage.py', - '--no_resume', - '--no_auth', - '--bucket', 'chromium-luci', - '-d', 'src/tools/luci-go/mac64', - ], - }, - { - 'name': 'luci-go_linux', - 'pattern': '.', - 'condition': 'host_os == "linux"', - 'action': [ 'python', - 'src/third_party/depot_tools/download_from_google_storage.py', - '--no_resume', - '--no_auth', - '--bucket', 'chromium-luci', - '-d', 'src/tools/luci-go/linux64', - ], - }, { 'name': 'apache_win32', 'pattern': '\\.sha1',
diff --git a/WATCHLISTS b/WATCHLISTS index 03408ce..b52b697 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -2293,7 +2293,7 @@ 'media_win': ['media-win-reviews@chromium.org'], 'message_loop': ['sadrul@chromium.org'], 'metrics': ['asvitkine+watch@chromium.org'], - 'metrics_xml_files': ['asvitkine+watch@chromium.org'], + 'metrics_xml_files': ['asvitkine+watchxml@chromium.org'], 'midi': ['toyoshim+midi@chromium.org'], 'mojo': ['darin@chromium.org'], 'multidevice': ['hansberry+watch-multidevice@chromium.org',
diff --git a/android_webview/BUILD.gn b/android_webview/BUILD.gn index 2849d90..334711cc 100644 --- a/android_webview/BUILD.gn +++ b/android_webview/BUILD.gn
@@ -97,13 +97,13 @@ java_cpp_enum("aw_error_ui") { sources = [ - "browser/aw_safe_browsing_blocking_page.h", + "browser/safe_browsing/aw_safe_browsing_blocking_page.h", ] } java_cpp_enum("aw_safe_browsing_action") { sources = [ - "browser/aw_url_checker_delegate_impl.h", + "browser/safe_browsing/aw_url_checker_delegate_impl.h", ] } @@ -579,22 +579,12 @@ "browser/aw_renderer_priority.h", "browser/aw_resource_context.cc", "browser/aw_resource_context.h", - "browser/aw_safe_browsing_blocking_page.cc", - "browser/aw_safe_browsing_blocking_page.h", - "browser/aw_safe_browsing_resource_throttle.cc", - "browser/aw_safe_browsing_resource_throttle.h", - "browser/aw_safe_browsing_ui_manager.cc", - "browser/aw_safe_browsing_ui_manager.h", - "browser/aw_safe_browsing_whitelist_manager.cc", - "browser/aw_safe_browsing_whitelist_manager.h", "browser/aw_settings.cc", "browser/aw_settings.h", "browser/aw_speech_recognition_manager_delegate.cc", "browser/aw_speech_recognition_manager_delegate.h", "browser/aw_ssl_host_state_delegate.cc", "browser/aw_ssl_host_state_delegate.h", - "browser/aw_url_checker_delegate_impl.cc", - "browser/aw_url_checker_delegate_impl.h", "browser/aw_url_loader_throttle.cc", "browser/aw_url_loader_throttle.h", "browser/aw_variations_seed_bridge.cc", @@ -692,6 +682,16 @@ "browser/renderer_host/aw_render_view_host_ext.h", "browser/renderer_host/aw_resource_dispatcher_host_delegate.cc", "browser/renderer_host/aw_resource_dispatcher_host_delegate.h", + "browser/safe_browsing/aw_safe_browsing_blocking_page.cc", + "browser/safe_browsing/aw_safe_browsing_blocking_page.h", + "browser/safe_browsing/aw_safe_browsing_resource_throttle.cc", + "browser/safe_browsing/aw_safe_browsing_resource_throttle.h", + "browser/safe_browsing/aw_safe_browsing_ui_manager.cc", + "browser/safe_browsing/aw_safe_browsing_ui_manager.h", + "browser/safe_browsing/aw_safe_browsing_whitelist_manager.cc", + "browser/safe_browsing/aw_safe_browsing_whitelist_manager.h", + "browser/safe_browsing/aw_url_checker_delegate_impl.cc", + "browser/safe_browsing/aw_url_checker_delegate_impl.h", "browser/scoped_app_gl_state_restore.cc", "browser/scoped_app_gl_state_restore.h", "browser/state_serializer.cc",
diff --git a/android_webview/browser/OWNERS b/android_webview/browser/OWNERS index 0aa62a29..852fa10 100644 --- a/android_webview/browser/OWNERS +++ b/android_webview/browser/OWNERS
@@ -1,5 +1,3 @@ -per-file aw_safe_browsing*=ntfschr@chromium.org - per-file aw_content_utility_overlay_manifest.cc=set noparent per-file aw_content_utility_overlay_manifest.cc=file://ipc/SECURITY_OWNERS per-file aw_content_renderer_overlay_manifest.cc=set noparent
diff --git a/android_webview/browser/aw_browser_context.cc b/android_webview/browser/aw_browser_context.cc index 4554377..c4ed7fa 100644 --- a/android_webview/browser/aw_browser_context.cc +++ b/android_webview/browser/aw_browser_context.cc
@@ -14,9 +14,9 @@ #include "android_webview/browser/aw_permission_manager.h" #include "android_webview/browser/aw_quota_manager_bridge.h" #include "android_webview/browser/aw_resource_context.h" -#include "android_webview/browser/aw_safe_browsing_whitelist_manager.h" #include "android_webview/browser/aw_web_ui_controller_factory.h" #include "android_webview/browser/net/aw_url_request_context_getter.h" +#include "android_webview/browser/safe_browsing/aw_safe_browsing_whitelist_manager.h" #include "base/base_paths_posix.h" #include "base/bind.h" #include "base/path_service.h"
diff --git a/android_webview/browser/aw_browser_context.h b/android_webview/browser/aw_browser_context.h index 62d6a4a..f38628b 100644 --- a/android_webview/browser/aw_browser_context.h +++ b/android_webview/browser/aw_browser_context.h
@@ -8,8 +8,8 @@ #include <memory> #include <vector> -#include "android_webview/browser/aw_safe_browsing_ui_manager.h" #include "android_webview/browser/aw_ssl_host_state_delegate.h" +#include "android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.h" #include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/macros.h"
diff --git a/android_webview/browser/aw_content_browser_client.cc b/android_webview/browser/aw_content_browser_client.cc index 3502eaa..594c9f19 100644 --- a/android_webview/browser/aw_content_browser_client.cc +++ b/android_webview/browser/aw_content_browser_client.cc
@@ -25,7 +25,6 @@ #include "android_webview/browser/aw_quota_permission_context.h" #include "android_webview/browser/aw_settings.h" #include "android_webview/browser/aw_speech_recognition_manager_delegate.h" -#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" @@ -33,6 +32,7 @@ #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/safe_browsing/aw_url_checker_delegate_impl.h" #include "android_webview/browser/tracing/aw_tracing_delegate.h" #include "android_webview/common/aw_content_client.h" #include "android_webview/common/aw_descriptors.h"
diff --git a/android_webview/browser/aw_contents.h b/android_webview/browser/aw_contents.h index ddb1da7..6645f050 100644 --- a/android_webview/browser/aw_contents.h +++ b/android_webview/browser/aw_contents.h
@@ -12,13 +12,13 @@ #include "android_webview/browser/aw_browser_permission_request_delegate.h" #include "android_webview/browser/aw_render_process_gone_delegate.h" -#include "android_webview/browser/aw_safe_browsing_ui_manager.h" #include "android_webview/browser/browser_view_renderer.h" #include "android_webview/browser/browser_view_renderer_client.h" #include "android_webview/browser/find_helper.h" #include "android_webview/browser/icon_helper.h" #include "android_webview/browser/permission/permission_request_handler_client.h" #include "android_webview/browser/renderer_host/aw_render_view_host_ext.h" +#include "android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.h" #include "base/android/jni_weak_ref.h" #include "base/android/scoped_java_ref.h" #include "base/callback_forward.h"
diff --git a/android_webview/browser/aw_contents_client_bridge.h b/android_webview/browser/aw_contents_client_bridge.h index bbe9d38..50c4a39 100644 --- a/android_webview/browser/aw_contents_client_bridge.h +++ b/android_webview/browser/aw_contents_client_bridge.h
@@ -7,8 +7,8 @@ #include <memory> -#include "android_webview/browser/aw_url_checker_delegate_impl.h" #include "android_webview/browser/net/aw_web_resource_request.h" +#include "android_webview/browser/safe_browsing/aw_url_checker_delegate_impl.h" #include "base/android/jni_weak_ref.h" #include "base/android/scoped_java_ref.h" #include "base/callback.h"
diff --git a/android_webview/browser/aw_contents_statics.cc b/android_webview/browser/aw_contents_statics.cc index 7f7f66cd..319634f 100644 --- a/android_webview/browser/aw_contents_statics.cc +++ b/android_webview/browser/aw_contents_statics.cc
@@ -5,8 +5,8 @@ #include "android_webview/browser/aw_browser_context.h" #include "android_webview/browser/aw_contents.h" #include "android_webview/browser/aw_contents_io_thread_client.h" -#include "android_webview/browser/aw_safe_browsing_whitelist_manager.h" #include "android_webview/browser/net/aw_url_request_context_getter.h" +#include "android_webview/browser/safe_browsing/aw_safe_browsing_whitelist_manager.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h"
diff --git a/android_webview/browser/cookie_manager.cc b/android_webview/browser/cookie_manager.cc index cd5de81..aecaa35 100644 --- a/android_webview/browser/cookie_manager.cc +++ b/android_webview/browser/cookie_manager.cc
@@ -30,6 +30,7 @@ #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "base/threading/thread_restrictions.h" +#include "base/time/time.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/cookie_store_factory.h" #include "jni/AwCookieManager_jni.h" @@ -43,6 +44,7 @@ #include "services/network/network_service.h" #include "services/network/public/cpp/features.h" #include "services/network/public/mojom/cookie_manager.mojom-forward.h" +#include "services/network/public/mojom/cookie_manager.mojom.h" #include "url/url_constants.h" using base::FilePath; @@ -95,6 +97,38 @@ namespace { +// Copied from net/cookies/cookie_util.h for consistency and backwards +// compatibility. +const int kVlogSetCookies = 7; + +// TODO(ntfschr): see if we can turn this into OnceCallback. +// http://crbug.com/932535. +void MaybeRunCookieCallback(base::RepeatingCallback<void(bool)> callback, + const bool& result) { + if (callback) + std::move(callback).Run(result); +} + +GURL MaybeFixUpSchemeForSecureCookie(const GURL& host, + const std::string& value) { + // Log message for catching strict secure cookies related bugs. + // TODO(sgurun) temporary. Add UMA stats to monitor, and remove afterwards. + // http://crbug.com/933981. + if (host.is_valid() && + (!host.has_scheme() || host.SchemeIs(url::kHttpScheme))) { + net::ParsedCookie parsed_cookie(value); + if (parsed_cookie.IsValid() && parsed_cookie.IsSecure()) { + LOG(WARNING) << "Strict Secure Cookie policy does not allow setting a " + "secure cookie for " + << host.spec(); + GURL::Replacements replace_host; + replace_host.SetSchemeStr("https"); + return host.ReplaceComponents(replace_host); + } + } + return host; +} + // Construct a closure which signals a waitable event if and when the closure // is called the waitable event must still exist. static base::RepeatingClosure SignalEventClosure(WaitableEvent* completion) { @@ -129,6 +163,18 @@ } } +net::CookieStore::SetCookiesCallback StatusToBool( + base::OnceCallback<void(bool)> callback) { + return base::BindOnce( + [](base::OnceCallback<void(bool)> callback, + const net::CanonicalCookie::CookieInclusionStatus status) { + bool success = + (status == net::CanonicalCookie::CookieInclusionStatus::INCLUDE); + std::move(callback).Run(success); + }, + std::move(callback)); +} + } // namespace namespace { @@ -296,25 +342,63 @@ net::CookieOptions options; options.set_include_httponly(); - // Log message for catching strict secure cookies related bugs. - // TODO(sgurun) temporary. Add UMA stats to monitor, and remove afterwards. - if (host.is_valid() && - (!host.has_scheme() || host.SchemeIs(url::kHttpScheme))) { - net::ParsedCookie parsed_cookie(value); - if (parsed_cookie.IsValid() && parsed_cookie.IsSecure()) { - LOG(WARNING) << "Strict Secure Cookie policy does not allow setting a " - "secure cookie for " - << host.spec(); - GURL::Replacements replace_host; - replace_host.SetSchemeStr("https"); - GURL new_host = host.ReplaceComponents(replace_host); - GetCookieStore()->SetCookieWithOptionsAsync(new_host, value, options, - callback); - return; - } + const GURL& new_host = MaybeFixUpSchemeForSecureCookie(host, value); + + // The below is copied from net::CookieMonster::SetCookieWithOptions. We do + // this because we have strict requirements to keep behavior identical across + // WebView versions. + + // If this scheme is not cookieable, then we should not set a cookie for it. + // Instead, invoke the callback and indicate failure. + if (!HasCookieableScheme(new_host)) { + MaybeRunCookieCallback(std::move(callback), false); + return; } - GetCookieStore()->SetCookieWithOptionsAsync(host, value, options, callback); + VLOG(kVlogSetCookies) << "SetCookie() line: " << value; + + net::CanonicalCookie::CookieInclusionStatus status; + + std::unique_ptr<net::CanonicalCookie> cc(net::CanonicalCookie::Create( + new_host, value, base::Time::Now(), options, &status)); + + if (status != net::CanonicalCookie::CookieInclusionStatus::INCLUDE) { + DCHECK(!cc); + VLOG(kVlogSetCookies) << "WARNING: Failed to allocate CanonicalCookie"; + MaybeRunCookieCallback(std::move(callback), false); + return; + } + + DCHECK(cc); + + // Note: CookieStore and network::CookieManager have different signatures: one + // accepts a boolean callback while the other (recently) changed to accept a + // CookieInclusionStatus callback. WebView only cares about boolean success, + // which is why we use StatusToBool. This is temporary technical debt until we + // fully launch the Network Service code path. + if (base::FeatureList::IsEnabled(network::features::kNetworkService)) { + // *cc.get() is safe, because network::CookieManager::SetCanonicalCookie + // will make a copy before our smart pointer goes out of scope. + GetCookieManagerWrapper()->SetCanonicalCookie( + *cc.get(), new_host.SchemeIsCryptographic(), + !options.exclude_httponly(), std::move(callback)); + } else { + GetCookieStore()->SetCanonicalCookieAsync( + std::move(cc), new_host.SchemeIsCryptographic(), + !options.exclude_httponly(), StatusToBool(callback)); + } +} + +bool CookieManager::HasCookieableScheme(const GURL& host) { + for (int i = 0; i < net::CookieMonster::kDefaultCookieableSchemesCount; ++i) { + if (host.SchemeIs(net::CookieMonster::kDefaultCookieableSchemes[i])) { + return true; + } + } + if (host.SchemeIsFile() && AllowFileSchemeCookies()) { + return true; + } + return false; } std::string CookieManager::GetCookie(const GURL& host) { @@ -377,9 +461,19 @@ void CookieManager::RemoveSessionCookiesHelper( base::RepeatingCallback<void(bool)> callback) { - GetCookieStore()->DeleteSessionCookiesAsync( - base::BindOnce(&CookieManager::RemoveCookiesCompleted, - base::Unretained(this), callback)); + if (base::FeatureList::IsEnabled(network::features::kNetworkService)) { + auto match_session_cookies = network::mojom::CookieDeletionFilter::New(); + match_session_cookies->session_control = + network::mojom::CookieDeletionSessionControl::SESSION_COOKIES; + GetCookieManagerWrapper()->DeleteCookies( + std::move(match_session_cookies), + base::BindOnce(&CookieManager::RemoveCookiesCompleted, + base::Unretained(this), callback)); + } else { + GetCookieStore()->DeleteSessionCookiesAsync( + base::BindOnce(&CookieManager::RemoveCookiesCompleted, + base::Unretained(this), callback)); + } } void CookieManager::RemoveCookiesCompleted( @@ -403,9 +497,18 @@ void CookieManager::RemoveAllCookiesHelper( const base::RepeatingCallback<void(bool)> callback) { - GetCookieStore()->DeleteAllAsync( - base::BindOnce(&CookieManager::RemoveCookiesCompleted, - base::Unretained(this), callback)); + if (base::FeatureList::IsEnabled(network::features::kNetworkService)) { + // An empty filter matches all cookies. + auto match_all_cookies = network::mojom::CookieDeletionFilter::New(); + GetCookieManagerWrapper()->DeleteCookies( + std::move(match_all_cookies), + base::BindOnce(&CookieManager::RemoveCookiesCompleted, + base::Unretained(this), callback)); + } else { + GetCookieStore()->DeleteAllAsync( + base::BindOnce(&CookieManager::RemoveCookiesCompleted, + base::Unretained(this), callback)); + } } void CookieManager::RemoveExpiredCookies() { @@ -433,9 +536,15 @@ // should not be needed. void CookieManager::HasCookiesAsyncHelper(bool* result, base::OnceClosure complete) { - GetCookieStore()->GetAllCookiesAsync( - base::BindOnce(&CookieManager::HasCookiesCompleted, - base::Unretained(this), std::move(complete), result)); + if (base::FeatureList::IsEnabled(network::features::kNetworkService)) { + GetCookieManagerWrapper()->GetAllCookies( + base::BindOnce(&CookieManager::HasCookiesCompleted2, + base::Unretained(this), std::move(complete), result)); + } else { + GetCookieStore()->GetAllCookiesAsync( + base::BindOnce(&CookieManager::HasCookiesCompleted, + base::Unretained(this), std::move(complete), result)); + } } void CookieManager::HasCookiesCompleted( @@ -447,6 +556,13 @@ std::move(complete).Run(); } +void CookieManager::HasCookiesCompleted2(base::OnceClosure complete, + bool* result, + const CookieList& cookies) { + *result = cookies.size() != 0; + std::move(complete).Run(); +} + bool CookieManager::AllowFileSchemeCookies() { base::AutoLock lock(accept_file_scheme_cookies_lock_); return accept_file_scheme_cookies_;
diff --git a/android_webview/browser/cookie_manager.h b/android_webview/browser/cookie_manager.h index 5e4a2fbe..8d03009 100644 --- a/android_webview/browser/cookie_manager.h +++ b/android_webview/browser/cookie_manager.h
@@ -113,6 +113,12 @@ bool* result, const net::CookieList& cookies, const net::CookieStatusList& excluded_cookies); + void HasCookiesCompleted2(base::OnceClosure complete, + bool* result, + const net::CookieList& cookies); + // Determine if cookies can be set for |host|, based on its scheme. This is + // based on net::CookieMonster::HasCookieableScheme. + bool HasCookieableScheme(const GURL& host); // This protects the following two bools, as they're used on multiple threads. base::Lock accept_file_scheme_cookies_lock_;
diff --git a/android_webview/browser/net/aw_cookie_store_wrapper.cc b/android_webview/browser/net/aw_cookie_store_wrapper.cc index afa6edb..33fc9ac 100644 --- a/android_webview/browser/net/aw_cookie_store_wrapper.cc +++ b/android_webview/browser/net/aw_cookie_store_wrapper.cc
@@ -96,7 +96,8 @@ DCHECK(client_task_runner_->RunsTasksInCurrentSequence()); PostTaskToCookieStoreTaskRunner(base::BindOnce( &SetCookieWithOptionsAsyncOnCookieThread, url, cookie_line, options, - CreateWrappedCallback<bool>(std::move(callback)))); + CreateWrappedCallback<net::CanonicalCookie::CookieInclusionStatus>( + std::move(callback)))); } void AwCookieStoreWrapper::SetCanonicalCookieAsync( @@ -107,7 +108,9 @@ DCHECK(client_task_runner_->RunsTasksInCurrentSequence()); PostTaskToCookieStoreTaskRunner(base::BindOnce( &SetCanonicalCookieAsyncOnCookieThread, std::move(cookie), secure_source, - modify_http_only, CreateWrappedCallback<bool>(std::move(callback)))); + modify_http_only, + CreateWrappedCallback<net::CanonicalCookie::CookieInclusionStatus>( + std::move(callback)))); } void AwCookieStoreWrapper::GetCookieListWithOptionsAsync(
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 index 3328c13..972b2bd 100644 --- a/android_webview/browser/net_network_service/aw_cookie_manager_wrapper.cc +++ b/android_webview/browser/net_network_service/aw_cookie_manager_wrapper.cc
@@ -26,8 +26,33 @@ const net::CookieOptions& cookie_options, GetCookieListCallback callback) { // TODO(ntfschr): handle the case where content layer isn't initialized yet - // (http://crbug.com/902641). + // (http://crbug.com/933461). cookie_manager_->GetCookieList(url, cookie_options, std::move(callback)); } +void AwCookieManagerWrapper::SetCanonicalCookie( + const net::CanonicalCookie& cc, + bool secure_source, + bool modify_http_only, + SetCanonicalCookieCallback callback) { + // TODO(ntfschr): handle the case where content layer isn't initialized yet + // (http://crbug.com/933461). + cookie_manager_->SetCanonicalCookie(cc, secure_source, modify_http_only, + std::move(callback)); +} + +void AwCookieManagerWrapper::DeleteCookies( + network::mojom::CookieDeletionFilterPtr filter, + DeleteCookiesCallback callback) { + // TODO(ntfschr): handle the case where content layer isn't initialized yet + // (http://crbug.com/933461). + cookie_manager_->DeleteCookies(std::move(filter), std::move(callback)); +} + +void AwCookieManagerWrapper::GetAllCookies(GetCookieListCallback callback) { + // TODO(ntfschr): handle the case where content layer isn't initialized yet + // (http://crbug.com/933461). + cookie_manager_->GetAllCookies(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 index e1dbd2c..ad8cc20 100644 --- a/android_webview/browser/net_network_service/aw_cookie_manager_wrapper.h +++ b/android_webview/browser/net_network_service/aw_cookie_manager_wrapper.h
@@ -11,9 +11,6 @@ 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 @@ -24,17 +21,37 @@ AwCookieManagerWrapper(); ~AwCookieManagerWrapper(); + // We redefine these type aliases for consistency and readability. These are + // originally defined by generated mojo code in + // out/<folder>/gen/services/network/public/mojom/cookie_manager.mojom.h. + using GetCookieListCallback = + network::mojom::CookieManager::GetCookieListCallback; + using SetCanonicalCookieCallback = + network::mojom::CookieManager::SetCanonicalCookieCallback; + using DeleteCookiesCallback = + network::mojom::CookieManager::DeleteCookiesCallback; + // 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). + // TODO(ntfschr): implement the other APIs we need (http://crbug.com/933462). void GetCookieList(const GURL& url, const net::CookieOptions& cookie_options, GetCookieListCallback callback); + void SetCanonicalCookie(const net::CanonicalCookie& cc, + bool secure_source, + bool modify_http_only, + SetCanonicalCookieCallback); + + void DeleteCookies(network::mojom::CookieDeletionFilterPtr filter, + DeleteCookiesCallback callback); + + void GetAllCookies(GetCookieListCallback callback); + private: // A CookieManagerPtr which is cloned from the NetworkContext's // CookieManagerPtr (but, lives on this thread).
diff --git a/android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.cc b/android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.cc index 482826dd..da8612c4 100644 --- a/android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.cc +++ b/android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.cc
@@ -12,10 +12,10 @@ #include "android_webview/browser/aw_contents_client_bridge.h" #include "android_webview/browser/aw_contents_io_thread_client.h" #include "android_webview/browser/aw_resource_context.h" -#include "android_webview/browser/aw_safe_browsing_resource_throttle.h" #include "android_webview/browser/net/aw_web_resource_request.h" #include "android_webview/browser/net_helpers.h" #include "android_webview/browser/renderer_host/auto_login_parser.h" +#include "android_webview/browser/safe_browsing/aw_safe_browsing_resource_throttle.h" #include "android_webview/common/url_constants.h" #include "base/bind.h" #include "base/task/post_task.h"
diff --git a/android_webview/browser/safe_browsing/OWNERS b/android_webview/browser/safe_browsing/OWNERS new file mode 100644 index 0000000..606a16b7 --- /dev/null +++ b/android_webview/browser/safe_browsing/OWNERS
@@ -0,0 +1 @@ +ntfschr@chromium.org
diff --git a/android_webview/browser/aw_safe_browsing_blocking_page.cc b/android_webview/browser/safe_browsing/aw_safe_browsing_blocking_page.cc similarity index 97% rename from android_webview/browser/aw_safe_browsing_blocking_page.cc rename to android_webview/browser/safe_browsing/aw_safe_browsing_blocking_page.cc index 10b8ed1..3fe5025 100644 --- a/android_webview/browser/aw_safe_browsing_blocking_page.cc +++ b/android_webview/browser/safe_browsing/aw_safe_browsing_blocking_page.cc
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/browser/aw_safe_browsing_blocking_page.h" +#include "android_webview/browser/safe_browsing/aw_safe_browsing_blocking_page.h" #include <memory> #include "android_webview/browser/aw_browser_context.h" -#include "android_webview/browser/aw_safe_browsing_ui_manager.h" #include "android_webview/browser/net/aw_url_request_context_getter.h" +#include "android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.h" #include "base/metrics/histogram_macros.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing/browser/threat_details.h"
diff --git a/android_webview/browser/aw_safe_browsing_blocking_page.h b/android_webview/browser/safe_browsing/aw_safe_browsing_blocking_page.h similarity index 90% rename from android_webview/browser/aw_safe_browsing_blocking_page.h rename to android_webview/browser/safe_browsing/aw_safe_browsing_blocking_page.h index 7820624..28dae42 100644 --- a/android_webview/browser/aw_safe_browsing_blocking_page.h +++ b/android_webview/browser/safe_browsing/aw_safe_browsing_blocking_page.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ANDROID_WEBVIEW_BROWSER_AW_SAFE_BROWSING_BLOCKING_PAGE_H_ -#define ANDROID_WEBVIEW_BROWSER_AW_SAFE_BROWSING_BLOCKING_PAGE_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_SAFE_BROWSING_AW_SAFE_BROWSING_BLOCKING_PAGE_H_ +#define ANDROID_WEBVIEW_BROWSER_SAFE_BROWSING_AW_SAFE_BROWSING_BLOCKING_PAGE_H_ #include "components/safe_browsing/base_blocking_page.h" #include "components/security_interstitials/core/base_safe_browsing_error_ui.h" @@ -61,4 +61,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_BROWSER_AW_SAFE_BROWSING_BLOCKING_PAGE_H_ +#endif // ANDROID_WEBVIEW_BROWSER_SAFE_BROWSING_AW_SAFE_BROWSING_BLOCKING_PAGE_H_
diff --git a/android_webview/browser/aw_safe_browsing_resource_throttle.cc b/android_webview/browser/safe_browsing/aw_safe_browsing_resource_throttle.cc similarity index 92% rename from android_webview/browser/aw_safe_browsing_resource_throttle.cc rename to android_webview/browser/safe_browsing/aw_safe_browsing_resource_throttle.cc index 75f84d32..8fea87f 100644 --- a/android_webview/browser/aw_safe_browsing_resource_throttle.cc +++ b/android_webview/browser/safe_browsing/aw_safe_browsing_resource_throttle.cc
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/browser/aw_safe_browsing_resource_throttle.h" +#include "android_webview/browser/safe_browsing/aw_safe_browsing_resource_throttle.h" #include <memory> -#include "android_webview/browser/aw_safe_browsing_whitelist_manager.h" -#include "android_webview/browser/aw_url_checker_delegate_impl.h" +#include "android_webview/browser/safe_browsing/aw_safe_browsing_whitelist_manager.h" +#include "android_webview/browser/safe_browsing/aw_url_checker_delegate_impl.h" #include "components/safe_browsing/common/safebrowsing_constants.h" #include "components/safe_browsing/db/v4_protocol_manager_util.h" #include "content/public/browser/resource_request_info.h"
diff --git a/android_webview/browser/aw_safe_browsing_resource_throttle.h b/android_webview/browser/safe_browsing/aw_safe_browsing_resource_throttle.h similarity index 87% rename from android_webview/browser/aw_safe_browsing_resource_throttle.h rename to android_webview/browser/safe_browsing/aw_safe_browsing_resource_throttle.h index 1be37cf..8f28b1a 100644 --- a/android_webview/browser/aw_safe_browsing_resource_throttle.h +++ b/android_webview/browser/safe_browsing/aw_safe_browsing_resource_throttle.h
@@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ANDROID_WEBVIEW_BROWSER_AW_SAFE_BROWSING_RESOURCE_THROTTLE_H_ -#define ANDROID_WEBVIEW_BROWSER_AW_SAFE_BROWSING_RESOURCE_THROTTLE_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_SAFE_BROWSING_AW_SAFE_BROWSING_RESOURCE_THROTTLE_H_ +#define ANDROID_WEBVIEW_BROWSER_SAFE_BROWSING_AW_SAFE_BROWSING_RESOURCE_THROTTLE_H_ -#include "android_webview/browser/aw_safe_browsing_ui_manager.h" +#include "android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.h" #include "base/macros.h" #include "components/safe_browsing/browser/base_parallel_resource_throttle.h" #include "components/safe_browsing/db/database_manager.h" @@ -64,4 +64,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_BROWSER_AW_SAFE_BROWSING_RESOURCE_THROTTLE_H_ +#endif // ANDROID_WEBVIEW_BROWSER_SAFE_BROWSING_AW_SAFE_BROWSING_RESOURCE_THROTTLE_H_
diff --git a/android_webview/browser/aw_safe_browsing_ui_manager.cc b/android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.cc similarity index 97% rename from android_webview/browser/aw_safe_browsing_ui_manager.cc rename to android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.cc index e0fa414..89c8115 100644 --- a/android_webview/browser/aw_safe_browsing_ui_manager.cc +++ b/android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.cc
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/browser/aw_safe_browsing_ui_manager.h" +#include "android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.h" #include "android_webview/browser/aw_content_browser_client.h" -#include "android_webview/browser/aw_safe_browsing_blocking_page.h" #include "android_webview/browser/net/aw_url_request_context_getter.h" +#include "android_webview/browser/safe_browsing/aw_safe_browsing_blocking_page.h" #include "android_webview/common/aw_paths.h" #include "base/bind.h" #include "base/command_line.h"
diff --git a/android_webview/browser/aw_safe_browsing_ui_manager.h b/android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.h similarity index 92% rename from android_webview/browser/aw_safe_browsing_ui_manager.h rename to android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.h index 9c1f411..b57ff34 100644 --- a/android_webview/browser/aw_safe_browsing_ui_manager.h +++ b/android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.h
@@ -6,8 +6,8 @@ // anti-malware tables and checking urls against them. This is android_webview // specific ui_manager. -#ifndef ANDROID_WEBVIEW_BROWSER_AW_SAFE_BROWSING_UI_MANAGER_H_ -#define ANDROID_WEBVIEW_BROWSER_AW_SAFE_BROWSING_UI_MANAGER_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_SAFE_BROWSING_AW_SAFE_BROWSING_UI_MANAGER_H_ +#define ANDROID_WEBVIEW_BROWSER_SAFE_BROWSING_AW_SAFE_BROWSING_UI_MANAGER_H_ #include "components/safe_browsing/base_ui_manager.h" #include "content/public/browser/web_contents.h" @@ -23,7 +23,7 @@ class PingManager; class SafeBrowsingNetworkContext; class SafeBrowsingURLRequestContextGetter; -} // namespace +} // namespace safe_browsing namespace android_webview { class AwURLRequestContextGetter; @@ -102,4 +102,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_BROWSER_AW_SAFE_BROWSING_UI_MANAGER_H_ +#endif // ANDROID_WEBVIEW_BROWSER_SAFE_BROWSING_AW_SAFE_BROWSING_UI_MANAGER_H_
diff --git a/android_webview/browser/aw_safe_browsing_whitelist_manager.cc b/android_webview/browser/safe_browsing/aw_safe_browsing_whitelist_manager.cc similarity index 98% rename from android_webview/browser/aw_safe_browsing_whitelist_manager.cc rename to android_webview/browser/safe_browsing/aw_safe_browsing_whitelist_manager.cc index 24bfa09..3428731 100644 --- a/android_webview/browser/aw_safe_browsing_whitelist_manager.cc +++ b/android_webview/browser/safe_browsing/aw_safe_browsing_whitelist_manager.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/browser/aw_safe_browsing_whitelist_manager.h" +#include "android_webview/browser/safe_browsing/aw_safe_browsing_whitelist_manager.h" #include <map> #include <memory>
diff --git a/android_webview/browser/aw_safe_browsing_whitelist_manager.h b/android_webview/browser/safe_browsing/aw_safe_browsing_whitelist_manager.h similarity index 91% rename from android_webview/browser/aw_safe_browsing_whitelist_manager.h rename to android_webview/browser/safe_browsing/aw_safe_browsing_whitelist_manager.h index 3d98ebb..8e5c49e 100644 --- a/android_webview/browser/aw_safe_browsing_whitelist_manager.h +++ b/android_webview/browser/safe_browsing/aw_safe_browsing_whitelist_manager.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ANDROID_WEBVIEW_BROWSER_AW_SAFE_BROWSING_WHITELIST_MANAGER_H_ -#define ANDROID_WEBVIEW_BROWSER_AW_SAFE_BROWSING_WHITELIST_MANAGER_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_SAFE_BROWSING_AW_SAFE_BROWSING_WHITELIST_MANAGER_H_ +#define ANDROID_WEBVIEW_BROWSER_SAFE_BROWSING_AW_SAFE_BROWSING_WHITELIST_MANAGER_H_ #include <string> #include <vector> @@ -86,4 +86,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_BROWSER_AW_SAFE_BROWSING_WHITELIST_MANAGER_H_ +#endif // ANDROID_WEBVIEW_BROWSER_SAFE_BROWSING_AW_SAFE_BROWSING_WHITELIST_MANAGER_H_
diff --git a/android_webview/browser/aw_safe_browsing_whitelist_manager_unittest.cc b/android_webview/browser/safe_browsing/aw_safe_browsing_whitelist_manager_unittest.cc similarity index 99% rename from android_webview/browser/aw_safe_browsing_whitelist_manager_unittest.cc rename to android_webview/browser/safe_browsing/aw_safe_browsing_whitelist_manager_unittest.cc index c7b1f5e5..fc14f73 100644 --- a/android_webview/browser/aw_safe_browsing_whitelist_manager_unittest.cc +++ b/android_webview/browser/safe_browsing/aw_safe_browsing_whitelist_manager_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/browser/aw_safe_browsing_whitelist_manager.h" +#include "android_webview/browser/safe_browsing/aw_safe_browsing_whitelist_manager.h" #include "base/bind.h" #include "base/callback.h"
diff --git a/android_webview/browser/aw_url_checker_delegate_impl.cc b/android_webview/browser/safe_browsing/aw_url_checker_delegate_impl.cc similarity index 96% rename from android_webview/browser/aw_url_checker_delegate_impl.cc rename to android_webview/browser/safe_browsing/aw_url_checker_delegate_impl.cc index 8fe987da..dbb21a62 100644 --- a/android_webview/browser/aw_url_checker_delegate_impl.cc +++ b/android_webview/browser/safe_browsing/aw_url_checker_delegate_impl.cc
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/browser/aw_url_checker_delegate_impl.h" +#include "android_webview/browser/safe_browsing/aw_url_checker_delegate_impl.h" #include "android_webview/browser/aw_contents_client_bridge.h" #include "android_webview/browser/aw_contents_io_thread_client.h" -#include "android_webview/browser/aw_safe_browsing_ui_manager.h" -#include "android_webview/browser/aw_safe_browsing_whitelist_manager.h" #include "android_webview/browser/net/aw_web_resource_request.h" +#include "android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.h" +#include "android_webview/browser/safe_browsing/aw_safe_browsing_whitelist_manager.h" #include "base/bind.h" #include "base/task/post_task.h" #include "components/safe_browsing/db/database_manager.h"
diff --git a/android_webview/browser/aw_url_checker_delegate_impl.h b/android_webview/browser/safe_browsing/aw_url_checker_delegate_impl.h similarity index 93% rename from android_webview/browser/aw_url_checker_delegate_impl.h rename to android_webview/browser/safe_browsing/aw_url_checker_delegate_impl.h index d97f52f..00cf0f47 100644 --- a/android_webview/browser/aw_url_checker_delegate_impl.h +++ b/android_webview/browser/safe_browsing/aw_url_checker_delegate_impl.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ANDROID_WEBVIEW_BROWSER_AW_URL_CHECKER_DELEGATE_IMPL_H_ -#define ANDROID_WEBVIEW_BROWSER_AW_URL_CHECKER_DELEGATE_IMPL_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_SAFE_BROWSING_AW_URL_CHECKER_DELEGATE_IMPL_H_ +#define ANDROID_WEBVIEW_BROWSER_SAFE_BROWSING_AW_URL_CHECKER_DELEGATE_IMPL_H_ #include "base/macros.h" #include "base/memory/ref_counted.h" @@ -86,4 +86,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_BROWSER_AW_URL_CHECKER_DELEGATE_IMPL_H_ +#endif // ANDROID_WEBVIEW_BROWSER_SAFE_BROWSING_AW_URL_CHECKER_DELEGATE_IMPL_H_
diff --git a/android_webview/docs/test-instructions.md b/android_webview/docs/test-instructions.md index 05c5105..97602fb 100644 --- a/android_webview/docs/test-instructions.md +++ b/android_webview/docs/test-instructions.md
@@ -120,7 +120,6 @@ # Run pre-built WebView CTS tests: $ android_webview/tools/run_cts.py \ - --apk-dir="$HOME/run-cts-apk-dir" \ # Any folder, to use as an optional cache --verbose \ # Optional -f=android.webkit.cts.WebViewTest#* # Supports similar test filters ```
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/CookieManagerTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/CookieManagerTest.java index 4be2e23..04f3e4d 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/CookieManagerTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/CookieManagerTest.java
@@ -299,10 +299,9 @@ @Test @MediumTest @Feature({"AndroidWebView", "Privacy"}) - public void testSetCookieCallback() throws Throwable { + public void testSetCookieCallback_goodUrl() throws Throwable { final String url = "http://www.example.com"; final String cookie = "name=test"; - final String brokenUrl = "foo"; final TestCallback<Boolean> callback = new TestCallback<Boolean>(); int callCount = callback.getOnResultHelper().getCallCount(); @@ -311,13 +310,23 @@ callback.getOnResultHelper().waitForCallback(callCount); Assert.assertTrue(callback.getValue()); Assert.assertEquals(cookie, mCookieManager.getCookie(url)); + } - callCount = callback.getOnResultHelper().getCallCount(); + @Test + @MediumTest + @Feature({"AndroidWebView", "Privacy"}) + public void testSetCookieCallback_badUrl() throws Throwable { + final String cookie = "name=test"; + final String brokenUrl = "foo"; + + final TestCallback<Boolean> callback = new TestCallback<Boolean>(); + int callCount = callback.getOnResultHelper().getCallCount(); setCookieOnUiThread(brokenUrl, cookie, callback); callback.getOnResultHelper().waitForCallback(callCount); - Assert.assertFalse(callback.getValue()); - Assert.assertEquals(null, mCookieManager.getCookie(brokenUrl)); + Assert.assertFalse("Cookie should not be set for bad URLs", callback.getValue()); + Assert.assertNull("getCookie should be null if cookie hasn't been set", + mCookieManager.getCookie(brokenUrl)); } @Test @@ -333,6 +342,7 @@ mCookieManager.setCookie(url, cookie, null); AwActivityTestRule.pollInstrumentationThread(() -> mCookieManager.hasCookies()); + Assert.assertEquals(cookie, mCookieManager.getCookie(url)); } @Test
diff --git a/android_webview/test/BUILD.gn b/android_webview/test/BUILD.gn index f9519e61..578383d 100644 --- a/android_webview/test/BUILD.gn +++ b/android_webview/test/BUILD.gn
@@ -336,7 +336,6 @@ "../browser/aw_form_database_service_unittest.cc", "../browser/aw_media_url_interceptor_unittest.cc", "../browser/aw_permission_manager_unittest.cc", - "../browser/aw_safe_browsing_whitelist_manager_unittest.cc", "../browser/aw_static_cookie_policy_unittest.cc", "../browser/browser_view_renderer_unittest.cc", "../browser/command_line_helper_unittest.cc", @@ -349,6 +348,7 @@ "../browser/permission/media_access_permission_request_unittest.cc", "../browser/permission/permission_request_handler_unittest.cc", "../browser/renderer_host/auto_login_parser_unittest.cc", + "../browser/safe_browsing/aw_safe_browsing_whitelist_manager_unittest.cc", "../browser/state_serializer_unittest.cc", "../browser/test/fake_window.cc", "../browser/test/fake_window.h",
diff --git a/android_webview/tools/automated_ui_tests/OWNERS b/android_webview/tools/automated_ui_tests/OWNERS deleted file mode 100644 index d7bf90f..0000000 --- a/android_webview/tools/automated_ui_tests/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -aluo@chromium.org
diff --git a/android_webview/tools/run_cts.py b/android_webview/tools/run_cts.py index 09340623..ca70e00 100755 --- a/android_webview/tools/run_cts.py +++ b/android_webview/tools/run_cts.py
@@ -43,7 +43,7 @@ _CTS_ARCHIVE_DIR = os.path.join(os.path.dirname(__file__), 'cts_archive') -_SDK_PLATFORM_DICT = { +SDK_PLATFORM_DICT = { version_codes.LOLLIPOP: 'L', version_codes.LOLLIPOP_MR1: 'L', version_codes.MARSHMALLOW: 'M', @@ -73,8 +73,8 @@ TEST_FILTER_OPT = '--test-filter' ISOLATED_FILTER_OPT = '--isolated-script-test-filter' -def GetCtsInfo(arch, platform, item): - """Gets contents of CTS Info for arch and platform. +def GetCtsInfo(arch, cts_release, item): + """Gets contents of CTS Info for arch and cts_release. See _WEBVIEW_CTS_GCS_PATH_FILE """ @@ -82,17 +82,17 @@ cts_gcs_path_info = json.load(f) try: if item in _ARCH_SPECIFIC_CTS_INFO: - return cts_gcs_path_info[platform]['arch'][arch][item] + return cts_gcs_path_info[cts_release]['arch'][arch][item] else: - return cts_gcs_path_info[platform][item] + return cts_gcs_path_info[cts_release][item] except KeyError: raise Exception('No %s info available for arch:%s, android:%s' % - (item, arch, platform)) + (item, arch, cts_release)) -def GetCTSModuleNames(arch, platform): - """Gets the module apk name of the arch and platform""" - test_runs = GetCtsInfo(arch, platform, 'test_runs') +def GetCTSModuleNames(arch, cts_release): + """Gets the module apk name of the arch and cts_release""" + test_runs = GetCtsInfo(arch, cts_release, 'test_runs') return [os.path.basename(r['apk']) for r in test_runs] @@ -179,20 +179,20 @@ "Can't merge results field %s that is not a list or dict" % v) -def ExtractCTSZip(args, arch): - """Extract the CTS tests for args.platform. +def ExtractCTSZip(args, arch, cts_release): + """Extract the CTS tests for cts_release. Extract the CTS zip file from _CTS_ARCHIVE_DIR to apk_dir if specified, or a new temporary directory if not. Returns following tuple (local_cts_dir, base_cts_dir, delete_cts_dir): - local_cts_dir - CTS extraction location for current arch and platform + local_cts_dir - CTS extraction location for current arch and cts_release base_cts_dir - Root directory for all the arches and platforms delete_cts_dir - Set if the base_cts_dir was created as a temporary directory """ base_cts_dir = None delete_cts_dir = False - relative_cts_zip_path = GetCtsInfo(arch, args.platform, 'filename') + relative_cts_zip_path = GetCtsInfo(arch, cts_release, 'filename') if args.apk_dir: base_cts_dir = args.apk_dir @@ -202,7 +202,7 @@ cts_zip_path = os.path.join(_CTS_ARCHIVE_DIR, relative_cts_zip_path) local_cts_dir = os.path.join(base_cts_dir, - GetCtsInfo(arch, args.platform, + GetCtsInfo(arch, cts_release, 'unzip_dir') ) zf = zipfile.ZipFile(cts_zip_path, 'r') @@ -210,21 +210,22 @@ return (local_cts_dir, base_cts_dir, delete_cts_dir) -def RunAllCTSTests(args, arch, test_runner_args): +def RunAllCTSTests(args, arch, cts_release, test_runner_args): """Run CTS tests downloaded from _CTS_BUCKET. Downloads CTS tests from bucket, runs them for the - specified platform+arch, then creates a single + specified cts_release+arch, then creates a single results json file (if specified) Returns 0 if all tests passed, otherwise returns the failure code of the last failing test. """ - local_cts_dir, base_cts_dir, delete_cts_dir = ExtractCTSZip(args, arch) + local_cts_dir, base_cts_dir, delete_cts_dir = ExtractCTSZip(args, arch, + cts_release) cts_result = 0 json_results_file = args.json_results_file try: - cts_test_runs = GetCtsInfo(arch, args.platform, 'test_runs') + cts_test_runs = GetCtsInfo(arch, cts_release, 'test_runs') cts_results_json = {} for cts_test_run in cts_test_runs: iteration_cts_result = 0 @@ -259,13 +260,38 @@ return cts_result -def DeterminePlatform(device): - """Determines the platform based on the Android SDK level +def DetermineCtsRelease(device): + """Determines the CTS release based on the Android SDK level - Returns the first letter of the platform in uppercase - if platform is found, otherwise returns None + Args: + device: The DeviceUtils instance + Returns: + The first letter of the cts_release in uppercase. + Raises: + Exception: if we don't have the CTS tests for the device platform saved in + CIPD already. """ - return _SDK_PLATFORM_DICT.get(device.build_version_sdk) + cts_release = SDK_PLATFORM_DICT.get(device.build_version_sdk) + if not cts_release: + # Check if we're above the supported version range. + max_supported_sdk = max(SDK_PLATFORM_DICT.keys()) + if device.build_version_sdk > max_supported_sdk: + raise Exception("We don't have tests for API level {api_level}, try " + "running the {release} tests with `--cts-release " + "{release}`".format( + api_level=device.build_version_sdk, + release=SDK_PLATFORM_DICT.get(max_supported_sdk), + )) + # Otherwise, we must be below the supported version range. + min_supported_sdk = min(SDK_PLATFORM_DICT.keys()) + raise Exception("We don't support running CTS tests on platforms less " + "than {release} as the WebView is not updatable".format( + release=SDK_PLATFORM_DICT.get(min_supported_sdk), + )) + logging.info(('Using test APKs from CTS release=%s because ' + 'build.version.sdk=%s'), + cts_release, device.build_version_sdk) + return cts_release def DetermineArch(device): @@ -298,12 +324,16 @@ help=('Architecture to for CTS tests. Will auto-determine based on ' 'the device ro.product.cpu.abi property.')) parser.add_argument( + '--cts-release', + # TODO(aluo): --platform is deprecated (the meaning is unclear). '--platform', - choices=['L', 'M', 'N', 'O'], + choices=sorted(set(SDK_PLATFORM_DICT.values())), required=False, default=None, - help='Android platform version for CTS tests. ' - 'Will auto-determine based on SDK level by default.') + help='Which CTS release to use for the run. This should generally be <= ' + 'device OS level (otherwise, the newer tests will fail). If ' + 'unspecified, the script will auto-determine the release based on ' + 'device OS level.') parser.add_argument( '--skip-expected-failures', action='store_true', @@ -344,13 +374,8 @@ len(devices), device.serial) test_runner_args.extend(['-d', device.serial]) - if args.platform is None: - args.platform = DeterminePlatform(device) - if args.platform is None: - raise Exception('Could not auto-determine device platform, ' - 'please specifiy --platform') - - arch = args.arch if args.arch else DetermineArch(device) + arch = args.arch or DetermineArch(device) + cts_release = args.cts_release or DetermineCtsRelease(device) if (args.test_filter_file or args.test_filter or args.isolated_script_test_filter): @@ -364,13 +389,13 @@ if not args.module_apk: args.module_apk = 'CtsWebkitTestCases.apk' - platform_modules = GetCTSModuleNames(arch, args.platform) + platform_modules = GetCTSModuleNames(arch, cts_release) if args.module_apk and args.module_apk not in platform_modules: - raise Exception('--module-apk for arch==' + arch + 'and platform==' - + args.platform + ' must be one of: ' + raise Exception('--module-apk for arch==' + arch + 'and cts_release==' + + cts_release + ' must be one of: ' + ', '.join(platform_modules)) - return RunAllCTSTests(args, arch, test_runner_args) + return RunAllCTSTests(args, arch, cts_release, test_runner_args) if __name__ == '__main__':
diff --git a/android_webview/tools/run_cts_test.py b/android_webview/tools/run_cts_test.py index f6eab53..e2d07aa8 100644 --- a/android_webview/tools/run_cts_test.py +++ b/android_webview/tools/run_cts_test.py
@@ -14,6 +14,7 @@ os.path.dirname(__file__), os.pardir, os.pardir, 'build', 'android')) import devil_chromium # pylint: disable=import-error, unused-import from devil.android.ndk import abis # pylint: disable=import-error +from devil.android.sdk import version_codes # pylint: disable=import-error class _RunCtsTest(unittest.TestCase): """Unittests for the run_cts module. @@ -46,6 +47,38 @@ with self.assertRaises(Exception) as _: run_cts.DetermineArch(device) + def testDetermineCtsRelease_marshmallow(self): + logging_mock = mock.Mock() + logging.info = logging_mock + device = mock.Mock(build_version_sdk=version_codes.MARSHMALLOW) + self.assertEqual(run_cts.DetermineCtsRelease(device), 'M') + # We should log a message to explain how we auto-determined the CTS release. + # We don't assert the message itself, since that's rather strict. + logging_mock.assert_called() + + def testDetermineCtsRelease_tooLow(self): + device = mock.Mock(build_version_sdk=version_codes.KITKAT) + with self.assertRaises(Exception) as cm: + run_cts.DetermineCtsRelease(device) + message = str(cm.exception) + self.assertIn('not updatable', message) + + def testDetermineCtsRelease_tooHigh(self): + device = mock.Mock(build_version_sdk=version_codes.OREO) + # Mock this out with a couple version codes to check that the logic is + # correct, without making assumptions about what version_codes we may + # support in the future. + mock_sdk_platform_dict = { + version_codes.MARSHMALLOW: 'min fake release', + version_codes.NOUGAT: 'max fake release', + } + run_cts.SDK_PLATFORM_DICT = mock_sdk_platform_dict + with self.assertRaises(Exception) as cm: + run_cts.DetermineCtsRelease(device) + message = str(cm.exception) + self.assertIn('--cts-release max fake release', message, + msg='Should recommend the highest supported CTS release') + def testNoFilter_SkipExpectedFailures(self): mock_args = self._getArgsMock(skip_expected_failures=True) skips = run_cts.GetExpectedFailures()
diff --git a/ash/app_list/app_list_controller_impl.cc b/ash/app_list/app_list_controller_impl.cc index d801aa79..31254ce 100644 --- a/ash/app_list/app_list_controller_impl.cc +++ b/ash/app_list/app_list_controller_impl.cc
@@ -92,10 +92,11 @@ } // namespace AppListControllerImpl::AppListControllerImpl() - : presenter_(std::make_unique<AppListPresenterDelegateImpl>(this)), + : model_(std::make_unique<app_list::AppListModel>()), + presenter_(std::make_unique<AppListPresenterDelegateImpl>(this)), home_launcher_gesture_handler_( std::make_unique<HomeLauncherGestureHandler>(this)) { - model_.AddObserver(this); + model_->AddObserver(this); SessionController* session_controller = Shell::Get()->session_controller(); session_controller->AddObserver(this); @@ -130,7 +131,7 @@ } app_list::AppListModel* AppListControllerImpl::GetModel() { - return &model_; + return model_.get(); } app_list::SearchModel* AppListControllerImpl::GetSearchModel() { @@ -140,7 +141,7 @@ void AppListControllerImpl::AddItem(AppListItemMetadataPtr item_data) { const std::string folder_id = item_data->folder_id; if (folder_id.empty()) - model_.AddItem(CreateAppListItem(std::move(item_data))); + model_->AddItem(CreateAppListItem(std::move(item_data))); else AddItemToFolder(std::move(item_data), folder_id); } @@ -152,34 +153,34 @@ // the item to add is not in the target folder yet, and sets its folder id // later. So we should clear the folder id here to avoid breaking checks. item_data->folder_id.clear(); - model_.AddItemToFolder(CreateAppListItem(std::move(item_data)), folder_id); + model_->AddItemToFolder(CreateAppListItem(std::move(item_data)), folder_id); } void AppListControllerImpl::RemoveItem(const std::string& id) { - model_.DeleteItem(id); + model_->DeleteItem(id); } void AppListControllerImpl::RemoveUninstalledItem(const std::string& id) { - model_.DeleteUninstalledItem(id); + model_->DeleteUninstalledItem(id); } void AppListControllerImpl::MoveItemToFolder(const std::string& id, const std::string& folder_id) { - app_list::AppListItem* item = model_.FindItem(id); - model_.MoveItemToFolder(item, folder_id); + app_list::AppListItem* item = model_->FindItem(id); + model_->MoveItemToFolder(item, folder_id); } void AppListControllerImpl::SetStatus(ash::AppListModelStatus status) { - model_.SetStatus(status); + model_->SetStatus(status); } void AppListControllerImpl::SetState(ash::AppListState state) { - model_.SetState(state); + model_->SetState(state); } void AppListControllerImpl::HighlightItemInstalledFromUI( const std::string& id) { - model_.top_level_item_list()->HighlightItemInstalledFromUI(id); + model_->top_level_item_list()->HighlightItemInstalledFromUI(id); } void AppListControllerImpl::SetSearchEngineIsGoogle(bool is_google) { @@ -216,7 +217,7 @@ void AppListControllerImpl::SetItemMetadata(const std::string& id, AppListItemMetadataPtr data) { - app_list::AppListItem* item = model_.FindItem(id); + app_list::AppListItem* item = model_->FindItem(id); if (!item) return; @@ -226,15 +227,15 @@ // Update the item's position and name based on the metadata. if (!data->position.Equals(item->position())) - model_.SetItemPosition(item, data->position); + model_->SetItemPosition(item, data->position); if (data->short_name.empty()) { if (data->name != item->name()) { - model_.SetItemName(item, data->name); + model_->SetItemName(item, data->name); } } else { if (data->name != item->name() || data->short_name != item->short_name()) { - model_.SetItemNameAndShortName(item, data->name, data->short_name); + model_->SetItemNameAndShortName(item, data->name, data->short_name); } } @@ -247,14 +248,14 @@ void AppListControllerImpl::SetItemIcon(const std::string& id, const gfx::ImageSkia& icon) { - app_list::AppListItem* item = model_.FindItem(id); + app_list::AppListItem* item = model_->FindItem(id); if (item) item->SetIcon(icon); } void AppListControllerImpl::SetItemIsInstalling(const std::string& id, bool is_installing) { - app_list::AppListItem* item = model_.FindItem(id); + app_list::AppListItem* item = model_->FindItem(id); if (item) item->SetIsInstalling(is_installing); } @@ -262,7 +263,7 @@ void AppListControllerImpl::SetItemPercentDownloaded( const std::string& id, int32_t percent_downloaded) { - app_list::AppListItem* item = model_.FindItem(id); + app_list::AppListItem* item = model_->FindItem(id); if (item) item->SetPercentDownloaded(percent_downloaded); } @@ -271,7 +272,7 @@ std::vector<AppListItemMetadataPtr> apps, bool is_search_engine_google) { // Clear old model data. - model_.DeleteAllItems(); + model_->DeleteAllItems(); search_model_.DeleteAllResults(); // Populate new models. First populate folders and then other items to avoid @@ -322,8 +323,8 @@ void AppListControllerImpl::GetIdToAppListIndexMap( GetIdToAppListIndexMapCallback callback) { base::flat_map<std::string, uint16_t> id_to_app_list_index; - for (size_t i = 0; i < model_.top_level_item_list()->item_count(); ++i) - id_to_app_list_index[model_.top_level_item_list()->item_at(i)->id()] = i; + for (size_t i = 0; i < model_->top_level_item_list()->item_count(); ++i) + id_to_app_list_index[model_->top_level_item_list()->item_at(i)->id()] = i; std::move(callback).Run(id_to_app_list_index); } @@ -331,7 +332,8 @@ const std::string& oem_folder_name, const syncer::StringOrdinal& preferred_oem_position, FindOrCreateOemFolderCallback callback) { - app_list::AppListFolderItem* oem_folder = model_.FindFolderItem(kOemFolderId); + app_list::AppListFolderItem* oem_folder = + model_->FindFolderItem(kOemFolderId); if (!oem_folder) { std::unique_ptr<app_list::AppListFolderItem> new_folder = std::make_unique<app_list::AppListFolderItem>(kOemFolderId); @@ -341,10 +343,10 @@ // Do not create a sync item for the OEM folder here, do it in // ResolveFolderPositions() when the item position is finalized. oem_folder = static_cast<app_list::AppListFolderItem*>( - model_.AddItem(std::move(new_folder))); - model_.SetItemPosition(oem_folder, oem_position); + model_->AddItem(std::move(new_folder))); + model_->SetItemPosition(oem_folder, oem_position); } - model_.SetItemName(oem_folder, oem_folder_name); + model_->SetItemName(oem_folder, oem_folder_name); std::move(callback).Run(oem_folder->CloneMetadata()); } @@ -358,7 +360,7 @@ const syncer::StringOrdinal& oem_folder_pos = preferred_oem_position.IsValid() ? preferred_oem_position : GetOemFolderPos(); - model_.SetItemPosition(ash_oem_folder, oem_folder_pos); + model_->SetItemPosition(ash_oem_folder, oem_folder_pos); metadata = ash_oem_folder->CloneMetadata(); } std::move(callback).Run(std::move(metadata)); @@ -533,7 +535,7 @@ } app_list::AppListViewState AppListControllerImpl::GetAppListViewState() { - return model_.state_fullscreen(); + return model_->state_fullscreen(); } void AppListControllerImpl::OnWindowDragStarted() { @@ -565,7 +567,7 @@ shell->wallpaper_controller()->RemoveObserver(this); shell->tablet_mode_controller()->RemoveObserver(this); shell->session_controller()->RemoveObserver(this); - model_.RemoveObserver(this); + model_->RemoveObserver(this); } void AppListControllerImpl::OnOverviewModeStarting() { @@ -794,6 +796,13 @@ return app_list::AppListViewState::CLOSED; } +void AppListControllerImpl::SetAppListModelForTest( + std::unique_ptr<app_list::AppListModel> model) { + model_->RemoveObserver(this); + model_ = std::move(model); + model_->AddObserver(this); +} + //////////////////////////////////////////////////////////////////////////////// // Methods of |client_|: @@ -1040,7 +1049,7 @@ // followed by a pre-installed app (e.g. Search), so the poosition should be // stable. TODO(stevenjb): consider explicitly setting the OEM folder location // along with the name in ServicesCustomizationDocument::SetOemFolderName(). - app_list::AppListItemList* item_list = model_.top_level_item_list(); + app_list::AppListItemList* item_list = model_->top_level_item_list(); if (!item_list->item_count()) { LOG(ERROR) << "No top level item was found. " << "Placing OEM folder at the beginning."; @@ -1091,7 +1100,7 @@ app_list::AppListFolderItem* AppListControllerImpl::FindFolderItem( const std::string& folder_id) { - return model_.FindFolderItem(folder_id); + return model_->FindFolderItem(folder_id); } void AppListControllerImpl::UpdateHomeLauncherVisibility() {
diff --git a/ash/app_list/app_list_controller_impl.h b/ash/app_list/app_list_controller_impl.h index 64f13f6..3c243c8c 100644 --- a/ash/app_list/app_list_controller_impl.h +++ b/ash/app_list/app_list_controller_impl.h
@@ -274,6 +274,8 @@ const ui::GestureEvent& gesture_in_screen, float launcher_above_shelf_bottom_amount) const; + void SetAppListModelForTest(std::unique_ptr<app_list::AppListModel> model); + private: syncer::StringOrdinal GetOemFolderPos(); std::unique_ptr<app_list::AppListItem> CreateAppListItem( @@ -296,7 +298,7 @@ mojom::AppListClientPtr client_; - app_list::AppListModel model_; + std::unique_ptr<app_list::AppListModel> model_; app_list::SearchModel search_model_; // |presenter_| should be put below |client_| and |model_| to prevent a crash
diff --git a/ash/app_list/views/apps_container_view.cc b/ash/app_list/views/apps_container_view.cc index 6466327..c1f6c82 100644 --- a/ash/app_list/views/apps_container_view.cc +++ b/ash/app_list/views/apps_container_view.cc
@@ -64,7 +64,6 @@ suggestion_chip_container_view_ = new SuggestionChipContainerView(contents_view); AddChildView(suggestion_chip_container_view_); - UpdateSuggestionChips(); apps_grid_view_ = new AppsGridView(contents_view_, nullptr); apps_grid_view_->SetLayout(AppListConfig::instance().preferred_cols(), @@ -420,6 +419,14 @@ return search_box_bounds; } +void AppsContainerView::UpdateSuggestionChips() { + suggestion_chip_container_view_->SetResults( + contents_view_->GetAppListMainView() + ->view_delegate() + ->GetSearchModel() + ->results()); +} + void AppsContainerView::SetShowState(ShowState show_state, bool show_apps_with_animation) { if (show_state_ == show_state) @@ -435,7 +442,6 @@ case SHOW_APPS: folder_background_view_->SetVisible(false); apps_grid_view_->ResetForShowApps(); - UpdateSuggestionChips(); if (show_apps_with_animation) app_list_folder_view_->ScheduleShowHideAnimation(false, false); else @@ -454,14 +460,6 @@ } } -void AppsContainerView::UpdateSuggestionChips() { - suggestion_chip_container_view_->SetResults( - contents_view_->GetAppListMainView() - ->view_delegate() - ->GetSearchModel() - ->results()); -} - void AppsContainerView::DisableFocusForShowingActiveFolder(bool disabled) { suggestion_chip_container_view_->DisableFocusForShowingActiveFolder(disabled); apps_grid_view_->DisableFocusForShowingActiveFolder(disabled);
diff --git a/ash/app_list/views/apps_container_view.h b/ash/app_list/views/apps_container_view.h index e60daf7c..9141431 100644 --- a/ash/app_list/views/apps_container_view.h +++ b/ash/app_list/views/apps_container_view.h
@@ -97,6 +97,9 @@ } AppListFolderView* app_list_folder_view() { return app_list_folder_view_; } + // Updates suggestion chips from app list model. + void UpdateSuggestionChips(); + private: enum ShowState { SHOW_NONE, // initial state @@ -107,9 +110,6 @@ void SetShowState(ShowState show_state, bool show_apps_with_animation); - // Updates suggestion chips from app list model. - void UpdateSuggestionChips(); - // Suggestion chips and apps grid view become unfocusable if |disabled| is // true. This is used to trap focus within the folder when it is opened. void DisableFocusForShowingActiveFolder(bool disabled);
diff --git a/ash/app_list/views/contents_view.cc b/ash/app_list/views/contents_view.cc index 8eabd94..ee155372 100644 --- a/ash/app_list/views/contents_view.cc +++ b/ash/app_list/views/contents_view.cc
@@ -135,6 +135,10 @@ pagination_model_.SelectPage(initial_page_index, false); + // Update suggestion chips after valid page is selected to prevent the update + // from being ignored. + GetAppsContainerView()->UpdateSuggestionChips(); + ActivePageChanged(); }
diff --git a/ash/app_list/views/search_box_view.cc b/ash/app_list/views/search_box_view.cc index 8352b3f..fcd7a78 100644 --- a/ash/app_list/views/search_box_view.cc +++ b/ash/app_list/views/search_box_view.cc
@@ -330,7 +330,7 @@ ash::AppListState state) const { if (state == ash::AppListState::kStateSearchResults) return AppListConfig::instance().card_background_color(); - return background_color(); + return search_box::kSearchBoxBackgroundDefault; } void SearchBoxView::UpdateOpacity() { @@ -436,7 +436,7 @@ gfx::CreateVectorIcon(views::kIcCloseIcon, kCloseIconSize, search_box_color())); search_box()->set_placeholder_text_color(search_box_color()); - UpdateBackgroundColor(background_color()); + UpdateBackgroundColor(search_box::kSearchBoxBackgroundDefault); SchedulePaint(); }
diff --git a/ash/app_list/views/search_result_suggestion_chip_view.cc b/ash/app_list/views/search_result_suggestion_chip_view.cc index 4a816930..ad04ce4e 100644 --- a/ash/app_list/views/search_result_suggestion_chip_view.cc +++ b/ash/app_list/views/search_result_suggestion_chip_view.cc
@@ -38,6 +38,9 @@ SearchResultSuggestionChipView::SearchResultSuggestionChipView( AppListViewDelegate* view_delegate) : view_delegate_(view_delegate), weak_ptr_factory_(this) { + // Make it unfocusable to avoid violating accessibiliy rule since its child + // view |suggestion_chip_view_| is focusable. + SetFocusBehavior(FocusBehavior::NEVER); suggestion_chip_view_ = new SuggestionChipView( app_list::SuggestionChipView::Params(), /* listener */ this); AddChildView(suggestion_chip_view_);
diff --git a/ash/components/shortcut_viewer/views/ksv_search_box_view.cc b/ash/components/shortcut_viewer/views/ksv_search_box_view.cc index 9a5276f..7a67814e 100644 --- a/ash/components/shortcut_viewer/views/ksv_search_box_view.cc +++ b/ash/components/shortcut_viewer/views/ksv_search_box_view.cc
@@ -32,7 +32,7 @@ KSVSearchBoxView::KSVSearchBoxView(search_box::SearchBoxViewDelegate* delegate) : search_box::SearchBoxViewBase(delegate) { SetSearchBoxBackgroundCornerRadius(kBorderCornerRadius); - SetSearchBoxBackgroundColor(kDefaultSearchBoxBackgroundColor); + UpdateBackgroundColor(kDefaultSearchBoxBackgroundColor); search_box()->SetBackgroundColor(SK_ColorTRANSPARENT); search_box()->SetColor(gfx::kGoogleGrey900); search_box()->set_placeholder_text_color(gfx::kGoogleGrey900); @@ -83,7 +83,7 @@ } void KSVSearchBoxView::UpdateBackgroundColor(SkColor color) { - SetSearchBoxBackgroundColor(color); + GetSearchBoxBackground()->SetNativeControlColor(color); } void KSVSearchBoxView::UpdateSearchBoxBorder() { @@ -98,12 +98,12 @@ if (search_box()->HasFocus() || is_search_box_active()) { SetBorder(views::CreateRoundedRectBorder( kBorderThichness, kBorderCornerRadius, kActiveBorderColor)); - SetSearchBoxBackgroundColor(gfx::kGoogleGrey100); + UpdateBackgroundColor(gfx::kGoogleGrey100); return; } SetBorder(views::CreateRoundedRectBorder( kBorderThichness, kBorderCornerRadius, SK_ColorTRANSPARENT)); - SetSearchBoxBackgroundColor(kDefaultSearchBoxBackgroundColor); + UpdateBackgroundColor(kDefaultSearchBoxBackgroundColor); } void KSVSearchBoxView::SetupCloseButton() {
diff --git a/ash/login/ui/login_big_user_view.cc b/ash/login/ui/login_big_user_view.cc index bd081de..306fdfd 100644 --- a/ash/login/ui/login_big_user_view.cc +++ b/ash/login/ui/login_big_user_view.cc
@@ -81,7 +81,9 @@ DCHECK(OnlyOneSet(public_account_, auth_user_)); DCHECK(auth_user_); - if (!auth_user_) + // Do not show parent access if LoginBigUserView does not host regular user + // view or if ParentAccessView is already shown. + if (!auth_user_ || parent_access_) return; DCHECK(IsChildAccountUser(auth_user_->current_user()));
diff --git a/ash/login/ui/parent_access_view.cc b/ash/login/ui/parent_access_view.cc index d1be294..ad00e8d 100644 --- a/ash/login/ui/parent_access_view.cc +++ b/ash/login/ui/parent_access_view.cc
@@ -172,6 +172,8 @@ // All key pressed events not handled below are ignored. if (key_code >= ui::VKEY_0 && key_code <= ui::VKEY_9) { InsertDigit(key_code - ui::VKEY_0); + } else if (key_code >= ui::VKEY_NUMPAD0 && key_code <= ui::VKEY_NUMPAD9) { + InsertDigit(key_code - ui::VKEY_NUMPAD0); } else if (key_code == ui::VKEY_LEFT) { FocusPreviousField(); } else if (key_code == ui::VKEY_RIGHT) {
diff --git a/ash/login/ui/parent_access_view_unittest.cc b/ash/login/ui/parent_access_view_unittest.cc index 6beb019..1210234 100644 --- a/ash/login/ui/parent_access_view_unittest.cc +++ b/ash/login/ui/parent_access_view_unittest.cc
@@ -112,6 +112,21 @@ EXPECT_EQ(1, submit_action_); } +// Tests that access code can be entered with numpad. +TEST_F(ParentAccessViewTest, Numpad) { + ParentAccessView::TestApi test_api(view_); + + ui::test::EventGenerator* generator = GetEventGenerator(); + for (int i = 0; i < 6; ++i) + generator->PressKey(ui::KeyboardCode(ui::VKEY_NUMPAD0 + i), ui::EF_NONE); + EXPECT_TRUE(test_api.submit_button()->enabled()); + + SimulateButtonPress(test_api.submit_button()); + ASSERT_TRUE(code_.has_value()); + EXPECT_EQ("012345", *code_); + EXPECT_EQ(1, submit_action_); +} + // Tests that backspace button works. TEST_F(ParentAccessViewTest, Backspace) { ParentAccessView::TestApi test_api(view_);
diff --git a/ash/public/cpp/app_list/app_list_features.cc b/ash/public/cpp/app_list/app_list_features.cc index db0a6ed..c0231c5 100644 --- a/ash/public/cpp/app_list/app_list_features.cc +++ b/ash/public/cpp/app_list/app_list_features.cc
@@ -27,6 +27,8 @@ "EnableZeroStateSuggestions", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kEnableAppListSearchAutocomplete{ "EnableAppListSearchAutocomplete", base::FEATURE_ENABLED_BY_DEFAULT}; +const base::Feature kEnableAdaptiveResultRanker{ + "EnableAdaptiveResultRanker", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kEnableAppSearchResultRanker{ "EnableAppSearchResultRanker", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kEnableAppReinstallZeroState{ @@ -68,6 +70,10 @@ return base::FeatureList::IsEnabled(kEnableAppListSearchAutocomplete); } +bool IsAdaptiveResultRankerEnabled() { + return base::FeatureList::IsEnabled(kEnableAdaptiveResultRanker); +} + bool IsAppSearchResultRankerEnabled() { return base::FeatureList::IsEnabled(kEnableAppSearchResultRanker); }
diff --git a/ash/public/cpp/app_list/app_list_features.h b/ash/public/cpp/app_list/app_list_features.h index 2c192d4..3f3eaea 100644 --- a/ash/public/cpp/app_list/app_list_features.h +++ b/ash/public/cpp/app_list/app_list_features.h
@@ -44,6 +44,9 @@ // Enables the feature to autocomplete text typed in the AppList search box. ASH_PUBLIC_EXPORT extern const base::Feature kEnableAppListSearchAutocomplete; +// Enable an adaptive model that tweaks search result scores. +ASH_PUBLIC_EXPORT extern const base::Feature kEnableAdaptiveResultRanker; + // Enables the feature to rank app search result using AppSearchResultRanker. ASH_PUBLIC_EXPORT extern const base::Feature kEnableAppSearchResultRanker; @@ -62,6 +65,7 @@ bool ASH_PUBLIC_EXPORT IsSettingsShortcutSearchEnabled(); bool ASH_PUBLIC_EXPORT IsZeroStateSuggestionsEnabled(); bool ASH_PUBLIC_EXPORT IsAppListSearchAutocompleteEnabled(); +bool ASH_PUBLIC_EXPORT IsAdaptiveResultRankerEnabled(); bool ASH_PUBLIC_EXPORT IsAppSearchResultRankerEnabled(); bool ASH_PUBLIC_EXPORT IsAppReinstallZeroStateEnabled(); bool ASH_PUBLIC_EXPORT IsEmbeddedAssistantUIEnabled();
diff --git a/ash/public/cpp/app_list/app_list_struct_traits.h b/ash/public/cpp/app_list/app_list_struct_traits.h index b644a72..73e714e 100644 --- a/ash/public/cpp/app_list/app_list_struct_traits.h +++ b/ash/public/cpp/app_list/app_list_struct_traits.h
@@ -115,6 +115,8 @@ return ash::mojom::SearchResultType::kAnswerCard; case ash::SearchResultType::kPlayStoreReinstallApp: return ash::mojom::SearchResultType::kPlayStoreReinstallApp; + case ash::SearchResultType::kArcAppShortcut: + return ash::mojom::SearchResultType::kArcAppShortcut; case ash::SearchResultType::kUnknown: break; } @@ -155,6 +157,9 @@ case ash::mojom::SearchResultType::kPlayStoreReinstallApp: *out = ash::SearchResultType::kPlayStoreReinstallApp; return true; + case ash::mojom::SearchResultType::kArcAppShortcut: + *out = ash::SearchResultType::kArcAppShortcut; + return true; } NOTREACHED(); return false;
diff --git a/ash/public/cpp/app_list/app_list_types.h b/ash/public/cpp/app_list/app_list_types.h index b8e78a7..f55a215 100644 --- a/ash/public/cpp/app_list/app_list_types.h +++ b/ash/public/cpp/app_list/app_list_types.h
@@ -48,6 +48,7 @@ kLauncher, // Results from launcher search (currently only from Files). kAnswerCard, // WebContents based answer card. kPlayStoreReinstallApp, // Reinstall recommendations from PlayStore. + kArcAppShortcut, // ARC++ app shortcuts. // Add new values here. };
diff --git a/ash/public/interfaces/app_list.mojom b/ash/public/interfaces/app_list.mojom index a28933a..82a731276 100644 --- a/ash/public/interfaces/app_list.mojom +++ b/ash/public/interfaces/app_list.mojom
@@ -121,6 +121,7 @@ kLauncher, // Results from launcher search (currently only from Files). kAnswerCard, // WebContents based answer card. kPlayStoreReinstallApp, // Reinstall recommendations from PlayStore. + kArcAppShortcut, // ARC++ app shortcuts. // Add new values here. };
diff --git a/ash/system/model/update_model.cc b/ash/system/model/update_model.cc index e694954d2..f0e5e8b 100644 --- a/ash/system/model/update_model.cc +++ b/ash/system/model/update_model.cc
@@ -46,8 +46,8 @@ } mojom::UpdateSeverity UpdateModel::GetSeverity() const { - // TODO(weidongg/691108): adjust severity according the amount of time - // passing after update is available over cellular connection. Use low + // TODO(https://crbug.com/927010): adjust severity according the amount of + // time passing after update is available over cellular connection. Use low // severity for update available over cellular connection. return update_over_cellular_available_ ? mojom::UpdateSeverity::LOW : severity_;
diff --git a/ash/wm/overview/caption_container_view.cc b/ash/wm/overview/caption_container_view.cc index 76a8d028..64b80ec 100644 --- a/ash/wm/overview/caption_container_view.cc +++ b/ash/wm/overview/caption_container_view.cc
@@ -153,7 +153,7 @@ if (listener()) { gfx::Point location(event.location()); views::View::ConvertPointToScreen(this, &location); - listener()->HandlePressEvent(location); + listener()->HandlePressEvent(gfx::PointF(location)); return true; } return views::Button::OnMousePressed(event); @@ -163,7 +163,7 @@ if (listener()) { gfx::Point location(event.location()); views::View::ConvertPointToScreen(this, &location); - listener()->HandleDragEvent(location); + listener()->HandleDragEvent(gfx::PointF(location)); return true; } return views::Button::OnMouseDragged(event); @@ -173,7 +173,7 @@ if (listener()) { gfx::Point location(event.location()); views::View::ConvertPointToScreen(this, &location); - listener()->HandleReleaseEvent(location); + listener()->HandleReleaseEvent(gfx::PointF(location)); return; } views::Button::OnMouseReleased(event); @@ -186,8 +186,8 @@ } if (listener()) { - gfx::Point location(event->location()); - views::View::ConvertPointToScreen(this, &location); + const gfx::PointF location = + event->details().bounding_box_f().CenterPoint(); switch (event->type()) { case ui::ET_GESTURE_TAP_DOWN: listener()->HandlePressEvent(location);
diff --git a/ash/wm/overview/overview_controller.cc b/ash/wm/overview/overview_controller.cc index 6c08d80..6bbe587b6 100644 --- a/ash/wm/overview/overview_controller.cc +++ b/ash/wm/overview/overview_controller.cc
@@ -5,7 +5,6 @@ #include "ash/wm/overview/overview_controller.h" #include <algorithm> -#include <vector> #include "ash/app_list/app_list_controller_impl.h" #include "ash/public/cpp/window_properties.h"
diff --git a/ash/wm/overview/overview_grid.cc b/ash/wm/overview/overview_grid.cc index 18bc21e..8d59c7d 100644 --- a/ash/wm/overview/overview_grid.cc +++ b/ash/wm/overview/overview_grid.cc
@@ -502,7 +502,7 @@ if (window_list_.empty()) return; - std::vector<gfx::Rect> rects = GetWindowRects(ignored_item); + std::vector<gfx::RectF> rects = GetWindowRects(ignored_item); // Position the windows centering the left-aligned rows vertically. Do not // position |ignored_item| if it is not nullptr and matches a item in @@ -546,7 +546,7 @@ bool recreate_selection_widget = false; bool out_of_bounds = false; bool changed_selection_index = false; - gfx::Rect old_bounds; + gfx::RectF old_bounds; if (SelectedWindow()) { old_bounds = SelectedWindow()->target_bounds(); // Make the old selected window header non-transparent first. @@ -1080,11 +1080,11 @@ // Get the bounds of the windows currently, and the bounds if |item| were to // be removed. - std::vector<gfx::Rect> src_rects; + std::vector<gfx::RectF> src_rects; for (const auto& window_item : window_list_) src_rects.push_back(window_item->target_bounds()); - std::vector<gfx::Rect> dst_rects = GetWindowRects(item); + std::vector<gfx::RectF> dst_rects = GetWindowRects(item); // Get the index of |item|. size_t index = @@ -1101,10 +1101,10 @@ // should not be used. The item at |index| is marked with a 0. The heights of // items are all set to the same value so a new row is determined if the y // value has changed from the previous item. - auto get_rows = [](const std::vector<gfx::Rect>& bounds_list, size_t index) { + auto get_rows = [](const std::vector<gfx::RectF>& bounds_list, size_t index) { std::vector<int> row_numbers; int current_row = 1; - int last_y = 0; + float last_y = 0; for (size_t i = 0; i < bounds_list.size(); ++i) { if (i == index) { row_numbers.push_back(0); @@ -1204,8 +1204,8 @@ OverviewItem* nudged_item = window_list_[data.index].get(); double nudge_param = value * value / 30.0; nudge_param = base::ClampToRange(nudge_param, 0.0, 1.0); - gfx::Rect bounds = - gfx::Tween::RectValueBetween(nudge_param, data.src, data.dst); + gfx::RectF bounds = + gfx::Tween::RectFValueBetween(nudge_param, data.src, data.dst); nudged_item->SetBounds(bounds, OVERVIEW_ANIMATION_NONE); } } @@ -1243,19 +1243,18 @@ shield_window->layer()->SetOpacity(opacity); // Apply the same translation and opacity change to the windows in the grid. - for (const auto& window_item : window_list_) { + for (const auto& window_item : window_list_) window_item->UpdateYPositionAndOpacity(new_y, opacity, callback); - } } aura::Window* OverviewGrid::GetTargetWindowOnLocation( const gfx::Point& location_in_screen) { // Find the overview item that contains |location_in_screen|. - auto iter = - std::find_if(window_list_.begin(), window_list_.end(), - [&location_in_screen](std::unique_ptr<OverviewItem>& item) { - return item->target_bounds().Contains(location_in_screen); - }); + auto iter = std::find_if( + window_list_.begin(), window_list_.end(), + [&location_in_screen](std::unique_ptr<OverviewItem>& item) { + return item->target_bounds().Contains(gfx::PointF(location_in_screen)); + }); return (iter != window_list_.end()) ? (*iter)->GetWindow() : nullptr; } @@ -1302,7 +1301,8 @@ kWindowSelectionRadius, SK_ColorTRANSPARENT, 0.f, /*parent=*/nullptr, /*stack_on_top=*/true, /*accept_events=*/false); aura::Window* widget_window = selection_widget_->GetNativeWindow(); - gfx::Rect target_bounds = SelectedWindow()->target_bounds(); + gfx::Rect target_bounds = + gfx::ToEnclosedRect(SelectedWindow()->target_bounds()); ::wm::ConvertRectFromScreen(root_window_, &target_bounds); gfx::Vector2d fade_out_direction = GetSlideVectorForFadeIn(direction, target_bounds); @@ -1360,7 +1360,7 @@ } void OverviewGrid::MoveSelectionWidgetToTarget(bool animate) { - gfx::Rect bounds = SelectedWindow()->target_bounds(); + gfx::Rect bounds = gfx::ToEnclosingRect(SelectedWindow()->target_bounds()); ::wm::ConvertRectFromScreen(root_window_, &bounds); if (animate) { ScopedOverviewAnimationSettings settings( @@ -1388,7 +1388,7 @@ } } -std::vector<gfx::Rect> OverviewGrid::GetWindowRects( +std::vector<gfx::RectF> OverviewGrid::GetWindowRects( OverviewItem* ignored_item) { gfx::Rect total_bounds = bounds_; @@ -1404,7 +1404,7 @@ kOverviewVerticalInset * (total_bounds.height() - 2 * horizontal_inset); total_bounds.Inset(std::max(0, horizontal_inset - kWindowMargin), std::max(0, vertical_inset - kWindowMargin)); - std::vector<gfx::Rect> rects; + std::vector<gfx::RectF> rects; // Keep track of the lowest coordinate. int max_bottom = total_bounds.y(); @@ -1428,8 +1428,7 @@ // true and the rows are balanced by repeatedly squeezing the widest row to // cause windows to overflow to the subsequent rows. int low_height = 2 * kWindowMargin; - int high_height = - std::max(low_height, static_cast<int>(total_bounds.height() + 1)); + int high_height = std::max(low_height, total_bounds.height() + 1); int height = 0.5 * (low_height + high_height); bool height_fixed = false; @@ -1498,7 +1497,7 @@ ignored_item, &rects, &max_bottom, &min_right, &max_right); } - gfx::Vector2d offset(0, (total_bounds.bottom() - max_bottom) / 2); + gfx::Vector2dF offset(0, (total_bounds.bottom() - max_bottom) / 2.f); for (size_t i = 0; i < rects.size(); ++i) rects[i] += offset; return rects; @@ -1507,7 +1506,7 @@ bool OverviewGrid::FitWindowRectsInBounds(const gfx::Rect& bounds, int height, OverviewItem* ignored_item, - std::vector<gfx::Rect>* out_rects, + std::vector<gfx::RectF>* out_rects, int* out_max_bottom, int* out_min_right, int* out_max_right) { @@ -1539,7 +1538,7 @@ continue; } - const gfx::Rect target_bounds = window->GetTargetBoundsInScreen(); + const gfx::RectF target_bounds = window->GetTargetBoundsInScreen(); int width = std::max(1, gfx::ToFlooredInt(target_bounds.width() * window->GetItemScale(item_size)) + 2 * kWindowMargin); @@ -1582,10 +1581,10 @@ } // Position the current rect. - (*out_rects)[i].SetRect(left, top, width, height); + (*out_rects)[i] = gfx::RectF(gfx::Rect(left, top, width, height)); // Increment horizontal position using sanitized positive |width()|. - left += (*out_rects)[i].width(); + left += gfx::ToRoundedInt((*out_rects)[i].width()); if (++i == out_rects->size()) { // Update the narrowest and widest row width for the last row. @@ -1652,8 +1651,8 @@ if (old_bounds != new_bounds) { // It's for smoother animation. gfx::Transform transform = - ScopedOverviewTransformWindow::GetTransformForRect(new_bounds, - old_bounds); + ScopedOverviewTransformWindow::GetTransformForRect( + gfx::RectF(new_bounds), gfx::RectF(old_bounds)); dragged_window->SetTransform(transform); } dragged_window->ClearProperty(ash::kCanAttachToAnotherWindowKey);
diff --git a/ash/wm/overview/overview_grid.h b/ash/wm/overview/overview_grid.h index 03d5dca..fb7c59c 100644 --- a/ash/wm/overview/overview_grid.h +++ b/ash/wm/overview/overview_grid.h
@@ -8,7 +8,6 @@ #include <stddef.h> #include <memory> -#include <set> #include <vector> #include "ash/rotator/screen_rotation_animator_observer.h" @@ -19,6 +18,7 @@ #include "base/scoped_observer.h" #include "ui/aura/window_observer.h" #include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/rect_f.h" namespace ui { class Shadow; @@ -29,7 +29,6 @@ } namespace ash { - class OverviewItem; // Represents a grid of windows in the Overview Mode in a particular root @@ -253,8 +252,8 @@ // Struct which holds data required to perform nudges. struct NudgeData { size_t index; - gfx::Rect src; - gfx::Rect dst; + gfx::RectF src; + gfx::RectF dst; }; // Initializes the screen shield widget. @@ -282,7 +281,7 @@ // Overall this achieves the goals of maximum size for previews (or maximum // row height which is equivalent assuming fixed height), balanced rows and // minimal wasted space. - std::vector<gfx::Rect> GetWindowRects(OverviewItem* ignored_item); + std::vector<gfx::RectF> GetWindowRects(OverviewItem* ignored_item); // Attempts to fit all |out_rects| inside |bounds|. The method ensures that // the |out_rects| vector has appropriate size and populates it with the @@ -297,7 +296,7 @@ bool FitWindowRectsInBounds(const gfx::Rect& bounds, int height, OverviewItem* ignored_item, - std::vector<gfx::Rect>* out_rects, + std::vector<gfx::RectF>* out_rects, int* out_max_bottom, int* out_min_right, int* out_max_right);
diff --git a/ash/wm/overview/overview_item.cc b/ash/wm/overview/overview_item.cc index d6d157f5..6cdc42e6 100644 --- a/ash/wm/overview/overview_item.cc +++ b/ash/wm/overview/overview_item.cc
@@ -228,21 +228,21 @@ } float OverviewItem::GetItemScale(const gfx::Size& size) { - gfx::Size inset_size(size.width(), size.height() - 2 * kWindowMargin); + gfx::SizeF inset_size(size.width(), size.height() - 2 * kWindowMargin); return ScopedOverviewTransformWindow::GetItemScale( GetTargetBoundsInScreen().size(), inset_size, transform_window_.GetTopInset(), kHeaderHeightDp); } -gfx::Rect OverviewItem::GetTargetBoundsInScreen() const { +gfx::RectF OverviewItem::GetTargetBoundsInScreen() const { return ::ash::GetTargetBoundsInScreen(transform_window_.GetOverviewWindow()); } -gfx::Rect OverviewItem::GetTransformedBounds() const { +gfx::RectF OverviewItem::GetTransformedBounds() const { return transform_window_.GetTransformedBounds(); } -void OverviewItem::SetBounds(const gfx::Rect& target_bounds, +void OverviewItem::SetBounds(const gfx::RectF& target_bounds, OverviewAnimationType animation_type) { if (in_bounds_update_) return; @@ -261,7 +261,7 @@ const bool is_first_update = target_bounds_.IsEmpty(); target_bounds_ = target_bounds; - gfx::Rect inset_bounds(target_bounds); + gfx::RectF inset_bounds(target_bounds); inset_bounds.Inset(kWindowMargin, kWindowMargin); // Do not animate if entering when the window is minimized, as it will be @@ -317,7 +317,7 @@ } void OverviewItem::CloseWindow() { - gfx::Rect inset_bounds(target_bounds_); + gfx::RectF inset_bounds(target_bounds_); inset_bounds.Inset(target_bounds_.width() * kPreCloseScale, target_bounds_.height() * kPreCloseScale); // Scale down both the window and label. @@ -397,21 +397,21 @@ } gfx::Rect OverviewItem::GetBoundsOfSelectedItem() { - gfx::Rect original_bounds = target_bounds(); + gfx::RectF original_bounds = target_bounds(); ScaleUpSelectedItem(OVERVIEW_ANIMATION_NONE); - gfx::Rect selected_bounds = transform_window_.GetTransformedBounds(); + gfx::RectF selected_bounds = transform_window_.GetTransformedBounds(); SetBounds(original_bounds, OVERVIEW_ANIMATION_NONE); - return selected_bounds; + return gfx::ToEnclosedRect(selected_bounds); } void OverviewItem::ScaleUpSelectedItem(OverviewAnimationType animation_type) { - gfx::Rect scaled_bounds(target_bounds()); + gfx::RectF scaled_bounds = target_bounds(); scaled_bounds.Inset(-scaled_bounds.width() * kDragWindowScale, -scaled_bounds.height() * kDragWindowScale); SetBounds(scaled_bounds, animation_type); } -void OverviewItem::HandlePressEvent(const gfx::Point& location_in_screen) { +void OverviewItem::HandlePressEvent(const gfx::PointF& location_in_screen) { // We allow switching finger while dragging, but do not allow dragging two or // more items. if (overview_session_->window_drag_controller() && @@ -423,7 +423,7 @@ overview_session_->InitiateDrag(this, location_in_screen); } -void OverviewItem::HandleReleaseEvent(const gfx::Point& location_in_screen) { +void OverviewItem::HandleReleaseEvent(const gfx::PointF& location_in_screen) { if (!IsDragItem()) return; @@ -431,21 +431,21 @@ overview_session_->CompleteDrag(this, location_in_screen); } -void OverviewItem::HandleDragEvent(const gfx::Point& location_in_screen) { +void OverviewItem::HandleDragEvent(const gfx::PointF& location_in_screen) { if (!IsDragItem()) return; overview_session_->Drag(this, location_in_screen); } -void OverviewItem::HandleLongPressEvent(const gfx::Point& location_in_screen) { +void OverviewItem::HandleLongPressEvent(const gfx::PointF& location_in_screen) { if (!ShouldAllowSplitView()) return; overview_session_->StartSplitViewDragMode(location_in_screen); } -void OverviewItem::HandleFlingStartEvent(const gfx::Point& location_in_screen, +void OverviewItem::HandleFlingStartEvent(const gfx::PointF& location_in_screen, float velocity_x, float velocity_y) { overview_session_->Fling(this, location_in_screen, velocity_x, velocity_y); @@ -571,7 +571,8 @@ } transform_window_.UpdateMask(true); - SetShadowBounds(transform_window_.GetTransformedBounds()); + SetShadowBounds( + gfx::ToEnclosedRect(transform_window_.GetTransformedBounds())); } void OverviewItem::OnStartingAnimationComplete() { @@ -673,24 +674,24 @@ return shadow_->content_bounds(); } -void OverviewItem::SetItemBounds(const gfx::Rect& target_bounds, +void OverviewItem::SetItemBounds(const gfx::RectF& target_bounds, OverviewAnimationType animation_type) { aura::Window* window = GetWindow(); DCHECK(root_window_ == window->GetRootWindow()); - gfx::Rect screen_rect = GetTargetBoundsInScreen(); + gfx::RectF screen_rect = gfx::RectF(GetTargetBoundsInScreen()); // Avoid division by zero by ensuring screen bounds is not empty. - gfx::Size screen_size(screen_rect.size()); - screen_size.SetToMax(gfx::Size(1, 1)); + gfx::SizeF screen_size(screen_rect.size()); + screen_size.SetToMax(gfx::SizeF(1.f, 1.f)); screen_rect.set_size(screen_size); const int top_view_inset = transform_window_.GetTopInset(); - gfx::Rect overview_item_bounds = + gfx::RectF overview_item_bounds = transform_window_.ShrinkRectToFitPreservingAspectRatio( screen_rect, target_bounds, top_view_inset, kHeaderHeightDp); // Do not set transform for drop target, set bounds instead. if (overview_grid_->IsDropTargetWindow(window)) { - window->layer()->SetBounds(overview_item_bounds); + window->layer()->SetBounds(gfx::ToEnclosedRect(overview_item_bounds)); transform_window_.GetOverviewWindow()->SetTransform(gfx::Transform()); return; } @@ -735,10 +736,10 @@ } void OverviewItem::UpdateHeaderLayout(OverviewAnimationType animation_type) { - gfx::Rect transformed_window_bounds = + gfx::RectF transformed_window_bounds = transform_window_.overview_bounds().value_or( transform_window_.GetTransformedBounds()); - ::wm::ConvertRectFromScreen(root_window_, &transformed_window_bounds); + ::wm::TranslateRectFromScreen(root_window_, &transformed_window_bounds); gfx::Rect label_rect(kHeaderHeightDp, kHeaderHeightDp); label_rect.set_width(transformed_window_bounds.width()); @@ -766,8 +767,8 @@ label_rect.Inset(-kOverviewMargin, -kOverviewMargin); widget_window->SetBounds(label_rect); gfx::Transform label_transform; - label_transform.Translate(transformed_window_bounds.x(), - transformed_window_bounds.y()); + label_transform.Translate(gfx::ToRoundedInt(transformed_window_bounds.x()), + gfx::ToRoundedInt(transformed_window_bounds.y())); widget_window->SetTransform(label_transform); }
diff --git a/ash/wm/overview/overview_item.h b/ash/wm/overview/overview_item.h index 47ad4d0..f16f768 100644 --- a/ash/wm/overview/overview_item.h +++ b/ash/wm/overview/overview_item.h
@@ -14,6 +14,7 @@ #include "ui/aura/window_observer.h" #include "ui/compositor/layer_animation_observer.h" #include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/rect_f.h" #include "ui/views/controls/button/button.h" namespace ui { @@ -81,15 +82,15 @@ // Returns the union of the original target bounds of all transformed windows // managed by |this| item, i.e. all regular (normal or panel transient // descendants of the window returned by GetWindow()). - gfx::Rect GetTargetBoundsInScreen() const; + gfx::RectF GetTargetBoundsInScreen() const; // Returns the transformed bound of |transform_window_|. - gfx::Rect GetTransformedBounds() const; + gfx::RectF GetTransformedBounds() const; // Sets the bounds of this overview item to |target_bounds| in the // |root_window_| root window. The bounds change will be animated as specified // by |animation_type|. - void SetBounds(const gfx::Rect& target_bounds, + void SetBounds(const gfx::RectF& target_bounds, OverviewAnimationType animation_type); // Activates or deactivates selection depending on |selected|. @@ -138,7 +139,7 @@ // Increases the bounds of the dragged item. void ScaleUpSelectedItem(OverviewAnimationType animation_type); - const gfx::Rect& target_bounds() const { return target_bounds_; } + const gfx::RectF& target_bounds() const { return target_bounds_; } // Shift the window item up and then animates it to its original spot. Used // to transition from the home launcher. @@ -156,11 +157,11 @@ void UpdateItemContentViewForMinimizedWindow(); // Handle the mouse/gesture event and facilitate dragging the item. - void HandlePressEvent(const gfx::Point& location_in_screen); - void HandleReleaseEvent(const gfx::Point& location_in_screen); - void HandleDragEvent(const gfx::Point& location_in_screen); - void HandleLongPressEvent(const gfx::Point& location_in_screen); - void HandleFlingStartEvent(const gfx::Point& location_in_screen, + void HandlePressEvent(const gfx::PointF& location_in_screen); + void HandleReleaseEvent(const gfx::PointF& location_in_screen); + void HandleDragEvent(const gfx::PointF& location_in_screen); + void HandleLongPressEvent(const gfx::PointF& location_in_screen); + void HandleFlingStartEvent(const gfx::PointF& location_in_screen, float velocity_x, float velocity_y); void ActivateDraggedWindow(); @@ -244,7 +245,7 @@ // Sets the bounds of this overview item to |target_bounds| in |root_window_|. // The bounds change will be animated as specified by |animation_type|. - void SetItemBounds(const gfx::Rect& target_bounds, + void SetItemBounds(const gfx::RectF& target_bounds, OverviewAnimationType animation_type); // Creates the window label. @@ -273,7 +274,7 @@ ScopedOverviewTransformWindow transform_window_; // The target bounds this overview item is fit within. - gfx::Rect target_bounds_; + gfx::RectF target_bounds_; // True if running SetItemBounds. This prevents recursive calls resulting from // the bounds update when calling ::wm::RecreateWindowLayers to copy
diff --git a/ash/wm/overview/overview_session.cc b/ash/wm/overview/overview_session.cc index 7a88fbd1..071cf86 100644 --- a/ash/wm/overview/overview_session.cc +++ b/ash/wm/overview/overview_session.cc
@@ -448,7 +448,7 @@ } void OverviewSession::InitiateDrag(OverviewItem* item, - const gfx::Point& location_in_screen) { + const gfx::PointF& location_in_screen) { window_drag_controller_ = std::make_unique<OverviewWindowDragController>(this); window_drag_controller_->InitiateDrag(item, location_in_screen); @@ -458,14 +458,14 @@ } void OverviewSession::Drag(OverviewItem* item, - const gfx::Point& location_in_screen) { + const gfx::PointF& location_in_screen) { DCHECK(window_drag_controller_); DCHECK_EQ(item, window_drag_controller_->item()); window_drag_controller_->Drag(location_in_screen); } void OverviewSession::CompleteDrag(OverviewItem* item, - const gfx::Point& location_in_screen) { + const gfx::PointF& location_in_screen) { DCHECK(window_drag_controller_); DCHECK_EQ(item, window_drag_controller_->item()); window_drag_controller_->CompleteDrag(location_in_screen); @@ -475,12 +475,12 @@ } void OverviewSession::StartSplitViewDragMode( - const gfx::Point& location_in_screen) { + const gfx::PointF& location_in_screen) { window_drag_controller_->StartSplitViewDragMode(location_in_screen); } void OverviewSession::Fling(OverviewItem* item, - const gfx::Point& location_in_screen, + const gfx::PointF& location_in_screen, float velocity_x, float velocity_y) { // Its possible a fling event is not paired with a tap down event. Ignore
diff --git a/ash/wm/overview/overview_session.h b/ash/wm/overview/overview_session.h index d7516444..59fe581 100644 --- a/ash/wm/overview/overview_session.h +++ b/ash/wm/overview/overview_session.h
@@ -156,12 +156,12 @@ // the windows in the window grid do not need to be repositioned. void RemoveOverviewItem(OverviewItem* item, bool reposition); - void InitiateDrag(OverviewItem* item, const gfx::Point& location_in_screen); - void Drag(OverviewItem* item, const gfx::Point& location_in_screen); - void CompleteDrag(OverviewItem* item, const gfx::Point& location_in_screen); - void StartSplitViewDragMode(const gfx::Point& location_in_screen); + void InitiateDrag(OverviewItem* item, const gfx::PointF& location_in_screen); + void Drag(OverviewItem* item, const gfx::PointF& location_in_screen); + void CompleteDrag(OverviewItem* item, const gfx::PointF& location_in_screen); + void StartSplitViewDragMode(const gfx::PointF& location_in_screen); void Fling(OverviewItem* item, - const gfx::Point& location_in_screen, + const gfx::PointF& location_in_screen, float velocity_x, float velocity_y); void ActivateDraggedWindow();
diff --git a/ash/wm/overview/overview_session_unittest.cc b/ash/wm/overview/overview_session_unittest.cc index 95d91f4..5efd7322 100644 --- a/ash/wm/overview/overview_session_unittest.cc +++ b/ash/wm/overview/overview_session_unittest.cc
@@ -1166,7 +1166,8 @@ // Labels are located based on target_bounds, not the actual window item // bounds. - gfx::Rect label_bounds = label->GetWidget()->GetWindowBoundsInScreen(); + gfx::RectF label_bounds = + gfx::RectF(label->GetWidget()->GetWindowBoundsInScreen()); label_bounds.Inset(kWindowMargin, kWindowMargin); EXPECT_EQ(label_bounds, window_item->target_bounds()); } @@ -2004,7 +2005,8 @@ OverviewItem* item2 = GetWindowItemForWindow(0, window2.get()); // Drag |item2| in a way so that |window2| does not get activated. ui::test::EventGenerator* generator = GetEventGenerator(); - generator->MoveMouseTo(item2->target_bounds().CenterPoint()); + generator->MoveMouseTo( + gfx::ToRoundedPoint(item2->target_bounds().CenterPoint())); generator->PressLeftButton(); base::RunLoop().RunUntilIdle(); @@ -2033,7 +2035,8 @@ // opaque as its a child of the header which handles fading away the whole // header. All other items, |item2| should only have the close button hidden. ui::test::EventGenerator* generator = GetEventGenerator(); - generator->MoveMouseTo(item1->target_bounds().CenterPoint()); + generator->MoveMouseTo( + gfx::ToRoundedPoint(item1->target_bounds().CenterPoint())); generator->PressLeftButton(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(0.f, item1->GetTitlebarOpacityForTesting()); @@ -2112,7 +2115,8 @@ // Drag the first window. Verify that it's item widget is not stacked above // the other two. - const gfx::Point start_drag = item1->target_bounds().CenterPoint(); + const gfx::Point start_drag = + gfx::ToRoundedPoint(item1->target_bounds().CenterPoint()); ui::test::EventGenerator* generator = GetEventGenerator(); generator->MoveMouseTo(start_drag); generator->PressLeftButton(); @@ -2258,7 +2262,8 @@ // Drag the first window. Verify that the mask was removed for the first // window but still exists for the second window as we do not apply mask // for a dragged window. - const gfx::Point start_drag = item1->target_bounds().CenterPoint(); + const gfx::Point start_drag = + gfx::ToRoundedPoint(item1->target_bounds().CenterPoint()); ui::test::EventGenerator* generator = GetEventGenerator(); generator->MoveMouseTo(start_drag); generator->PressLeftButton(); @@ -2389,8 +2394,8 @@ OverviewItem* item1 = GetWindowItemForWindow(0, window1.get()); OverviewItem* item2 = GetWindowItemForWindow(0, window2.get()); - const gfx::Rect original_bounds1 = item1->target_bounds(); - const gfx::Rect original_bounds2 = item2->target_bounds(); + const gfx::RectF original_bounds1 = item1->target_bounds(); + const gfx::RectF original_bounds2 = item2->target_bounds(); constexpr int kTouchId1 = 1; constexpr int kTouchId2 = 2; @@ -2407,7 +2412,8 @@ // Verify that the bounds of the tapped window expand when touched. ui::test::EventGenerator* generator = GetEventGenerator(); - generator->set_current_screen_location(original_bounds1.CenterPoint()); + generator->set_current_screen_location( + gfx::ToRoundedPoint(original_bounds1.CenterPoint())); generator->PressTouchId(kTouchId1); dispatch_long_press(); EXPECT_GT(item1->target_bounds().width(), original_bounds1.width()); @@ -2416,7 +2422,8 @@ // Verify that attempting to touch the second window with a second finger does // nothing to the second window. The first window remains the window to be // dragged. - generator->set_current_screen_location(original_bounds2.CenterPoint()); + generator->set_current_screen_location( + gfx::ToRoundedPoint(original_bounds2.CenterPoint())); generator->PressTouchId(kTouchId2); dispatch_long_press(); EXPECT_GT(item1->target_bounds().width(), original_bounds1.width()); @@ -2424,7 +2431,7 @@ EXPECT_EQ(item2->target_bounds(), original_bounds2); // Verify the first window moves on drag. - gfx::Point last_center_point = item1->target_bounds().CenterPoint(); + gfx::PointF last_center_point = item1->target_bounds().CenterPoint(); generator->MoveTouchIdBy(kTouchId1, 40, 40); EXPECT_NE(last_center_point, item1->target_bounds().CenterPoint()); EXPECT_EQ(original_bounds2.CenterPoint(), @@ -2485,9 +2492,9 @@ OverviewItem* item1 = GetWindowItemForWindow(0, window1.get()); OverviewItem* item2 = GetWindowItemForWindow(0, window2.get()); OverviewItem* item3 = GetWindowItemForWindow(0, window3.get()); - const gfx::Rect bounds1 = item1->target_bounds(); - const gfx::Rect bounds2 = item2->target_bounds(); - const gfx::Rect bounds3 = item3->target_bounds(); + const gfx::RectF bounds1 = item1->target_bounds(); + const gfx::RectF bounds2 = item2->target_bounds(); + const gfx::RectF bounds3 = item3->target_bounds(); // Verify that the bounds remain the same when calling PositionWindows again. overview_session()->PositionWindows(/*animate=*/false); @@ -2671,10 +2678,10 @@ // want to long press after every press, which enables dragging vertically to // close an item. void DragWindowTo(OverviewItem* item, - const gfx::Point& end_location, + const gfx::PointF& end_location, SelectorItemLocation location, bool long_press = true) { - gfx::Point start_location; + gfx::PointF start_location; switch (location) { case SelectorItemLocation::CENTER: start_location = item->target_bounds().CenterPoint(); @@ -2703,7 +2710,7 @@ } // Drags a overview item |item| from its center point to |end_location|. - void DragWindowTo(OverviewItem* item, const gfx::Point& end_location) { + void DragWindowTo(OverviewItem* item, const gfx::PointF& end_location) { DragWindowTo(item, end_location, SelectorItemLocation::CENTER, true); } @@ -2747,7 +2754,7 @@ const int grid_index = 0; OverviewItem* overview_item1 = GetWindowItemForWindow(grid_index, window1.get()); - DragWindowTo(overview_item1, gfx::Point(0, 0)); + DragWindowTo(overview_item1, gfx::PointF(0, 0)); EXPECT_TRUE(split_view_controller()->IsSplitViewModeActive()); EXPECT_EQ(split_view_controller()->state(), @@ -2759,7 +2766,7 @@ // overview mode. OverviewItem* overview_item2 = GetWindowItemForWindow(grid_index, window2.get()); - DragWindowTo(overview_item2, gfx::Point(0, 0)); + DragWindowTo(overview_item2, gfx::PointF(0, 0)); EXPECT_EQ(split_view_controller()->state(), SplitViewController::LEFT_SNAPPED); @@ -2770,7 +2777,8 @@ // Drag |window3| selector item to snap to right. OverviewItem* overview_item3 = GetWindowItemForWindow(grid_index, window3.get()); - const gfx::Point end_location3(GetWorkAreaInScreen(window3.get()).width(), 0); + const gfx::PointF end_location3(GetWorkAreaInScreen(window3.get()).width(), + 0.f); DragWindowTo(overview_item3, end_location3); EXPECT_EQ(split_view_controller()->state(), @@ -2797,7 +2805,7 @@ using DragBehavior = OverviewWindowDragController::DragBehavior; ui::test::EventGenerator* generator = GetEventGenerator(); generator->set_current_screen_location( - window_item1->target_bounds().CenterPoint()); + gfx::ToRoundedPoint(window_item1->target_bounds().CenterPoint())); generator->PressTouch(); OverviewWindowDragController* drag_controller = overview_session()->window_drag_controller(); @@ -2811,7 +2819,7 @@ // Verify that if a drag is orginally vertical, the drag behavior is drag to // close. generator->set_current_screen_location( - window_item2->target_bounds().CenterPoint()); + gfx::ToRoundedPoint(window_item2->target_bounds().CenterPoint())); generator->PressTouch(); drag_controller = overview_session()->window_drag_controller(); EXPECT_EQ(DragBehavior::kUndefined, drag_controller->current_drag_behavior()); @@ -2833,21 +2841,21 @@ ASSERT_TRUE(overview_controller()->IsSelecting()); OverviewItem* item = GetWindowItemForWindow(0, widget->GetNativeWindow()); - const gfx::Point start = item->target_bounds().CenterPoint(); + const gfx::PointF start = item->target_bounds().CenterPoint(); ASSERT_TRUE(item); // This drag has not covered enough distance, so the widget is not closed and // we remain in overview mode. overview_session()->InitiateDrag(item, start); - overview_session()->Drag(item, start + gfx::Vector2d(0, 80)); - overview_session()->CompleteDrag(item, start + gfx::Vector2d(0, 80)); + overview_session()->Drag(item, start + gfx::Vector2dF(0, 80)); + overview_session()->CompleteDrag(item, start + gfx::Vector2dF(0, 80)); ASSERT_TRUE(overview_session()); // Verify that the second drag has enough vertical distance, so the widget // will be closed and overview mode will be exited. overview_session()->InitiateDrag(item, start); - overview_session()->Drag(item, start + gfx::Vector2d(0, 180)); - overview_session()->CompleteDrag(item, start + gfx::Vector2d(0, 180)); + overview_session()->Drag(item, start + gfx::Vector2dF(0, 180)); + overview_session()->CompleteDrag(item, start + gfx::Vector2dF(0, 180)); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(overview_session()); EXPECT_TRUE(widget->IsClosed()); @@ -2864,26 +2872,26 @@ EXPECT_EQ(1u, overview_session()->grid_list_for_testing()[0]->size()); OverviewItem* item = GetWindowItemForWindow(0, widget->GetNativeWindow()); - const gfx::Point start = item->target_bounds().CenterPoint(); + const gfx::PointF start = item->target_bounds().CenterPoint(); ASSERT_TRUE(item); // Verify that items flung horizontally do not close the item. overview_session()->InitiateDrag(item, start); - overview_session()->Drag(item, start + gfx::Vector2d(0, 50)); + overview_session()->Drag(item, start + gfx::Vector2dF(0, 50)); overview_session()->Fling(item, start, 2500, 0); ASSERT_TRUE(overview_session()); // Verify that items flung vertically but without enough velocity do not // close the item. overview_session()->InitiateDrag(item, start); - overview_session()->Drag(item, start + gfx::Vector2d(0, 50)); + overview_session()->Drag(item, start + gfx::Vector2dF(0, 50)); overview_session()->Fling(item, start, 0, 1500); ASSERT_TRUE(overview_session()); // Verify that flinging the item closes it, and since it is the last item in // overview mode, overview mode is exited. overview_session()->InitiateDrag(item, start); - overview_session()->Drag(item, start + gfx::Vector2d(0, 50)); + overview_session()->Drag(item, start + gfx::Vector2dF(0, 50)); overview_session()->Fling(item, start, 0, 2500); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(overview_session()); @@ -2909,15 +2917,15 @@ OverviewItem* item2 = GetWindowItemForWindow(0, window2.get()); OverviewItem* item3 = GetWindowItemForWindow(0, window3.get()); - const gfx::Rect item1_bounds = item1->target_bounds(); - const gfx::Rect item2_bounds = item2->target_bounds(); - const gfx::Rect item3_bounds = item3->target_bounds(); + const gfx::RectF item1_bounds = item1->target_bounds(); + const gfx::RectF item2_bounds = item2->target_bounds(); + const gfx::RectF item3_bounds = item3->target_bounds(); // Drag |item1| vertically. |item2| and |item3| bounds should change as they // should be nudging towards their final bounds. overview_session()->InitiateDrag(item1, item1_bounds.CenterPoint()); overview_session()->Drag(item1, - item1_bounds.CenterPoint() + gfx::Vector2d(0, 160)); + item1_bounds.CenterPoint() + gfx::Vector2dF(0, 160)); EXPECT_NE(item2_bounds, item2->target_bounds()); EXPECT_NE(item3_bounds, item3->target_bounds()); @@ -2930,7 +2938,7 @@ // should be nudging towards their final bounds. overview_session()->InitiateDrag(item3, item3_bounds.CenterPoint()); overview_session()->Drag(item3, - item3_bounds.CenterPoint() + gfx::Vector2d(0, 160)); + item3_bounds.CenterPoint() + gfx::Vector2dF(0, 160)); EXPECT_NE(item1_bounds, item1->target_bounds()); EXPECT_NE(item2_bounds, item2->target_bounds()); } @@ -2955,16 +2963,16 @@ OverviewItem* item3 = GetWindowItemForWindow(0, window3.get()); OverviewItem* item4 = GetWindowItemForWindow(0, window4.get()); - const gfx::Rect item1_bounds = item1->target_bounds(); - const gfx::Rect item2_bounds = item2->target_bounds(); - const gfx::Rect item3_bounds = item3->target_bounds(); - const gfx::Rect item4_bounds = item4->target_bounds(); + const gfx::RectF item1_bounds = item1->target_bounds(); + const gfx::RectF item2_bounds = item2->target_bounds(); + const gfx::RectF item3_bounds = item3->target_bounds(); + const gfx::RectF item4_bounds = item4->target_bounds(); // Drag |item1| past the drag to swipe threshold. None of the other window // bounds should change, as none of them should be nudged. overview_session()->InitiateDrag(item1, item1_bounds.CenterPoint()); overview_session()->Drag(item1, - item1_bounds.CenterPoint() + gfx::Vector2d(0, 160)); + item1_bounds.CenterPoint() + gfx::Vector2dF(0, 160)); EXPECT_EQ(item2_bounds, item2->target_bounds()); EXPECT_EQ(item3_bounds, item3->target_bounds()); EXPECT_EQ(item4_bounds, item4->target_bounds()); @@ -2988,7 +2996,7 @@ ASSERT_TRUE(overview_controller()->IsSelecting()); OverviewItem* items[kWindows]; - gfx::Rect item_bounds[kWindows]; + gfx::RectF item_bounds[kWindows]; for (int i = 0; i < kWindows; ++i) { items[i] = GetWindowItemForWindow(0, windows[i].get()); item_bounds[i] = items[i]->target_bounds(); @@ -3000,7 +3008,7 @@ // first row to the second. overview_session()->InitiateDrag(items[3], item_bounds[3].CenterPoint()); overview_session()->Drag( - items[3], item_bounds[3].CenterPoint() + gfx::Vector2d(0, 160)); + items[3], item_bounds[3].CenterPoint() + gfx::Vector2dF(0, 160)); EXPECT_EQ(item_bounds[0], items[0]->target_bounds()); EXPECT_EQ(item_bounds[1], items[1]->target_bounds()); EXPECT_EQ(item_bounds[2], items[2]->target_bounds()); @@ -3017,7 +3025,7 @@ // row than the first item. overview_session()->InitiateDrag(items[0], item_bounds[0].CenterPoint()); overview_session()->Drag( - items[0], item_bounds[0].CenterPoint() + gfx::Vector2d(0, 160)); + items[0], item_bounds[0].CenterPoint() + gfx::Vector2dF(0, 160)); EXPECT_NE(item_bounds[1], items[1]->target_bounds()); EXPECT_NE(item_bounds[2], items[2]->target_bounds()); EXPECT_EQ(item_bounds[3], items[3]->target_bounds()); @@ -3042,13 +3050,13 @@ Shell::Get()->GetPrimaryRootWindow()->GetBoundsInScreen().width(); OverviewItem* overview_item = GetWindowItemForWindow(grid_index, window1.get()); - gfx::Rect overview_item_bounds = overview_item->target_bounds(); - gfx::Point start_location(overview_item_bounds.CenterPoint()); + gfx::RectF overview_item_bounds = overview_item->target_bounds(); + gfx::PointF start_location(overview_item_bounds.CenterPoint()); overview_session()->InitiateDrag(overview_item, start_location); // Verify that when dragged to the left, the window grid is located where the // right window of split view mode should be. - const gfx::Point left(0, 0); + const gfx::PointF left(0, 0); overview_session()->Drag(overview_item, left); EXPECT_FALSE(split_view_controller()->IsSplitViewModeActive()); EXPECT_EQ(SplitViewController::NO_SNAP, split_view_controller()->state()); @@ -3057,7 +3065,7 @@ // Verify that when dragged to the right, the window grid is located where the // left window of split view mode should be. - const gfx::Point right(window_width, 0); + const gfx::PointF right(window_width, 0); overview_session()->Drag(overview_item, right); EXPECT_EQ(SplitViewController::NO_SNAP, split_view_controller()->state()); EXPECT_TRUE(split_view_controller()->right_window() == nullptr); @@ -3065,7 +3073,7 @@ // Verify that when dragged to the center, the window grid is has the // dimensions of the work area. - const gfx::Point center(window_width / 2, 0); + const gfx::PointF center(window_width / 2, 0); overview_session()->Drag(overview_item, center); EXPECT_EQ(SplitViewController::NO_SNAP, split_view_controller()->state()); EXPECT_EQ(GetWorkAreaInScreen(window1.get()), GetGridBounds()); @@ -3112,13 +3120,13 @@ GetWindowItemForWindow(0, unsnappable_window.get()); overview_session()->InitiateDrag( overview_item, overview_item->target_bounds().CenterPoint()); - overview_session()->Drag(overview_item, gfx::Point(0, 0)); + overview_session()->Drag(overview_item, gfx::PointF()); EXPECT_EQ(expected_grid_bounds, GetGridBounds()); overview_session()->Drag(overview_item, - gfx::Point(root_window_bounds.right(), 0)); + gfx::PointF(root_window_bounds.right(), 0.f)); EXPECT_EQ(expected_grid_bounds, GetGridBounds()); overview_session()->Drag(overview_item, - gfx::Point(root_window_bounds.right() / 2, 0)); + gfx::PointF(root_window_bounds.right() / 2.f, 0.f)); EXPECT_EQ(expected_grid_bounds, GetGridBounds()); } @@ -3136,7 +3144,7 @@ const int grid_index = 0; OverviewItem* overview_item1 = GetWindowItemForWindow(grid_index, window1.get()); - DragWindowTo(overview_item1, gfx::Point(0, 0)); + DragWindowTo(overview_item1, gfx::PointF()); // Test that overview mode is active in this single window case. EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), true); @@ -3188,7 +3196,7 @@ // end split view and overview correctly. ToggleOverview(); overview_item1 = GetWindowItemForWindow(grid_index, window1.get()); - DragWindowTo(overview_item1, gfx::Point(0, 0)); + DragWindowTo(overview_item1, gfx::PointF()); EXPECT_TRUE(Shell::Get()->IsSplitViewModeActive()); EXPECT_TRUE(overview_controller()->IsSelecting()); Shell::Get()->tablet_mode_controller()->EnableTabletModeWindowManager(false); @@ -3230,7 +3238,7 @@ const int grid_index = 0; OverviewItem* overview_item1 = GetWindowItemForWindow(grid_index, window1.get()); - DragWindowTo(overview_item1, gfx::Point(0, 0)); + DragWindowTo(overview_item1, gfx::PointF()); EXPECT_EQ(split_view_controller()->state(), svc::LEFT_SNAPPED); EXPECT_EQ(split_view_controller()->left_window(), window1.get()); @@ -3238,7 +3246,7 @@ OverviewItem* overview_item2 = GetWindowItemForWindow(grid_index, window2.get()); gfx::Rect work_area_rect = GetWorkAreaInScreen(window2.get()); - gfx::Point end_location2(work_area_rect.width(), work_area_rect.height()); + gfx::PointF end_location2(work_area_rect.width(), work_area_rect.height()); DragWindowTo(overview_item2, end_location2); EXPECT_EQ(split_view_controller()->state(), svc::BOTH_SNAPPED); EXPECT_EQ(split_view_controller()->right_window(), window2.get()); @@ -3259,14 +3267,14 @@ // Test that dragging |window1| to the top of the screen snaps it to left. overview_item1 = GetWindowItemForWindow(grid_index, window1.get()); - DragWindowTo(overview_item1, gfx::Point(0, 0)); + DragWindowTo(overview_item1, gfx::PointF(0, 0)); EXPECT_EQ(split_view_controller()->state(), svc::LEFT_SNAPPED); EXPECT_EQ(split_view_controller()->left_window(), window1.get()); // Test that dragging |window2| to the bottom of the screen snaps it to right. overview_item2 = GetWindowItemForWindow(grid_index, window2.get()); work_area_rect = GetWorkAreaInScreen(window2.get()); - end_location2 = gfx::Point(work_area_rect.width(), work_area_rect.height()); + end_location2 = gfx::PointF(work_area_rect.width(), work_area_rect.height()); DragWindowTo(overview_item2, end_location2, SelectorItemLocation::ORIGIN); EXPECT_EQ(split_view_controller()->state(), svc::BOTH_SNAPPED); EXPECT_EQ(split_view_controller()->right_window(), window2.get()); @@ -3287,14 +3295,14 @@ // Test that dragging |window1| to the left of the screen snaps it to right. overview_item1 = GetWindowItemForWindow(grid_index, window1.get()); - DragWindowTo(overview_item1, gfx::Point(0, 0)); + DragWindowTo(overview_item1, gfx::PointF()); EXPECT_EQ(split_view_controller()->state(), svc::RIGHT_SNAPPED); EXPECT_EQ(split_view_controller()->right_window(), window1.get()); // Test that dragging |window2| to the right of the screen snaps it to left. overview_item2 = GetWindowItemForWindow(grid_index, window2.get()); work_area_rect = GetWorkAreaInScreen(window2.get()); - end_location2 = gfx::Point(work_area_rect.width(), work_area_rect.height()); + end_location2 = gfx::PointF(work_area_rect.width(), work_area_rect.height()); DragWindowTo(overview_item2, end_location2, SelectorItemLocation::ORIGIN); EXPECT_EQ(split_view_controller()->state(), svc::BOTH_SNAPPED); EXPECT_EQ(split_view_controller()->left_window(), window2.get()); @@ -3315,14 +3323,14 @@ // Test that dragging |window1| to the top of the screen snaps it to right. overview_item1 = GetWindowItemForWindow(grid_index, window1.get()); - DragWindowTo(overview_item1, gfx::Point(0, 0)); + DragWindowTo(overview_item1, gfx::PointF(0, 0)); EXPECT_EQ(split_view_controller()->state(), svc::RIGHT_SNAPPED); EXPECT_EQ(split_view_controller()->right_window(), window1.get()); // Test that dragging |window2| to the bottom of the screen snaps it to left. overview_item2 = GetWindowItemForWindow(grid_index, window2.get()); work_area_rect = GetWorkAreaInScreen(window2.get()); - end_location2 = gfx::Point(work_area_rect.width(), work_area_rect.height()); + end_location2 = gfx::PointF(work_area_rect.width(), work_area_rect.height()); DragWindowTo(overview_item2, end_location2); EXPECT_EQ(split_view_controller()->state(), svc::BOTH_SNAPPED); EXPECT_EQ(split_view_controller()->left_window(), window2.get()); @@ -3352,7 +3360,7 @@ const int grid_index = 0; OverviewItem* overview_item1 = GetWindowItemForWindow(grid_index, window1.get()); - DragWindowTo(overview_item1, gfx::Point(0, 0)); + DragWindowTo(overview_item1, gfx::PointF()); EXPECT_EQ(split_view_controller()->state(), SplitViewController::LEFT_SNAPPED); @@ -3407,7 +3415,7 @@ GetWindowItemForWindow(grid_index, unsnappable_window.get()); ui::test::EventGenerator* generator = GetEventGenerator(); generator->set_current_screen_location( - overview_item->target_bounds().CenterPoint()); + gfx::ToRoundedPoint(overview_item->target_bounds().CenterPoint())); generator->ClickLeftButton(); // Verify that we are out of split view and overview mode, and that the active @@ -3437,7 +3445,7 @@ // Now select the unsnappable window. overview_item = GetWindowItemForWindow(grid_index, unsnappable_window.get()); generator->set_current_screen_location( - overview_item->target_bounds().CenterPoint()); + gfx::ToRoundedPoint(overview_item->target_bounds().CenterPoint())); generator->ClickLeftButton(); // Split view mode should be ended. And the unsnappable window should be the @@ -3507,7 +3515,7 @@ const int grid_index = 0; OverviewItem* overview_item1 = GetWindowItemForWindow(grid_index, window1.get()); - DragWindowTo(overview_item1, gfx::Point(0, 0)); + DragWindowTo(overview_item1, gfx::PointF()); // Test that overview mode and split view mode are both active. EXPECT_TRUE(split_view_controller()->IsSplitViewModeActive()); EXPECT_TRUE(Shell::Get()->overview_controller()->IsSelecting()); @@ -3524,7 +3532,7 @@ // Now drag |window2| selector item to snap to left. OverviewItem* overview_item2 = GetWindowItemForWindow(grid_index, window2.get()); - DragWindowTo(overview_item2, gfx::Point(0, 0)); + DragWindowTo(overview_item2, gfx::PointF()); // Test that overview mode and split view mode are both active. EXPECT_TRUE(split_view_controller()->IsSplitViewModeActive()); EXPECT_TRUE(Shell::Get()->overview_controller()->IsSelecting()); @@ -3550,8 +3558,8 @@ ASSERT_TRUE(overview_controller()->IsSelecting()); OverviewItem* overview_item = GetWindowItemForWindow(0, window1.get()); - gfx::Point start_location(overview_item->target_bounds().CenterPoint()); - const gfx::Rect original_bounds(overview_item->target_bounds()); + gfx::PointF start_location(overview_item->target_bounds().CenterPoint()); + const gfx::RectF original_bounds(overview_item->target_bounds()); // Verify that when a overview item receives a resetting gesture, we // stay in overview mode and the bounds of the item are the same as they were @@ -3588,7 +3596,7 @@ const int grid_index = 0; OverviewItem* overview_item1 = GetWindowItemForWindow(grid_index, window1.get()); - DragWindowTo(overview_item1, gfx::Point(0, 0)); + DragWindowTo(overview_item1, gfx::PointF()); EXPECT_EQ(SplitViewController::LEFT_SNAPPED, split_view_controller()->state()); EXPECT_TRUE(Shell::Get()->overview_controller()->IsSelecting()); @@ -3614,7 +3622,7 @@ const gfx::Rect work_area_rect = GetWorkAreaInScreen(window2.get()); gfx::Point end_location2 = gfx::Point(work_area_rect.width(), work_area_rect.height()); - DragWindowTo(overview_item2, end_location2); + DragWindowTo(overview_item2, gfx::PointF(end_location2)); EXPECT_EQ(SplitViewController::RIGHT_SNAPPED, split_view_controller()->state()); EXPECT_TRUE(Shell::Get()->overview_controller()->IsSelecting()); @@ -3652,7 +3660,7 @@ const int grid_index = 0; OverviewItem* overview_item1 = GetWindowItemForWindow(grid_index, window1.get()); - DragWindowTo(overview_item1, gfx::Point(0, 0)); + DragWindowTo(overview_item1, gfx::PointF()); EXPECT_EQ(SplitViewController::LEFT_SNAPPED, split_view_controller()->state()); EXPECT_TRUE(IsSelecting()); @@ -3750,7 +3758,7 @@ const int grid_index = 0; OverviewItem* overview_item1 = GetWindowItemForWindow(grid_index, window1.get()); - DragWindowTo(overview_item1, gfx::Point(0, 0)); + DragWindowTo(overview_item1, gfx::PointF()); EXPECT_EQ(split_view_controller()->state(), SplitViewController::LEFT_SNAPPED); EXPECT_EQ(split_view_controller()->left_window(), window1.get()); @@ -3764,7 +3772,7 @@ // Now snap both |window1| and |window2|. overview_item1 = GetWindowItemForWindow(grid_index, window1.get()); - DragWindowTo(overview_item1, gfx::Point(0, 0)); + DragWindowTo(overview_item1, gfx::PointF()); ::wm::ActivateWindow(window2.get()); EXPECT_FALSE(IsSelecting()); EXPECT_EQ(split_view_controller()->state(), @@ -3810,7 +3818,7 @@ const int grid_index = 0; OverviewItem* overview_item1 = GetWindowItemForWindow(grid_index, window1.get()); - DragWindowTo(overview_item1, gfx::Point(0, 0)); + DragWindowTo(overview_item1, gfx::PointF()); EXPECT_EQ(SplitViewController::LEFT_SNAPPED, split_view_controller()->state()); // Drag |window2| to snap to right. @@ -3819,7 +3827,7 @@ const gfx::Rect work_area_rect = screen_util::GetDisplayWorkAreaBoundsInScreenForDefaultContainer( window2.get()); - const gfx::Point end_location2(work_area_rect.width(), 0); + const gfx::PointF end_location2(work_area_rect.width(), 0); DragWindowTo(overview_item2, end_location2); EXPECT_EQ(SplitViewController::BOTH_SNAPPED, split_view_controller()->state()); @@ -3883,7 +3891,7 @@ // double tapping on the divider can swap the window's position with the // overview window grid's postion. TEST_F(SplitViewOverviewSessionTest, SwapWindowAndOverviewGrid) { - const gfx::Rect bounds(0, 0, 400, 400); + const gfx::Rect bounds(400, 400); std::unique_ptr<aura::Window> window1(CreateWindow(bounds)); std::unique_ptr<aura::Window> window2(CreateWindow(bounds)); @@ -3891,7 +3899,7 @@ const int grid_index = 0; OverviewItem* overview_item1 = GetWindowItemForWindow(grid_index, window1.get()); - DragWindowTo(overview_item1, gfx::Point(0, 0)); + DragWindowTo(overview_item1, gfx::PointF()); EXPECT_EQ(split_view_controller()->state(), SplitViewController::LEFT_SNAPPED); EXPECT_EQ(split_view_controller()->default_snap_position(),
diff --git a/ash/wm/overview/overview_utils.cc b/ash/wm/overview/overview_utils.cc index ce0f9d3..7c10558 100644 --- a/ash/wm/overview/overview_utils.cc +++ b/ash/wm/overview/overview_utils.cc
@@ -228,9 +228,9 @@ return widget; } -gfx::Rect GetTransformedBounds(aura::Window* transformed_window, - int top_inset) { - gfx::Rect bounds; +gfx::RectF GetTransformedBounds(aura::Window* transformed_window, + int top_inset) { + gfx::RectF bounds; for (auto* window : wm::GetTransientTreeIterator(transformed_window)) { // Ignore other window types when computing bounding box of overview target // item. @@ -240,7 +240,7 @@ } gfx::RectF window_bounds(window->GetTargetBounds()); gfx::Transform new_transform = - TransformAboutPivot(gfx::Point(window_bounds.x(), window_bounds.y()), + TransformAboutPivot(gfx::ToRoundedPoint(window_bounds.origin()), window->layer()->GetTargetTransform()); new_transform.TransformRect(&window_bounds); @@ -251,17 +251,16 @@ gfx::RectF header_bounds(window_bounds); header_bounds.set_height(top_inset); new_transform.TransformRect(&header_bounds); - window_bounds.Inset(0, gfx::ToCeiledInt(header_bounds.height()), 0, 0); + window_bounds.Inset(0, header_bounds.height(), 0, 0); } - gfx::Rect enclosing_bounds = ToEnclosingRect(window_bounds); - ::wm::ConvertRectToScreen(window->parent(), &enclosing_bounds); - bounds.Union(enclosing_bounds); + ::wm::TranslateRectToScreen(window->parent(), &window_bounds); + bounds.Union(window_bounds); } return bounds; } -gfx::Rect GetTargetBoundsInScreen(aura::Window* window) { - gfx::Rect bounds; +gfx::RectF GetTargetBoundsInScreen(aura::Window* window) { + gfx::RectF bounds; for (auto* window_iter : wm::GetTransientTreeIterator(window)) { // Ignore other window types when computing bounding box of overview target // item. @@ -269,19 +268,19 @@ window_iter->type() != aura::client::WINDOW_TYPE_NORMAL) { continue; } - gfx::Rect target_bounds = window_iter->GetTargetBounds(); - ::wm::ConvertRectToScreen(window_iter->parent(), &target_bounds); + gfx::RectF target_bounds(window_iter->GetTargetBounds()); + ::wm::TranslateRectToScreen(window_iter->parent(), &target_bounds); bounds.Union(target_bounds); } return bounds; } void SetTransform(aura::Window* window, const gfx::Transform& transform) { - gfx::Point target_origin(GetTargetBoundsInScreen(window).origin()); + gfx::PointF target_origin(GetTargetBoundsInScreen(window).origin()); for (auto* window_iter : wm::GetTransientTreeIterator(window)) { aura::Window* parent_window = window_iter->parent(); - gfx::Rect original_bounds(window_iter->GetTargetBounds()); - ::wm::ConvertRectToScreen(parent_window, &original_bounds); + gfx::RectF original_bounds(window_iter->GetTargetBounds()); + ::wm::TranslateRectToScreen(parent_window, &original_bounds); gfx::Transform new_transform = TransformAboutPivot(gfx::Point(target_origin.x() - original_bounds.x(), target_origin.y() - original_bounds.y()),
diff --git a/ash/wm/overview/overview_utils.h b/ash/wm/overview/overview_utils.h index cfdc97a0..99633b2 100644 --- a/ash/wm/overview/overview_utils.h +++ b/ash/wm/overview/overview_utils.h
@@ -68,11 +68,12 @@ // transient hierarchy. The returned Rect is in virtual screen coordinates. The // returned bounds are adjusted to allow the original |transformed_window|'s // header to be hidden if |top_inset| is not zero. -gfx::Rect GetTransformedBounds(aura::Window* transformed_window, int top_inset); +gfx::RectF GetTransformedBounds(aura::Window* transformed_window, + int top_inset); // Returns the original target bounds of |window|. The bounds are a union of all // regular (normal and panel) windows in the window's transient hierarchy. -gfx::Rect GetTargetBoundsInScreen(aura::Window* window); +gfx::RectF GetTargetBoundsInScreen(aura::Window* window); // Applies the |transform| to |window| and all of its transient children. Note // |transform| is the transform that is applied to |window| and needs to be
diff --git a/ash/wm/overview/overview_window_drag_controller.cc b/ash/wm/overview/overview_window_drag_controller.cc index 64a7af74..b567324 100644 --- a/ash/wm/overview/overview_window_drag_controller.cc +++ b/ash/wm/overview/overview_window_drag_controller.cc
@@ -31,16 +31,16 @@ constexpr float kDragToCloseDistanceThresholdDp = 160.f; // The minimum distance that will be considered as a drag event. -constexpr int kMinimumDragDistanceDp = 5; +constexpr float kMinimumDragDistanceDp = 5.f; // Items dragged to within |kDistanceFromEdgeDp| of the screen will get snapped // even if they have not moved by |kMinimumDragDistanceDp|. -constexpr int kDistanceFromEdgeDp = 16; +constexpr float kDistanceFromEdgeDp = 16.f; // The minimum distance that an item must be moved before it is snapped. This // prevents accidental snaps. -constexpr int kMinimumDragToSnapDistanceDp = 96; +constexpr float kMinimumDragToSnapDistanceDp = 96.f; // The minimum distance that an item must be moved before it is considered a // drag event, if the drag starts in one of the snap regions. -constexpr int kMinimumDragDistanceAlreadyInSnapRegionDp = 48; +constexpr float kMinimumDragDistanceAlreadyInSnapRegionDp = 48.f; // Flings with less velocity than this will not close the dragged item. constexpr float kFlingToCloseVelocityThreshold = 2000.f; @@ -62,10 +62,10 @@ void OverviewWindowDragController::InitiateDrag( OverviewItem* item, - const gfx::Point& location_in_screen) { + const gfx::PointF& location_in_screen) { item_ = item; - previous_event_location_ = location_in_screen; initial_event_location_ = location_in_screen; + initial_centerpoint_ = item_->target_bounds().CenterPoint(); if (ShouldAllowSplitView()) { started_in_snap_region_ = GetSnapPosition(location_in_screen) != SplitViewController::NONE; @@ -74,11 +74,11 @@ Shell::Get()->overview_controller()->PauseOcclusionTracker(); } -void OverviewWindowDragController::Drag(const gfx::Point& location_in_screen) { +void OverviewWindowDragController::Drag(const gfx::PointF& location_in_screen) { if (!did_move_) { - gfx::Vector2d distance = location_in_screen - previous_event_location_; + gfx::Vector2dF distance = location_in_screen - initial_event_location_; // Do not start dragging if the distance from |location_in_screen| to - // |previous_event_location_| is not greater than |kMinimumDragDistanceDp|. + // |initial_event_location_| is not greater than |kMinimumDragDistanceDp|. if (std::abs(distance.x()) < kMinimumDragDistanceDp && std::abs(distance.y()) < kMinimumDragDistanceDp) { return; @@ -95,13 +95,11 @@ } } - int x_offset = 0; // Update the state based on the drag behavior. if (current_drag_behavior_ == DragBehavior::kDragToClose) { // Update |item_|'s opacity based on its distance. |item_|'s x coordinate // should not change while in drag to close state. - float val = std::abs(static_cast<float>(location_in_screen.y()) - - initial_event_location_.y()) / + float val = std::abs(location_in_screen.y() - initial_event_location_.y()) / kDragToCloseDistanceThresholdDp; overview_session_->GetGridWithRootWindow(item_->root_window()) ->UpdateNudge(item_, val); @@ -112,7 +110,6 @@ item_->SetOpacity(opacity); } else if (current_drag_behavior_ == DragBehavior::kDragToSnap) { UpdateDragIndicatorsAndOverviewGrid(location_in_screen); - x_offset = location_in_screen.x() - previous_event_location_.x(); } // Update the split view divider bar status if necessary. If splitview is @@ -121,23 +118,28 @@ if (ShouldAllowSplitView()) split_view_controller_->OnWindowDragStarted(item_->GetWindow()); - // Update the dragged |item_|'s bounds accordingly. - gfx::Rect bounds(item_->target_bounds()); - bounds.Offset(x_offset, - location_in_screen.y() - previous_event_location_.y()); + // Update the dragged |item_|'s bounds accordingly. The distance from the new + // location to the new centerpoint should be the same it was initially. Do not + // update x bounds if dragging to close. + gfx::RectF bounds(item_->target_bounds()); + const gfx::PointF centerpoint = + location_in_screen - (initial_event_location_ - initial_centerpoint_); + if (current_drag_behavior_ == DragBehavior::kDragToSnap) + bounds.set_x(centerpoint.x() - bounds.width() / 2.f); + bounds.set_y(centerpoint.y() - bounds.height() / 2.f); item_->SetBounds(bounds, OVERVIEW_ANIMATION_NONE); - previous_event_location_ = location_in_screen; } void OverviewWindowDragController::CompleteDrag( - const gfx::Point& location_in_screen) { + const gfx::PointF& location_in_screen) { // Update the split view divider bar stuatus if necessary. The divider bar // should be placed above the dragged window after drag ends. Note here the // passed paramters |snap_position_| and |location_in_screen| won't be used in // this function for this case, but they are passed in as placeholders. if (ShouldAllowSplitView()) { split_view_controller_->OnWindowDragEnded( - item_->GetWindow(), snap_position_, location_in_screen); + item_->GetWindow(), snap_position_, + gfx::ToRoundedPoint(location_in_screen)); } // Update window grid bounds and |snap_position_| in case the screen @@ -181,7 +183,7 @@ } void OverviewWindowDragController::StartSplitViewDragMode( - const gfx::Point& location_in_screen) { + const gfx::PointF& location_in_screen) { DCHECK(ShouldAllowSplitView()); item_->ScaleUpSelectedItem( @@ -192,10 +194,10 @@ overview_session_->SetSplitViewDragIndicatorsIndicatorState( CanSnapInSplitview(item_->GetWindow()) ? IndicatorState::kDragArea : IndicatorState::kCannotSnap, - location_in_screen); + gfx::ToRoundedPoint(location_in_screen)); } -void OverviewWindowDragController::Fling(const gfx::Point& location_in_screen, +void OverviewWindowDragController::Fling(const gfx::PointF& location_in_screen, float velocity_x, float velocity_y) { if (current_drag_behavior_ == DragBehavior::kDragToClose || @@ -203,7 +205,8 @@ if (std::abs(velocity_y) > kFlingToCloseVelocityThreshold) { if (ShouldAllowSplitView()) { split_view_controller_->OnWindowDragEnded( - item_->GetWindow(), snap_position_, location_in_screen); + item_->GetWindow(), snap_position_, + gfx::ToRoundedPoint(location_in_screen)); } item_->AnimateAndCloseWindow( @@ -262,7 +265,7 @@ } void OverviewWindowDragController::UpdateDragIndicatorsAndOverviewGrid( - const gfx::Point& location_in_screen) { + const gfx::PointF& location_in_screen) { DCHECK(ShouldAllowSplitView()); if (!ShouldUpdateDragIndicatorsOrSnap(location_in_screen)) return; @@ -306,7 +309,7 @@ } bool OverviewWindowDragController::ShouldUpdateDragIndicatorsOrSnap( - const gfx::Point& event_location) { + const gfx::PointF& event_location) { auto snap_position = GetSnapPosition(event_location); const bool inverted = !IsCurrentScreenOrientationPrimary(); // Note: in some orientations SplitViewController::LEFT is not physically on @@ -321,19 +324,20 @@ screen_util::GetDisplayWorkAreaBoundsInParent(item_->GetWindow())); ::wm::ConvertRectToScreen(item_->GetWindow()->GetRootWindow(), &area); area.Inset(kDistanceFromEdgeDp, kDistanceFromEdgeDp); - if ((landscape && - (event_location.x() < area.x() || event_location.x() > area.right())) || - (!landscape && - (event_location.y() < area.y() || event_location.y() > area.bottom()))) { + const gfx::Point event_location_i = gfx::ToRoundedPoint(event_location); + if ((landscape && (event_location_i.x() < area.x() || + event_location_i.x() > area.right())) || + (!landscape && (event_location_i.y() < area.y() || + event_location_i.y() > area.bottom()))) { return true; } // The drag indicators can update or the item can snap even if the drag events // are in the snap region, if the event has travelled past the threshold in // the direction of the attempted snap region. - const gfx::Vector2d distance = event_location - initial_event_location_; + const gfx::Vector2dF distance = event_location - initial_event_location_; // Check the x-axis distance for landscape, y-axis distance for portrait. - const int distance_scalar = landscape ? distance.x() : distance.y(); + const float distance_scalar = landscape ? distance.x() : distance.y(); // If not started in a snap region, snap if the item has been dragged // |kMinimumDragDistanceDp|. This prevents accidental snaps. @@ -363,7 +367,7 @@ } SplitViewController::SnapPosition OverviewWindowDragController::GetSnapPosition( - const gfx::Point& location_in_screen) const { + const gfx::PointF& location_in_screen) const { DCHECK(item_); DCHECK(ShouldAllowSplitView()); gfx::Rect area( @@ -378,8 +382,8 @@ // should show the preview window as soon as the window past the split divider // bar. if (split_view_controller_->IsSplitViewModeActive()) { - const int position = - is_landscape ? location_in_screen.x() : location_in_screen.y(); + const int position = gfx::ToRoundedInt( + is_landscape ? location_in_screen.x() : location_in_screen.y()); SplitViewController::SnapPosition default_snap_position = split_view_controller_->default_snap_position(); // If we're trying to snap to a position that already has a snapped window:
diff --git a/ash/wm/overview/overview_window_drag_controller.h b/ash/wm/overview/overview_window_drag_controller.h index e497c6d..99f8d3c 100644 --- a/ash/wm/overview/overview_window_drag_controller.h +++ b/ash/wm/overview/overview_window_drag_controller.h
@@ -10,7 +10,7 @@ #include "ash/ash_export.h" #include "ash/wm/splitview/split_view_controller.h" #include "base/macros.h" -#include "ui/gfx/geometry/point.h" +#include "ui/gfx/geometry/point_f.h" namespace ash { @@ -37,11 +37,11 @@ explicit OverviewWindowDragController(OverviewSession* overview_session); ~OverviewWindowDragController(); - void InitiateDrag(OverviewItem* item, const gfx::Point& location_in_screen); - void Drag(const gfx::Point& location_in_screen); - void CompleteDrag(const gfx::Point& location_in_screen); - void StartSplitViewDragMode(const gfx::Point& location_in_screen); - void Fling(const gfx::Point& location_in_screen, + void InitiateDrag(OverviewItem* item, const gfx::PointF& location_in_screen); + void Drag(const gfx::PointF& location_in_screen); + void CompleteDrag(const gfx::PointF& location_in_screen); + void StartSplitViewDragMode(const gfx::PointF& location_in_screen); + void Fling(const gfx::PointF& location_in_screen, float velocity_x, float velocity_y); void ActivateDraggedWindow(); @@ -60,15 +60,15 @@ private: // Updates visuals for the user while dragging items around. void UpdateDragIndicatorsAndOverviewGrid( - const gfx::Point& location_in_screen); + const gfx::PointF& location_in_screen); // Dragged items should not attempt to update the indicators or snap if // the drag started in a snap region and has not been dragged pass the // threshold. - bool ShouldUpdateDragIndicatorsOrSnap(const gfx::Point& event_location); + bool ShouldUpdateDragIndicatorsOrSnap(const gfx::PointF& event_location); SplitViewController::SnapPosition GetSnapPosition( - const gfx::Point& location_in_screen) const; + const gfx::PointF& location_in_screen) const; // Returns the expected window grid bounds based on |snap_position|. gfx::Rect GetGridBounds(SplitViewController::SnapPosition snap_position); @@ -84,11 +84,12 @@ DragBehavior current_drag_behavior_ = DragBehavior::kNoDrag; - // The location of the previous mouse/touch/gesture event in screen. - gfx::Point previous_event_location_; - // The location of the initial mouse/touch/gesture event in screen. - gfx::Point initial_event_location_; + gfx::PointF initial_event_location_; + + // Stores the bounds of |item_| when a drag is started. Used to calculate the + // new bounds on a drag event. + gfx::PointF initial_centerpoint_; // False if the initial drag location was not a snap region, or if it was in // a snap region but the drag has since moved out.
diff --git a/ash/wm/overview/scoped_overview_transform_window.cc b/ash/wm/overview/scoped_overview_transform_window.cc index 00843ff..ae3f814 100644 --- a/ash/wm/overview/scoped_overview_transform_window.cc +++ b/ash/wm/overview/scoped_overview_transform_window.cc
@@ -31,7 +31,6 @@ #include "ui/compositor/layer.h" #include "ui/compositor/layer_observer.h" #include "ui/compositor/paint_recorder.h" -#include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/safe_integer_conversions.h" #include "ui/gfx/transform_util.h" #include "ui/views/widget/widget.h" @@ -189,23 +188,23 @@ } // static -float ScopedOverviewTransformWindow::GetItemScale(const gfx::Size& source, - const gfx::Size& target, +float ScopedOverviewTransformWindow::GetItemScale(const gfx::SizeF& source, + const gfx::SizeF& target, int top_view_inset, int title_height) { - return std::min(2.0f, static_cast<float>((target.height() - title_height)) / + return std::min(2.0f, (target.height() - title_height) / (source.height() - top_view_inset)); } // static gfx::Transform ScopedOverviewTransformWindow::GetTransformForRect( - const gfx::Rect& src_rect, - const gfx::Rect& dst_rect) { + const gfx::RectF& src_rect, + const gfx::RectF& dst_rect) { DCHECK(!src_rect.IsEmpty()); gfx::Transform transform; transform.Translate(dst_rect.x() - src_rect.x(), dst_rect.y() - src_rect.y()); - transform.Scale(static_cast<float>(dst_rect.width()) / src_rect.width(), - static_cast<float>(dst_rect.height()) / src_rect.height()); + transform.Scale(dst_rect.width() / src_rect.width(), + dst_rect.height() / src_rect.height()); return transform; } @@ -289,7 +288,7 @@ return minimized_widget_->GetNativeWindow()->Contains(target); } -gfx::Rect ScopedOverviewTransformWindow::GetTransformedBounds() const { +gfx::RectF ScopedOverviewTransformWindow::GetTransformedBounds() const { return ::ash::GetTransformedBounds(GetOverviewWindow(), GetTopInset()); } @@ -332,24 +331,22 @@ } } -gfx::Rect ScopedOverviewTransformWindow::ShrinkRectToFitPreservingAspectRatio( - const gfx::Rect& rect, - const gfx::Rect& bounds, +gfx::RectF ScopedOverviewTransformWindow::ShrinkRectToFitPreservingAspectRatio( + const gfx::RectF& rect, + const gfx::RectF& bounds, int top_view_inset, int title_height) { DCHECK(!rect.IsEmpty()); DCHECK_LE(top_view_inset, rect.height()); const float scale = GetItemScale(rect.size(), bounds.size(), top_view_inset, title_height); - const int horizontal_offset = gfx::ToFlooredInt( - 0.5 * (bounds.width() - gfx::ToFlooredInt(scale * rect.width()))); - const int width = bounds.width() - 2 * horizontal_offset; - const int vertical_offset = - title_height - gfx::ToCeiledInt(scale * top_view_inset); - const int height = std::min(gfx::ToCeiledInt(scale * rect.height()), - bounds.height() - vertical_offset); - gfx::Rect new_bounds(bounds.x() + horizontal_offset, - bounds.y() + vertical_offset, width, height); + const float horizontal_offset = 0.5 * (bounds.width() - scale * rect.width()); + const float width = bounds.width() - 2.f * horizontal_offset; + const float vertical_offset = title_height - scale * top_view_inset; + const float height = + std::min(scale * rect.height(), bounds.height() - vertical_offset); + gfx::RectF new_bounds(bounds.x() + horizontal_offset, + bounds.y() + vertical_offset, width, height); switch (type()) { case ScopedOverviewTransformWindow::GridWindowFillMode::kLetterBoxed: @@ -360,16 +357,14 @@ const bool is_pillar = type() == ScopedOverviewTransformWindow::GridWindowFillMode::kPillarBoxed; - gfx::Rect src = rect; + gfx::RectF src = rect; new_bounds = bounds; src.Inset(0, top_view_inset, 0, 0); new_bounds.Inset(0, title_height, 0, 0); - float scale = is_pillar ? static_cast<float>(new_bounds.height()) / - static_cast<float>(src.height()) - : static_cast<float>(new_bounds.width()) / - static_cast<float>(src.width()); - gfx::Size size(is_pillar ? src.width() * scale : new_bounds.width(), - is_pillar ? new_bounds.height() : src.height() * scale); + float scale = is_pillar ? new_bounds.height() / src.height() + : new_bounds.width() / src.width(); + gfx::SizeF size(is_pillar ? src.width() * scale : new_bounds.width(), + is_pillar ? new_bounds.height() : src.height() * scale); new_bounds.ClampToCenteredSize(size); // Extend |new_bounds| in the vertical direction to account for the header
diff --git a/ash/wm/overview/scoped_overview_transform_window.h b/ash/wm/overview/scoped_overview_transform_window.h index b5affb5..219ab4d8 100644 --- a/ash/wm/overview/scoped_overview_transform_window.h +++ b/ash/wm/overview/scoped_overview_transform_window.h
@@ -16,6 +16,7 @@ #include "services/ws/public/mojom/window_tree_constants.mojom.h" #include "ui/compositor/layer_animation_observer.h" #include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/transform.h" @@ -23,10 +24,6 @@ class Window; } -namespace gfx { -class Rect; -} - namespace ui { class Layer; } @@ -66,14 +63,14 @@ // Calculates and returns an optimal scale ratio. This is only taking into // account |size.height()| as the width can vary. - static float GetItemScale(const gfx::Size& source, - const gfx::Size& target, + static float GetItemScale(const gfx::SizeF& source, + const gfx::SizeF& target, int top_view_inset, int title_height); // Returns the transform turning |src_rect| into |dst_rect|. - static gfx::Transform GetTransformForRect(const gfx::Rect& src_rect, - const gfx::Rect& dst_rect); + static gfx::Transform GetTransformForRect(const gfx::RectF& src_rect, + const gfx::RectF& dst_rect); ScopedOverviewTransformWindow(OverviewItem* overview_item, aura::Window* window); @@ -102,7 +99,7 @@ // Returns transformed bounds of the overview window. See // OverviewUtil::GetTransformedBounds for more details. - gfx::Rect GetTransformedBounds() const; + gfx::RectF GetTransformedBounds() const; // Returns the kTopViewInset property of |window_| unless there are transient // ancestors, in which case returns 0. @@ -132,16 +129,18 @@ // tall in the original window getting replaced by a window caption that is // |title_height| tall in the transformed window. If |type_| is not normal, // write |overview_bounds_|, which would differ than the return bounds. - gfx::Rect ShrinkRectToFitPreservingAspectRatio(const gfx::Rect& rect, - const gfx::Rect& bounds, - int top_view_inset, - int title_height); + gfx::RectF ShrinkRectToFitPreservingAspectRatio(const gfx::RectF& rect, + const gfx::RectF& bounds, + int top_view_inset, + int title_height); aura::Window* window() const { return window_; } GridWindowFillMode type() const { return type_; } - base::Optional<gfx::Rect> overview_bounds() const { return overview_bounds_; } + base::Optional<gfx::RectF> overview_bounds() const { + return overview_bounds_; + } // Closes the transient root of the window managed by |this|. void Close(); @@ -219,7 +218,7 @@ // Empty if window is of type normal. Contains the bounds the overview item // should be if the window is too wide or too tall. - base::Optional<gfx::Rect> overview_bounds_; + base::Optional<gfx::RectF> overview_bounds_; // A widget that holds the content for the minimized window. std::unique_ptr<views::Widget> minimized_widget_;
diff --git a/ash/wm/overview/scoped_overview_transform_window_unittest.cc b/ash/wm/overview/scoped_overview_transform_window_unittest.cc index e3a673cb..9f7fdadd 100644 --- a/ash/wm/overview/scoped_overview_transform_window_unittest.cc +++ b/ash/wm/overview/scoped_overview_transform_window_unittest.cc
@@ -15,8 +15,8 @@ namespace { -float GetItemScale(const gfx::Rect& source, - const gfx::Rect& target, +float GetItemScale(const gfx::RectF& source, + const gfx::RectF& target, int top_view_inset, int title_height) { return ScopedOverviewTransformWindow::GetItemScale( @@ -38,36 +38,36 @@ CreateTestWindow(gfx::Rect(10, 10, 100, 100)); ScopedOverviewTransformWindow transform_window(nullptr, window.get()); - gfx::Rect rect(50, 50, 200, 400); - gfx::Rect bounds(100, 100, 50, 50); - gfx::Rect transformed_rect = + gfx::RectF rect(50.f, 50.f, 200.f, 400.f); + gfx::RectF bounds(100.f, 100.f, 50.f, 50.f); + gfx::RectF transformed_rect = transform_window.ShrinkRectToFitPreservingAspectRatio(rect, bounds, 0, 0); float scale = GetItemScale(rect, bounds, 0, 0); EXPECT_NEAR(scale * rect.width(), transformed_rect.width(), 1); EXPECT_NEAR(scale * rect.height(), transformed_rect.height(), 1); - rect = gfx::Rect(50, 50, 400, 200); + rect = gfx::RectF(50.f, 50.f, 400.f, 200.f); scale = GetItemScale(rect, bounds, 0, 0); transformed_rect = transform_window.ShrinkRectToFitPreservingAspectRatio(rect, bounds, 0, 0); EXPECT_NEAR(scale * rect.width(), transformed_rect.width(), 1); EXPECT_NEAR(scale * rect.height(), transformed_rect.height(), 1); - rect = gfx::Rect(50, 50, 25, 25); + rect = gfx::RectF(50.f, 50.f, 25.f, 25.f); scale = GetItemScale(rect, bounds, 0, 0); transformed_rect = transform_window.ShrinkRectToFitPreservingAspectRatio(rect, bounds, 0, 0); EXPECT_NEAR(scale * rect.width(), transformed_rect.width(), 1); EXPECT_NEAR(scale * rect.height(), transformed_rect.height(), 1); - rect = gfx::Rect(50, 50, 25, 50); + rect = gfx::RectF(50.f, 50.f, 25.f, 50.f); scale = GetItemScale(rect, bounds, 0, 0); transformed_rect = transform_window.ShrinkRectToFitPreservingAspectRatio(rect, bounds, 0, 0); EXPECT_NEAR(scale * rect.width(), transformed_rect.width(), 1); EXPECT_NEAR(scale * rect.height(), transformed_rect.height(), 1); - rect = gfx::Rect(50, 50, 50, 25); + rect = gfx::RectF(50.f, 50.f, 50.f, 25.f); scale = GetItemScale(rect, bounds, 0, 0); transformed_rect = transform_window.ShrinkRectToFitPreservingAspectRatio(rect, bounds, 0, 0); @@ -80,9 +80,9 @@ std::unique_ptr<aura::Window> window = CreateTestWindow(gfx::Rect(10, 10, 100, 100)); ScopedOverviewTransformWindow transform_window(nullptr, window.get()); - gfx::Rect rect(50, 50, 200, 400); - gfx::Rect bounds(100, 100, 50, 50); - gfx::Rect transformed_rect = + gfx::RectF rect(50.f, 50.f, 200.f, 400.f); + gfx::RectF bounds(100.f, 100.f, 50.f, 50.f); + gfx::RectF transformed_rect = transform_window.ShrinkRectToFitPreservingAspectRatio(rect, bounds, 0, 0); EXPECT_GE(transformed_rect.x(), bounds.x()); EXPECT_LE(transformed_rect.right(), bounds.right()); @@ -100,12 +100,12 @@ std::unique_ptr<aura::Window> window = CreateTestWindow(gfx::Rect(10, 10, 100, 100)); ScopedOverviewTransformWindow transform_window(nullptr, window.get()); - gfx::Rect rect(50, 50, 400, 200); - gfx::Rect bounds(100, 100, 50, 50); + gfx::RectF rect(50.f, 50.f, 400.f, 200.f); + gfx::RectF bounds(100.f, 100.f, 50.f, 50.f); const int inset = 20; const int header_height = 10; const float scale = GetItemScale(rect, bounds, inset, header_height); - gfx::Rect transformed_rect = + gfx::RectF transformed_rect = transform_window.ShrinkRectToFitPreservingAspectRatio(rect, bounds, inset, header_height); // The |rect| width does not fit and therefore it gets centered outside @@ -136,10 +136,10 @@ // Without any headers, the width should match the target, and the height // should be such that the aspect ratio of |original_bounds| is maintained. - const gfx::Rect overview_bounds(0, 0, 100, 100); - gfx::Rect transformed_rect = + const gfx::RectF overview_bounds(100.f, 100.f); + gfx::RectF transformed_rect = transform_window.ShrinkRectToFitPreservingAspectRatio( - original_bounds, overview_bounds, 0, 0); + gfx::RectF(original_bounds), overview_bounds, 0, 0); EXPECT_EQ(overview_bounds.width(), transformed_rect.width()); EXPECT_NEAR(overview_bounds.height() / scale, transformed_rect.height(), 1); @@ -149,7 +149,8 @@ const int original_header = 10; const int overview_header = 20; transformed_rect = transform_window.ShrinkRectToFitPreservingAspectRatio( - original_bounds, overview_bounds, original_header, overview_header); + gfx::RectF(original_bounds), overview_bounds, original_header, + overview_header); EXPECT_EQ(overview_bounds.width(), transformed_rect.width()); EXPECT_NEAR((overview_bounds.height() - original_header) / scale, transformed_rect.height() - original_header / scale, 1); @@ -157,7 +158,7 @@ // Verify that for an extreme window, the transform window stores the // original overview item bounds, minus the header. - gfx::Rect new_overview_bounds = overview_bounds; + gfx::RectF new_overview_bounds = overview_bounds; new_overview_bounds.Inset(0, overview_header, 0, 0); ASSERT_TRUE(transform_window.overview_bounds().has_value()); EXPECT_EQ(transform_window.overview_bounds().value(), new_overview_bounds); @@ -176,10 +177,10 @@ // Without any headers, the height should match the target, and the width // should be such that the aspect ratio of |original_bounds| is maintained. - const gfx::Rect overview_bounds(0, 0, 100, 100); - gfx::Rect transformed_rect = + const gfx::RectF overview_bounds(100.f, 100.f); + gfx::RectF transformed_rect = transform_window.ShrinkRectToFitPreservingAspectRatio( - original_bounds, overview_bounds, 0, 0); + gfx::RectF(original_bounds), overview_bounds, 0, 0); EXPECT_EQ(overview_bounds.height(), transformed_rect.height()); EXPECT_NEAR(overview_bounds.width() / scale, transformed_rect.width(), 1); @@ -189,14 +190,15 @@ const int original_header = 10; const int overview_header = 20; transformed_rect = transform_window.ShrinkRectToFitPreservingAspectRatio( - original_bounds, overview_bounds, original_header, overview_header); + gfx::RectF(original_bounds), overview_bounds, original_header, + overview_header); EXPECT_NEAR(overview_bounds.height() - overview_header, transformed_rect.height() - original_header / scale, 1); EXPECT_TRUE(overview_bounds.Contains(transformed_rect)); // Verify that for an extreme window, the transform window stores the // original overview item bounds, minus the header. - gfx::Rect new_overview_bounds = overview_bounds; + gfx::RectF new_overview_bounds = overview_bounds; new_overview_bounds.Inset(0, overview_header, 0, 0); ASSERT_TRUE(transform_window.overview_bounds().has_value()); EXPECT_EQ(transform_window.overview_bounds().value(), new_overview_bounds);
diff --git a/ash/wm/splitview/split_view_constants.h b/ash/wm/splitview/split_view_constants.h index 0ae22a5..7ea0294a 100644 --- a/ash/wm/splitview/split_view_constants.h +++ b/ash/wm/splitview/split_view_constants.h
@@ -12,10 +12,10 @@ // The ratio between a highlight view's primary axis, and the screens // primary axis. -ASH_EXPORT constexpr double kHighlightScreenPrimaryAxisRatio = 0.10; +ASH_EXPORT constexpr float kHighlightScreenPrimaryAxisRatio = 0.10; // The padding between a highlight view and the edge of the screen. -ASH_EXPORT constexpr double kHighlightScreenEdgePaddingDp = 8; +ASH_EXPORT constexpr float kHighlightScreenEdgePaddingDp = 8; // The amount of inset to be applied on a split view label. Here horizontal and // vertical apply to the orientation before rotation (if there is rotation).
diff --git a/ash/wm/splitview/split_view_controller.cc b/ash/wm/splitview/split_view_controller.cc index 0526923..852d7123 100644 --- a/ash/wm/splitview/split_view_controller.cc +++ b/ash/wm/splitview/split_view_controller.cc
@@ -1346,8 +1346,8 @@ const gfx::Rect snapped_bounds = GetSnappedWindowBoundsInScreen( window, (window == left_window_) ? LEFT : RIGHT); const gfx::Transform starting_transform = - ScopedOverviewTransformWindow::GetTransformForRect(snapped_bounds, - item_bounds); + ScopedOverviewTransformWindow::GetTransformForRect( + gfx::RectF(snapped_bounds), gfx::RectF(item_bounds)); SetTransformWithAnimation(window, starting_transform, gfx::Transform()); } } @@ -1434,7 +1434,8 @@ aura::Window* window, const gfx::Transform& start_transform, const gfx::Transform& target_transform) { - gfx::Point target_origin(GetTargetBoundsInScreen(window).origin()); + gfx::Point target_origin = + gfx::ToRoundedPoint(GetTargetBoundsInScreen(window).origin()); for (auto* window_iter : wm::GetTransientTreeIterator(window)) { // Adjust |start_transform| and |target_transform| for the transient child. aura::Window* parent_window = window_iter->parent(); @@ -1484,7 +1485,7 @@ aura::Window* window) { if (!window->layer()->GetTargetTransform().IsIdentity()) { snapping_window_transformed_bounds_map_[window] = - GetTransformedBounds(window, /*top_inset=*/0); + gfx::ToEnclosedRect(GetTransformedBounds(window, /*top_inset=*/0)); } }
diff --git a/ash/wm/splitview/split_view_controller_unittest.cc b/ash/wm/splitview/split_view_controller_unittest.cc index 18597d0..702f6fd 100644 --- a/ash/wm/splitview/split_view_controller_unittest.cc +++ b/ash/wm/splitview/split_view_controller_unittest.cc
@@ -2028,7 +2028,7 @@ DCHECK(current_grid); OverviewItem* overview_item = current_grid->GetDropTarget(); - return overview_item->GetTransformedBounds(); + return gfx::ToEnclosedRect(overview_item->GetTransformedBounds()); } private: @@ -2683,7 +2683,8 @@ drop_target_widget->GetNativeWindow()); ASSERT_TRUE(drop_target); EXPECT_EQ(drop_target, current_grid->window_list().front().get()); - const gfx::Rect drop_target_bounds = drop_target->target_bounds(); + const gfx::Rect drop_target_bounds = + gfx::ToEnclosingRect(drop_target->target_bounds()); DragWindowTo(resizer.get(), drop_target_bounds.CenterPoint()); CompleteDrag(std::move(resizer)); @@ -2960,7 +2961,8 @@ OverviewItem* overview_item = current_grid->GetDropTarget(); ASSERT_TRUE(overview_item); - gfx::Rect drop_target_bounds = overview_item->target_bounds(); + gfx::Rect drop_target_bounds = + gfx::ToEnclosingRect(overview_item->target_bounds()); DragWindowTo(resizer.get(), drop_target_bounds.CenterPoint()); CompleteDrag(std::move(resizer)); @@ -2972,7 +2974,8 @@ overview_item = current_grid->window_list().front().get(); // The new overview item's bounds should be the same during drag and after // drag. - EXPECT_EQ(drop_target_bounds, overview_item->target_bounds()); + EXPECT_EQ(drop_target_bounds, + gfx::ToEnclosingRect(overview_item->target_bounds())); ToggleOverview(); EXPECT_FALSE(overview_controller->IsSelecting());
diff --git a/ash/wm/splitview/split_view_drag_indicators_unittest.cc b/ash/wm/splitview/split_view_drag_indicators_unittest.cc index a861d1f3..74ca413 100644 --- a/ash/wm/splitview/split_view_drag_indicators_unittest.cc +++ b/ash/wm/splitview/split_view_drag_indicators_unittest.cc
@@ -79,7 +79,7 @@ return iter->get(); } - int GetEdgeInset(int screen_width) const { + float GetEdgeInset(int screen_width) const { return screen_width * kHighlightScreenPrimaryAxisRatio + kHighlightScreenEdgePaddingDp; } @@ -104,7 +104,7 @@ Shell::Get()->aura_env()->set_throttle_input_on_resize_for_testing(false); UpdateDisplay("800x600"); const int screen_width = 800; - const int edge_inset = GetEdgeInset(screen_width); + const float edge_inset = GetEdgeInset(screen_width); std::unique_ptr<aura::Window> right_window(CreateTestWindow()); std::unique_ptr<aura::Window> left_window(CreateTestWindow()); ui::test::EventGenerator* generator = GetEventGenerator(); @@ -134,9 +134,9 @@ // must move by |drag_offset| before split view acknowledges the drag (ie. // starts moving the selector item). generator->set_current_screen_location( - left_item->target_bounds().CenterPoint()); + gfx::ToRoundedPoint(left_item->target_bounds().CenterPoint())); generator->PressLeftButton(); - const gfx::Rect left_original_bounds = left_item->target_bounds(); + const gfx::RectF left_original_bounds = left_item->target_bounds(); generator->MoveMouseBy(drag_offset - 1, 0); EXPECT_EQ(left_original_bounds, left_item->target_bounds()); generator->MoveMouseBy(1, 0); @@ -158,7 +158,8 @@ EXPECT_TRUE(IsPreviewAreaShowing()); // Drag back to the middle before releasing so that we stay in overview mode // on release. - generator->MoveMouseTo(left_original_bounds.CenterPoint()); + generator->MoveMouseTo( + gfx::ToRoundedPoint(left_original_bounds.CenterPoint())); generator->ReleaseLeftButton(); // Verify if the drag is started in the right snap region, the drag needs to @@ -180,7 +181,7 @@ TEST_F(SplitViewDragIndicatorsTest, PreviewAreaVisibility) { UpdateDisplay("800x600"); const int screen_width = 800; - const int edge_inset = GetEdgeInset(screen_width); + const float edge_inset = GetEdgeInset(screen_width); std::unique_ptr<aura::Window> window(CreateTestWindow()); ToggleOverview(); @@ -188,19 +189,19 @@ // range [0, edge_inset] or [screen_width - edge_inset - 1, screen_width]. OverviewItem* item = GetOverviewItemForWindow(window.get()); ASSERT_TRUE(item); - const gfx::Point start_location(item->target_bounds().CenterPoint()); + const gfx::PointF start_location(item->target_bounds().CenterPoint()); // Drag horizontally to avoid activating drag to close. - const int y = start_location.y(); + const float y = start_location.y(); overview_session_->InitiateDrag(item, start_location); EXPECT_FALSE(IsPreviewAreaShowing()); - overview_session_->Drag(item, gfx::Point(edge_inset + 1, y)); + overview_session_->Drag(item, gfx::PointF(edge_inset + 1, y)); EXPECT_FALSE(IsPreviewAreaShowing()); - overview_session_->Drag(item, gfx::Point(edge_inset, y)); + overview_session_->Drag(item, gfx::PointF(edge_inset, y)); EXPECT_TRUE(IsPreviewAreaShowing()); - overview_session_->Drag(item, gfx::Point(screen_width - edge_inset - 2, y)); + overview_session_->Drag(item, gfx::PointF(screen_width - edge_inset - 2, y)); EXPECT_FALSE(IsPreviewAreaShowing()); - overview_session_->Drag(item, gfx::Point(screen_width - edge_inset - 1, y)); + overview_session_->Drag(item, gfx::PointF(screen_width - edge_inset - 1, y)); EXPECT_TRUE(IsPreviewAreaShowing()); // Drag back to |start_location| before compeleting the drag, otherwise @@ -220,12 +221,12 @@ ToggleOverview(); OverviewItem* item = GetOverviewItemForWindow(window.get()); - const gfx::Point start_location(item->target_bounds().CenterPoint()); + const gfx::PointF start_location(item->target_bounds().CenterPoint()); overview_session_->InitiateDrag(item, start_location); EXPECT_FALSE(IsPreviewAreaShowing()); - overview_session_->Drag(item, gfx::Point(0, 1)); + overview_session_->Drag(item, gfx::PointF(0.f, 1.f)); EXPECT_FALSE(IsPreviewAreaShowing()); - overview_session_->Drag(item, gfx::Point(screen_width, 1)); + overview_session_->Drag(item, gfx::PointF(screen_width, 1.f)); EXPECT_FALSE(IsPreviewAreaShowing()); overview_session_->CompleteDrag(item, start_location); @@ -236,7 +237,7 @@ TEST_F(SplitViewDragIndicatorsTest, SplitViewDragIndicatorsState) { UpdateDisplay("800x600"); const int screen_width = 800; - const int edge_inset = GetEdgeInset(screen_width); + const float edge_inset = GetEdgeInset(screen_width); std::unique_ptr<aura::Window> window1(CreateTestWindow()); std::unique_ptr<aura::Window> window2(CreateTestWindow()); ToggleOverview(); @@ -244,7 +245,7 @@ // Verify that when are no snapped windows, the indicator is visible once // there is a long press or after the drag has started. OverviewItem* item = GetOverviewItemForWindow(window1.get()); - gfx::Point start_location(item->target_bounds().CenterPoint()); + gfx::PointF start_location(item->target_bounds().CenterPoint()); overview_session_->InitiateDrag(item, start_location); EXPECT_EQ(IndicatorState::kNone, indicator_state()); overview_session_->StartSplitViewDragMode(start_location); @@ -256,16 +257,16 @@ // Verify the indicator is visible once the item starts moving, and becomes a // preview area once we reach the left edge of the screen. Drag horizontal to // avoid activating drag to close. - const int y_position = start_location.y(); + const float y_position = start_location.y(); overview_session_->InitiateDrag(item, start_location); EXPECT_EQ(IndicatorState::kNone, indicator_state()); - overview_session_->Drag(item, gfx::Point(edge_inset + 1, y_position)); + overview_session_->Drag(item, gfx::PointF(edge_inset + 1, y_position)); EXPECT_EQ(IndicatorState::kDragArea, indicator_state()); - overview_session_->Drag(item, gfx::Point(edge_inset, y_position)); + overview_session_->Drag(item, gfx::PointF(edge_inset, y_position)); EXPECT_EQ(IndicatorState::kPreviewAreaLeft, indicator_state()); // Snap window to the left. - overview_session_->CompleteDrag(item, gfx::Point(edge_inset, y_position)); + overview_session_->CompleteDrag(item, gfx::PointF(edge_inset, y_position)); ASSERT_TRUE(split_view_controller()->IsSplitViewModeActive()); ASSERT_EQ(SplitViewController::LEFT_SNAPPED, split_view_controller()->state()); @@ -276,7 +277,7 @@ start_location = item->target_bounds().CenterPoint(); overview_session_->InitiateDrag(item, start_location); EXPECT_EQ(IndicatorState::kNone, indicator_state()); - overview_session_->Drag(item, gfx::Point(screen_width - 1, y_position)); + overview_session_->Drag(item, gfx::PointF(screen_width - 1, y_position)); EXPECT_EQ(IndicatorState::kPreviewAreaRight, indicator_state()); overview_session_->CompleteDrag(item, start_location); } @@ -289,11 +290,11 @@ ToggleOverview(); OverviewItem* item = GetOverviewItemForWindow(unsnappable_window.get()); - gfx::Point start_location(item->target_bounds().CenterPoint()); + gfx::PointF start_location(item->target_bounds().CenterPoint()); overview_session_->InitiateDrag(item, start_location); overview_session_->StartSplitViewDragMode(start_location); EXPECT_EQ(IndicatorState::kCannotSnap, indicator_state()); - const gfx::Point end_location1(0, 0); + const gfx::PointF end_location1(0.f, 0.f); overview_session_->Drag(item, end_location1); EXPECT_EQ(IndicatorState::kCannotSnap, indicator_state()); overview_session_->CompleteDrag(item, end_location1); @@ -367,26 +368,28 @@ // Select an item on the primary display and verify the drag indicators // widget's parent is the primary root window. OverviewItem* item = GetOverviewItemForWindow(primary_screen_window.get()); - gfx::Point start_location(item->target_bounds().CenterPoint()); + gfx::PointF start_location(item->target_bounds().CenterPoint()); overview_session_->InitiateDrag(item, start_location); - overview_session_->Drag(item, gfx::Point(100, start_location.y())); + overview_session_->Drag(item, gfx::PointF(100.f, start_location.y())); EXPECT_EQ(IndicatorState::kDragArea, indicator_state()); EXPECT_EQ(root_windows[0], overview_session_->split_view_drag_indicators() ->widget_->GetNativeView() ->GetRootWindow()); // Drag the item in a way that neither opens the window nor activates // splitview mode. - overview_session_->Drag(item, primary_screen_bounds.CenterPoint()); - overview_session_->CompleteDrag(item, primary_screen_bounds.CenterPoint()); + overview_session_->Drag(item, + gfx::PointF(primary_screen_bounds.CenterPoint())); + overview_session_->CompleteDrag( + item, gfx::PointF(primary_screen_bounds.CenterPoint())); ASSERT_TRUE(Shell::Get()->overview_controller()->IsSelecting()); ASSERT_FALSE(split_view_controller()->IsSplitViewModeActive()); // Select an item on the secondary display and verify the indicators widget // has reparented to the secondary root window. item = GetOverviewItemForWindow(secondary_screen_window.get(), 1); - start_location = gfx::Point(item->target_bounds().CenterPoint()); + start_location = item->target_bounds().CenterPoint(); overview_session_->InitiateDrag(item, start_location); - overview_session_->Drag(item, gfx::Point(800, start_location.y())); + overview_session_->Drag(item, gfx::PointF(800.f, start_location.y())); EXPECT_EQ(IndicatorState::kDragArea, indicator_state()); EXPECT_EQ(root_windows[1], overview_session_->split_view_drag_indicators() ->widget_->GetNativeView()
diff --git a/ash/wm/toplevel_window_event_handler.cc b/ash/wm/toplevel_window_event_handler.cc index fdef5fe..48e504c 100644 --- a/ash/wm/toplevel_window_event_handler.cc +++ b/ash/wm/toplevel_window_event_handler.cc
@@ -51,13 +51,9 @@ ::wm::WindowMoveSource source = gesture_target ? ::wm::WINDOW_MOVE_SOURCE_TOUCH : ::wm::WINDOW_MOVE_SOURCE_MOUSE; - if (gesture_target) { - window->env()->gesture_recognizer()->TransferEventsTo( - gesture_target, window, ui::TransferTouchesBehavior::kDontCancel); - } return wm_toplevel_window_event_handler_.AttemptToStartDrag( - window, point_in_parent, window_component, source, - std::move(end_closure)); + window, point_in_parent, window_component, source, std::move(end_closure), + /*update_gesture_target=*/true); } ::wm::WindowMoveResult ToplevelWindowEventHandler::RunMoveLoop( @@ -96,7 +92,8 @@ if (!wm_toplevel_window_event_handler_.AttemptToStartDrag( source, drag_location, HTCAPTION, move_source, base::Bind(&ToplevelWindowEventHandler::OnDragCompleted, - weak_factory_.GetWeakPtr(), &result, &run_loop))) { + weak_factory_.GetWeakPtr(), &result, &run_loop), + /*update_gesture_target=*/false)) { return ::wm::MOVE_CANCELED; }
diff --git a/ash/wm/window_finder_unittest.cc b/ash/wm/window_finder_unittest.cc index c031b42b..1fe01d14d 100644 --- a/ash/wm/window_finder_unittest.cc +++ b/ash/wm/window_finder_unittest.cc
@@ -141,10 +141,10 @@ OverviewGrid* grid = overview_controller->overview_session()->GetGridWithRootWindow( window1->GetRootWindow()); - gfx::Rect bounds1 = - grid->GetOverviewItemContaining(window1.get())->target_bounds(); - gfx::Rect bounds2 = - grid->GetOverviewItemContaining(window2.get())->target_bounds(); + gfx::Rect bounds1 = gfx::ToEnclosedRect( + grid->GetOverviewItemContaining(window1.get())->target_bounds()); + gfx::Rect bounds2 = gfx::ToEnclosedRect( + grid->GetOverviewItemContaining(window2.get())->target_bounds()); std::set<aura::Window*> ignore; aura::Window* real_topmost = nullptr;
diff --git a/ash/wm/wm_toplevel_window_event_handler.cc b/ash/wm/wm_toplevel_window_event_handler.cc index e261958..34b179b 100644 --- a/ash/wm/wm_toplevel_window_event_handler.cc +++ b/ash/wm/wm_toplevel_window_event_handler.cc
@@ -376,7 +376,8 @@ if (CanStartTwoFingerMove(target, first_finger_hittest_, second_finger_hittest)) { AttemptToStartDrag(target, first_finger_touch_point_, HTCAPTION, - ::wm::WINDOW_MOVE_SOURCE_TOUCH, EndClosure()); + ::wm::WINDOW_MOVE_SOURCE_TOUCH, EndClosure(), + /*update_gesture_target=*/false); event->StopPropagation(); } } @@ -398,7 +399,8 @@ aura::Window::ConvertPointToTarget(target, target->parent(), &location_in_parent); AttemptToStartDrag(target, location_in_parent, component, - ::wm::WINDOW_MOVE_SOURCE_TOUCH, EndClosure()); + ::wm::WINDOW_MOVE_SOURCE_TOUCH, EndClosure(), + /*update_gesture_target=*/false); event->StopPropagation(); return; } @@ -461,7 +463,8 @@ const gfx::Point& point_in_parent, int window_component, ::wm::WindowMoveSource source, - EndClosure end_closure) { + EndClosure end_closure, + bool update_gesture_target) { if (!PrepareForDrag(window, point_in_parent, window_component, source)) { // Treat failure to start as a revert. if (end_closure) @@ -473,8 +476,14 @@ in_gesture_drag_ = (source == ::wm::WINDOW_MOVE_SOURCE_TOUCH); // |gesture_target_| needs to be updated if the drag originated from a // client (i.e. |this| never handled ET_GESTURE_EVENT_BEGIN). - if (in_gesture_drag_ && !gesture_target_) + if (in_gesture_drag_ && (!gesture_target_ || update_gesture_target)) { + if (gesture_target_ && gesture_target_ != window) { + // Transfer events for gesture if switching to new target. + window->env()->gesture_recognizer()->TransferEventsTo( + gesture_target_, window, ui::TransferTouchesBehavior::kDontCancel); + } UpdateGestureTarget(window); + } return true; } @@ -543,7 +552,8 @@ aura::Window::ConvertPointToTarget(target, target->parent(), &location_in_parent); AttemptToStartDrag(target, location_in_parent, component, - ::wm::WINDOW_MOVE_SOURCE_MOUSE, EndClosure()); + ::wm::WINDOW_MOVE_SOURCE_MOUSE, EndClosure(), + /*update_gesture_target=*/false); // Set as handled so that other event handlers do no act upon the event // but still receive it so that they receive both parts of each pressed/ // released pair.
diff --git a/ash/wm/wm_toplevel_window_event_handler.h b/ash/wm/wm_toplevel_window_event_handler.h index 12205ac..37c2b63 100644 --- a/ash/wm/wm_toplevel_window_event_handler.h +++ b/ash/wm/wm_toplevel_window_event_handler.h
@@ -67,12 +67,15 @@ // Attempts to start a drag if one is not already in progress. Returns true if // successful. |end_closure| is run when the drag completes, including if the - // drag is not started. + // drag is not started. If |update_gesture_target| is true, the gesture + // target is forcefully updated and gesture events are transferred to + // new target if any. bool AttemptToStartDrag(aura::Window* window, const gfx::Point& point_in_parent, int window_component, ::wm::WindowMoveSource source, - EndClosure end_closure); + EndClosure end_closure, + bool update_gesture_target); // If there is a drag in progress it is reverted, otherwise does nothing. void RevertDrag();
diff --git a/ash/wm/wm_toplevel_window_event_handler_unittest.cc b/ash/wm/wm_toplevel_window_event_handler_unittest.cc index 6dc246a9..80ac565 100644 --- a/ash/wm/wm_toplevel_window_event_handler_unittest.cc +++ b/ash/wm/wm_toplevel_window_event_handler_unittest.cc
@@ -87,7 +87,8 @@ non_dragged_window_->GetRootWindow()); OverviewItem* item = current_grid->GetOverviewItemContaining(non_dragged_window_.get()); - GetEventGenerator()->GestureTapAt(item->GetTransformedBounds().CenterPoint()); + GetEventGenerator()->GestureTapAt( + gfx::ToRoundedPoint(item->GetTransformedBounds().CenterPoint())); // Overview mode is no longer active and |non_dragged_window_| is not in the // overview grid after tapping it in overview grid.
diff --git a/ash/ws/window_service_delegate_impl.cc b/ash/ws/window_service_delegate_impl.cc index d66b1efb..a17f378 100644 --- a/ash/ws/window_service_delegate_impl.cc +++ b/ash/ws/window_service_delegate_impl.cc
@@ -137,7 +137,8 @@ ->wm_toplevel_window_event_handler() ->AttemptToStartDrag( window, location_in_parent, window_component, aura_source, - base::BindOnce(&OnMoveLoopCompleted, std::move(callback))); + base::BindOnce(&OnMoveLoopCompleted, std::move(callback)), + /*update_gesture_target=*/false); } void WindowServiceDelegateImpl::CancelWindowMoveLoop() {
diff --git a/base/OWNERS b/base/OWNERS index defbe4f4e..32711874 100644 --- a/base/OWNERS +++ b/base/OWNERS
@@ -22,6 +22,9 @@ # For Fuchsia-specific changes: per-file *_fuchsia*=file://build/fuchsia/OWNERS +# For Windows-specific changes: +per-file *_win*=file://base/win/OWNERS + # For FeatureList API: per-file feature_list*=asvitkine@chromium.org per-file feature_list*=isherman@chromium.org
diff --git a/base/android/java/src/org/chromium/base/TraceEvent.java b/base/android/java/src/org/chromium/base/TraceEvent.java index b741df5..1054d47 100644 --- a/base/android/java/src/org/chromium/base/TraceEvent.java +++ b/base/android/java/src/org/chromium/base/TraceEvent.java
@@ -33,7 +33,8 @@ private static volatile boolean sATraceEnabled; // True when taking an Android systrace. private static class BasicLooperMonitor implements Printer { - private static final String EARLY_TOPLEVEL_TASK_NAME = "Looper.dispatchMessage: "; + private static final String LOOPER_TASK_PREFIX = "Looper.dispatch: "; + private static final int SHORTEST_LOG_PREFIX_LENGTH = "<<<<< Finished to ".length(); @Override public void println(final String line) { @@ -50,33 +51,58 @@ // will filter the event in this case. boolean earlyTracingActive = EarlyTraceEvent.isActive(); if (sEnabled || earlyTracingActive) { - String target = getTarget(line); + String target = getTraceEventName(line); if (sEnabled) { nativeBeginToplevel(target); - } else if (earlyTracingActive) { - // Synthesize a task name instead of using a parameter, as early tracing doesn't - // support parameters. - EarlyTraceEvent.begin(EARLY_TOPLEVEL_TASK_NAME + target); + } else { + EarlyTraceEvent.begin(target); } } } void endHandling(final String line) { - if (EarlyTraceEvent.isActive()) { - EarlyTraceEvent.end(EARLY_TOPLEVEL_TASK_NAME + getTarget(line)); + boolean earlyTracingActive = EarlyTraceEvent.isActive(); + if (sEnabled || earlyTracingActive) { + String target = getTraceEventName(line); + if (sEnabled) { + nativeEndToplevel(target); + } else { + EarlyTraceEvent.end(target); + } } - if (sEnabled) nativeEndToplevel(); + } + + private static String getTraceEventName(String line) { + return LOOPER_TASK_PREFIX + getTarget(line) + "(" + getTargetName(line) + ")"; } /** - * Android Looper formats |line| as ">>>>> Dispatching to (TARGET) [...]" since at least - * 2009 (Donut). Extracts the TARGET part of the message. + * Android Looper formats |logLine| as + * + * ">>>>> Dispatching to (TARGET) {HASH_CODE} TARGET_NAME: WHAT" + * + * and + * + * "<<<<< Finished to (TARGET) {HASH_CODE} TARGET_NAME". + * + * This has been the case since at least 2009 (Donut). This function extracts the + * TARGET part of the message. */ private static String getTarget(String logLine) { - int start = logLine.indexOf('(', 21); // strlen(">>>>> Dispatching to ") + int start = logLine.indexOf('(', SHORTEST_LOG_PREFIX_LENGTH); int end = start == -1 ? -1 : logLine.indexOf(')', start); return end != -1 ? logLine.substring(start + 1, end) : ""; } + + // Extracts the TARGET_NAME part of the log message (see above). + private static String getTargetName(String logLine) { + int start = logLine.indexOf('}', SHORTEST_LOG_PREFIX_LENGTH); + int end = start == -1 ? -1 : logLine.indexOf(':', start); + if (end == -1) { + end = logLine.length(); + } + return start != -1 ? logLine.substring(start + 2, end) : ""; + } } /** @@ -381,7 +407,7 @@ private static native void nativeBegin(String name, String arg); private static native void nativeEnd(String name, String arg); private static native void nativeBeginToplevel(String target); - private static native void nativeEndToplevel(); + private static native void nativeEndToplevel(String target); private static native void nativeStartAsync(String name, long id); private static native void nativeFinishAsync(String name, long id); }
diff --git a/base/android/trace_event_binding.cc b/base/android/trace_event_binding.cc index 495233f..e3c018f08 100644 --- a/base/android/trace_event_binding.cc +++ b/base/android/trace_event_binding.cc
@@ -19,7 +19,6 @@ constexpr const char kJavaCategory[] = "Java"; constexpr const char kToplevelCategory[] = "toplevel"; -constexpr const char kLooperDispatchMessage[] = "Looper.dispatchMessage"; // Boilerplate for safely converting Java data to TRACE_EVENT data. class TraceEventDataConverter { @@ -82,8 +81,8 @@ TraceEventDataConverter converter(env, jname, jarg); if (converter.arg()) { TRACE_EVENT_COPY_INSTANT1(kJavaCategory, converter.name(), - TRACE_EVENT_SCOPE_THREAD, - converter.arg_name(), converter.arg()); + TRACE_EVENT_SCOPE_THREAD, converter.arg_name(), + converter.arg()); } else { TRACE_EVENT_COPY_INSTANT0(kJavaCategory, converter.name(), TRACE_EVENT_SCOPE_THREAD); @@ -96,7 +95,7 @@ TraceEventDataConverter converter(env, jname, jarg); if (converter.arg()) { TRACE_EVENT_COPY_BEGIN1(kJavaCategory, converter.name(), - converter.arg_name(), converter.arg()); + converter.arg_name(), converter.arg()); } else { TRACE_EVENT_COPY_BEGIN0(kJavaCategory, converter.name()); } @@ -107,8 +106,8 @@ const JavaParamRef<jstring>& jarg) { TraceEventDataConverter converter(env, jname, jarg); if (converter.arg()) { - TRACE_EVENT_COPY_END1(kJavaCategory, converter.name(), - converter.arg_name(), converter.arg()); + TRACE_EVENT_COPY_END1(kJavaCategory, converter.name(), converter.arg_name(), + converter.arg()); } else { TRACE_EVENT_COPY_END0(kJavaCategory, converter.name()); } @@ -117,12 +116,13 @@ static void JNI_TraceEvent_BeginToplevel(JNIEnv* env, const JavaParamRef<jstring>& jtarget) { std::string target = ConvertJavaStringToUTF8(env, jtarget); - TRACE_EVENT_BEGIN1(kToplevelCategory, kLooperDispatchMessage, "target", - target); + TRACE_EVENT_COPY_BEGIN0(kToplevelCategory, target.c_str()); } -static void JNI_TraceEvent_EndToplevel(JNIEnv* env) { - TRACE_EVENT_END0(kToplevelCategory, kLooperDispatchMessage); +static void JNI_TraceEvent_EndToplevel(JNIEnv* env, + const JavaParamRef<jstring>& jtarget) { + std::string target = ConvertJavaStringToUTF8(env, jtarget); + TRACE_EVENT_COPY_END0(kToplevelCategory, target.c_str()); } static void JNI_TraceEvent_StartAsync(JNIEnv* env,
diff --git a/base/debug/stack_trace.cc b/base/debug/stack_trace.cc index fe90448..d8ca822 100644 --- a/base/debug/stack_trace.cc +++ b/base/debug/stack_trace.cc
@@ -239,6 +239,15 @@ return stream.str(); } +std::ostream& operator<<(std::ostream& os, const StackTrace& s) { +#if !defined(__UCLIBC__) & !defined(_AIX) + s.OutputToStream(&os); +#else + os << "StackTrace::OutputToStream not implemented."; +#endif + return os; +} + #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS) size_t TraceStackFramePointers(const void** out_trace,
diff --git a/base/debug/stack_trace.h b/base/debug/stack_trace.h index 087ef06..73a2f23c 100644 --- a/base/debug/stack_trace.h +++ b/base/debug/stack_trace.h
@@ -124,6 +124,9 @@ size_t count_; }; +// Forwards to StackTrace::OutputToStream(). +BASE_EXPORT std::ostream& operator<<(std::ostream& os, const StackTrace& s); + // Record a stack trace with up to |count| frames into |trace|. Returns the // number of frames read. BASE_EXPORT size_t CollectStackTrace(void** trace, size_t count);
diff --git a/base/message_loop/message_loop.cc b/base/message_loop/message_loop.cc index ec20869..fff922d3 100644 --- a/base/message_loop/message_loop.cc +++ b/base/message_loop/message_loop.cc
@@ -168,6 +168,12 @@ return WrapUnique(new MessageLoop(type, nullptr)); } +// static +std::unique_ptr<MessageLoop> MessageLoop::CreateUnbound( + std::unique_ptr<MessagePump> custom_pump) { + return WrapUnique(new MessageLoop(TYPE_CUSTOM, std::move(custom_pump))); +} + MessageLoop::MessageLoop(Type type, std::unique_ptr<MessagePump> custom_pump) : backend_(sequence_manager::internal::SequenceManagerImpl::CreateUnbound( sequence_manager::SequenceManager::Settings{.message_loop_type =
diff --git a/base/message_loop/message_loop.h b/base/message_loop/message_loop.h index 8143567c..46782b4 100644 --- a/base/message_loop/message_loop.h +++ b/base/message_loop/message_loop.h
@@ -24,6 +24,10 @@ namespace base { +namespace internal { +class MessageLoopTaskEnvironment; +} // namespace internal + class MessageLoopImpl; namespace sequence_manager { @@ -321,6 +325,7 @@ friend class MessageLoopTypedTest; friend class ScheduleWorkTest; friend class Thread; + friend class internal::MessageLoopTaskEnvironment; friend class sequence_manager::internal::SequenceManagerImpl; FRIEND_TEST_ALL_PREFIXES(MessageLoopTest, DeleteUnboundLoop); @@ -333,6 +338,8 @@ // Before BindToCurrentThread() is called, only Post*Task() functions can // be called on the message loop. static std::unique_ptr<MessageLoop> CreateUnbound(Type type); + static std::unique_ptr<MessageLoop> CreateUnbound( + std::unique_ptr<MessagePump> pump); scoped_refptr<sequence_manager::TaskQueue> CreateDefaultTaskQueue();
diff --git a/base/message_loop/message_pump_perftest.cc b/base/message_loop/message_pump_perftest.cc index 68c7fd9..b7cfb6e 100644 --- a/base/message_loop/message_pump_perftest.cc +++ b/base/message_loop/message_pump_perftest.cc
@@ -27,13 +27,6 @@ namespace base { -class ThreadForTest : public Thread { - public: - ThreadForTest() : Thread("test") {} - - using Thread::message_loop_base; -}; - class ScheduleWorkTest : public testing::Test { public: ScheduleWorkTest() : counter_(0) {} @@ -85,8 +78,16 @@ } else #endif { - target_.reset(new ThreadForTest()); - target_->StartWithOptions(Thread::Options(target_type, 0u)); + target_.reset(new Thread("test")); + + Thread::Options options(target_type, 0u); + + std::unique_ptr<MessageLoop> message_loop = + MessageLoop::CreateUnbound(target_type); + message_loop_ = message_loop.get(); + options.task_environment = + new internal::MessageLoopTaskEnvironment(std::move(message_loop)); + target_->StartWithOptions(options); // Without this, it's possible for the scheduling threads to start and run // before the target thread. In this case, the scheduling threads will @@ -179,11 +180,12 @@ if (java_thread_) return java_thread_->message_loop()->GetMessageLoopBase(); #endif - return target_->message_loop_base(); + return message_loop_->GetMessageLoopBase(); } private: - std::unique_ptr<ThreadForTest> target_; + std::unique_ptr<Thread> target_; + MessageLoop* message_loop_; #if defined(OS_ANDROID) std::unique_ptr<android::JavaHandlerThread> java_thread_; #endif
diff --git a/base/task/sequence_manager/sequence_manager.h b/base/task/sequence_manager/sequence_manager.h index 5d6cf5f7..1525911f 100644 --- a/base/task/sequence_manager/sequence_manager.h +++ b/base/task/sequence_manager/sequence_manager.h
@@ -163,7 +163,7 @@ // run. This method ignores any pending delayed tasks that might have become // eligible to run since the last task was executed. This is important because // if it did tests would become flaky depending on the exact timing of this - // call. + // call. This is moderately expensive. virtual bool IsIdleForTesting() = 0; // The total number of posted tasks that haven't executed yet.
diff --git a/base/task/sequence_manager/sequence_manager_impl.cc b/base/task/sequence_manager/sequence_manager_impl.cc index a7af2a5..a8475b9 100644 --- a/base/task/sequence_manager/sequence_manager_impl.cc +++ b/base/task/sequence_manager/sequence_manager_impl.cc
@@ -819,6 +819,13 @@ main_thread_only().queues_to_delete.clear(); } +void SequenceManagerImpl::RemoveAllCanceledTasksFromFrontOfWorkQueues() { + for (internal::TaskQueueImpl* queue : main_thread_only().active_queues) { + queue->delayed_work_queue()->RemoveAllCanceledTasksFromFront(); + queue->immediate_work_queue()->RemoveAllCanceledTasksFromFront(); + } +} + WeakPtr<SequenceManagerImpl> SequenceManagerImpl::GetWeakPtr() { return weak_factory_.GetWeakPtr(); } @@ -866,6 +873,7 @@ bool SequenceManagerImpl::HasTasks() { DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker); + RemoveAllCanceledTasksFromFrontOfWorkQueues(); for (TaskQueueImpl* task_queue : main_thread_only().active_queues) { if (task_queue->HasTasks()) @@ -901,10 +909,8 @@ #endif bool SequenceManagerImpl::IsIdleForTesting() { - // We don't use DelayTillNextTask here because the MessageLoop version which - // we're emulating does not take Now() into account. If it did tests would - // become flaky wrt delayed tasks that are just about to run. ReloadEmptyWorkQueues(); + RemoveAllCanceledTasksFromFrontOfWorkQueues(); return main_thread_only().selector.AllEnabledWorkQueuesAreEmpty(); }
diff --git a/base/task/sequence_manager/sequence_manager_impl.h b/base/task/sequence_manager/sequence_manager_impl.h index d892f83..5c9f83f 100644 --- a/base/task/sequence_manager/sequence_manager_impl.h +++ b/base/task/sequence_manager/sequence_manager_impl.h
@@ -348,6 +348,8 @@ // Deletes queues marked for deletion and empty queues marked for shutdown. void CleanUpQueues(); + void RemoveAllCanceledTasksFromFrontOfWorkQueues(); + bool ShouldRecordTaskTiming(const internal::TaskQueueImpl* task_queue); bool ShouldRecordCPUTimeForTask();
diff --git a/base/test/launcher/test_launcher.cc b/base/test/launcher/test_launcher.cc index a25bec59..dbac622 100644 --- a/base/test/launcher/test_launcher.cc +++ b/base/test/launcher/test_launcher.cc
@@ -1206,10 +1206,10 @@ continue; } - if (!launcher_delegate_->ShouldRunTest(test_id.test_case_name, - test_id.test_name)) { + bool will_run_test = launcher_delegate_->WillRunTest(test_id.test_case_name, + test_id.test_name); + if (!will_run_test) continue; - } // Count tests in the binary, before we apply filter and sharding. test_found_count_++; @@ -1245,14 +1245,33 @@ continue; } - if (Hash(test_name) % total_shards_ != static_cast<uint32_t>(shard_index_)) + // Tests with the name XYZ will cause tests with the name PRE_XYZ to run. We + // should bucket all of these tests together. + std::string test_name_to_bucket = test_name; + size_t index_of_first_period = test_name_to_bucket.find("."); + if (index_of_first_period == std::string::npos) + index_of_first_period = 0; + base::ReplaceSubstringsAfterOffset(&test_name_to_bucket, + index_of_first_period, "PRE_", ""); + + if (Hash(test_name_to_bucket) % total_shards_ != + static_cast<uint32_t>(shard_index_)) { continue; + } // Report test locations after applying all filters, so that we report test // locations only for those tests that were run as part of this shard. results_tracker_.AddTestLocation(test_name, test_id.file, test_id.line); - test_names.push_back(test_name); + bool should_run_test = launcher_delegate_->ShouldRunTest( + test_id.test_case_name, test_id.test_name); + if (should_run_test) { + // Only a subset of tests that are run require placeholders -- namely, + // those that will output results. + results_tracker_.AddTestPlaceholder(test_name); + + test_names.push_back(test_name); + } } if (shuffle_) {
diff --git a/base/test/launcher/test_launcher.h b/base/test/launcher/test_launcher.h index ef8cbeb..13aca16 100644 --- a/base/test/launcher/test_launcher.h +++ b/base/test/launcher/test_launcher.h
@@ -52,9 +52,14 @@ // must put the result in |output| and return true on success. virtual bool GetTests(std::vector<TestIdentifier>* output) = 0; - // Called before a test is considered for running. If it returns false, - // the test is not run. If it returns true, the test will be run provided - // it is part of the current shard. + // Called before a test is considered for running. This method must return + // true if either the delegate or the TestLauncher will run the test. + virtual bool WillRunTest(const std::string& test_case_name, + const std::string& test_name) = 0; + + // Called before a test is considered for running. This method must return + // true if the TestLauncher is expected to run the test, provided it is part + // of the current shard. virtual bool ShouldRunTest(const std::string& test_case_name, const std::string& test_name) = 0;
diff --git a/base/test/launcher/test_results_tracker.cc b/base/test/launcher/test_results_tracker.cc index a20859c..95024f8a 100644 --- a/base/test/launcher/test_results_tracker.cc +++ b/base/test/launcher/test_results_tracker.cc
@@ -233,6 +233,10 @@ test_locations_.insert(std::make_pair(test_name, CodeLocation(file, line))); } +void TestResultsTracker::AddTestPlaceholder(const std::string& test_name) { + test_placeholders_.push_back(test_name); +} + void TestResultsTracker::AddTestResult(const TestResult& result) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK_GE(iteration_, 0); @@ -259,10 +263,8 @@ void TestResultsTracker::GeneratePlaceholderIteration() { DCHECK(thread_checker_.CalledOnValidThread()); - // We use test_locations_ since that only includes tests that will be run in - // this shard. - for (auto& it : test_locations_) { - std::string test_name = TestNameWithoutDisabledPrefix(it.first); + for (auto& full_test_name : test_placeholders_) { + std::string test_name = TestNameWithoutDisabledPrefix(full_test_name); // Ignore disabled tests. if (disabled_tests_.find(test_name) != disabled_tests_.end()) @@ -274,9 +276,9 @@ // There shouldn't be any existing results when we generate placeholder // results. - DCHECK(per_iteration_data_[iteration_] - .results[test_name] - .test_results.empty()); + DCHECK( + per_iteration_data_[iteration_].results[test_name].test_results.empty()) + << test_name; per_iteration_data_[iteration_].results[test_name].test_results.push_back( test_result); }
diff --git a/base/test/launcher/test_results_tracker.h b/base/test/launcher/test_results_tracker.h index c17f1ad..341b128 100644 --- a/base/test/launcher/test_results_tracker.h +++ b/base/test/launcher/test_results_tracker.h
@@ -48,11 +48,16 @@ // Adds |test_name| to the set of disabled tests. void AddDisabledTest(const std::string& test_name); - // Adds location for the |test_name|. + // Adds location for the |test_name|. Locations are required for all tests run + // in a given shard, by both the TestLauncher and its delegate. void AddTestLocation(const std::string& test_name, const std::string& file, int line); + // Adds placeholder for the |test_name|. Placeholders are required for all + // tests that are expected to produce results in a given shard. + void AddTestPlaceholder(const std::string& test_name); + // Adds |result| to the stored test results. void AddTestResult(const TestResult& result); @@ -135,6 +140,9 @@ // CodeLocation for all tests that will be run as a part of this shard. std::map<std::string, CodeLocation> test_locations_; + // Name of tests that will run and produce results. + std::vector<std::string> test_placeholders_; + // Set of all disabled tests in the current executable. std::set<std::string> disabled_tests_;
diff --git a/base/test/launcher/unit_test_launcher.cc b/base/test/launcher/unit_test_launcher.cc index 7b2362f..787bc7c 100644 --- a/base/test/launcher/unit_test_launcher.cc +++ b/base/test/launcher/unit_test_launcher.cc
@@ -704,6 +704,14 @@ return platform_delegate_->GetTests(output); } +bool UnitTestLauncherDelegate::WillRunTest(const std::string& test_case_name, + const std::string& test_name) { + DCHECK(thread_checker_.CalledOnValidThread()); + + // There is no additional logic to disable specific tests. + return true; +} + bool UnitTestLauncherDelegate::ShouldRunTest(const std::string& test_case_name, const std::string& test_name) { DCHECK(thread_checker_.CalledOnValidThread());
diff --git a/base/test/launcher/unit_test_launcher.h b/base/test/launcher/unit_test_launcher.h index 0d1c21e0..13e9889 100644 --- a/base/test/launcher/unit_test_launcher.h +++ b/base/test/launcher/unit_test_launcher.h
@@ -109,6 +109,8 @@ private: // TestLauncherDelegate: bool GetTests(std::vector<TestIdentifier>* output) override; + bool WillRunTest(const std::string& test_case_name, + const std::string& test_name) override; bool ShouldRunTest(const std::string& test_case_name, const std::string& test_name) override; size_t RunTests(TestLauncher* test_launcher,
diff --git a/base/test/scoped_task_environment.cc b/base/test/scoped_task_environment.cc index 6231df2..d383bce 100644 --- a/base/test/scoped_task_environment.cc +++ b/base/test/scoped_task_environment.cc
@@ -92,7 +92,9 @@ : public sequence_manager::TimeDomain, public TickClock { public: - explicit MockTimeDomain(ScopedTaskEnvironment::NowSource now_source) { + MockTimeDomain(ScopedTaskEnvironment::NowSource now_source, + sequence_manager::SequenceManager* sequence_manager) + : sequence_manager_(sequence_manager) { DCHECK_EQ(nullptr, current_mock_time_domain_); current_mock_time_domain_ = this; if (now_source == ScopedTaskEnvironment::NowSource::MAIN_THREAD_MOCK_TIME) { @@ -116,6 +118,13 @@ using TimeDomain::NextScheduledRunTime; + Optional<TimeTicks> NextScheduledRunTime() const { + // The TimeDomain doesn't know about immediate tasks, check if we have any. + if (!sequence_manager_->IsIdleForTesting()) + return Now(); + return TimeDomain::NextScheduledRunTime(); + } + static std::unique_ptr<ScopedTaskEnvironment::MockTimeDomain> CreateAndRegister(ScopedTaskEnvironment::MainThreadType main_thread_type, ScopedTaskEnvironment::NowSource now_source, @@ -124,7 +133,8 @@ main_thread_type == MainThreadType::UI_MOCK_TIME || main_thread_type == MainThreadType::IO_MOCK_TIME) { auto mock_time_donain = - std::make_unique<ScopedTaskEnvironment::MockTimeDomain>(now_source); + std::make_unique<ScopedTaskEnvironment::MockTimeDomain>( + now_source, sequence_manager); sequence_manager->RegisterTimeDomain(mock_time_donain.get()); return mock_time_donain; } @@ -229,6 +239,8 @@ SEQUENCE_CHECKER(sequence_checker_); + sequence_manager::SequenceManager* const sequence_manager_; + std::unique_ptr<subtle::ScopedTimeClockOverrides> time_overrides_; // By default we want RunLoop.Run() to advance virtual time due to the API @@ -456,19 +468,13 @@ return task_runner_; } -bool ScopedTaskEnvironment::MainThreadHasPendingTask() const { +bool ScopedTaskEnvironment::MainThreadIsIdle() const { sequence_manager::internal::SequenceManagerImpl* sequence_manager_impl = static_cast<sequence_manager::internal::SequenceManagerImpl*>( sequence_manager_.get()); // ReclaimMemory sweeps canceled delayed tasks. sequence_manager_impl->ReclaimMemory(); - // Unfortunately this API means different things depending on whether mock - // time is used or not. If MockTime is used then tests want to know if there - // are any delayed or non-delayed tasks, otherwise only non-delayed tasks are - // considered. - if (mock_time_domain_) - return sequence_manager_impl->HasTasks(); - return !sequence_manager_impl->IsIdleForTesting(); + return sequence_manager_impl->IsIdleForTesting(); } void ScopedTaskEnvironment::RunUntilIdle() { @@ -606,6 +612,11 @@ return TimeDelta::Max(); } +bool ScopedTaskEnvironment::NextTaskIsDelayed() const { + TimeDelta delay = NextMainThreadPendingTaskDelay(); + return !delay.is_zero() && !delay.is_max(); +} + ScopedTaskEnvironment::TestTaskTracker::TestTaskTracker() : internal::TaskSchedulerImpl::TaskTrackerImpl("ScopedTaskEnvironment"), can_run_tasks_cv_(&lock_),
diff --git a/base/test/scoped_task_environment.h b/base/test/scoped_task_environment.h index dd5c3da5..5613c1e2 100644 --- a/base/test/scoped_task_environment.h +++ b/base/test/scoped_task_environment.h
@@ -156,8 +156,9 @@ // Returns a TaskRunner that schedules tasks on the main thread. scoped_refptr<base::SingleThreadTaskRunner> GetMainThreadTaskRunner(); - // Returns whether the main thread's TaskRunner has pending tasks. - bool MainThreadHasPendingTask() const; + // Returns whether the main thread's TaskRunner has pending tasks. This will + // always return true if called right after RunUntilIdle. + bool MainThreadIsIdle() const; // Runs tasks until both the (Thread|Sequenced)TaskRunnerHandle and the // TaskScheduler's non-delayed queues are empty. @@ -193,14 +194,20 @@ base::TimeTicks NowTicks() const; // Only valid for instances with a MOCK_TIME MainThreadType. - // Returns the number of pending tasks of the main thread's TaskRunner. + // Returns the number of pending tasks (delayed and non-delayed) of the main + // thread's TaskRunner. size_t GetPendingMainThreadTaskCount() const; // Only valid for instances with a MOCK_TIME MainThreadType. - // Returns the delay until the next delayed pending task of the main thread's - // TaskRunner. + // Returns the delay until the next pending task of the main thread's + // TaskRunner if there is one, otherwise it returns TimeDelta::Max(). TimeDelta NextMainThreadPendingTaskDelay() const; + // Only valid for instances with a MOCK_TIME MainThreadType. + // Returns true iff the next task is delayed. Returns false if the next task + // is immediate or if there is no next task. + bool NextTaskIsDelayed() const; + protected: explicit ScopedTaskEnvironment(ScopedTaskEnvironment&& other);
diff --git a/base/test/scoped_task_environment_unittest.cc b/base/test/scoped_task_environment_unittest.cc index 3f01cbf6..56a21b8 100644 --- a/base/test/scoped_task_environment_unittest.cc +++ b/base/test/scoped_task_environment_unittest.cc
@@ -562,34 +562,49 @@ ScopedTaskEnvironment scoped_task_environment( GetParam(), ScopedTaskEnvironment::ExecutionMode::QUEUED); - CancelableOnceClosure task1(Bind([]() {})); + CancelableOnceClosure task1(BindOnce([]() {})); ThreadTaskRunnerHandle::Get()->PostDelayedTask(FROM_HERE, task1.callback(), TimeDelta::FromSeconds(1)); - EXPECT_TRUE(scoped_task_environment.MainThreadHasPendingTask()); + EXPECT_TRUE(scoped_task_environment.MainThreadIsIdle()); EXPECT_EQ(1u, scoped_task_environment.GetPendingMainThreadTaskCount()); EXPECT_EQ(TimeDelta::FromSeconds(1), scoped_task_environment.NextMainThreadPendingTaskDelay()); + EXPECT_TRUE(scoped_task_environment.MainThreadIsIdle()); task1.Cancel(); - EXPECT_FALSE(scoped_task_environment.MainThreadHasPendingTask()); + EXPECT_TRUE(scoped_task_environment.MainThreadIsIdle()); + EXPECT_EQ(TimeDelta::Max(), + scoped_task_environment.NextMainThreadPendingTaskDelay()); - CancelableClosure task2(Bind([]() {})); + CancelableClosure task2(BindRepeating([]() {})); ThreadTaskRunnerHandle::Get()->PostDelayedTask(FROM_HERE, task2.callback(), TimeDelta::FromSeconds(1)); task2.Cancel(); EXPECT_EQ(0u, scoped_task_environment.GetPendingMainThreadTaskCount()); - CancelableClosure task3(Bind([]() {})); + CancelableClosure task3(BindRepeating([]() {})); ThreadTaskRunnerHandle::Get()->PostDelayedTask(FROM_HERE, task3.callback(), TimeDelta::FromSeconds(1)); task3.Cancel(); EXPECT_EQ(TimeDelta::Max(), scoped_task_environment.NextMainThreadPendingTaskDelay()); - CancelableClosure task4(Bind([]() {})); + CancelableClosure task4(BindRepeating([]() {})); ThreadTaskRunnerHandle::Get()->PostDelayedTask(FROM_HERE, task4.callback(), TimeDelta::FromSeconds(1)); task4.Cancel(); - EXPECT_FALSE(scoped_task_environment.MainThreadHasPendingTask()); + EXPECT_TRUE(scoped_task_environment.MainThreadIsIdle()); +} + +TEST_P(ScopedTaskEnvironmentMockedTime, CancelPendingImmediateTask) { + ScopedTaskEnvironment scoped_task_environment(GetParam()); + EXPECT_TRUE(scoped_task_environment.MainThreadIsIdle()); + + CancelableOnceClosure task1(BindOnce([]() {})); + ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, task1.callback()); + EXPECT_FALSE(scoped_task_environment.MainThreadIsIdle()); + + task1.Cancel(); + EXPECT_TRUE(scoped_task_environment.MainThreadIsIdle()); } TEST_P(ScopedTaskEnvironmentMockedTime, NoFastForwardToCancelledTask) { @@ -597,7 +612,7 @@ GetParam(), ScopedTaskEnvironment::ExecutionMode::QUEUED); TimeTicks start_time = scoped_task_environment.NowTicks(); - CancelableClosure task(Bind([]() {})); + CancelableClosure task(BindRepeating([]() {})); ThreadTaskRunnerHandle::Get()->PostDelayedTask(FROM_HERE, task.callback(), TimeDelta::FromSeconds(1)); EXPECT_EQ(TimeDelta::FromSeconds(1), @@ -619,6 +634,38 @@ EXPECT_EQ(TimeTicks::Now(), start_time + delay); } +TEST_P(ScopedTaskEnvironmentMockedTime, NextTaskIsDelayed) { + ScopedTaskEnvironment scoped_task_environment(GetParam()); + + EXPECT_FALSE(scoped_task_environment.NextTaskIsDelayed()); + CancelableClosure task(BindRepeating([]() {})); + ThreadTaskRunnerHandle::Get()->PostDelayedTask(FROM_HERE, task.callback(), + TimeDelta::FromSeconds(1)); + EXPECT_TRUE(scoped_task_environment.NextTaskIsDelayed()); + task.Cancel(); + EXPECT_FALSE(scoped_task_environment.NextTaskIsDelayed()); + + ThreadTaskRunnerHandle::Get()->PostDelayedTask(FROM_HERE, BindOnce([]() {}), + TimeDelta::FromSeconds(2)); + EXPECT_TRUE(scoped_task_environment.NextTaskIsDelayed()); + scoped_task_environment.FastForwardUntilNoTasksRemain(); + EXPECT_FALSE(scoped_task_environment.NextTaskIsDelayed()); + + ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, BindOnce([]() {})); + EXPECT_FALSE(scoped_task_environment.NextTaskIsDelayed()); +} + +TEST_P(ScopedTaskEnvironmentMockedTime, + NextMainThreadPendingTaskDelayWithImmediateTask) { + ScopedTaskEnvironment scoped_task_environment(GetParam()); + + EXPECT_EQ(TimeDelta::Max(), + scoped_task_environment.NextMainThreadPendingTaskDelay()); + ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, BindOnce([]() {})); + EXPECT_EQ(TimeDelta(), + scoped_task_environment.NextMainThreadPendingTaskDelay()); +} + INSTANTIATE_TEST_SUITE_P( MainThreadMockTime, ScopedTaskEnvironmentMockedTime,
diff --git a/base/threading/thread.cc b/base/threading/thread.cc index 105950d..96950c23 100644 --- a/base/threading/thread.cc +++ b/base/threading/thread.cc
@@ -9,6 +9,7 @@ #include "base/lazy_instance.h" #include "base/location.h" #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/synchronization/waitable_event.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" @@ -78,7 +79,7 @@ bool Thread::StartWithOptions(const Options& options) { DCHECK(owning_sequence_checker_.CalledOnValidSequence()); - DCHECK(!message_loop_base_); + DCHECK(!task_environment_); DCHECK(!IsRunning()); DCHECK(!stopping_) << "Starting a non-joinable thread a second time? That's " << "not allowed!"; @@ -93,19 +94,17 @@ SetThreadWasQuitProperly(false); - MessageLoop::Type type = options.message_loop_type; - if (!options.message_pump_factory.is_null()) - type = MessageLoop::TYPE_CUSTOM; - timer_slack_ = options.timer_slack; - std::unique_ptr<MessageLoop> message_loop_owned; - if (options.message_loop_base) { - message_loop_base_ = options.message_loop_base; + if (options.task_environment) { + DCHECK(!options.message_pump_factory); + task_environment_ = WrapUnique(options.task_environment); + } else if (options.message_pump_factory) { + task_environment_ = std::make_unique<internal::MessageLoopTaskEnvironment>( + MessageLoop::CreateUnbound(options.message_pump_factory.Run())); } else { - message_pump_factory_ = options.message_pump_factory; - message_loop_owned = MessageLoop::CreateUnbound(type); - message_loop_base_ = message_loop_owned->GetMessageLoopBase(); + task_environment_ = std::make_unique<internal::MessageLoopTaskEnvironment>( + MessageLoop::CreateUnbound(options.message_loop_type)); } start_event_.Reset(); @@ -123,18 +122,12 @@ options.stack_size, this, options.priority); if (!success) { DLOG(ERROR) << "failed to create thread"; - message_loop_base_ = nullptr; return false; } } joinable_ = options.joinable; - // The ownership of |message_loop_| is managed by the newly created thread - // within the ThreadMain. - ignore_result(message_loop_owned.release()); - - DCHECK(message_loop_base_); return true; } @@ -149,7 +142,7 @@ bool Thread::WaitUntilThreadStarted() const { DCHECK(owning_sequence_checker_.CalledOnValidSequence()); - if (!message_loop_base_) + if (!task_environment_) return false; // https://crbug.com/918039 base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait; @@ -159,7 +152,7 @@ void Thread::FlushForTesting() { DCHECK(owning_sequence_checker_.CalledOnValidSequence()); - if (!message_loop_base_) + if (!task_environment_) return; WaitableEvent done(WaitableEvent::ResetPolicy::AUTOMATIC, @@ -186,14 +179,14 @@ // Wait for the thread to exit. // - // TODO(darin): Unfortunately, we need to keep |message_loop_base_| around + // TODO(darin): Unfortunately, we need to keep |task_environment_| around // until the thread exits. Some consumers are abusing the API. Make them stop. PlatformThread::Join(thread_); thread_ = base::PlatformThreadHandle(); - // The thread should nullify |message_loop_base_| on exit (note: Join() adds + // The thread should release |task_environment_| on exit (note: Join() adds // an implicit memory barrier and no lock is thus required for this check). - DCHECK(!message_loop_base_); + DCHECK(!task_environment_); stopping_ = false; } @@ -203,20 +196,11 @@ // enable this check. // DCHECK(owning_sequence_checker_.CalledOnValidSequence()); - if (stopping_ || !message_loop_base_) + if (stopping_ || !task_environment_) return; stopping_ = true; - if (using_external_message_loop_) { - // Setting |stopping_| to true above should have been sufficient for this - // thread to be considered "stopped" per it having never set its |running_| - // bit by lack of its own ThreadMain. - DCHECK(!IsRunning()); - message_loop_base_ = nullptr; - return; - } - task_runner()->PostTask( FROM_HERE, base::BindOnce(&Thread::ThreadQuitHelper, Unretained(this))); } @@ -238,11 +222,11 @@ // enable this check. // DCHECK(owning_sequence_checker_.CalledOnValidSequence()); - // If the thread's already started (i.e. |message_loop_base_| is non-null) and + // If the thread's already started (i.e. |task_environment_| is non-null) and // not yet requested to stop (i.e. |stopping_| is false) we can just return // true. (Note that |stopping_| is touched only on the same sequence that // starts / started the new thread so we need no locking here.) - if (message_loop_base_ && !stopping_) + if (task_environment_ && !stopping_) return true; // Otherwise check the |running_| flag, which is set to true by the new thread // only while it is inside Run(). @@ -266,25 +250,12 @@ // static bool Thread::GetThreadWasQuitProperly() { bool quit_properly = true; -#ifndef NDEBUG +#if DCHECK_IS_ON() quit_properly = lazy_tls_bool.Pointer()->Get(); #endif return quit_properly; } -void Thread::SetMessageLoop(MessageLoop* message_loop) { - DCHECK(owning_sequence_checker_.CalledOnValidSequence()); - DCHECK(message_loop); - - // Setting |message_loop_base_| should suffice for this thread to be - // considered as "running", until Stop() is invoked. - DCHECK(!IsRunning()); - message_loop_base_ = message_loop->GetMessageLoopBase(); - DCHECK(IsRunning()); - - using_external_message_loop_ = true; -} - void Thread::ThreadMain() { // First, make GetThreadId() available to avoid deadlocks. It could be called // any place in the following thread initialization code. @@ -302,23 +273,18 @@ ANNOTATE_THREAD_NAME(name_.c_str()); // Tell the name to race detector. // Lazily initialize the |message_loop| so that it can run on this thread. - DCHECK(message_loop_base_); - std::unique_ptr<MessageLoopBase> message_loop_base(message_loop_base_); + DCHECK(task_environment_); // This binds MessageLoopCurrent and ThreadTaskRunnerHandle. - message_loop_base_->BindToCurrentThread( - message_pump_factory_ ? message_pump_factory_.Run() - : MessageLoop::CreateMessagePumpForType( - message_loop_base_->GetType())); + task_environment_->BindToCurrentThread(timer_slack_); DCHECK(MessageLoopCurrent::Get()); - DCHECK(ThreadTaskRunnerHandle::Get()); - message_loop_base_->SetTimerSlack(timer_slack_); + DCHECK(ThreadTaskRunnerHandle::IsSet()); #if defined(OS_POSIX) && !defined(OS_NACL) // Allow threads running a MessageLoopForIO to use FileDescriptorWatcher API. std::unique_ptr<FileDescriptorWatcher> file_descriptor_watcher; if (MessageLoopCurrentForIO::IsSet()) { file_descriptor_watcher.reset( - new FileDescriptorWatcher(message_loop_base_->GetTaskRunner())); + new FileDescriptorWatcher(task_environment_->GetDefaultTaskRunner())); } #endif @@ -357,16 +323,11 @@ com_initializer.reset(); #endif - if (message_loop_base->GetType() != MessageLoop::TYPE_CUSTOM) { - // Assert that RunLoop::QuitWhenIdle was called by ThreadQuitHelper. Don't - // check for custom message pumps, because their shutdown might not allow - // this. - DCHECK(GetThreadWasQuitProperly()); - } + DCHECK(GetThreadWasQuitProperly()); // We can't receive messages anymore. // (The message loop is destructed at the end of this block) - message_loop_base_ = nullptr; + task_environment_.reset(); run_loop_ = nullptr; } @@ -376,4 +337,24 @@ SetThreadWasQuitProperly(true); } +namespace internal { + +MessageLoopTaskEnvironment::MessageLoopTaskEnvironment( + std::unique_ptr<MessageLoop> message_loop) + : message_loop_(std::move(message_loop)) {} + +MessageLoopTaskEnvironment::~MessageLoopTaskEnvironment() {} + +scoped_refptr<SingleThreadTaskRunner> +MessageLoopTaskEnvironment::GetDefaultTaskRunner() { + return message_loop_->task_runner(); +} + +void MessageLoopTaskEnvironment::BindToCurrentThread(TimerSlack timer_slack) { + message_loop_->BindToCurrentThread(); + message_loop_->SetTimerSlack(timer_slack); +} + +} // namespace internal + } // namespace base
diff --git a/base/threading/thread.h b/base/threading/thread.h index 64a85aaec..94e260cc 100644 --- a/base/threading/thread.h +++ b/base/threading/thread.h
@@ -59,6 +59,18 @@ // Thread object (including ~Thread()). class BASE_EXPORT Thread : PlatformThread::Delegate { public: + class BASE_EXPORT TaskEnvironment { + public: + virtual ~TaskEnvironment() {} + + virtual scoped_refptr<SingleThreadTaskRunner> GetDefaultTaskRunner() = 0; + + // Binds a RunLoop::Delegate and TaskRunnerHandle to the thread. The + // underlying MessagePump will have its |timer_slack| set to the specified + // amount. + virtual void BindToCurrentThread(TimerSlack timer_slack) = 0; + }; + struct BASE_EXPORT Options { typedef Callback<std::unique_ptr<MessagePump>()> MessagePumpFactory; @@ -71,10 +83,10 @@ // This is ignored if message_pump_factory.is_null() is false. MessageLoop::Type message_loop_type = MessageLoop::TYPE_DEFAULT; - // An unbound MessageLoopBase that will be bound to the thread. Ownership - // of |message_loop_base| will be transferred to the thread. + // An unbound TaskEnvironment that will be bound to the thread. Ownership + // of |task_environment| will be transferred to the thread. // TODO(alexclarke): This should be a std::unique_ptr - MessageLoopBase* message_loop_base = nullptr; + TaskEnvironment* task_environment = nullptr; // Specifies timer slack for thread message loop. TimerSlack timer_slack = TIMER_SLACK_NONE; @@ -82,7 +94,8 @@ // Used to create the MessagePump for the MessageLoop. The callback is Run() // on the thread. If message_pump_factory.is_null(), then a MessagePump // appropriate for |message_loop_type| is created. Setting this forces the - // MessageLoop::Type to TYPE_CUSTOM. + // MessageLoop::Type to TYPE_CUSTOM. This is not compatible with a non-null + // |task_environment|. MessagePumpFactory message_pump_factory; // Specifies the maximum stack size that the thread is allowed to use. @@ -123,7 +136,7 @@ // init_com_with_mta(false) and then StartWithOptions() with any message loop // type other than TYPE_UI. void init_com_with_mta(bool use_mta) { - DCHECK(!message_loop_base_); + DCHECK(!task_environment_); com_status_ = use_mta ? MTA : STA; } #endif @@ -216,8 +229,9 @@ // Start(). DCHECK(owning_sequence_checker_.CalledOnValidSequence() || (id_event_.IsSignaled() && id_ == PlatformThread::CurrentId()) || - message_loop_base_); - return message_loop_base_ ? message_loop_base_->GetTaskRunner() : nullptr; + task_environment_); + return task_environment_ ? task_environment_->GetDefaultTaskRunner() + : nullptr; } // Returns the name of this thread (for display in debugger too). @@ -248,39 +262,10 @@ static void SetThreadWasQuitProperly(bool flag); static bool GetThreadWasQuitProperly(); - // Bind this Thread to an existing MessageLoop instead of starting a new one. - // TODO(gab): Remove this after ios/ has undergone the same surgery as - // BrowserThreadImpl (ref. - // https://chromium-review.googlesource.com/c/chromium/src/+/969104). - void SetMessageLoop(MessageLoop* message_loop); - - bool using_external_message_loop() const { - return using_external_message_loop_; - } - - // Returns the message loop for this thread. Use the MessageLoop's - // PostTask methods to execute code on the thread. This only returns - // non-null after a successful call to Start. After Stop has been called, - // this will return nullptr. - // - // NOTE: You must not call this MessageLoop's Quit method directly. Use - // the Thread's Stop method instead. - // - // In addition to this Thread's owning sequence, this can also safely be - // called from the underlying thread itself. - MessageLoopBase* message_loop_base() const { - // See the comment inside |task_runner()|. - DCHECK(owning_sequence_checker_.CalledOnValidSequence() || - (id_event_.IsSignaled() && id_ == PlatformThread::CurrentId()) || - message_loop_base_); - return message_loop_base_; - } - private: // Friends for message_loop() access: friend class MessageLoopTaskRunnerTest; friend class ScheduleWorkTest; - friend class MessageLoopTaskRunnerTest; #if defined(OS_WIN) enum ComStatus { @@ -323,21 +308,11 @@ // Protects |id_| which must only be read while it's signaled. mutable WaitableEvent id_event_; - // Supports creation of MessageLoopType::CUSTOM. - Options::MessagePumpFactory message_pump_factory_; - - // The thread's MessageLooBase and RunLoop. Valid only while the thread is + // The thread's TaskEnvironment and RunLoop are valid only while the thread is // alive. Set by the created thread. - MessageLoopBase* message_loop_base_ = nullptr; + std::unique_ptr<TaskEnvironment> task_environment_; RunLoop* run_loop_ = nullptr; - // True only if |message_loop_base_| was externally provided by | - // SetMessageLoop()| in which case this Thread has no underlying |thread_| and - // should merely drop |message_loop_base_| on Stop(). In that event, this - // remains true after Stop() was invoked so that subclasses can use this state - // to build their own cleanup logic as required. - bool using_external_message_loop_ = false; - // Stores Options::timer_slack_ until the sequence manager has been bound to // a thread. TimerSlack timer_slack_ = TIMER_SLACK_NONE; @@ -355,6 +330,25 @@ DISALLOW_COPY_AND_ASSIGN(Thread); }; +namespace internal { + +class BASE_EXPORT MessageLoopTaskEnvironment : public Thread::TaskEnvironment { + public: + explicit MessageLoopTaskEnvironment( + std::unique_ptr<MessageLoop> message_loop); + + ~MessageLoopTaskEnvironment() override; + + // Thread::TaskEnvironment: + scoped_refptr<SingleThreadTaskRunner> GetDefaultTaskRunner() override; + void BindToCurrentThread(TimerSlack timer_slack) override; + + private: + std::unique_ptr<MessageLoop> message_loop_; +}; + +} // namespace internal + } // namespace base #endif // BASE_THREADING_THREAD_H_
diff --git a/base/threading/thread_unittest.cc b/base/threading/thread_unittest.cc index 45e62da5..2f9132dc 100644 --- a/base/threading/thread_unittest.cc +++ b/base/threading/thread_unittest.cc
@@ -524,78 +524,49 @@ namespace { -// A Thread which uses a MessageLoop on the stack. It won't start a real -// underlying thread (instead its messages can be processed by a RunLoop on the -// stack). -class ExternalMessageLoopThread : public Thread { +class SequenceManagerTaskEnvironment : public Thread::TaskEnvironment { public: - ExternalMessageLoopThread() : Thread("ExternalMessageLoopThread") {} + SequenceManagerTaskEnvironment() + : sequence_manager_( + base::sequence_manager::CreateUnboundSequenceManager()), + task_queue_( + sequence_manager_ + ->CreateTaskQueueWithType<base::sequence_manager::TaskQueue>( + base::sequence_manager::TaskQueue::Spec("default_tq"))) { + sequence_manager_->SetDefaultTaskRunner(GetDefaultTaskRunner()); + } - ~ExternalMessageLoopThread() override { Stop(); } + ~SequenceManagerTaskEnvironment() override {} - void InstallMessageLoop() { SetMessageLoop(&external_message_loop_); } + scoped_refptr<base::SingleThreadTaskRunner> GetDefaultTaskRunner() override { + return task_queue_->task_runner(); + } - void VerifyUsingExternalMessageLoop( - bool expected_using_external_message_loop) { - EXPECT_EQ(expected_using_external_message_loop, - using_external_message_loop()); + void BindToCurrentThread(base::TimerSlack timer_slack) override { + sequence_manager_->BindToMessagePump( + base::MessageLoop::CreateMessagePumpForType( + base::MessageLoop::TYPE_DEFAULT)); + sequence_manager_->SetTimerSlack(timer_slack); } private: - base::MessageLoop external_message_loop_; + std::unique_ptr<base::sequence_manager::SequenceManager> sequence_manager_; + scoped_refptr<base::sequence_manager::TaskQueue> task_queue_; - DISALLOW_COPY_AND_ASSIGN(ExternalMessageLoopThread); + DISALLOW_COPY_AND_ASSIGN(SequenceManagerTaskEnvironment); }; } // namespace -TEST_F(ThreadTest, ExternalMessageLoop) { - ExternalMessageLoopThread a; - EXPECT_FALSE(a.task_runner()); - EXPECT_FALSE(a.IsRunning()); - a.VerifyUsingExternalMessageLoop(false); - - a.InstallMessageLoop(); - EXPECT_TRUE(a.task_runner()); - EXPECT_TRUE(a.IsRunning()); - a.VerifyUsingExternalMessageLoop(true); - - bool ran = false; - a.task_runner()->PostTask( - FROM_HERE, base::BindOnce([](bool* toggled) { *toggled = true; }, &ran)); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(ran); - - a.Stop(); - EXPECT_FALSE(a.task_runner()); - EXPECT_FALSE(a.IsRunning()); - a.VerifyUsingExternalMessageLoop(true); - - // Confirm that running any remaining tasks posted from Stop() goes smoothly - // (e.g. https://codereview.chromium.org/2135413003/#ps300001 crashed if - // StopSoon() posted Thread::ThreadQuitHelper() while |run_loop_| was null). - base::RunLoop().RunUntilIdle(); -} - -TEST_F(ThreadTest, ProvidedMessageLoopBase) { - Thread thread("ProvidedMessageLoopBase"); - std::unique_ptr<base::sequence_manager::internal::SequenceManagerImpl> - sequence_manager = - base::sequence_manager::internal::SequenceManagerImpl::CreateUnbound( - base::sequence_manager::SequenceManager::Settings()); - scoped_refptr<base::sequence_manager::TaskQueue> task_queue = - sequence_manager - ->CreateTaskQueueWithType<base::sequence_manager::TaskQueue>( - base::sequence_manager::TaskQueue::Spec("default_tq")); - sequence_manager->SetTaskRunner(task_queue->task_runner()); - +TEST_F(ThreadTest, ProvidedTaskEnvironment) { + Thread thread("TaskEnvironment"); base::Thread::Options options; - options.message_loop_base = sequence_manager.release(); + options.task_environment = new SequenceManagerTaskEnvironment(); thread.StartWithOptions(options); base::WaitableEvent event; - task_queue->task_runner()->PostTask( + options.task_environment->GetDefaultTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&base::WaitableEvent::Signal, base::Unretained(&event))); event.Wait();
diff --git a/base/trace_event/trace_log.cc b/base/trace_event/trace_log.cc index a5701c7..bbf71941 100644 --- a/base/trace_event/trace_log.cc +++ b/base/trace_event/trace_log.cc
@@ -1216,17 +1216,19 @@ args); #endif // OS_WIN - auto trace_event_override = - add_trace_event_override_.load(std::memory_order_relaxed); - if (trace_event_override) { - TraceEvent new_trace_event(thread_id, offset_event_timestamp, thread_now, - phase, category_group_enabled, name, scope, id, - bind_id, args, flags); + if (*category_group_enabled & RECORDING_MODE) { + auto trace_event_override = + add_trace_event_override_.load(std::memory_order_relaxed); + if (trace_event_override) { + TraceEvent new_trace_event(thread_id, offset_event_timestamp, thread_now, + phase, category_group_enabled, name, scope, id, + bind_id, args, flags); - trace_event_override( - &new_trace_event, - /*thread_will_flush=*/thread_local_event_buffer != nullptr, &handle); - return handle; + trace_event_override( + &new_trace_event, + /*thread_will_flush=*/thread_local_event_buffer != nullptr, &handle); + return handle; + } } std::string console_message;
diff --git a/base/trace_event/traced_value.cc b/base/trace_event/traced_value.cc index cf254fea..9fb4b91 100644 --- a/base/trace_event/traced_value.cc +++ b/base/trace_event/traced_value.cc
@@ -456,10 +456,11 @@ TracedValue::TracedValue() : TracedValue(0) {} -TracedValue::TracedValue(size_t capacity) { +TracedValue::TracedValue(size_t capacity, bool force_json) { DEBUG_PUSH_CONTAINER(kStackTypeDict); - writer_ = CreateWriter(capacity); + writer_ = force_json ? std::make_unique<PickleWriter>(capacity) + : CreateWriter(capacity); } TracedValue::~TracedValue() {
diff --git a/base/trace_event/traced_value.h b/base/trace_event/traced_value.h index aebd562d..38459de 100644 --- a/base/trace_event/traced_value.h +++ b/base/trace_event/traced_value.h
@@ -25,7 +25,7 @@ class BASE_EXPORT TracedValue : public ConvertableToTraceFormat { public: TracedValue(); - explicit TracedValue(size_t capacity); + explicit TracedValue(size_t capacity, bool force_json = false); ~TracedValue() override; void EndDictionary();
diff --git a/build/BUILD.gn b/build/BUILD.gn index 7ab955a..2e07ff0 100644 --- a/build/BUILD.gn +++ b/build/BUILD.gn
@@ -2,8 +2,43 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//build/config/compiler/compiler.gni") + source_set("buildflag_header_h") { sources = [ "buildflag.h", ] + + if (current_toolchain == default_toolchain && current_cpu == "arm64" && + is_android) { + # This dependency (and the associated action below) is designed to clear + # the ThinLTO cache if the state of |arm64_allow_outlining| changes when + # compiling for Android on arm64. + # + # See crbug.com/931297 for more information. + deps = [ + ":check_thinlto_cache($default_toolchain)", + ] + } +} + +if (current_toolchain == default_toolchain && current_cpu == "arm64" && + is_android) { + action("check_thinlto_cache") { + script = "//build/check_and_clear_thinlto_cache_on_outlining_change.py" + + outputs = [ + "$target_out_dir/arm64_outlining_status.stamp", + ] + + args = [ + "--cache-location", + "thinlto-cache", + "--stampfile", + rebase_path(outputs[0], root_build_dir), + ] + if (arm64_allow_outlining) { + args += [ "--allowing-outlining" ] + } + } }
diff --git a/build/android/stacktrace/README.md b/build/android/stacktrace/README.md index 01062be4..bfa537c5 100644 --- a/build/android/stacktrace/README.md +++ b/build/android/stacktrace/README.md
@@ -16,3 +16,8 @@ Extracts Breakpad microdumps from a log file and uses `stackwalker` to symbolize them. + + +# crashpad_stackwalker.py + +Fetches Crashpad dumps from a given device, walks and symbolizes the stacks.
diff --git a/build/android/stacktrace/crashpad_stackwalker.py b/build/android/stacktrace/crashpad_stackwalker.py new file mode 100755 index 0000000..7991985 --- /dev/null +++ b/build/android/stacktrace/crashpad_stackwalker.py
@@ -0,0 +1,157 @@ +#!/usr/bin/env python +# +# 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. + +# Fetches Crashpad dumps from a given device, walks and symbolizes the stacks. +# All the non-trivial operations are performed by generate_breakpad_symbols.py, +# minidump_dump and minidump_stackwalk. + +import argparse +import logging +import os +import posixpath +import re +import sys +import shutil +import subprocess +import tempfile + +sys.path.append( + os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))) +import devil_chromium +from devil.android import device_utils + + +def _CreateSymbolsDir(build_path, dynamic_library_names): + generator = os.path.join('components', 'crash', 'content', 'tools', + 'generate_breakpad_symbols.py') + syms_dir = os.path.join(build_path, 'crashpad_syms') + shutil.rmtree(syms_dir, ignore_errors=True) + os.mkdir(syms_dir) + for lib in dynamic_library_names: + unstripped_library_path = os.path.join(build_path, 'lib.unstripped', lib) + if not os.path.exists(unstripped_library_path): + continue + logging.info('Generating symbols for: %s', unstripped_library_path) + cmd = [ + generator, + '--symbols-dir', + syms_dir, + '--build-dir', + build_path, + '--binary', + unstripped_library_path, + ] + return_code = subprocess.call(cmd) + if return_code != 0: + logging.error('Could not extract symbols, command failed: %s', + ' '.join(cmd)) + return syms_dir + + +def _ChooseLatestCrashpadDump(device, crashpad_dump_path): + latest = None + latest_timestamp = 0 + for crashpad_file in device.ListDirectory(crashpad_dump_path): + if crashpad_file.endswith('.dmp'): + stat = device.StatPath(posixpath.join(crashpad_dump_path, crashpad_file)) + current_timestamp = stat['st_mtime'] + if current_timestamp > latest_timestamp: + latest_timestamp = current_timestamp + latest = crashpad_file + return latest + + +def _ExtractLibraryNamesFromDump(build_path, dump_path): + default_library_name = 'libmonochrome.so' + dumper_path = os.path.join(build_path, 'minidump_dump') + if not os.access(dumper_path, os.X_OK): + logging.warning('Cannot extract library name from dump, default to: %s', + default_library_name) + return [default_library_name] + p = subprocess.Popen([dumper_path, dump_path], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + stdout, stderr = p.communicate() + if p.returncode != 0: + # Dumper errors often do not affect stack walkability, just a warning. + logging.warning('Reading minidump failed with output:\n%s', stderr) + + library_names = [] + module_library_line_re = re.compile(r'[(]code_file[)]\s+= ' + r'"(?P<library_name>lib[^. ]+.so)"') + in_module = False + for line in stdout.splitlines(): + line = line.rstrip('\n') + if line == 'MDRawModule': + in_module = True + continue + if line == '': + in_module = False + continue + if in_module: + m = module_library_line_re.match(line) + if m: + library_names.append(m.group('library_name')) + if not library_names: + logging.warning( + 'Could not find any library name in the dump, ' + 'default to: %s', default_library_name) + return [default_library_name] + return library_names + + +def main(): + logging.basicConfig(level=logging.INFO) + parser = argparse.ArgumentParser( + description='Fetches Crashpad dumps from a given device, ' + 'walks and symbolizes the stacks.') + parser.add_argument('--device', required=True, help='Device serial number') + parser.add_argument( + '--adb-path', required=True, help='Path to the "adb" command') + parser.add_argument( + '--build-path', + required=True, + help='Build output directory, equivalent to CHROMIUM_OUTPUT_DIR') + parser.add_argument( + '--chrome-cache-path', + required=True, + help='Directory on the device where Chrome stores cached files,' + ' crashpad stores dumps in a subdirectory of it') + args = parser.parse_args() + devil_chromium.Initialize(adb_path=args.adb_path) + device = device_utils.DeviceUtils(args.device) + + device_crashpad_path = posixpath.join(args.chrome_cache_path, 'Crashpad', + 'pending') + crashpad_file = _ChooseLatestCrashpadDump(device, device_crashpad_path) + if not crashpad_file: + logging.error('Could not locate a crashpad dump') + return 1 + else: + dump_dir = tempfile.mkdtemp() + symbols_dir = None + try: + device.PullFile( + device_path=posixpath.join(device_crashpad_path, crashpad_file), + host_path=dump_dir) + dump_full_path = os.path.join(dump_dir, crashpad_file) + library_names = _ExtractLibraryNamesFromDump(args.build_path, + dump_full_path) + symbols_dir = _CreateSymbolsDir(args.build_path, library_names) + stackwalk_cmd = [ + os.path.join(args.build_path, 'minidump_stackwalk'), dump_full_path, + symbols_dir + ] + subprocess.call(stackwalk_cmd) + finally: + shutil.rmtree(dump_dir, ignore_errors=True) + if symbols_dir: + shutil.rmtree(symbols_dir, ignore_errors=True) + return 0 + + +if __name__ == '__main__': + sys.exit(main())
diff --git a/build/check_and_clear_thinlto_cache_on_outlining_change.py b/build/check_and_clear_thinlto_cache_on_outlining_change.py new file mode 100755 index 0000000..61a9559 --- /dev/null +++ b/build/check_and_clear_thinlto_cache_on_outlining_change.py
@@ -0,0 +1,48 @@ +#!/usr/bin/env python +# Copyright (c) 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. +""" +This script removes the ThinLTO cache if: + * the stampfile for this script does not exist. + * the state of |arm64_allow_outlining| in gn.args has changed. + +Added as part of crbug.com/931297 +""" + +import argparse +import os +import shutil +import sys + +def check_cache_exists_and_clear(cache_location): + if os.path.exists(cache_location): + shutil.rmtree(cache_location) + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--cache-location') + parser.add_argument('--stampfile') + parser.add_argument('--allowing-outlining', action='store_true') + args = parser.parse_args() + + if not os.path.exists(args.stampfile): + # If we've never checked before, clear the ThinLTO cache. + check_cache_exists_and_clear(args.cache_location) + + else: + # If we've checked before, check if outlining has been toggled and clear + # the ThinLTO cache if so. + with open(args.stampfile, 'r') as handle: + previously_allowed_outlining = handle.read().strip() == 'True' + + if previously_allowed_outlining != args.allowing_outlining: + check_cache_exists_and_clear(args.cache_location) + + with open(args.stampfile, 'w') as handle: + handle.write(str(args.allowing_outlining)) + + return 0 + +if __name__ == '__main__': + sys.exit(main())
diff --git a/build/chromeos/test_runner.py b/build/chromeos/test_runner.py index e2d990a..c596387 100755 --- a/build/chromeos/test_runner.py +++ b/build/chromeos/test_runner.py
@@ -230,6 +230,9 @@ self._on_vm_script = None + # If set, pass this value to the LLVM_PROFILE_FILE env var in the vm. + self._vm_profile_var = None + @property def suite_name(self): return self._test_exe @@ -258,6 +261,21 @@ '--results-dest-dir', result_dir, ] + # This environment variable is set for tests that have been instrumented + # for code coverage. Its incoming value is expected to be a location + # inside a subdirectory of result_dir above. This is converted to an + # absolute path that the vm is able to write to, and passed in the + # --results-src flag to cros_run_vm_test for copying out of the vm before + # its termination. + if os.environ.get('LLVM_PROFILE_FILE'): + _, vm_profile_file = os.path.split(os.environ['LLVM_PROFILE_FILE']) + self._vm_profile_var = '/tmp/profraw/%s' % vm_profile_file + + # This should make the vm test runner exfil the profiling data. + self._vm_test_cmd += [ + '--results-src', '/tmp/profraw' + ] + # Build the shell script that will be used on the VM to invoke the test. vm_test_script_contents = ['#!/bin/sh'] @@ -268,6 +286,11 @@ # duration of the test. vm_test_script_contents.append('export HOME=/tmp') + if self._vm_profile_var: + vm_test_script_contents += [ + 'export LLVM_PROFILE_FILE=%s'% self._vm_profile_var, + ] + if self._vpython_dir: vpython_spec_path = os.path.relpath( os.path.join(CHROMIUM_SRC_PATH, '.vpython'),
diff --git a/build/config/arm.gni b/build/config/arm.gni index 29434eb..c2128d7 100644 --- a/build/config/arm.gni +++ b/build/config/arm.gni
@@ -124,4 +124,10 @@ # arm64 supports only "hard". arm_float_abi = "hard" arm_use_neon = true + + declare_args() { + # Turn on to allow function outlining when compiling for arm64. + # See crbug.com/931297 for why this is turned off by default. + arm64_allow_outlining = false + } }
diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn index 63736c0e..4c0230ad 100644 --- a/build/config/compiler/BUILD.gn +++ b/build/config/compiler/BUILD.gn
@@ -1041,6 +1041,7 @@ config("compiler_codegen") { configs = [] cflags = [] + ldflags = [] if (is_nacl) { configs += [ "//build/config/nacl:compiler_codegen" ] @@ -1053,25 +1054,21 @@ "-momit-leaf-frame-pointer", ] } - } else if (current_cpu == "arm") { - if (is_android && !is_clang) { - # Clang doesn't support these flags. - cflags += [ - # The tree-sra optimization (scalar replacement for - # aggregates enabling subsequent optimizations) leads to - # invalid code generation when using the Android NDK's - # compiler (r5-r7). This can be verified using - # blink_unittests' WTF.Checked_int8_t test. - "-fno-tree-sra", - - # The following option is disabled to improve binary - # size and performance in gcc 4.9. - "-fno-caller-saves", - ] - } } } + if (current_cpu == "arm64" && !arm64_allow_outlining && is_android) { + # On arm64 disable outlining unless explicitly asked for with + # |arm64_allow_outlining|. + # See crbug.com/931297 for more information. + cflags += [ "-mno-outline" ] + + # This can be removed once https://bugs.llvm.org/show_bug.cgi?id=40348 + # has been resolved, and -mno-outline is obeyed by the linker during + # ThinLTO. + ldflags += [ "-Wl,-mllvm,-enable-machine-outliner=never" ] + } + asmflags = cflags } @@ -1178,10 +1175,6 @@ if (current_cpu == "arm" && arm_use_thumb && is_posix && !(is_mac || is_ios || is_nacl)) { cflags = [ "-mthumb" ] - if (is_android && !is_clang) { - # Clang doesn't support this option. - cflags += [ "-mthumb-interwork" ] - } } }
diff --git a/build/config/fuchsia/testing_sandbox_policy b/build/config/fuchsia/testing_sandbox_policy index 2907f4d9..33ec4010 100644 --- a/build/config/fuchsia/testing_sandbox_policy +++ b/build/config/fuchsia/testing_sandbox_policy
@@ -1,6 +1,6 @@ { "features": [ - "deprecated-global-persistent-storage", + "isolated-persistent-storage", "root-ssl-certificates", "system-temp", "vulkan" ],
diff --git a/build/fuchsia/target.py b/build/fuchsia/target.py index 26797f6..317186bf 100644 --- a/build/fuchsia/target.py +++ b/build/fuchsia/target.py
@@ -15,6 +15,20 @@ _ATTACH_RETRY_INTERVAL = 1 +class _MapRemoteDataPathForPackage: + """Callable object which remaps /data paths to their package-specific + locations.""" + + def __init__(self, package_name, package_version): + self.data_path = '/data/r/sys/fuchsia.com:{0}:{1}#meta:{0}.cmx'.format( + package_name, package_version) + + def __call__(self, path): + if path[:5] == '/data': + return self.data_path + path[5:] + return path + + class FuchsiaTargetException(Exception): def __init__(self, message): super(FuchsiaTargetException, self).__init__(message) @@ -92,44 +106,65 @@ return self.GetCommandRunner().RunCommand(command, silent, timeout_secs=timeout_secs) - def PutFile(self, source, dest, recursive=False): + def EnsurePackageDataDirectoryExists(self, package_name): + """Ensures that the specified package's isolated /data directory exists.""" + return self.RunCommand( + ['mkdir','-p',_MapRemoteDataPathForPackage(package_name, 0)('/data')]) + + def PutFile(self, source, dest, recursive=False, for_package=None): """Copies a file from the local filesystem to the target filesystem. source: The path of the file being copied. dest: The path on the remote filesystem which will be copied to. - recursive: If true, performs a recursive copy.""" + recursive: If true, performs a recursive copy. + for_package: If specified, /data in the |dest| is mapped to the package's + isolated /data location. + """ assert type(source) is str - self.PutFiles([source], dest, recursive) + self.PutFiles([source], dest, recursive, for_package) - def PutFiles(self, sources, dest, recursive=False): + def PutFiles(self, sources, dest, recursive=False, for_package=None): """Copies files from the local filesystem to the target filesystem. sources: List of local file paths to copy from, or a single path. dest: The path on the remote filesystem which will be copied to. - recursive: If true, performs a recursive copy.""" + recursive: If true, performs a recursive copy. + for_package: If specified, /data in the |dest| is mapped to the package's + isolated /data location. + """ assert type(sources) is tuple or type(sources) is list + if for_package: + self.EnsurePackageDataDirectoryExists(for_package) + dest = _MapRemoteDataPathForPackage(for_package, 0)(dest) logging.debug('copy local:%s => remote:%s' % (sources, dest)) self.GetCommandRunner().RunScp(sources, dest, remote_cmd.COPY_TO_TARGET, recursive) - def GetFile(self, source, dest): + def GetFile(self, source, dest, for_package=None): """Copies a file from the target filesystem to the local filesystem. source: The path of the file being copied. - dest: The path on the local filesystem which will be copied to.""" + dest: The path on the local filesystem which will be copied to. + for_package: If specified, /data in paths in |sources| is mapped to the + package's isolated /data location. + """ assert type(source) is str - self.GetFiles([source], dest) + self.GetFiles([source], dest, for_package) - def GetFiles(self, sources, dest): + def GetFiles(self, sources, dest, for_package=None): """Copies files from the target filesystem to the local filesystem. sources: List of remote file paths to copy. - dest: The path on the local filesystem which will be copied to.""" + dest: The path on the local filesystem which will be copied to. + for_package: If specified, /data in paths in |sources| is mapped to the + package's isolated /data location. + """ assert type(sources) is tuple or type(sources) is list self._AssertIsStarted() - host, port = self._GetEndpoint() + if for_package: + sources = map(_MapRemoteDataPathForPackage(for_package, 0), sources) logging.debug('copy remote:%s => local:%s' % (sources, dest)) return self.GetCommandRunner().RunScp(sources, dest, remote_cmd.COPY_FROM_TARGET)
diff --git a/build/fuchsia/test_runner.py b/build/fuchsia/test_runner.py index 32a0ea4a..ca0c176 100755 --- a/build/fuchsia/test_runner.py +++ b/build/fuchsia/test_runner.py
@@ -21,11 +21,9 @@ from run_package import RunPackage, RunPackageArgs DEFAULT_TEST_CONCURRENCY = 4 -# TODO(https://crbug.com/930182): Migrate off of deprecated global storage. + TEST_RESULT_PATH = '/data/test_summary.json' -TEST_RESULT_SCP_PATH = '/data/deprecated-global-persistent-storage/test_summary.json' TEST_FILTER_PATH = '/data/test_filter.txt' -TEST_FILTER_SCP_PATH = '/data/deprecated-global-persistent-storage/test_filter.txt' def main(): parser = argparse.ArgumentParser() @@ -106,7 +104,8 @@ target.Start() if args.test_launcher_filter_file: - target.PutFile(args.test_launcher_filter_file, TEST_FILTER_SCP_PATH) + target.PutFile(args.test_launcher_filter_file, TEST_FILTER_PATH, + for_package=args.package_name) child_args.append('--test-launcher-filter-file=' + TEST_FILTER_PATH) test_server = None @@ -122,7 +121,8 @@ test_server.Stop() if args.test_launcher_summary_output: - target.GetFile(TEST_RESULT_SCP_PATH, args.test_launcher_summary_output) + target.GetFile(TEST_RESULT_PATH, args.test_launcher_summary_output, + for_package=args.package_name) return returncode
diff --git a/cc/input/scroll_snap_data.cc b/cc/input/scroll_snap_data.cc index 3d4ad87..de776f3 100644 --- a/cc/input/scroll_snap_data.cc +++ b/cc/input/scroll_snap_data.cc
@@ -16,12 +16,6 @@ b.visible_range().Contains(gfx::RangeF(a.snap_offset())); } -bool SnappableOnAxis(const SnapAreaData& area, SearchAxis search_axis) { - return search_axis == SearchAxis::kX - ? area.scroll_snap_align.alignment_inline != SnapAlignment::kNone - : area.scroll_snap_align.alignment_block != SnapAlignment::kNone; -} - void SetOrUpdateResult(const SnapSearchResult& candidate, base::Optional<SnapSearchResult>* result) { if (result->has_value()) @@ -30,6 +24,30 @@ *result = candidate; } +const base::Optional<SnapSearchResult>& ClosestSearchResult( + const gfx::ScrollOffset reference_point, + SearchAxis axis, + const base::Optional<SnapSearchResult>& a, + const base::Optional<SnapSearchResult>& b) { + if (!a.has_value()) + return b; + if (!b.has_value()) + return a; + + float reference_position = + axis == SearchAxis::kX ? reference_point.x() : reference_point.y(); + float position_a = a.value().snap_offset(); + float position_b = b.value().snap_offset(); + DCHECK( + (reference_position <= position_a && reference_position <= position_b) || + (reference_position >= position_a && reference_position >= position_b)); + + float distance_a = std::abs(position_a - reference_position); + float distance_b = std::abs(position_b - reference_position); + + return distance_a < distance_b ? a : b; +} + } // namespace SnapSearchResult::SnapSearchResult(float offset, const gfx::RangeF& range) @@ -155,6 +173,26 @@ const SnapSearchResult& cros_axis_snap_result) const { base::Optional<SnapSearchResult> result = FindClosestValidAreaInternal(axis, strategy, cros_axis_snap_result); + + // For EndAndDirectionStrategy, if there is a snap area with snap-stop:always, + // and is between the starting position and the above result, we should choose + // the first snap area with snap-stop:always. + // This additional search is executed only if we found a result, while the + // additional search for the relaxed_strategy is executed only if we didn't + // find a result. So we put this search first so we can return early if we + // could find a result. + if (result.has_value() && strategy.ShouldRespectSnapStop()) { + std::unique_ptr<SnapSelectionStrategy> must_only_strategy = + SnapSelectionStrategy::CreateForDirection( + strategy.current_position(), + strategy.intended_position() - strategy.current_position(), + SnapStopAlwaysFilter::kRequire); + base::Optional<SnapSearchResult> must_only_result = + FindClosestValidAreaInternal(axis, *must_only_strategy, + cros_axis_snap_result, false); + result = ClosestSearchResult(strategy.current_position(), axis, result, + must_only_result); + } // Our current direction based strategies are too strict ignoring the other // directions even when we have no candidate in the given direction. This is // particularly problematic with mandatory snap points and for fling @@ -178,7 +216,8 @@ SnapContainerData::FindClosestValidAreaInternal( SearchAxis axis, const SnapSelectionStrategy& strategy, - const SnapSearchResult& cros_axis_snap_result) const { + const SnapSearchResult& cros_axis_snap_result, + bool should_consider_covering) const { // The search result from the snap area that's closest to the search origin. base::Optional<SnapSearchResult> closest; // The search result with the intended position if it makes a snap area cover @@ -202,11 +241,12 @@ float smallest_distance = axis == SearchAxis::kX ? proximity_range_.x() : proximity_range_.y(); for (const SnapAreaData& area : snap_area_list_) { - if (!SnappableOnAxis(area, axis)) + if (!strategy.IsValidSnapArea(axis, area)) continue; SnapSearchResult candidate = GetSnapSearchResult(axis, area); - if (IsSnapportCoveredOnAxis(axis, intended_position, area.rect)) { + if (should_consider_covering && + IsSnapportCoveredOnAxis(axis, intended_position, area.rect)) { // Since snap area will cover the snapport, we consider the intended // position as a valid snap position. SnapSearchResult covering_candidate = candidate; @@ -229,6 +269,9 @@ closest = candidate; } } + if (!should_consider_covering) + continue; + if (candidate.snap_offset() < intended_position && candidate.snap_offset() > prev) { prev = candidate.snap_offset(); @@ -238,6 +281,7 @@ next = candidate.snap_offset(); } } + // According to the spec [1], if the snap area is covering the snapport, the // scroll position is a valid snap position only if the distance between the // geometrically previous and subsequent snap positions in that axis is larger
diff --git a/cc/input/scroll_snap_data.h b/cc/input/scroll_snap_data.h index 3a8da21..9938c0b 100644 --- a/cc/input/scroll_snap_data.h +++ b/cc/input/scroll_snap_data.h
@@ -218,10 +218,13 @@ // or the original scroll offset if this is the first iteration of search. // Returns the candidate as SnapSearchResult that includes the area's // |snap_offset| and its visible range on the cross axis. + // When |should_consider_covering| is true, the current offset can be valid if + // it makes a snap area cover the snapport. base::Optional<SnapSearchResult> FindClosestValidAreaInternal( SearchAxis axis, const SnapSelectionStrategy& strategy, - const SnapSearchResult& cross_axis_snap_result) const; + const SnapSearchResult& cross_axis_snap_result, + bool should_consider_covering = true) const; // A wrapper of FindClosestValidAreaInternal(). If // FindClosestValidAreaInternal() doesn't return a valid result when the snap
diff --git a/cc/input/scroll_snap_data_unittest.cc b/cc/input/scroll_snap_data_unittest.cc index 3d95014..704b47e8 100644 --- a/cc/input/scroll_snap_data_unittest.cc +++ b/cc/input/scroll_snap_data_unittest.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "cc/input/scroll_snap_data.h" +#include <memory> #include "cc/input/snap_selection_strategy.h" #include "testing/gtest/include/gtest/gtest.h" @@ -307,4 +308,99 @@ container.FindSnapPosition(*end_direction_strategy, &snap_position)); } +TEST_F(ScrollSnapDataTest, ShouldNotPassScrollSnapStopAlwaysElement) { + SnapContainerData container( + ScrollSnapType(false, SnapAxis::kBoth, SnapStrictness::kMandatory), + gfx::RectF(0, 0, 200, 200), gfx::ScrollOffset(2000, 2000)); + SnapAreaData must_snap_1(ScrollSnapAlign(SnapAlignment::kStart), + gfx::RectF(200, 0, 100, 100), true); + SnapAreaData must_snap_2(ScrollSnapAlign(SnapAlignment::kStart), + gfx::RectF(400, 0, 100, 100), true); + SnapAreaData closer_to_target(ScrollSnapAlign(SnapAlignment::kStart), + gfx::RectF(600, 0, 100, 100), false); + container.AddSnapAreaData(must_snap_1); + container.AddSnapAreaData(must_snap_2); + container.AddSnapAreaData(closer_to_target); + gfx::ScrollOffset snap_position; + + std::unique_ptr<SnapSelectionStrategy> end_direction_strategy = + SnapSelectionStrategy::CreateForEndAndDirection( + gfx::ScrollOffset(0, 0), gfx::ScrollOffset(600, 0)); + EXPECT_TRUE( + container.FindSnapPosition(*end_direction_strategy, &snap_position)); + + // Even though closer_to_target and must_snap_2 are closer to the target + // position of the scroll, the must_snap_1 which is closer to the start + // shouldn't be passed. + EXPECT_EQ(200, snap_position.x()); + EXPECT_EQ(0, snap_position.y()); +} + +TEST_F(ScrollSnapDataTest, SnapStopAlwaysOverridesCoveringSnapArea) { + SnapContainerData container( + ScrollSnapType(false, SnapAxis::kBoth, SnapStrictness::kMandatory), + gfx::RectF(0, 0, 200, 200), gfx::ScrollOffset(600, 800)); + SnapAreaData stop_area(ScrollSnapAlign(SnapAlignment::kStart), + gfx::RectF(100, 0, 100, 100), true); + SnapAreaData covering_area(ScrollSnapAlign(SnapAlignment::kStart), + gfx::RectF(250, 0, 600, 600), false); + container.AddSnapAreaData(stop_area); + container.AddSnapAreaData(covering_area); + + gfx::ScrollOffset snap_position; + std::unique_ptr<SnapSelectionStrategy> strategy = + SnapSelectionStrategy::CreateForEndAndDirection( + gfx::ScrollOffset(0, 0), gfx::ScrollOffset(300, 0)); + // The fling is from (0, 0) to (300, 0), and the destination would make + // the |covering_area| perfectly cover the snapport. However, another area + // with snap-stop:always precedes this |covering_area| so we snap at + // (100, 100). + EXPECT_TRUE(container.FindSnapPosition(*strategy, &snap_position)); + EXPECT_EQ(100, snap_position.x()); + EXPECT_EQ(0, snap_position.y()); +} + +TEST_F(ScrollSnapDataTest, SnapStopAlwaysInReverseDirection) { + SnapContainerData container( + ScrollSnapType(false, SnapAxis::kBoth, SnapStrictness::kMandatory), + gfx::RectF(0, 0, 200, 300), gfx::ScrollOffset(600, 800)); + SnapAreaData stop_area(ScrollSnapAlign(SnapAlignment::kStart), + gfx::RectF(100, 0, 100, 100), true); + container.AddSnapAreaData(stop_area); + + gfx::ScrollOffset snap_position; + std::unique_ptr<SnapSelectionStrategy> strategy = + SnapSelectionStrategy::CreateForEndAndDirection( + gfx::ScrollOffset(150, 0), gfx::ScrollOffset(200, 0)); + // The fling is from (150, 0) to (350, 0), but the snap position is in the + // reverse direction at (100, 0). Since the container has mandatory for + // snapstrictness, we should go back to snap at (100, 0). + EXPECT_TRUE(container.FindSnapPosition(*strategy, &snap_position)); + EXPECT_EQ(100, snap_position.x()); + EXPECT_EQ(0, snap_position.y()); +} + +TEST_F(ScrollSnapDataTest, SnapStopAlwaysNotInterferingWithDirectionStrategy) { + SnapContainerData container( + ScrollSnapType(false, SnapAxis::kBoth, SnapStrictness::kMandatory), + gfx::RectF(0, 0, 200, 300), gfx::ScrollOffset(600, 800)); + SnapAreaData closer_area(ScrollSnapAlign(SnapAlignment::kStart), + gfx::RectF(100, 0, 1, 1), false); + SnapAreaData stop_area(ScrollSnapAlign(SnapAlignment::kStart), + gfx::RectF(120, 0, 1, 1), true); + container.AddSnapAreaData(closer_area); + container.AddSnapAreaData(stop_area); + + // The DirectionStrategy should always choose the first snap position + // regardless its scroll-snap-stop value. + gfx::ScrollOffset snap_position; + std::unique_ptr<SnapSelectionStrategy> direction_strategy = + SnapSelectionStrategy::CreateForDirection(gfx::ScrollOffset(90, 0), + gfx::ScrollOffset(50, 0)); + snap_position = gfx::ScrollOffset(); + EXPECT_TRUE(container.FindSnapPosition(*direction_strategy, &snap_position)); + EXPECT_EQ(100, snap_position.x()); + EXPECT_EQ(0, snap_position.y()); +} + } // namespace cc
diff --git a/cc/input/snap_selection_strategy.cc b/cc/input/snap_selection_strategy.cc index 8803cce..7ea5fe4 100644 --- a/cc/input/snap_selection_strategy.cc +++ b/cc/input/snap_selection_strategy.cc
@@ -17,8 +17,9 @@ std::unique_ptr<SnapSelectionStrategy> SnapSelectionStrategy::CreateForDirection(gfx::ScrollOffset current_position, - gfx::ScrollOffset step) { - return std::make_unique<DirectionStrategy>(current_position, step); + gfx::ScrollOffset step, + SnapStopAlwaysFilter filter) { + return std::make_unique<DirectionStrategy>(current_position, step, filter); } std::unique_ptr<SnapSelectionStrategy> @@ -33,6 +34,17 @@ return true; } +bool SnapSelectionStrategy::ShouldRespectSnapStop() const { + return false; +} + +bool SnapSelectionStrategy::IsValidSnapArea(SearchAxis axis, + const SnapAreaData& area) const { + return axis == SearchAxis::kX + ? area.scroll_snap_align.alignment_inline != SnapAlignment::kNone + : area.scroll_snap_align.alignment_block != SnapAlignment::kNone; +} + bool EndPositionStrategy::ShouldSnapOnX() const { return scrolled_x_; } @@ -95,6 +107,13 @@ } } +bool DirectionStrategy::IsValidSnapArea(SearchAxis axis, + const SnapAreaData& area) const { + return SnapSelectionStrategy::IsValidSnapArea(axis, area) && + (snap_stop_always_filter_ == SnapStopAlwaysFilter::kIgnore || + area.must_snap); +} + const base::Optional<SnapSearchResult>& DirectionStrategy::PickBestResult( const base::Optional<SnapSearchResult>& closest, const base::Optional<SnapSearchResult>& covering) const { @@ -150,6 +169,10 @@ } } +bool EndAndDirectionStrategy::ShouldRespectSnapStop() const { + return true; +} + const base::Optional<SnapSearchResult>& EndAndDirectionStrategy::PickBestResult( const base::Optional<SnapSearchResult>& closest, const base::Optional<SnapSearchResult>& covering) const {
diff --git a/cc/input/snap_selection_strategy.h b/cc/input/snap_selection_strategy.h index ef6b00ba..4b2fc2e 100644 --- a/cc/input/snap_selection_strategy.h +++ b/cc/input/snap_selection_strategy.h
@@ -11,6 +11,8 @@ namespace cc { +enum class SnapStopAlwaysFilter { kIgnore, kRequire }; + // This class represents an abstract strategy that decide which snap selection // should be considered valid. There are concrete implementations for three core // scrolling types: scroll with end position only, scroll with direction only, @@ -25,7 +27,8 @@ bool scrolled_y); static std::unique_ptr<SnapSelectionStrategy> CreateForDirection( gfx::ScrollOffset current_position, - gfx::ScrollOffset step); + gfx::ScrollOffset step, + SnapStopAlwaysFilter filter = SnapStopAlwaysFilter::kIgnore); static std::unique_ptr<SnapSelectionStrategy> CreateForEndAndDirection( gfx::ScrollOffset current_position, gfx::ScrollOffset displacement); @@ -47,9 +50,14 @@ // Returns true if the selection strategy considers the given snap offset // valid for the current axis. virtual bool IsValidSnapPosition(SearchAxis axis, float position) const = 0; + virtual bool IsValidSnapArea(SearchAxis axis, const SnapAreaData& data) const; virtual bool HasIntendedDirection() const; + // Returns true if a snap area with scroll-snap-stop:always should not be + // bypassed. + virtual bool ShouldRespectSnapStop() const; + // Returns the best result according to snap selection strategy. This method // is called at the end of selection process to make the final decision. // @@ -116,8 +124,11 @@ class DirectionStrategy : public SnapSelectionStrategy { public: DirectionStrategy(const gfx::ScrollOffset& current_position, - const gfx::ScrollOffset& step) - : SnapSelectionStrategy(current_position), step_(step) {} + const gfx::ScrollOffset& step, + SnapStopAlwaysFilter filter) + : SnapSelectionStrategy(current_position), + step_(step), + snap_stop_always_filter_(filter) {} ~DirectionStrategy() override = default; bool ShouldSnapOnX() const override; @@ -127,6 +138,8 @@ gfx::ScrollOffset base_position() const override; bool IsValidSnapPosition(SearchAxis axis, float position) const override; + bool IsValidSnapArea(SearchAxis axis, + const SnapAreaData& area) const override; const base::Optional<SnapSearchResult>& PickBestResult( const base::Optional<SnapSearchResult>& closest, @@ -135,6 +148,7 @@ private: // The default step for this DirectionStrategy. const gfx::ScrollOffset step_; + SnapStopAlwaysFilter snap_stop_always_filter_; }; // Examples for intended direction and end position scrolls include @@ -160,6 +174,8 @@ bool IsValidSnapPosition(SearchAxis axis, float position) const override; + bool ShouldRespectSnapStop() const override; + const base::Optional<SnapSearchResult>& PickBestResult( const base::Optional<SnapSearchResult>& closest, const base::Optional<SnapSearchResult>& covering) const override;
diff --git a/cc/paint/node_holder.cc b/cc/paint/node_holder.cc index c94f3de..ee5921d5 100644 --- a/cc/paint/node_holder.cc +++ b/cc/paint/node_holder.cc
@@ -6,31 +6,34 @@ namespace cc { -NodeHolder::NodeHolder() : tag(EMPTY) {} +NodeHolder::NodeHolder() : is_empty(true) {} NodeHolder::NodeHolder(scoped_refptr<TextHolder> holder) - : tag(TEXT_HOLDER), text_holder(holder) {} + : text_holder(holder), type(Type::kTextHolder), is_empty(false) {} -NodeHolder::NodeHolder(int id) : tag(ID), id(id) {} +NodeHolder::NodeHolder(int id) : id(id), type(Type::kID), is_empty(false) {} NodeHolder::NodeHolder(const NodeHolder& other) { text_holder = other.text_holder; id = other.id; - tag = other.tag; + type = other.type; + is_empty = other.is_empty; } NodeHolder::~NodeHolder() = default; bool operator==(const NodeHolder& l, const NodeHolder& r) { - if (l.tag != r.tag) + if (l.is_empty != r.is_empty) { return false; - switch (l.tag) { - case NodeHolder::TEXT_HOLDER: - return l.text_holder == r.text_holder; - case NodeHolder::ID: - return l.id == r.id; - case NodeHolder::EMPTY: - return true; + } else if (l.is_empty) { + return true; + } else { + switch (l.type) { + case NodeHolder::Type::kTextHolder: + return l.text_holder == r.text_holder; + case NodeHolder::Type::kID: + return l.id == r.id; + } } }
diff --git a/cc/paint/node_holder.h b/cc/paint/node_holder.h index eae2e58..48cffdd9 100644 --- a/cc/paint/node_holder.h +++ b/cc/paint/node_holder.h
@@ -21,12 +21,13 @@ NodeHolder(const NodeHolder& node_holder); virtual ~NodeHolder(); - bool IsEmpty() const { return tag == EMPTY; } + enum class Type : bool { kTextHolder = false, kID = true }; - enum { EMPTY, TEXT_HOLDER, ID } tag; - + // Only valid if is_empty is false. scoped_refptr<TextHolder> text_holder; int id; + Type type; + bool is_empty; }; bool operator==(const NodeHolder& l, const NodeHolder& r);
diff --git a/cc/tiles/tile_manager.cc b/cc/tiles/tile_manager.cc index 493f5b0..3bd8215 100644 --- a/cc/tiles/tile_manager.cc +++ b/cc/tiles/tile_manager.cc
@@ -44,12 +44,12 @@ DEFINE_SCOPED_UMA_HISTOGRAM_AREA_TIMER( ScopedSoftwareRasterTaskTimer, "Compositing.%s.RasterTask.RasterUs.Software", - "Compositing.%s.RasterTask.RasterPixelsPerMs2.Software"); + "Compositing.%s.RasterTask.RasterPixelsPerMs2.Software") DEFINE_SCOPED_UMA_HISTOGRAM_AREA_TIMER( ScopedGpuRasterTaskTimer, "Compositing.%s.RasterTask.RasterUs.Gpu", - "Compositing.%s.RasterTask.RasterPixelsPerMs2.Gpu"); + "Compositing.%s.RasterTask.RasterPixelsPerMs2.Gpu") class ScopedRasterTaskTimer { public:
diff --git a/cc/trees/layer_tree_host_impl.cc b/cc/trees/layer_tree_host_impl.cc index ace6be4..c86480bf4 100644 --- a/cc/trees/layer_tree_host_impl.cc +++ b/cc/trees/layer_tree_host_impl.cc
@@ -255,9 +255,9 @@ } // namespace DEFINE_SCOPED_UMA_HISTOGRAM_TIMER(PendingTreeDurationHistogramTimer, - "Scheduling.%s.PendingTreeDuration"); + "Scheduling.%s.PendingTreeDuration") DEFINE_SCOPED_UMA_HISTOGRAM_TIMER(PendingTreeRasterDurationHistogramTimer, - "Scheduling.%s.PendingTreeRasterDuration"); + "Scheduling.%s.PendingTreeRasterDuration") LayerTreeHostImpl::FrameData::FrameData() = default; LayerTreeHostImpl::FrameData::~FrameData() = default;
diff --git a/cc/trees/layer_tree_host_unittest_capture_content.cc b/cc/trees/layer_tree_host_unittest_capture_content.cc index 1a37ba2..75f69a3 100644 --- a/cc/trees/layer_tree_host_unittest_capture_content.cc +++ b/cc/trees/layer_tree_host_unittest_capture_content.cc
@@ -83,7 +83,7 @@ EXPECT_EQ(expected_result->size(), captured_content_.size()); size_t expected_left_result = expected_result->size(); for (auto c : captured_content_) { - EXPECT_EQ(c.tag, NodeHolder::TEXT_HOLDER); + EXPECT_EQ(c.type, NodeHolder::Type::kTextHolder); for (auto it = expected_result->begin(); it != expected_result->end(); ++it) { if (it->get() == c.text_holder.get()) {
diff --git a/chrome/VERSION b/chrome/VERSION index 2b605e18..dcd66d4 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=74 MINOR=0 -BUILD=3714 +BUILD=3715 PATCH=0
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index 4deebb47..9e3ea74 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -1068,12 +1068,17 @@ # # Variables: # is_monochrome: If true, generate Monochrome targets rather than Chrome. + # is_trichrome: Optionally generated Trichrome targets that use monochrome + # library targets but don't include webview resources. # is_bundle: If true, generate resources for bundles rather than APK. template("resource_packaging") { _is_monochrome = invoker.is_monochrome _is_bundle = invoker.is_bundle + _is_trichrome = defined(invoker.is_trichrome) && invoker.is_trichrome - if (_is_monochrome) { + if (_is_trichrome) { + _type = "trichrome_chrome" + } else if (_is_monochrome) { _type = "monochrome" } else { _type = "chrome" @@ -1086,11 +1091,16 @@ _variant = "${_type}_${_output_type}" if (enable_resource_whitelist_generation) { + if (_is_trichrome || _is_monochrome) { + _lib = "monochrome" + } else { + _lib = "chrome" + } _resource_whitelist_target = "${_variant}_resource_whitelist" _resource_whitelist_file = "$target_gen_dir/${_variant}_resource_whitelist.txt" - if (_is_monochrome) { + if (_is_trichrome || _is_monochrome) { _target_prefix = "" } else { _target_prefix = "lib" @@ -1100,8 +1110,8 @@ } else { _suffix = "" } - _lib_path = "/lib.unstripped/lib" + _type + _suffix + shlib_extension - _lib_target = _target_prefix + _type + _suffix + _lib_path = "/lib.unstripped/lib" + _lib + _suffix + shlib_extension + _lib_target = _target_prefix + _lib + _suffix generate_resource_whitelist(_resource_whitelist_target) { _fat_lib_toolchain = "" @@ -1260,6 +1270,11 @@ is_monochrome = true is_bundle = false } + resource_packaging("trichrome_chrome_apk_pak_assets") { + is_monochrome = false + is_trichrome = true + is_bundle = false + } resource_packaging("chrome_bundle_pak_assets") { is_monochrome = false is_bundle = true @@ -1546,12 +1561,12 @@ template("monochrome_public_apk_or_module_tmpl") { _android_manifest = "$target_gen_dir/manifest/${target_name}/AndroidManifest.xml" + _is_trichrome = + defined(invoker.use_trichrome_library) && invoker.use_trichrome_library # Generate the manifest here in the template, to avoid a growing collection # of manually-instantiated manifests. jinja_template("${target_name}__android_manifest") { - _is_trichrome = - defined(invoker.use_trichrome_library) && invoker.use_trichrome_library includes = [ "java/AndroidManifest.xml" ] variables = chrome_public_jinja_variables if (_is_trichrome) { @@ -1602,7 +1617,7 @@ android_manifest = _android_manifest android_manifest_dep = ":${target_name}__android_manifest" - if (public_android_sdk) { + if (public_android_sdk && !_is_trichrome) { # Resource whitelist used when generating R.java files and causes # only the webview subset of resources to be marked as non-final. shared_resources_whitelist_target = "//android_webview:system_webview_apk" @@ -1613,16 +1628,18 @@ } deps = [ - ":monochrome_java", - "//android_webview:platform_service_bridge_upstream_implementation_java", - "//base:base_java", "//chrome/android:app_hooks_java", "//chrome/android:chrome_java", ] + if (!_is_trichrome) { + deps += [ + ":monochrome_java", + "//android_webview:platform_service_bridge_upstream_implementation_java", + ] + } add_unwind_tables_in_apk = - _add_unwind_tables_in_chrome_public_apk && - (!defined(use_trichrome_library) || !use_trichrome_library) + _add_unwind_tables_in_chrome_public_apk && !_is_trichrome version_name = chrome_version_name }
diff --git a/chrome/android/chrome_public_apk_tmpl.gni b/chrome/android/chrome_public_apk_tmpl.gni index 24ce95d0..3a28317 100644 --- a/chrome/android/chrome_public_apk_tmpl.gni +++ b/chrome/android/chrome_public_apk_tmpl.gni
@@ -50,6 +50,10 @@ # final APK or bundle. # is_modern: If true, indicates this corresponds to a chrome_modern_XXX # target that can only run on Android L-M. +# is_monochrome: Indicates that this target contains chrome and webview +# packaged together and can only run on Android N+. +# is_trichrome: Indicates this target relies on a trichrome static library +# target and can only run on Android P+. # png_to_webp: Optional. If true, convert image resources to webp format. # requires Android K+, since these were not supported by Android properly # before 4.3.0. @@ -57,7 +61,6 @@ # directly from the APK (and stored zipaligned and uncompressed). This # requires either the Chromium linker, or Android M+. # version_name: Application version name (e.g. "Developer Build"). -# is_modern: Optional. true iff this is a chrome_modern derived build. # # Plus all other variables accepted by android_apk() or # android_app_bundle_module(), depending on the target type. @@ -69,6 +72,9 @@ invoker.target_type == "android_app_bundle_module" || invoker.target_type == "instrumentation_test_apk", "Invalid target_type definition, should be 'android_apk' or 'android_app_bundle_module'") + assert(!(defined(invoker.is_trichrome) && invoker.is_trichrome) || + !(defined(invoker.is_monochrome) && invoker.is_monochrome), + "Cannot be both trichrome and monochrome!") # Adds unwind table asset to the chrome apk for the given library target. This # is not part of generic apk assets target since it depends on the main shared @@ -96,10 +102,8 @@ assert(_is_modern || !_is_modern) # Mark as used. _is_monochrome = defined(invoker.is_monochrome) && invoker.is_monochrome - - _use_trichrome_library = - defined(invoker.use_trichrome_library) && invoker.use_trichrome_library - assert(_use_trichrome_library || !_use_trichrome_library) # Mark as used. + _is_trichrome = defined(invoker.is_trichrome) && invoker.is_trichrome + assert(_is_trichrome || !_is_trichrome) # Mark as used. if (defined(invoker.enable_multidex)) { _enable_multidex = invoker.enable_multidex @@ -145,7 +149,7 @@ } } - if (!_is_monochrome) { + if (!_is_monochrome && !_is_trichrome) { deps += [ "//third_party/crashpad/crashpad/handler:crashpad_handler_named_as_so", ] @@ -237,7 +241,7 @@ } if (!defined(version_code)) { - if (_use_trichrome_library) { + if (_is_trichrome) { version_code = trichrome_version_code } else if (_is_monochrome) { version_code = monochrome_version_code @@ -252,7 +256,12 @@ } # The equivalent of chrome_common_apk_or_module_tmpl for all builds of -# monochrome. +# monochrome and trichrome chrome. + +# Variables: +# use_trichrome_library: Specifies that this target depends on a trichrome +# static library target to provide certain shared library deps, and that +# this target should not package webview deps. template("monochrome_public_common_apk_or_module_tmpl") { if (defined(invoker.enable_multidex)) { _enable_multidex = invoker.enable_multidex @@ -260,11 +269,11 @@ _enable_multidex = is_java_debug || multidex_in_release } chrome_public_common_apk_or_module_tmpl(target_name) { - is_monochrome = true - use_trichrome_library = + is_trichrome = defined(invoker.use_trichrome_library) && invoker.use_trichrome_library + is_monochrome = !is_trichrome - if (!use_trichrome_library) { + if (!is_trichrome) { if (invoker.target_type == "android_app_bundle_module") { _suffix = bundle_library_suffix } else { @@ -303,10 +312,15 @@ } } - alternative_android_sdk_dep = webview_framework_dep - app_as_shared_lib = true + if (is_monochrome) { + alternative_android_sdk_dep = webview_framework_dep + app_as_shared_lib = true + min_sdk_version = 24 + } + if (is_trichrome) { + min_sdk_version = 28 + } use_chromium_linker = false - min_sdk_version = 24 # Resources config for blocklisting resource names from obfuscation resources_config_path = "//android_webview/aapt2.config" @@ -335,18 +349,28 @@ deps = [] } deps += [ - "//android_webview:monochrome_webview_assets", - "//android_webview/apk:webview_license_activity_java", - "//android_webview/glue", "//chrome/android:chrome_public_non_pak_assets", - "//chrome/android/monochrome:monochrome_license_provider_java", "//components/crash/android:handler_java", ] + _pak_prefix = "chrome" + if (is_monochrome) { + deps += [ + "//android_webview:monochrome_webview_assets", + "//android_webview/apk:webview_license_activity_java", + "//android_webview/glue", + "//chrome/android:monochrome_java", + "//chrome/android/monochrome:monochrome_license_provider_java", + ] + _pak_prefix = "monochrome" + } else if (is_trichrome) { + _pak_prefix = "trichrome_chrome" + } if (invoker.target_type == "android_app_bundle_module") { - deps += - [ "//chrome/android:monochrome_${bundle_pak_asset_type}_pak_assets" ] + deps += [ + "//chrome/android:${_pak_prefix}_${bundle_pak_asset_type}_pak_assets", + ] } else { - deps += [ "//chrome/android:monochrome_apk_pak_assets" ] + deps += [ "//chrome/android:${_pak_prefix}_apk_pak_assets" ] } if (_enable_multidex && invoker.target_type == "android_apk" && @@ -364,7 +388,9 @@ if (!defined(proguard_configs)) { proguard_configs = [] } - proguard_configs += [ "//android_webview/apk/java/proguard.flags" ] + if (is_monochrome) { + proguard_configs += [ "//android_webview/apk/java/proguard.flags" ] + } png_to_webp = true }
diff --git a/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedProcessScopeFactory.java b/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedProcessScopeFactory.java index 36de5e2..8df001b 100644 --- a/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedProcessScopeFactory.java +++ b/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedProcessScopeFactory.java
@@ -221,15 +221,16 @@ } private static void articlesEnabledPrefChange() { - // Should only be subscribed while it was enabled. A change should mean articles are now - // disabled. - assert !PrefServiceBridge.getInstance().getBoolean(Pref.NTP_ARTICLES_SECTION_ENABLED); - // There have been quite a few crashes/bugs that happen when code does not correctly handle - // the scenario where Feed suddenly becomes disabled and the above getters start returning - // nulls. Having this log a warning helps diagnose this pattern from the logcat. - Log.w(TAG, "Disabling Feed because of policy."); - sEverDisabledForPolicy = true; - destroy(); + // Cannot assume this is called because of an actual change. May be going from true to true. + if (!PrefServiceBridge.getInstance().getBoolean(Pref.NTP_ARTICLES_SECTION_ENABLED)) { + // There have been quite a few crashes/bugs that happen when code does not correctly + // handle the scenario where Feed suddenly becomes disabled and the above getters start + // returning nulls. Having this log a warning helps diagnose this pattern from the + // logcat. + Log.w(TAG, "Disabling Feed because of policy."); + sEverDisabledForPolicy = true; + destroy(); + } } /** Clears out all static state. */
diff --git a/chrome/android/java/res/layout/new_tab_page_incognito_md.xml b/chrome/android/java/res/layout/new_tab_page_incognito.xml similarity index 96% rename from chrome/android/java/res/layout/new_tab_page_incognito_md.xml rename to chrome/android/java/res/layout/new_tab_page_incognito.xml index 81016e92..b294fa1 100644 --- a/chrome/android/java/res/layout/new_tab_page_incognito_md.xml +++ b/chrome/android/java/res/layout/new_tab_page_incognito.xml
@@ -3,7 +3,7 @@ Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> -<org.chromium.chrome.browser.ntp.IncognitoNewTabPageViewMD +<org.chromium.chrome.browser.ntp.IncognitoNewTabPageView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/ntp_content" @@ -86,4 +86,4 @@ </org.chromium.chrome.browser.ntp.NewTabPageScrollView> -</org.chromium.chrome.browser.ntp.IncognitoNewTabPageViewMD> +</org.chromium.chrome.browser.ntp.IncognitoNewTabPageView>
diff --git a/chrome/android/java/res/values-v17/styles.xml b/chrome/android/java/res/values-v17/styles.xml index 14b0fba9..93ce100 100644 --- a/chrome/android/java/res/values-v17/styles.xml +++ b/chrome/android/java/res/values-v17/styles.xml
@@ -89,8 +89,9 @@ <!-- Activity themes --> <style name="Theme.Chromium.Activity" parent="Theme.Chromium.WithWindowAnimation" /> - <!-- TODO(huayinz): Can this be merged to Theme.Chromium.Activity.Fullscreen.Transparent? --> - <style name="Theme.Chromium.Activity.Translucent"> + <!-- This is distinct from Theme.Chromium.Activity.Fullscreen.Transparent, which makes the + payment handler window overlap the bottom nav bar. --> + <style name="Theme.Chromium.Activity.Translucent" parent="Base.Theme.Chromium"> <item name="android:windowBackground">@android:color/transparent</item> <item name="android:windowIsTranslucent">true</item> </style>
diff --git a/chrome/android/java/res/xml/sync_and_services_preferences.xml b/chrome/android/java/res/xml/sync_and_services_preferences.xml index 54b3ff3..5cbe09a 100644 --- a/chrome/android/java/res/xml/sync_and_services_preferences.xml +++ b/chrome/android/java/res/xml/sync_and_services_preferences.xml
@@ -15,7 +15,6 @@ <Preference android:key="sync_error_card" android:layout="@layout/account_management_account_row" - android:icon="@drawable/ic_sync_error_40dp" android:title="@string/sync_error_card_title"/> <org.chromium.chrome.browser.preferences.ChromeSwitchPreference android:key="sync_requested"
diff --git a/chrome/android/java/res_autofill_assistant/layout/autofill_assistant_details.xml b/chrome/android/java/res_autofill_assistant/layout/autofill_assistant_details.xml index 1a33be0..c5cddbd 100644 --- a/chrome/android/java/res_autofill_assistant/layout/autofill_assistant_details.xml +++ b/chrome/android/java/res_autofill_assistant/layout/autofill_assistant_details.xml
@@ -6,86 +6,96 @@ <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" - android:layout_height="64dp" + android:layout_height="wrap_content" android:background="@drawable/autofill_assistant_details_bg" android:padding="8dp" android:visibility="gone" - android:orientation="horizontal"> - <org.chromium.ui.widget.ChromeImageView - android:id="@+id/details_image" - android:layout_width="@dimen/autofill_assistant_details_image_size" - android:layout_height="@dimen/autofill_assistant_details_image_size" - android:layout_marginEnd="16dp" - android:scaleType="centerCrop"/> - + android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" - android:layout_height="match_parent" - android:orientation="vertical"> + android:layout_height="wrap_content" + android:orientation="horizontal"> - <Space - android:layout_width="match_parent" - android:layout_height="0dp" - android:layout_weight="1"/> + <org.chromium.ui.widget.ChromeImageView + android:id="@+id/details_image" + android:layout_width="@dimen/autofill_assistant_details_image_size" + android:layout_height="@dimen/autofill_assistant_details_image_size" + android:layout_marginEnd="8dp" + android:layout_gravity="top" + android:scaleType="centerCrop"/> - <!-- The top line of the details --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" - android:orientation="horizontal"> + android:orientation="vertical" + android:layout_gravity="top"> <TextView android:id="@+id/details_title" - android:layout_width="0dp" - android:layout_weight="1" - android:layout_height="match_parent" + android:layout_width="match_parent" + android:layout_height="wrap_content" android:textAppearance="@style/TextAppearance.DetailsTitle" android:singleLine="true" android:requiresFadingEdge="horizontal" android:fadingEdgeLength="20dp" - android:ellipsize="none"/> - <!-- Some space between the fading edge of the prev. element and the next element. --> - <Space android:layout_height="match_parent" - android:layout_width="10dp"/> - <!-- The total purchase price in the current locale, e.g. '$123.00' or '123.00 €'. --> + android:ellipsize="none" + android:layout_marginBottom="0dp"/> + <TextView - android:id="@+id/total_price" - android:layout_width="wrap_content" - android:layout_height="match_parent" - android:textAppearance="@style/TextAppearance.DetailsTitle" - android:singleLine="true"/> + android:id="@+id/details_line1" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.AssistantBlackCaption" + android:singleLine="true" + android:requiresFadingEdge="horizontal" + android:fadingEdgeLength="20dp" + android:ellipsize="none" + android:layout_marginTop="0dp" + android:layout_marginBottom="0dp"/> + + <TextView + android:id="@+id/details_line2" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.AssistantBlackCaption" + android:singleLine="true" + android:requiresFadingEdge="horizontal" + android:fadingEdgeLength="20dp" + android:ellipsize="none" + android:layout_marginTop="0dp" + android:layout_marginBottom="0dp"/> </LinearLayout> + </LinearLayout> - <Space - android:layout_width="match_parent" - android:layout_height="0dp" - android:layout_weight="1"/> + <LinearLayout android:id="@+id/details_price" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> - <!-- The bottom line of the details --> + <View style="@style/HorizontalDivider" + android:layout_width="match_parent" + android:layout_height="2dp" + android:layout_marginTop="8dp" + android:layout_marginBottom="8dp"/> + <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView - android:id="@+id/details_text" - android:layout_width="0dp" - android:layout_weight="1" - android:layout_height="match_parent" - android:textAppearance="@style/TextAppearance.AssistantBlackCaption" - android:singleLine="true" - android:requiresFadingEdge="horizontal" - android:fadingEdgeLength="20dp" - android:ellipsize="none"/> - <!-- Some space between the fading edge of the prev. element and the next element. --> - <Space android:layout_height="match_parent" - android:layout_width="10dp"/> - <TextView - android:id="@+id/purchase_summary" + android:id="@+id/details_total_price_label" android:layout_width="wrap_content" android:layout_height="match_parent" - android:textAppearance="@style/TextAppearance.AssistantBlackCaption" + android:textAppearance="@style/TextAppearance.DetailsTitle" + android:singleLine="true"/> + + <Space + android:layout_width="0dp" + android:layout_height="match_parent" + android:layout_weight="1"/> + + <TextView + android:id="@+id/details_total_price" + android:layout_width="wrap_content" + android:layout_height="match_parent" + android:textAppearance="@style/TextAppearance.DetailsTitle" android:singleLine="true"/> </LinearLayout> - - <Space - android:layout_width="match_parent" - android:layout_height="0dp" - android:layout_weight="1"/> </LinearLayout> </LinearLayout>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java index 9f7124b..d13a30c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java
@@ -1389,7 +1389,11 @@ manager.removeTouchExplorationStateChangeListener(mTouchExplorationStateChangeListener); } - mTabThemeColorProvider.destroy(); + if (mTabThemeColorProvider != null) { + mTabThemeColorProvider.destroy(); + mTabThemeColorProvider = null; + } + mActivityTabProvider.destroy(); mComponent = null;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java index 72f6513..78b0f320 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java
@@ -297,6 +297,7 @@ public static final String SPANNABLE_INLINE_AUTOCOMPLETE = "SpannableInlineAutocomplete"; public static final String SUBRESOURCE_FILTER = "SubresourceFilter"; public static final String QUERY_IN_OMNIBOX = "QueryInOmnibox"; + public static final String TAB_GROUP_ANDROID = "TabGroupsAndroid"; public static final String TAB_GRID_LAYOUT_ANDROID = "TabGridLayoutAndroid"; public static final String TAB_REPARENTING = "TabReparenting"; public static final String TAB_SWITCHER_ON_RETURN = "TabSwitcherOnReturn";
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/appmenu/AppMenuAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/appmenu/AppMenuAdapter.java index 21086e1f..662de26 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/appmenu/AppMenuAdapter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/appmenu/AppMenuAdapter.java
@@ -212,8 +212,10 @@ if (!TextUtils.isEmpty(itemState.summary)) { holder.summary.setText(itemState.summary); + holder.summary.setVisibility(View.VISIBLE); } else { holder.summary.setText(""); + holder.summary.setVisibility(View.GONE); } holder.image.setImageResource(itemState.icon);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetails.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetails.java index 86200f0..f403e76b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetails.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetails.java
@@ -23,38 +23,46 @@ private static final String RFC_3339_FORMAT_WITHOUT_TIMEZONE = "yyyy'-'MM'-'dd'T'HH':'mm':'ss"; private final String mTitle; - private final String mUrl; + private final String mImageUrl; @Nullable private final Date mDate; - private final String mDescription; - private final String mMid; + private final String mDescriptionLine1; + private final String mDescriptionLine2; /** Whether user approval is required (i.e., due to changes). */ private boolean mUserApprovalRequired; /** Whether the title should be highlighted. */ private boolean mHighlightTitle; - /** Whether the date should be highlighted. */ - private boolean mHighlightDate; + /** Whether the first description line should be highlighted. */ + private boolean mHighlightLine1; + /** Whether the second description line should be highlighted. */ + private boolean mHighlightLine2; /** Whether empty fields should have the animated placeholder background. */ private final boolean mShowPlaceholdersForEmptyFields; /** * The correctly formatted price for the client locale, including the currency. * Example: '$20.50' or '20.50 €'. */ - private final String mPrice; - // NOTE: When adding a new field, update the clearChangedFlags and toJSONObject methods. + private final String mTotalPrice; + /** An optional price label, such as 'Estimated Total incl. VAT'. */ + private final String mTotalPriceLabel; - public AssistantDetails(String title, String url, @Nullable Date date, String description, - String mId, @Nullable String price, boolean userApprovalRequired, - boolean highlightTitle, boolean highlightDate, boolean showPlaceholdersForEmptyFields) { + public AssistantDetails(String title, String imageUrl, String totalPriceLabel, + String totalPrice, @Nullable Date date, String descriptionLine1, + String descriptionLine2, boolean userApprovalRequired, boolean highlightTitle, + boolean highlightLine1, boolean highlightLine2, + boolean showPlaceholdersForEmptyFields) { + this.mTotalPriceLabel = totalPriceLabel; this.mTitle = title; - this.mUrl = url; + this.mImageUrl = imageUrl; + this.mTotalPrice = totalPrice; this.mDate = date; - this.mDescription = description; - this.mMid = mId; - this.mPrice = price; + this.mDescriptionLine1 = descriptionLine1; + this.mDescriptionLine2 = descriptionLine2; + this.mUserApprovalRequired = userApprovalRequired; this.mHighlightTitle = highlightTitle; - this.mHighlightDate = highlightDate; + this.mHighlightLine1 = highlightLine1; + this.mHighlightLine2 = highlightLine2; this.mShowPlaceholdersForEmptyFields = showPlaceholdersForEmptyFields; } @@ -62,8 +70,8 @@ return mTitle; } - String getUrl() { - return mUrl; + String getImageUrl() { + return mImageUrl; } @Nullable @@ -71,17 +79,20 @@ return mDate; } - String getDescription() { - return mDescription; + String getDescriptionLine1() { + return mDescriptionLine1; } - private String getMid() { - return mMid; + String getDescriptionLine2() { + return mDescriptionLine2; } - @Nullable - String getPrice() { - return mPrice; + String getTotalPrice() { + return mTotalPrice; + } + + String getTotalPriceLabel() { + return mTotalPriceLabel; } boolean getUserApprovalRequired() { @@ -92,8 +103,12 @@ return mHighlightTitle; } - boolean getHighlightDate() { - return mHighlightDate; + boolean getHighlightLine1() { + return mHighlightLine1; + } + + boolean getHighlightLine2() { + return mHighlightLine2; } boolean getShowPlaceholdersForEmptyFields() { @@ -104,10 +119,11 @@ * Create details with the given values. */ @CalledByNative - private static AssistantDetails create(String title, String url, String description, String mId, - String price, String datetime, long year, int month, int day, int hour, int minute, - int second, boolean userApprovalRequired, boolean highlightTitle, - boolean highlightDate) { + private static AssistantDetails create(String title, String imageUrl, String totalPriceLabel, + String totalPrice, String datetime, long year, int month, int day, int hour, int minute, + int second, String descriptionLine1, String descriptionLine2, + boolean userApprovalRequired, boolean highlightTitle, boolean highlightLine1, + boolean highlightLine2) { Date date = null; if (year > 0 && month > 0 && day > 0 && hour >= 0 && minute >= 0 && second >= 0) { Calendar calendar = Calendar.getInstance(); @@ -126,10 +142,8 @@ } } - if (price.length() == 0) price = null; - - return new AssistantDetails(title, url, date, description, mId, price, userApprovalRequired, - highlightTitle, highlightDate, - /* showPlaceholdersForEmptyFields= */ false); + return new AssistantDetails(title, imageUrl, totalPriceLabel, totalPrice, date, + descriptionLine1, descriptionLine2, userApprovalRequired, highlightTitle, + highlightLine1, highlightLine2, /* showPlaceholdersForEmptyFields= */ false); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetailsViewBinder.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetailsViewBinder.java index 01d26a3..3e5c3f4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetailsViewBinder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetailsViewBinder.java
@@ -62,7 +62,10 @@ final GradientDrawable mDefaultImage; final ImageView mImageView; final TextView mTitleView; - final TextView mSubtextView; + final TextView mDescriptionLine1View; + final TextView mDescriptionLine2View; + final View mPriceView; + final TextView mTotalPriceLabelView; final TextView mTotalPriceView; public ViewHolder(Context context, View detailsView) { @@ -70,8 +73,11 @@ R.drawable.autofill_assistant_default_details); mImageView = detailsView.findViewById(R.id.details_image); mTitleView = detailsView.findViewById(R.id.details_title); - mSubtextView = detailsView.findViewById(R.id.details_text); - mTotalPriceView = detailsView.findViewById(R.id.total_price); + mDescriptionLine1View = detailsView.findViewById(R.id.details_line1); + mDescriptionLine2View = detailsView.findViewById(R.id.details_line2); + mPriceView = detailsView.findViewById(R.id.details_price); + mTotalPriceView = detailsView.findViewById(R.id.details_total_price); + mTotalPriceLabelView = detailsView.findViewById(R.id.details_total_price_label); } } @@ -111,10 +117,23 @@ } private void setDetails(AssistantDetails details, ViewHolder viewHolder) { - String detailsText = makeDetailsText(details); viewHolder.mTitleView.setText(details.getTitle()); - viewHolder.mSubtextView.setText(detailsText); - viewHolder.mTotalPriceView.setText(details.getPrice()); + if (!details.getDescriptionLine1().isEmpty()) { + viewHolder.mDescriptionLine1View.setText(details.getDescriptionLine1()); + } else { + String datetimeText = makeDatetimeText(details); + viewHolder.mDescriptionLine1View.setText(datetimeText); + } + viewHolder.mDescriptionLine2View.setText(details.getDescriptionLine2()); + viewHolder.mTotalPriceLabelView.setText(details.getTotalPriceLabel()); + viewHolder.mTotalPriceView.setText(details.getTotalPrice()); + + hideIfEmpty(viewHolder.mDescriptionLine1View); + hideIfEmpty(viewHolder.mDescriptionLine2View); + + // If no price provided, hide the price view (containing separator, price label, and price). + viewHolder.mPriceView.setVisibility( + details.getTotalPrice().isEmpty() ? View.GONE : View.VISIBLE); if (viewHolder.mImageView.getDrawable() == null) { // Set default image if no image was set before. @@ -124,9 +143,9 @@ setTextStyles(details, viewHolder); // Download image and then set it in the model. - if (!details.getUrl().isEmpty()) { + if (!details.getImageUrl().isEmpty()) { CachedImageFetcher.getInstance().fetchImage( - details.getUrl(), CACHED_IMAGE_FETCHER_UMA_CLIENT_NAME, image -> { + details.getImageUrl(), CACHED_IMAGE_FETCHER_UMA_CLIENT_NAME, image -> { if (image != null) { viewHolder.mImageView.setImageDrawable(getRoundedImage(image)); } @@ -134,69 +153,7 @@ } } - private void setTextStyles(AssistantDetails details, ViewHolder viewHolder) { - setTitleStyle(details, viewHolder); - setSubtextStyle(details, viewHolder); - } - - private void setTitleStyle(AssistantDetails details, ViewHolder viewHolder) { - boolean animateBackground = false; - TextView titleView = viewHolder.mTitleView; - - if (details.getUserApprovalRequired() && !details.getHighlightTitle()) { - // De-emphasize title if user needs to accept details but the title should not be - // highlighted. - titleView.setTextColor(ApiCompatibilityUtils.getColor( - mContext.getResources(), R.color.modern_grey_300)); - } else { - // Normal style: bold black text. - ApiCompatibilityUtils.setTextAppearance( - titleView, R.style.TextAppearance_BlackCaptionDefault); - titleView.setTypeface(titleView.getTypeface(), Typeface.BOLD); - - if (titleView.length() == 0 && details.getShowPlaceholdersForEmptyFields()) { - animateBackground = true; - } - } - - if (animateBackground) { - addViewToAnimation(titleView, viewHolder); - } else { - removeViewFromAnimation(titleView); - } - } - - private void setSubtextStyle(AssistantDetails details, ViewHolder viewHolder) { - boolean animateBackground = false; - TextView subtextView = viewHolder.mSubtextView; - - if (details.getUserApprovalRequired()) { - if (details.getHighlightDate()) { - // Emphasized style. - subtextView.setTypeface(subtextView.getTypeface(), Typeface.BOLD_ITALIC); - } else { - // De-emphasized style. - subtextView.setTextColor(ApiCompatibilityUtils.getColor( - mContext.getResources(), R.color.modern_grey_300)); - } - } else { - // Normal style. - ApiCompatibilityUtils.setTextAppearance( - subtextView, R.style.TextAppearance_BlackCaption); - - if (subtextView.length() == 0 && details.getShowPlaceholdersForEmptyFields()) { - animateBackground = true; - } - } - - if (animateBackground) { - addViewToAnimation(subtextView, viewHolder); - } else { - removeViewFromAnimation(subtextView); - } - } - - private String makeDetailsText(AssistantDetails details) { + private String makeDatetimeText(AssistantDetails details) { List<String> parts = new ArrayList<>(); Date date = details.getDate(); if (date != null) { @@ -204,11 +161,6 @@ parts.add(formatDetailsDate(date)); } - String description = details.getDescription(); - if (description != null && !description.isEmpty()) { - parts.add(description); - } - // TODO(crbug.com/806868): Use a view instead of this dot text. return TextUtils.join(" • ", parts); } @@ -231,6 +183,63 @@ return new SimpleDateFormat(DETAILS_DATE_FORMAT, getLocale()).format(date); } + private void hideIfEmpty(TextView view) { + view.setVisibility(view.length() == 0 ? View.GONE : View.VISIBLE); + } + + private void setTextStyles(AssistantDetails details, ViewHolder viewHolder) { + setTitleStyle(details.getUserApprovalRequired(), details.getHighlightTitle(), viewHolder); + setSubtextStyle(viewHolder.mDescriptionLine1View, details.getUserApprovalRequired(), + details.getHighlightLine1(), viewHolder); + setSubtextStyle(viewHolder.mDescriptionLine2View, details.getUserApprovalRequired(), + details.getHighlightLine2(), viewHolder); + + animateIfEmpty( + viewHolder.mTitleView, details.getShowPlaceholdersForEmptyFields(), viewHolder); + animateIfEmpty(viewHolder.mDescriptionLine1View, + details.getShowPlaceholdersForEmptyFields(), viewHolder); + animateIfEmpty(viewHolder.mDescriptionLine2View, + details.getShowPlaceholdersForEmptyFields(), viewHolder); + } + + private void animateIfEmpty(TextView view, boolean animate, ViewHolder viewHolder) { + if (animate && view.length() == 0) { + addViewToAnimation(view, viewHolder); + } else { + removeViewFromAnimation(view); + } + } + + private void setTitleStyle(boolean approvalRequired, boolean highlight, ViewHolder viewHolder) { + TextView titleView = viewHolder.mTitleView; + if (approvalRequired && !highlight) { + // De-emphasize title if user needs to accept details but the title should not be + // highlighted. + titleView.setTextColor(ApiCompatibilityUtils.getColor( + mContext.getResources(), R.color.modern_grey_300)); + } else { + // Normal style: bold black text. + ApiCompatibilityUtils.setTextAppearance( + titleView, R.style.TextAppearance_BlackCaptionDefault); + titleView.setTypeface(titleView.getTypeface(), Typeface.BOLD); + } + } + + private void setSubtextStyle( + TextView view, boolean approvalRequired, boolean highlight, ViewHolder viewHolder) { + // Emphasized style. + if (approvalRequired && highlight) { + view.setTypeface(view.getTypeface(), Typeface.BOLD_ITALIC); + } else if (approvalRequired && !highlight) { + // De-emphasized style. + view.setTextColor(ApiCompatibilityUtils.getColor( + mContext.getResources(), R.color.modern_grey_300)); + } else { + // getUserApprovalRequired == false, normal style. + ApiCompatibilityUtils.setTextAppearance(view, R.style.TextAppearance_BlackCaption); + } + } + private Drawable getRoundedImage(Bitmap bitmap) { RoundedBitmapDrawable roundedBitmap = RoundedBitmapDrawableFactory.create(mContext.getResources(), @@ -254,7 +263,8 @@ @Override public void onAnimationCancel(Animator animation) { viewHolder.mTitleView.setBackgroundColor(Color.WHITE); - viewHolder.mSubtextView.setBackgroundColor(Color.WHITE); + viewHolder.mDescriptionLine1View.setBackgroundColor(Color.WHITE); + viewHolder.mDescriptionLine2View.setBackgroundColor(Color.WHITE); viewHolder.mDefaultImage.setColor(mPulseAnimationStartColor); } });
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPage.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPage.java index b4cc46c..35573eb 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPage.java
@@ -86,7 +86,7 @@ LayoutInflater inflater = LayoutInflater.from(activity); mIncognitoNewTabPageView = - (IncognitoNewTabPageView) inflater.inflate(getLayoutResource(), null); + (IncognitoNewTabPageView) inflater.inflate(R.layout.new_tab_page_incognito, null); mIncognitoNewTabPageView.initialize(mIncognitoNewTabPageManager); boolean useAlternateIncognitoStrings = @@ -97,10 +97,6 @@ : R.string.new_tab_otr_title); } - protected int getLayoutResource() { - return R.layout.new_tab_page_incognito_md; - } - /** * @return Whether the NTP has finished loaded. */
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPageView.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPageView.java index 8c15fe3..0e02ddb 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPageView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPageView.java
@@ -4,16 +4,31 @@ package org.chromium.chrome.browser.ntp; +import static org.chromium.chrome.browser.util.ViewUtils.dpToPx; + import android.content.Context; +import android.content.res.Configuration; import android.graphics.Canvas; +import android.support.annotation.IdRes; +import android.support.annotation.StringRes; +import android.text.SpannableString; +import android.text.method.LinkMovementMethod; +import android.text.style.ForegroundColorSpan; import android.util.AttributeSet; +import android.view.Gravity; import android.view.View; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.gesturenav.HistoryNavigationLayout; import org.chromium.chrome.browser.util.ViewUtils; +import org.chromium.ui.text.NoUnderlineClickableSpan; +import org.chromium.ui.text.SpanApplier; +import org.chromium.ui.widget.ChromeBulletSpan; /** * The New Tab Page for use in the incognito profile. @@ -27,6 +42,20 @@ private int mSnapshotHeight; private int mSnapshotScrollY; + private int mWidthDp; + private int mHeightDp; + + private LinearLayout mContainer; + private TextView mHeader; + private TextView mSubtitle; + private LinearLayout mBulletpointsContainer; + private TextView mLearnMore; + private TextView[] mParagraphs; + + private static final int BULLETPOINTS_HORIZONTAL_SPACING_DP = 40; + private static final int CONTENT_WIDTH_DP = 600; + private static final int WIDE_LAYOUT_THRESHOLD_DP = 720; + /** * Manages the view interaction with the rest of the system. */ @@ -69,6 +98,22 @@ mManager.loadIncognitoLearnMore(); } }); + + mWidthDp = getContext().getResources().getConfiguration().screenWidthDp; + mHeightDp = getContext().getResources().getConfiguration().screenHeightDp; + + populateBulletpoints(R.id.new_tab_incognito_features, R.string.new_tab_otr_not_saved); + populateBulletpoints(R.id.new_tab_incognito_warning, R.string.new_tab_otr_visible); + + mContainer = findViewById(R.id.new_tab_incognito_container); + mHeader = findViewById(R.id.new_tab_incognito_title); + mSubtitle = findViewById(R.id.new_tab_incognito_subtitle); + mLearnMore = findViewById(R.id.learn_more); + mParagraphs = new TextView[] {mSubtitle, findViewById(R.id.new_tab_incognito_features), + findViewById(R.id.new_tab_incognito_warning), mLearnMore}; + mBulletpointsContainer = findViewById(R.id.new_tab_incognito_bulletpoints_container); + + adjustView(); } /** @@ -116,4 +161,191 @@ mFirstShow = false; } } + + @Override + public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + // View#onConfigurationChanged() doesn't get called when resizing this view in + // multi-window mode, so #onMeasure() is used instead. + Configuration config = getContext().getResources().getConfiguration(); + if (mWidthDp != config.screenWidthDp || mHeightDp != config.screenHeightDp) { + mWidthDp = config.screenWidthDp; + mHeightDp = config.screenHeightDp; + adjustView(); + } + + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + } + + private void adjustView() { + adjustIcon(); + adjustLayout(); + adjustLearnMore(); + } + + /** + * @param element Resource ID of the element to be populated with the bulletpoints. + * @param content String ID to serve as the text of |element|. Must contain an <em></em> span, + * which will be emphasized, and three <li> items, which will be converted to + * bulletpoints. + * Populates |element| with |content|. + */ + private void populateBulletpoints(@IdRes int element, @StringRes int content) { + TextView view = (TextView) findViewById(element); + String text = getContext().getResources().getString(content); + + // TODO(msramek): Unfortunately, our strings are missing the closing "</li>" tag, which + // is not a problem when they're used in the Desktop WebUI (omitting the tag is valid in + // HTML5), but it is a problem for SpanApplier. Update the strings and remove this regex. + // Note that modifying the strings is a non-trivial operation as they went through a special + // translation process. + text = text.replaceAll("<li>([^<]+)\n", "<li>$1</li>\n"); + + // Format the bulletpoints: + // - Disambiguate the <li></li> spans for SpanApplier. + // - Remove leading whitespace (caused by formatting in the .grdp file) + // - Remove the trailing newline after the last bulletpoint. + text = text.replaceFirst(" *<li>([^<]*)</li>", "<li1>$1</li1>"); + text = text.replaceFirst(" *<li>([^<]*)</li>", "<li2>$1</li2>"); + text = text.replaceFirst(" *<li>([^<]*)</li>\n", "<li3>$1</li3>"); + + // Remove the <ul></ul> tags which serve no purpose here, including the whitespace around + // them. + text = text.replaceAll(" *</?ul>\\n?", ""); + + view.setText(SpanApplier.applySpans(text, + new SpanApplier.SpanInfo("<em>", "</em>", + new ForegroundColorSpan(ApiCompatibilityUtils.getColor( + getContext().getResources(), R.color.incognito_emphasis))), + new SpanApplier.SpanInfo("<li1>", "</li1>", new ChromeBulletSpan(getContext())), + new SpanApplier.SpanInfo("<li2>", "</li2>", new ChromeBulletSpan(getContext())), + new SpanApplier.SpanInfo("<li3>", "</li3>", new ChromeBulletSpan(getContext())))); + } + + /** Adjusts the paddings, margins, and the orientation of bulletpoints. */ + private void adjustLayout() { + int paddingHorizontalDp; + int paddingVerticalDp; + + boolean bulletpointsArrangedHorizontally; + + if (mWidthDp <= WIDE_LAYOUT_THRESHOLD_DP) { + // Small padding. + paddingHorizontalDp = mWidthDp <= 240 ? 24 : 32; + paddingVerticalDp = 32; + + // Align left. + mContainer.setGravity(Gravity.START); + + // Decide the bulletpoints orientation. + bulletpointsArrangedHorizontally = false; + + // The subtitle is sized automatically, but not wider than CONTENT_WIDTH_DP. + mSubtitle.setLayoutParams( + new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, + LinearLayout.LayoutParams.WRAP_CONTENT)); + mSubtitle.setMaxWidth(dpToPx(getContext(), CONTENT_WIDTH_DP)); + + // The bulletpoints container takes the same width as subtitle. Since the width can + // not be directly measured at this stage, we must calculate it manually. + mBulletpointsContainer.setLayoutParams(new LinearLayout.LayoutParams( + dpToPx(getContext(), + Math.min(CONTENT_WIDTH_DP, mWidthDp - 2 * paddingHorizontalDp)), + LinearLayout.LayoutParams.WRAP_CONTENT)); + } else { + // Large padding. + paddingHorizontalDp = 0; // Should not be necessary on a screen this large. + paddingVerticalDp = mHeightDp <= 320 ? 16 : 72; + + // Align to the center. + mContainer.setGravity(Gravity.CENTER_HORIZONTAL); + + // Decide the bulletpoints orientation. + bulletpointsArrangedHorizontally = true; + + int contentWidthPx = dpToPx(getContext(), CONTENT_WIDTH_DP); + mSubtitle.setLayoutParams(new LinearLayout.LayoutParams( + contentWidthPx, LinearLayout.LayoutParams.WRAP_CONTENT)); + mBulletpointsContainer.setLayoutParams(new LinearLayout.LayoutParams( + contentWidthPx, LinearLayout.LayoutParams.WRAP_CONTENT)); + } + + // Apply the bulletpoints orientation. + if (bulletpointsArrangedHorizontally) { + mBulletpointsContainer.setOrientation(LinearLayout.HORIZONTAL); + } else { + mBulletpointsContainer.setOrientation(LinearLayout.VERTICAL); + } + + // Set up paddings and margins. + int paddingTop; + int paddingBottom; + paddingTop = paddingBottom = dpToPx(getContext(), paddingVerticalDp); + mContainer.setPadding(dpToPx(getContext(), paddingHorizontalDp), paddingTop, + dpToPx(getContext(), paddingHorizontalDp), paddingBottom); + + int spacingPx = + (int) Math.ceil(mParagraphs[0].getTextSize() * (mHeightDp <= 600 ? 1 : 1.5)); + + for (TextView paragraph : mParagraphs) { + // If bulletpoints are arranged horizontally, there should be space between them. + int rightMarginPx = (bulletpointsArrangedHorizontally + && paragraph == mBulletpointsContainer.getChildAt(0)) + ? dpToPx(getContext(), BULLETPOINTS_HORIZONTAL_SPACING_DP) + : 0; + + ((LinearLayout.LayoutParams) paragraph.getLayoutParams()) + .setMargins(0, spacingPx, rightMarginPx, 0); + paragraph.setLayoutParams(paragraph.getLayoutParams()); // Apply the new layout. + } + + ((LinearLayout.LayoutParams) mHeader.getLayoutParams()).setMargins(0, spacingPx, 0, 0); + mHeader.setLayoutParams(mHeader.getLayoutParams()); // Apply the new layout. + } + + /** Adjust the Incognito icon. */ + private void adjustIcon() { + // The icon resource is 120dp x 120dp (i.e. 120px x 120px at MDPI). This method always + // resizes the icon view to 120dp x 120dp or smaller, therefore image quality is not lost. + + int sizeDp; + if (mWidthDp <= WIDE_LAYOUT_THRESHOLD_DP) { + sizeDp = (mWidthDp <= 240 || mHeightDp <= 480) ? 48 : 72; + } else { + sizeDp = mHeightDp <= 480 ? 72 : 120; + } + + ImageView icon = (ImageView) findViewById(R.id.new_tab_incognito_icon); + icon.getLayoutParams().width = dpToPx(getContext(), sizeDp); + icon.getLayoutParams().height = dpToPx(getContext(), sizeDp); + } + + /** Adjust the "Learn More" link. */ + private void adjustLearnMore() { + final String subtitleText = + getContext().getResources().getString(R.string.new_tab_otr_subtitle); + boolean learnMoreInSubtitle = mWidthDp > WIDE_LAYOUT_THRESHOLD_DP; + + mLearnMore.setVisibility(learnMoreInSubtitle ? View.GONE : View.VISIBLE); + + if (!learnMoreInSubtitle) { + // Revert to the original text. + mSubtitle.setText(subtitleText); + mSubtitle.setMovementMethod(null); + return; + } + + // Concatenate the original text with a clickable "Learn more" link. + StringBuilder concatenatedText = new StringBuilder(); + concatenatedText.append(subtitleText); + concatenatedText.append(" "); + concatenatedText.append(getContext().getResources().getString(R.string.learn_more)); + SpannableString textWithLearnMoreLink = new SpannableString(concatenatedText.toString()); + + NoUnderlineClickableSpan span = new NoUnderlineClickableSpan( + R.color.modern_blue_300, (view) -> getManager().loadIncognitoLearnMore()); + textWithLearnMoreLink.setSpan( + span, subtitleText.length() + 1, textWithLearnMoreLink.length(), 0 /* flags */); + mSubtitle.setText(textWithLearnMoreLink); + mSubtitle.setMovementMethod(LinkMovementMethod.getInstance()); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPageViewMD.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPageViewMD.java deleted file mode 100644 index b486cd71..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPageViewMD.java +++ /dev/null
@@ -1,265 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.ntp; - -import static org.chromium.chrome.browser.util.ViewUtils.dpToPx; - -import android.content.Context; -import android.content.res.Configuration; -import android.support.annotation.IdRes; -import android.support.annotation.StringRes; -import android.text.SpannableString; -import android.text.method.LinkMovementMethod; -import android.text.style.ForegroundColorSpan; -import android.util.AttributeSet; -import android.view.Gravity; -import android.view.View; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; - -import org.chromium.base.ApiCompatibilityUtils; -import org.chromium.chrome.R; -import org.chromium.ui.text.NoUnderlineClickableSpan; -import org.chromium.ui.text.SpanApplier; -import org.chromium.ui.widget.ChromeBulletSpan; - -/** - * The Material Design New Tab Page for use in the Incognito profile. This is an extension - * of the IncognitoNewTabPageView class with improved text content and a more responsive design. - */ -public class IncognitoNewTabPageViewMD extends IncognitoNewTabPageView { - private final Context mContext; - - private int mWidthDp; - private int mHeightDp; - - private LinearLayout mContainer; - private TextView mHeader; - private TextView mSubtitle; - private LinearLayout mBulletpointsContainer; - private TextView mLearnMore; - private TextView[] mParagraphs; - - private static final int BULLETPOINTS_HORIZONTAL_SPACING_DP = 40; - private static final int CONTENT_WIDTH_DP = 600; - private static final int WIDE_LAYOUT_THRESHOLD_DP = 720; - - /** Default constructor needed to inflate via XML. */ - public IncognitoNewTabPageViewMD(Context context, AttributeSet attrs) { - super(context, attrs); - mContext = context; - } - - @Override - protected void onFinishInflate() { - super.onFinishInflate(); - - mWidthDp = mContext.getResources().getConfiguration().screenWidthDp; - mHeightDp = mContext.getResources().getConfiguration().screenHeightDp; - - populateBulletpoints(R.id.new_tab_incognito_features, R.string.new_tab_otr_not_saved); - populateBulletpoints(R.id.new_tab_incognito_warning, R.string.new_tab_otr_visible); - - mContainer = (LinearLayout) findViewById(R.id.new_tab_incognito_container); - mHeader = (TextView) findViewById(R.id.new_tab_incognito_title); - mSubtitle = (TextView) findViewById(R.id.new_tab_incognito_subtitle); - mLearnMore = (TextView) findViewById(R.id.learn_more); - mParagraphs = - new TextView[] {mSubtitle, (TextView) findViewById(R.id.new_tab_incognito_features), - (TextView) findViewById(R.id.new_tab_incognito_warning), mLearnMore}; - mBulletpointsContainer = - (LinearLayout) findViewById(R.id.new_tab_incognito_bulletpoints_container); - - adjustView(); - } - - private void adjustView() { - adjustIcon(); - adjustLayout(); - adjustLearnMore(); - } - - @Override - public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - // View#onConfigurationChanged() doesn't get called when resizing this view in - // multi-window mode, so #onMeasure() is used instead. - Configuration config = getContext().getResources().getConfiguration(); - if (mWidthDp != config.screenWidthDp || mHeightDp != config.screenHeightDp) { - mWidthDp = config.screenWidthDp; - mHeightDp = config.screenHeightDp; - adjustView(); - } - - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - } - - /** - * @param element Resource ID of the element to be populated with the bulletpoints. - * @param content String ID to serve as the text of |element|. Must contain an <em></em> span, - * which will be emphasized, and three <li> items, which will be converted to - * bulletpoints. - * Populates |element| with |content|. - */ - private void populateBulletpoints(@IdRes int element, @StringRes int content) { - TextView view = (TextView) findViewById(element); - String text = mContext.getResources().getString(content); - - // TODO(msramek): Unfortunately, our strings are missing the closing "</li>" tag, which - // is not a problem when they're used in the Desktop WebUI (omitting the tag is valid in - // HTML5), but it is a problem for SpanApplier. Update the strings and remove this regex. - // Note that modifying the strings is a non-trivial operation as they went through a special - // translation process. - text = text.replaceAll("<li>([^<]+)\n", "<li>$1</li>\n"); - - // Format the bulletpoints: - // - Disambiguate the <li></li> spans for SpanApplier. - // - Remove leading whitespace (caused by formatting in the .grdp file) - // - Remove the trailing newline after the last bulletpoint. - text = text.replaceFirst(" *<li>([^<]*)</li>", "<li1>$1</li1>"); - text = text.replaceFirst(" *<li>([^<]*)</li>", "<li2>$1</li2>"); - text = text.replaceFirst(" *<li>([^<]*)</li>\n", "<li3>$1</li3>"); - - // Remove the <ul></ul> tags which serve no purpose here, including the whitespace around - // them. - text = text.replaceAll(" *</?ul>\\n?", ""); - - view.setText(SpanApplier.applySpans(text, - new SpanApplier.SpanInfo("<em>", "</em>", - new ForegroundColorSpan(ApiCompatibilityUtils.getColor( - mContext.getResources(), R.color.incognito_emphasis))), - new SpanApplier.SpanInfo("<li1>", "</li1>", new ChromeBulletSpan(mContext)), - new SpanApplier.SpanInfo("<li2>", "</li2>", new ChromeBulletSpan(mContext)), - new SpanApplier.SpanInfo("<li3>", "</li3>", new ChromeBulletSpan(mContext)))); - } - - /** Adjusts the paddings, margins, and the orientation of bulletpoints. */ - private void adjustLayout() { - int paddingHorizontalDp; - int paddingVerticalDp; - - boolean bulletpointsArrangedHorizontally; - - if (mWidthDp <= WIDE_LAYOUT_THRESHOLD_DP) { - // Small padding. - paddingHorizontalDp = mWidthDp <= 240 ? 24 : 32; - paddingVerticalDp = 32; - - // Align left. - mContainer.setGravity(Gravity.START); - - // Decide the bulletpoints orientation. - bulletpointsArrangedHorizontally = false; - - // The subtitle is sized automatically, but not wider than CONTENT_WIDTH_DP. - mSubtitle.setLayoutParams( - new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, - LinearLayout.LayoutParams.WRAP_CONTENT)); - mSubtitle.setMaxWidth(dpToPx(mContext, CONTENT_WIDTH_DP)); - - // The bulletpoints container takes the same width as subtitle. Since the width can - // not be directly measured at this stage, we must calculate it manually. - mBulletpointsContainer.setLayoutParams(new LinearLayout.LayoutParams( - dpToPx(mContext, - Math.min(CONTENT_WIDTH_DP, mWidthDp - 2 * paddingHorizontalDp)), - LinearLayout.LayoutParams.WRAP_CONTENT)); - } else { - // Large padding. - paddingHorizontalDp = 0; // Should not be necessary on a screen this large. - paddingVerticalDp = mHeightDp <= 320 ? 16 : 72; - - // Align to the center. - mContainer.setGravity(Gravity.CENTER_HORIZONTAL); - - // Decide the bulletpoints orientation. - bulletpointsArrangedHorizontally = true; - - int contentWidthPx = dpToPx(mContext, CONTENT_WIDTH_DP); - mSubtitle.setLayoutParams(new LinearLayout.LayoutParams( - contentWidthPx, LinearLayout.LayoutParams.WRAP_CONTENT)); - mBulletpointsContainer.setLayoutParams(new LinearLayout.LayoutParams( - contentWidthPx, LinearLayout.LayoutParams.WRAP_CONTENT)); - } - - // Apply the bulletpoints orientation. - if (bulletpointsArrangedHorizontally) { - mBulletpointsContainer.setOrientation(LinearLayout.HORIZONTAL); - } else { - mBulletpointsContainer.setOrientation(LinearLayout.VERTICAL); - } - - // Set up paddings and margins. - int paddingTop; - int paddingBottom; - paddingTop = paddingBottom = dpToPx(mContext, paddingVerticalDp); - mContainer.setPadding(dpToPx(mContext, paddingHorizontalDp), paddingTop, - dpToPx(mContext, paddingHorizontalDp), paddingBottom); - - int spacingPx = - (int) Math.ceil(mParagraphs[0].getTextSize() * (mHeightDp <= 600 ? 1 : 1.5)); - - for (TextView paragraph : mParagraphs) { - // If bulletpoints are arranged horizontally, there should be space between them. - int rightMarginPx = (bulletpointsArrangedHorizontally - && paragraph == mBulletpointsContainer.getChildAt(0)) - ? dpToPx(mContext, BULLETPOINTS_HORIZONTAL_SPACING_DP) - : 0; - - ((LinearLayout.LayoutParams) paragraph.getLayoutParams()) - .setMargins(0, spacingPx, rightMarginPx, 0); - paragraph.setLayoutParams(paragraph.getLayoutParams()); // Apply the new layout. - } - - ((LinearLayout.LayoutParams) mHeader.getLayoutParams()).setMargins(0, spacingPx, 0, 0); - mHeader.setLayoutParams(mHeader.getLayoutParams()); // Apply the new layout. - } - - /** Adjust the Incognito icon. */ - private void adjustIcon() { - // The icon resource is 120dp x 120dp (i.e. 120px x 120px at MDPI). This method always - // resizes the icon view to 120dp x 120dp or smaller, therefore image quality is not lost. - - int sizeDp; - if (mWidthDp <= WIDE_LAYOUT_THRESHOLD_DP) { - sizeDp = (mWidthDp <= 240 || mHeightDp <= 480) ? 48 : 72; - } else { - sizeDp = mHeightDp <= 480 ? 72 : 120; - } - - ImageView icon = (ImageView) findViewById(R.id.new_tab_incognito_icon); - icon.getLayoutParams().width = dpToPx(mContext, sizeDp); - icon.getLayoutParams().height = dpToPx(mContext, sizeDp); - } - - /** Adjust the "Learn More" link. */ - private void adjustLearnMore() { - final String subtitleText = - mContext.getResources().getString(R.string.new_tab_otr_subtitle); - boolean learnMoreInSubtitle = mWidthDp > WIDE_LAYOUT_THRESHOLD_DP; - - mLearnMore.setVisibility(learnMoreInSubtitle ? View.GONE : View.VISIBLE); - - if (!learnMoreInSubtitle) { - // Revert to the original text. - mSubtitle.setText(subtitleText); - mSubtitle.setMovementMethod(null); - return; - } - - // Concatenate the original text with a clickable "Learn more" link. - StringBuilder concatenatedText = new StringBuilder(); - concatenatedText.append(subtitleText); - concatenatedText.append(" "); - concatenatedText.append(mContext.getResources().getString(R.string.learn_more)); - SpannableString textWithLearnMoreLink = new SpannableString(concatenatedText.toString()); - - NoUnderlineClickableSpan span = new NoUnderlineClickableSpan( - R.color.modern_blue_300, (view) -> getManager().loadIncognitoLearnMore()); - textWithLearnMoreLink.setSpan( - span, subtitleText.length() + 1, textWithLearnMoreLink.length(), 0 /* flags */); - mSubtitle.setText(textWithLearnMoreLink); - mSubtitle.setMovementMethod(LinkMovementMethod.getInstance()); - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/SyncAndServicesPreferences.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/SyncAndServicesPreferences.java index e78db5d..6201fb9 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/SyncAndServicesPreferences.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/SyncAndServicesPreferences.java
@@ -21,6 +21,7 @@ import android.support.annotation.IntDef; import android.support.annotation.Nullable; import android.support.v7.app.AlertDialog; +import android.support.v7.content.res.AppCompatResources; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; @@ -157,6 +158,8 @@ mSyncCategory = (PreferenceCategory) findPreference(PREF_SYNC_CATEGORY); mSyncErrorCard = findPreference(PREF_SYNC_ERROR_CARD); + mSyncErrorCard.setIcon( + AppCompatResources.getDrawable(getActivity(), R.drawable.ic_sync_error_40dp)); mSyncErrorCard.setOnPreferenceClickListener( SyncPreferenceUtils.toOnClickListener(this, this::onSyncErrorCardClicked)); mSyncRequested = (ChromeSwitchPreference) findPreference(PREF_SYNC_REQUESTED);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridge.java new file mode 100644 index 0000000..fc58acc --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridge.java
@@ -0,0 +1,132 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.send_tab_to_self; + +import android.support.annotation.Nullable; + +import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.JCaller; +import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; +import org.chromium.chrome.browser.profiles.Profile; + +import java.util.ArrayList; +import java.util.List; + +/** + * Bridge to interface with send_tab_to_self_android_bridge which interacts with the corresponding + * sync service. This is used by SendTabToSelfShareActivity when a user taps to share a tab. The + * bridge is created and destroyed within the same method call. + * + * <p>TODO(tgupta): Add a paragraph describing the expected lifecycle of this class I.e. who would + * own it, when is it destroyed, etc? + */ +@JNINamespace("send_tab_to_self") +public class SendTabToSelfAndroidBridge { + // TODO(tgupta): Add logic back in to track whether model is loaded. + private boolean mIsNativeSendTabToSelfModelLoaded; + private long mNativeSendTabToSelfAndroidBridge; + + /** + * Handler to fetch the share entries + * + * @param profile Profile instance corresponding to the active profile. + */ + public SendTabToSelfAndroidBridge(Profile profile) { + Natives jni = SendTabToSelfAndroidBridgeJni.get(); + mNativeSendTabToSelfAndroidBridge = jni.init(this, profile); + } + + /** Destroys this instance so no further calls can be executed. */ + public void destroy() { + if (mNativeSendTabToSelfAndroidBridge != 0) { + Natives jni = SendTabToSelfAndroidBridgeJni.get(); + jni.destroy(this, mNativeSendTabToSelfAndroidBridge); + mNativeSendTabToSelfAndroidBridge = 0; + mIsNativeSendTabToSelfModelLoaded = false; + } + } + + /** @returns All GUIDs for all SendTabToSelf entries */ + public List<String> getAllGuids() { + // TODO(tgupta): Add this assertion back in once the code to load is in place. + // assert mIsNativeSendTabToSelfModelLoaded; + List<String> toPopulate = new ArrayList<String>(); + Natives jni = SendTabToSelfAndroidBridgeJni.get(); + jni.getAllGuids(this, mNativeSendTabToSelfAndroidBridge, toPopulate); + return toPopulate; + } + + /** + * Called by the native code in order to populate the list. + * + * @param allGuids List to populate provided by getAllGuids + * @param newGuid The GUID to add to the list + */ + @CalledByNative + private static void addToGuidList(List<String> allGuids, String newGuid) { + allGuids.add(newGuid); + } + + /** Deletes all SendTabToSelf entries. This is called when the user disables sync. */ + public void deleteAllEntries() { + // TODO(tgupta): Add this assertion back in once the code to load is in place. + // assert mIsNativeSendTabToSelfModelLoaded; + Natives jni = SendTabToSelfAndroidBridgeJni.get(); + jni.deleteAllEntries(this, mNativeSendTabToSelfAndroidBridge); + } + + /** + * Creates a new entry to be persisted to the sync backend. + * + * @param url URL to be shared + * @param title Title of the page + * @param navigationTime Time the user navigated to the page + * @return The persisted entry which contains additional information such as the GUID or null in + * the case of an error. + */ + @Nullable + public SendTabToSelfEntry addEntry(String url, String title, long navigationTime) { + // TODO(tgupta): Add this assertion back in once the code to load is in place. + // assert mIsNativeSendTabToSelfModelLoaded; + Natives jni = SendTabToSelfAndroidBridgeJni.get(); + return jni.addEntry(this, mNativeSendTabToSelfAndroidBridge, url, title, navigationTime); + } + + /** + * Return the entry associated with a particular GUID + * + * @param guid The GUID to retrieve the entry for + * @return The found entry or null if none exists + */ + @Nullable + public SendTabToSelfEntry getEntryByGUID(String guid) { + // TODO(tgupta): Add this assertion back in once the code to load is in place. + // assert mIsNativeSendTabToSelfModelLoaded; + Natives jni = SendTabToSelfAndroidBridgeJni.get(); + return jni.getEntryByGUID(this, mNativeSendTabToSelfAndroidBridge, guid); + } + + @NativeMethods + interface Natives { + long init(@JCaller SendTabToSelfAndroidBridge bridge, Profile profile); + + void destroy( + @JCaller SendTabToSelfAndroidBridge bridge, long nativeSendTabToSelfAndroidBridge); + + SendTabToSelfEntry addEntry(@JCaller SendTabToSelfAndroidBridge bridge, + long nativeSendTabToSelfAndroidBridge, String url, String title, + long navigationTime); + + void getAllGuids(@JCaller SendTabToSelfAndroidBridge bridge, + long nativeSendTabToSelfAndroidBridge, List<String> guids); + + void deleteAllEntries( + @JCaller SendTabToSelfAndroidBridge bridge, long nativeSendTabToSelfAndroidBridge); + + SendTabToSelfEntry getEntryByGUID(@JCaller SendTabToSelfAndroidBridge bridge, + long nativeSendTabToSelfAndroidBridge, String guid); + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfEntry.java b/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfEntry.java new file mode 100644 index 0000000..a00ef72 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfEntry.java
@@ -0,0 +1,45 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.send_tab_to_self; + +import org.chromium.base.annotations.CalledByNative; + +/** + * SendTabToSelfEntry mirrors the native struct send_tab_to_self::SendTabToSelfEntry declared in + * //components/send_tab_to_self/send_tab_to_self_entry.h. This provides useful getters and methods + * called by native code. + */ +public class SendTabToSelfEntry { + /** The unique random id for the entry. */ + public final String guid; + /** The mUrl of the page the user would like to send to themselves. */ + public final String url; + /** The mTitle of the entry. Might be empty. */ + public final String title; + /** The name of the device that originated the sent tab. */ + public final String deviceName; + /** The time that the tab was shared. */ + public final long sharedTime; + /** The time that the tab was navigated to. */ + public final long originalNavigationTime; + + public SendTabToSelfEntry(String guid, String url, String title, long sharedTime, + long originalNavigationTime, String deviceName) { + this.guid = guid; + this.url = url; + this.title = title; + this.sharedTime = sharedTime; + this.originalNavigationTime = originalNavigationTime; + this.deviceName = deviceName; + } + + /** Used by native code in order to create a new object of this type. */ + @CalledByNative + private static SendTabToSelfEntry createSendTabToSelfEntry(String mGuid, String mUrl, + String mTitle, long mSharedTime, long mOriginalNavigationTime, String mDeviceName) { + return new SendTabToSelfEntry( + mGuid, mUrl, mTitle, mSharedTime, mOriginalNavigationTime, mDeviceName); + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfShareActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfShareActivity.java index 29b31b7..d2a0cfe 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfShareActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfShareActivity.java
@@ -1,4 +1,4 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. +// 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. @@ -13,13 +13,16 @@ import org.chromium.components.sync.ModelType; /** - * A simple activity that allows Chrome to expose send tab to self as an - * option in the share menu. + * A simple activity that allows Chrome to expose send tab to self as an option in the share menu. */ public class SendTabToSelfShareActivity extends ShareActivity { @Override protected void handleShareAction(ChromeActivity triggeringActivity) { - // TODO(tgupta): Hook up logic to the sync server here + Tab tab = triggeringActivity.getActivityTabProvider().getActivityTab(); + SendTabToSelfAndroidBridge bridge = new SendTabToSelfAndroidBridge(tab.getProfile()); + // TODO(tgupta): Get the real navigation time here rather than bogus hard-coded one. + bridge.addEntry(tab.getUrl(), tab.getTitle(), 123l); + bridge.destroy(); } public static boolean featureIsAvailable(Tab currentTab) { @@ -44,4 +47,3 @@ return featureEnabled && contentRequirementsMet && syncRequirementsMet; } } -
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/EmptyTabObserver.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/EmptyTabObserver.java index 9e5fcc9..b63085a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/EmptyTabObserver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/EmptyTabObserver.java
@@ -77,6 +77,9 @@ public void onContextualActionBarVisibilityChanged(Tab tab, boolean visible) { } @Override + public void onCloseContents(Tab tab) {} + + @Override public void onLoadStarted(Tab tab, boolean toDifferentDocument) { } @Override
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 a0b3035..c2afa07d 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
@@ -182,13 +182,6 @@ private int mRootId; /** - * If this tab was opened from another tab in another Activity, this is the Intent that can be - * fired to bring the parent Activity back. - * TODO(dfalcantara): Remove this mechanism when we have a global TabManager. - */ - private Intent mParentIntent; - - /** * Whether the tab should be grouped with its parent tab. */ private boolean mGroupedWithParent = true; @@ -2475,21 +2468,6 @@ } /** - * Sets the Intent that can be fired to restart the Activity of this Tab's parent. - * Should only be called if the Tab was launched via a different Activity. - */ - public void setParentIntent(Intent parentIntent) { - mParentIntent = parentIntent; - } - - /** - * @return Intent that can be fired to restart the parent Activity. - */ - protected Intent getParentIntent() { - return mParentIntent; - } - - /** * Creates a new, "frozen" tab from a saved state. This can be used for background tabs restored * on cold start that should be loaded when switched to. initialize() needs to be called * afterwards to complete the second level initialization.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabObserver.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabObserver.java index 0c9948fd..30a668f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabObserver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabObserver.java
@@ -162,6 +162,12 @@ // WebContentsDelegateAndroid methods --------------------------------------------------------- /** + * Called when the WebContents is closed. + * @param tab The notifying {@link Tab}. + */ + void onCloseContents(Tab tab); + + /** * Called when the WebContents starts loading. Different from * {@link #onPageLoadStarted(Tab, String)}, if the user is navigated to a different url while * staying in the same html document, {@link #onLoadStarted(Tab)} will be called, while
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabParentIntent.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabParentIntent.java new file mode 100644 index 0000000..0d11c3d --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabParentIntent.java
@@ -0,0 +1,59 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.tab; + +import android.content.Intent; + +import org.chromium.base.UserData; +import org.chromium.base.UserDataHost; + +/** + * A holder of {@link Intent} object to be used to bring back the parent {@link Activity} + * from which the associated tab was opened. + */ +public final class TabParentIntent extends EmptyTabObserver implements UserData { + private static final Class<TabParentIntent> USER_DATA_KEY = TabParentIntent.class; + + private final Tab mTab; + + /** + * If the associated tab was opened from another tab in another Activity, this is the Intent + * that can be fired to bring the parent Activity back. + */ + private Intent mParentIntent; + + public static TabParentIntent from(Tab tab) { + UserDataHost host = tab.getUserDataHost(); + TabParentIntent tabParentIntent = host.getUserData(USER_DATA_KEY); + if (tabParentIntent == null) { + tabParentIntent = host.setUserData(USER_DATA_KEY, new TabParentIntent(tab)); + } + return tabParentIntent; + } + + private TabParentIntent(Tab tab) { + mTab = tab; + mTab.addObserver(this); + } + + @Override + public void onCloseContents(Tab tab) { + boolean isSelected = mTab.getTabModelSelector().getCurrentTab() == tab; + + // If the parent Tab belongs to another Activity, fire the Intent to bring it back. + if (isSelected && mParentIntent != null && tab.getActivity().getIntent() != mParentIntent) { + tab.getActivity().startActivity(mParentIntent); + } + } + + public void set(Intent intent) { + mParentIntent = intent; + } + + @Override + public void destroy() { + mTab.removeObserver(this); + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsDelegateAndroid.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsDelegateAndroid.java index fcc57ca..e2af499 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsDelegateAndroid.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsDelegateAndroid.java
@@ -6,7 +6,6 @@ import android.annotation.TargetApi; import android.app.Activity; -import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.content.res.Resources; @@ -30,7 +29,6 @@ import org.chromium.chrome.browser.AppHooks; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.SwipeRefreshHandler; -import org.chromium.chrome.browser.document.DocumentUtils; import org.chromium.chrome.browser.document.DocumentWebContentsDelegate; import org.chromium.chrome.browser.findinpage.FindMatchRectsDetails; import org.chromium.chrome.browser.findinpage.FindNotificationDetails; @@ -77,47 +75,23 @@ /** Used for logging. */ private static final String TAG = "WebContentsDelegate"; + private final Runnable mCloseContentsRunnable; protected final Tab mTab; - private FindResultListener mFindResultListener; - - private FindMatchRectsListener mFindMatchRectsListener; - - private @WebDisplayMode int mDisplayMode = WebDisplayMode.BROWSER; - protected Handler mHandler; - - private final Runnable mCloseContentsRunnable = new Runnable() { - @Override - public void run() { - boolean isSelected = mTab.getTabModelSelector().getCurrentTab() == mTab; - mTab.getTabModelSelector().closeTab(mTab); - - // If the parent Tab belongs to another Activity, fire the Intent to bring it back. - if (isSelected && mTab.getParentIntent() != null - && mTab.getActivity().getIntent() != mTab.getParentIntent()) { - mTab.getActivity().startActivity(mTab.getParentIntent()); - } - } - - /** If the API allows it, returns whether a Task still exists for the parent Activity. */ - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - private boolean isParentInAndroidOverview() { - ActivityManager activityManager = (ActivityManager) mTab.getApplicationContext() - .getSystemService(Context.ACTIVITY_SERVICE); - for (ActivityManager.AppTask task : activityManager.getAppTasks()) { - Intent taskIntent = DocumentUtils.getBaseIntentFromTask(task); - if (taskIntent != null && taskIntent.filterEquals(mTab.getParentIntent())) { - return true; - } - } - return false; - } - }; + private FindResultListener mFindResultListener; + private FindMatchRectsListener mFindMatchRectsListener; + private @WebDisplayMode int mDisplayMode = WebDisplayMode.BROWSER; public TabWebContentsDelegateAndroid(Tab tab) { mTab = tab; mHandler = new Handler(); + mCloseContentsRunnable = () -> { + // TODO(jinsukkim): Move |closeTab| to TabModelSelector by making it observe its tabs. + mTab.getTabModelSelector().closeTab(mTab); + RewindableIterator<TabObserver> observers = mTab.getTabObservers(); + while (observers.hasNext()) observers.next().onCloseContents(mTab); + }; } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/ChromeTabCreator.java b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/ChromeTabCreator.java index cabe5fc..37054d9 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/ChromeTabCreator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/ChromeTabCreator.java
@@ -16,6 +16,7 @@ import org.chromium.chrome.browser.net.spdyproxy.DataReductionProxySettings; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabDelegateFactory; +import org.chromium.chrome.browser.tab.TabParentIntent; import org.chromium.chrome.browser.tab.TabRedirectHandler; import org.chromium.chrome.browser.tab.TabState; import org.chromium.chrome.browser.util.IntentUtils; @@ -132,7 +133,7 @@ !openInForeground); tab.initialize( webContents, mTabContentManager, delegateFactory, !openInForeground, false); - tab.setParentIntent(parentIntent); + TabParentIntent.from(tab).set(parentIntent); webContents.resumeLoadingCreatedWebContents(); } else if (!openInForeground && SysUtils.isLowEndDevice()) { // On low memory devices the tabs opened in background are not loaded automatically
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_list_ui/BottomTabGridCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_list_ui/BottomTabGridCoordinator.java new file mode 100644 index 0000000..7b2dd62 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_list_ui/BottomTabGridCoordinator.java
@@ -0,0 +1,80 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.tasks.tab_list_ui; + +import static org.chromium.chrome.browser.dependency_injection.ChromeCommonQualifiers.ACTIVITY_CONTEXT; + +import android.content.Context; + +import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager; +import org.chromium.chrome.browser.dependency_injection.ActivityScope; +import org.chromium.chrome.browser.init.ActivityLifecycleDispatcher; +import org.chromium.chrome.browser.lifecycle.Destroyable; +import org.chromium.chrome.browser.tabmodel.TabModel; +import org.chromium.chrome.browser.tabmodel.TabModelSelector; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController; + +import javax.inject.Inject; +import javax.inject.Named; + +/** + * A coordinator for BottomTabGrid component. Manages the communication + * with {@link TabListCoordinator} as well as the life-cycle of shared component objects. + */ +@ActivityScope +public class BottomTabGridCoordinator implements Destroyable { + private final BottomTabGridMediator mMediator; + private final TabListCoordinator mTabGridCoordinator; + private BottomTabGridSheetContent mBottomSheetContent; + private final ActivityLifecycleDispatcher mLifecycleDispatcher; + + @Inject + BottomTabGridCoordinator(@Named(ACTIVITY_CONTEXT) Context context, + BottomSheetController bottomSheetController, TabModelSelector tabModelSelector, + TabContentManager tabContentManager, ActivityLifecycleDispatcher lifecycleDispatcher) { + mTabGridCoordinator = new TabListCoordinator(TabListCoordinator.TabListMode.GRID, context, + tabModelSelector, tabContentManager, bottomSheetController.getBottomSheet()); + + mMediator = new BottomTabGridMediator(bottomSheetController, this::resetWithTabModel); + + mLifecycleDispatcher = lifecycleDispatcher; + mLifecycleDispatcher.register(this); + } + + /** + * Destroy any members that needs clean up. + */ + @Override + public void destroy() { + mTabGridCoordinator.destroy(); + mLifecycleDispatcher.unregister(this); + if (mBottomSheetContent != null) { + mBottomSheetContent.destroy(); + } + } + + /** + * Updates tabs list through {@link TabListCoordinator} with given tab model + * and calls onReset() on {@link BottomTabGridMediator} + */ + void resetWithTabModel(TabModel tabModel) { + mTabGridCoordinator.resetWithTabModel(tabModel); + updateBottomSheetContent(tabModel); + mMediator.onReset(mBottomSheetContent); + } + + private void updateBottomSheetContent(TabModel tabModel) { + if (tabModel != null) { + // create and display sheet content + mBottomSheetContent = + new BottomTabGridSheetContent(mTabGridCoordinator.getContainerView()); + } else { + if (mBottomSheetContent != null) { + mBottomSheetContent.destroy(); + mBottomSheetContent = null; + } + } + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_list_ui/BottomTabGridMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_list_ui/BottomTabGridMediator.java new file mode 100644 index 0000000..2f468d7 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_list_ui/BottomTabGridMediator.java
@@ -0,0 +1,67 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.tasks.tab_list_ui; + +import org.chromium.chrome.browser.tabmodel.TabModel; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheet.StateChangeReason; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetObserver; +import org.chromium.chrome.browser.widget.bottomsheet.EmptyBottomSheetObserver; + +/** + * A mediator for the BottomTabGrid component, respoonsible for communicating with + * the components' coordinator as well as managing the state of the bottom sheet. + */ +class BottomTabGridMediator { + /** + * Defines an interface for a {@link BottomTabGridMediator} reset event handler. + */ + interface ResetHandler { + /** + * Handles reset event originating from {@link BottomTabGridMediator}. + * @param tabModel current {@link TabModel} instance. + */ + void resetWithTabModel(TabModel tabModel); + } + + private final BottomSheetController mBottomSheetController; + private final BottomSheetObserver mSheetObserver; + + BottomTabGridMediator(BottomSheetController bottomSheetController, ResetHandler resetHandler) { + mBottomSheetController = bottomSheetController; + + // TODO (ayman): Add instrumentation to observer calls. + mSheetObserver = new EmptyBottomSheetObserver() { + @Override + public void onSheetClosed(@StateChangeReason int reason) { + resetHandler.resetWithTabModel(null); + } + }; + } + + /** + * Handles communication with the bottom sheet based on the content provided. + * @param sheetContent The {@link BottomTabGridSheetContent} to populate the bottom sheet with. + * When set to null, the bottom sheet will be hidden. + */ + void onReset(BottomTabGridSheetContent sheetContent) { + if (sheetContent == null) { + removeSuggestionsFromSheet(sheetContent); + } else { + showTabGridInBottomSheet(sheetContent); + } + } + + private void showTabGridInBottomSheet(BottomTabGridSheetContent sheetContent) { + mBottomSheetController.getBottomSheet().addObserver(mSheetObserver); + mBottomSheetController.requestShowContent(sheetContent, true); + mBottomSheetController.expandSheet(); + } + + private void removeSuggestionsFromSheet(BottomTabGridSheetContent sheetContent) { + mBottomSheetController.hideContent(sheetContent, true); + mBottomSheetController.getBottomSheet().removeObserver(mSheetObserver); + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_list_ui/BottomTabGridSheetContent.java b/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_list_ui/BottomTabGridSheetContent.java new file mode 100644 index 0000000..9c37caf --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_list_ui/BottomTabGridSheetContent.java
@@ -0,0 +1,80 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.tasks.tab_list_ui; + +import android.view.View; + +import org.chromium.chrome.R; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheet.BottomSheetContent; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheet.ContentPriority; + +import javax.inject.Inject; + +/** A {@link BottomSheetContent} that displays tab grid. **/ +public class BottomTabGridSheetContent implements BottomSheetContent { + private final TabListRecyclerView mRecyclerView; + + /** + * Construct a new {@link ContextualSuggestionsBottomSheetContent}. + * @param recyclerView The {@link TabListRecyclerView} holding the tab grid. + */ + @Inject + BottomTabGridSheetContent(TabListRecyclerView recyclerView) { + mRecyclerView = recyclerView; + } + + @Override + public View getContentView() { + return mRecyclerView; + } + + @Override + public View getToolbarView() { + return null; + } + + @Override + public int getVerticalScrollOffset() { + return mRecyclerView.computeVerticalScrollOffset(); + } + + @Override + public void destroy() {} + + @Override + public @ContentPriority int getPriority() { + return ContentPriority.HIGH; + } + + @Override + public boolean swipeToDismissEnabled() { + return true; + } + + @Override + public boolean isPeekStateEnabled() { + return false; + } + + @Override + public int getSheetContentDescriptionStringId() { + return R.string.bottom_tab_grid_description; + } + + @Override + public int getSheetHalfHeightAccessibilityStringId() { + return R.string.bottom_tab_grid_opened_half; + } + + @Override + public int getSheetFullHeightAccessibilityStringId() { + return R.string.bottom_tab_grid_opened_full; + } + + @Override + public int getSheetClosedAccessibilityStringId() { + return R.string.bottom_tab_grid_closed; + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_list_ui/TabListCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_list_ui/TabListCoordinator.java index 9fea313..5d0a5d41 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_list_ui/TabListCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_list_ui/TabListCoordinator.java
@@ -64,9 +64,15 @@ "Attempting to create a tab list UI with invalid mode"); } - LayoutInflater.from(context).inflate( - R.layout.tab_list_recycler_view_layout, parentView, true); - mRecyclerView = parentView.findViewById(R.id.tab_list_view); + if (parentView != null) { + mRecyclerView = (TabListRecyclerView) LayoutInflater.from(context).inflate( + R.layout.tab_list_recycler_view_layout, parentView, false); + } else { + LayoutInflater.from(context).inflate( + R.layout.tab_list_recycler_view_layout, parentView, true); + mRecyclerView = parentView.findViewById(R.id.tab_list_view); + } + mRecyclerView.setAdapter(adapter); if (mode == TabListMode.GRID) { @@ -104,4 +110,4 @@ public void destroy() { mMediator.destroy(); } -} \ No newline at end of file +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarPhone.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarPhone.java index ca7be01..054042ff 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarPhone.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarPhone.java
@@ -1528,8 +1528,7 @@ if (mForceTextureCapture) { return true; } - return !(mTabSwitcherState == TAB_SWITCHER || mTabSwitcherModeAnimation != null - || urlHasFocus() || mUrlFocusChangeInProgress || mNtpSearchBoxScrollPercent > 0); + return !(urlHasFocus() || mUrlFocusChangeInProgress || mNtpSearchBoxScrollPercent > 0); } @Override
diff --git a/chrome/android/java/strings/android_chrome_strings.grd b/chrome/android/java/strings/android_chrome_strings.grd index 81822f3bc..f14f490 100644 --- a/chrome/android/java/strings/android_chrome_strings.grd +++ b/chrome/android/java/strings/android_chrome_strings.grd
@@ -2740,7 +2740,7 @@ Google may use your history to personalize Search and other Google services </message> <message name="IDS_SIGNIN_DETAILS_DESCRIPTION" desc="Message with a link to customize Sync settings. Shown on the screen that asks the user to turn on Sync."> - You can <ph name="BEGIN_LINK1"><LINK1></ph>customize these settings<ph name="END_LINK1"></LINK1></ph> anytime + You can always <ph name="BEGIN_LINK1"><LINK1></ph>choose what to sync in settings<ph name="END_LINK1"></LINK1></ph> </message> <message name="IDS_SIGNIN_ACCEPT_BUTTON" desc="Text for the confirmation button in the sign-in screen. By clicking this button users signs in and turns on Sync. [CHAR-LIMIT=20]"> Yes, I'm in @@ -4024,6 +4024,24 @@ <message name="IDS_USAGE_STATS_SETTING_TITLE" desc="Title for setting toggling Digital Wellbeing to access Chrome usage data"> Connect to Digital Wellbeing </message> + + <!-- Bottom Tab Grid strings --> + <message name="IDS_BOTTOM_TAB_GRID_DESCRIPTION" desc="The content description of the 'opened tabs' bottom sheet."> + Opened tabs + </message> + + <message name="IDS_BOTTOM_TAB_GRID_OPENED_HALF" desc="Accessibility string read when the 'opened tabs' sheet is opened at half height. The sheet will occupy the bottom half the screen. "> + Opened tabs at half height + </message> + + <message name="IDS_BOTTOM_TAB_GRID_OPENED_FULL" desc="Accessibility string read when the 'opened tabs' bottom sheet is opened at full height. The sheet will occupy the entire screen."> + Opened tabs at full height + </message> + + <message name="IDS_BOTTOM_TAB_GRID_CLOSED" desc="Accessibility string read when the 'opened tabs' bottom sheet is closed."> + Opened tabs closed + </message> + </messages> </release> </grit>
diff --git a/chrome/android/java_sources.gni b/chrome/android/java_sources.gni index 237dbdd75..339bfa2 100644 --- a/chrome/android/java_sources.gni +++ b/chrome/android/java_sources.gni
@@ -1021,7 +1021,6 @@ "java/src/org/chromium/chrome/browser/ntp/ForeignSessionHelper.java", "java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPage.java", "java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPageView.java", - "java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPageViewMD.java", "java/src/org/chromium/chrome/browser/ntp/LogoBridge.java", "java/src/org/chromium/chrome/browser/ntp/LogoDelegateImpl.java", "java/src/org/chromium/chrome/browser/ntp/LogoView.java", @@ -1443,6 +1442,8 @@ "java/src/org/chromium/chrome/browser/searchwidget/SearchActivityLocationBarLayout.java", "java/src/org/chromium/chrome/browser/searchwidget/SearchBoxDataProvider.java", "java/src/org/chromium/chrome/browser/searchwidget/SearchWidgetProvider.java", + "java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridge.java", + "java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfEntry.java", "java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfShareActivity.java", "java/src/org/chromium/chrome/browser/services/AccountsChangedReceiver.java", "java/src/org/chromium/chrome/browser/services/AndroidEduAndChildAccountHelper.java", @@ -1563,6 +1564,7 @@ "java/src/org/chromium/chrome/browser/tab/TabIdManager.java", "java/src/org/chromium/chrome/browser/tab/TabImportanceManager.java", "java/src/org/chromium/chrome/browser/tab/TabObserver.java", + "java/src/org/chromium/chrome/browser/tab/TabParentIntent.java", "java/src/org/chromium/chrome/browser/tab/TabRedirectHandler.java", "java/src/org/chromium/chrome/browser/tab/TabState.java", "java/src/org/chromium/chrome/browser/tab/TabStateBrowserControlsVisibilityDelegate.java", @@ -1619,6 +1621,9 @@ "java/src/org/chromium/chrome/browser/tabmodel/document/StorageDelegate.java", "java/src/org/chromium/chrome/browser/tabmodel/document/TabDelegate.java", "java/src/org/chromium/chrome/browser/tasks/TasksUma.java", + "java/src/org/chromium/chrome/browser/tasks/tab_list_ui/BottomTabGridCoordinator.java", + "java/src/org/chromium/chrome/browser/tasks/tab_list_ui/BottomTabGridMediator.java", + "java/src/org/chromium/chrome/browser/tasks/tab_list_ui/BottomTabGridSheetContent.java", "java/src/org/chromium/chrome/browser/tasks/tab_list_ui/GridTabSwitcherCoordinator.java", "java/src/org/chromium/chrome/browser/tasks/tab_list_ui/GridTabSwitcherMediator.java", "java/src/org/chromium/chrome/browser/tasks/tab_list_ui/TabGridContainerViewBinder.java", @@ -2572,6 +2577,7 @@ "junit/src/org/chromium/chrome/browser/preferences/password/SingleThreadBarrierClosureTest.java", "junit/src/org/chromium/chrome/browser/preferences/password/TimedCallbackDelayerTest.java", "junit/src/org/chromium/chrome/browser/preferences/privacy/PrivacyPreferencesManagerTest.java", + "junit/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridgeTest.java", "junit/src/org/chromium/chrome/browser/signin/SigninManagerTest.java", "junit/src/org/chromium/chrome/browser/signin/SigninPromoUtilTest.java", "junit/src/org/chromium/chrome/browser/snackbar/SnackbarCollectionUnitTest.java",
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTest.java index 0dadb72..98fe8bdf 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTest.java
@@ -165,22 +165,26 @@ // Show movie details. String movieTitle = "testTitle"; - String movieDescription = "This is a fancy test movie"; + String descriptionLine1 = "This is a fancy line1"; + String descriptionLine2 = "This is a fancy line2"; ThreadUtils.runOnUiThreadBlocking( () -> assistantCoordinator.getModel().getDetailsModel().set( AssistantDetailsModel.DETAILS, - new AssistantDetails(movieTitle, /* url = */ "", - Calendar.getInstance().getTime(), movieDescription, - /* mId = */ "", - /* price = */ null, + new AssistantDetails(movieTitle, /* imageUrl = */ "", + /* totalPriceLabel = */ "", + /* totalPrice = */ "", Calendar.getInstance().getTime(), + descriptionLine1, descriptionLine2, /* userApprovalRequired= */ false, - /* highlightTitle= */ false, /* highlightDate= */ - false, /* showPlaceholdersForEmptyFields= */ false))); - TextView detailsTitle = (TextView) bottomSheet.findViewById(R.id.details_title); - TextView detailsText = (TextView) bottomSheet.findViewById(R.id.details_text); + /* highlightTitle= */ false, /* highlightLine1= */ + false, /* highlightLine1 = */ false, + /* showPlaceholdersForEmptyFields= */ false))); + TextView detailsTitle = bottomSheet.findViewById(R.id.details_title); + TextView detailsLine1 = bottomSheet.findViewById(R.id.details_line1); + TextView detailsLine2 = bottomSheet.findViewById(R.id.details_line2); Assert.assertEquals(detailsTitle.getText(), movieTitle); - Assert.assertTrue(detailsText.getText().toString().contains(movieDescription)); + Assert.assertTrue(detailsLine1.getText().toString().contains(descriptionLine1)); + Assert.assertTrue(detailsLine2.getText().toString().contains(descriptionLine2)); // Progress bar must be shown. Assert.assertTrue(bottomSheet.findViewById(R.id.progress_bar).isShown());
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserControllerInputTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserControllerInputTest.java index b085ee71..4b12b81 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserControllerInputTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserControllerInputTest.java
@@ -418,11 +418,11 @@ VrBrowserTestFramework.getFileUrlForHtmlTestFile("test_navigation_2d_page"), PAGE_LOAD_TIMEOUT_S); // Enter fullscreen - DOMUtils.clickNode(mVrBrowserTestFramework.getFirstTabWebContents(), "fullscreen", + DOMUtils.clickNode(mVrBrowserTestFramework.getCurrentWebContents(), "fullscreen", false /* goThroughRootAndroidView */); mVrBrowserTestFramework.waitOnJavaScriptStep(); Assert.assertTrue("Page did not enter fullscreen", - DOMUtils.isFullscreen(mVrBrowserTestFramework.getFirstTabWebContents())); + DOMUtils.isFullscreen(mVrBrowserTestFramework.getCurrentWebContents())); NativeUiUtils.clickAppButton(UserFriendlyElementName.NONE, new PointF()); CriteriaHelper.pollInstrumentationThread( @@ -430,7 +430,7 @@ -> { try { return !DOMUtils.isFullscreen( - mVrBrowserTestFramework.getFirstTabWebContents()); + mVrBrowserTestFramework.getCurrentWebContents()); } catch (InterruptedException | TimeoutException e) { return false; }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserDialogTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserDialogTest.java index 2d6a17a..f5f4bab 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserDialogTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserDialogTest.java
@@ -106,9 +106,8 @@ NativeUiUtils.performActionAndWaitForUiQuiescence(() -> { NativeUiUtils.performActionAndWaitForVisibilityStatus( UserFriendlyElementName.BROWSING_DIALOG, true /* visible */, () -> { - VrBrowserTestFramework.runJavaScriptOrFail(promptCommand, - POLL_TIMEOUT_LONG_MS, - mVrTestRule.getActivity().getActivityTab().getWebContents()); + mVrBrowserTestFramework.runJavaScriptOrFail( + promptCommand, POLL_TIMEOUT_LONG_MS); }); }); } @@ -152,17 +151,12 @@ // Special case location because the callbacks never fire on swarming, likely because // location is disabled at the system level during device provisioning. if (!nameBase.equals("location_permission_prompt")) { - // We specify the web contents here so that it works in both regular and incognito mode. - // This can be removed as part of https://crbug.com/931420 - VrBrowserTestFramework.waitOnJavaScriptStep( - mVrTestRule.getActivity().getActivityTab().getWebContents()); + mVrBrowserTestFramework.waitOnJavaScriptStep(); Assert.assertEquals("Last permission interaction did not have expected grant result", grant, - Boolean.valueOf(VrBrowserTestFramework.runJavaScriptOrFail( - "lastPermissionGranted", POLL_TIMEOUT_SHORT_MS, - mVrTestRule.getActivity().getActivityTab().getWebContents()))); - VrBrowserTestFramework.assertNoJavaScriptErrors( - mVrTestRule.getActivity().getActivityTab().getWebContents()); + Boolean.valueOf(mVrBrowserTestFramework.runJavaScriptOrFail( + "lastPermissionGranted", POLL_TIMEOUT_SHORT_MS))); + mVrBrowserTestFramework.assertNoJavaScriptErrors(); } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserNavigationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserNavigationTest.java index 0706bbb..75c0989 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserNavigationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserNavigationTest.java
@@ -167,7 +167,7 @@ navigateTo(Page.PAGE_2D_2); - assertState(mVrBrowserTestFramework.getFirstTabWebContents(), Page.PAGE_2D_2, + assertState(mVrBrowserTestFramework.getCurrentWebContents(), Page.PAGE_2D_2, PresentationMode.NON_PRESENTING, FullscreenMode.NON_FULLSCREENED); // Test that the navigations were added to history @@ -189,7 +189,7 @@ ThreadUtils.runOnUiThreadBlocking(() -> itemViews.get(0).onClick()); ChromeTabUtils.waitForTabPageLoaded( mTestRule.getActivity().getActivityTab(), getUrl(Page.PAGE_2D_2)); - assertState(mWebXrVrTestFramework.getFirstTabWebContents(), Page.PAGE_2D_2, + assertState(mWebXrVrTestFramework.getCurrentWebContents(), Page.PAGE_2D_2, PresentationMode.NON_PRESENTING, FullscreenMode.NON_FULLSCREENED); } @@ -222,7 +222,7 @@ navigateTo(page); - assertState(framework.getFirstTabWebContents(), page, PresentationMode.NON_PRESENTING, + assertState(framework.getCurrentWebContents(), page, PresentationMode.NON_PRESENTING, FullscreenMode.NON_FULLSCREENED); } @@ -252,11 +252,11 @@ private void impl2dFullscreenToWeb(@Page int page, WebXrVrTestFramework framework) throws InterruptedException, TimeoutException { framework.loadUrlAndAwaitInitialization(TEST_PAGE_2D_URL, PAGE_LOAD_TIMEOUT_S); - enterFullscreenOrFail(framework.getFirstTabWebContents()); + enterFullscreenOrFail(framework.getCurrentWebContents()); navigateTo(page); - assertState(framework.getFirstTabWebContents(), page, PresentationMode.NON_PRESENTING, + assertState(framework.getCurrentWebContents(), page, PresentationMode.NON_PRESENTING, FullscreenMode.NON_FULLSCREENED); } @@ -289,7 +289,7 @@ navigateTo(Page.PAGE_2D); - assertState(framework.getFirstTabWebContents(), Page.PAGE_2D, + assertState(framework.getCurrentWebContents(), Page.PAGE_2D, PresentationMode.NON_PRESENTING, FullscreenMode.NON_FULLSCREENED); } @@ -322,7 +322,7 @@ navigateTo(page); - assertState(framework.getFirstTabWebContents(), page, PresentationMode.NON_PRESENTING, + assertState(framework.getCurrentWebContents(), page, PresentationMode.NON_PRESENTING, FullscreenMode.NON_FULLSCREENED); } @@ -356,7 +356,7 @@ navigateTo(Page.PAGE_2D); - assertState(framework.getFirstTabWebContents(), Page.PAGE_2D, + assertState(framework.getCurrentWebContents(), Page.PAGE_2D, PresentationMode.NON_PRESENTING, FullscreenMode.NON_FULLSCREENED); } @@ -390,7 +390,7 @@ navigateTo(page); - assertState(framework.getFirstTabWebContents(), page, PresentationMode.NON_PRESENTING, + assertState(framework.getCurrentWebContents(), page, PresentationMode.NON_PRESENTING, FullscreenMode.NON_FULLSCREENED); } @@ -420,11 +420,11 @@ private void webFullscreenTo2dImpl(@Page int page, WebXrVrTestFramework framework) throws InterruptedException, TimeoutException { framework.loadUrlAndAwaitInitialization(getUrl(page), PAGE_LOAD_TIMEOUT_S); - enterFullscreenOrFail(framework.getFirstTabWebContents()); + enterFullscreenOrFail(framework.getCurrentWebContents()); navigateTo(Page.PAGE_2D); - assertState(framework.getFirstTabWebContents(), Page.PAGE_2D, + assertState(framework.getCurrentWebContents(), Page.PAGE_2D, PresentationMode.NON_PRESENTING, FullscreenMode.NON_FULLSCREENED); } @@ -454,11 +454,11 @@ private void webFullscreenToWebImpl(@Page int page, WebXrVrTestFramework framework) throws InterruptedException, TimeoutException { framework.loadUrlAndAwaitInitialization(getUrl(page), PAGE_LOAD_TIMEOUT_S); - enterFullscreenOrFail(framework.getFirstTabWebContents()); + enterFullscreenOrFail(framework.getCurrentWebContents()); navigateTo(page); - assertState(framework.getFirstTabWebContents(), page, PresentationMode.NON_PRESENTING, + assertState(framework.getCurrentWebContents(), page, PresentationMode.NON_PRESENTING, FullscreenMode.NON_FULLSCREENED); } @@ -581,7 +581,7 @@ throws IllegalArgumentException, InterruptedException, TimeoutException { mVrBrowserTestFramework.loadUrlAndAwaitInitialization( TEST_PAGE_2D_URL, PAGE_LOAD_TIMEOUT_S); - enterFullscreenOrFail(mVrBrowserTestFramework.getFirstTabWebContents()); + enterFullscreenOrFail(mVrBrowserTestFramework.getCurrentWebContents()); final Tab tab = mTestRule.getActivity().getActivityTab(); ThreadUtils.runOnUiThreadBlocking( @@ -593,7 +593,7 @@ ChromeTabUtils.waitForTabPageLoaded(tab, TEST_PAGE_2D_URL); ChromeTabUtils.waitForInteractable(tab); - assertState(mVrBrowserTestFramework.getFirstTabWebContents(), Page.PAGE_2D, + assertState(mVrBrowserTestFramework.getCurrentWebContents(), Page.PAGE_2D, PresentationMode.NON_PRESENTING, FullscreenMode.NON_FULLSCREENED); } @@ -706,11 +706,7 @@ @Test @MediumTest public void testUrlEntryTriggersNavigationIncognito() throws InterruptedException { - ThreadUtils.runOnUiThreadBlocking(() -> { - mTestRule.getActivity() - .getTabCreator(true /* incognito */) - .launchUrl("about:blank", TabLaunchType.FROM_LINK); - }); + mVrBrowserTestFramework.openIncognitoTab("about:blank"); testUrlEntryTriggersNavigationImpl(); } @@ -748,11 +744,7 @@ @Test @MediumTest public void testSuggestionClickTriggersNavigationIncognito() throws InterruptedException { - ThreadUtils.runOnUiThreadBlocking(() -> { - mTestRule.getActivity() - .getTabCreator(true /* incognito */) - .launchUrl("about:blank", TabLaunchType.FROM_LINK); - }); + mVrBrowserTestFramework.openIncognitoTab("about:blank"); testSuggestionClickTriggersNavigationImpl(); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserTransitionTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserTransitionTest.java index d992e1b..19bf68d 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserTransitionTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserTransitionTest.java
@@ -209,12 +209,12 @@ mVrBrowserTestFramework.loadUrlAndAwaitInitialization( VrBrowserTestFramework.getFileUrlForHtmlTestFile("test_navigation_2d_page"), PAGE_LOAD_TIMEOUT_S); - DOMUtils.clickNode(mVrBrowserTestFramework.getFirstTabWebContents(), "fullscreen", + DOMUtils.clickNode(mVrBrowserTestFramework.getCurrentWebContents(), "fullscreen", false /* goThroughRootAndroidView */); mVrBrowserTestFramework.waitOnJavaScriptStep(); Assert.assertTrue("Page is not in fullscreen", - DOMUtils.isFullscreen(mVrBrowserTestFramework.getFirstTabWebContents())); + DOMUtils.isFullscreen(mVrBrowserTestFramework.getCurrentWebContents())); VrBrowserTransitionUtils.forceExitVr(); // The fullscreen exit from exiting VR isn't necessarily instantaneous, so give it // a bit of time. @@ -223,7 +223,7 @@ -> { try { return !DOMUtils.isFullscreen( - mVrBrowserTestFramework.getFirstTabWebContents()); + mVrBrowserTestFramework.getCurrentWebContents()); } catch (InterruptedException | TimeoutException e) { return false; } @@ -459,7 +459,7 @@ // Alerts block JavaScript execution until they're closed, so we can't use the normal // runJavaScriptOrFail, as that will time out. JavaScriptUtils.executeJavaScript( - mVrBrowserTestFramework.getFirstTabWebContents(), "alert('Please no crash')"); + mVrBrowserTestFramework.getCurrentWebContents(), "alert('Please no crash')"); VrBrowserTransitionUtils.waitForNativeUiPrompt(POLL_TIMEOUT_LONG_MS); VrBrowserTransitionUtils.forceExitVr();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserWebInputEditingTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserWebInputEditingTest.java index c132c48f..1aa41ed 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserWebInputEditingTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserWebInputEditingTest.java
@@ -143,7 +143,7 @@ VrBrowserTransitionUtils.forceEnterVrBrowserOrFail(POLL_TIMEOUT_LONG_MS); NativeUiUtils.enableMockedInput(); // Click on the <select> tag and wait for the resulting modal dialog to appear. - DOMUtils.clickNode(mVrBrowserTestFramework.getFirstTabWebContents(), "selectbox", + DOMUtils.clickNode(mVrBrowserTestFramework.getCurrentWebContents(), "selectbox", false /* goThroughRootAndroidView */); NativeUiUtils.waitForModalDialogStatus(true /* shouldBeShown */, mVrTestRule.getActivity()); // On fast devices such as the Vega, it's possible to send the first click before the modal
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrTestFramework.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrTestFramework.java index efde549..8dacc7a3 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrTestFramework.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrTestFramework.java
@@ -37,12 +37,12 @@ } /** - * Helper function to run xrDeviceFound with the first tab's WebContents. + * Helper function to run xrDeviceFound with the current tab's WebContents. * * @return Whether an XRDevice was found. */ public boolean xrDeviceFound() { - return xrDeviceFound(mFirstTabWebContents); + return xrDeviceFound(getCurrentWebContents()); } /** @@ -61,10 +61,10 @@ } /** - * Helper function to run enterSessionWithUserGesture using the first tab's WebContents. + * Helper function to run enterSessionWithUserGesture using the current tab's WebContents. */ public void enterSessionWithUserGesture() { - enterSessionWithUserGesture(mFirstTabWebContents); + enterSessionWithUserGesture(getCurrentWebContents()); } /** @@ -80,10 +80,10 @@ } /** - * Helper function to run enterSessionWithUserGestureAndWait with the first tab's WebContents. + * Helper function to run enterSessionWithUserGestureAndWait with the current tab's WebContents. */ public void enterSessionWithUserGestureAndWait() { - enterSessionWithUserGestureAndWait(mFirstTabWebContents); + enterSessionWithUserGestureAndWait(getCurrentWebContents()); } /** @@ -94,10 +94,10 @@ public abstract void enterSessionWithUserGestureOrFail(WebContents webContents); /** - * Helper function to run enterSessionWithUserGestureOrFail with the first tab's WebContents. + * Helper function to run enterSessionWithUserGestureOrFail with the current tab's WebContents. */ public void enterSessionWithUserGestureOrFail() { - enterSessionWithUserGestureOrFail(mFirstTabWebContents); + enterSessionWithUserGestureOrFail(getCurrentWebContents()); } /** @@ -108,9 +108,9 @@ public abstract void endSession(WebContents webContents); /** - * Helper function to run endSession with the first tab's WebContents. + * Helper function to run endSession with the current tab's WebContents. */ public void endSession() { - endSession(mFirstTabWebContents); + endSession(getCurrentWebContents()); } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrInputTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrInputTest.java index 3809d19..35fc421 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrInputTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrInputTest.java
@@ -39,7 +39,6 @@ import org.chromium.base.test.util.MinAndroidSdkLevel; import org.chromium.base.test.util.Restriction; import org.chromium.chrome.browser.ChromeSwitches; -import org.chromium.chrome.browser.tabmodel.TabLaunchType; import org.chromium.chrome.browser.vr.mock.MockVrDaydreamApi; import org.chromium.chrome.browser.vr.rules.XrActivityRestriction; import org.chromium.chrome.browser.vr.util.NativeUiUtils; @@ -278,8 +277,8 @@ mWebVrTestFramework.runJavaScriptOrFail("canStartTest = true;", POLL_TIMEOUT_SHORT_MS); // Wait to enter VR mWebVrTestFramework.enterSessionWithUserGestureOrFail(); - int x = mWebVrTestFramework.getFirstTabContentView().getWidth() / 2; - int y = mWebVrTestFramework.getFirstTabContentView().getHeight() / 2; + int x = mWebVrTestFramework.getCurrentContentView().getWidth() / 2; + int y = mWebVrTestFramework.getCurrentContentView().getHeight() / 2; // TODO(mthiesse, https://crbug.com/758374): Injecting touch events into the root GvrLayout // (VrShell) is flaky. Sometimes the events just don't get routed to the presentation // view for no apparent reason. We should figure out why this is and see if it's fixable. @@ -315,8 +314,8 @@ mWebXrVrTestFramework.runJavaScriptOrFail( "stepSetupListeners(" + String.valueOf(numIterations) + ")", POLL_TIMEOUT_SHORT_MS); - int x = mWebXrVrTestFramework.getFirstTabContentView().getWidth() / 2; - int y = mWebXrVrTestFramework.getFirstTabContentView().getHeight() / 2; + int x = mWebXrVrTestFramework.getCurrentContentView().getWidth() / 2; + int y = mWebXrVrTestFramework.getCurrentContentView().getHeight() / 2; // TODO(mthiesse, https://crbug.com/758374): Injecting touch events into the root GvrLayout // (VrShell) is flaky. Sometimes the events just don't get routed to the presentation // view for no apparent reason. We should figure out why this is and see if it's fixable. @@ -683,8 +682,8 @@ controller.performControllerClick(); } } else { - int x = mWebXrVrTestFramework.getFirstTabContentView().getWidth() / 2; - int y = mWebXrVrTestFramework.getFirstTabContentView().getHeight() / 2; + int x = mWebXrVrTestFramework.getCurrentContentView().getWidth() / 2; + int y = mWebXrVrTestFramework.getCurrentContentView().getHeight() / 2; View presentationView; if (webxrPresent) { @@ -730,11 +729,7 @@ @XrActivityRestriction({XrActivityRestriction.SupportedActivity.CTA}) public void testAppButtonLongPressDisplaysPermissionsIncognito() throws InterruptedException { - ThreadUtils.runOnUiThreadBlocking(() -> { - mTestRule.getActivity() - .getTabCreator(true /* incognito */) - .launchUrl("about:blank", TabLaunchType.FROM_LINK); - }); + mWebXrVrTestFramework.openIncognitoTab("about:blank"); testAppButtonLongPressDisplaysPermissionsImpl(); } @@ -820,11 +815,7 @@ @CommandLineFlags.Add({"enable-features=WebXR"}) @XrActivityRestriction({XrActivityRestriction.SupportedActivity.CTA}) public void testInSessionPermissionRequestsIncognito() throws InterruptedException { - ThreadUtils.runOnUiThreadBlocking(() -> { - mTestRule.getActivity() - .getTabCreator(true /* incognito */) - .launchUrl("about:blank", TabLaunchType.FROM_LINK); - }); + mWebXrVrTestFramework.openIncognitoTab("about:blank"); testInSessionPermissionRequestsImpl(); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrTabTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrTabTest.java index 3dca686..dd5fef3 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrTabTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrTabTest.java
@@ -18,7 +18,6 @@ import org.junit.rules.RuleChain; import org.junit.runner.RunWith; -import org.chromium.base.ThreadUtils; import org.chromium.base.test.params.ParameterAnnotations.ClassParameter; import org.chromium.base.test.params.ParameterAnnotations.UseRunnerDelegate; import org.chromium.base.test.params.ParameterSet; @@ -27,12 +26,12 @@ import org.chromium.base.test.util.MinAndroidSdkLevel; import org.chromium.base.test.util.Restriction; import org.chromium.chrome.browser.ChromeSwitches; -import org.chromium.chrome.browser.tabmodel.TabLaunchType; import org.chromium.chrome.browser.vr.util.NativeUiUtils; import org.chromium.chrome.browser.vr.util.PermissionUtils; import org.chromium.chrome.browser.vr.util.VrTestRuleUtils; import org.chromium.chrome.test.ChromeActivityTestRule; import org.chromium.chrome.test.ChromeJUnit4RunnerDelegate; +import org.chromium.content_public.browser.WebContents; import java.util.List; import java.util.concurrent.Callable; @@ -101,11 +100,13 @@ throws InterruptedException { framework.loadUrlAndAwaitInitialization(url, PAGE_LOAD_TIMEOUT_S); framework.executeStepAndWait("stepCheckFrameDataWhileFocusedTab()"); + WebContents firstTabContents = framework.getCurrentWebContents(); mTestRule.loadUrlInNewTab("about:blank"); - framework.executeStepAndWait("stepCheckFrameDataWhileNonFocusedTab()"); - framework.endTest(); + WebXrVrTestFramework.executeStepAndWait( + "stepCheckFrameDataWhileNonFocusedTab()", firstTabContents); + WebXrVrTestFramework.endTest(firstTabContents); } /** @@ -140,9 +141,8 @@ // Be sure to store the stream we're given so that the permission is actually in use, as // otherwise the toast doesn't show up since another tab isn't actually using the // permission. - WebXrVrTestFramework.runJavaScriptOrFail( - "requestPermission({audio:true}, true /* storeValue */)", POLL_TIMEOUT_SHORT_MS, - mTestRule.getWebContents()); + mWebXrVrTestFramework.runJavaScriptOrFail( + "requestPermission({audio:true}, true /* storeValue */)", POLL_TIMEOUT_SHORT_MS); // Accept the permission prompt. Standalone devices need to be special cased since they // will be in the VR Browser. @@ -157,14 +157,10 @@ PermissionUtils.acceptPermissionPrompt(); } - WebXrVrTestFramework.waitOnJavaScriptStep(mTestRule.getWebContents()); + mWebXrVrTestFramework.waitOnJavaScriptStep(); if (incognito) { - ThreadUtils.runOnUiThreadBlocking(() -> { - mTestRule.getActivity() - .getTabCreator(true /* incognito */) - .launchUrl("about:blank", TabLaunchType.FROM_LINK); - }); + mWebXrVrTestFramework.openIncognitoTab("about:blank"); } else { mTestRule.loadUrlInNewTab("about:blank"); } @@ -172,7 +168,7 @@ mWebXrVrTestFramework.loadUrlAndAwaitInitialization( WebXrVrTestFramework.getFileUrlForHtmlTestFile("generic_webxr_page"), PAGE_LOAD_TIMEOUT_S); - mWebXrVrTestFramework.enterSessionWithUserGestureOrFail(mTestRule.getWebContents()); + mWebXrVrTestFramework.enterSessionWithUserGestureOrFail(); NativeUiUtils.performActionAndWaitForVisibilityStatus( UserFriendlyElementName.WEB_XR_AUDIO_INDICATOR, true /* visible */, () -> {}); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/XrTestFramework.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/XrTestFramework.java index 59041862..43b7a48 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/XrTestFramework.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/XrTestFramework.java
@@ -81,8 +81,6 @@ } private ChromeActivityTestRule mRule; - protected WebContents mFirstTabWebContents; - private View mFirstTabContentView; /** * Gets the file:// URL to the test file. @@ -374,8 +372,6 @@ */ public XrTestFramework(ChromeActivityTestRule rule) { mRule = rule; - mFirstTabWebContents = mRule.getWebContents(); - mFirstTabContentView = mRule.getActivity().getActivityTab().getContentView(); } /** @@ -405,125 +401,125 @@ } /** - * Helper method to run permissionRequestWouldTriggerPrompt with the first tab's WebContents. + * Helper method to run permissionRequestWouldTriggerPrompt with the current tab's WebContents. * * @param permission The name of the permission to check. * @return True if the permission request would trigger a prompt, false otherwise. */ public boolean permissionRequestWouldTriggerPrompt(String permission) { - return permissionRequestWouldTriggerPrompt(permission, mFirstTabWebContents); + return permissionRequestWouldTriggerPrompt(permission, getCurrentWebContents()); } /** - * Helper method to run runJavaScriptOrFail with the first tab's WebContents. + * Helper method to run runJavaScriptOrFail with the current tab's WebContents. * * @param js The JavaScript to run. * @param timeout The timeout in milliseconds before a failure. * @return The return value of the JavaScript. */ public String runJavaScriptOrFail(String js, int timeout) { - return runJavaScriptOrFail(js, timeout, mFirstTabWebContents); + return runJavaScriptOrFail(js, timeout, getCurrentWebContents()); } /** - * Helper method to run runJavaScriptInFrameOrFail with the first tab's WebContents. + * Helper method to run runJavaScriptInFrameOrFail with the current tab's WebContents. * * @param js The JavaScript to run. * @param timeout The timeout in milliseconds before a failure. * @return The return value of the JavaScript. */ public String runJavaScriptInFrameOrFail(String js, int timeout) { - return runJavaScriptInFrameOrFail(js, timeout, mFirstTabWebContents); + return runJavaScriptInFrameOrFail(js, timeout, getCurrentWebContents()); } /** - * Helper function to run pollJavaScriptBoolean with the first tab's WebContents. + * Helper function to run pollJavaScriptBoolean with the current tab's WebContents. * * @param boolExpression The JavaScript boolean expression to poll. * @param timeoutMs The polling timeout in milliseconds. * @return True if the boolean evaluated to true, false if timed out. */ public boolean pollJavaScriptBoolean(String boolExpression, int timeoutMs) { - return pollJavaScriptBoolean(boolExpression, timeoutMs, mFirstTabWebContents); + return pollJavaScriptBoolean(boolExpression, timeoutMs, getCurrentWebContents()); } /** - * Helper function to run pollJavaScriptBooleanInFrame with the first tab's WebContents. + * Helper function to run pollJavaScriptBooleanInFrame with the current tab's WebContents. * * @param boolExpression The JavaScript boolean expression to poll. * @param timeoutMs The polling timeout in milliseconds. * @return True if the boolean evaluated to true, false if timed out. */ public boolean pollJavaScriptInFrameBoolean(String boolExpression, int timeoutMs) { - return pollJavaScriptBooleanInFrame(boolExpression, timeoutMs, mFirstTabWebContents); + return pollJavaScriptBooleanInFrame(boolExpression, timeoutMs, getCurrentWebContents()); } /** - * Helper function to run pollJavaScriptBooleanOrFail with the first tab's WebContents. + * Helper function to run pollJavaScriptBooleanOrFail with the current tab's WebContents. * * @param boolExpression The JavaScript boolean expression to poll. * @param timeoutMs The polling timeout in milliseconds. */ public void pollJavaScriptBooleanOrFail(String boolExpression, int timeoutMs) { - pollJavaScriptBooleanOrFail(boolExpression, timeoutMs, mFirstTabWebContents); + pollJavaScriptBooleanOrFail(boolExpression, timeoutMs, getCurrentWebContents()); } /** - * Helper function to run pollJavaScriptBooleanInFrameOrFail with the first tab's WebContents. + * Helper function to run pollJavaScriptBooleanInFrameOrFail with the current tab's WebContents. * * @param boolExpression The JavaScript boolean expression to poll. * @param timeoutMs The polling timeout in milliseconds. */ public void pollJavaScriptBooleanInFrameOrFail(String boolExpression, int timeoutMs) { - pollJavaScriptBooleanInFrameOrFail(boolExpression, timeoutMs, mFirstTabWebContents); + pollJavaScriptBooleanInFrameOrFail(boolExpression, timeoutMs, getCurrentWebContents()); } /** - * Helper function to run executeStepAndWait using the first tab's WebContents. + * Helper function to run executeStepAndWait using the current tab's WebContents. * * @param stepFunction The JavaScript step function to call. */ public void executeStepAndWait(String stepFunction) { - executeStepAndWait(stepFunction, mFirstTabWebContents); + executeStepAndWait(stepFunction, getCurrentWebContents()); } /** - * Helper function to run waitOnJavaScriptStep with the first tab's WebContents. + * Helper function to run waitOnJavaScriptStep with current current tab's WebContents. */ public void waitOnJavaScriptStep() { - waitOnJavaScriptStep(mFirstTabWebContents); + waitOnJavaScriptStep(getCurrentWebContents()); } /** - * Helper method to run checkTestSTatus with the first tab's WebContents. + * Helper method to run checkTestSTatus with the current tab's WebContents. * * @return A TestStatus integer corresponding to the current state of the JavaScript test. */ @TestStatus public int checkTestStatus() { - return checkTestStatus(mFirstTabWebContents); + return checkTestStatus(getCurrentWebContents()); } /** - * Helper function to run endTest with the first tab's WebContents. + * Helper function to run endTest with the current tab's WebContents. */ public void endTest() { - endTest(mFirstTabWebContents); + endTest(getCurrentWebContents()); } /** - * Helper function to run assertNoJavaScriptErrors with the first tab's WebContents. + * Helper function to run assertNoJavaScriptErrors with the current tab's WebContents. */ public void assertNoJavaScriptErrors() { - assertNoJavaScriptErrors(mFirstTabWebContents); + assertNoJavaScriptErrors(getCurrentWebContents()); } - public View getFirstTabContentView() { - return mFirstTabContentView; + public View getCurrentContentView() { + return mRule.getActivity().getActivityTab().getContentView(); } - public WebContents getFirstTabWebContents() { - return mFirstTabWebContents; + public WebContents getCurrentWebContents() { + return mRule.getWebContents(); } public ChromeActivityTestRule getRule() {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/util/NativeUiUtils.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/util/NativeUiUtils.java index efc9a6ea..cbdc575b 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/util/NativeUiUtils.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/util/NativeUiUtils.java
@@ -168,7 +168,7 @@ */ public static void clickContentNode(String nodeId, PointF position, final int numClicks, VrBrowserTestFramework testFramework) throws InterruptedException, TimeoutException { - Rect nodeBounds = DOMUtils.getNodeBounds(testFramework.getFirstTabWebContents(), nodeId); + Rect nodeBounds = DOMUtils.getNodeBounds(testFramework.getCurrentWebContents(), nodeId); int contentWidth = Integer.valueOf( testFramework.runJavaScriptOrFail("window.innerWidth", POLL_TIMEOUT_SHORT_MS)); int contentHeight = Integer.valueOf(
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/xr_instrumentation_deep_dive.md b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/xr_instrumentation_deep_dive.md index 5b06471..7cce3d7 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/xr_instrumentation_deep_dive.md +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/xr_instrumentation_deep_dive.md
@@ -49,11 +49,11 @@ Most methods in the `TestFramework` classes have both a static and non-static version, with the non-static version simply calling the static one with the framework's `mFirstTabWebContents` reference. This is because the vast majority -of use cases are interacting with the web page that is in the tab automatically -opened at the start of the test, but some rare cases require interacting with -other tabs. Thus, we need to provide a way of using the frameworks with -arbitrary tabs/`WebContents` (the static methods), but offering the non-static -versions cuts down the clutter of calling `getFirstTabWebContents()` everywhere. +of use cases are interacting with the web page that is in the current tab, but +some rare cases require interacting with other tabs. Thus, we need to provide a +way of using the frameworks with arbitrary tabs/`WebContents` +(the static methods), but offering the non-static versions cuts down the clutter +of calling `getCurrentWebContents()` everywhere. ## Parameterization
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridgeTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridgeTest.java new file mode 100644 index 0000000..7861ab1 --- /dev/null +++ b/chrome/android/junit/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridgeTest.java
@@ -0,0 +1,122 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.send_tab_to_self; + +import static org.mockito.AdditionalAnswers.answerVoid; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyLong; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.support.test.filters.SmallTest; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.stubbing.VoidAnswer3; +import org.robolectric.annotation.Config; + +import org.chromium.base.test.BaseRobolectricTestRunner; +import org.chromium.base.test.util.JniMocker; +import org.chromium.chrome.browser.profiles.Profile; + +import java.util.List; + +/** Tests for SendTabToSelfAndroidBridge */ +@RunWith(BaseRobolectricTestRunner.class) +@Config(manifest = Config.NONE) +public class SendTabToSelfAndroidBridgeTest { + @Rule + public JniMocker mocker = new JniMocker(); + + @Mock + SendTabToSelfAndroidBridge.Natives mNativeMock; + private Profile mProfile; + + private SendTabToSelfAndroidBridge mBridge; + private static final String GUID = "randomguid"; + private static final String URL = "http://www.tanyastacos.com"; + private static final String TITLE = "Come try Tanya's famous tacos"; + private static final String DEVICE_NAME = "Macbook Pro"; + private static final long NAVIGATION_TIME_MS = 123l; + private static final long SHARE_TIME_MS = 456l; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + mocker.mock(SendTabToSelfAndroidBridgeJni.TEST_HOOKS, mNativeMock); + + mBridge = new SendTabToSelfAndroidBridge(mProfile); + verify(mNativeMock).init(any(SendTabToSelfAndroidBridge.class), eq(mProfile)); + } + + @Test + @SmallTest + public void testAddEntry() { + mBridge.addEntry(URL, TITLE, NAVIGATION_TIME_MS); + verify(mNativeMock) + .addEntry(any(SendTabToSelfAndroidBridge.class), anyLong(), eq(URL), eq(TITLE), + eq(NAVIGATION_TIME_MS)); + } + + @Test + @SmallTest + @SuppressWarnings("unchecked") + public void testGetAllGuids() { + doAnswer(answerVoid(new VoidAnswer3<SendTabToSelfAndroidBridge, Long, List<String>>() { + @Override + public void answer(SendTabToSelfAndroidBridge bridge, Long nativeBridgeAddress, + List<String> guids) { + guids.add("one"); + guids.add("two"); + guids.add("three"); + } + })) + .when(mNativeMock) + .getAllGuids(any(SendTabToSelfAndroidBridge.class), anyLong(), any(List.class)); + + List<String> actual = mBridge.getAllGuids(); + + verify(mNativeMock) + .getAllGuids(any(SendTabToSelfAndroidBridge.class), anyLong(), any(List.class)); + Assert.assertEquals(3, actual.size()); + Assert.assertArrayEquals(new String[] {"one", "two", "three"}, actual.toArray()); + } + + @Test + @SmallTest + public void testGetEntryByGUID() { + SendTabToSelfEntry expected = new SendTabToSelfEntry( + GUID, URL, TITLE, SHARE_TIME_MS, NAVIGATION_TIME_MS, DEVICE_NAME); + when(mNativeMock.getEntryByGUID( + any(SendTabToSelfAndroidBridge.class), anyLong(), anyString())) + .thenReturn(expected); + // Note that the GUID passed in this function does not match the GUID of the returned entry. + // This is okay because the purpose of the test is to make sure that the JNI layer passes + // the entry returned by the native code. The native code does the actual matching of + // the GUID but since that is mocked out and not the purpose of the test, this is fine. + SendTabToSelfEntry actual = mBridge.getEntryByGUID("guid"); + Assert.assertEquals(expected.guid, actual.guid); + Assert.assertEquals(expected.url, actual.url); + Assert.assertEquals(expected.title, actual.title); + Assert.assertEquals(expected.sharedTime, actual.sharedTime); + Assert.assertEquals(expected.originalNavigationTime, actual.originalNavigationTime); + Assert.assertEquals(expected.deviceName, actual.deviceName); + } + + @Test + @SmallTest + public void testDeleteAllEntries() { + mBridge.deleteAllEntries(); + verify(mNativeMock).deleteAllEntries(any(SendTabToSelfAndroidBridge.class), anyLong()); + } +}
diff --git a/chrome/app/file_manager_strings.grdp b/chrome/app/file_manager_strings.grdp index d1a3cd2a..a5a3514 100644 --- a/chrome/app/file_manager_strings.grdp +++ b/chrome/app/file_manager_strings.grdp
@@ -68,9 +68,6 @@ <message name="IDS_FILE_BROWSER_MY_FILES_ROOT_LABEL" desc="A label for the 'My files' root which is parent of Downloads, Linux and Android files. Use sentence case."> My files </message> - <message name="IDS_FILE_BROWSER_EXTERNAL_STORAGE_ROOT_LABEL" desc="A label for external USB storage. Use sentence case."> - External storage - </message> <message name="IDS_FILE_BROWSER_MEDIA_VIEW_IMAGES_ROOT_LABEL" desc="A label for the 'Images' root of media views."> Images </message>
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index fd6a571..e823d3b 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -6340,9 +6340,16 @@ <!-- Managed UI on pages like chrome://settings and chrome://downloads --> <if expr="not is_android"> - <message name="IDS_MANAGED_BY_ORG_WITH_HYPERLINK"> - Your <ph name="BEGIN_LINK"><a target="_blank" href="$1"></ph>browser is managed<ph name="END_LINK"></a></ph> by your organization - </message> + <if expr="chromeos"> + <message name="IDS_MANAGED_BY_ORG_WITH_HYPERLINK" desc="Message to end users in Enterprise/EDU, with a link for more info (ChromeOS)"> + Your <ph name="BEGIN_LINK"><a target="_blank" href="$1"></ph><ph name="DEVICE_TYPE">$2<ex>Chromebook</ex></ph> is managed<ph name="END_LINK"></a></ph> by your organization + </message> + </if> + <if expr="not chromeos"> + <message name="IDS_MANAGED_BY_ORG_WITH_HYPERLINK" desc="Message to end users in Enterprise/EDU, with a link for more info (non-ChromeOS)"> + Your <ph name="BEGIN_LINK"><a target="_blank" href="$1"></ph>browser is managed<ph name="END_LINK"></a></ph> by your organization + </message> + </if> </if> <!-- Cookies Window --> @@ -6723,7 +6730,7 @@ Google may use your history to personalize Search, ads, and other Google services </message> <message name="IDS_SYNC_CONFIRMATION_UNITY_SETTINGS_INFO" desc="Information about customizing Sync settings in the sync confirmation dialog when Unity is enabled"> - You can customize these settings anytime + You can always choose what to sync in settings </message> <!-- "Chrome sync" is the Google Cloud Based service used for sync. Thus this string resource is set to "Chrome sync" even for Chromium builds. --> @@ -9218,17 +9225,14 @@ <message name="IDS_WEBAUTHN_ERROR_GENERIC_TITLE" desc="Title of most dialogs shown when an error occurs while the user trying to sign in to a web site using a hardware-based authentication mechanism."> Something went wrong </message> - <message name="IDS_WEBAUTHN_ERROR_WRONG_KEY_REGISTER_TITLE" desc="Title of the dialog informing the user that they are trying to register a security key (an external physical device for user authentication) that they have already registered with the given web site before." meaning="Here, `key` refers to a security key, an external physical device for user authentication."> - Try a different key + <message name="IDS_WEBAUTHN_ERROR_WRONG_KEY_TITLE" desc="Title of the dialog informing the user that they are trying to register a security key (an external physical device for user authentication) that they have already registered with the given web site before or they are trying to sign in to a given web site with a key they have not previously registered on that site."> + Try a different security key </message> - <message name="IDS_WEBAUTHN_ERROR_WRONG_KEY_REGISTER_DESCRIPTION" desc="Description in the dialog informing the user that they are trying to register a security key (an external physical device for user authentication) that they have already registered with the given web site before." meaning="Here, `key` refers to a security key, an external physical device for user authentication."> - You already registered this key before. You don't have to register it again. + <message name="IDS_WEBAUTHN_ERROR_WRONG_KEY_REGISTER_DESCRIPTION" desc="Description in the dialog informing the user that they are trying to register a security key (an external physical device for user authentication) that they have already registered with the given web site before."> + You already registered this security key. You don't have to register it again. </message> - <message name="IDS_WEBAUTHN_ERROR_WRONG_KEY_SIGN_TITLE" desc="Title of the dialog informing the user that they are trying to use the wrong security key (an external physical device for user authentication) to sign in to a given web site, that is, not the one they have previously registered on that site." meaning="Here, `key` refers to a security key, an external physical device for user authentication."> - Try a different key - </message> - <message name="IDS_WEBAUTHN_ERROR_WRONG_KEY_SIGN_DESCRIPTION" desc="Description in the dialog informing the user that they are trying to use the wrong security key (an external physical device for user authentication) to sign in to a given web site, that is, not the one they have previously registered on that site." meaning="Here, `key` refers to a security key, an external physical device for user authentication."> - You're using a key that's not registered with this website + <message name="IDS_WEBAUTHN_ERROR_WRONG_KEY_SIGN_DESCRIPTION" desc="Description in the dialog informing the user that they are trying to use the wrong security key (an external physical device for user authentication) to sign in to a given web site, that is, not the one they have previously registered on that site."> + You're using a security key that's not registered with this website </message> <message name="IDS_WEBAUTHN_ERROR_TIMEOUT_DESCRIPTION" desc="Description in the dialog shown when the user takes too long to sign in to a web site using a hardware-based authentication mechanism."> The request timed out @@ -9266,8 +9270,8 @@ <message name="IDS_WEBAUTHN_BLE_PAIRING_BEGIN_TITLE" desc="Title of the dialog explaining to the user that they first need to pair a Bluetooth security key (an external physical device for user authentication) with their computer, and only after they can use it to sign in to web sites on their computer."> Ready to pair your security key? </message> - <message name="IDS_WEBAUTHN_BLE_PAIRING_BEGIN_DESCRIPTION" desc="Description in the dialog explaining to the user that they first need to pair a Bluetooth security key (an external physical device for user authentication) with their computer, and only after they can use it to sign in to web sites on their computer." meaning="Here, `key` refers to a security key, an external physical device for user authentication."> - Pair your key to this device so you can use it to sign into your account + <message name="IDS_WEBAUTHN_BLE_PAIRING_BEGIN_DESCRIPTION" desc="Description in the dialog explaining to the user that they first need to pair a Bluetooth security key (an external physical device for user authentication) with their computer, and only after they can use it to sign in to web sites on their computer."> + Pair your security key to this device so you can use it to sign into your account </message> <message name="IDS_WEBAUTHN_BLE_PAIRING_BEGIN_NEXT" desc="Button text to initiate pairing of a Bluetooth security key with their computer."> Begin @@ -9281,20 +9285,20 @@ <message name="IDS_WEBAUTHN_BLE_DEVICE_SELECTION_TITLE" desc="Title of the dialog instructing the user to select their Bluetooth security key (an external physical device for user authentication) from a list of nearby Bluetooth devices. The user can identify their security key in the list by the name printed on the back of the security key."> Select your security key </message> - <message name="IDS_WEBAUTHN_BLE_DEVICE_SELECTION_DESCRIPTION" desc="Description in the dialog instructing the user to select their Bluetooth security key (an external physical device for user authentication) from a list of nearby Bluetooth devices. The user can identify their security key in the list by the name printed on the back of the security key." meaning="Here, `key` refers to a security key, an external physical device for user authentication."> - Find the name printed on the back of your key + <message name="IDS_WEBAUTHN_BLE_DEVICE_SELECTION_DESCRIPTION" desc="Description in the dialog instructing the user to select their Bluetooth security key (an external physical device for user authentication) from a list of nearby Bluetooth devices. The user can identify their security key in the list by the name printed on the back of the security key."> + Find the name printed on the back of your security key </message> <message name="IDS_WEBAUTHN_BLE_DEVICE_SELECTION_SEARCHING_LABEL" desc="Label text. Displayed while Chrome is scanning for nearby Bluetooth devices."> Searching... </message> - <message name="IDS_WEBAUTHN_BLE_DEVICE_SELECTION_REMINDER_LABEL" desc="Label text. Reminds the user that their Bluetooth security key (an external physical device for user authentication) will only show up in the list of nearby Bluetooth devices if they put it into pairing mode. This is achieved by holding down the button on the device for 5 seconds, or longer." meaning="Here, `key` refers to a security key, an external physical device for user authentication."> - If your security key isn't listed, press the key's button for at least 5 seconds. + <message name="IDS_WEBAUTHN_BLE_DEVICE_SELECTION_REMINDER_LABEL" desc="Label text. Reminds the user that their Bluetooth security key (an external physical device for user authentication) will only show up in the list of nearby Bluetooth devices if they put it into pairing mode. This is achieved by holding down the button on the device for 5 seconds, or longer."> + If your security key isn't listed, press its button for at least 5 seconds. </message> <message name="IDS_WEBAUTHN_BLE_PIN_ENTRY_TITLE" desc="Title of the dialog shown when instructing the user to enter the PIN code (a 6-digit number) to pair a Bluetooth security key (an external physical device for user authentication) with their computer."> Pair with <ph name="DEVICE_NAME">$1<ex>VHGSHSSN</ex></ph> </message> - <message name="IDS_WEBAUTHN_BLE_PIN_ENTRY_DESCRIPTION" desc="Description in the dialog shown when instructing the user to enter the PIN code to pair a Bluetooth security key (an external physical device for user authentication) with their computer. The PIN code is a 6-digit secret number written on the back of the device." meaning="Here, `key` refers to a security key, an external physical device for user authentication."> - Find the 6-digit PIN on the back of your key + <message name="IDS_WEBAUTHN_BLE_PIN_ENTRY_DESCRIPTION" desc="Description in the dialog shown when instructing the user to enter the PIN code to pair a Bluetooth security key (an external physical device for user authentication) with their computer. The PIN code is a 6-digit secret number written on the back of the device."> + Find the 6-digit PIN on the back of your security key </message> <message name="IDS_WEBAUTHN_BLE_PIN_ENTRY_PIN_LABEL" desc="Label text. Displayed next to a text box where the user enters the PIN code (a 6-digit number) to pair a Bluetooth device."> Pin @@ -9302,17 +9306,11 @@ <message name="IDS_WEBAUTHN_BLE_PIN_ENTRY_NEXT" desc="Button text. The user clicks this button once they have entered the PIN code (a 6-digit number) into a text vbox, so that the pairing of the Bluetooth device can continue."> Next </message> - <message name="IDS_WEBAUTHN_BLE_OS_PIN_ENTRY_TITLE" desc="Description in the dialog instructing the user to enter the PIN code to pair a Bluetooth security key (an external physical device for user authentication) with their computer. The PIN code is a 6-digit secret number written on the back of the device." meaning="Here, `key` refers to a security key, an external physical device for user authentication."> - Find the 6-digit PIN on the back of your key - </message> - <message name="IDS_WEBAUTHN_BLE_OS_PIN_ENTRY_DESCRIPTION" desc="Description in the drepresenting using the user's phone as a physical device that is connected to the user's computer over Bluetooth Low Energy to authenticate the user on the web.ialog shown when instructing the user to enter the PIN code to pair a Bluetooth security key (an external physical device for user authentication)."> - Continue when you're ready to enter the PIN - </message> <message name="IDS_WEBAUTHN_BLE_VERIFYING_TITLE" desc="Title of the dialog informing the user that verifying a Bluetooth security key (an external physical device for user authentication) is in progress."> Verifying your security key... </message> - <message name="IDS_WEBAUTHN_BLE_ACTIVATE_DESCRIPTION" desc="Description in the dialog instructing the user to activate (e.g. press a button on) their Bluetooth security key (an external physical device for user authentication)." meaning="Here, `key` refers to a security key, an external physical device for user authentication."> - To use most keys, simply press the button + <message name="IDS_WEBAUTHN_BLE_ACTIVATE_DESCRIPTION" desc="Description in the dialog instructing the user to activate (e.g. press a button on) their Bluetooth security key (an external physical device for user authentication)."> + Press the button on the security key </message> <message name="IDS_WEBAUTHN_TRANSPORT_POPUP_LABEL" desc="Menu item text. The user selects this to verify their identity on a web site (i.e. sign in) using a different hardware-based authentication mechanism from what they have selected previously."> Choose another option @@ -9339,7 +9337,7 @@ Check your phone </message> <message name="IDS_WEBAUTHN_CABLE_ACTIVATE_DESCRIPTION" desc="Contents of the dialog shown when the user tries to sign-in using a phone as a security key."> - A notification was sent to your phone. Follow the prompts to confirm it's you. + A notification was sent to your phone to confirm it's you. </message> <message name="IDS_WEBAUTHN_PIN_ENTRY_TITLE" desc="Title of the dialog shown when instructing the user to enter the PIN code to use a security key (an external physical device for user authentication) with their computer."> PIN required @@ -9375,17 +9373,17 @@ </message> </if> - <!-- Incognito Window Counter bubble. --> - <message name="IDS_INCOGNITO_WINDOW_COUNTER_TITLE" desc="The title of the incognito window counter dialog."> + <!-- Incognito Profile Menu bubble. --> + <message name="IDS_INCOGNITO_PROFILE_MENU_TITLE" desc="The title of the incognito version of profile menu."> Incognito </message> - <message name="IDS_INCOGNITO_WINDOW_COUNTER_MESSAGE" desc="The message showing the number of open incogntio windows. This is not used for zero windows.[ICU Syntax]"> + <message name="IDS_INCOGNITO_WINDOW_COUNT_MESSAGE" desc="The message showing the number of open incogntio windows. This is not used for zero windows.[ICU Syntax]"> {0, plural, =1 {# open window} other {# open windows} } </message> - <message name="IDS_INCOGNITO_WINDOW_COUNTER_CLOSE_BUTTON" desc="The text of the button offering to close all incognito windows."> + <message name="IDS_INCOGNITO_PROFILE_MENU_CLOSE_BUTTON" desc="The text of the button offering to close all incognito windows."> Exit Incognito </message> </messages>
diff --git a/chrome/app/generated_resources_grd/IDS_SYNC_CONFIRMATION_UNITY_SETTINGS_INFO.png.sha1 b/chrome/app/generated_resources_grd/IDS_SYNC_CONFIRMATION_UNITY_SETTINGS_INFO.png.sha1 new file mode 100644 index 0000000..6a66ac5e --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_SYNC_CONFIRMATION_UNITY_SETTINGS_INFO.png.sha1
@@ -0,0 +1 @@ +ea64609f6b5e30252cf467ee2dbf3b0b6c580d2a \ No newline at end of file
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index c9132572..991e192 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -1110,16 +1110,14 @@ "performance_manager/system_resource_coordinator.h", "performance_manager/webui_graph_dump_impl.cc", "performance_manager/webui_graph_dump_impl.h", + "performance_monitor/metric_evaluator_helper_win.cc", + "performance_monitor/metric_evaluator_helper_win.h", "performance_monitor/process_metrics_history.cc", "performance_monitor/process_metrics_history.h", "performance_monitor/process_monitor.cc", "performance_monitor/process_monitor.h", "performance_monitor/system_monitor.cc", "performance_monitor/system_monitor.h", - "performance_monitor/system_monitor_helper_posix.cc", - "performance_monitor/system_monitor_helper_posix.h", - "performance_monitor/system_monitor_helper_win.cc", - "performance_monitor/system_monitor_helper_win.h", "permissions/chooser_context_base.cc", "permissions/chooser_context_base.h", "permissions/permission_context_base.cc", @@ -1209,8 +1207,6 @@ "policy/schema_registry_service.h", "policy/schema_registry_service_factory.cc", "policy/schema_registry_service_factory.h", - "policy/webusb_allow_devices_for_urls_policy_handler.cc", - "policy/webusb_allow_devices_for_urls_policy_handler.h", "predictors/autocomplete_action_predictor.cc", "predictors/autocomplete_action_predictor.h", "predictors/autocomplete_action_predictor_factory.cc", @@ -2094,6 +2090,8 @@ "download/trusted_sources_manager_posix.cc", "google/google_update_settings_posix.cc", "net/net_error_diagnostics_dialog_posix.cc", + "performance_monitor/metric_evaluator_helper_posix.cc", + "performance_monitor/metric_evaluator_helper_posix.h", ] } @@ -2480,6 +2478,8 @@ "android/search_permissions/search_permissions_service.h", "android/seccomp_support_detector.cc", "android/seccomp_support_detector.h", + "android/send_tab_to_self/send_tab_to_self_android_bridge.cc", + "android/send_tab_to_self/send_tab_to_self_android_bridge.h", "android/service_tab_launcher.cc", "android/service_tab_launcher.h", "android/sessions/session_tab_helper_android.cc", @@ -2701,6 +2701,7 @@ "//components/omnibox/browser", "//components/payments/content/android", "//components/resources:components_resources", + "//components/send_tab_to_self", "//media/mojo/clients", "//media/mojo/interfaces:constants", "//rlz:rlz_utils", @@ -2970,6 +2971,8 @@ "permissions/attestation_permission_request.h", "policy/local_sync_policy_handler.cc", "policy/local_sync_policy_handler.h", + "policy/webusb_allow_devices_for_urls_policy_handler.cc", + "policy/webusb_allow_devices_for_urls_policy_handler.h", "process_singleton_modal_dialog_lock.cc", "process_singleton_modal_dialog_lock.h", "process_singleton_startup_lock.cc", @@ -5093,6 +5096,8 @@ "../android/java/src/org/chromium/chrome/browser/rlz/RlzPingHandler.java", "../android/java/src/org/chromium/chrome/browser/search_engines/TemplateUrl.java", "../android/java/src/org/chromium/chrome/browser/search_engines/TemplateUrlService.java", + "../android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridge.java", + "../android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfEntry.java", "../android/java/src/org/chromium/chrome/browser/sessions/SessionTabHelper.java", "../android/java/src/org/chromium/chrome/browser/signin/AccountManagementScreenHelper.java", "../android/java/src/org/chromium/chrome/browser/signin/IdentityServicesProvider.java", @@ -5485,6 +5490,7 @@ "android/download/mock_download_controller.cc", "android/download/mock_download_controller.h", ] + deps += [ "//chrome/android:test_support_jni_headers" ] } else { sources += [ "chooser_controller/fake_bluetooth_chooser_controller.cc",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index e0d7ee3..e34b693 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -1440,10 +1440,6 @@ kOsWin | kOsLinux | kOsCrOS | kOsAndroid, SINGLE_DISABLE_VALUE_TYPE(switches::kDisableTouchAdjustment)}, #if defined(OS_CHROMEOS) - {"enable-captive-portal-random-url", - flag_descriptions::kEnableCaptivePortalRandomUrl, - flag_descriptions::kEnableCaptivePortalRandomUrlDescription, kOsCrOS, - SINGLE_VALUE_TYPE(chromeos::switches::kEnableCaptivePortalRandomUrl)}, {"enable-explicit-dma-fences", flag_descriptions::kEnableExplicitDmaFencesName, flag_descriptions::kEnableExplicitDmaFencesDescription, kOsCrOS, @@ -1681,9 +1677,6 @@ flag_descriptions::kVirtualKeyboardOverscrollDescription, kOsCrOS, SINGLE_DISABLE_VALUE_TYPE( keyboard::switches::kDisableVirtualKeyboardOverscroll)}, - {"input-view", flag_descriptions::kInputViewName, - flag_descriptions::kInputViewDescription, kOsCrOS, - SINGLE_DISABLE_VALUE_TYPE(keyboard::switches::kDisableInputView)}, {"enable-physical-keyboard-autocorrect", flag_descriptions::kPhysicalKeyboardAutocorrectName, flag_descriptions::kPhysicalKeyboardAutocorrectDescription, kOsCrOS, @@ -1882,11 +1875,6 @@ flag_descriptions::kReducedReferrerGranularityDescription, kOsAll, SINGLE_VALUE_TYPE(switches::kReducedReferrerGranularity)}, #if defined(OS_CHROMEOS) - {"disable-new-zip-unpacker", flag_descriptions::kNewZipUnpackerName, - flag_descriptions::kNewZipUnpackerDescription, kOsCrOS, - SINGLE_DISABLE_VALUE_TYPE(chromeos::switches::kDisableNewZIPUnpacker)}, -#endif // OS_CHROMEOS -#if defined(OS_CHROMEOS) {"crostini-backup", flag_descriptions::kCrostiniBackupName, flag_descriptions::kCrostiniBackupDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kCrostiniBackup)}, @@ -3011,6 +2999,12 @@ flag_descriptions::kOmniboxUISwapTitleAndUrlDescription, kOsDesktop, FEATURE_VALUE_TYPE(omnibox::kUIExperimentSwapTitleAndUrl)}, + {"omnibox-ui-blue-search-loop-and-search-query", + flag_descriptions::kOmniboxUIBlueSearchLoopAndSearchQueryName, + flag_descriptions::kOmniboxUIBlueSearchLoopAndSearchQueryDescription, + kOsDesktop, + FEATURE_VALUE_TYPE(omnibox::kUIExperimentBlueSearchLoopAndSearchQuery)}, + {"omnibox-ui-use-generic-search-engine-icon", flag_descriptions::kOmniboxUIUseGenericSearchEngineIconName, flag_descriptions::kOmniboxUIUseGenericSearchEngineIconDescription,
diff --git a/chrome/browser/android/autofill_assistant/ui_controller_android.cc b/chrome/browser/android/autofill_assistant/ui_controller_android.cc index 8cd2545..580b441 100644 --- a/chrome/browser/android/autofill_assistant/ui_controller_android.cc +++ b/chrome/browser/android/autofill_assistant/ui_controller_android.cc
@@ -423,19 +423,21 @@ return; } - const DetailsProto& proto = details->proto; + const DetailsProto& proto = details->proto().details(); + const DetailsChangesProto& changes = details->proto().change_flags(); auto jdetails = Java_AssistantDetails_create( env, base::android::ConvertUTF8ToJavaString(env, proto.title()), - base::android::ConvertUTF8ToJavaString(env, proto.url()), - base::android::ConvertUTF8ToJavaString(env, proto.description()), - base::android::ConvertUTF8ToJavaString(env, proto.m_id()), + base::android::ConvertUTF8ToJavaString(env, proto.image_url()), + base::android::ConvertUTF8ToJavaString(env, proto.total_price_label()), base::android::ConvertUTF8ToJavaString(env, proto.total_price()), - base::android::ConvertUTF8ToJavaString(env, details->datetime), + base::android::ConvertUTF8ToJavaString(env, details->GetDatetime()), proto.datetime().date().year(), proto.datetime().date().month(), proto.datetime().date().day(), proto.datetime().time().hour(), proto.datetime().time().minute(), proto.datetime().time().second(), - details->changes.user_approval_required(), - details->changes.highlight_title(), details->changes.highlight_date()); + base::android::ConvertUTF8ToJavaString(env, proto.description_line1()), + base::android::ConvertUTF8ToJavaString(env, proto.description_line2()), + changes.user_approval_required(), changes.highlight_title(), + changes.highlight_line1(), changes.highlight_line2()); Java_AssistantDetailsModel_setDetails(env, jmodel, jdetails); }
diff --git a/chrome/browser/android/chrome_feature_list.cc b/chrome/browser/android/chrome_feature_list.cc index dc351700..f889321e 100644 --- a/chrome/browser/android/chrome_feature_list.cc +++ b/chrome/browser/android/chrome_feature_list.cc
@@ -156,6 +156,7 @@ &kSoleIntegration, &kSpannableInlineAutocomplete, &kSpecialLocaleWrapper, + &kTabGroupsAndroid, &kTabGridLayoutAndroid, &kTabReparenting, &kTabSwitcherOnReturn, @@ -447,6 +448,9 @@ const base::Feature kSpecialLocaleWrapper{"SpecialLocaleWrapper", base::FEATURE_ENABLED_BY_DEFAULT}; +const base::Feature kTabGroupsAndroid{"TabGroupsAndroid", + base::FEATURE_DISABLED_BY_DEFAULT}; + const base::Feature kTabGridLayoutAndroid{"TabGridLayoutAndroid", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/chrome/browser/android/chrome_feature_list.h b/chrome/browser/android/chrome_feature_list.h index 93796ca4..6fa358f 100644 --- a/chrome/browser/android/chrome_feature_list.h +++ b/chrome/browser/android/chrome_feature_list.h
@@ -88,6 +88,7 @@ extern const base::Feature kSoleIntegration; extern const base::Feature kSpannableInlineAutocomplete; extern const base::Feature kSpecialLocaleWrapper; +extern const base::Feature kTabGroupsAndroid; extern const base::Feature kTabGridLayoutAndroid; extern const base::Feature kTabReparenting; extern const base::Feature kTabSwitcherOnReturn;
diff --git a/chrome/browser/android/send_tab_to_self/send_tab_to_self_android_bridge.cc b/chrome/browser/android/send_tab_to_self/send_tab_to_self_android_bridge.cc new file mode 100644 index 0000000..f50fedb --- /dev/null +++ b/chrome/browser/android/send_tab_to_self/send_tab_to_self_android_bridge.cc
@@ -0,0 +1,129 @@ +// 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/android/send_tab_to_self/send_tab_to_self_android_bridge.h" + +#include <string> +#include <vector> + +#include "base/android/jni_array.h" +#include "base/android/jni_string.h" +#include "base/time/time.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_android.h" +#include "chrome/browser/sync/send_tab_to_self_sync_service_factory.h" +#include "components/send_tab_to_self/send_tab_to_self_entry.h" +#include "components/send_tab_to_self/send_tab_to_self_model.h" +#include "components/send_tab_to_self/send_tab_to_self_sync_service.h" +#include "jni/SendTabToSelfAndroidBridge_jni.h" +#include "jni/SendTabToSelfEntry_jni.h" +#include "url/gurl.h" + +using base::android::AttachCurrentThread; +using base::android::ConvertUTF8ToJavaString; +using base::android::JavaParamRef; +using base::android::JavaRef; +using base::android::ScopedJavaGlobalRef; +using base::android::ScopedJavaLocalRef; + +namespace send_tab_to_self { + +namespace { + +ScopedJavaLocalRef<jobject> CreateJavaSendTabToSelfEntry( + JNIEnv* env, + const SendTabToSelfEntry* entry) { + return Java_SendTabToSelfEntry_createSendTabToSelfEntry( + env, ConvertUTF8ToJavaString(env, entry->GetGUID()), + ConvertUTF8ToJavaString(env, entry->GetURL().spec()), + ConvertUTF8ToJavaString(env, entry->GetTitle()), + entry->GetSharedTime().ToJavaTime(), + entry->GetOriginalNavigationTime().ToJavaTime(), + ConvertUTF8ToJavaString(env, entry->GetDeviceName())); +} + +} // namespace + +SendTabToSelfAndroidBridge::SendTabToSelfAndroidBridge( + JNIEnv* env, + const JavaRef<jobject>& obj, + const JavaRef<jobject>& j_profile) + : send_tab_to_self_model_(nullptr), weak_java_ref_(env, obj) { + Profile* profile = ProfileAndroid::FromProfileAndroid(j_profile); + send_tab_to_self_model_ = SendTabToSelfSyncServiceFactory::GetInstance() + ->GetForProfile(profile) + ->GetSendTabToSelfModel(); +} + +static jlong JNI_SendTabToSelfAndroidBridge_Init( + JNIEnv* env, + const JavaParamRef<jobject>& obj, + const JavaParamRef<jobject>& j_profile) { + SendTabToSelfAndroidBridge* send_tab_to_self_android_bridge = + new SendTabToSelfAndroidBridge(env, obj, j_profile); + return reinterpret_cast<intptr_t>(send_tab_to_self_android_bridge); +} + +void SendTabToSelfAndroidBridge::destroy(JNIEnv*, + const JavaParamRef<jobject>&) { + delete this; +} + +void SendTabToSelfAndroidBridge::getAllGuids( + JNIEnv* env, + const JavaParamRef<jobject>& obj, + const JavaParamRef<jobject>& j_guid_list_obj) { + // TODO(tgupta): Check that the model is loaded + // if (!send_tab_to_self_model_->loaded()()) + // return; + + std::vector<std::string> all_ids = send_tab_to_self_model_->GetAllGuids(); + for (std::vector<std::string>::iterator it = all_ids.begin(); + it != all_ids.end(); ++it) { + ScopedJavaLocalRef<jstring> j_guid = ConvertUTF8ToJavaString(env, *it); + Java_SendTabToSelfAndroidBridge_addToGuidList(env, j_guid_list_obj, j_guid); + } +} + +void SendTabToSelfAndroidBridge::deleteAllEntries( + JNIEnv* env, + const JavaParamRef<jobject>& obj) { + send_tab_to_self_model_->DeleteAllEntries(); +} + +ScopedJavaLocalRef<jobject> SendTabToSelfAndroidBridge::addEntry( + JNIEnv* env, + const JavaParamRef<jobject>& obj, + const JavaParamRef<jstring>& j_url, + const JavaParamRef<jstring>& j_title, + jlong j_navigation_time) { + const std::string url = ConvertJavaStringToUTF8(env, j_url); + const std::string title = ConvertJavaStringToUTF8(env, j_title); + + const SendTabToSelfEntry* persisted_entry = send_tab_to_self_model_->AddEntry( + GURL(url), title, base::Time::FromJavaTime(j_navigation_time)); + + if (persisted_entry == nullptr) { + return nullptr; + } + + return CreateJavaSendTabToSelfEntry(env, persisted_entry); +} + +ScopedJavaLocalRef<jobject> SendTabToSelfAndroidBridge::getEntryByGUID( + JNIEnv* env, + const JavaParamRef<jobject>& obj, + const JavaParamRef<jstring>& j_guid) { + const std::string guid = ConvertJavaStringToUTF8(env, j_guid); + const SendTabToSelfEntry* found_entry = + send_tab_to_self_model_->GetEntryByGUID(guid); + + if (found_entry == nullptr) { + return nullptr; + } + + return CreateJavaSendTabToSelfEntry(env, found_entry); +} + +} // namespace send_tab_to_self
diff --git a/chrome/browser/android/send_tab_to_self/send_tab_to_self_android_bridge.h b/chrome/browser/android/send_tab_to_self/send_tab_to_self_android_bridge.h new file mode 100644 index 0000000..083aec05 --- /dev/null +++ b/chrome/browser/android/send_tab_to_self/send_tab_to_self_android_bridge.h
@@ -0,0 +1,67 @@ +// 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_ANDROID_SEND_TAB_TO_SELF_SEND_TAB_TO_SELF_ANDROID_BRIDGE_H_ +#define CHROME_BROWSER_ANDROID_SEND_TAB_TO_SELF_SEND_TAB_TO_SELF_ANDROID_BRIDGE_H_ + +#include "base/android/jni_android.h" +#include "base/android/jni_weak_ref.h" +#include "base/macros.h" +#include "components/send_tab_to_self/send_tab_to_self_model_observer.h" + +namespace send_tab_to_self { +class SendTabToSelfModel; + +// The delegate to fetch SendTabToSelf information and persist new +// SendTabToSelf entries. The class is owned by the SendTabToSelf Java +// counterpart and lives for the duration of the life of that class. +class SendTabToSelfAndroidBridge { + public: + SendTabToSelfAndroidBridge(JNIEnv* env, + const base::android::JavaRef<jobject>& obj, + const base::android::JavaRef<jobject>& j_profile); + + void destroy(JNIEnv*, const base::android::JavaParamRef<jobject>&); + + // Populates a list of GUIDs in the model. + void getAllGuids(JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj, + const base::android::JavaParamRef<jobject>& j_guid_list_obj); + + // Returns the entry associated with a GUID. May return nullptr if none is + // found. + base::android::ScopedJavaLocalRef<jobject> getEntryByGUID( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj, + const base::android::JavaParamRef<jstring>& j_guid); + + // Adds a new entry with the specified parameters. Returns the persisted + // version which contains additional information such as GUID. + base::android::ScopedJavaLocalRef<jobject> addEntry( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj, + const base::android::JavaParamRef<jstring>& j_url, + const base::android::JavaParamRef<jstring>& j_title, + jlong j_navigation_time); + + // Deletes all entries in the model. + void deleteAllEntries(JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj); + + protected: + ~SendTabToSelfAndroidBridge() {} + // Set during the constructor and owned by the SendTabToSelfSyncServiceFactory + // is based off the KeyedServiceFactory which lives for the length of the + // profile. SendTabToSelf is not supported for the InCognito profile. + SendTabToSelfModel* send_tab_to_self_model_; + + private: + JavaObjectWeakGlobalRef weak_java_ref_; + + DISALLOW_COPY_AND_ASSIGN(SendTabToSelfAndroidBridge); +}; + +} // namespace send_tab_to_self + +#endif // CHROME_BROWSER_ANDROID_SEND_TAB_TO_SELF_SEND_TAB_TO_SELF_ANDROID_BRIDGE_H_
diff --git a/chrome/browser/android/signin/unified_consent_service_bridge.cc b/chrome/browser/android/signin/unified_consent_service_bridge.cc index d0d62a5..c0447ad 100644 --- a/chrome/browser/android/signin/unified_consent_service_bridge.cc +++ b/chrome/browser/android/signin/unified_consent_service_bridge.cc
@@ -39,5 +39,5 @@ Profile* profile = ProfileAndroid::FromProfileAndroid(profileAndroid); auto* unifiedConsentService = UnifiedConsentServiceFactory::GetForProfile(profile); - unifiedConsentService->SetUrlKeyedAnonymizedDataCollectionEnabled(true); + unifiedConsentService->SetUrlKeyedAnonymizedDataCollectionEnabled(enabled); }
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 7412671..bb159f9 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
@@ -66,7 +66,8 @@ } AppShimHostManager::~AppShimHostManager() { - acceptor_.reset(); + base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO}) + ->DeleteSoon(FROM_HERE, std::move(acceptor_)); // The AppShimHostManager is only initialized if the Chrome process // successfully took the singleton lock. If it was not initialized, do not
diff --git a/chrome/browser/badging/badge_manager.cc b/chrome/browser/badging/badge_manager.cc index f7c5ed4d..5ac63d5 100644 --- a/chrome/browser/badging/badge_manager.cc +++ b/chrome/browser/badging/badge_manager.cc
@@ -28,9 +28,9 @@ if (!badge_content) return "•"; - if (badge_content > 99u) { + if (badge_content > kMaxBadgeContent) { return base::UTF16ToUTF8(l10n_util::GetStringFUTF16( - IDS_SATURATED_BADGE_CONTENT, base::FormatNumber(99))); + IDS_SATURATED_BADGE_CONTENT, base::FormatNumber(kMaxBadgeContent))); } return base::UTF16ToUTF8(base::FormatNumber(badge_content.value()));
diff --git a/chrome/browser/badging/badge_manager.h b/chrome/browser/badging/badge_manager.h index 940cff3..f849949 100644 --- a/chrome/browser/badging/badge_manager.h +++ b/chrome/browser/badging/badge_manager.h
@@ -20,6 +20,9 @@ namespace badging { +// The maximum value of badge contents before saturation occurs. +constexpr uint64_t kMaxBadgeContent = 99u; + // Determines the text to put on the badge based on some badge_content. std::string GetBadgeString(base::Optional<uint64_t> badge_content);
diff --git a/chrome/browser/badging/badge_manager_delegate_win.cc b/chrome/browser/badging/badge_manager_delegate_win.cc index b192948..dd6d676 100644 --- a/chrome/browser/badging/badge_manager_delegate_win.cc +++ b/chrome/browser/badging/badge_manager_delegate_win.cc
@@ -22,11 +22,32 @@ void BadgeManagerDelegateWin::OnBadgeSet(const std::string& app_id, base::Optional<uint64_t> contents) { auto badge_string = badging::GetBadgeString(contents); - auto badge_alt_string = - contents ? l10n_util::GetPluralStringFUTF8(IDS_BADGE_UNREAD_NOTIFICATIONS, - contents.value()) - : l10n_util::GetStringUTF8( - IDS_BADGE_UNREAD_NOTIFICATIONS_UNSPECIFIED); + // There are 3 different cases: + // 1. |contents| is between 1 and 99 inclusive => Set the accessibility text + // to a pluralized notification count (e.g. 4 Unread Notifications). + // 2. |contents| is greater than 99 => Set the accessibility text to + // More than |kMaxBadgeContent| unread notifications, so the + // accessibility text matches what is displayed on the badge (e.g. More + // than 99 notifications). + // 3. |contents| doesn't have a value (i.e. the badge is set to 'flag') => Set + // the accessibility text to something less specific (e.g. Unread + // Notifications). + std::string badge_alt_string; + if (contents) { + uint64_t value = contents.value(); + badge_alt_string = value <= badging::kMaxBadgeContent + // Case 1. + ? l10n_util::GetPluralStringFUTF8( + IDS_BADGE_UNREAD_NOTIFICATIONS, value) + // Case 2. + : l10n_util::GetPluralStringFUTF8( + IDS_BADGE_UNREAD_NOTIFICATIONS_SATURATED, + badging::kMaxBadgeContent); + } else { + // Case 3. + badge_alt_string = + l10n_util::GetStringUTF8(IDS_BADGE_UNREAD_NOTIFICATIONS_UNSPECIFIED); + } for (Browser* browser : *BrowserList::GetInstance()) { if (!IsAppBrowser(browser, app_id))
diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index 81c7437..87061704 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd
@@ -200,6 +200,7 @@ <include name="IDR_EOC_INTERNALS_MOJO_JS" file="${root_gen_dir}\chrome\browser\ui\webui\eoc_internals\eoc_internals.mojom.js" use_base_dir="false" type="BINDATA" compress="gzip" /> <include name="IDR_EXPLORE_SITES_INTERNALS_HTML" file="resources\explore_sites_internals\explore_sites_internals.html" allowexternalscript="true" compress="gzip" type="BINDATA" /> <include name="IDR_FEED_INTERNALS_HTML" file="resources\feed_internals\feed_internals.html" allowexternalscript="true" compress="gzip" type="BINDATA" /> + <include name="IDR_FEED_INTERNALS_CSS" file="resources\feed_internals\feed_internals.css" allowexternalscript="true" compress="gzip" type="BINDATA" /> <include name="IDR_FEED_INTERNALS_JS" file="resources\feed_internals\feed_internals.js" compress="gzip" type="BINDATA" /> <include name="IDR_FEED_INTERNALS_MOJO_JS" file="${root_gen_dir}\chrome\browser\ui\webui\feed_internals\feed_internals.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" /> <include name="IDR_OFFLINE_INTERNALS_HTML" file="resources\offline_pages\offline_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" /> @@ -453,16 +454,16 @@ </if> <if expr="is_android"> <then> - <include name="IDR_POLICY_CSS" file="resources\policy_android.css" type="BINDATA" compress="gzip" /> + <include name="IDR_POLICY_CSS" file="resources\policy\policy_android.css" type="BINDATA" compress="gzip" /> </then> <else> - <include name="IDR_POLICY_CSS" file="resources\policy.css" type="BINDATA" compress="gzip" /> + <include name="IDR_POLICY_CSS" file="resources\policy\policy.css" type="BINDATA" compress="gzip" /> </else> </if> - <include name="IDR_POLICY_HTML" file="resources\policy.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" /> - <include name="IDR_POLICY_BASE_JS" file="resources\policy_base.js" type="BINDATA" compress="gzip" /> - <include name="IDR_POLICY_JS" file="resources\policy.js" type="BINDATA" compress="gzip" /> - <include name="IDR_POLICY_COMMON_CSS" file="resources\policy_common.css" type="BINDATA" compress="gzip" /> + <include name="IDR_POLICY_HTML" file="resources\policy\policy.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" /> + <include name="IDR_POLICY_BASE_JS" file="resources\policy\policy_base.js" type="BINDATA" compress="gzip" /> + <include name="IDR_POLICY_JS" file="resources\policy\policy.js" type="BINDATA" compress="gzip" /> + <include name="IDR_POLICY_COMMON_CSS" file="resources\policy\policy_common.css" type="BINDATA" compress="gzip" /> <if expr="not is_android"> <include name="IDR_MANAGEMENT_HTML" file="resources\management\management.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" /> <include name="IDR_MANAGEMENT_UI_HTML" file="resources\management\management_ui.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
diff --git a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc index bd528a5..fba8f91 100644 --- a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc +++ b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc
@@ -23,6 +23,7 @@ #include "chrome/browser/android/feed/feed_host_service_factory.h" #include "chrome/browser/autofill/legacy_strike_database_factory.h" #include "chrome/browser/autofill/personal_data_manager_factory.h" +#include "chrome/browser/autofill/strike_database_factory.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browsing_data/browsing_data_helper.h" @@ -64,7 +65,9 @@ #include "chrome/common/url_constants.h" #include "components/autofill/core/browser/legacy_strike_database.h" #include "components/autofill/core/browser/personal_data_manager.h" +#include "components/autofill/core/browser/strike_database.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" +#include "components/autofill/core/common/autofill_features.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/content_settings/core/browser/content_settings_registry.h" #include "components/content_settings/core/browser/host_content_settings_map.h" @@ -852,12 +855,24 @@ // TODO(crbug.com/884817): Respect |delete_begin_| and |delete_end_| and // only clear out entries whose last strikes were created in that // timeframe. - autofill::LegacyStrikeDatabase* legacy_strike_database = - autofill::LegacyStrikeDatabaseFactory::GetForProfile(profile_); - if (legacy_strike_database) - legacy_strike_database->ClearAllStrikes( - base::AdaptCallbackForRepeating(IgnoreArgument<bool>( - CreateTaskCompletionClosure(TracingDataType::kLegacyStrikes)))); + if (base::FeatureList::IsEnabled( + autofill::features::kAutofillSaveCreditCardUsesStrikeSystemV2)) { + autofill::StrikeDatabase* strike_database = + autofill::StrikeDatabaseFactory::GetForProfile(profile_); + if (strike_database) + strike_database->ClearAllStrikes(); + } else if (base::FeatureList::IsEnabled( + autofill::features:: + kAutofillSaveCreditCardUsesStrikeSystem)) { + autofill::LegacyStrikeDatabase* legacy_strike_database = + autofill::LegacyStrikeDatabaseFactory::GetForProfile(profile_); + if (legacy_strike_database) { + legacy_strike_database->ClearAllStrikes( + base::AdaptCallbackForRepeating( + IgnoreArgument<bool>(CreateTaskCompletionClosure( + TracingDataType::kLegacyStrikes)))); + } + } // Ask for a call back when the above calls are finished. web_data_service->GetDBTaskRunner()->PostTaskAndReply(
diff --git a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h index f854b60..d907432 100644 --- a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h +++ b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h
@@ -223,6 +223,7 @@ kDrmLicenses = 28, kHostCache = 29, kTpmAttestationKeys = 30, + kStrikes = 31, }; // Called by CreateTaskCompletionClosure().
diff --git a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc index 58dbf38..a331a97 100644 --- a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc +++ b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc
@@ -28,6 +28,7 @@ #include "build/build_config.h" #include "chrome/browser/autofill/legacy_strike_database_factory.h" #include "chrome/browser/autofill/personal_data_manager_factory.h" +#include "chrome/browser/autofill/strike_database_factory.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/browsing_data/browsing_data_helper.h" #include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_factory.h" @@ -59,6 +60,7 @@ #include "components/autofill/core/browser/legacy_strike_database.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/browser/personal_data_manager_observer.h" +#include "components/autofill/core/browser/strike_database.h" #include "components/autofill/core/browser/test_autofill_clock.h" #include "components/autofill/core/common/autofill_constants.h" #include "components/bookmarks/browser/bookmark_model.h" @@ -1014,6 +1016,30 @@ autofill::LegacyStrikeDatabase* legacy_strike_database_; }; +// StrikeDatabaseTester is in the autofill namespace since +// StrikeDatabase declares it as a friend in the autofill namespace. +class StrikeDatabaseTester { + public: + explicit StrikeDatabaseTester(Profile* profile) + : strike_database_( + autofill::StrikeDatabaseFactory::GetForProfile(profile)) {} + + bool IsEmpty() { + int num_keys; + base::RunLoop run_loop; + strike_database_->LoadKeys(base::BindLambdaForTesting( + [&](bool success, std::unique_ptr<std::vector<std::string>> keys) { + num_keys = keys.get()->size(); + run_loop.Quit(); + })); + run_loop.Run(); + return (num_keys == 0); + } + + private: + autofill::StrikeDatabase* strike_database_; +}; + } // namespace autofill class ClearReportingCacheTester { @@ -1659,6 +1685,30 @@ ASSERT_FALSE(tester.HasProfile()); } +TEST_F(ChromeBrowsingDataRemoverDelegateTest, + StrikeDatabaseEmptyOnAutofillRemoveEverything) { + GetProfile()->CreateWebDataService(); + RemoveAutofillTester tester(GetProfile()); + + ASSERT_FALSE(tester.HasProfile()); + tester.AddProfilesAndCards(); + ASSERT_TRUE(tester.HasProfile()); + + autofill::StrikeDatabaseTester strike_database_tester(GetProfile()); + BlockUntilBrowsingDataRemoved( + base::Time(), base::Time::Max(), + ChromeBrowsingDataRemoverDelegate::DATA_TYPE_FORM_DATA, false); + + // StrikeDatabase should be empty when DATA_TYPE_FORM_DATA browsing data + // gets deleted. + ASSERT_TRUE(strike_database_tester.IsEmpty()); + EXPECT_EQ(ChromeBrowsingDataRemoverDelegate::DATA_TYPE_FORM_DATA, + GetRemovalMask()); + EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB, + GetOriginTypeMask()); + ASSERT_FALSE(tester.HasProfile()); +} + // Verify that clearing autofill form data works. TEST_F(ChromeBrowsingDataRemoverDelegateTest, AutofillOriginsRemovedWithHistory) {
diff --git a/chrome/browser/browsing_data/counters/history_counter_browsertest.cc b/chrome/browser/browsing_data/counters/history_counter_browsertest.cc index 0448291d..d954e6f 100644 --- a/chrome/browser/browsing_data/counters/history_counter_browsertest.cc +++ b/chrome/browser/browsing_data/counters/history_counter_browsertest.cc
@@ -12,7 +12,6 @@ #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" -#include "components/browser_sync/profile_sync_service.h" #include "components/browsing_data/core/browsing_data_utils.h" #include "components/browsing_data/core/pref_names.h" #include "components/history/core/browser/history_service.h"
diff --git a/chrome/browser/browsing_data/counters/passwords_counter_browsertest.cc b/chrome/browser/browsing_data/counters/passwords_counter_browsertest.cc index a70ff8e3..3d16b97 100644 --- a/chrome/browser/browsing_data/counters/passwords_counter_browsertest.cc +++ b/chrome/browser/browsing_data/counters/passwords_counter_browsertest.cc
@@ -14,7 +14,6 @@ #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" #include "components/autofill/core/common/password_form.h" -#include "components/browser_sync/profile_sync_service.h" #include "components/browsing_data/core/browsing_data_utils.h" #include "components/browsing_data/core/pref_names.h" #include "components/prefs/pref_service.h"
diff --git a/chrome/browser/browsing_data/counters/sync_aware_counter_browsertest.cc b/chrome/browser/browsing_data/counters/sync_aware_counter_browsertest.cc index 8dd0dc3..4844195 100644 --- a/chrome/browser/browsing_data/counters/sync_aware_counter_browsertest.cc +++ b/chrome/browser/browsing_data/counters/sync_aware_counter_browsertest.cc
@@ -96,8 +96,7 @@ // Set up the Sync client. ASSERT_TRUE(SetupClients()); static const int kFirstProfileIndex = 0; - browser_sync::ProfileSyncService* sync_service = - GetSyncService(kFirstProfileIndex); + syncer::SyncService* sync_service = GetSyncService(kFirstProfileIndex); Profile* profile = GetProfile(kFirstProfileIndex); // Set up the counter. browsing_data::AutofillCounter counter( @@ -160,8 +159,7 @@ // Set up the Sync client. ASSERT_TRUE(SetupClients()); static const int kFirstProfileIndex = 0; - browser_sync::ProfileSyncService* sync_service = - GetSyncService(kFirstProfileIndex); + syncer::SyncService* sync_service = GetSyncService(kFirstProfileIndex); Profile* profile = GetProfile(kFirstProfileIndex); // Set up the counter. browsing_data::PasswordsCounter counter( @@ -228,8 +226,7 @@ // Set up the Sync client. ASSERT_TRUE(SetupClients()); static const int kFirstProfileIndex = 0; - browser_sync::ProfileSyncService* sync_service = - GetSyncService(kFirstProfileIndex); + syncer::SyncService* sync_service = GetSyncService(kFirstProfileIndex); Profile* profile = GetProfile(kFirstProfileIndex); // Set up the fake web history service and the counter.
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 783a2969..8fb31a5 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -5349,7 +5349,7 @@ previews_state |= previews::DetermineAllowedClientPreviewsState( previews_data, current_navigation_url, is_reload, is_redirect, data_reduction_proxy_settings->IsDataReductionProxyEnabled(), - previews_decider_impl); + previews_decider_impl, navigation_handle); if (previews_state & content::PREVIEWS_OFF) { previews_data->set_allowed_previews_state(content::PREVIEWS_OFF);
diff --git a/chrome/browser/chromeos/accessibility/spoken_feedback_app_list_browsertest.cc b/chrome/browser/chromeos/accessibility/spoken_feedback_app_list_browsertest.cc new file mode 100644 index 0000000..02e99f57b --- /dev/null +++ b/chrome/browser/chromeos/accessibility/spoken_feedback_app_list_browsertest.cc
@@ -0,0 +1,376 @@ +// 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 "ash/app_list/app_list_controller_impl.h" +#include "ash/app_list/model/search/search_model.h" +#include "ash/app_list/test/app_list_test_model.h" +#include "ash/app_list/test/test_search_result.h" +#include "ash/app_list/views/app_list_view.h" +#include "ash/shell.h" +#include "base/strings/pattern.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/chromeos/accessibility/spoken_feedback_browsertest.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/ui/app_list/app_list_client_impl.h" +#include "chrome/common/chrome_switches.h" +#include "chrome/grit/generated_resources.h" +#include "chromeos/constants/chromeos_switches.h" +#include "components/account_id/account_id.h" +#include "components/user_manager/user_names.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/base/l10n/l10n_util.h" + +namespace chromeos { + +enum SpokenFeedbackAppListTestVariant { kTestAsNormalUser, kTestAsGuestUser }; + +class TestSuggestionChipResult : public app_list::TestSearchResult { + public: + TestSuggestionChipResult(const base::string16& title) { + set_display_type(ash::SearchResultDisplayType::kRecommendation); + set_title(title); + } + ~TestSuggestionChipResult() override = default; + + private: + DISALLOW_COPY_AND_ASSIGN(TestSuggestionChipResult); +}; + +class SpokenFeedbackAppListTest + : public LoggedInSpokenFeedbackTest, + public ::testing::WithParamInterface<SpokenFeedbackAppListTestVariant> { + protected: + SpokenFeedbackAppListTest() = default; + ~SpokenFeedbackAppListTest() override = default; + + void SetUp() override { + // Do not run expand arrow hinting animation to avoid msan test crash. + // (See https://crbug.com/926038) + app_list::AppListView::SetShortAnimationForTesting(true); + LoggedInSpokenFeedbackTest::SetUp(); + } + + void TearDown() override { + LoggedInSpokenFeedbackTest::TearDown(); + app_list::AppListView::SetShortAnimationForTesting(false); + } + + void SetUpOnMainThread() override { + LoggedInSpokenFeedbackTest::SetUpOnMainThread(); + auto* controller = ash::Shell::Get()->app_list_controller(); + controller->SetSearchTabletAndClamshellAccessibleName( + l10n_util::GetStringUTF16(IDS_SEARCH_BOX_ACCESSIBILITY_NAME_TABLET), + l10n_util::GetStringUTF16(IDS_SEARCH_BOX_ACCESSIBILITY_NAME)); + controller->SetAppListModelForTest( + std::make_unique<app_list::test::AppListTestModel>()); + app_list_test_model_ = + static_cast<app_list::test::AppListTestModel*>(controller->GetModel()); + search_model = controller->GetSearchModel(); + } + + void SetUpCommandLine(base::CommandLine* command_line) override { + if (GetParam() == kTestAsGuestUser) { + command_line->AppendSwitch(chromeos::switches::kGuestSession); + command_line->AppendSwitch(::switches::kIncognito); + command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile, + "user"); + command_line->AppendSwitchASCII( + switches::kLoginUser, user_manager::GuestAccountId().GetUserEmail()); + } + } + + // Populate apps grid with |num| items. + void PopulateApps(size_t num) { app_list_test_model_->PopulateApps(num); } + + // Populate |num| suggestion chips. + void PopulateChips(size_t num) { + for (size_t i = 0; i < num; i++) { + search_model->results()->Add(std::make_unique<TestSuggestionChipResult>( + base::UTF8ToUTF16("Chip " + base::IntToString(i)))); + } + } + + private: + app_list::test::AppListTestModel* app_list_test_model_ = nullptr; + app_list::SearchModel* search_model = nullptr; +}; + +INSTANTIATE_TEST_SUITE_P(TestAsNormalAndGuestUser, + SpokenFeedbackAppListTest, + ::testing::Values(kTestAsNormalUser, + kTestAsGuestUser)); + +IN_PROC_BROWSER_TEST_P(SpokenFeedbackAppListTest, LauncherStateTransition) { + EnableChromeVox(); + + EXPECT_TRUE(PerformAcceleratorAction(ash::FOCUS_SHELF)); + + while (!base::MatchPattern(speech_monitor_.GetNextUtterance(), "Launcher")) { + } + + EXPECT_EQ("Button", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Shelf", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Tool bar", speech_monitor_.GetNextUtterance()); + EXPECT_EQ(", window", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Press Search plus Space to activate.", + speech_monitor_.GetNextUtterance()); + + // Press space on the launcher button in shelf, this opens peeking launcher. + SendKeyPressWithSearch(ui::VKEY_SPACE); + EXPECT_EQ("Search your device,", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("apps,", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("and web.", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Use the arrow keys to navigate your apps.", + speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Edit text", speech_monitor_.GetNextUtterance()); + EXPECT_EQ(", window", speech_monitor_.GetNextUtterance()); + + // Check that Launcher, partial view state is announced. + EXPECT_EQ("Launcher, partial view", speech_monitor_.GetNextUtterance()); + + // Move focus to expand all apps button; + SendKeyPressWithSearchAndShift(ui::VKEY_TAB); + EXPECT_EQ("Expand to all apps", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Button", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Press Search plus Space to activate.", + speech_monitor_.GetNextUtterance()); + + // Press space on expand arrow to go to fullscreen launcher. + SendKeyPressWithSearch(ui::VKEY_SPACE); + EXPECT_EQ("Search your device,", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("apps,", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("and web.", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Use the arrow keys to navigate your apps.", + speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Edit text", speech_monitor_.GetNextUtterance()); + + // Check that Launcher, all apps state is announced. + EXPECT_EQ("Launcher, all apps", speech_monitor_.GetNextUtterance()); +} + +IN_PROC_BROWSER_TEST_P(SpokenFeedbackAppListTest, + DisabledFullscreenExpandButton) { + EnableChromeVox(); + + EXPECT_TRUE(PerformAcceleratorAction(ash::FOCUS_SHELF)); + + while (speech_monitor_.GetNextUtterance() != + "Press Search plus Space to activate.") { + } + + // Press space on the launcher button in shelf, this opens peeking launcher. + SendKeyPressWithSearch(ui::VKEY_SPACE); + while (speech_monitor_.GetNextUtterance() != "Launcher, partial view") { + } + + // Move focus to expand all apps button. + SendKeyPressWithSearchAndShift(ui::VKEY_TAB); + while (speech_monitor_.GetNextUtterance() != + "Press Search plus Space to activate.") { + } + + // Press space on expand arrow to go to fullscreen launcher. + SendKeyPressWithSearch(ui::VKEY_SPACE); + while (speech_monitor_.GetNextUtterance() != "Launcher, all apps") { + } + + // Make sure the first traversal left is not the expand arrow button. + SendKeyPressWithSearch(ui::VKEY_LEFT); + EXPECT_NE("Expand to all apps", speech_monitor_.GetNextUtterance()); + + // Make sure the second traversal left is not the expand arrow button. + SendKeyPressWithSearch(ui::VKEY_LEFT); + EXPECT_NE("Expand to all apps", speech_monitor_.GetNextUtterance()); +} + +IN_PROC_BROWSER_TEST_P(SpokenFeedbackAppListTest, + PeekingLauncherFocusTraversal) { + // Add 3 suggestion chips. + PopulateChips(3); + + EnableChromeVox(); + + EXPECT_TRUE(PerformAcceleratorAction(ash::FOCUS_SHELF)); + + while (speech_monitor_.GetNextUtterance() != + "Press Search plus Space to activate.") { + } + + // Press space on the launcher button in shelf, this opens peeking launcher. + SendKeyPressWithSearch(ui::VKEY_SPACE); + while (speech_monitor_.GetNextUtterance() != "Launcher, partial view") { + } + + // Move focus to 1st suggestion chip; + SendKeyPressWithSearch(ui::VKEY_RIGHT); + EXPECT_EQ("Chip 0", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Button", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Press Search plus Space to activate.", + speech_monitor_.GetNextUtterance()); + + // Move focus to 2nd suggestion chip; + SendKeyPressWithSearch(ui::VKEY_RIGHT); + EXPECT_EQ("Chip 1", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Button", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Press Search plus Space to activate.", + speech_monitor_.GetNextUtterance()); + + // Move focus to 3rd suggestion chip; + SendKeyPressWithSearch(ui::VKEY_RIGHT); + EXPECT_EQ("Chip 2", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Button", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Press Search plus Space to activate.", + speech_monitor_.GetNextUtterance()); + + // Move focus to expand all apps button; + SendKeyPressWithSearch(ui::VKEY_RIGHT); + EXPECT_EQ("Expand to all apps", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Button", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Press Search plus Space to activate.", + speech_monitor_.GetNextUtterance()); + + // Move focus to app list window; + SendKeyPressWithSearch(ui::VKEY_RIGHT); + EXPECT_EQ(", window", speech_monitor_.GetNextUtterance()); + + // Move focus to search box; + SendKeyPressWithSearch(ui::VKEY_RIGHT); + EXPECT_EQ("Search your device,", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("apps,", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("and web.", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Use the arrow keys to navigate your apps.", + speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Edit text", speech_monitor_.GetNextUtterance()); +} + +IN_PROC_BROWSER_TEST_P(SpokenFeedbackAppListTest, + FullscreenLauncherFocusTraversal) { + // Add 1 suggestion chip and 3 apps. + PopulateChips(1); + PopulateApps(3); + + EnableChromeVox(); + + EXPECT_TRUE(PerformAcceleratorAction(ash::FOCUS_SHELF)); + + while (speech_monitor_.GetNextUtterance() != + "Press Search plus Space to activate.") { + } + + // Press space on the launcher button in shelf, this opens peeking launcher. + SendKeyPressWithSearch(ui::VKEY_SPACE); + while (speech_monitor_.GetNextUtterance() != "Launcher, partial view") { + } + + // Move focus to expand all apps button. + SendKeyPressWithSearchAndShift(ui::VKEY_TAB); + while (speech_monitor_.GetNextUtterance() != + "Press Search plus Space to activate.") { + } + + // Press space on expand arrow to go to fullscreen launcher. + SendKeyPressWithSearch(ui::VKEY_SPACE); + while (speech_monitor_.GetNextUtterance() != "Launcher, all apps") { + } + + // Move focus to the suggestion chip; + SendKeyPressWithSearch(ui::VKEY_RIGHT); + EXPECT_EQ("Chip 0", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Button", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Press Search plus Space to activate.", + speech_monitor_.GetNextUtterance()); + + // Move focus to 1st app; + SendKeyPressWithSearch(ui::VKEY_RIGHT); + EXPECT_EQ("Item 0", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Button", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Press Search plus Space to activate.", + speech_monitor_.GetNextUtterance()); + + // Move focus to 2nd app; + SendKeyPressWithSearch(ui::VKEY_RIGHT); + EXPECT_EQ("Item 1", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Button", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Press Search plus Space to activate.", + speech_monitor_.GetNextUtterance()); + + // Move focus to 3rd app; + SendKeyPressWithSearch(ui::VKEY_RIGHT); + EXPECT_EQ("Item 2", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Button", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Press Search plus Space to activate.", + speech_monitor_.GetNextUtterance()); + + // Move focus to app list window; + SendKeyPressWithSearch(ui::VKEY_RIGHT); + EXPECT_EQ(", window", speech_monitor_.GetNextUtterance()); + + // Move focus to search box; + SendKeyPressWithSearch(ui::VKEY_RIGHT); + EXPECT_EQ("Search your device,", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("apps,", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("and web.", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Use the arrow keys to navigate your apps.", + speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Edit text", speech_monitor_.GetNextUtterance()); +} + +// TODO(newcomer): reimplement this test once the AppListFocus changes are +// complete (http://crbug.com/784942). +IN_PROC_BROWSER_TEST_P(SpokenFeedbackAppListTest, + DISABLED_NavigateAppLauncher) { + EnableChromeVox(); + + EXPECT_TRUE(PerformAcceleratorAction(ash::FOCUS_SHELF)); + + // Wait for it to say "Launcher", "Button", "Shelf", "Tool bar". + while (true) { + std::string utterance = speech_monitor_.GetNextUtterance(); + if (base::MatchPattern(utterance, "Launcher")) + break; + } + EXPECT_EQ("Button", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Shelf", speech_monitor_.GetNextUtterance()); + EXPECT_EQ("Tool bar", speech_monitor_.GetNextUtterance()); + + // Click on the launcher, it brings up the app list UI. + SendKeyPress(ui::VKEY_SPACE); + while ("Search or type URL" != speech_monitor_.GetNextUtterance()) { + } + while ("Edit text" != speech_monitor_.GetNextUtterance()) { + } + + // Close it and open it again. + SendKeyPress(ui::VKEY_ESCAPE); + while (true) { + std::string utterance = speech_monitor_.GetNextUtterance(); + if (base::MatchPattern(utterance, "*window*")) + break; + } + + EXPECT_TRUE(PerformAcceleratorAction(ash::FOCUS_SHELF)); + while (true) { + std::string utterance = speech_monitor_.GetNextUtterance(); + if (base::MatchPattern(utterance, "Button")) + break; + } + SendKeyPress(ui::VKEY_SPACE); + + // Now type a space into the text field and wait until we hear "space". + // This makes the test more robust as it allows us to skip over other + // speech along the way. + SendKeyPress(ui::VKEY_SPACE); + while (true) { + if ("space" == speech_monitor_.GetNextUtterance()) + break; + } + + // Now press the down arrow and we should be focused on an app button + // in a dialog. + SendKeyPress(ui::VKEY_DOWN); + while ("Button" != speech_monitor_.GetNextUtterance()) { + } +} + +} // namespace chromeos
diff --git a/chrome/browser/chromeos/accessibility/spoken_feedback_browsertest.cc b/chrome/browser/chromeos/accessibility/spoken_feedback_browsertest.cc index 50b2559..3200085 100644 --- a/chrome/browser/chromeos/accessibility/spoken_feedback_browsertest.cc +++ b/chrome/browser/chromeos/accessibility/spoken_feedback_browsertest.cc
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/chromeos/accessibility/spoken_feedback_browsertest.h" + #include <queue> #include "ash/accelerators/accelerator_controller.h" -#include "ash/app_list/views/app_list_view.h" -#include "ash/public/cpp/accelerators.h" #include "ash/root_window_controller.h" #include "ash/shell.h" #include "ash/system/status_area_widget.h" @@ -21,13 +21,11 @@ #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/accessibility/accessibility_manager.h" -#include "chrome/browser/chromeos/accessibility/speech_monitor.h" #include "chrome/browser/chromeos/login/login_manager_test.h" #include "chrome/browser/chromeos/login/ui/login_display_host.h" #include "chrome/browser/chromeos/login/ui/webui_login_view.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/extensions/api/automation_internal/automation_event_router.h" -#include "chrome/browser/extensions/api/braille_display_private/stub_braille_controller.h" #include "chrome/browser/ui/ash/ksv/keyboard_shortcut_viewer_util.h" #include "chrome/browser/ui/aura/accessibility/automation_manager_aura.h" #include "chrome/browser/ui/browser.h" @@ -36,7 +34,6 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension_constants.h" -#include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/ui_test_utils.h" @@ -53,120 +50,106 @@ #include "extensions/browser/process_manager.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/test/ui_controls.h" -#include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/views/mus/ax_remote_host.h" #include "ui/views/widget/widget.h" -using extensions::api::braille_display_private::StubBrailleController; - namespace chromeos { -// -// Spoken feedback tests only in a logged in user's window. -// +LoggedInSpokenFeedbackTest::LoggedInSpokenFeedbackTest() + : animation_mode_(ui::ScopedAnimationDurationScaleMode::ZERO_DURATION) {} +LoggedInSpokenFeedbackTest::~LoggedInSpokenFeedbackTest() = default; -class LoggedInSpokenFeedbackTest : public InProcessBrowserTest { - public: - LoggedInSpokenFeedbackTest() - : animation_mode_(ui::ScopedAnimationDurationScaleMode::ZERO_DURATION) {} - ~LoggedInSpokenFeedbackTest() override {} +void LoggedInSpokenFeedbackTest::SetUpInProcessBrowserTestFixture() { + AccessibilityManager::SetBrailleControllerForTest(&braille_controller_); +} - void SetUpInProcessBrowserTestFixture() override { - AccessibilityManager::SetBrailleControllerForTest(&braille_controller_); +void LoggedInSpokenFeedbackTest::TearDownOnMainThread() { + AccessibilityManager::SetBrailleControllerForTest(nullptr); + // Unload the ChromeVox extension so the browser doesn't try to respond to + // in-flight requests during test shutdown. https://crbug.com/923090 + AccessibilityManager::Get()->EnableSpokenFeedback(false); + AutomationManagerAura::GetInstance()->Disable(); +} + +void LoggedInSpokenFeedbackTest::SendKeyPress(ui::KeyboardCode key) { + ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync( + nullptr, key, false, false, false, false))); +} + +void LoggedInSpokenFeedbackTest::SendKeyPressWithControl(ui::KeyboardCode key) { + ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync( + nullptr, key, true, false, false, false))); +} + +void LoggedInSpokenFeedbackTest::SendKeyPressWithSearchAndShift( + ui::KeyboardCode key) { + ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync( + nullptr, key, false, true, false, true))); +} + +void LoggedInSpokenFeedbackTest::SendKeyPressWithSearch(ui::KeyboardCode key) { + ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync( + nullptr, key, false, false, false, true))); +} + +void LoggedInSpokenFeedbackTest::RunJavaScriptInChromeVoxBackgroundPage( + const std::string& script) { + extensions::ExtensionHost* host = + extensions::ProcessManager::Get(browser()->profile()) + ->GetBackgroundHostForExtension( + extension_misc::kChromeVoxExtensionId); + CHECK(content::ExecuteScript(host->host_contents(), script)); +} + +void LoggedInSpokenFeedbackTest::SimulateTouchScreenInChromeVox() { + // ChromeVox looks at whether 'ontouchstart' exists to know whether + // or not it should respond to hover events. Fake it so that touch + // exploration events get spoken. + RunJavaScriptInChromeVoxBackgroundPage( + "window.ontouchstart = function() {};"); +} + +bool LoggedInSpokenFeedbackTest::PerformAcceleratorAction( + ash::AcceleratorAction action) { + ash::AcceleratorController* controller = + ash::Shell::Get()->accelerator_controller(); + return controller->PerformActionIfEnabled(action); +} + +void LoggedInSpokenFeedbackTest::DisableEarcons() { + // Playing earcons from within a test is not only annoying if you're + // running the test locally, but seems to cause crashes + // (http://crbug.com/396507). Work around this by just telling + // ChromeVox to not ever play earcons (prerecorded sound effects). + RunJavaScriptInChromeVoxBackgroundPage( + "cvox.ChromeVox.earcons.playEarcon = function() {};"); +} + +void LoggedInSpokenFeedbackTest::EnableChromeVox() { + // Test setup. + // Enable ChromeVox, skip welcome message/notification, and disable earcons. + ASSERT_FALSE(AccessibilityManager::Get()->IsSpokenFeedbackEnabled()); + + AccessibilityManager::Get()->EnableSpokenFeedback(true); + EXPECT_TRUE(speech_monitor_.SkipChromeVoxEnabledMessage()); + DisableEarcons(); +} + +void LoggedInSpokenFeedbackTest::PressRepeatedlyUntilUtterance( + ui::KeyboardCode key, + const std::string& expected_utterance) { + // This helper function is needed when you want to poll for something + // that happens asynchronously. Keep pressing |key|, until + // the speech feedback that follows is |expected_utterance|. + // Note that this doesn't work if pressing that key doesn't speak anything + // at all before the asynchronous event occurred. + while (true) { + SendKeyPress(key); + const std::string& utterance = speech_monitor_.GetNextUtterance(); + if (utterance == expected_utterance) + break; } - - void TearDownOnMainThread() override { - AccessibilityManager::SetBrailleControllerForTest(nullptr); - // Unload the ChromeVox extension so the browser doesn't try to respond to - // in-flight requests during test shutdown. https://crbug.com/923090 - AccessibilityManager::Get()->EnableSpokenFeedback(false); - AutomationManagerAura::GetInstance()->Disable(); - } - - void SendKeyPress(ui::KeyboardCode key) { - ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync( - nullptr, key, false, false, false, false))); - } - - void SendKeyPressWithControl(ui::KeyboardCode key) { - ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync( - nullptr, key, true, false, false, false))); - } - - void SendKeyPressWithSearchAndShift(ui::KeyboardCode key) { - ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync( - nullptr, key, false, true, false, true))); - } - - void SendKeyPressWithSearch(ui::KeyboardCode key) { - ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync( - nullptr, key, false, false, false, true))); - } - - void RunJavaScriptInChromeVoxBackgroundPage(const std::string& script) { - extensions::ExtensionHost* host = - extensions::ProcessManager::Get(browser()->profile()) - ->GetBackgroundHostForExtension( - extension_misc::kChromeVoxExtensionId); - CHECK(content::ExecuteScript(host->host_contents(), script)); - } - - void SimulateTouchScreenInChromeVox() { - // ChromeVox looks at whether 'ontouchstart' exists to know whether - // or not it should respond to hover events. Fake it so that touch - // exploration events get spoken. - RunJavaScriptInChromeVoxBackgroundPage( - "window.ontouchstart = function() {};"); - } - - bool PerformAcceleratorAction(ash::AcceleratorAction action) { - ash::AcceleratorController* controller = - ash::Shell::Get()->accelerator_controller(); - return controller->PerformActionIfEnabled(action); - } - - void DisableEarcons() { - // Playing earcons from within a test is not only annoying if you're - // running the test locally, but seems to cause crashes - // (http://crbug.com/396507). Work around this by just telling - // ChromeVox to not ever play earcons (prerecorded sound effects). - RunJavaScriptInChromeVoxBackgroundPage( - "cvox.ChromeVox.earcons.playEarcon = function() {};"); - } - - void EnableChromeVox() { - // Test setup. - // Enable ChromeVox, skip welcome message/notification, and disable earcons. - ASSERT_FALSE(AccessibilityManager::Get()->IsSpokenFeedbackEnabled()); - - AccessibilityManager::Get()->EnableSpokenFeedback(true); - EXPECT_TRUE(speech_monitor_.SkipChromeVoxEnabledMessage()); - DisableEarcons(); - } - - void PressRepeatedlyUntilUtterance(ui::KeyboardCode key, - const std::string& expected_utterance) { - // This helper function is needed when you want to poll for something - // that happens asynchronously. Keep pressing |key|, until - // the speech feedback that follows is |expected_utterance|. - // Note that this doesn't work if pressing that key doesn't speak anything - // at all before the asynchronous event occurred. - while (true) { - SendKeyPress(key); - const std::string& utterance = speech_monitor_.GetNextUtterance(); - if (utterance == expected_utterance) - break; - } - } - - SpeechMonitor speech_monitor_; - - private: - StubBrailleController braille_controller_; - ui::ScopedAnimationDurationScaleMode animation_mode_; - - DISALLOW_COPY_AND_ASSIGN(LoggedInSpokenFeedbackTest); -}; +} // This test is very flakey with ChromeVox Next since we generate a lot more // utterances for text fields. @@ -350,90 +333,6 @@ EXPECT_EQ("z", speech_monitor_.GetNextUtterance()); } -IN_PROC_BROWSER_TEST_P(SpokenFeedbackTest, DISABLED_LauncherStateTransition) { - // Do not running expand arrow hinting animation to avoid msan test crash. - // (See https://crbug.com/926038) - app_list::AppListView::SetShortAnimationForTesting(true); - EnableChromeVox(); - - EXPECT_TRUE(PerformAcceleratorAction(ash::FOCUS_SHELF)); - - while (true) { - std::string utterance = speech_monitor_.GetNextUtterance(); - if (base::MatchPattern(utterance, "Launcher")) - break; - } - - EXPECT_EQ("Button", speech_monitor_.GetNextUtterance()); - EXPECT_EQ("Shelf", speech_monitor_.GetNextUtterance()); - EXPECT_EQ("Tool bar", speech_monitor_.GetNextUtterance()); - EXPECT_EQ(", window", speech_monitor_.GetNextUtterance()); - EXPECT_EQ("Press Search plus Space to activate.", - speech_monitor_.GetNextUtterance()); - - // Press space on the launcher button in shelf, this opens peeking launcher. - SendKeyPressWithSearch(ui::VKEY_SPACE); - EXPECT_EQ("Edit text", speech_monitor_.GetNextUtterance()); - EXPECT_EQ(", window", speech_monitor_.GetNextUtterance()); - - // Check that Launcher, partial view state is announced. - EXPECT_EQ("Launcher, partial view", speech_monitor_.GetNextUtterance()); - - // Move focus to expand all apps button; - SendKeyPressWithSearchAndShift(ui::VKEY_TAB); - EXPECT_EQ("Expand to all apps", speech_monitor_.GetNextUtterance()); - EXPECT_EQ("Button", speech_monitor_.GetNextUtterance()); - EXPECT_EQ("Press Search plus Space to activate.", - speech_monitor_.GetNextUtterance()); - - // Press space on expand arrow to go to fullscreen launcher. - SendKeyPressWithSearch(ui::VKEY_SPACE); - EXPECT_EQ("Edit text", speech_monitor_.GetNextUtterance()); - - // Check that Launcher, all apps state is announced. - EXPECT_EQ("Launcher, all apps", speech_monitor_.GetNextUtterance()); - app_list::AppListView::SetShortAnimationForTesting(false); -} - -IN_PROC_BROWSER_TEST_P(SpokenFeedbackTest, - DISABLED_DisabledFullscreenExpandButton) { - // Do not running expand arrow hinting animation to avoid msan test crash. - // (See https://crbug.com/926038) - app_list::AppListView::SetShortAnimationForTesting(true); - EnableChromeVox(); - - EXPECT_TRUE(PerformAcceleratorAction(ash::FOCUS_SHELF)); - - while (speech_monitor_.GetNextUtterance() != - "Press Search plus Space to activate.") { - } - - // Press space on the launcher button in shelf, this opens peeking launcher. - SendKeyPressWithSearch(ui::VKEY_SPACE); - while (speech_monitor_.GetNextUtterance() != "Launcher, partial view") { - } - - // Move focus to expand all apps button. - SendKeyPressWithSearchAndShift(ui::VKEY_TAB); - while (speech_monitor_.GetNextUtterance() != - "Press Search plus Space to activate.") { - } - - // Press space on expand arrow to go to fullscreen launcher. - SendKeyPressWithSearch(ui::VKEY_SPACE); - while (speech_monitor_.GetNextUtterance() != "Launcher, all apps") { - } - - // Make sure the first traversal left is not the expand arrow button. - SendKeyPressWithSearch(ui::VKEY_LEFT); - EXPECT_NE("Expand to all apps", speech_monitor_.GetNextUtterance()); - - // Make sure the second traversal left is not the expand arrow button. - SendKeyPressWithSearch(ui::VKEY_LEFT); - EXPECT_NE("Expand to all apps", speech_monitor_.GetNextUtterance()); - app_list::AppListView::SetShortAnimationForTesting(false); -} - IN_PROC_BROWSER_TEST_P(SpokenFeedbackTest, FocusShelf) { EnableChromeVox(); @@ -456,62 +355,6 @@ EXPECT_TRUE(base::MatchPattern(speech_monitor_.GetNextUtterance(), "Button")); } -// TODO(newcomer): reimplement this test once the AppListFocus changes are -// complete (http://crbug.com/784942). -IN_PROC_BROWSER_TEST_P(SpokenFeedbackTest, DISABLED_NavigateAppLauncher) { - EnableChromeVox(); - - EXPECT_TRUE(PerformAcceleratorAction(ash::FOCUS_SHELF)); - - // Wait for it to say "Launcher", "Button", "Shelf", "Tool bar". - while (true) { - std::string utterance = speech_monitor_.GetNextUtterance(); - if (base::MatchPattern(utterance, "Launcher")) - break; - } - EXPECT_EQ("Button", speech_monitor_.GetNextUtterance()); - EXPECT_EQ("Shelf", speech_monitor_.GetNextUtterance()); - EXPECT_EQ("Tool bar", speech_monitor_.GetNextUtterance()); - - // Click on the launcher, it brings up the app list UI. - SendKeyPress(ui::VKEY_SPACE); - while ("Search or type URL" != speech_monitor_.GetNextUtterance()) { - } - while ("Edit text" != speech_monitor_.GetNextUtterance()) { - } - - // Close it and open it again. - SendKeyPress(ui::VKEY_ESCAPE); - while (true) { - std::string utterance = speech_monitor_.GetNextUtterance(); - if (base::MatchPattern(utterance, "*window*")) - break; - } - - EXPECT_TRUE(PerformAcceleratorAction(ash::FOCUS_SHELF)); - while (true) { - std::string utterance = speech_monitor_.GetNextUtterance(); - if (base::MatchPattern(utterance, "Button")) - break; - } - SendKeyPress(ui::VKEY_SPACE); - - // Now type a space into the text field and wait until we hear "space". - // This makes the test more robust as it allows us to skip over other - // speech along the way. - SendKeyPress(ui::VKEY_SPACE); - while (true) { - if ("space" == speech_monitor_.GetNextUtterance()) - break; - } - - // Now press the down arrow and we should be focused on an app button - // in a dialog. - SendKeyPress(ui::VKEY_DOWN); - while ("Button" != speech_monitor_.GetNextUtterance()) { - } -} - IN_PROC_BROWSER_TEST_P(SpokenFeedbackTest, OpenStatusTray) { EnableChromeVox();
diff --git a/chrome/browser/chromeos/accessibility/spoken_feedback_browsertest.h b/chrome/browser/chromeos/accessibility/spoken_feedback_browsertest.h new file mode 100644 index 0000000..4499288 --- /dev/null +++ b/chrome/browser/chromeos/accessibility/spoken_feedback_browsertest.h
@@ -0,0 +1,59 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_ACCESSIBILITY_SPOKEN_FEEDBACK_BROWSERTEST_H_ +#define CHROME_BROWSER_CHROMEOS_ACCESSIBILITY_SPOKEN_FEEDBACK_BROWSERTEST_H_ + +#include "ash/public/cpp/accelerators.h" +#include "chrome/browser/chromeos/accessibility/speech_monitor.h" +#include "chrome/browser/extensions/api/braille_display_private/stub_braille_controller.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "ui/compositor/scoped_animation_duration_scale_mode.h" +#include "ui/events/keycodes/keyboard_codes_posix.h" + +using extensions::api::braille_display_private::StubBrailleController; + +namespace chromeos { + +// Spoken feedback tests only in a logged in user's window. +class LoggedInSpokenFeedbackTest : public InProcessBrowserTest { + public: + LoggedInSpokenFeedbackTest(); + ~LoggedInSpokenFeedbackTest() override; + + // InProcessBrowserTest: + void SetUpInProcessBrowserTestFixture() override; + void TearDownOnMainThread() override; + + // Simulate key press event. + void SendKeyPress(ui::KeyboardCode key); + void SendKeyPressWithControl(ui::KeyboardCode key); + void SendKeyPressWithSearchAndShift(ui::KeyboardCode key); + void SendKeyPressWithSearch(ui::KeyboardCode key); + + void RunJavaScriptInChromeVoxBackgroundPage(const std::string& script); + + void SimulateTouchScreenInChromeVox(); + + bool PerformAcceleratorAction(ash::AcceleratorAction action); + + void DisableEarcons(); + + void EnableChromeVox(); + + void PressRepeatedlyUntilUtterance(ui::KeyboardCode key, + const std::string& expected_utterance); + + SpeechMonitor speech_monitor_; + + private: + StubBrailleController braille_controller_; + ui::ScopedAnimationDurationScaleMode animation_mode_; + + DISALLOW_COPY_AND_ASSIGN(LoggedInSpokenFeedbackTest); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_CHROMEOS_ACCESSIBILITY_SPOKEN_FEEDBACK_BROWSERTEST_H_
diff --git a/chrome/browser/chromeos/arc/arc_session_manager.cc b/chrome/browser/chromeos/arc/arc_session_manager.cc index c7e72ac..51de655b 100644 --- a/chrome/browser/chromeos/arc/arc_session_manager.cc +++ b/chrome/browser/chromeos/arc/arc_session_manager.cc
@@ -438,6 +438,7 @@ DCHECK(!profile || !profile_); DCHECK(!profile || IsArcAllowedForProfile(profile)); profile_ = profile; + UpdatePersistentUMAState(); } void ArcSessionManager::Initialize() { @@ -609,8 +610,10 @@ void ArcSessionManager::RecordArcState() { // Only record legacy enabled state if ARC is allowed in the first place, so // we do not split the ARC population by devices that cannot run ARC. + if (should_record_legacy_enabled_state_) + UpdateEnabledStateUMA(enabled_state_uma_); + if (IsAllowed()) { - UpdateEnabledStateUMA(enable_requested_); UpdateEnabledStateByUserTypeUMA(enable_requested_, profile_); ArcMetricsService* service = ArcMetricsService::GetForBrowserContext(profile_); @@ -631,7 +634,7 @@ return; } - UpdateEnabledStateByUserTypeUMA(enable_requested_, profile); + UpdateEnabledStateByUserTypeUMA(enabled_state_uma_, profile); } void ArcSessionManager::RequestEnable() { @@ -643,6 +646,7 @@ return; } enable_requested_ = true; + UpdatePersistentUMAState(); VLOG(1) << "ARC opt-in. Starting ARC session."; @@ -751,6 +755,7 @@ directly_started_ = false; enable_requested_ = false; + UpdatePersistentUMAState(); scoped_opt_in_tracker_.reset(); pai_starter_.reset(); fast_app_reinstall_starter_.reset(); @@ -1178,6 +1183,11 @@ arc_session_runner_->RequestStartMiniInstance(); } +void ArcSessionManager::UpdatePersistentUMAState() { + should_record_legacy_enabled_state_ = IsAllowed(); + enabled_state_uma_ = enable_requested_; +} + std::ostream& operator<<(std::ostream& os, const ArcSessionManager::State& state) { #define MAP_STATE(name) \
diff --git a/chrome/browser/chromeos/arc/arc_session_manager.h b/chrome/browser/chromeos/arc/arc_session_manager.h index 5d89286..dbcdcff 100644 --- a/chrome/browser/chromeos/arc/arc_session_manager.h +++ b/chrome/browser/chromeos/arc/arc_session_manager.h
@@ -349,6 +349,11 @@ // chromeos::SessionManagerClient::Observer: void EmitLoginPromptVisibleCalled() override; + // Updates |should_record_legacy_enabled_state_| and |enabled_state_uma_| + // whenever |profile_| or |enable_requested_| is changed (except Shutdown()). + // TODO(crbug.com/929583): Remove this temporary fix. + void UpdatePersistentUMAState(); + std::unique_ptr<ArcSessionRunner> arc_session_runner_; // Unowned pointer. Keeps current profile. @@ -385,6 +390,13 @@ base::Time arc_start_time_; base::Closure attempt_user_exit_callback_; + // ARC state depends on |profile_| and |enable_requested_| which is reset in + // Shutdown(). Since UMA recording happens after Shutdown() on browser + // shutdown, here we persist relevant state for UMA recording purposes. + // TODO(crbug.com/929583): Remove this temporary fix. + bool should_record_legacy_enabled_state_ = false; + bool enabled_state_uma_ = false; + // Must be the last member. base::WeakPtrFactory<ArcSessionManager> weak_ptr_factory_;
diff --git a/chrome/browser/chromeos/arc/fileapi/arc_file_system_bridge.cc b/chrome/browser/chromeos/arc/fileapi/arc_file_system_bridge.cc index 393c5ae..850dbc1b 100644 --- a/chrome/browser/chromeos/arc/fileapi/arc_file_system_bridge.cc +++ b/chrome/browser/chromeos/arc/fileapi/arc_file_system_bridge.cc
@@ -4,16 +4,23 @@ #include "chrome/browser/chromeos/arc/fileapi/arc_file_system_bridge.h" +#include <fcntl.h> +#include <sys/stat.h> +#include <sys/types.h> #include <utility> #include "base/bind.h" #include "base/logging.h" #include "base/memory/singleton.h" +#include "base/posix/eintr_wrapper.h" #include "base/system/sys_info.h" #include "base/task/post_task.h" +#include "base/threading/scoped_blocking_call.h" #include "chrome/browser/chromeos/arc/fileapi/arc_select_files_handler.h" #include "chrome/browser/chromeos/arc/fileapi/chrome_content_provider_url_util.h" #include "chrome/browser/chromeos/arc/fileapi/file_stream_forwarder.h" +#include "chrome/browser/chromeos/drive/drive_integration_service.h" +#include "chrome/browser/chromeos/drive/file_system_util.h" #include "chrome/browser/chromeos/file_manager/fileapi_util.h" #include "chrome/browser/chromeos/fileapi/external_file_url_util.h" #include "chrome/browser/profiles/profile.h" @@ -30,10 +37,12 @@ #include "mojo/public/cpp/system/platform_handle.h" #include "net/base/escape.h" #include "storage/browser/fileapi/file_system_context.h" +#include "url/gurl.h" namespace { constexpr char kChromeOSReleaseTrack[] = "CHROMEOS_RELEASE_TRACK"; constexpr char kTestImageRelease[] = "testimage-channel"; +constexpr char kDriveFSPrefix[] = "drivefs-"; } // namespace namespace arc { @@ -97,6 +106,49 @@ base::Passed(&callback))); } +// Decodes a percent-encoded URL to the drivefs path in the filesystem. +base::FilePath GetDriveFSPathFromURL(Profile* const profile, const GURL& url) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + // If DriveFS is not mounted, return an empty base::FilePath(). + if (!drive::util::GetIntegrationServiceByProfile(profile) || + !drive::util::GetIntegrationServiceByProfile(profile)->GetDriveFsHost()) { + return base::FilePath(); + } + base::FilePath virtual_path = chromeos::ExternalFileURLToVirtualPath(url); + std::vector<base::FilePath::StringType> virtual_path_components; + virtual_path.GetComponents(&virtual_path_components); + + // If the path is not DriveFS prefixed, then it might be FSP/MTP. + if (virtual_path_components.empty() || + !base::StartsWith(virtual_path_components[0], kDriveFSPrefix, + base::CompareCase::SENSITIVE)) { + return base::FilePath(); + } + + // Construct the path. + base::FilePath drivefs_path = + drive::util::GetIntegrationServiceByProfile(profile)->GetMountPointPath(); + DCHECK(!drivefs_path.empty()); + for (size_t i = 1; i < virtual_path_components.size(); i++) { + drivefs_path = drivefs_path.Append(virtual_path_components[i]); + } + return drivefs_path; +} + +// TODO(risan): Write test. +// Open DriveFS file from the fuse filesystem. +mojo::ScopedHandle OpenDriveFSFileToRead(const base::FilePath& fs_path) { + base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::WILL_BLOCK); + // Open the file and wrap the fd to be returned through mojo. + base::ScopedFD fd(HANDLE_EINTR( + open(fs_path.value().c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW))); + if (!fd.is_valid()) { + PLOG(WARNING) << "Invalid FD for fs_path: " << fs_path; + return mojo::ScopedHandle(); + } + return mojo::WrapPlatformHandle(mojo::PlatformHandle(std::move(fd))); +} + // Factory of ArcFileSystemBridge. class ArcFileSystemBridgeFactory : public internal::ArcBrowserContextKeyedServiceFactoryBase< @@ -241,10 +293,23 @@ std::move(callback).Run(mojo::ScopedHandle()); return; } - GetFileSize( - url, base::BindOnce(&ArcFileSystemBridge::OpenFileToReadAfterGetFileSize, - weak_ptr_factory_.GetWeakPtr(), url_decoded, - std::move(callback))); + + // TODO(risan): Remove the fallback path in M75+ after DriveFS is always + // enabled. + base::FilePath fs_path = GetDriveFSPathFromURL(profile_, url_decoded); + // If either DriveFS is not enabled/not mounted, or the URL doesn't represent + // drivefs file (e.g., FSP, MTP), use VirtualFileProvider instead. + if (fs_path.empty()) { + GetFileSize(url, base::BindOnce( + &ArcFileSystemBridge::OpenFileToReadAfterGetFileSize, + weak_ptr_factory_.GetWeakPtr(), url_decoded, + std::move(callback))); + return; + } + + base::PostTaskWithTraitsAndReplyWithResult( + FROM_HERE, {base::MayBlock()}, + base::BindOnce(&OpenDriveFSFileToRead, fs_path), std::move(callback)); } void ArcFileSystemBridge::SelectFiles(mojom::SelectFilesRequestPtr request,
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_base.cc b/chrome/browser/chromeos/extensions/file_manager/private_api_base.cc index 528a2de2..3183701 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_base.cc +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_base.cc
@@ -8,6 +8,7 @@ #include "base/strings/string_number_conversions.h" #include "chrome/browser/chromeos/extensions/file_manager/private_api_util.h" +#include "chrome/browser/extensions/chrome_extension_function_details.h" #include "components/drive/event_logger.h" namespace extensions { @@ -43,4 +44,32 @@ ChromeAsyncExtensionFunction::OnResponded(); } +LoggedUIThreadExtensionFunction::LoggedUIThreadExtensionFunction() + : log_on_completion_(false) { + start_time_ = base::Time::Now(); +} + +LoggedUIThreadExtensionFunction::~LoggedUIThreadExtensionFunction() = default; + +void LoggedUIThreadExtensionFunction::OnResponded() { + const ChromeExtensionFunctionDetails chrome_details(this); + drive::EventLogger* logger = + file_manager::util::GetLogger(chrome_details.GetProfile()); + if (logger) { + int64_t elapsed = (base::Time::Now() - start_time_).InMilliseconds(); + DCHECK(response_type()); + bool success = *response_type() == SUCCEEDED; + if (log_on_completion_) { + logger->Log(logging::LOG_INFO, "%s[%d] %s. (elapsed time: %sms)", name(), + request_id(), success ? "succeeded" : "failed", + base::NumberToString(elapsed).c_str()); + } else if (elapsed >= kSlowOperationThresholdMs) { + logger->Log(logging::LOG_WARNING, + "PEFORMANCE WARNING: %s[%d] was slow. (elapsed time: %sms)", + name(), request_id(), base::NumberToString(elapsed).c_str()); + } + } + UIThreadExtensionFunction::OnResponded(); +} + } // namespace extensions
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_base.h b/chrome/browser/chromeos/extensions/file_manager/private_api_base.h index 4598f9a..1fdd81cf 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_base.h +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_base.h
@@ -9,6 +9,7 @@ #include "base/time/time.h" #include "chrome/browser/extensions/chrome_extension_function.h" +#include "extensions/browser/extension_function.h" namespace extensions { @@ -20,6 +21,8 @@ // set_log_on_completion(true) to enable it, if they want. However, even if // the logging is turned off, a warning is emitted when a function call is // very slow. See the implementation of OnResponded() for details. +// TODO(crbug.com/934541): Remove this once all extension functions have been +// migrated to LoggedUIThreadExtensionFunction. class LoggedAsyncExtensionFunction : public ChromeAsyncExtensionFunction { public: LoggedAsyncExtensionFunction(); @@ -40,6 +43,28 @@ bool log_on_completion_; }; +// This is the same class as above, but inheriting directly from +// UIThreadExtensionFunction instead. +class LoggedUIThreadExtensionFunction : public UIThreadExtensionFunction { + public: + LoggedUIThreadExtensionFunction(); + + protected: + ~LoggedUIThreadExtensionFunction() override; + + // UIThreadExtensionFunction overrides. + void OnResponded() override; + + // Sets the logging on completion flag. By default, logging is turned off. + void set_log_on_completion(bool log_on_completion) { + log_on_completion_ = log_on_completion; + } + + private: + base::Time start_time_; + bool log_on_completion_; +}; + } // namespace extensions #endif // CHROME_BROWSER_CHROMEOS_EXTENSIONS_FILE_MANAGER_PRIVATE_API_BASE_H_
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_dialog.cc b/chrome/browser/chromeos/extensions/file_manager/private_api_dialog.cc index c3daa939..fa4477c3 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_dialog.cc +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_dialog.cc
@@ -8,6 +8,7 @@ #include "base/bind.h" #include "chrome/browser/chromeos/extensions/file_manager/private_api_util.h" +#include "chrome/browser/extensions/chrome_extension_function_details.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/views/select_file_dialog_extension.h" @@ -49,14 +50,14 @@ } // namespace -bool FileManagerPrivateCancelDialogFunction::RunAsync() { +ExtensionFunction::ResponseAction +FileManagerPrivateCancelDialogFunction::Run() { SelectFileDialogExtension::OnFileSelectionCanceled( GetFileDialogRoutingID(this)); - SendResponse(true); - return true; + return RespondNow(NoArguments()); } -bool FileManagerPrivateSelectFileFunction::RunAsync() { +ExtensionFunction::ResponseAction FileManagerPrivateSelectFileFunction::Run() { using extensions::api::file_manager_private::SelectFile::Params; const std::unique_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); @@ -72,12 +73,13 @@ file_manager::util::NEED_LOCAL_PATH_FOR_SAVING; } + ChromeExtensionFunctionDetails chrome_details(this); file_manager::util::GetSelectedFileInfo( - render_frame_host(), GetProfile(), file_paths, option, + render_frame_host(), chrome_details.GetProfile(), file_paths, option, base::BindOnce( &FileManagerPrivateSelectFileFunction::GetSelectedFileInfoResponse, this, params->index)); - return true; + return RespondLater(); } void FileManagerPrivateSelectFileFunction::GetSelectedFileInfoResponse( @@ -85,15 +87,15 @@ const std::vector<ui::SelectedFileInfo>& files) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (files.size() != 1) { - SendResponse(false); + Respond(Error("No file selected")); return; } SelectFileDialogExtension::OnFileSelected(GetFileDialogRoutingID(this), files[0], index); - SendResponse(true); + Respond(NoArguments()); } -bool FileManagerPrivateSelectFilesFunction::RunAsync() { +ExtensionFunction::ResponseAction FileManagerPrivateSelectFilesFunction::Run() { using extensions::api::file_manager_private::SelectFiles::Params; const std::unique_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); @@ -102,28 +104,29 @@ for (size_t i = 0; i < params->selected_paths.size(); ++i) file_urls.emplace_back(params->selected_paths[i]); + ChromeExtensionFunctionDetails chrome_details(this); file_manager::util::GetSelectedFileInfo( - render_frame_host(), GetProfile(), file_urls, + render_frame_host(), chrome_details.GetProfile(), file_urls, params->should_return_local_path ? file_manager::util::NEED_LOCAL_PATH_FOR_OPENING : file_manager::util::NO_LOCAL_PATH_RESOLUTION, base::BindOnce( &FileManagerPrivateSelectFilesFunction::GetSelectedFileInfoResponse, this)); - return true; + return RespondLater(); } void FileManagerPrivateSelectFilesFunction::GetSelectedFileInfoResponse( const std::vector<ui::SelectedFileInfo>& files) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (files.empty()) { - SendResponse(false); + Respond(Error("No files selected")); return; } SelectFileDialogExtension::OnMultiFilesSelected(GetFileDialogRoutingID(this), files); - SendResponse(true); + Respond(NoArguments()); } } // namespace extensions
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_dialog.h b/chrome/browser/chromeos/extensions/file_manager/private_api_dialog.h index d8dc8204..093081e 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_dialog.h +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_dialog.h
@@ -20,7 +20,7 @@ // Cancel file selection Dialog. Closes the dialog window. class FileManagerPrivateCancelDialogFunction - : public LoggedAsyncExtensionFunction { + : public LoggedUIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileManagerPrivate.cancelDialog", FILEMANAGERPRIVATE_CANCELDIALOG) @@ -28,12 +28,12 @@ protected: ~FileManagerPrivateCancelDialogFunction() override = default; - // ChromeAsyncExtensionFunction overrides. - bool RunAsync() override; + // ExtensionFunction overrides. + ResponseAction Run() override; }; class FileManagerPrivateSelectFileFunction - : public LoggedAsyncExtensionFunction { + : public LoggedUIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileManagerPrivate.selectFile", FILEMANAGERPRIVATE_SELECTFILE) @@ -41,8 +41,8 @@ protected: ~FileManagerPrivateSelectFileFunction() override = default; - // ChromeAsyncExtensionFunction overrides. - bool RunAsync() override; + // ExtensionFunction overrides. + ResponseAction Run() override; private: // A callback method to handle the result of GetSelectedFileInfo. @@ -53,7 +53,7 @@ // Select multiple files. Closes the dialog window. class FileManagerPrivateSelectFilesFunction - : public LoggedAsyncExtensionFunction { + : public LoggedUIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileManagerPrivate.selectFiles", FILEMANAGERPRIVATE_SELECTFILES) @@ -61,8 +61,8 @@ protected: ~FileManagerPrivateSelectFilesFunction() override = default; - // ChromeAsyncExtensionFunction overrides. - bool RunAsync() override; + // ExtensionFunction overrides. + ResponseAction Run() override; private: // A callback method to handle the result of GetSelectedFileInfo.
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_misc.cc b/chrome/browser/chromeos/extensions/file_manager/private_api_misc.cc index e06dd54c..685b1e3 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_misc.cc +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_misc.cc
@@ -248,41 +248,45 @@ FileManagerPrivateInternalZipSelectionFunction:: ~FileManagerPrivateInternalZipSelectionFunction() = default; -bool FileManagerPrivateInternalZipSelectionFunction::RunAsync() { +ExtensionFunction::ResponseAction +FileManagerPrivateInternalZipSelectionFunction::Run() { using extensions::api::file_manager_private_internal::ZipSelection::Params; const std::unique_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); // First param is the parent directory URL. if (params->parent_url.empty()) - return false; + return RespondNow(Error("Empty parent URL.")); + const ChromeExtensionFunctionDetails chrome_details(this); base::FilePath src_dir = file_manager::util::GetLocalPathFromURL( - render_frame_host(), GetProfile(), GURL(params->parent_url)); + render_frame_host(), chrome_details.GetProfile(), + GURL(params->parent_url)); if (src_dir.empty()) - return false; + return RespondNow(Error("Invalid source dir.")); // Second param is the list of selected file URLs to be zipped. if (params->urls.empty()) - return false; + return RespondNow(Error("No files selected to be zipped.")); std::vector<base::FilePath> files; for (size_t i = 0; i < params->urls.size(); ++i) { base::FilePath path = file_manager::util::GetLocalPathFromURL( - render_frame_host(), GetProfile(), GURL(params->urls[i])); + render_frame_host(), chrome_details.GetProfile(), + GURL(params->urls[i])); if (path.empty()) - return false; + return RespondNow(Error("Invalid selected file path.")); files.push_back(path); } // Third param is the name of the output zip file. if (params->dest_name.empty()) - return false; + return RespondNow(Error("Empty output file name.")); // Check if the dir path is under Drive mount point. // TODO(hshi): support create zip file on Drive (crbug.com/158690). if (drive::util::IsUnderDriveMountPoint(src_dir)) - return false; + return RespondNow(Error("Unable to zip Drive files.")); base::FilePath dest_file = src_dir.Append(params->dest_name); std::vector<base::FilePath> src_relative_paths; @@ -292,7 +296,7 @@ // Obtain the relative path of |file_path| under |src_dir|. base::FilePath relative_path; if (!src_dir.AppendRelativePath(file_path, &relative_path)) - return false; + return RespondNow(Error("Invalid selected file path.")); src_relative_paths.push_back(relative_path); } @@ -302,12 +306,11 @@ src_dir, src_relative_paths, dest_file)) ->Start( content::ServiceManagerConnection::GetForProcess()->GetConnector()); - return true; + return RespondLater(); } void FileManagerPrivateInternalZipSelectionFunction::OnZipDone(bool success) { - SetResult(std::make_unique<base::Value>(success)); - SendResponse(true); + Respond(OneArgument(std::make_unique<base::Value>(success))); } ExtensionFunction::ResponseAction FileManagerPrivateZoomFunction::Run() { @@ -335,27 +338,29 @@ } FileManagerPrivateRequestWebStoreAccessTokenFunction:: - FileManagerPrivateRequestWebStoreAccessTokenFunction() = default; + FileManagerPrivateRequestWebStoreAccessTokenFunction() + : chrome_details_(this) {} FileManagerPrivateRequestWebStoreAccessTokenFunction:: ~FileManagerPrivateRequestWebStoreAccessTokenFunction() = default; -bool FileManagerPrivateRequestWebStoreAccessTokenFunction::RunAsync() { +ExtensionFunction::ResponseAction +FileManagerPrivateRequestWebStoreAccessTokenFunction::Run() { std::vector<std::string> scopes; scopes.emplace_back(kCWSScope); identity::IdentityManager* identity_manager = - IdentityManagerFactory::GetForProfile(GetProfile()); + IdentityManagerFactory::GetForProfile(chrome_details_.GetProfile()); if (!identity_manager) { - drive::EventLogger* logger = file_manager::util::GetLogger(GetProfile()); + drive::EventLogger* logger = + file_manager::util::GetLogger(chrome_details_.GetProfile()); if (logger) { logger->Log(logging::LOG_ERROR, "CWS Access token fetch failed. IdentityManager can't " "be retrieved."); } - SetResult(std::make_unique<base::Value>()); - return false; + return RespondNow(Error("Unable to fetch token.")); } auth_service_ = std::make_unique<google_apis::AuthService>( @@ -368,29 +373,28 @@ OnAccessTokenFetched, this)); - return true; + return RespondLater(); } void FileManagerPrivateRequestWebStoreAccessTokenFunction::OnAccessTokenFetched( google_apis::DriveApiErrorCode code, const std::string& access_token) { - drive::EventLogger* logger = file_manager::util::GetLogger(GetProfile()); + drive::EventLogger* logger = + file_manager::util::GetLogger(chrome_details_.GetProfile()); if (code == google_apis::HTTP_SUCCESS) { DCHECK(auth_service_->HasAccessToken()); DCHECK(access_token == auth_service_->access_token()); if (logger) logger->Log(logging::LOG_INFO, "CWS OAuth token fetch succeeded."); - SetResult(std::make_unique<base::Value>(access_token)); - SendResponse(true); + Respond(OneArgument(std::make_unique<base::Value>(access_token))); } else { if (logger) { logger->Log(logging::LOG_ERROR, "CWS OAuth token fetch failed. (DriveApiErrorCode: %s)", google_apis::DriveApiErrorCodeToString(code).c_str()); } - SetResult(std::make_unique<base::Value>()); - SendResponse(false); + Respond(Error("Token fetch failed.")); } } @@ -468,31 +472,32 @@ FileManagerPrivateInternalGetMimeTypeFunction:: ~FileManagerPrivateInternalGetMimeTypeFunction() = default; -bool FileManagerPrivateInternalGetMimeTypeFunction::RunAsync() { +ExtensionFunction::ResponseAction +FileManagerPrivateInternalGetMimeTypeFunction::Run() { using extensions::api::file_manager_private_internal::GetMimeType::Params; const std::unique_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); // Convert file url to local path. + const ChromeExtensionFunctionDetails chrome_details(this); const scoped_refptr<storage::FileSystemContext> file_system_context = file_manager::util::GetFileSystemContextForRenderFrameHost( - GetProfile(), render_frame_host()); + chrome_details.GetProfile(), render_frame_host()); storage::FileSystemURL file_system_url( file_system_context->CrackURL(GURL(params->url))); app_file_handler_util::GetMimeTypeForLocalPath( - GetProfile(), file_system_url.path(), + chrome_details.GetProfile(), file_system_url.path(), base::Bind(&FileManagerPrivateInternalGetMimeTypeFunction::OnGetMimeType, this)); - return true; + return RespondLater(); } void FileManagerPrivateInternalGetMimeTypeFunction::OnGetMimeType( const std::string& mimeType) { - SetResult(std::make_unique<base::Value>(mimeType)); - SendResponse(true); + Respond(OneArgument(std::make_unique<base::Value>(mimeType))); } ExtensionFunction::ResponseAction @@ -642,7 +647,8 @@ FileManagerPrivateMountCrostiniFunction:: ~FileManagerPrivateMountCrostiniFunction() = default; -bool FileManagerPrivateMountCrostiniFunction::RunAsync() { +ExtensionFunction::ResponseAction +FileManagerPrivateMountCrostiniFunction::Run() { // Use OriginalProfile since using crostini in incognito such as saving // files into Linux files should still work. Profile* profile = @@ -652,7 +658,7 @@ crostini::kCrostiniDefaultVmName, crostini::kCrostiniDefaultContainerName, base::BindOnce(&FileManagerPrivateMountCrostiniFunction::RestartCallback, this)); - return true; + return RespondLater(); } void FileManagerPrivateMountCrostiniFunction::RestartCallback(
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_misc.h b/chrome/browser/chromeos/extensions/file_manager/private_api_misc.h index d356dca..611398e 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_misc.h +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_misc.h
@@ -16,7 +16,6 @@ #include "base/macros.h" #include "chrome/browser/chromeos/extensions/file_manager/private_api_base.h" #include "chrome/browser/chromeos/file_system_provider/provided_file_system_interface.h" -#include "chrome/browser/extensions/chrome_extension_function.h" #include "chrome/browser/extensions/chrome_extension_function_details.h" #include "chrome/common/extensions/api/file_manager_private.h" #include "google_apis/drive/drive_api_error_codes.h" @@ -90,7 +89,7 @@ // Implements the chrome.fileManagerPrivate.zipSelection method. // Creates a zip file for the selected files. class FileManagerPrivateInternalZipSelectionFunction - : public LoggedAsyncExtensionFunction { + : public LoggedUIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileManagerPrivateInternal.zipSelection", FILEMANAGERPRIVATEINTERNAL_ZIPSELECTION) @@ -100,8 +99,8 @@ protected: ~FileManagerPrivateInternalZipSelectionFunction() override; - // ChromeAsyncExtensionFunction overrides. - bool RunAsync() override; + // ExtensionFunction overrides. + ResponseAction Run() override; // Receives the result from ZipFileCreator. void OnZipDone(bool success); @@ -124,7 +123,7 @@ }; class FileManagerPrivateRequestWebStoreAccessTokenFunction - : public LoggedAsyncExtensionFunction { + : public LoggedUIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileManagerPrivate.requestWebStoreAccessToken", FILEMANAGERPRIVATE_REQUESTWEBSTOREACCESSTOKEN) @@ -134,14 +133,15 @@ protected: ~FileManagerPrivateRequestWebStoreAccessTokenFunction() override; - // ChromeAsyncExtensionFunction overrides. - bool RunAsync() override; + // ExtensionFunction overrides. + ResponseAction Run() override; private: std::unique_ptr<google_apis::AuthServiceInterface> auth_service_; void OnAccessTokenFetched(google_apis::DriveApiErrorCode code, const std::string& access_token); + const ChromeExtensionFunctionDetails chrome_details_; }; class FileManagerPrivateGetProfilesFunction : public UIThreadExtensionFunction { @@ -184,7 +184,7 @@ // Implements the chrome.fileManagerPrivate.getMimeType method. class FileManagerPrivateInternalGetMimeTypeFunction - : public LoggedAsyncExtensionFunction { + : public LoggedUIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileManagerPrivateInternal.getMimeType", FILEMANAGERPRIVATEINTERNAL_GETMIMETYPE) @@ -194,8 +194,8 @@ protected: ~FileManagerPrivateInternalGetMimeTypeFunction() override; - // ChromeAsyncExtensionFunction overrides. - bool RunAsync() override; + // ExtensionFunction overrides. + ResponseAction Run() override; void OnGetMimeType(const std::string& mimeType); }; @@ -284,7 +284,7 @@ // Implements the chrome.fileManagerPrivate.mountCrostini method. // Starts and mounts crostini container. class FileManagerPrivateMountCrostiniFunction - : public LoggedAsyncExtensionFunction { + : public LoggedUIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileManagerPrivate.mountCrostini", FILEMANAGERPRIVATE_MOUNTCROSTINI) @@ -293,7 +293,7 @@ protected: ~FileManagerPrivateMountCrostiniFunction() override; - bool RunAsync() override; + ResponseAction Run() override; void RestartCallback(crostini::CrostiniResult); private:
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_mount.cc b/chrome/browser/chromeos/extensions/file_manager/private_api_mount.cc index 649dbd44..c9be2cc4 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_mount.cc +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_mount.cc
@@ -50,12 +50,16 @@ } // namespace -bool FileManagerPrivateAddMountFunction::RunAsync() { +FileManagerPrivateAddMountFunction::FileManagerPrivateAddMountFunction() + : chrome_details_(this) {} + +ExtensionFunction::ResponseAction FileManagerPrivateAddMountFunction::Run() { using file_manager_private::AddMount::Params; const std::unique_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - drive::EventLogger* logger = file_manager::util::GetLogger(GetProfile()); + drive::EventLogger* logger = + file_manager::util::GetLogger(chrome_details_.GetProfile()); if (logger) { logger->Log(logging::LOG_INFO, "%s[%d] called. (source: '%s')", name(), request_id(), @@ -64,17 +68,17 @@ set_log_on_completion(true); const base::FilePath path = file_manager::util::GetLocalPathFromURL( - render_frame_host(), GetProfile(), GURL(params->source)); + render_frame_host(), chrome_details_.GetProfile(), GURL(params->source)); if (path.empty()) - return false; + return RespondNow(Error("Invalid path")); // Check if the source path is under Drive cache directory. if (drive::util::IsUnderDriveMountPoint(path)) { drive::FileSystemInterface* file_system = - drive::util::GetFileSystemByProfile(GetProfile()); + drive::util::GetFileSystemByProfile(chrome_details_.GetProfile()); if (!file_system) - return false; + return RespondNow(Error("Drive not available")); // Ensure that the cache file exists. const base::FilePath drive_path = drive::util::ExtractDrivePath(path); @@ -85,7 +89,7 @@ drive_path)); } else { file_manager::VolumeManager* volume_manager = - file_manager::VolumeManager::Get(GetProfile()); + file_manager::VolumeManager::Get(chrome_details_.GetProfile()); DCHECK(volume_manager); bool is_under_downloads = false; @@ -114,7 +118,7 @@ path.BaseName(), drive::FILE_ERROR_OK, path); } } - return true; + return RespondLater(); } void FileManagerPrivateAddMountFunction::RunAfterGetDriveFile( @@ -125,14 +129,14 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); if (error != drive::FILE_ERROR_OK) { - SendResponse(false); + Respond(Error(FileErrorToString(error))); return; } drive::FileSystemInterface* const file_system = - drive::util::GetFileSystemByProfile(GetProfile()); + drive::util::GetFileSystemByProfile(chrome_details_.GetProfile()); if (!file_system) { - SendResponse(false); + Respond(Error("Drive not available")); return; } @@ -149,8 +153,7 @@ bool is_marked_as_mounted) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (error != drive::FILE_ERROR_OK) { - SetError(FileErrorToString(error)); - SendResponse(false); + Respond(Error(FileErrorToString(error))); return; } if (is_marked_as_mounted) { @@ -162,9 +165,9 @@ return; } drive::FileSystemInterface* const file_system = - drive::util::GetFileSystemByProfile(GetProfile()); + drive::util::GetFileSystemByProfile(chrome_details_.GetProfile()); if (!file_system) { - SendResponse(false); + Respond(Error("Drive not available")); return; } file_system->MarkCacheFileAsMounted( @@ -181,13 +184,12 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); if (error != drive::FILE_ERROR_OK) { - SendResponse(false); + Respond(Error(FileErrorToString(error))); return; } // Pass back the actual source path of the mount point. - SetResult(std::make_unique<base::Value>(file_path.AsUTF8Unsafe())); - SendResponse(true); + Respond(OneArgument(std::make_unique<base::Value>(file_path.AsUTF8Unsafe()))); // MountPath() takes a std::string. DiskMountManager* disk_mount_manager = DiskMountManager::GetInstance(); @@ -198,12 +200,14 @@ chromeos::MOUNT_ACCESS_MODE_READ_WRITE); } -bool FileManagerPrivateRemoveMountFunction::RunAsync() { +ExtensionFunction::ResponseAction FileManagerPrivateRemoveMountFunction::Run() { using file_manager_private::RemoveMount::Params; const std::unique_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - drive::EventLogger* logger = file_manager::util::GetLogger(GetProfile()); + const ChromeExtensionFunctionDetails chrome_details(this); + drive::EventLogger* logger = + file_manager::util::GetLogger(chrome_details.GetProfile()); if (logger) { logger->Log(logging::LOG_INFO, "%s[%d] called. (volume_id: '%s')", name(), request_id(), params->volume_id.c_str()); @@ -212,13 +216,14 @@ using file_manager::VolumeManager; using file_manager::Volume; - VolumeManager* const volume_manager = VolumeManager::Get(GetProfile()); + VolumeManager* const volume_manager = + VolumeManager::Get(chrome_details.GetProfile()); DCHECK(volume_manager); base::WeakPtr<Volume> volume = volume_manager->FindVolumeById(params->volume_id); if (!volume.get()) - return false; + return RespondNow(Error("Volume not available")); // TODO(tbarzic): Send response when callback is received, it would make more // sense than remembering issued unmount requests in file manager and showing @@ -237,29 +242,34 @@ } case file_manager::VOLUME_TYPE_PROVIDED: { chromeos::file_system_provider::Service* service = - chromeos::file_system_provider::Service::Get(GetProfile()); + chromeos::file_system_provider::Service::Get( + chrome_details.GetProfile()); DCHECK(service); // TODO(mtomasz): Pass a more detailed error than just a bool. if (!service->RequestUnmount(volume->provider_id(), volume->file_system_id())) { - return false; + return RespondNow(Error("Unmount failed")); } break; } case file_manager::VOLUME_TYPE_CROSTINI: - file_manager::VolumeManager::Get(GetProfile()) + file_manager::VolumeManager::Get(chrome_details.GetProfile()) ->RemoveSshfsCrostiniVolume(volume->mount_path()); break; default: // Requested unmounting a device which is not unmountable. - return false; + return RespondNow(Error("Invalid volume type")); } - SendResponse(true); - return true; + return RespondNow(NoArguments()); } -bool FileManagerPrivateMarkCacheAsMountedFunction::RunAsync() { +FileManagerPrivateMarkCacheAsMountedFunction:: + FileManagerPrivateMarkCacheAsMountedFunction() + : chrome_details_(this) {} + +ExtensionFunction::ResponseAction +FileManagerPrivateMarkCacheAsMountedFunction::Run() { using file_manager_private::MarkCacheAsMounted::Params; const std::unique_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); @@ -268,18 +278,17 @@ bool is_mounted = params->is_mounted; if (path.empty()) - return false; + return RespondNow(Error("Invalid path")); if (!drive::util::IsUnderDriveMountPoint(path)) { // Ignore non-drive files. Treated as success. - SendResponse(true); - return true; + return RespondNow(NoArguments()); } drive::FileSystemInterface* file_system = - drive::util::GetFileSystemByProfile(GetProfile()); + drive::util::GetFileSystemByProfile(chrome_details_.GetProfile()); if (!file_system) - return false; + return RespondNow(Error("Drive not available")); // Ensure that the cache file exists. const base::FilePath drive_path = drive::util::ExtractDrivePath(path); @@ -288,7 +297,7 @@ base::BindOnce( &FileManagerPrivateMarkCacheAsMountedFunction::RunAfterGetDriveFile, this, drive_path, is_mounted)); - return true; + return RespondLater(); } void FileManagerPrivateMarkCacheAsMountedFunction::RunAfterGetDriveFile( @@ -300,15 +309,14 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); if (error != drive::FILE_ERROR_OK) { - SetError(FileErrorToString(error)); - SendResponse(false); + Respond(Error(FileErrorToString(error))); return; } drive::FileSystemInterface* const file_system = - drive::util::GetFileSystemByProfile(GetProfile()); + drive::util::GetFileSystemByProfile(chrome_details_.GetProfile()); if (!file_system) { - SendResponse(false); + Respond(Error("Drive not available")); return; } @@ -338,11 +346,10 @@ case drive::FILE_ERROR_INVALID_OPERATION: // The file was already marked as mounted. Ignore and treat as success. case drive::FILE_ERROR_OK: - SendResponse(true); + Respond(NoArguments()); break; default: - SetError(FileErrorToString(error)); - SendResponse(false); + Respond(Error(FileErrorToString(error))); } } @@ -354,44 +361,45 @@ case drive::FILE_ERROR_INVALID_OPERATION: // The file was already marked as unmounted. Ignore and treat as success. case drive::FILE_ERROR_OK: - SendResponse(true); + Respond(NoArguments()); break; default: - SetError(FileErrorToString(error)); - SendResponse(false); + Respond(Error(FileErrorToString(error))); } } -bool FileManagerPrivateGetVolumeMetadataListFunction::RunAsync() { +ExtensionFunction::ResponseAction +FileManagerPrivateGetVolumeMetadataListFunction::Run() { if (args_->GetSize()) - return false; + return RespondNow(Error("Invalid arguments")); + const ChromeExtensionFunctionDetails chrome_details(this); const std::vector<base::WeakPtr<file_manager::Volume>>& volume_list = - file_manager::VolumeManager::Get(GetProfile())->GetVolumeList(); + file_manager::VolumeManager::Get(chrome_details.GetProfile()) + ->GetVolumeList(); std::string log_string; std::vector<file_manager_private::VolumeMetadata> result; for (const auto& volume : volume_list) { file_manager_private::VolumeMetadata volume_metadata; - file_manager::util::VolumeToVolumeMetadata(GetProfile(), *volume, - &volume_metadata); + file_manager::util::VolumeToVolumeMetadata(chrome_details.GetProfile(), + *volume, &volume_metadata); result.push_back(std::move(volume_metadata)); if (!log_string.empty()) log_string += ", "; log_string += volume->mount_path().AsUTF8Unsafe(); } - drive::EventLogger* logger = file_manager::util::GetLogger(GetProfile()); + drive::EventLogger* logger = + file_manager::util::GetLogger(chrome_details.GetProfile()); if (logger) { logger->Log(logging::LOG_INFO, "%s[%d] succeeded. (results: '[%s]', %" PRIuS " mount points)", name(), request_id(), log_string.c_str(), result.size()); } - SetResultList( - file_manager_private::GetVolumeMetadataList::Results::Create(result)); - SendResponse(true); - return true; + return RespondNow(ArgumentList( + file_manager_private::GetVolumeMetadataList::Results::Create(result))); } } // namespace extensions
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_mount.h b/chrome/browser/chromeos/extensions/file_manager/private_api_mount.h index 94bfe8ba..af49e745 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_mount.h +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_mount.h
@@ -11,6 +11,7 @@ #include "base/files/file_path.h" #include "chrome/browser/chromeos/extensions/file_manager/private_api_base.h" +#include "chrome/browser/extensions/chrome_extension_function_details.h" #include "components/drive/drive.pb.h" #include "components/drive/file_errors.h" @@ -18,16 +19,19 @@ // Implements chrome.fileManagerPrivate.addMount method. // Mounts removable devices and archive files. -class FileManagerPrivateAddMountFunction : public LoggedAsyncExtensionFunction { +class FileManagerPrivateAddMountFunction + : public LoggedUIThreadExtensionFunction { public: + FileManagerPrivateAddMountFunction(); + DECLARE_EXTENSION_FUNCTION("fileManagerPrivate.addMount", FILEMANAGERPRIVATE_ADDMOUNT) protected: ~FileManagerPrivateAddMountFunction() override = default; - // ChromeAsyncExtensionFunction overrides. - bool RunAsync() override; + // ExtensionFunction overrides. + ResponseAction Run() override; private: // Part of Run(). Called after GetFile for Drive File System. @@ -48,12 +52,14 @@ void RunAfterMarkCacheFileAsMounted(const base::FilePath& display_name, drive::FileError error, const base::FilePath& file_path); + + const ChromeExtensionFunctionDetails chrome_details_; }; // Implements chrome.fileManagerPrivate.removeMount method. // Unmounts selected volume. Expects volume id as an argument. class FileManagerPrivateRemoveMountFunction - : public LoggedAsyncExtensionFunction { + : public LoggedUIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileManagerPrivate.removeMount", FILEMANAGERPRIVATE_REMOVEMOUNT) @@ -61,23 +67,25 @@ protected: ~FileManagerPrivateRemoveMountFunction() override = default; - // ChromeAsyncExtensionFunction overrides. - bool RunAsync() override; + // ExtensionFunction overrides. + ResponseAction Run() override; }; // Implements chrome.fileManagerPrivate.markCacheAsMounted method. // Marks a cached file as mounted or unmounted. class FileManagerPrivateMarkCacheAsMountedFunction - : public LoggedAsyncExtensionFunction { + : public LoggedUIThreadExtensionFunction { public: + FileManagerPrivateMarkCacheAsMountedFunction(); + DECLARE_EXTENSION_FUNCTION("fileManagerPrivate.markCacheAsMounted", FILEMANAGERPRIVATE_MARKCACHEASMOUNTED) protected: ~FileManagerPrivateMarkCacheAsMountedFunction() override = default; - // ChromeAsyncExtensionFunction overrides. - bool RunAsync() override; + // ExtensionFunction overrides. + ResponseAction Run() override; private: // Part of Run(). Called after GetFile for Drive File System. @@ -93,11 +101,13 @@ // Part of Run(). Called after MarkCacheFielAsUnmounted for Drive File System. void RunAfterMarkCacheFileAsUnmounted(drive::FileError error); + + const ChromeExtensionFunctionDetails chrome_details_; }; // Implements chrome.fileManagerPrivate.getVolumeMetadataList method. class FileManagerPrivateGetVolumeMetadataListFunction - : public LoggedAsyncExtensionFunction { + : public LoggedUIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileManagerPrivate.getVolumeMetadataList", FILEMANAGERPRIVATE_GETVOLUMEMETADATALIST) @@ -105,8 +115,8 @@ protected: ~FileManagerPrivateGetVolumeMetadataListFunction() override = default; - // ChromeAsyncExtensionFunction overrides. - bool RunAsync() override; + // ExtensionFunction overrides. + ResponseAction Run() override; }; } // namespace extensions
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_tasks.cc b/chrome/browser/chromeos/extensions/file_manager/private_api_tasks.cc index 5c9a3f9..eb6321d 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_tasks.cc +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_tasks.cc
@@ -67,7 +67,12 @@ } // namespace -bool FileManagerPrivateInternalExecuteTaskFunction::RunAsync() { +FileManagerPrivateInternalExecuteTaskFunction:: + FileManagerPrivateInternalExecuteTaskFunction() + : chrome_details_(this) {} + +ExtensionFunction::ResponseAction +FileManagerPrivateInternalExecuteTaskFunction::Run() { using extensions::api::file_manager_private_internal::ExecuteTask::Params; using extensions::api::file_manager_private_internal::ExecuteTask::Results:: Create; @@ -76,73 +81,76 @@ file_manager::file_tasks::TaskDescriptor task; if (!file_manager::file_tasks::ParseTaskID(params->task_id, &task)) { - SetError(kInvalidTask + params->task_id); - SetResultList( - Create(extensions::api::file_manager_private::TASK_RESULT_FAILED)); - return false; + // TODO(crbug.com/514135): Stop relying on the result being set on error. + return RespondNow(ErrorWithArguments( + Create(extensions::api::file_manager_private::TASK_RESULT_FAILED), + kInvalidTask + params->task_id)); } if (params->urls.empty()) { - SetResultList( - Create(extensions::api::file_manager_private::TASK_RESULT_EMPTY)); - SendResponse(true); - return true; + return RespondNow(ArgumentList( + Create(extensions::api::file_manager_private::TASK_RESULT_EMPTY))); } const scoped_refptr<storage::FileSystemContext> file_system_context = file_manager::util::GetFileSystemContextForRenderFrameHost( - GetProfile(), render_frame_host()); + chrome_details_.GetProfile(), render_frame_host()); std::vector<FileSystemURL> urls; for (size_t i = 0; i < params->urls.size(); i++) { const FileSystemURL url = file_system_context->CrackURL(GURL(params->urls[i])); if (!chromeos::FileSystemBackend::CanHandleURL(url)) { - SetError(kInvalidFileUrl); - SetResultList( - Create(extensions::api::file_manager_private::TASK_RESULT_FAILED)); - return false; + return RespondNow(ErrorWithArguments( + Create(extensions::api::file_manager_private::TASK_RESULT_FAILED), + kInvalidFileUrl)); } urls.push_back(url); } const bool result = file_manager::file_tasks::ExecuteFileTask( - GetProfile(), source_url(), task, urls, + chrome_details_.GetProfile(), source_url(), task, urls, base::BindOnce( &FileManagerPrivateInternalExecuteTaskFunction::OnTaskExecuted, this)); if (!result) { - SetResultList( - Create(extensions::api::file_manager_private::TASK_RESULT_FAILED)); + return RespondNow(ErrorWithArguments( + Create(extensions::api::file_manager_private::TASK_RESULT_FAILED), + "ExecuteFileTask failed")); } - return result; + return RespondLater(); } void FileManagerPrivateInternalExecuteTaskFunction::OnTaskExecuted( extensions::api::file_manager_private::TaskResult result) { - SetResultList(extensions::api::file_manager_private_internal::ExecuteTask:: - Results::Create(result)); - SendResponse(result != - extensions::api::file_manager_private::TASK_RESULT_FAILED); + auto result_list = extensions::api::file_manager_private_internal:: + ExecuteTask::Results::Create(result); + if (result == extensions::api::file_manager_private::TASK_RESULT_FAILED) { + Respond(ErrorWithArguments(std::move(result_list), "Task result failed")); + } else { + Respond(ArgumentList(std::move(result_list))); + } } FileManagerPrivateInternalGetFileTasksFunction:: - FileManagerPrivateInternalGetFileTasksFunction() = default; + FileManagerPrivateInternalGetFileTasksFunction() + : chrome_details_(this) {} FileManagerPrivateInternalGetFileTasksFunction:: ~FileManagerPrivateInternalGetFileTasksFunction() = default; -bool FileManagerPrivateInternalGetFileTasksFunction::RunAsync() { +ExtensionFunction::ResponseAction +FileManagerPrivateInternalGetFileTasksFunction::Run() { using extensions::api::file_manager_private_internal::GetFileTasks::Params; const std::unique_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); if (params->urls.empty()) - return false; + return RespondNow(Error("No URLs provided")); const scoped_refptr<storage::FileSystemContext> file_system_context = file_manager::util::GetFileSystemContextForRenderFrameHost( - GetProfile(), render_frame_host()); + chrome_details_.GetProfile(), render_frame_host()); // Collect all the URLs, convert them to GURLs, and crack all the urls into // file paths. @@ -156,21 +164,22 @@ } mime_type_collector_ = - std::make_unique<app_file_handler_util::MimeTypeCollector>(GetProfile()); + std::make_unique<app_file_handler_util::MimeTypeCollector>( + chrome_details_.GetProfile()); mime_type_collector_->CollectForLocalPaths( local_paths_, base::Bind( &FileManagerPrivateInternalGetFileTasksFunction::OnMimeTypesCollected, this)); - return true; + return RespondLater(); } void FileManagerPrivateInternalGetFileTasksFunction::OnMimeTypesCollected( std::unique_ptr<std::vector<std::string>> mime_types) { is_directory_collector_ = std::make_unique<app_file_handler_util::IsDirectoryCollector>( - GetProfile()); + chrome_details_.GetProfile()); is_directory_collector_->CollectForEntriesPaths( local_paths_, base::Bind(&FileManagerPrivateInternalGetFileTasksFunction:: OnAreDirectoriesAndMimeTypesCollected, @@ -189,7 +198,7 @@ } file_manager::file_tasks::FindAllTypesOfTasks( - GetProfile(), entries, urls_, + chrome_details_.GetProfile(), entries, urls_, base::BindOnce( &FileManagerPrivateInternalGetFileTasksFunction::OnFileTasksListed, this)); @@ -214,9 +223,8 @@ results.push_back(std::move(converted)); } - SetResultList(extensions::api::file_manager_private_internal::GetFileTasks:: - Results::Create(results)); - SendResponse(true); + Respond(ArgumentList(extensions::api::file_manager_private_internal:: + GetFileTasks::Results::Create(results))); } ExtensionFunction::ResponseAction
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_tasks.h b/chrome/browser/chromeos/extensions/file_manager/private_api_tasks.h index e8a5f33..2842f9ae 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_tasks.h +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_tasks.h
@@ -28,25 +28,29 @@ // Implements the chrome.fileManagerPrivateInternal.executeTask method. class FileManagerPrivateInternalExecuteTaskFunction - : public LoggedAsyncExtensionFunction { + : public LoggedUIThreadExtensionFunction { public: + FileManagerPrivateInternalExecuteTaskFunction(); + DECLARE_EXTENSION_FUNCTION("fileManagerPrivateInternal.executeTask", FILEMANAGERPRIVATEINTERNAL_EXECUTETASK) protected: ~FileManagerPrivateInternalExecuteTaskFunction() override = default; - // ChromeAsyncExtensionFunction overrides. - bool RunAsync() override; + // UIThreadExtensionFunction overrides. + ResponseAction Run() override; private: void OnTaskExecuted( extensions::api::file_manager_private::TaskResult success); + + const ChromeExtensionFunctionDetails chrome_details_; }; // Implements the chrome.fileManagerPrivateInternal.getFileTasks method. class FileManagerPrivateInternalGetFileTasksFunction - : public LoggedAsyncExtensionFunction { + : public LoggedUIThreadExtensionFunction { public: FileManagerPrivateInternalGetFileTasksFunction(); @@ -56,8 +60,8 @@ protected: ~FileManagerPrivateInternalGetFileTasksFunction() override; - // ChromeAsyncExtensionFunction overrides. - bool RunAsync() override; + // UIThreadExtensionFunction overrides. + ResponseAction Run() override; private: void OnMimeTypesCollected( @@ -77,6 +81,7 @@ mime_type_collector_; std::vector<GURL> urls_; std::vector<base::FilePath> local_paths_; + const ChromeExtensionFunctionDetails chrome_details_; }; // Implements the chrome.fileManagerPrivateInternal.setDefaultTask method.
diff --git a/chrome/browser/chromeos/file_manager/file_browser_handlers.cc b/chrome/browser/chromeos/file_manager/file_browser_handlers.cc index 923f325..a58eeb24a 100644 --- a/chrome/browser/chromeos/file_manager/file_browser_handlers.cc +++ b/chrome/browser/chromeos/file_manager/file_browser_handlers.cc
@@ -137,20 +137,6 @@ if (!handler->MatchesURL(lowercase_url)) continue; - // Filter out Files app from handling ZIP files via a handler, as it's - // now handled by: - // - Zip Archiver native extension component - // TODO(amistry): This can be removed once the AVFS-based zip mounting is - // removed and zip handling is removed from the file manager's - // manifest.json. - const URLPattern zip_pattern(URLPattern::SCHEME_EXTENSION, - "chrome-extension://*/*.zip"); - if (handler->extension_id() == kFileManagerAppId && - zip_pattern.MatchesURL(selected_file_url) && - !base::CommandLine::ForCurrentProcess()->HasSwitch( - chromeos::switches::kDisableNewZIPUnpacker)) { - continue; - } results.push_back(handler); } }
diff --git a/chrome/browser/chromeos/file_manager/path_util.cc b/chrome/browser/chromeos/file_manager/path_util.cc index 7e615476..575bca4 100644 --- a/chrome/browser/chromeos/file_manager/path_util.cc +++ b/chrome/browser/chromeos/file_manager/path_util.cc
@@ -560,9 +560,12 @@ } else if (ReplacePrefix(&result, GetCrostiniMountDirectory(profile).value(), l10n_util::GetStringUTF8( IDS_FILE_BROWSER_LINUX_FILES_ROOT_LABEL))) { - } else if (ReplacePrefix(&result, kRemovableMediaPath, - l10n_util::GetStringUTF8( - IDS_FILE_BROWSER_EXTERNAL_STORAGE_ROOT_LABEL))) { + } else if (ReplacePrefix(&result, + base::FilePath(kRemovableMediaPath) + .AsEndingWithSeparator() + .value(), + "")) { + // Strip prefix of "/media/removable/" including trailing slash. } base::ReplaceChars(result, "/", " \u203a ", &result);
diff --git a/chrome/browser/chromeos/file_manager/path_util_unittest.cc b/chrome/browser/chromeos/file_manager/path_util_unittest.cc index e7b18c0..d2863bce 100644 --- a/chrome/browser/chromeos/file_manager/path_util_unittest.cc +++ b/chrome/browser/chromeos/file_manager/path_util_unittest.cc
@@ -184,9 +184,8 @@ GetPathDisplayTextForSettings( profile_.get(), "/media/fuse/crostini_0123456789abcdef_termina_penguin/foo")); - EXPECT_EQ( - "External storage \u203a foo", - GetPathDisplayTextForSettings(profile_.get(), "/media/removable/foo")); + EXPECT_EQ("foo", GetPathDisplayTextForSettings(profile_.get(), + "/media/removable/foo")); { base::test::ScopedFeatureList features; features.InitAndDisableFeature(chromeos::features::kDriveFs);
diff --git a/chrome/browser/chromeos/file_manager/video_player_browsertest.cc b/chrome/browser/chromeos/file_manager/video_player_browsertest.cc index 158719b..4240f9f 100644 --- a/chrome/browser/chromeos/file_manager/video_player_browsertest.cc +++ b/chrome/browser/chromeos/file_manager/video_player_browsertest.cc
@@ -67,10 +67,12 @@ IN_PROC_BROWSER_TEST_F(VideoPlayerBrowserTest, OpenVideoWithSubtitle) { set_test_case_name("openVideoWithSubtitle"); + StartTest(); } IN_PROC_BROWSER_TEST_F(VideoPlayerBrowserTest, OpenVideoWithoutSubtitle) { set_test_case_name("openVideoWithoutSubtitle"); + StartTest(); } IN_PROC_BROWSER_TEST_F(VideoPlayerBrowserTest, CheckInitialElements) {
diff --git a/chrome/browser/chromeos/login/demo_mode/demo_setup_browsertest.cc b/chrome/browser/chromeos/login/demo_mode/demo_setup_browsertest.cc index 2ff33b7e..fac7f136 100644 --- a/chrome/browser/chromeos/login/demo_mode/demo_setup_browsertest.cc +++ b/chrome/browser/chromeos/login/demo_mode/demo_setup_browsertest.cc
@@ -24,6 +24,7 @@ #include "chrome/browser/chromeos/login/screens/network_screen.h" #include "chrome/browser/chromeos/login/screens/screen_exit_code.h" #include "chrome/browser/chromeos/login/startup_utils.h" +#include "chrome/browser/chromeos/login/test/enrollment_helper_mixin.h" #include "chrome/browser/chromeos/login/test/js_checker.h" #include "chrome/browser/chromeos/login/test/oobe_screen_waiter.h" #include "chrome/browser/chromeos/login/test/test_condition_waiter.h" @@ -47,8 +48,6 @@ #include "ui/base/l10n/l10n_util.h" using chromeos::test::DemoModeSetupResult; -using chromeos::test::MockDemoModeOfflineEnrollmentHelperCreator; -using chromeos::test::MockDemoModeOnlineEnrollmentHelperCreator; using chromeos::test::SetupDummyOfflinePolicyDir; namespace chromeos { @@ -327,9 +326,11 @@ void SkipToErrorDialog() { // Simulate online setup error. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOnlineEnrollmentHelperCreator< - DemoModeSetupResult::ERROR_DEFAULT>); + enrollment_helper_.ExpectEnrollmentMode( + policy::EnrollmentConfig::MODE_ATTESTATION); + enrollment_helper_.ExpectAttestationEnrollmentError( + policy::EnrollmentStatus::ForRegistrationError( + policy::DeviceManagementStatus::DM_STATUS_TEMPORARY_UNAVAILABLE)); // Enrollment type is set in the part of the flow that is skipped, That is // why we need to set it here. @@ -431,6 +432,9 @@ test::ExecuteOobeJS(query); } + protected: + test::EnrollmentHelperMixin enrollment_helper_{&mixin_host_}; + private: void DisableConfirmationDialogAnimations() { test::ExecuteOobeJS( @@ -504,8 +508,9 @@ IN_PROC_BROWSER_TEST_F(DemoSetupTest, OnlineSetupFlowSuccess) { // Simulate successful online setup. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOnlineEnrollmentHelperCreator<DemoModeSetupResult::SUCCESS>); + enrollment_helper_.ExpectEnrollmentMode( + policy::EnrollmentConfig::MODE_ATTESTATION); + enrollment_helper_.ExpectAttestationEnrollmentSuccess(); SimulateNetworkConnected(); InvokeDemoModeWithAccelerator(); @@ -554,9 +559,11 @@ IN_PROC_BROWSER_TEST_F(DemoSetupTest, OnlineSetupFlowErrorDefault) { // Simulate online setup failure. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOnlineEnrollmentHelperCreator< - DemoModeSetupResult::ERROR_DEFAULT>); + enrollment_helper_.ExpectEnrollmentMode( + policy::EnrollmentConfig::MODE_ATTESTATION); + enrollment_helper_.ExpectAttestationEnrollmentError( + policy::EnrollmentStatus::ForRegistrationError( + policy::DeviceManagementStatus::DM_STATUS_TEMPORARY_UNAVAILABLE)); SimulateNetworkConnected(); InvokeDemoModeWithAccelerator(); @@ -618,9 +625,11 @@ IN_PROC_BROWSER_TEST_F(DemoSetupTest, OnlineSetupFlowErrorPowerwashRequired) { // Simulate online setup failure that requires powerwash. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOnlineEnrollmentHelperCreator< - DemoModeSetupResult::ERROR_POWERWASH_REQUIRED>); + enrollment_helper_.ExpectEnrollmentMode( + policy::EnrollmentConfig::MODE_ATTESTATION); + enrollment_helper_.ExpectAttestationEnrollmentError( + policy::EnrollmentStatus::ForLockError( + chromeos::InstallAttributes::LOCK_ALREADY_LOCKED)); SimulateNetworkConnected(); InvokeDemoModeWithAccelerator(); @@ -681,8 +690,8 @@ IN_PROC_BROWSER_TEST_F(DemoSetupTest, OnlineSetupFlowCrosComponentFailure) { // Simulate failure to load demo resources CrOS component. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOnlineEnrollmentHelperCreator<DemoModeSetupResult::SUCCESS>); + // There is no enrollment attempt, as process fails earlier. + enrollment_helper_.ExpectNoEnrollment(); SimulateNetworkConnected(); InvokeDemoModeWithAccelerator(); @@ -762,9 +771,7 @@ IN_PROC_BROWSER_TEST_F(DemoSetupTest, OfflineSetupFlowSuccess) { // Simulate offline setup success. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOfflineEnrollmentHelperCreator< - DemoModeSetupResult::SUCCESS>); + enrollment_helper_.ExpectOfflineEnrollmentSuccess(); SimulateNetworkDisconnected(); InvokeDemoModeWithAccelerator(); @@ -816,9 +823,9 @@ IN_PROC_BROWSER_TEST_F(DemoSetupTest, OfflineSetupFlowErrorDefault) { // Simulate offline setup failure. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOfflineEnrollmentHelperCreator< - DemoModeSetupResult::ERROR_DEFAULT>); + enrollment_helper_.ExpectOfflineEnrollmentError( + policy::EnrollmentStatus::ForStatus( + policy::EnrollmentStatus::OFFLINE_POLICY_DECODING_FAILED)); SimulateNetworkDisconnected(); InvokeDemoModeWithAccelerator(); @@ -883,9 +890,9 @@ IN_PROC_BROWSER_TEST_F(DemoSetupTest, OfflineSetupFlowErrorPowerwashRequired) { // Simulate offline setup failure. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOfflineEnrollmentHelperCreator< - DemoModeSetupResult::ERROR_POWERWASH_REQUIRED>); + enrollment_helper_.ExpectOfflineEnrollmentError( + policy::EnrollmentStatus::ForLockError( + chromeos::InstallAttributes::LOCK_READBACK_ERROR)); SimulateNetworkDisconnected(); InvokeDemoModeWithAccelerator(); @@ -1023,9 +1030,12 @@ IN_PROC_BROWSER_TEST_F(DemoSetupTest, RetryOnErrorScreen) { SkipToErrorDialog(); + // We need to create another mock after showing error dialog. + enrollment_helper_.ResetMock(); // Simulate successful online setup on retry. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOnlineEnrollmentHelperCreator<DemoModeSetupResult::SUCCESS>); + enrollment_helper_.ExpectEnrollmentMode( + policy::EnrollmentConfig::MODE_ATTESTATION); + enrollment_helper_.ExpectAttestationEnrollmentSuccess(); ClickScreenDialogButtonWithSelector(OobeScreen::SCREEN_OOBE_DEMO_SETUP, DemoSetupDialog::kError, "#retryButton", JSExecution::kAsync); @@ -1110,9 +1120,7 @@ // "block_devmode" flags do not exist in VPD. // Simulate offline setup success. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOfflineEnrollmentHelperCreator< - DemoModeSetupResult::SUCCESS>); + enrollment_helper_.ExpectOfflineEnrollmentSuccess(); SimulateNetworkDisconnected(); InvokeDemoModeWithAccelerator(); @@ -1147,9 +1155,7 @@ statistics_provider_.SetMachineStatistic(system::kBlockDevModeKey, "0"); // Simulate offline setup success. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOfflineEnrollmentHelperCreator< - DemoModeSetupResult::SUCCESS>); + enrollment_helper_.ExpectOfflineEnrollmentSuccess(); SimulateNetworkDisconnected(); InvokeDemoModeWithAccelerator(); @@ -1185,9 +1191,7 @@ statistics_provider_.SetMachineStatistic(system::kBlockDevModeKey, "0"); // Simulate offline setup success. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOfflineEnrollmentHelperCreator< - DemoModeSetupResult::SUCCESS>); + enrollment_helper_.ExpectOfflineEnrollmentSuccess(); SimulateNetworkDisconnected(); InvokeDemoModeWithAccelerator(); @@ -1220,10 +1224,8 @@ statistics_provider_.SetMachineStatistic(system::kCheckEnrollmentKey, "1"); statistics_provider_.SetMachineStatistic(system::kBlockDevModeKey, "1"); - // Simulate offline setup success. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOfflineEnrollmentHelperCreator< - DemoModeSetupResult::SUCCESS>); + // Expect no enrollment to take place due to error. + enrollment_helper_.ExpectNoEnrollment(); SimulateNetworkDisconnected(); InvokeDemoModeWithAccelerator();
diff --git a/chrome/browser/chromeos/login/demo_mode/demo_setup_controller_unittest.cc b/chrome/browser/chromeos/login/demo_mode/demo_setup_controller_unittest.cc index 0554e5dd..e79d3ef 100644 --- a/chrome/browser/chromeos/login/demo_mode/demo_setup_controller_unittest.cc +++ b/chrome/browser/chromeos/login/demo_mode/demo_setup_controller_unittest.cc
@@ -32,9 +32,10 @@ #include "testing/gtest/include/gtest/gtest.h" using chromeos::test::DemoModeSetupResult; -using chromeos::test::MockDemoModeOfflineEnrollmentHelperCreator; -using chromeos::test::MockDemoModeOnlineEnrollmentHelperCreator; using chromeos::test::SetupDummyOfflinePolicyDir; +using chromeos::test::SetupMockDemoModeNoEnrollmentHelper; +using chromeos::test::SetupMockDemoModeOfflineEnrollmentHelper; +using chromeos::test::SetupMockDemoModeOnlineEnrollmentHelper; using testing::_; namespace chromeos { @@ -110,6 +111,7 @@ } void TearDown() override { + EnterpriseEnrollmentHelper::SetEnrollmentHelperMock(nullptr); DBusThreadManager::Shutdown(); SystemSaltGetter::Shutdown(); DeviceSettingsService::Shutdown(); @@ -138,10 +140,7 @@ TEST_F(DemoSetupControllerTest, OfflineSuccess) { base::ScopedTempDir temp_dir; ASSERT_TRUE(SetupDummyOfflinePolicyDir("test", &temp_dir)); - - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOfflineEnrollmentHelperCreator< - DemoModeSetupResult::SUCCESS>); + SetupMockDemoModeOfflineEnrollmentHelper(DemoModeSetupResult::SUCCESS); policy::MockCloudPolicyStore mock_store; EXPECT_CALL(mock_store, Store(_)) .WillOnce(testing::InvokeWithoutArgs( @@ -165,10 +164,8 @@ TEST_F(DemoSetupControllerTest, OfflineDeviceLocalAccountPolicyStoreFailed) { base::ScopedTempDir temp_dir; ASSERT_TRUE(SetupDummyOfflinePolicyDir("test", &temp_dir)); + SetupMockDemoModeOfflineEnrollmentHelper(DemoModeSetupResult::SUCCESS); - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOfflineEnrollmentHelperCreator< - DemoModeSetupResult::SUCCESS>); policy::MockCloudPolicyStore mock_store; EXPECT_CALL(mock_store, Store(_)) .WillOnce(testing::InvokeWithoutArgs( @@ -193,10 +190,7 @@ TEST_F(DemoSetupControllerTest, OfflineInvalidDeviceLocalAccountPolicyBlob) { base::ScopedTempDir temp_dir; ASSERT_TRUE(SetupDummyOfflinePolicyDir("", &temp_dir)); - - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOfflineEnrollmentHelperCreator< - DemoModeSetupResult::SUCCESS>); + SetupMockDemoModeOfflineEnrollmentHelper(DemoModeSetupResult::SUCCESS); tested_controller_->set_demo_config(DemoSession::DemoModeConfig::kOffline); tested_controller_->SetPreinstalledOfflineResourcesPathForTesting( @@ -217,9 +211,7 @@ base::ScopedTempDir temp_dir; ASSERT_TRUE(SetupDummyOfflinePolicyDir("test", &temp_dir)); - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOfflineEnrollmentHelperCreator< - DemoModeSetupResult::ERROR_DEFAULT>); + SetupMockDemoModeOfflineEnrollmentHelper(DemoModeSetupResult::ERROR_DEFAULT); policy::MockCloudPolicyStore mock_store; EXPECT_CALL(mock_store, Store(_)).Times(0); @@ -244,9 +236,8 @@ base::ScopedTempDir temp_dir; ASSERT_TRUE(SetupDummyOfflinePolicyDir("test", &temp_dir)); - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOfflineEnrollmentHelperCreator< - DemoModeSetupResult::ERROR_POWERWASH_REQUIRED>); + SetupMockDemoModeOfflineEnrollmentHelper( + DemoModeSetupResult::ERROR_POWERWASH_REQUIRED); policy::MockCloudPolicyStore mock_store; EXPECT_CALL(mock_store, Store(_)).Times(0); @@ -268,8 +259,7 @@ } TEST_F(DemoSetupControllerTest, OnlineSuccess) { - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOnlineEnrollmentHelperCreator<DemoModeSetupResult::SUCCESS>); + SetupMockDemoModeOnlineEnrollmentHelper(DemoModeSetupResult::SUCCESS); tested_controller_->set_demo_config(DemoSession::DemoModeConfig::kOnline); tested_controller_->Enroll( @@ -283,9 +273,7 @@ } TEST_F(DemoSetupControllerTest, OnlineErrorDefault) { - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOnlineEnrollmentHelperCreator< - DemoModeSetupResult::ERROR_DEFAULT>); + SetupMockDemoModeOnlineEnrollmentHelper(DemoModeSetupResult::ERROR_DEFAULT); tested_controller_->set_demo_config(DemoSession::DemoModeConfig::kOnline); tested_controller_->Enroll( @@ -300,9 +288,8 @@ } TEST_F(DemoSetupControllerTest, OnlineErrorPowerwashRequired) { - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOnlineEnrollmentHelperCreator< - DemoModeSetupResult::ERROR_POWERWASH_REQUIRED>); + SetupMockDemoModeOnlineEnrollmentHelper( + DemoModeSetupResult::ERROR_POWERWASH_REQUIRED); tested_controller_->set_demo_config(DemoSession::DemoModeConfig::kOnline); tested_controller_->Enroll( @@ -317,8 +304,8 @@ } TEST_F(DemoSetupControllerTest, OnlineComponentError) { - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOnlineEnrollmentHelperCreator<DemoModeSetupResult::SUCCESS>); + // Expect no enrollment attempt. + SetupMockDemoModeNoEnrollmentHelper(); tested_controller_->set_demo_config(DemoSession::DemoModeConfig::kOnline); tested_controller_->SetCrOSComponentLoadErrorForTest( @@ -336,9 +323,7 @@ } TEST_F(DemoSetupControllerTest, EnrollTwice) { - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOnlineEnrollmentHelperCreator< - DemoModeSetupResult::ERROR_DEFAULT>); + SetupMockDemoModeOnlineEnrollmentHelper(DemoModeSetupResult::ERROR_DEFAULT); tested_controller_->set_demo_config(DemoSession::DemoModeConfig::kOnline); tested_controller_->Enroll( @@ -353,8 +338,7 @@ helper_->Reset(); - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockDemoModeOnlineEnrollmentHelperCreator<DemoModeSetupResult::SUCCESS>); + SetupMockDemoModeOnlineEnrollmentHelper(DemoModeSetupResult::SUCCESS); tested_controller_->set_demo_config(DemoSession::DemoModeConfig::kOnline); tested_controller_->Enroll(
diff --git a/chrome/browser/chromeos/login/demo_mode/demo_setup_test_utils.cc b/chrome/browser/chromeos/login/demo_mode/demo_setup_test_utils.cc index 48251fb..c97001f 100644 --- a/chrome/browser/chromeos/login/demo_mode/demo_setup_test_utils.cc +++ b/chrome/browser/chromeos/login/demo_mode/demo_setup_test_utils.cc
@@ -9,10 +9,90 @@ #include "base/threading/thread_restrictions.h" #include "components/policy/proto/device_management_backend.pb.h" +using testing::_; + +namespace { + +MATCHER(ConfigIsAttestation, "") { + return arg.mode == policy::EnrollmentConfig::MODE_ATTESTATION; +} + +MATCHER(ConfigIsOfflineDemo, "") { + return arg.mode == policy::EnrollmentConfig::MODE_OFFLINE_DEMO; +} + +} // namespace + namespace chromeos { namespace test { +void SetupMockDemoModeNoEnrollmentHelper() { + std::unique_ptr<EnterpriseEnrollmentHelperMock> mock = + std::make_unique<EnterpriseEnrollmentHelperMock>(); + EXPECT_CALL(*mock, Setup(_, _, _)).Times(0); + EnterpriseEnrollmentHelper::SetEnrollmentHelperMock(std::move(mock)); +} + +void SetupMockDemoModeOnlineEnrollmentHelper(DemoModeSetupResult result) { + std::unique_ptr<EnterpriseEnrollmentHelperMock> mock = + std::make_unique<EnterpriseEnrollmentHelperMock>(); + auto* mock_ptr = mock.get(); + EXPECT_CALL(*mock, Setup(_, ConfigIsAttestation(), _)); + + EXPECT_CALL(*mock, EnrollUsingAttestation()) + .WillRepeatedly(testing::Invoke([mock_ptr, result]() { + switch (result) { + case DemoModeSetupResult::SUCCESS: + mock_ptr->status_consumer()->OnDeviceEnrolled(); + break; + case DemoModeSetupResult::ERROR_POWERWASH_REQUIRED: + mock_ptr->status_consumer()->OnEnrollmentError( + policy::EnrollmentStatus::ForLockError( + chromeos::InstallAttributes::LOCK_ALREADY_LOCKED)); + break; + case DemoModeSetupResult::ERROR_DEFAULT: + mock_ptr->status_consumer()->OnEnrollmentError( + policy::EnrollmentStatus::ForRegistrationError( + policy::DeviceManagementStatus:: + DM_STATUS_TEMPORARY_UNAVAILABLE)); + break; + default: + NOTREACHED(); + } + })); + EnterpriseEnrollmentHelper::SetEnrollmentHelperMock(std::move(mock)); +}; + +void SetupMockDemoModeOfflineEnrollmentHelper(DemoModeSetupResult result) { + std::unique_ptr<EnterpriseEnrollmentHelperMock> mock = + std::make_unique<EnterpriseEnrollmentHelperMock>(); + auto* mock_ptr = mock.get(); + EXPECT_CALL(*mock, Setup(_, ConfigIsOfflineDemo(), _)); + + EXPECT_CALL(*mock, EnrollForOfflineDemo()) + .WillRepeatedly(testing::Invoke([mock_ptr, result]() { + switch (result) { + case DemoModeSetupResult::SUCCESS: + mock_ptr->status_consumer()->OnDeviceEnrolled(); + break; + case DemoModeSetupResult::ERROR_POWERWASH_REQUIRED: + mock_ptr->status_consumer()->OnEnrollmentError( + policy::EnrollmentStatus::ForLockError( + chromeos::InstallAttributes::LOCK_READBACK_ERROR)); + break; + case DemoModeSetupResult::ERROR_DEFAULT: + mock_ptr->status_consumer()->OnEnrollmentError( + policy::EnrollmentStatus::ForStatus( + policy::EnrollmentStatus::OFFLINE_POLICY_DECODING_FAILED)); + break; + default: + NOTREACHED(); + } + })); + EnterpriseEnrollmentHelper::SetEnrollmentHelperMock(std::move(mock)); +}; + bool SetupDummyOfflinePolicyDir(const std::string& account_id, base::ScopedTempDir* temp_dir) { base::ScopedAllowBlockingForTesting allow_io;
diff --git a/chrome/browser/chromeos/login/demo_mode/demo_setup_test_utils.h b/chrome/browser/chromeos/login/demo_mode/demo_setup_test_utils.h index 29dd4cac..27fac3a7 100644 --- a/chrome/browser/chromeos/login/demo_mode/demo_setup_test_utils.h +++ b/chrome/browser/chromeos/login/demo_mode/demo_setup_test_utils.h
@@ -29,75 +29,17 @@ ERROR_POWERWASH_REQUIRED }; +// Helper method that mocks EnterpriseEnrollmentHelper to ensure that no +// enrollment attempt was made. +void SetupMockDemoModeNoEnrollmentHelper(); + // Helper method that mocks EnterpriseEnrollmentHelper for online Demo Mode // setup. It simulates specified Demo Mode enrollment |result|. -template <DemoModeSetupResult result> -EnterpriseEnrollmentHelper* MockDemoModeOnlineEnrollmentHelperCreator( - EnterpriseEnrollmentHelper::EnrollmentStatusConsumer* status_consumer, - const policy::EnrollmentConfig& enrollment_config, - const std::string& enrolling_user_domain) { - EnterpriseEnrollmentHelperMock* mock = - new EnterpriseEnrollmentHelperMock(status_consumer); - - EXPECT_EQ(enrollment_config.mode, policy::EnrollmentConfig::MODE_ATTESTATION); - EXPECT_CALL(*mock, EnrollUsingAttestation()) - .WillRepeatedly(testing::Invoke([mock]() { - switch (result) { - case DemoModeSetupResult::SUCCESS: - mock->status_consumer()->OnDeviceEnrolled(); - break; - case DemoModeSetupResult::ERROR_POWERWASH_REQUIRED: - mock->status_consumer()->OnEnrollmentError( - policy::EnrollmentStatus::ForLockError( - chromeos::InstallAttributes::LOCK_ALREADY_LOCKED)); - break; - case DemoModeSetupResult::ERROR_DEFAULT: - mock->status_consumer()->OnEnrollmentError( - policy::EnrollmentStatus::ForRegistrationError( - policy::DeviceManagementStatus:: - DM_STATUS_TEMPORARY_UNAVAILABLE)); - break; - default: - NOTREACHED(); - } - })); - return mock; -} +void SetupMockDemoModeOnlineEnrollmentHelper(DemoModeSetupResult result); // Helper method that mocks EnterpriseEnrollmentHelper for offline Demo Mode // setup. It simulates specified Demo Mode enrollment |result|. -template <DemoModeSetupResult result> -EnterpriseEnrollmentHelper* MockDemoModeOfflineEnrollmentHelperCreator( - EnterpriseEnrollmentHelper::EnrollmentStatusConsumer* status_consumer, - const policy::EnrollmentConfig& enrollment_config, - const std::string& enrolling_user_domain) { - EnterpriseEnrollmentHelperMock* mock = - new EnterpriseEnrollmentHelperMock(status_consumer); - - EXPECT_EQ(enrollment_config.mode, - policy::EnrollmentConfig::MODE_OFFLINE_DEMO); - EXPECT_CALL(*mock, EnrollForOfflineDemo()) - .WillRepeatedly(testing::Invoke([mock]() { - switch (result) { - case DemoModeSetupResult::SUCCESS: - mock->status_consumer()->OnDeviceEnrolled(); - break; - case DemoModeSetupResult::ERROR_POWERWASH_REQUIRED: - mock->status_consumer()->OnEnrollmentError( - policy::EnrollmentStatus::ForLockError( - chromeos::InstallAttributes::LOCK_READBACK_ERROR)); - break; - case DemoModeSetupResult::ERROR_DEFAULT: - mock->status_consumer()->OnEnrollmentError( - policy::EnrollmentStatus::ForStatus( - policy::EnrollmentStatus::OFFLINE_POLICY_DECODING_FAILED)); - break; - default: - NOTREACHED(); - } - })); - return mock; -} +void SetupMockDemoModeOfflineEnrollmentHelper(DemoModeSetupResult result); // Creates fake offline policy directory to be used in tests. bool SetupDummyOfflinePolicyDir(const std::string& account_id,
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_regular.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_regular.cc index df625e7..86d3f74 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_regular.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_regular.cc
@@ -275,16 +275,13 @@ // |profile| has to be a signed-in profile with IdentityManager already // created. Otherwise, just crash to collect stack. DCHECK(identity_manager); - const AccountInfo account_info = identity_manager->GetPrimaryAccountInfo(); + const CoreAccountInfo account_info = + identity_manager->GetPrimaryAccountInfo(); // A regular signed-in (i.e., non-login) profile should always have an email. // TODO(crbug.com/857494): Enable this DCHECK once all browser tests create // correctly signed in profiles. // DCHECK(!account_info.email.empty()); - return account_info.email.empty() - ? EmptyAccountId() - : AccountId::FromUserEmailGaiaId( - gaia::CanonicalizeEmail(account_info.email), - account_info.gaia); + return AccountIdFromAccountInfo(account_info); } void EasyUnlockServiceRegular::SetHardlockAfterKeyOperation(
diff --git a/chrome/browser/chromeos/login/enrollment/enrollment_screen.h b/chrome/browser/chromeos/login/enrollment/enrollment_screen.h index 10121eb..99e2494 100644 --- a/chrome/browser/chromeos/login/enrollment/enrollment_screen.h +++ b/chrome/browser/chromeos/login/enrollment/enrollment_screen.h
@@ -33,6 +33,10 @@ class BaseScreenDelegate; class ScreenManager; +namespace test { +class EnrollmentHelperMixin; +} + // The screen implementation that links the enterprise enrollment UI into the // OOBE wizard. class EnrollmentScreen @@ -92,28 +96,12 @@ friend class MultiLicenseEnrollmentScreenUnitTest; friend class ZeroTouchEnrollmentScreenUnitTest; friend class AutomaticReenrollmentScreenUnitTest; - friend class EnterpriseEnrollmentConfigurationTest; + friend class test::EnrollmentHelperMixin; FRIEND_TEST_ALL_PREFIXES(AttestationAuthEnrollmentScreenTest, TestCancel); FRIEND_TEST_ALL_PREFIXES(ForcedAttestationAuthEnrollmentScreenTest, TestCancel); FRIEND_TEST_ALL_PREFIXES(MultiAuthEnrollmentScreenTest, TestCancel); - FRIEND_TEST_ALL_PREFIXES(EnterpriseEnrollmentTest, - TestProperPageGetsLoadedOnEnrollmentSuccess); - FRIEND_TEST_ALL_PREFIXES(EnterpriseEnrollmentTest, - TestAttributePromptPageGetsLoaded); - FRIEND_TEST_ALL_PREFIXES(EnterpriseEnrollmentTest, - TestAuthCodeGetsProperlyReceivedFromGaia); - FRIEND_TEST_ALL_PREFIXES(ActiveDirectoryJoinTest, - TestActiveDirectoryEnrollment_Success); - FRIEND_TEST_ALL_PREFIXES(ActiveDirectoryJoinTest, - TestActiveDirectoryEnrollment_DistinguishedName); - FRIEND_TEST_ALL_PREFIXES(ActiveDirectoryJoinTest, - TestActiveDirectoryEnrollment_UIErrors); - FRIEND_TEST_ALL_PREFIXES(ActiveDirectoryJoinTest, - TestActiveDirectoryEnrollment_ErrorCard); - FRIEND_TEST_ALL_PREFIXES(ActiveDirectoryJoinTest, - TestActiveDirectoryEnrollment_Streamline); FRIEND_TEST_ALL_PREFIXES(ZeroTouchEnrollmentScreenUnitTest, Retry); FRIEND_TEST_ALL_PREFIXES(ZeroTouchEnrollmentScreenUnitTest, TestSuccess); FRIEND_TEST_ALL_PREFIXES(ZeroTouchEnrollmentScreenUnitTest,
diff --git a/chrome/browser/chromeos/login/enrollment/enrollment_screen_unittest.cc b/chrome/browser/chromeos/login/enrollment/enrollment_screen_unittest.cc index 7907892..88fe7246 100644 --- a/chrome/browser/chromeos/login/enrollment/enrollment_screen_unittest.cc +++ b/chrome/browser/chromeos/login/enrollment/enrollment_screen_unittest.cc
@@ -94,19 +94,16 @@ // appropriate expectations for testing with the Google Mock framework. // The template parameter should_enroll indicates whether or not // the EnterpriseEnrollmentHelper should be mocked to successfully enroll. - template <AttestationEnrollmentStatus status> - static EnterpriseEnrollmentHelper* MockEnrollmentHelperCreator( - EnterpriseEnrollmentHelper::EnrollmentStatusConsumer* status_consumer, - const policy::EnrollmentConfig& enrollment_config, - const std::string& enrolling_user_domain) { - EnterpriseEnrollmentHelperMock* mock = - new EnterpriseEnrollmentHelperMock(status_consumer); + void SetupMockEnrollmentHelper(AttestationEnrollmentStatus status) { + std::unique_ptr<EnterpriseEnrollmentHelperMock> mock = + std::make_unique<EnterpriseEnrollmentHelperMock>(); + EnterpriseEnrollmentHelperMock* mock_ptr = mock.get(); if (status == SUCCESS) { // Define behavior of EnrollUsingAttestation to successfully enroll. EXPECT_CALL(*mock, EnrollUsingAttestation()) .Times(AnyNumber()) - .WillRepeatedly(Invoke([mock]() { - static_cast<EnrollmentScreen*>(mock->status_consumer()) + .WillRepeatedly(Invoke([mock_ptr]() { + static_cast<EnrollmentScreen*>(mock_ptr->status_consumer()) ->ShowEnrollmentStatusOnSuccess(); })); } else { @@ -120,16 +117,17 @@ DM_STATUS_TEMPORARY_UNAVAILABLE); EXPECT_CALL(*mock, EnrollUsingAttestation()) .Times(AnyNumber()) - .WillRepeatedly(Invoke([mock, enrollment_status]() { - mock->status_consumer()->OnEnrollmentError(enrollment_status); + .WillRepeatedly(Invoke([mock_ptr, enrollment_status]() { + mock_ptr->status_consumer()->OnEnrollmentError(enrollment_status); })); } // Define behavior of ClearAuth to only run the callback it is given. EXPECT_CALL(*mock, ClearAuth(_)) .Times(AnyNumber()) .WillRepeatedly(Invoke( - [](const base::RepeatingClosure& callback) { callback.Run(); })); - return mock; + [](base::OnceClosure callback) { std::move(callback).Run(); })); + + EnterpriseEnrollmentHelper::SetEnrollmentHelperMock(std::move(mock)); } void SetUpEnrollmentScreen() override { @@ -159,9 +157,7 @@ void TestRetry() { // Define behavior of EnterpriseEnrollmentHelperMock to always fail // enrollment. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &ZeroTouchEnrollmentScreenUnitTest::MockEnrollmentHelperCreator< - DMSERVER_ERROR>); + SetupMockEnrollmentHelper(DMSERVER_ERROR); SetUpEnrollmentScreen(); @@ -180,9 +176,7 @@ void TestFinishEnrollmentFlow() { // Define behavior of EnterpriseEnrollmentHelperMock to successfully enroll. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &ZeroTouchEnrollmentScreenUnitTest::MockEnrollmentHelperCreator< - SUCCESS>); + SetupMockEnrollmentHelper(SUCCESS); SetUpEnrollmentScreen(); @@ -201,9 +195,7 @@ void TestFallback() { // Define behavior of EnterpriseEnrollmentHelperMock to fail // attestation-based enrollment. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &ZeroTouchEnrollmentScreenUnitTest::MockEnrollmentHelperCreator< - DEVICE_NOT_SETUP_FOR_ZERO_TOUCH>); + SetupMockEnrollmentHelper(DEVICE_NOT_SETUP_FOR_ZERO_TOUCH); SetUpEnrollmentScreenForFallback(); @@ -233,9 +225,7 @@ TEST_F(ZeroTouchEnrollmentScreenUnitTest, DoNotRetryOnTopOfUser) { // Define behavior of EnterpriseEnrollmentHelperMock to always fail // enrollment. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &ZeroTouchEnrollmentScreenUnitTest::MockEnrollmentHelperCreator< - DMSERVER_ERROR>); + SetupMockEnrollmentHelper(DMSERVER_ERROR); SetUpEnrollmentScreen(); @@ -261,8 +251,7 @@ TEST_F(ZeroTouchEnrollmentScreenUnitTest, DoNotRetryAfterSuccess) { // Define behavior of EnterpriseEnrollmentHelperMock to successfully enroll. - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &ZeroTouchEnrollmentScreenUnitTest::MockEnrollmentHelperCreator<SUCCESS>); + SetupMockEnrollmentHelper(SUCCESS); SetUpEnrollmentScreen(); @@ -329,32 +318,25 @@ EnrollmentScreenUnitTest::SetUpEnrollmentScreen(); } - static EnterpriseEnrollmentHelper* MockEnrollmentHelperCreator( - EnterpriseEnrollmentHelper::EnrollmentStatusConsumer* status_consumer, - const policy::EnrollmentConfig& enrollment_config, - const std::string& enrolling_user_domain) { - EnterpriseEnrollmentHelperMock* mock = - new EnterpriseEnrollmentHelperMock(status_consumer); - EXPECT_CALL(*mock, EnrollUsingAuthCode(_, _)) - .Times(AnyNumber()) - .WillRepeatedly(Invoke([mock](const std::string&, bool) { - EnrollmentLicenseMap licenses; - static_cast<EnrollmentScreen*>(mock->status_consumer()) - ->OnMultipleLicensesAvailable(licenses); - })); - EXPECT_CALL(*mock, UseLicenseType(::policy::LicenseType::ANNUAL)).Times(1); - - return mock; - } - private: DISALLOW_COPY_AND_ASSIGN(MultiLicenseEnrollmentScreenUnitTest); }; // Sign in and check that selected license type is propagated correctly. TEST_F(MultiLicenseEnrollmentScreenUnitTest, TestLicenseSelection) { - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MultiLicenseEnrollmentScreenUnitTest::MockEnrollmentHelperCreator); + std::unique_ptr<EnterpriseEnrollmentHelperMock> mock = + std::make_unique<EnterpriseEnrollmentHelperMock>(); + auto* mock_ref = mock.get(); + EXPECT_CALL(*mock, EnrollUsingAuthCode(_, _)) + .Times(AnyNumber()) + .WillRepeatedly(Invoke([mock_ref](const std::string&, bool) { + EnrollmentLicenseMap licenses; + static_cast<EnrollmentScreen*>(mock_ref->status_consumer()) + ->OnMultipleLicensesAvailable(licenses); + })); + EXPECT_CALL(*mock, UseLicenseType(::policy::LicenseType::ANNUAL)).Times(1); + + EnterpriseEnrollmentHelper::SetEnrollmentHelperMock(std::move(mock)); EXPECT_CALL(*GetMockScreenView(), SetEnrollmentConfig(_, _)).Times(1);
diff --git a/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper.cc b/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper.cc index f7a7ae2..95d78f20 100644 --- a/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper.cc +++ b/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper.cc
@@ -10,15 +10,18 @@ namespace chromeos { -EnterpriseEnrollmentHelper::CreateMockEnrollmentHelper - EnterpriseEnrollmentHelper::create_mock_enrollment_helper_ = nullptr; +EnterpriseEnrollmentHelper* + EnterpriseEnrollmentHelper::mock_enrollment_helper_ = nullptr; EnterpriseEnrollmentHelper::~EnterpriseEnrollmentHelper() {} // static -void EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - CreateMockEnrollmentHelper creator) { - create_mock_enrollment_helper_ = creator; +void EnterpriseEnrollmentHelper::SetEnrollmentHelperMock( + std::unique_ptr<EnterpriseEnrollmentHelper> mock) { + if (mock_enrollment_helper_) { + delete mock_enrollment_helper_; + } + mock_enrollment_helper_ = mock.release(); } // static @@ -27,26 +30,26 @@ ActiveDirectoryJoinDelegate* ad_join_delegate, const policy::EnrollmentConfig& enrollment_config, const std::string& enrolling_user_domain) { - // Create a mock instance. - if (create_mock_enrollment_helper_) { - // The evaluated code might call |SetupEnrollmentHelperMock| to setup a new - // allocator, so we reset the enrollment helper to null before that. - auto enrollment_helper_allocator = create_mock_enrollment_helper_; - create_mock_enrollment_helper_ = nullptr; - EnterpriseEnrollmentHelper* helper = enrollment_helper_allocator( - status_consumer, enrollment_config, enrolling_user_domain); - return base::WrapUnique(helper); - } + std::unique_ptr<EnterpriseEnrollmentHelper> result; - return base::WrapUnique(new EnterpriseEnrollmentHelperImpl( - status_consumer, ad_join_delegate, enrollment_config, - enrolling_user_domain)); + // Create a mock instance. + if (mock_enrollment_helper_) { + result = base::WrapUnique(mock_enrollment_helper_); + mock_enrollment_helper_ = nullptr; + } else { + result = std::make_unique<EnterpriseEnrollmentHelperImpl>(); + } + result->set_status_consumer(status_consumer); + result->Setup(ad_join_delegate, enrollment_config, enrolling_user_domain); + return result; } -EnterpriseEnrollmentHelper::EnterpriseEnrollmentHelper( - EnrollmentStatusConsumer* status_consumer) - : status_consumer_(status_consumer) { +EnterpriseEnrollmentHelper::EnterpriseEnrollmentHelper() {} + +void EnterpriseEnrollmentHelper::set_status_consumer( + EnrollmentStatusConsumer* status_consumer) { DCHECK(status_consumer_); + status_consumer_ = status_consumer; } } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper.h b/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper.h index c6c653d..5916fe10 100644 --- a/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper.h +++ b/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper.h
@@ -88,16 +88,10 @@ const policy::EnrollmentConfig& enrollment_config, const std::string& enrolling_user_domain); - using CreateMockEnrollmentHelper = - EnterpriseEnrollmentHelper* (*)(EnrollmentStatusConsumer* status_consumer, - const policy::EnrollmentConfig& - enrollment_config, - const std::string& enrolling_user_domain); - - // Use |creator| instead of the default enrollment helper allocator. This - // allows tests to substitute in a mock enrollment helper. This function will - // only be used once. - static void SetupEnrollmentHelperMock(CreateMockEnrollmentHelper creator); + // Sets up a mock object that would be returned by next Create call. + // This call passes ownership of |mock|. + static void SetEnrollmentHelperMock( + std::unique_ptr<EnterpriseEnrollmentHelper> mock); virtual ~EnterpriseEnrollmentHelper(); @@ -160,23 +154,29 @@ // used) and revokes fetched tokens. // Does not revoke the additional token if enrollment finished successfully. // Calls |callback| on completion. - virtual void ClearAuth(const base::Closure& callback) = 0; + virtual void ClearAuth(base::OnceClosure callback) = 0; protected: - // |status_consumer| must outlive |this|. Moreover, the user of this class - // is responsible for clearing auth data in some cases (see comment for - // EnrollUsingProfile()). - explicit EnterpriseEnrollmentHelper( - EnrollmentStatusConsumer* status_consumer); + // The user of this class is responsible for clearing auth data in some cases + // (see comment for EnrollUsingProfile()). + EnterpriseEnrollmentHelper(); - EnrollmentStatusConsumer* status_consumer() { return status_consumer_; } + // This method is called once from Create method. + virtual void Setup(ActiveDirectoryJoinDelegate* ad_join_delegate, + const policy::EnrollmentConfig& enrollment_config, + const std::string& enrolling_user_domain) = 0; + + // This method is used in Create method. |status_consumer| must outlive + // |this|. + void set_status_consumer(EnrollmentStatusConsumer* status_consumer); + + EnrollmentStatusConsumer* status_consumer() const { return status_consumer_; } private: EnrollmentStatusConsumer* status_consumer_; - // If this is not nullptr, then it will be used to create the enrollment - // helper. |create_mock_enrollment_helper_| needs to outlive this class. - static CreateMockEnrollmentHelper create_mock_enrollment_helper_; + // If this is not nullptr, then it will be used to as next enrollment helper. + static EnterpriseEnrollmentHelper* mock_enrollment_helper_; DISALLOW_COPY_AND_ASSIGN(EnterpriseEnrollmentHelper); };
diff --git a/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_impl.cc b/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_impl.cc index 557e0e4..6e327c3e 100644 --- a/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_impl.cc +++ b/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_impl.cc
@@ -72,16 +72,7 @@ namespace chromeos { -EnterpriseEnrollmentHelperImpl::EnterpriseEnrollmentHelperImpl( - EnrollmentStatusConsumer* status_consumer, - ActiveDirectoryJoinDelegate* ad_join_delegate, - const policy::EnrollmentConfig& enrollment_config, - const std::string& enrolling_user_domain) - : EnterpriseEnrollmentHelper(status_consumer), - enrollment_config_(enrollment_config), - enrolling_user_domain_(enrolling_user_domain), - ad_join_delegate_(ad_join_delegate), - weak_ptr_factory_(this) { +EnterpriseEnrollmentHelperImpl::EnterpriseEnrollmentHelperImpl() { // Init the TPM if it has not been done until now (in debug build we might // have not done that yet). DBusThreadManager::Get()->GetCryptohomeClient()->TpmCanAttemptOwnership( @@ -95,6 +86,15 @@ (oauth_status_ == OAUTH_FINISHED && (success_ || oauth_data_cleared_))); } +void EnterpriseEnrollmentHelperImpl::Setup( + ActiveDirectoryJoinDelegate* ad_join_delegate, + const policy::EnrollmentConfig& enrollment_config, + const std::string& enrolling_user_domain) { + ad_join_delegate_ = ad_join_delegate; + enrollment_config_ = enrollment_config; + enrolling_user_domain_ = enrolling_user_domain; +} + void EnterpriseEnrollmentHelperImpl::EnrollUsingAuthCode( const std::string& auth_code, bool fetch_additional_token) { @@ -206,7 +206,7 @@ FROM_HERE, device_account_initializer_.release()); } -void EnterpriseEnrollmentHelperImpl::ClearAuth(const base::Closure& callback) { +void EnterpriseEnrollmentHelperImpl::ClearAuth(base::OnceClosure callback) { if (oauth_status_ != OAUTH_NOT_STARTED) { // Do not revoke the additional token if enrollment has finished // successfully. @@ -228,8 +228,9 @@ } auth_data_.reset(); chromeos::ProfileHelper::Get()->ClearSigninProfile( - base::Bind(&EnterpriseEnrollmentHelperImpl::OnSigninProfileCleared, - weak_ptr_factory_.GetWeakPtr(), callback)); + base::AdaptCallbackForRepeating(base::BindOnce( + &EnterpriseEnrollmentHelperImpl::OnSigninProfileCleared, + weak_ptr_factory_.GetWeakPtr(), std::move(callback)))); } bool EnterpriseEnrollmentHelperImpl::ShouldCheckLicenseType() const { @@ -601,9 +602,9 @@ } void EnterpriseEnrollmentHelperImpl::OnSigninProfileCleared( - const base::Closure& callback) { + base::OnceClosure callback) { oauth_data_cleared_ = true; - callback.Run(); + std::move(callback).Run(); } } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_impl.h b/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_impl.h index 085f07e..7b9b046 100644 --- a/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_impl.h +++ b/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_impl.h
@@ -31,14 +31,10 @@ public policy::DeviceAccountInitializer::Delegate, public policy::DeviceCloudPolicyManagerChromeOS::Observer { public: - EnterpriseEnrollmentHelperImpl( - EnrollmentStatusConsumer* status_consumer, - ActiveDirectoryJoinDelegate* ad_join_delegate, - const policy::EnrollmentConfig& enrollment_config, - const std::string& enrolling_user_domain); + EnterpriseEnrollmentHelperImpl(); ~EnterpriseEnrollmentHelperImpl() override; - // Overridden from EnterpriseEnrollmentHelper: + // EnterpriseEnrollmentHelper: void EnrollUsingAuthCode(const std::string& auth_code, bool fetch_additional_token) override; void EnrollUsingToken(const std::string& token) override; @@ -46,11 +42,14 @@ void EnrollUsingAttestation() override; void EnrollForOfflineDemo() override; void RestoreAfterRollback() override; - void ClearAuth(const base::Closure& callback) override; + void ClearAuth(base::OnceClosure callback) override; void UseLicenseType(policy::LicenseType type) override; void GetDeviceAttributeUpdatePermission() override; void UpdateDeviceAttributes(const std::string& asset_id, const std::string& location) override; + void Setup(ActiveDirectoryJoinDelegate* ad_join_delegate, + const policy::EnrollmentConfig& enrollment_config, + const std::string& enrolling_user_domain) override; // DeviceCloudPolicyManagerChromeOS::Observer: void OnDeviceCloudPolicyManagerConnected() override; @@ -101,13 +100,13 @@ // Called by ProfileHelper when a signin profile clearance has finished. // |callback| is a callback, that was passed to ClearAuth() before. - void OnSigninProfileCleared(const base::Closure& callback); + void OnSigninProfileCleared(base::OnceClosure callback); // Called when CloudPolicyClient exists, so device account can be initialized. void RestoreAfterRollbackInitialized(); - const policy::EnrollmentConfig enrollment_config_; - const std::string enrolling_user_domain_; + policy::EnrollmentConfig enrollment_config_; + std::string enrolling_user_domain_; bool fetch_additional_token_; std::string additional_token_; @@ -125,7 +124,7 @@ std::unique_ptr<policy::PolicyOAuth2TokenFetcher> oauth_fetcher_; std::unique_ptr<policy::DeviceAccountInitializer> device_account_initializer_; - base::WeakPtrFactory<EnterpriseEnrollmentHelperImpl> weak_ptr_factory_; + base::WeakPtrFactory<EnterpriseEnrollmentHelperImpl> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(EnterpriseEnrollmentHelperImpl); };
diff --git a/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_mock.cc b/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_mock.cc index b3a45e2..e91e008 100644 --- a/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_mock.cc +++ b/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_mock.cc
@@ -7,14 +7,12 @@ namespace chromeos { -EnterpriseEnrollmentHelperMock::EnterpriseEnrollmentHelperMock( - EnrollmentStatusConsumer* status_consumer) - : EnterpriseEnrollmentHelper(status_consumer) {} +EnterpriseEnrollmentHelperMock::EnterpriseEnrollmentHelperMock() {} EnterpriseEnrollmentHelperMock::~EnterpriseEnrollmentHelperMock() {} EnterpriseEnrollmentHelper::EnrollmentStatusConsumer* -EnterpriseEnrollmentHelperMock::status_consumer() { +EnterpriseEnrollmentHelperMock::status_consumer() const { return EnterpriseEnrollmentHelper::status_consumer(); }
diff --git a/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_mock.h b/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_mock.h index dbb05c1..5ca5fdc4 100644 --- a/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_mock.h +++ b/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_mock.h
@@ -16,12 +16,15 @@ // Mocks out EnterpriseEnrollmentHelper. class EnterpriseEnrollmentHelperMock : public EnterpriseEnrollmentHelper { public: - explicit EnterpriseEnrollmentHelperMock( - EnrollmentStatusConsumer* status_consumer); + EnterpriseEnrollmentHelperMock(); ~EnterpriseEnrollmentHelperMock() override; - EnrollmentStatusConsumer* status_consumer(); + EnrollmentStatusConsumer* status_consumer() const; + MOCK_METHOD3(Setup, + void(ActiveDirectoryJoinDelegate* ad_join_delegate, + const policy::EnrollmentConfig& enrollment_config, + const std::string& enrolling_user_domain)); MOCK_METHOD2(EnrollUsingAuthCode, void(const std::string& auth_code, bool fetch_additional_token)); MOCK_METHOD1(EnrollUsingToken, void(const std::string& token)); @@ -33,7 +36,7 @@ MOCK_METHOD0(GetDeviceAttributeUpdatePermission, void()); MOCK_METHOD2(UpdateDeviceAttributes, void(const std::string& asset_id, const std::string& location)); - MOCK_METHOD1(ClearAuth, void(const base::Closure& callback)); + MOCK_METHOD1(ClearAuth, void(base::OnceClosure callback)); }; } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/enrollment/hands_off_enrollment_browsertest.cc b/chrome/browser/chromeos/login/enrollment/hands_off_enrollment_browsertest.cc index 53e3bbe..5f846eb 100644 --- a/chrome/browser/chromeos/login/enrollment/hands_off_enrollment_browsertest.cc +++ b/chrome/browser/chromeos/login/enrollment/hands_off_enrollment_browsertest.cc
@@ -7,12 +7,13 @@ #include "chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_mock.h" #include "chrome/browser/chromeos/login/existing_user_controller.h" #include "chrome/browser/chromeos/login/login_wizard.h" +#include "chrome/browser/chromeos/login/mixin_based_in_process_browser_test.h" #include "chrome/browser/chromeos/login/oobe_screen.h" #include "chrome/browser/chromeos/login/startup_utils.h" +#include "chrome/browser/chromeos/login/test/enrollment_helper_mixin.h" #include "chrome/browser/chromeos/login/test/oobe_screen_waiter.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/policy/enrollment_status_chromeos.h" -#include "chrome/test/base/in_process_browser_test.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/shill_service_client.h" @@ -32,21 +33,21 @@ } // namespace // Hands-off enrollment flow test. -class HandsOffEnrollmentTest : public InProcessBrowserTest { +class HandsOffEnrollmentTest : public MixinBasedInProcessBrowserTest { protected: HandsOffEnrollmentTest() {} ~HandsOffEnrollmentTest() override = default; // InProcessBrowserTest: void SetUpCommandLine(base::CommandLine* command_line) override { - InProcessBrowserTest::SetUpCommandLine(command_line); + MixinBasedInProcessBrowserTest::SetUpCommandLine(command_line); command_line->AppendArg(switches::kLoginManager); command_line->AppendSwitchASCII( switches::kEnterpriseEnableZeroTouchEnrollment, "hands-off"); } void SetUpOnMainThread() override { - InProcessBrowserTest::SetUpOnMainThread(); + MixinBasedInProcessBrowserTest::SetUpOnMainThread(); ShowLoginWizard(OobeScreen::SCREEN_TEST_NO_WINDOW); // Set official build so EULA screen is not skipped by default. @@ -79,56 +80,20 @@ base::RunLoop().RunUntilIdle(); } - // Result of attestation based enrollment used by - // EnterpriseEnrollmentHelperMock. - enum class AttestationEnrollmentResult { SUCCESS, ERROR }; - - // Helper method that mocks EnterpriseEnrollmentHelper for hands-off - // enrollment. It simulates specified attestation based enrollment |result|. - template <AttestationEnrollmentResult result> - static EnterpriseEnrollmentHelper* MockEnrollmentHelperCreator( - EnterpriseEnrollmentHelper::EnrollmentStatusConsumer* status_consumer, - const policy::EnrollmentConfig& enrollment_config, - const std::string& enrolling_user_domain) { - EnterpriseEnrollmentHelperMock* mock = - new EnterpriseEnrollmentHelperMock(status_consumer); - if (result == AttestationEnrollmentResult::SUCCESS) { - // Simulate successful attestation based enrollment. - EXPECT_CALL(*mock, EnrollUsingAttestation()) - .Times(testing::AnyNumber()) - .WillRepeatedly(testing::Invoke( - [mock]() { mock->status_consumer()->OnDeviceEnrolled(); })); - EXPECT_CALL(*mock, GetDeviceAttributeUpdatePermission()) - .Times(testing::AnyNumber()) - .WillRepeatedly(testing::Invoke([mock]() { - mock->status_consumer()->OnDeviceAttributeUpdatePermission(false); - })); - } else { - // Simulate error during attestation based enrollment. - const policy::EnrollmentStatus enrollment_status = - policy::EnrollmentStatus::ForRegistrationError( - policy::DeviceManagementStatus::DM_STATUS_TEMPORARY_UNAVAILABLE); - EXPECT_CALL(*mock, GetDeviceAttributeUpdatePermission()) - .Times(testing::AnyNumber()) - .WillRepeatedly(testing::Invoke([mock, enrollment_status]() { - mock->status_consumer()->OnEnrollmentError(enrollment_status); - })); - } - // Define behavior of ClearAuth to only run the callback it is given. - EXPECT_CALL(*mock, ClearAuth(testing::_)) - .Times(testing::AnyNumber()) - .WillRepeatedly(testing::Invoke( - [](const base::RepeatingClosure& callback) { callback.Run(); })); - return mock; - } + protected: + test::EnrollmentHelperMixin enrollment_helper_{&mixin_host_}; private: DISALLOW_COPY_AND_ASSIGN(HandsOffEnrollmentTest); }; IN_PROC_BROWSER_TEST_F(HandsOffEnrollmentTest, NetworkConnectionReady) { - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockEnrollmentHelperCreator<AttestationEnrollmentResult::SUCCESS>); + enrollment_helper_.ExpectEnrollmentMode( + policy::EnrollmentConfig::MODE_ATTESTATION_LOCAL_FORCED); + enrollment_helper_.ExpectAttestationEnrollmentSuccess(); + enrollment_helper_.DisableAttributePromptUpdate(); + enrollment_helper_.SetupClearAuth(); + SimulateNetworkConnected(); WizardController::default_controller()->AdvanceToScreen( @@ -146,9 +111,11 @@ } IN_PROC_BROWSER_TEST_F(HandsOffEnrollmentTest, WaitForNetworkConnection) { - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockEnrollmentHelperCreator<AttestationEnrollmentResult::SUCCESS>); - + enrollment_helper_.ExpectEnrollmentMode( + policy::EnrollmentConfig::MODE_ATTESTATION_LOCAL_FORCED); + enrollment_helper_.ExpectAttestationEnrollmentSuccess(); + enrollment_helper_.DisableAttributePromptUpdate(); + enrollment_helper_.SetupClearAuth(); WizardController::default_controller()->AdvanceToScreen( OobeScreen::SCREEN_OOBE_WELCOME); @@ -166,8 +133,17 @@ } IN_PROC_BROWSER_TEST_F(HandsOffEnrollmentTest, EnrollmentError) { - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - &MockEnrollmentHelperCreator<AttestationEnrollmentResult::ERROR>); + enrollment_helper_.SetupClearAuth(); + const policy::EnrollmentStatus enrollment_status = + policy::EnrollmentStatus::ForRegistrationError( + policy::DeviceManagementStatus::DM_STATUS_TEMPORARY_UNAVAILABLE); + // With hands-off we expect that there will be a retry attempt, so + // set up repeated expectations. + enrollment_helper_.ExpectEnrollmentModeRepeated( + policy::EnrollmentConfig::MODE_ATTESTATION_LOCAL_FORCED); + enrollment_helper_.ExpectAttestationEnrollmentErrorRepeated( + enrollment_status); + SimulateNetworkConnected(); WizardController::default_controller()->AdvanceToScreen(
diff --git a/chrome/browser/chromeos/login/enterprise_enrollment_browsertest.cc b/chrome/browser/chromeos/login/enterprise_enrollment_browsertest.cc index d967ae5..7a05dbb 100644 --- a/chrome/browser/chromeos/login/enterprise_enrollment_browsertest.cc +++ b/chrome/browser/chromeos/login/enterprise_enrollment_browsertest.cc
@@ -17,6 +17,7 @@ #include "chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_mock.h" #include "chrome/browser/chromeos/login/login_manager_test.h" #include "chrome/browser/chromeos/login/startup_utils.h" +#include "chrome/browser/chromeos/login/test/enrollment_helper_mixin.h" #include "chrome/browser/chromeos/login/test/hid_controller_mixin.h" #include "chrome/browser/chromeos/login/test/js_checker.h" #include "chrome/browser/chromeos/login/test/oobe_configuration_waiter.h" @@ -147,74 +148,13 @@ explicit EnterpriseEnrollmentTestBase(bool should_initialize_webui) : LoginManagerTest(true /*should_launch_browser*/, should_initialize_webui) { - enrollment_setup_functions_.clear(); - - EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( - [](EnterpriseEnrollmentHelper::EnrollmentStatusConsumer* - status_consumer, - const policy::EnrollmentConfig& enrollment_config, - const std::string& enrolling_user_domain) { - - auto* mock = new EnterpriseEnrollmentHelperMock(status_consumer); - for (OnSetupEnrollmentHelper fn : enrollment_setup_functions_) - fn(mock); - return (EnterpriseEnrollmentHelper*)mock; - }); } - using OnSetupEnrollmentHelper = - std::function<void(EnterpriseEnrollmentHelperMock*)>; - - // The given function will be executed when the next enrollment helper is - // created. - void AddEnrollmentSetupFunction(OnSetupEnrollmentHelper on_setup) { - enrollment_setup_functions_.push_back(on_setup); - } - - // Set up expectations for enrollment credentials. - void ExpectEnrollmentCredentials() { - AddEnrollmentSetupFunction( - [](EnterpriseEnrollmentHelperMock* enrollment_helper) { - EXPECT_CALL(*enrollment_helper, - EnrollUsingAuthCode("test_auth_code", _)); - - ON_CALL(*enrollment_helper, ClearAuth(_)) - .WillByDefault(Invoke( - [](const base::Closure& callback) { callback.Run(); })); - }); - } // Submits regular enrollment credentials. void SubmitEnrollmentCredentials() { - enrollment_screen()->OnLoginDone("testuser@test.com", "test_auth_code"); - } - - void DisableAttributePromptUpdate() { - AddEnrollmentSetupFunction( - [](EnterpriseEnrollmentHelperMock* enrollment_helper) { - EXPECT_CALL(*enrollment_helper, GetDeviceAttributeUpdatePermission()) - .WillOnce(InvokeWithoutArgs([enrollment_helper]() { - enrollment_helper->status_consumer() - ->OnDeviceAttributeUpdatePermission(false); - })); - }); - } - - // Forces an attribute prompt to display. - void ExpectAttributePromptUpdate() { - AddEnrollmentSetupFunction( - [](EnterpriseEnrollmentHelperMock* enrollment_helper) { - // Causes the attribute-prompt flow to activate. - ON_CALL(*enrollment_helper, GetDeviceAttributeUpdatePermission()) - .WillByDefault(InvokeWithoutArgs([enrollment_helper]() { - enrollment_helper->status_consumer() - ->OnDeviceAttributeUpdatePermission(true); - })); - - // Ensures we receive the updates attributes. - EXPECT_CALL(*enrollment_helper, - UpdateDeviceAttributes("asset_id", "location")); - }); + enrollment_screen()->OnLoginDone( + "testuser@test.com", test::EnrollmentHelperMixin::kTestAuthCode); } // Fills out the UI with device attribute information and submits it. @@ -268,15 +208,13 @@ WizardController::default_controller()->screen_manager()); } - private: - static std::vector<OnSetupEnrollmentHelper> enrollment_setup_functions_; + protected: + test::EnrollmentHelperMixin enrollment_helper_{&mixin_host_}; + private: DISALLOW_COPY_AND_ASSIGN(EnterpriseEnrollmentTestBase); }; -std::vector<EnterpriseEnrollmentTestBase::OnSetupEnrollmentHelper> - EnterpriseEnrollmentTestBase::enrollment_setup_functions_; - class EnterpriseEnrollmentTest : public EnterpriseEnrollmentTestBase { public: EnterpriseEnrollmentTest() @@ -488,28 +426,6 @@ mock_auth_policy_client()->set_expected_request(std::move(request)); } - // Forces the Active Directory domain join flow during enterprise enrollment. - void SetupActiveDirectoryJoin(const std::string& expected_domain, - const std::string& domain_join_config) { - AddEnrollmentSetupFunction( - [this, expected_domain, domain_join_config]( - EnterpriseEnrollmentHelperMock* enrollment_helper) { - // Causes the attribute-prompt flow to activate. - EXPECT_CALL(*enrollment_helper, - EnrollUsingAuthCode("test_auth_code", _)) - .WillOnce(InvokeWithoutArgs( - [this, expected_domain, domain_join_config]() { - this->enrollment_screen()->JoinDomain( - kDMToken, domain_join_config, - base::BindOnce( - [](const std::string& expected_domain, - const std::string& domain) { - ASSERT_EQ(expected_domain, domain); - }, - expected_domain)); - })); - }); - } MockAuthPolicyClient* mock_auth_policy_client() { return static_cast<MockAuthPolicyClient*>( @@ -675,24 +591,6 @@ NetworkHandler::Get()->network_state_handler()->SetCheckPortalList(""); } - void TearDownOnMainThread() override { - enrollment_screen()->enrollment_helper_.reset(); - EnterpriseEnrollmentTestBase::TearDownOnMainThread(); - } - - // Set up expectations for token enrollment. - void ExpectTokenEnrollment() { - AddEnrollmentSetupFunction( - [](EnterpriseEnrollmentHelperMock* enrollment_helper) { - EXPECT_CALL(*enrollment_helper, - EnrollUsingEnrollmentToken( - "00000000-1111-2222-3333-444444444444")) - .WillOnce(InvokeWithoutArgs([enrollment_helper]() { - enrollment_helper->status_consumer()->OnDeviceEnrolled(); - })); - }); - } - protected: // Owned by DBusThreadManagerSetter chromeos::FakeUpdateEngineClient* fake_update_engine_client_; @@ -732,12 +630,12 @@ TEST_DISABLED_ON_MSAN(EnterpriseEnrollmentTest, TestAuthCodeGetsProperlyReceivedFromGaia) { ShowEnrollmentScreen(); - ExpectEnrollmentCredentials(); - SubmitEnrollmentCredentials(); + enrollment_helper_.ExpectEnrollmentMode( + policy::EnrollmentConfig::MODE_MANUAL); + enrollment_helper_.ExpectEnrollmentCredentials(); + enrollment_helper_.SetupClearAuth(); - // We need to reset enrollment_screen->enrollment_helper_, otherwise we will - // get some errors on shutdown. - enrollment_screen()->enrollment_helper_.reset(); + SubmitEnrollmentCredentials(); } // Shows the enrollment screen and simulates an enrollment failure. Verifies @@ -762,16 +660,15 @@ TEST_DISABLED_ON_MSAN(EnterpriseEnrollmentTest, TestProperPageGetsLoadedOnEnrollmentSuccess) { ShowEnrollmentScreen(); - DisableAttributePromptUpdate(); + enrollment_helper_.ExpectEnrollmentMode( + policy::EnrollmentConfig::MODE_MANUAL); + enrollment_helper_.DisableAttributePromptUpdate(); SubmitEnrollmentCredentials(); CompleteEnrollment(); // Verify that the success page is displayed. EXPECT_TRUE(IsStepDisplayed("success")); EXPECT_FALSE(IsStepDisplayed("error")); - - // We have to remove the enrollment_helper before the dtor gets called. - enrollment_screen()->enrollment_helper_.reset(); } // Shows the enrollment screen and mocks the enrollment helper to request an @@ -782,7 +679,9 @@ TEST_DISABLED_ON_MSAN(EnterpriseEnrollmentTest, TestAttributePromptPageGetsLoaded) { ShowEnrollmentScreen(); - ExpectAttributePromptUpdate(); + enrollment_helper_.ExpectEnrollmentMode( + policy::EnrollmentConfig::MODE_MANUAL); + enrollment_helper_.ExpectAttributePromptUpdate("asset_id", "location"); SubmitEnrollmentCredentials(); CompleteEnrollment(); @@ -792,9 +691,6 @@ EXPECT_FALSE(IsStepDisplayed("error")); SubmitAttributePromptUpdate(); - - // We have to remove the enrollment_helper before the dtor gets called. - enrollment_screen()->enrollment_helper_.reset(); } // Shows the enrollment screen and mocks the enrollment helper to show Active @@ -805,8 +701,9 @@ TEST_DISABLED_ON_MSAN(ActiveDirectoryJoinTest, TestActiveDirectoryEnrollment_Success) { ShowEnrollmentScreen(); - DisableAttributePromptUpdate(); - SetupActiveDirectoryJoin(kAdUserDomain, std::string()); + enrollment_helper_.DisableAttributePromptUpdate(); + enrollment_helper_.SetupActiveDirectoryJoin( + enrollment_screen(), kAdUserDomain, std::string(), kDMToken); SubmitEnrollmentCredentials(); chromeos::DBusThreadManager::Get() @@ -829,9 +726,6 @@ // Verify that the success page is displayed. EXPECT_TRUE(IsStepDisplayed("success")); EXPECT_FALSE(IsStepDisplayed("error")); - - // We have to remove the enrollment_helper before the dtor gets called. - enrollment_screen()->enrollment_helper_.reset(); } // Verifies that the distinguished name specified on the Active Directory join @@ -840,8 +734,10 @@ TEST_DISABLED_ON_MSAN(ActiveDirectoryJoinTest, TestActiveDirectoryEnrollment_DistinguishedName) { ShowEnrollmentScreen(); - DisableAttributePromptUpdate(); - SetupActiveDirectoryJoin(kAdMachineDomain, std::string()); + enrollment_helper_.DisableAttributePromptUpdate(); + enrollment_helper_.SetupActiveDirectoryJoin( + enrollment_screen(), kAdMachineDomain, std::string(), kDMToken); + SubmitEnrollmentCredentials(); chromeos::DBusThreadManager::Get() @@ -867,9 +763,6 @@ // Verify that the success page is displayed. EXPECT_TRUE(IsStepDisplayed("success")); EXPECT_FALSE(IsStepDisplayed("error")); - - // We have to remove the enrollment_helper before the dtor gets called. - enrollment_screen()->enrollment_helper_.reset(); } // Shows the enrollment screen and mocks the enrollment helper to show Active @@ -880,7 +773,8 @@ TEST_DISABLED_ON_MSAN(ActiveDirectoryJoinTest, TestActiveDirectoryEnrollment_UIErrors) { ShowEnrollmentScreen(); - SetupActiveDirectoryJoin(kAdUserDomain, std::string()); + enrollment_helper_.SetupActiveDirectoryJoin( + enrollment_screen(), kAdUserDomain, std::string(), kDMToken); SubmitEnrollmentCredentials(); chromeos::DBusThreadManager::Get() @@ -919,9 +813,6 @@ test::OobeJS().ExpectFalse(std::string(kAdMachineNameInput) + ".invalid"); test::OobeJS().ExpectTrue(std::string(kAdUsernameInput) + ".invalid"); test::OobeJS().ExpectFalse(std::string(kAdPasswordInput) + ".invalid"); - - // We have to remove the enrollment_helper before the dtor gets called. - enrollment_screen()->enrollment_helper_.reset(); } // Check that correct error card is shown (Active Directory one). Also checks @@ -930,7 +821,8 @@ TEST_DISABLED_ON_MSAN(ActiveDirectoryJoinTest, TestActiveDirectoryEnrollment_ErrorCard) { ShowEnrollmentScreen(); - SetupActiveDirectoryJoin(kAdUserDomain, std::string()); + enrollment_helper_.SetupActiveDirectoryJoin( + enrollment_screen(), kAdUserDomain, std::string(), kDMToken); SubmitEnrollmentCredentials(); chromeos::DBusThreadManager::Get() @@ -946,9 +838,6 @@ EXPECT_TRUE(IsStepDisplayed("active-directory-join-error")); ClickRetryOnErrorScreen(); EXPECT_TRUE(IsStepDisplayed("ad-join")); - - // We have to remove the enrollment_helper before the dtor gets called. - enrollment_screen()->enrollment_helper_.reset(); } // Check that configuration for the streamline Active Directory domain join @@ -959,7 +848,8 @@ ShowEnrollmentScreen(); std::string binary_config; EXPECT_TRUE(base::Base64Decode(kAdDomainJoinEncryptedConfig, &binary_config)); - SetupActiveDirectoryJoin(kAdUserDomain, binary_config); + enrollment_helper_.SetupActiveDirectoryJoin( + enrollment_screen(), kAdUserDomain, binary_config, kDMToken); SubmitEnrollmentCredentials(); chromeos::DBusThreadManager::Get() @@ -995,7 +885,6 @@ // Go through configuration. CheckPossibleConfiguration(kAdDomainJoinUnlockedConfig); - enrollment_screen()->enrollment_helper_.reset(); } // Check that configuration lets correctly pass Welcome screen. @@ -1141,8 +1030,10 @@ // screen. IN_PROC_BROWSER_TEST_F(EnterpriseEnrollmentConfigurationTest, TestEnrollUsingToken) { - ExpectTokenEnrollment(); - DisableAttributePromptUpdate(); + enrollment_helper_.DisableAttributePromptUpdate(); + // Token from configuration file: + enrollment_helper_.ExpectTokenEnrollmentSuccess( + "00000000-1111-2222-3333-444444444444"); LoadConfiguration(); OobeScreenWaiter(OobeScreen::SCREEN_OOBE_ENROLLMENT).Wait(); ExecutePendingJavaScript();
diff --git a/chrome/browser/chromeos/login/screens/update_screen.cc b/chrome/browser/chromeos/login/screens/update_screen.cc index cb0b2342..17218fb 100644 --- a/chrome/browser/chromeos/login/screens/update_screen.cc +++ b/chrome/browser/chromeos/login/screens/update_screen.cc
@@ -95,33 +95,9 @@ // its login page before error message appears. const int kDelayErrorMessageSec = 10; -// Invoked from call to RequestUpdateCheck upon completion of the DBus call. -void StartUpdateCallback(UpdateScreen* screen, - UpdateEngineClient::UpdateCheckResult result) { - VLOG(1) << "Callback from RequestUpdateCheck, result " << result; - if (UpdateScreen::HasInstance(screen) && - result != UpdateEngineClient::UPDATE_RESULT_SUCCESS) { - screen->ExitUpdate(UpdateScreen::REASON_UPDATE_INIT_FAILED); - } -} - } // anonymous namespace // static -UpdateScreen::InstanceSet& UpdateScreen::GetInstanceSet() { - static base::NoDestructor<std::set<UpdateScreen*>> instance_set; - DCHECK_CURRENTLY_ON(BrowserThread::UI); // not threadsafe. - return *instance_set; -} - -// static -bool UpdateScreen::HasInstance(UpdateScreen* inst) { - InstanceSet& instance_set = GetInstanceSet(); - InstanceSet::iterator found = instance_set.find(inst); - return (found != instance_set.end()); -} - -// static UpdateScreen* UpdateScreen::Get(ScreenManager* manager) { return static_cast<UpdateScreen*>( manager->GetScreen(OobeScreen::SCREEN_OOBE_UPDATE)); @@ -136,8 +112,6 @@ weak_factory_(this) { if (view_) view_->Bind(this); - - GetInstanceSet().insert(this); } UpdateScreen::~UpdateScreen() { @@ -146,7 +120,6 @@ DBusThreadManager::Get()->GetUpdateEngineClient()->RemoveObserver(this); network_portal_detector::GetInstance()->RemoveObserver(this); - GetInstanceSet().erase(this); } void UpdateScreen::OnViewDestroyed(UpdateView* view) { @@ -172,56 +145,11 @@ ignore_idle_status_ = ignore_idle_status; } -void UpdateScreen::ExitUpdate(UpdateScreen::ExitReason reason) { +void UpdateScreen::ExitUpdate(ScreenExitCode exit_code) { DBusThreadManager::Get()->GetUpdateEngineClient()->RemoveObserver(this); network_portal_detector::GetInstance()->RemoveObserver(this); - switch (reason) { - case REASON_UPDATE_CANCELED: - Finish(ScreenExitCode::UPDATE_NOUPDATE); - break; - case REASON_UPDATE_INIT_FAILED: - Finish(ScreenExitCode::UPDATE_ERROR_CHECKING_FOR_UPDATE); - break; - case REASON_UPDATE_OVER_CELLULAR_REJECTED: - Finish(ScreenExitCode::UPDATE_REJECT_OVER_CELLULAR); - break; - case REASON_UPDATE_NON_CRITICAL: - case REASON_UPDATE_ENDED: { - UpdateEngineClient* update_engine_client = - DBusThreadManager::Get()->GetUpdateEngineClient(); - switch (update_engine_client->GetLastStatus().status) { - case UpdateEngineClient::UPDATE_STATUS_ATTEMPTING_ROLLBACK: - break; - case UpdateEngineClient::UPDATE_STATUS_UPDATE_AVAILABLE: - case UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT: - case UpdateEngineClient::UPDATE_STATUS_DOWNLOADING: - case UpdateEngineClient::UPDATE_STATUS_FINALIZING: - case UpdateEngineClient::UPDATE_STATUS_VERIFYING: - case UpdateEngineClient::UPDATE_STATUS_NEED_PERMISSION_TO_UPDATE: - DCHECK(!HasCriticalUpdate()); - // Noncritical update, just exit screen as if there is no update. - FALLTHROUGH; - case UpdateEngineClient::UPDATE_STATUS_IDLE: - Finish(ScreenExitCode::UPDATE_NOUPDATE); - break; - case UpdateEngineClient::UPDATE_STATUS_ERROR: - case UpdateEngineClient::UPDATE_STATUS_REPORTING_ERROR_EVENT: - if (is_checking_for_update_) { - Finish(ScreenExitCode::UPDATE_ERROR_CHECKING_FOR_UPDATE); - } else if (HasCriticalUpdate()) { - Finish(ScreenExitCode::UPDATE_ERROR_UPDATING_CRITICAL_UPDATE); - } else { - Finish(ScreenExitCode::UPDATE_ERROR_UPDATING); - } - break; - default: - NOTREACHED(); - } - } break; - default: - NOTREACHED(); - } + Finish(exit_code); } void UpdateScreen::UpdateStatusChanged( @@ -247,7 +175,7 @@ .SetBoolean(kContextKeyShowEstimatedTimeLeft, false); if (!HasCriticalUpdate()) { VLOG(1) << "Noncritical update available: " << status.new_version; - ExitUpdate(REASON_UPDATE_NON_CRITICAL); + ExitUpdate(ScreenExitCode::UPDATE_NOUPDATE); } else { VLOG(1) << "Critical update available: " << status.new_version; GetContextEditor() @@ -270,7 +198,7 @@ download_average_speed_ = 0.0; if (!HasCriticalUpdate()) { VLOG(1) << "Non-critical update available: " << status.new_version; - ExitUpdate(REASON_UPDATE_NON_CRITICAL); + ExitUpdate(ScreenExitCode::UPDATE_NOUPDATE); } else { VLOG(1) << "Critical update available: " << status.new_version; GetContextEditor() @@ -311,7 +239,7 @@ base::TimeDelta::FromSeconds(reboot_check_delay_), this, &UpdateScreen::OnWaitForRebootTimeElapsed); } else { - ExitUpdate(REASON_UPDATE_NON_CRITICAL); + ExitUpdate(ScreenExitCode::UPDATE_NOUPDATE); } break; case UpdateEngineClient::UPDATE_STATUS_NEED_PERMISSION_TO_UPDATE: @@ -331,14 +259,21 @@ VLOG(1) << "Attempting rollback"; break; case UpdateEngineClient::UPDATE_STATUS_IDLE: - if (ignore_idle_status_) { - // It is first IDLE status that is sent before we initiated the check. - break; - } - FALLTHROUGH; + // Exit update only if update engine was in non-idle status before. + // Otherwise, it's possible that the update request has not yet been + // started. + if (!ignore_idle_status_) + ExitUpdate(ScreenExitCode::UPDATE_NOUPDATE); + break; case UpdateEngineClient::UPDATE_STATUS_ERROR: case UpdateEngineClient::UPDATE_STATUS_REPORTING_ERROR_EVENT: - ExitUpdate(REASON_UPDATE_ENDED); + if (is_checking_for_update_) { + ExitUpdate(ScreenExitCode::UPDATE_ERROR_CHECKING_FOR_UPDATE); + } else if (HasCriticalUpdate()) { + ExitUpdate(ScreenExitCode::UPDATE_ERROR_UPDATING_CRITICAL_UPDATE); + } else { + ExitUpdate(ScreenExitCode::UPDATE_ERROR_UPDATING); + } break; default: NOTREACHED(); @@ -400,7 +335,7 @@ void UpdateScreen::CancelUpdate() { VLOG(1) << "Forced update cancel"; - ExitUpdate(REASON_UPDATE_CANCELED); + ExitUpdate(ScreenExitCode::UPDATE_NOUPDATE); } // TODO(jdufault): This should return a pointer. See crbug.com/672142. @@ -449,7 +384,7 @@ GetContextEditor() .SetBoolean(kContextKeyShowCurtain, true) .SetBoolean(kContextKeyRequiresPermissionForCelluar, false); - ExitUpdate(REASON_UPDATE_OVER_CELLULAR_REJECTED); + ExitUpdate(ScreenExitCode::UPDATE_REJECT_OVER_CELLULAR); } else { BaseScreen::OnUserAction(action_id); } @@ -467,7 +402,7 @@ GetContextEditor() .SetBoolean(kContextKeyShowCurtain, true) .SetBoolean(kContextKeyRequiresPermissionForCelluar, false); - ExitUpdate(REASON_UPDATE_OVER_CELLULAR_REJECTED); + ExitUpdate(ScreenExitCode::UPDATE_REJECT_OVER_CELLULAR); } } @@ -570,7 +505,8 @@ DBusThreadManager::Get()->GetUpdateEngineClient()->AddObserver(this); VLOG(1) << "Initiate update check"; DBusThreadManager::Get()->GetUpdateEngineClient()->RequestUpdateCheck( - base::Bind(StartUpdateCallback, this)); + base::BindRepeating(&UpdateScreen::OnUpdateCheckStarted, + weak_factory_.GetWeakPtr())); } void UpdateScreen::ShowErrorMessage() { @@ -634,6 +570,13 @@ &UpdateScreen::ShowErrorMessage); } +void UpdateScreen::OnUpdateCheckStarted( + UpdateEngineClient::UpdateCheckResult result) { + VLOG(1) << "Callback from RequestUpdateCheck, result " << result; + if (result != UpdateEngineClient::UPDATE_RESULT_SUCCESS) + ExitUpdate(ScreenExitCode::UPDATE_ERROR_CHECKING_FOR_UPDATE); +} + void UpdateScreen::OnConnectRequested() { if (state_ == State::STATE_ERROR) { LOG(WARNING) << "Hiding error message since AP was reselected";
diff --git a/chrome/browser/chromeos/login/screens/update_screen.h b/chrome/browser/chromeos/login/screens/update_screen.h index 639e24c..77378c7 100644 --- a/chrome/browser/chromeos/login/screens/update_screen.h +++ b/chrome/browser/chromeos/login/screens/update_screen.h
@@ -5,8 +5,6 @@ #ifndef CHROME_BROWSER_CHROMEOS_LOGIN_SCREENS_UPDATE_SCREEN_H_ #define CHROME_BROWSER_CHROMEOS_LOGIN_SCREENS_UPDATE_SCREEN_H_ -#include <set> - #include "base/callback.h" #include "base/compiler_specific.h" #include "base/gtest_prod_util.h" @@ -35,9 +33,6 @@ public: static UpdateScreen* Get(ScreenManager* manager); - // Returns true if this instance is still active (i.e. has not been deleted). - static bool HasInstance(UpdateScreen* inst); - UpdateScreen(BaseScreenDelegate* base_screen_delegate, UpdateView* view); ~UpdateScreen() override; @@ -50,15 +45,8 @@ void SetIgnoreIdleStatus(bool ignore_idle_status); - enum ExitReason { - REASON_UPDATE_CANCELED = 0, - REASON_UPDATE_INIT_FAILED, - REASON_UPDATE_OVER_CELLULAR_REJECTED, - REASON_UPDATE_NON_CRITICAL, - REASON_UPDATE_ENDED - }; // Reports update results to the BaseScreenDelegate. - virtual void ExitUpdate(ExitReason reason); + void ExitUpdate(ScreenExitCode exit_code); // UpdateEngineClient::Observer implementation: void UpdateStatusChanged(const UpdateEngineClient::Status& status) override; @@ -124,6 +112,10 @@ void DelayErrorMessage(); + // Callback for UpdateEngineClient::RequestUpdateCheck() called fomr + // StartUpdateCheck(). + void OnUpdateCheckStarted(UpdateEngineClient::UpdateCheckResult result); + // The user requested an attempt to connect to the network should be made. void OnConnectRequested(); @@ -131,12 +123,6 @@ // If reboot didn't happen - ask user to reboot manually. base::OneShotTimer reboot_timer_; - // Returns a static InstanceSet. - // TODO(jdufault): There should only ever be one instance of this class. - // Remove support for supporting multiple instances. See crbug.com/672142. - typedef std::set<UpdateScreen*> InstanceSet; - static InstanceSet& GetInstanceSet(); - // Current state of the update screen. State state_ = State::STATE_IDLE;
diff --git a/chrome/browser/chromeos/login/test/enrollment_helper_mixin.cc b/chrome/browser/chromeos/login/test/enrollment_helper_mixin.cc new file mode 100644 index 0000000..15b9b276 --- /dev/null +++ b/chrome/browser/chromeos/login/test/enrollment_helper_mixin.cc
@@ -0,0 +1,175 @@ +// 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/chromeos/login/test/enrollment_helper_mixin.h" + +#include "base/bind.h" +#include "chrome/browser/chromeos/login/enrollment/enrollment_screen.h" +#include "chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper.h" +#include "chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_mock.h" +#include "chrome/browser/chromeos/login/wizard_controller.h" +#include "chrome/browser/chromeos/policy/active_directory_join_delegate.h" + +using testing::_; +using testing::AtLeast; +using testing::Invoke; +using testing::InvokeWithoutArgs; + +namespace { + +MATCHER_P(ConfigModeMatches, mode, "") { + return arg.mode == mode; +} + +} // namespace + +namespace chromeos { +namespace test { + +// static +const char EnrollmentHelperMixin::kTestAuthCode[] = "test_auth_code"; + +EnrollmentHelperMixin::EnrollmentHelperMixin( + InProcessBrowserTestMixinHost* host) + : InProcessBrowserTestMixin(host) {} + +EnrollmentHelperMixin::~EnrollmentHelperMixin() = default; + +void EnrollmentHelperMixin::SetUpInProcessBrowserTestFixture() { + ResetMock(); +} + +void EnrollmentHelperMixin::TearDownInProcessBrowserTestFixture() { + mock_ = nullptr; + EnterpriseEnrollmentHelper::SetEnrollmentHelperMock(nullptr); + // Enrollment screen might have reference to enrollment_helper_. + if (WizardController::default_controller()) { + auto* screen_manager = + WizardController::default_controller()->screen_manager(); + if (screen_manager->HasScreen(OobeScreen::SCREEN_OOBE_ENROLLMENT)) { + EnrollmentScreen::Get(screen_manager)->enrollment_helper_.reset(); + } + } +} + +void EnrollmentHelperMixin::ResetMock() { + std::unique_ptr<EnterpriseEnrollmentHelperMock> mock = + std::make_unique<EnterpriseEnrollmentHelperMock>(); + mock_ = mock.get(); + EnterpriseEnrollmentHelper::SetEnrollmentHelperMock(std::move(mock)); +} + +void EnrollmentHelperMixin::ExpectNoEnrollment() { + EXPECT_CALL(*mock_, Setup(_, _, _)).Times(0); +} + +void EnrollmentHelperMixin::ExpectEnrollmentMode( + policy::EnrollmentConfig::Mode mode) { + EXPECT_CALL(*mock_, Setup(_, ConfigModeMatches(mode), _)); +} + +void EnrollmentHelperMixin::ExpectEnrollmentModeRepeated( + policy::EnrollmentConfig::Mode mode) { + EXPECT_CALL(*mock_, Setup(_, ConfigModeMatches(mode), _)).Times(AtLeast(1)); +} + +void EnrollmentHelperMixin::ExpectAttestationEnrollmentSuccess() { + EXPECT_CALL(*mock_, EnrollUsingAttestation()) + .WillOnce(testing::Invoke( + [this]() { mock_->status_consumer()->OnDeviceEnrolled(); })); +} + +void EnrollmentHelperMixin::ExpectAttestationEnrollmentError( + policy::EnrollmentStatus status) { + EXPECT_CALL(*mock_, EnrollUsingAttestation()) + .WillOnce(testing::Invoke([this, status]() { + mock_->status_consumer()->OnEnrollmentError(status); + })); +} + +void EnrollmentHelperMixin::ExpectAttestationEnrollmentErrorRepeated( + policy::EnrollmentStatus status) { + EXPECT_CALL(*mock_, EnrollUsingAttestation()) + .Times(AtLeast(1)) + .WillRepeatedly(testing::Invoke([this, status]() { + mock_->status_consumer()->OnEnrollmentError(status); + })); +} + +void EnrollmentHelperMixin::ExpectOfflineEnrollmentSuccess() { + ExpectEnrollmentMode(policy::EnrollmentConfig::MODE_OFFLINE_DEMO); + + EXPECT_CALL(*mock_, EnrollForOfflineDemo()) + .WillOnce(testing::Invoke( + [this]() { mock_->status_consumer()->OnDeviceEnrolled(); })); +} + +void EnrollmentHelperMixin::ExpectOfflineEnrollmentError( + policy::EnrollmentStatus status) { + ExpectEnrollmentMode(policy::EnrollmentConfig::MODE_OFFLINE_DEMO); + EXPECT_CALL(*mock_, EnrollForOfflineDemo()) + .WillOnce(testing::Invoke([this, status]() { + mock_->status_consumer()->OnEnrollmentError(status); + })); +} + +void EnrollmentHelperMixin::SetupClearAuth() { + ON_CALL(*mock_, ClearAuth(_)) + .WillByDefault(Invoke( + [](base::OnceClosure callback) { std::move(callback).Run(); })); +} + +void EnrollmentHelperMixin::ExpectEnrollmentCredentials() { + EXPECT_CALL(*mock_, EnrollUsingAuthCode(kTestAuthCode, _)); +} + +void EnrollmentHelperMixin::DisableAttributePromptUpdate() { + EXPECT_CALL(*mock_, GetDeviceAttributeUpdatePermission()) + .WillOnce(InvokeWithoutArgs([this]() { + mock_->status_consumer()->OnDeviceAttributeUpdatePermission(false); + })); +} + +void EnrollmentHelperMixin::ExpectAttributePromptUpdate( + const std::string& asset_id, + const std::string& location) { + // Causes the attribute-prompt flow to activate. + ON_CALL(*mock_, GetDeviceAttributeUpdatePermission()) + .WillByDefault(InvokeWithoutArgs([this]() { + mock_->status_consumer()->OnDeviceAttributeUpdatePermission(true); + })); + + // Ensures we receive the updates attributes. + EXPECT_CALL(*mock_, UpdateDeviceAttributes(asset_id, location)); +} + +void EnrollmentHelperMixin::SetupActiveDirectoryJoin( + ActiveDirectoryJoinDelegate* delegate, + const std::string& expected_domain, + const std::string& domain_join_config, + const std::string& dm_token) { + EXPECT_CALL(*mock_, EnrollUsingAuthCode(kTestAuthCode, _)) + .WillOnce(InvokeWithoutArgs( + [delegate, expected_domain, domain_join_config, dm_token]() { + delegate->JoinDomain(dm_token, domain_join_config, + base::BindOnce( + [](const std::string& expected_domain, + const std::string& domain) { + ASSERT_EQ(expected_domain, domain); + }, + expected_domain)); + })); +} + +void EnrollmentHelperMixin::ExpectTokenEnrollmentSuccess( + const std::string& token) { + ExpectEnrollmentMode( + policy::EnrollmentConfig::MODE_ATTESTATION_ENROLLMENT_TOKEN); + EXPECT_CALL(*mock_, EnrollUsingEnrollmentToken(token)) + .WillOnce(InvokeWithoutArgs( + [this]() { mock_->status_consumer()->OnDeviceEnrolled(); })); +} + +} // namespace test +} // namespace chromeos
diff --git a/chrome/browser/chromeos/login/test/enrollment_helper_mixin.h b/chrome/browser/chromeos/login/test/enrollment_helper_mixin.h new file mode 100644 index 0000000..ade9165 --- /dev/null +++ b/chrome/browser/chromeos/login/test/enrollment_helper_mixin.h
@@ -0,0 +1,92 @@ +// 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_CHROMEOS_LOGIN_TEST_ENROLLMENT_HELPER_MIXIN_H_ +#define CHROME_BROWSER_CHROMEOS_LOGIN_TEST_ENROLLMENT_HELPER_MIXIN_H_ + +#include <string> + +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper.h" +#include "chrome/browser/chromeos/login/mixin_based_in_process_browser_test.h" +#include "chrome/browser/chromeos/policy/enrollment_config.h" +#include "chrome/browser/chromeos/policy/enrollment_status_chromeos.h" +#include "testing/gmock/include/gmock/gmock.h" + +namespace chromeos { + +class EnterpriseEnrollmentHelperMock; +class ActiveDirectoryJoinDelegate; + +namespace test { + +// This test mixin covers mocking backend interaction during enterprise +// enrollment on EnterpriseEnrollmentHelper level. +class EnrollmentHelperMixin : public InProcessBrowserTestMixin { + public: + static const char kTestAuthCode[]; + + explicit EnrollmentHelperMixin(InProcessBrowserTestMixinHost* host); + ~EnrollmentHelperMixin() override; + + // Resets mock (to be used in tests that retry enrollment. + void ResetMock(); + + // Sets up expectation of no enrollment attempt. + void ExpectNoEnrollment(); + + // Sets up expectation of enrollment mode. + void ExpectEnrollmentMode(policy::EnrollmentConfig::Mode mode); + void ExpectEnrollmentModeRepeated(policy::EnrollmentConfig::Mode mode); + + // Configures and sets expectations for successful attestation-based flow. + void ExpectAttestationEnrollmentSuccess(); + // Configures and sets expectations for attestation-based flow resulting in + // error. + void ExpectAttestationEnrollmentError(policy::EnrollmentStatus status); + void ExpectAttestationEnrollmentErrorRepeated( + policy::EnrollmentStatus status); + + // Configures and sets expectations for successful offline demo flow. + void ExpectOfflineEnrollmentSuccess(); + // Configures and sets expectations for offline demo flow resulting in error. + void ExpectOfflineEnrollmentError(policy::EnrollmentStatus status); + + // Sets up expectation of kTestAuthCode as enrollment credentials. + void ExpectEnrollmentCredentials(); + // Sets up default ClearAuth handling. + void SetupClearAuth(); + + // Configures not to show an attribute prompt. + void DisableAttributePromptUpdate(); + // Attribute prompt should be displayed during enrollment, and + // |asset_id| / |location| should be sent back to server. + void ExpectAttributePromptUpdate(const std::string& asset_id, + const std::string& location); + + // Forces the Active Directory domain join flow during enterprise enrollment. + void SetupActiveDirectoryJoin(ActiveDirectoryJoinDelegate* delegate, + const std::string& expected_domain, + const std::string& domain_join_config, + const std::string& dm_token); + // Sets up expectations for token enrollment. + void ExpectTokenEnrollmentSuccess(const std::string& token); + + // InProcessBrowserTestMixin: + void SetUpInProcessBrowserTestFixture() override; + void TearDownInProcessBrowserTestFixture() override; + + private: + // Unowned reference to last created mock. + EnterpriseEnrollmentHelperMock* mock_ = nullptr; + base::WeakPtrFactory<EnrollmentHelperMixin> weak_ptr_factory_{this}; + + DISALLOW_COPY_AND_ASSIGN(EnrollmentHelperMixin); +}; + +} // namespace test +} // namespace chromeos + +#endif // CHROME_BROWSER_CHROMEOS_LOGIN_TEST_ENROLLMENT_HELPER_MIXIN_H_
diff --git a/chrome/browser/chromeos/net/network_portal_detector_impl.cc b/chrome/browser/chromeos/net/network_portal_detector_impl.cc index eb4e857..4c7a06a 100644 --- a/chrome/browser/chromeos/net/network_portal_detector_impl.cc +++ b/chrome/browser/chromeos/net/network_portal_detector_impl.cc
@@ -11,9 +11,7 @@ #include "base/location.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" -#include "base/rand_util.h" #include "base/single_thread_task_runner.h" -#include "base/strings/stringprintf.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/chrome_notification_types.h" #include "chromeos/constants/chromeos_switches.h" @@ -28,7 +26,6 @@ #include "net/traffic_annotation/network_traffic_annotation.h" #include "third_party/cros_system_api/dbus/service_constants.h" -using base::StringPrintf; using captive_portal::CaptivePortalDetector; namespace chromeos { @@ -87,17 +84,6 @@ constexpr char kDetectionResultSinceShillPortalHistogram[] = "CaptivePortal.DetectionResultSincePortal"; -// Get randomized test url by rotating through alternate hostnames on each -// portal check, to defeat IP-based blocking. -GURL GetRandomizedTestURL() { - // This range is determined by the server-side configuration. See b/63033351. - const int kMinRandomHost = 1; - const int kMaxRandomHost = 25; - return GURL( - base::StringPrintf("http://alt%d.gstatic.com/generate_204", - base::RandInt(kMinRandomHost, kMaxRandomHost))); -} - const NetworkState* DefaultNetwork() { return NetworkHandler::Get()->network_state_handler()->DefaultNetwork(); } @@ -225,13 +211,7 @@ NET_LOG(EVENT) << "NetworkPortalDetectorImpl::NetworkPortalDetectorImpl()"; captive_portal_detector_.reset(new CaptivePortalDetector(loader_factory)); - // Captive portal randomization can cause problems in some environemnts. - // Disable randomization by default by setting portal_test_url_. - // http://crbug.com/776409. - if (!base::CommandLine::ForCurrentProcess()->HasSwitch( - chromeos::switches::kEnableCaptivePortalRandomUrl)) { - portal_test_url_ = GURL(CaptivePortalDetector::kDefaultURL); - } + portal_test_url_ = GURL(CaptivePortalDetector::kDefaultURL); registrar_.Add(this, chrome::NOTIFICATION_AUTH_SUPPLIED, content::NotificationService::AllSources()); @@ -466,12 +446,11 @@ state_ = STATE_CHECKING_FOR_PORTAL; attempt_start_time_ = NowTicks(); - const GURL test_url = - !portal_test_url_.is_empty() ? portal_test_url_ : GetRandomizedTestURL(); - DCHECK(test_url.is_valid()); - NET_LOG(EVENT) << "Starting captive portal detection with URL: " << test_url; + DCHECK(portal_test_url_.is_valid()); + NET_LOG(EVENT) << "Starting captive portal detection with URL: " + << portal_test_url_; captive_portal_detector_->DetectCaptivePortal( - test_url, + portal_test_url_, base::Bind(&NetworkPortalDetectorImpl::OnAttemptCompleted, weak_factory_.GetWeakPtr()), NO_TRAFFIC_ANNOTATION_YET);
diff --git a/chrome/browser/chromeos/network_change_manager_client_browsertest.cc b/chrome/browser/chromeos/network_change_manager_client_browsertest.cc index 9f49e39..a6fb47c6 100644 --- a/chrome/browser/chromeos/network_change_manager_client_browsertest.cc +++ b/chrome/browser/chromeos/network_change_manager_client_browsertest.cc
@@ -19,14 +19,17 @@ class NetObserver : public net::NetworkChangeNotifier::NetworkChangeObserver { public: - NetObserver() { net::NetworkChangeNotifier::AddNetworkChangeObserver(this); } + NetObserver() { + net::NetworkChangeNotifier::AddNetworkChangeObserver(this); + last_connection_type_ = net::NetworkChangeNotifier::GetConnectionType(); + } ~NetObserver() override { net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this); } void WaitForConnectionType(net::NetworkChangeNotifier::ConnectionType type) { - while (last_connection_type != type) { + while (last_connection_type_ != type) { run_loop_.reset(new base::RunLoop()); run_loop_->Run(); run_loop_.reset(); @@ -36,15 +39,14 @@ // net::NetworkChangeNotifier:NetworkChangeObserver: void OnNetworkChanged( net::NetworkChangeNotifier::ConnectionType type) override { - change_count++; - last_connection_type = type; + change_count_++; + last_connection_type_ = type; if (run_loop_) run_loop_->Quit(); } - int change_count = 0; - net::NetworkChangeNotifier::ConnectionType last_connection_type = - net::NetworkChangeNotifier::CONNECTION_UNKNOWN; + int change_count_ = 0; + net::NetworkChangeNotifier::ConnectionType last_connection_type_; private: std::unique_ptr<base::RunLoop> run_loop_; @@ -53,8 +55,12 @@ class NetworkServiceObserver : public network::NetworkConnectionTracker::NetworkConnectionObserver { public: - NetworkServiceObserver() { + NetworkServiceObserver() : weak_factory_(this) { content::GetNetworkConnectionTracker()->AddNetworkConnectionObserver(this); + content::GetNetworkConnectionTracker()->GetConnectionType( + &last_connection_type_, + base::BindOnce(&NetworkServiceObserver::OnConnectionChanged, + weak_factory_.GetWeakPtr())); } ~NetworkServiceObserver() override { @@ -63,7 +69,7 @@ } void WaitForConnectionType(network::mojom::ConnectionType type) { - while (last_connection_type != type) { + while (last_connection_type_ != type) { run_loop_.reset(new base::RunLoop()); run_loop_->Run(); run_loop_.reset(); @@ -72,18 +78,18 @@ // network::NetworkConnectionTracker::NetworkConnectionObserver: void OnConnectionChanged(network::mojom::ConnectionType type) override { - change_count++; - last_connection_type = type; + change_count_++; + last_connection_type_ = type; if (run_loop_) run_loop_->Quit(); } - int change_count = 0; - network::mojom::ConnectionType last_connection_type = - network::mojom::ConnectionType::CONNECTION_UNKNOWN; + int change_count_ = 0; + network::mojom::ConnectionType last_connection_type_; private: std::unique_ptr<base::RunLoop> run_loop_; + base::WeakPtrFactory<NetworkServiceObserver> weak_factory_; }; } // namespace @@ -119,15 +125,15 @@ net::NetworkChangeNotifier::CONNECTION_WIFI); // NetworkChangeNotifier will send a CONNECTION_NONE notification before // the CONNECTION_WIFI one. - EXPECT_EQ(2, net_observer.change_count); + EXPECT_EQ(2, net_observer.change_count_); EXPECT_EQ(net::NetworkChangeNotifier::CONNECTION_WIFI, - net_observer.last_connection_type); + net_observer.last_connection_type_); network_service_observer.WaitForConnectionType( network::mojom::ConnectionType::CONNECTION_WIFI); - EXPECT_EQ(2, network_service_observer.change_count); + EXPECT_EQ(2, network_service_observer.change_count_); EXPECT_EQ(network::mojom::ConnectionType::CONNECTION_WIFI, - network_service_observer.last_connection_type); + network_service_observer.last_connection_type_); } // Tests that the NetworkChangeManagerClient reconnects to the network service @@ -158,15 +164,15 @@ net::NetworkChangeNotifier::CONNECTION_WIFI); // NetworkChangeNotifier will send a CONNECTION_NONE notification before // the CONNECTION_WIFI one. - EXPECT_EQ(2, net_observer.change_count); + EXPECT_EQ(2, net_observer.change_count_); EXPECT_EQ(net::NetworkChangeNotifier::CONNECTION_WIFI, - net_observer.last_connection_type); + net_observer.last_connection_type_); network_service_observer.WaitForConnectionType( network::mojom::ConnectionType::CONNECTION_WIFI); - EXPECT_EQ(2, network_service_observer.change_count); + EXPECT_EQ(2, network_service_observer.change_count_); EXPECT_EQ(network::mojom::ConnectionType::CONNECTION_WIFI, - network_service_observer.last_connection_type); + network_service_observer.last_connection_type_); } } // namespace chromeos
diff --git a/chrome/browser/chromeos/smb_client/OWNERS b/chrome/browser/chromeos/smb_client/OWNERS index 0f05459..8302a70 100644 --- a/chrome/browser/chromeos/smb_client/OWNERS +++ b/chrome/browser/chromeos/smb_client/OWNERS
@@ -1,2 +1,4 @@ +amistry@chromium.org baileyberro@chromium.org +slangley@chromium.org zentaro@chromium.org
diff --git a/chrome/browser/chromeos/smb_client/smb_service.cc b/chrome/browser/chromeos/smb_client/smb_service.cc index 0655a59..418fd636 100644 --- a/chrome/browser/chromeos/smb_client/smb_service.cc +++ b/chrome/browser/chromeos/smb_client/smb_service.cc
@@ -525,6 +525,7 @@ base::BindRepeating(&SmbService::RequestUpdatedSharePath, base::Unretained(this)))); RestoreMounts(); + net::NetworkChangeNotifier::AddNetworkChangeObserver(this); } void SmbService::FireMountCallback(MountResponse callback, @@ -662,6 +663,22 @@ previous_host_discovery_time_ + kHostDiscoveryInterval; } +void SmbService::OnNetworkChanged( + net::NetworkChangeNotifier::ConnectionType type) { + user_manager::User* user = + chromeos::ProfileHelper::Get()->GetUserByProfile(profile_); + + if (!user) { + // If a network change occurs on the lockscreen, do nothing. + return; + } + + // Run host discovery to refresh list of cached hosts for subsequent name + // resolution attempts. + share_finder_->DiscoverHostsInNetwork(base::DoNothing() + /* HostDiscoveryResponse */); +} + void SmbService::RecordMountCount() const { const std::vector<ProvidedFileSystemInfo> file_systems = GetProviderService()->GetProvidedFileSystemInfoList(provider_id_);
diff --git a/chrome/browser/chromeos/smb_client/smb_service.h b/chrome/browser/chromeos/smb_client/smb_service.h index 076faf0f..b74dd9d5 100644 --- a/chrome/browser/chromeos/smb_client/smb_service.h +++ b/chrome/browser/chromeos/smb_client/smb_service.h
@@ -25,6 +25,7 @@ #include "chrome/browser/profiles/profile.h" #include "chromeos/dbus/smb_provider_client.h" #include "components/keyed_service/core/keyed_service.h" +#include "net/base/network_change_notifier.h" namespace base { class FilePath; @@ -46,6 +47,7 @@ // Creates and manages an smb file system. class SmbService : public KeyedService, + public net::NetworkChangeNotifier::NetworkChangeObserver, public base::SupportsWeakPtr<SmbService> { public: using MountResponse = base::OnceCallback<void(SmbMountResult result)>; @@ -245,6 +247,11 @@ // false if HostDiscovery was recently run. bool ShouldRunHostDiscoveryAgain() const; + // NetworkChangeNotifier::NetworkChangeObserver override. Runs HostDiscovery + // when network detects a change. + void OnNetworkChanged( + net::NetworkChangeNotifier::ConnectionType type) override; + // Records metrics on the number of SMB mounts a user has. void RecordMountCount() const;
diff --git a/chrome/browser/chromeos/smb_client/smb_share_finder.cc b/chrome/browser/chromeos/smb_client/smb_share_finder.cc index 8599b82..93aff23c 100644 --- a/chrome/browser/chromeos/smb_client/smb_share_finder.cc +++ b/chrome/browser/chromeos/smb_client/smb_share_finder.cc
@@ -19,29 +19,63 @@ void SmbShareFinder::GatherSharesInNetwork( HostDiscoveryResponse discovery_callback, GatherSharesInNetworkResponse shares_callback) { - const bool should_start_discovery = share_callbacks_.empty(); + const bool is_host_discovery_pending = !discovery_callbacks_.empty(); + const bool is_share_discovery_pending = !share_callbacks_.empty(); - if (discovery_callbacks_.empty() && !should_start_discovery) { - // Host discovery completed but shares callback is still in progress. - std::move(discovery_callback).Run(); - InsertShareCallback(std::move(shares_callback)); - } else { - // Either GatherSharesInNetwork has not been called yet or it has and - // discovery has not yet finished. + if (is_host_discovery_pending) { + // Host discovery is currently running, add both |discovery_callback| and + // |share_callback| to their respective vectors. InsertDiscoveryAndShareCallbacks(std::move(discovery_callback), std::move(shares_callback)); + return; } - if (should_start_discovery) { - scanner_.FindHostsInNetwork( - base::BindOnce(&SmbShareFinder::OnHostsFound, AsWeakPtr())); + + if (is_share_discovery_pending) { + // Host discovery is complete but there are still share callbacks pending. + // Run |discovery_callback| because pending share discoveries and no pending + // host discoveries indicate that a host discovery must have recently + // completed. + std::move(discovery_callback).Run(); + InsertShareCallback(std::move(shares_callback)); + return; } + + // No host discovery or share discovery in progress. This is only because + // GatherSharesInNetwork has not been called yet or the previous host + // discovery has been fully completed. + InsertDiscoveryAndShareCallbacks(std::move(discovery_callback), + std::move(shares_callback)); + scanner_.FindHostsInNetwork( + base::BindOnce(&SmbShareFinder::OnHostsFound, AsWeakPtr())); } void SmbShareFinder::DiscoverHostsInNetwork( HostDiscoveryResponse discovery_callback) { - scanner_.FindHostsInNetwork(base::BindOnce(&SmbShareFinder::OnHostsDiscovered, - AsWeakPtr(), - std::move(discovery_callback))); + const bool is_host_discovery_pending = !discovery_callbacks_.empty(); + const bool is_share_discovery_pending = !share_callbacks_.empty(); + + if (is_host_discovery_pending) { + // Host discovery is currently running, add |discovery_callback| to + // |discovery_callbacks|. + InsertDiscoveryCallback(std::move(discovery_callback)); + return; + } + + if (is_share_discovery_pending) { + // Host discovery is complete but there are still share callbacks pending. + // Run |discovery_callback| because pending share discoveries and no pending + // host discoveries indicate that a host discovery must have recently + // completed. + std::move(discovery_callback).Run(); + return; + } + + // No host discovery or share discovery in progress. This is only because + // GatherSharesInNetwork has not been called yet or the previous host + // discovery has been fully completed. + InsertDiscoveryCallback(std::move(discovery_callback)); + scanner_.FindHostsInNetwork( + base::BindOnce(&SmbShareFinder::OnHostsFound, AsWeakPtr())); } void SmbShareFinder::RegisterHostLocator(std::unique_ptr<HostLocator> locator) { @@ -67,12 +101,6 @@ return *updated_url != url.ToString(); } -void SmbShareFinder::OnHostsDiscovered(HostDiscoveryResponse discovery_callback, - bool success, - const HostMap& hosts) { - std::move(discovery_callback).Run(); -} - void SmbShareFinder::OnHostsFound(bool success, const HostMap& hosts) { DCHECK_EQ(0u, host_counter_); @@ -149,8 +177,8 @@ void SmbShareFinder::InsertDiscoveryAndShareCallbacks( HostDiscoveryResponse discovery_callback, GatherSharesInNetworkResponse share_callback) { - discovery_callbacks_.push_back(std::move(discovery_callback)); - share_callbacks_.push_back(std::move(share_callback)); + InsertDiscoveryCallback(std::move(discovery_callback)); + InsertShareCallback(std::move(share_callback)); } void SmbShareFinder::InsertShareCallback( @@ -158,5 +186,10 @@ share_callbacks_.push_back(std::move(share_callback)); } +void SmbShareFinder::InsertDiscoveryCallback( + HostDiscoveryResponse discovery_callback) { + discovery_callbacks_.push_back(std::move(discovery_callback)); +} + } // namespace smb_client } // namespace chromeos
diff --git a/chrome/browser/chromeos/smb_client/smb_share_finder.h b/chrome/browser/chromeos/smb_client/smb_share_finder.h index fed1b122..f01ae81 100644 --- a/chrome/browser/chromeos/smb_client/smb_share_finder.h +++ b/chrome/browser/chromeos/smb_client/smb_share_finder.h
@@ -64,11 +64,6 @@ bool TryResolveUrl(const SmbUrl& url, std::string* updated_url) const; private: - // Handles the response from discovering hosts in the network. - void OnHostsDiscovered(HostDiscoveryResponse discovery_callback, - bool success, - const HostMap& hosts); - // Handles the response from finding hosts in the network. void OnHostsFound(bool success, const HostMap& hosts); @@ -96,6 +91,9 @@ // Inserts |shares_callback| to |share_callbacks_|. void InsertShareCallback(GatherSharesInNetworkResponse shares_callback); + // Inserts |discovery_callback| to |discovery_callbacks_|. + void InsertDiscoveryCallback(HostDiscoveryResponse discovery_callback); + NetworkScanner scanner_; SmbProviderClient* client_; // Not owned.
diff --git a/chrome/browser/download/notification/download_notification_browsertest.cc b/chrome/browser/download/notification/download_notification_browsertest.cc index 4ed9fc8..a678baab 100644 --- a/chrome/browser/download/notification/download_notification_browsertest.cc +++ b/chrome/browser/download/notification/download_notification_browsertest.cc
@@ -1059,19 +1059,12 @@ IN_PROC_BROWSER_TEST_F(MultiProfileDownloadNotificationTest, PRE_DownloadMultipleFiles) { - // TODO(crbug.com/933963): Flaky with network service. - if (base::FeatureList::IsEnabled(network::features::kNetworkService)) - return; - AddAllUsers(); } +// TODO(crbug.com/933963): Flaky with network service. IN_PROC_BROWSER_TEST_F(MultiProfileDownloadNotificationTest, - DownloadMultipleFiles) { - // TODO(crbug.com/933963): Flaky with network service. - if (base::FeatureList::IsEnabled(network::features::kNetworkService)) - return; - + DISABLED_DownloadMultipleFiles) { AddAllUsers(); GURL url(SlowDownloadInterceptor::kUnknownSizeUrl);
diff --git a/chrome/browser/extensions/api/identity/identity_apitest.cc b/chrome/browser/extensions/api/identity/identity_apitest.cc index 8b8b314..7be1ef27 100644 --- a/chrome/browser/extensions/api/identity/identity_apitest.cc +++ b/chrome/browser/extensions/api/identity/identity_apitest.cc
@@ -31,7 +31,6 @@ #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/signin/account_fetcher_service_factory.h" #include "chrome/browser/signin/account_reconcilor_factory.h" #include "chrome/browser/signin/chrome_signin_client_factory.h" #include "chrome/browser/signin/chrome_signin_client_test_util.h" @@ -46,7 +45,6 @@ #include "components/crx_file/id_util.h" #include "components/guest_view/browser/guest_view_base.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_fetcher_service.h" #include "components/signin/core/browser/account_reconcilor.h" #include "components/signin/core/browser/list_accounts_test_utils.h" #include "components/signin/core/browser/signin_pref_names.h" @@ -467,15 +465,6 @@ ChromeSigninClientFactory::GetInstance()->SetTestingFactory( context, base::BindRepeating(&BuildChromeSigninClientWithURLLoader, &test_url_loader_factory_)); - - // Ensure that AccountFetcherService is (1) created at all and (2) created - // early enough for it to observe the Profile initialization process and - // loading of tokens by PO2TS. Explicitly forcing this setup (which happens - // naturally in production) is necessary for the flow of - // AccountTrackerService having accounts removed when tokens are revoked - // with PO2TS to work as expected in this testing context. - AccountFetcherServiceFactory::GetInstance()->GetForProfile( - Profile::FromBrowserContext(context)); } void SetUpOnMainThread() override { @@ -484,18 +473,10 @@ identity_test_env_profile_adaptor_ = std::make_unique<IdentityTestEnvironmentProfileAdaptor>(profile()); -#if defined(OS_CHROMEOS) - // On ChromeOS, ProfileOAuth2TokenService does not fire - // OnRefreshTokensLoaded() in text contexts. However, AccountFetcherService - // must receive this call in order to forward later - // OnRefreshToken{Available, Revoked} callbacks on to AccountTrackerService - // as expected. Hence, we make that call explicitly here. - // TODO(blundell): Hide this detail when converting this code to interact - // with IdentityTestEnvironment. - AccountFetcherServiceFactory::GetInstance() - ->GetForProfile(profile()) - ->OnRefreshTokensLoaded(); -#endif + // This test requires these callbacks to be fired on account + // update/removal. + identity_test_env() + ->EnableOnAccountUpdatedAndOnAccountRemovedWithInfoCallbacks(); } void TearDownOnMainThread() override {
diff --git a/chrome/browser/extensions/api/permissions/permissions_api.cc b/chrome/browser/extensions/api/permissions/permissions_api.cc index cd48cd4..524f1220 100644 --- a/chrome/browser/extensions/api/permissions/permissions_api.cc +++ b/chrome/browser/extensions/api/permissions/permissions_api.cc
@@ -55,18 +55,15 @@ api::permissions::Contains::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - // NOTE: The result is not used to make any security decisions. Therefore, - // it is entirely fine to set |allow_file_access| to true below. This will - // avoid throwing error when extension() doesn't have access to file://. - constexpr bool kAllowFileAccess = true; - std::string error; std::unique_ptr<UnpackPermissionSetResult> unpack_result = permissions_api_helpers::UnpackPermissionSet( params->permissions, PermissionsParser::GetRequiredPermissions(extension()), PermissionsParser::GetOptionalPermissions(extension()), - kAllowFileAccess, &error); + ExtensionPrefs::Get(browser_context()) + ->AllowFileAccess(extension()->id()), + &error); if (!unpack_result) return RespondNow(Error(error)); @@ -83,6 +80,9 @@ // Unsupported optional permissions can never be granted, so we know if // there are any specified, the extension doesn't actively have them. unpack_result->unsupported_optional_apis.empty() && + // Restricted file scheme patterns cannot be active on the extension, + // since it doesn't have file access in that case. + unpack_result->restricted_file_scheme_patterns.is_empty() && // Otherwise, check each expected location for whether it contains the // relevant permissions. active_permissions.apis().Contains(unpack_result->optional_apis) && @@ -99,6 +99,12 @@ } ExtensionFunction::ResponseAction PermissionsGetAllFunction::Run() { + // TODO(devlin): We should filter out file:-scheme patterns if the extension + // doesn't have file access here, so that they don't show up when the + // extension calls getAll(). This can either be solved by filtering here or + // by not adding file:-scheme patterns to |active_permissions| without file + // access (the former is easier, the latter is probably better overall but may + // require some investigation). std::unique_ptr<Permissions> permissions = permissions_api_helpers::PackPermissionSet( extension()->permissions_data()->active_permissions()); @@ -150,6 +156,11 @@ return RespondNow(Error(kCantRemoveRequiredPermissionsError)); } + // Note: We don't check |restricted_file_scheme_patterns| here. If there are + // any, it means that the extension didn't have file access, but it also means + // that it doesn't, effectively, currently have that permission granted (i.e., + // it doesn't actually have access to any file:-scheme URL). + PermissionSet permissions( std::move(unpack_result->optional_apis), ManifestPermissionSet(), unpack_result->optional_explicit_hosts, URLPatternSet()); @@ -231,6 +242,12 @@ (*unpack_result->unsupported_optional_apis.begin())->name())); } + if (!unpack_result->restricted_file_scheme_patterns.is_empty()) { + return RespondNow(Error( + "Extension must have file access enabled to request '*'.", + unpack_result->restricted_file_scheme_patterns.begin()->GetAsString())); + } + const PermissionSet& active_permissions = extension()->permissions_data()->active_permissions();
diff --git a/chrome/browser/extensions/api/permissions/permissions_api_helpers.cc b/chrome/browser/extensions/api/permissions/permissions_api_helpers.cc index 56b019ab..34b0007c 100644 --- a/chrome/browser/extensions/api/permissions/permissions_api_helpers.cc +++ b/chrome/browser/extensions/api/permissions/permissions_api_helpers.cc
@@ -145,12 +145,14 @@ std::string* error) { int user_script_schemes = UserScript::ValidUserScriptSchemes(); int explicit_schemes = Extension::kValidHostPermissionSchemes; - if (!allow_file_access) { - user_script_schemes &= ~URLPattern::SCHEME_FILE; - explicit_schemes &= ~URLPattern::SCHEME_FILE; - } - auto filter_chrome_scheme = [](URLPattern* pattern) { + auto filter_schemes = [allow_file_access](URLPattern* pattern) { + // NOTE: We use pattern->valid_schemes() here (instead of + // |user_script_schemes| or |explicit_schemes|) because + // URLPattern::Parse() can mutate the valid schemes for a pattern, and we + // don't want to override those changes. + int valid_schemes = pattern->valid_schemes(); + // We disallow the chrome:-scheme unless the pattern is explicitly // "chrome://..." - that is, <all_urls> should not match the chrome:-scheme. // Patterns which explicitly specify the chrome:-scheme are safe, since @@ -159,14 +161,16 @@ // Note that we don't check PermissionsData::AllUrlsIncludesChromeUrls() // here, since that's only needed for Chromevox (which doesn't use optional // permissions). - if (pattern->scheme() != content::kChromeUIScheme) { - // NOTE: We use pattern->valid_schemes() here (instead of - // |user_script_schemes| or |explicit_schemes|) because - // URLPattern::Parse() can mutate the valid schemes for a pattern, and we - // don't want to override those changes. - pattern->SetValidSchemes(pattern->valid_schemes() & - ~URLPattern::SCHEME_CHROMEUI); - } + if (pattern->scheme() != content::kChromeUIScheme) + valid_schemes &= ~URLPattern::SCHEME_CHROMEUI; + + // Similarly, <all_urls> should only match file:-scheme URLs if file access + // is granted. + if (!allow_file_access && pattern->scheme() != url::kFileScheme) + valid_schemes &= ~URLPattern::SCHEME_FILE; + + if (valid_schemes != pattern->valid_schemes()) + pattern->SetValidSchemes(valid_schemes); }; for (const auto& origin_str : origins_input) { @@ -179,7 +183,18 @@ return false; } - filter_chrome_scheme(&explicit_origin); + filter_schemes(&explicit_origin); + + if ((explicit_origin.valid_schemes() & URLPattern::SCHEME_FILE) && + !allow_file_access) { + // This should only happen with patterns that specify file schemes; + // otherwise they should have been filtered out in filter_schemes(). + DCHECK_EQ(url::kFileScheme, explicit_origin.scheme()); + result->restricted_file_scheme_patterns.AddPattern(explicit_origin); + // Don't add the pattern to any other set to indicate that it can't be + // requested/granted/contained. + continue; + } bool used_origin = false; if (required_permissions.explicit_hosts().ContainsPattern( @@ -195,7 +210,7 @@ URLPattern scriptable_origin(user_script_schemes); if (scriptable_origin.Parse(origin_str) == URLPattern::ParseResult::kSuccess) { - filter_chrome_scheme(&scriptable_origin); + filter_schemes(&scriptable_origin); if (required_permissions.scriptable_hosts().ContainsPattern( scriptable_origin)) { used_origin = true;
diff --git a/chrome/browser/extensions/api/permissions/permissions_api_helpers.h b/chrome/browser/extensions/api/permissions/permissions_api_helpers.h index dbefd7a..34ad764 100644 --- a/chrome/browser/extensions/api/permissions/permissions_api_helpers.h +++ b/chrome/browser/extensions/api/permissions/permissions_api_helpers.h
@@ -52,20 +52,40 @@ APIPermissionSet unlisted_apis; // Host permissions that were not listed in the extension's permissions. URLPatternSet unlisted_hosts; + + // Special case: restricted file:-scheme patterns. These are populated with + // the patterns that are explicitly related to file:-schemes if the extension + // does *not* have file access. + // Consider unpacking ["<all_urls>", "file:///*"]: + // - If the extension does *not* have file access: + // * <all_urls> will be unpacked normally, but will not include + // URLPattern::SCHEME_FILE as a valid scheme. + // * file:///* will be included in restricted_file_scheme_patterns, because + // it is restricted and cannot be granted without explicit access from the + // chrome://extensions page. + // - If the extension *has* file access: + // * <all_urls> will be unpacked normally, and will include + // URLPattern::SCHEME_FILE as a valid scheme. + // * file:///* will be unpacked normally (|restricted_file_scheme_patterns| + // will be empty). + URLPatternSet restricted_file_scheme_patterns; }; // Parses the |permissions_input| object, and partitions permissions into the // result. |required_permissions| and |optional_permissions| are the required // and optional permissions specified in the extension's manifest, used for -// separating permissions. |allow_file_access| is used to determine whether the -// file:-scheme is valid for host permissions. If an error is detected (e.g., -// an unknown API permission, invalid URL pattern, or API that doesn't support -// being optional), |error| is populated and null is returned. +// separating permissions. |has_file_access| is used to determine whether the +// file:-scheme is valid for host permissions. If file access is allowed, +// <all_urls> will match the file:-scheme (otherwise, it will not). Patterns +// that specifically specify "file:" will be parsed regardless (and placed into +// restricted_file_scheme_patterns if file access is disallowed). If an error is +// detected (e.g., an unknown API permission, invalid URL pattern, or API that +// doesn't support being optional), |error| is populated and null is returned. std::unique_ptr<UnpackPermissionSetResult> UnpackPermissionSet( const api::permissions::Permissions& permissions_input, const PermissionSet& required_permissions, const PermissionSet& optional_permissions, - bool allow_file_access, + bool has_file_access, std::string* error); } // namespace permissions_api_helpers
diff --git a/chrome/browser/extensions/api/permissions/permissions_api_helpers_unittest.cc b/chrome/browser/extensions/api/permissions/permissions_api_helpers_unittest.cc index 8f7cd52..e2cffeb0 100644 --- a/chrome/browser/extensions/api/permissions/permissions_api_helpers_unittest.cc +++ b/chrome/browser/extensions/api/permissions/permissions_api_helpers_unittest.cc
@@ -354,4 +354,134 @@ testing::ElementsAre(kWildcardSchemePattern)); } +// Tests that unpacking <all_urls> correctly includes or omits the file:-scheme. +TEST(ExtensionPermissionsAPIHelpers, Unpack_FileSchemes_AllUrls) { + // Without file access, <all_urls> should be parsed, but the resulting pattern + // should not include file:-scheme access. + { + const int kNonFileSchemes = + Extension::kValidHostPermissionSchemes & ~URLPattern::SCHEME_FILE; + URLPattern all_urls(kNonFileSchemes, URLPattern::kAllUrlsPattern); + PermissionSet required_permissions( + APIPermissionSet(), ManifestPermissionSet(), URLPatternSet({all_urls}), + URLPatternSet()); + + Permissions permissions_object; + permissions_object.origins = std::make_unique<std::vector<std::string>>( + std::vector<std::string>({URLPattern::kAllUrlsPattern})); + + constexpr bool kHasFileAccess = false; + std::string error; + std::unique_ptr<UnpackPermissionSetResult> unpack_result = + UnpackPermissionSet(permissions_object, required_permissions, + PermissionSet(), kHasFileAccess, &error); + ASSERT_TRUE(unpack_result) << error; + + EXPECT_THAT(GetPatternsAsStrings(unpack_result->required_explicit_hosts), + testing::ElementsAre(URLPattern::kAllUrlsPattern)); + EXPECT_FALSE( + unpack_result->required_explicit_hosts.begin()->valid_schemes() & + URLPattern::SCHEME_FILE); + EXPECT_THAT( + GetPatternsAsStrings(unpack_result->restricted_file_scheme_patterns), + testing::IsEmpty()); + } + + // With file access, <all_urls> should be parsed and include file:-scheme + // access. + { + URLPattern all_urls(Extension::kValidHostPermissionSchemes, + URLPattern::kAllUrlsPattern); + PermissionSet required_permissions( + APIPermissionSet(), ManifestPermissionSet(), URLPatternSet({all_urls}), + URLPatternSet()); + + Permissions permissions_object; + permissions_object.origins = std::make_unique<std::vector<std::string>>( + std::vector<std::string>({URLPattern::kAllUrlsPattern})); + + std::string error; + constexpr bool kHasFileAccess = true; + std::unique_ptr<UnpackPermissionSetResult> unpack_result = + UnpackPermissionSet(permissions_object, required_permissions, + PermissionSet(), kHasFileAccess, &error); + ASSERT_TRUE(unpack_result) << error; + + EXPECT_THAT(GetPatternsAsStrings(unpack_result->required_explicit_hosts), + testing::ElementsAre(URLPattern::kAllUrlsPattern)); + EXPECT_TRUE( + unpack_result->required_explicit_hosts.begin()->valid_schemes() & + URLPattern::SCHEME_FILE); + EXPECT_THAT( + GetPatternsAsStrings(unpack_result->restricted_file_scheme_patterns), + testing::IsEmpty()); + } +} + +// Tests that unpacking a pattern that explicitly specifies the file:-scheme is +// properly placed into the |restricted_file_scheme_patterns| set. +TEST(ExtensionPermissionsAPIHelpers, Unpack_FileSchemes_Specific) { + constexpr char kFilePattern[] = "file:///*"; + + // Without file access, the file:-scheme pattern should be populated into + // |restricted_file_scheme_patterns|. + { + URLPattern file_pattern(Extension::kValidHostPermissionSchemes, + kFilePattern); + PermissionSet required_permissions( + APIPermissionSet(), ManifestPermissionSet(), + URLPatternSet({file_pattern}), URLPatternSet()); + + Permissions permissions_object; + permissions_object.origins = std::make_unique<std::vector<std::string>>( + std::vector<std::string>({kFilePattern})); + + std::string error; + constexpr bool kHasFileAccess = false; + std::unique_ptr<UnpackPermissionSetResult> unpack_result = + UnpackPermissionSet(permissions_object, required_permissions, + PermissionSet(), kHasFileAccess, &error); + ASSERT_TRUE(unpack_result) << error; + + EXPECT_THAT(GetPatternsAsStrings(unpack_result->required_explicit_hosts), + testing::IsEmpty()); + EXPECT_THAT( + GetPatternsAsStrings(unpack_result->restricted_file_scheme_patterns), + testing::ElementsAre(kFilePattern)); + EXPECT_TRUE(unpack_result->restricted_file_scheme_patterns.begin() + ->valid_schemes() & + URLPattern::SCHEME_FILE); + } + + // With file access, the file:-scheme pattern should be populated into + // |required_explicit_hosts| (since it's not restricted). + { + URLPattern file_pattern(Extension::kValidHostPermissionSchemes, + kFilePattern); + PermissionSet required_permissions( + APIPermissionSet(), ManifestPermissionSet(), + URLPatternSet({file_pattern}), URLPatternSet()); + + Permissions permissions_object; + permissions_object.origins = std::make_unique<std::vector<std::string>>( + std::vector<std::string>({kFilePattern})); + + std::string error; + constexpr bool kHasFileAccess = true; + std::unique_ptr<UnpackPermissionSetResult> unpack_result = + UnpackPermissionSet(permissions_object, required_permissions, + PermissionSet(), kHasFileAccess, &error); + ASSERT_TRUE(unpack_result) << error; + + EXPECT_THAT(GetPatternsAsStrings(unpack_result->required_explicit_hosts), + testing::ElementsAre(kFilePattern)); + EXPECT_TRUE( + unpack_result->required_explicit_hosts.begin()->valid_schemes() & + URLPattern::SCHEME_FILE); + EXPECT_THAT( + GetPatternsAsStrings(unpack_result->restricted_file_scheme_patterns), + testing::IsEmpty()); + } +} + } // namespace extensions
diff --git a/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc b/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc index 351f1dc..5ff3bb13 100644 --- a/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc +++ b/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc
@@ -8,6 +8,7 @@ #include "base/json/json_writer.h" #include "base/strings/stringprintf.h" #include "base/test/scoped_feature_list.h" +#include "chrome/browser/extensions/chrome_test_extension_loader.h" #include "chrome/browser/extensions/extension_api_unittest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_service.h" @@ -18,9 +19,11 @@ #include "chrome/browser/extensions/scripting_permissions_modifier.h" #include "chrome/test/base/testing_profile.h" #include "components/crx_file/id_util.h" +#include "extensions/browser/test_extension_registry_observer.h" #include "extensions/common/extension_builder.h" #include "extensions/common/extension_features.h" #include "extensions/common/manifest_handlers/permissions_parser.h" +#include "extensions/test/test_extension_dir.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -110,6 +113,8 @@ required_permissions.Append(manifest_permission); scoped_refptr<const Extension> extension = CreateExtensionWithPermissions( required_permissions.Build(), "My Extension", allow_file_access); + ExtensionPrefs::Get(profile())->SetAllowFileAccess(extension->id(), + allow_file_access); scoped_refptr<PermissionsContainsFunction> function( new PermissionsContainsFunction()); function->set_extension(extension.get()); @@ -184,6 +189,15 @@ RunContainsFunction("file:///*", "[{\"origins\":[\"file:///*\"]}]", true /* allow_file_access */); EXPECT_EQ(expected_has_permission, has_permission); + + // Tests calling contains() with <all_urls> with and without file access. + // Regression test for https://crbug.com/931816. + EXPECT_TRUE(RunContainsFunction("<all_urls>", + R"([{"origins": ["<all_urls>"]}])", + false /* allow file access */)); + EXPECT_TRUE(RunContainsFunction("<all_urls>", + R"([{"origins": ["<all_urls>"]}])", + true /* allow file access */)); } TEST_F(PermissionsAPIUnitTest, ContainsAndGetAllWithRuntimeHostPermissions) { @@ -670,4 +684,59 @@ GURL("https://example.com"))); } +// Tests requesting the a file:-scheme pattern with and without file +// access granted. Regression test for https://crbug.com/932703. +TEST_F(PermissionsAPIUnitTest, RequestingFilePermissions) { + // We need a "real" extension here, since toggling file access requires + // reloading the extension to re-initialize permissions. + TestExtensionDir test_dir; + test_dir.WriteManifest( + R"({ + "name": "Extension", + "manifest_version": 2, + "version": "0.1", + "optional_permissions": ["file:///*"] + })"); + ChromeTestExtensionLoader loader(profile()); + loader.set_allow_file_access(false); + scoped_refptr<const Extension> extension = + loader.LoadExtension(test_dir.UnpackedPath()); + ASSERT_TRUE(extension); + EXPECT_FALSE(util::AllowFileAccess(extension->id(), profile())); + const GURL file_url("file:///foo"); + EXPECT_FALSE(extension->permissions_data()->HasHostPermission(file_url)); + + { + auto function = base::MakeRefCounted<PermissionsRequestFunction>(); + function->set_user_gesture(true); + function->set_extension(extension.get()); + std::string error = + extension_function_test_utils::RunFunctionAndReturnError( + function.get(), R"([{"origins": ["file:///*"]}])", browser(), + api_test_utils::NONE); + EXPECT_EQ("Extension must have file access enabled to request 'file:///*'.", + error); + EXPECT_FALSE(extension->permissions_data()->HasHostPermission(file_url)); + } + { + TestExtensionRegistryObserver observer(registry(), extension->id()); + // This will reload the extension, so we need to reset the extension + // pointer. + util::SetAllowFileAccess(extension->id(), profile(), true); + extension = base::WrapRefCounted(observer.WaitForExtensionLoaded()); + ASSERT_TRUE(extension); + } + + std::unique_ptr<const PermissionSet> prompted_permissions; + EXPECT_TRUE(RunRequestFunction(*extension, browser(), + R"([{"origins": ["file:///*"]}])", + &prompted_permissions)); + // Note: There are no permission warnings associated with requesting file + // URLs (probably because there's a separate toggle to control it already); + // they are filtered out of the permission ID set when we get permission + // messages. + EXPECT_FALSE(prompted_permissions); + EXPECT_TRUE(extension->permissions_data()->HasHostPermission(file_url)); +} + } // namespace extensions
diff --git a/chrome/browser/extensions/extension_service_unittest.cc b/chrome/browser/extensions/extension_service_unittest.cc index 9cda7e1..a70122e 100644 --- a/chrome/browser/extensions/extension_service_unittest.cc +++ b/chrome/browser/extensions/extension_service_unittest.cc
@@ -4805,8 +4805,8 @@ public: ExtensionCookieCallback() : result_(false) {} - void SetCookieCallback(bool result) { - result_ = result; + void SetCookieCallback(net::CanonicalCookie::CookieInclusionStatus result) { + result_ = (result == net::CanonicalCookie::CookieInclusionStatus::INCLUDE); } void GetAllCookiesCallback(const net::CookieList& list,
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 68d65253..1a10bb5 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -584,11 +584,6 @@ "expiry_milestone": 76 }, { - "name": "disable-new-zip-unpacker", - "owners": [ "chromeos-files-syd@google.com" ], - "expiry_milestone": 76 - }, - { "name": "disable-office-editing-component-app", // "owners": [ "your-team" ], "expiry_milestone": 76 @@ -689,7 +684,7 @@ }, { "name": "download-home-v2", - // "owners": [ "your-team" ], + "owners": [ "shaktisahu", "xingliu", "dtrainor" ], "expiry_milestone": 76 }, { @@ -789,8 +784,8 @@ }, { "name": "enable-async-dns", - // "owners": [ "your-team" ], - "expiry_milestone": 76 + "owners": [ "ericorth", "net-dev" ], + "expiry_milestone": 81 }, { "name": "enable-async-image-decoding", @@ -946,11 +941,6 @@ "expiry_milestone": 76 }, { - "name": "enable-captive-portal-random-url", - // "owners": [ "your-team" ], - "expiry_milestone": 76 - }, - { "name": "enable-chrome-duet", // "owners": [ "your-team" ], "expiry_milestone": 76 @@ -2226,11 +2216,6 @@ "expiry_milestone": 76 }, { - "name": "input-view", - // "owners": [ "your-team" ], - "expiry_milestone": 76 - }, - { "name": "instant-tethering", // "owners": [ "your-team" ], "expiry_milestone": 76 @@ -2582,6 +2567,11 @@ "expiry_milestone": 80 }, { + "name": "omnibox-ui-blue-search-loop-and-search-query", + "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], + "expiry_milestone": 80 + }, + { "name": "omnibox-ui-use-generic-search-engine-icon", "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], "expiry_milestone": 80 @@ -3023,7 +3013,7 @@ }, { "name": "try-supported-channel-layouts", - // "owners": [ "your-team" ], + "owners": [ "dalecurtis" ], "expiry_milestone": 76 }, { @@ -3119,7 +3109,7 @@ }, { "name": "use-winrt-midi-api", - // "owners": [ "your-team" ], + "owners": [ "toyoshim" ], "expiry_milestone": 76 }, {
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 01e847931..99f82c1c 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -498,10 +498,6 @@ const char kEnableBrotliDescription[] = "Enable Brotli Content-Encoding support."; -const char kEnableCaptivePortalRandomUrl[] = "Captive Portal url Randomization"; -const char kEnableCaptivePortalRandomUrlDescription[] = - "Enable Captive Portal URL randomization."; - const char kEnableDataSaverLiteModeRebrandName[] = "Data Saver Lite Mode Rebranding"; const char kEnableDataSaverLiteModeRebrandDescription[] = @@ -1362,6 +1358,11 @@ "When the omnibox is focused, start an empty spare renderer. This can " "speed up the load of the navigation from the omnibox."; +const char kOmniboxUIBlueSearchLoopAndSearchQueryName[] = + "Omnibox UI Blue Search Loop and Search Query"; +const char kOmniboxUIBlueSearchLoopAndSearchQueryDescription[] = + "Color the generic search icon and search terms blue."; + const char kOmniboxUIHideSteadyStateUrlSchemeName[] = "Omnibox UI Hide Steady-State URL Scheme"; const char kOmniboxUIHideSteadyStateUrlSchemeDescription[] = @@ -3299,11 +3300,6 @@ const char kImeServiceDescription[] = "Enable IME service to provide the IME functionality instead of NaCl"; -const char kInputViewName[] = "Input views"; -const char kInputViewDescription[] = - "Enable IME extensions to supply custom views for user input such as " - "virtual keyboards."; - const char kLockScreenNotificationName[] = "Lock screen notification"; const char kLockScreenNotificationDescription[] = "Enable notifications on the lock screen.";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 4e32335..6e01148 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -330,9 +330,6 @@ extern const char kEnableBrotliName[]; extern const char kEnableBrotliDescription[]; -extern const char kEnableCaptivePortalRandomUrl[]; -extern const char kEnableCaptivePortalRandomUrlDescription[]; - extern const char kEnableDataSaverLiteModeRebrandName[]; extern const char kEnableDataSaverLiteModeRebrandDescription[]; @@ -828,6 +825,9 @@ extern const char kOmniboxSpareRendererName[]; extern const char kOmniboxSpareRendererDescription[]; +extern const char kOmniboxUIBlueSearchLoopAndSearchQueryName[]; +extern const char kOmniboxUIBlueSearchLoopAndSearchQueryDescription[]; + extern const char kOmniboxUIHideSteadyStateUrlSchemeName[]; extern const char kOmniboxUIHideSteadyStateUrlSchemeDescription[]; @@ -1975,9 +1975,6 @@ extern const char kImeServiceName[]; extern const char kImeServiceDescription[]; -extern const char kInputViewName[]; -extern const char kInputViewDescription[]; - extern const char kLockScreenNotificationName[]; extern const char kLockScreenNotificationDescription[];
diff --git a/chrome/browser/lookalikes/lookalike_url_interstitial_page.cc b/chrome/browser/lookalikes/lookalike_url_interstitial_page.cc index 58d773e..232101f 100644 --- a/chrome/browser/lookalikes/lookalike_url_interstitial_page.cc +++ b/chrome/browser/lookalikes/lookalike_url_interstitial_page.cc
@@ -73,10 +73,6 @@ void LookalikeUrlInterstitialPage::OnInterstitialClosing() {} -bool LookalikeUrlInterstitialPage::ShouldDisplayURL() const { - return false; -} - // This handles the commands sent from the interstitial JavaScript. void LookalikeUrlInterstitialPage::CommandReceived(const std::string& command) { if (command == "\"pageLoadComplete\"") {
diff --git a/chrome/browser/lookalikes/lookalike_url_interstitial_page.h b/chrome/browser/lookalikes/lookalike_url_interstitial_page.h index ccb7817..aeeb0b5 100644 --- a/chrome/browser/lookalikes/lookalike_url_interstitial_page.h +++ b/chrome/browser/lookalikes/lookalike_url_interstitial_page.h
@@ -45,7 +45,6 @@ void PopulateInterstitialStrings( base::DictionaryValue* load_time_data) override; void OnInterstitialClosing() override; - bool ShouldDisplayURL() const override; int GetHTMLTemplateId() override; private:
diff --git a/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc b/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc index 6f5d9784..8173894 100644 --- a/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc +++ b/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc
@@ -187,7 +187,6 @@ NavigateToURL(browser, navigated_url); navigation_observer.Wait(); EXPECT_EQ(nullptr, GetCurrentInterstitial(web_contents)); - EXPECT_TRUE(IsUrlShowing(browser)); } { // Navigate to an empty page. This will happen after any @@ -197,7 +196,6 @@ NavigateToURL(browser, GURL("about:blank")); navigation_observer.Wait(); EXPECT_EQ(nullptr, GetCurrentInterstitial(web_contents)); - EXPECT_TRUE(IsUrlShowing(browser)); } } @@ -217,7 +215,6 @@ EXPECT_EQ(LookalikeUrlInterstitialPage::kTypeForTesting, GetInterstitialType(web_contents)); - EXPECT_FALSE(IsUrlShowing(browser)); } // Tests that the histogram event |expected_event| is recorded. If the UI is @@ -300,12 +297,8 @@ base::SimpleTestClock* test_clock() { return &test_clock_; } - protected: - virtual bool ui_enabled() const { return GetParam() == UIEnabled::kEnabled; } - - static bool IsUrlShowing(Browser* browser) { - return !browser->location_bar_model()->GetFormattedFullURL().empty(); - } + private: + bool ui_enabled() const { return GetParam() == UIEnabled::kEnabled; } // Simulates a link click navigation. We don't use // ui_test_utils::NavigateToURL(const GURL&) because it simulates the user @@ -334,7 +327,6 @@ browser->tab_strip_model()->GetActiveWebContents(); EXPECT_EQ(nullptr, GetCurrentInterstitial(web_contents)); - EXPECT_TRUE(IsUrlShowing(browser)); { content::TestNavigationObserver navigation_observer(web_contents, 1); NavigateToURL(browser, navigated_url); @@ -343,7 +335,6 @@ EXPECT_EQ(LookalikeUrlInterstitialPage::kTypeForTesting, GetInterstitialType(web_contents)); - EXPECT_FALSE(IsUrlShowing(browser)); // Clicking the link in the interstitial should remove the interstitial and // navigate to the suggested URL. @@ -356,7 +347,6 @@ EXPECT_EQ(nullptr, GetCurrentInterstitial(web_contents)); EXPECT_EQ(expected_suggested_url, web_contents->GetURL()); - EXPECT_TRUE(IsUrlShowing(browser)); // Clicking the link in the interstitial should also remove the original URL // from history. @@ -386,7 +376,6 @@ EXPECT_EQ(LookalikeUrlInterstitialPage::kTypeForTesting, GetInterstitialType(web_contents)); - EXPECT_FALSE(IsUrlShowing(browser)); // Clicking the ignore button in the interstitial should remove the // interstitial and navigate to the original URL. @@ -399,7 +388,6 @@ EXPECT_EQ(nullptr, GetCurrentInterstitial(web_contents)); EXPECT_EQ(navigated_url, web_contents->GetURL()); - EXPECT_TRUE(IsUrlShowing(browser)); // Clicking the link should result in the original URL appearing in history. ui_test_utils::HistoryEnumerator enumerator(browser->profile()); @@ -411,54 +399,6 @@ base::SimpleTestClock test_clock_; }; -class LookalikeUrlInterstitialPageBrowserTest - : public LookalikeUrlNavigationThrottleBrowserTest { - public: - // Checks that navigating to |navigated_url| displays an interstitial with a - // hidden URL, and then navigating to other pages shows/hides the URLs - // appropriately both when a URL is expected to be hidden (by navigating to - // "chrome://newtab") and when expected to be shown (by navigating to - // |subsequent_url|). - static void TestInterstitialHidesUrlThenRestores(Browser* browser, - const GURL& navigated_url, - const GURL& subsequent_url) { - content::WebContents* web_contents = - browser->tab_strip_model()->GetActiveWebContents(); - - EXPECT_EQ(nullptr, GetCurrentInterstitial(web_contents)); - EXPECT_TRUE(IsUrlShowing(browser)); - { - content::TestNavigationObserver navigation_observer(web_contents, 1); - NavigateToURL(browser, navigated_url); - navigation_observer.Wait(); - } - - EXPECT_EQ(LookalikeUrlInterstitialPage::kTypeForTesting, - GetInterstitialType(web_contents)); - EXPECT_FALSE(IsUrlShowing(browser)); - - { - content::TestNavigationObserver navigation_observer(web_contents, 1); - ui_test_utils::NavigateToURL(browser, subsequent_url); - navigation_observer.Wait(); - } - - EXPECT_EQ(nullptr, GetCurrentInterstitial(web_contents)); - EXPECT_TRUE(IsUrlShowing(browser)); - - { - content::TestNavigationObserver navigation_observer(web_contents, 1); - ui_test_utils::NavigateToURL(browser, GURL("chrome://newtab")); - navigation_observer.Wait(); - } - - EXPECT_FALSE(IsUrlShowing(browser)); - } - - protected: - bool ui_enabled() const override { return true; } -}; - INSTANTIATE_TEST_SUITE_P(, LookalikeUrlNavigationThrottleBrowserTest, ::testing::Values(UIEnabled::kDisabled, @@ -791,12 +731,3 @@ TestOnlyInterstitialShown(browser(), kNavigatedUrl); } } - -// Verify that the URL shows normally on pages after a lookalike interstitial. -IN_PROC_BROWSER_TEST_F(LookalikeUrlInterstitialPageBrowserTest, - UrlShownAfterInterstitial) { - const GURL kNavigatedUrl = GetURL("goooglé.com"); - const GURL kSubsequentUrl = GetURL("example.com"); - TestInterstitialHidesUrlThenRestores(browser(), kNavigatedUrl, - kSubsequentUrl); -}
diff --git a/chrome/browser/media/android/cdm/media_drm_origin_id_manager.h b/chrome/browser/media/android/cdm/media_drm_origin_id_manager.h index 0543aca..fcacd7a 100644 --- a/chrome/browser/media/android/cdm/media_drm_origin_id_manager.h +++ b/chrome/browser/media/android/cdm/media_drm_origin_id_manager.h
@@ -8,6 +8,7 @@ #include "base/callback_forward.h" #include "base/containers/queue.h" #include "base/memory/weak_ptr.h" +#include "base/optional.h" #include "base/threading/thread_checker.h" #include "base/unguessable_token.h" #include "components/keyed_service/core/keyed_service.h" @@ -28,8 +29,11 @@ // destroyed when the Profile goes away. class MediaDrmOriginIdManager : public KeyedService { public: - using ProvisionedOriginIdCB = - base::OnceCallback<void(bool success, const base::UnguessableToken&)>; + // |success| is true if an origin ID was obtained and |origin_id| is + // not null, false otherwise. + using ProvisionedOriginIdCB = base::OnceCallback<void( + bool success, + const base::Optional<base::UnguessableToken>& origin_id)>; static void RegisterProfilePrefs(PrefRegistrySimple* registry);
diff --git a/chrome/browser/media/android/cdm/media_drm_origin_id_manager_unittest.cc b/chrome/browser/media/android/cdm/media_drm_origin_id_manager_unittest.cc index 14893ef..f98dc55 100644 --- a/chrome/browser/media/android/cdm/media_drm_origin_id_manager_unittest.cc +++ b/chrome/browser/media/android/cdm/media_drm_origin_id_manager_unittest.cc
@@ -11,6 +11,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/json/json_string_value_serializer.h" +#include "base/optional.h" #include "base/run_loop.h" #include "base/stl_util.h" #include "base/test/scoped_task_environment.h" @@ -34,6 +35,8 @@ constexpr size_t kExpectedPreferenceListSize = 5; constexpr base::TimeDelta kExpirationDelta = base::TimeDelta::FromHours(24); +using MediaDrmOriginId = base::Optional<base::UnguessableToken>; + } // namespace class MediaDrmOriginIdManagerTest : public testing::Test { @@ -46,13 +49,13 @@ } // Call MediaDrmOriginIdManager::GetOriginId() synchronously. - base::UnguessableToken GetOriginId() { + MediaDrmOriginId GetOriginId() { base::RunLoop run_loop; - base::UnguessableToken result; + MediaDrmOriginId result; origin_id_manager_->GetOriginId(base::BindOnce( - [](base::OnceClosure callback, base::UnguessableToken* result, - bool success, const base::UnguessableToken& origin_id) { + [](base::OnceClosure callback, MediaDrmOriginId* result, bool success, + const MediaDrmOriginId& origin_id) { EXPECT_TRUE(success); *result = origin_id; std::move(callback).Run(); @@ -100,8 +103,8 @@ } TEST_F(MediaDrmOriginIdManagerTest, TwoOriginIds) { - base::UnguessableToken origin_id1 = GetOriginId(); - base::UnguessableToken origin_id2 = GetOriginId(); + MediaDrmOriginId origin_id1 = GetOriginId(); + MediaDrmOriginId origin_id2 = GetOriginId(); EXPECT_TRUE(origin_id1); EXPECT_TRUE(origin_id2); EXPECT_NE(origin_id1, origin_id2); @@ -164,20 +167,18 @@ } TEST_F(MediaDrmOriginIdManagerTest, OriginIdNotInList) { - base::UnguessableToken origin_id; - // After fetching one origin ID MediaDrmOriginIdManager will create the list // of pre-provisioned origin IDs (asynchronously). It doesn't matter if the // device supports per-application provisioning or not. - origin_id = GetOriginId(); + MediaDrmOriginId origin_id = GetOriginId(); test_browser_thread_bundle_.RunUntilIdle(); // Check that the preference does not contain |origin_id|. DVLOG(1) << "Checking preference " << kMediaDrmOriginIds; auto* dict = GetDictionary(kMediaDrmOriginIds); auto* list = dict->FindKey(kAvailableOriginIds); - EXPECT_FALSE( - ContainsValue(list->GetList(), CreateUnguessableTokenValue(origin_id))); + EXPECT_FALSE(ContainsValue(list->GetList(), + CreateUnguessableTokenValue(origin_id.value()))); } TEST_F(MediaDrmOriginIdManagerTest, ProvisioningFail) {
diff --git a/chrome/browser/media/android/cdm/media_drm_storage_factory.cc b/chrome/browser/media/android/cdm/media_drm_storage_factory.cc index 71ed71e9..d15acfe 100644 --- a/chrome/browser/media/android/cdm/media_drm_storage_factory.cc +++ b/chrome/browser/media/android/cdm/media_drm_storage_factory.cc
@@ -9,6 +9,7 @@ #include "base/bind.h" #include "base/callback.h" #include "base/logging.h" +#include "base/optional.h" #include "chrome/browser/media/android/cdm/media_drm_origin_id_manager.h" #include "chrome/browser/media/android/cdm/media_drm_origin_id_manager_factory.h" #include "chrome/browser/profiles/profile.h" @@ -31,7 +32,7 @@ auto* origin_id_manager = MediaDrmOriginIdManagerFactory::GetForProfile(profile); if (!origin_id_manager) { - std::move(callback).Run(false, base::UnguessableToken()); + std::move(callback).Run(false, base::nullopt); return; }
diff --git a/chrome/browser/media/router/issue_manager_unittest.cc b/chrome/browser/media/router/issue_manager_unittest.cc index 87c8f74..a43501f 100644 --- a/chrome/browser/media/router/issue_manager_unittest.cc +++ b/chrome/browser/media/router/issue_manager_unittest.cc
@@ -110,7 +110,7 @@ EXPECT_CALL(observer, OnIssuesCleared()).Times(1); base::TimeDelta timeout = IssueManager::GetAutoDismissTimeout(issue_info1); EXPECT_FALSE(timeout.is_zero()); - EXPECT_TRUE(thread_bundle_.MainThreadHasPendingTask()); + EXPECT_TRUE(thread_bundle_.MainThreadIsIdle()); thread_bundle_.FastForwardBy(timeout); EXPECT_CALL(observer, OnIssue(_)).Times(1); @@ -120,9 +120,9 @@ EXPECT_CALL(observer, OnIssuesCleared()).Times(1); timeout = IssueManager::GetAutoDismissTimeout(issue_info2); EXPECT_FALSE(timeout.is_zero()); - EXPECT_TRUE(thread_bundle_.MainThreadHasPendingTask()); + EXPECT_GT(thread_bundle_.GetPendingMainThreadTaskCount(), 0u); thread_bundle_.FastForwardBy(timeout); - EXPECT_FALSE(thread_bundle_.MainThreadHasPendingTask()); + EXPECT_EQ(thread_bundle_.GetPendingMainThreadTaskCount(), 0u); } TEST_F(IssueManagerTest, IssueAutoDismissNoopsIfAlreadyCleared) { @@ -136,13 +136,13 @@ ASSERT_TRUE(testing::Mock::VerifyAndClearExpectations(&observer)); EXPECT_CALL(observer, OnIssuesCleared()).Times(1); - EXPECT_TRUE(thread_bundle_.MainThreadHasPendingTask()); + EXPECT_GT(thread_bundle_.GetPendingMainThreadTaskCount(), 0u); manager_.ClearIssue(issue1.id()); EXPECT_CALL(observer, OnIssuesCleared()).Times(0); base::TimeDelta timeout = IssueManager::GetAutoDismissTimeout(issue_info1); EXPECT_FALSE(timeout.is_zero()); - EXPECT_FALSE(thread_bundle_.MainThreadHasPendingTask()); + EXPECT_EQ(thread_bundle_.GetPendingMainThreadTaskCount(), 0u); } TEST_F(IssueManagerTest, BlockingIssuesDoNotGetAutoDismissed) { @@ -158,7 +158,7 @@ base::TimeDelta timeout = IssueManager::GetAutoDismissTimeout(issue_info1); EXPECT_TRUE(timeout.is_zero()); - EXPECT_FALSE(thread_bundle_.MainThreadHasPendingTask()); + EXPECT_EQ(thread_bundle_.GetPendingMainThreadTaskCount(), 0u); // FATAL issues are always blocking. IssueInfo issue_info2 = CreateTestIssue(IssueInfo::Severity::FATAL); @@ -166,7 +166,7 @@ timeout = IssueManager::GetAutoDismissTimeout(issue_info2); EXPECT_TRUE(timeout.is_zero()); - EXPECT_FALSE(thread_bundle_.MainThreadHasPendingTask()); + EXPECT_EQ(thread_bundle_.GetPendingMainThreadTaskCount(), 0u); } TEST_F(IssueManagerTest, ClearNonBlockingIssues) {
diff --git a/chrome/browser/media/router/providers/cast/cast_activity_manager.cc b/chrome/browser/media/router/providers/cast/cast_activity_manager.cc index 8569e0cd..9e084fc 100644 --- a/chrome/browser/media/router/providers/cast/cast_activity_manager.cc +++ b/chrome/browser/media/router/providers/cast/cast_activity_manager.cc
@@ -4,6 +4,9 @@ #include "chrome/browser/media/router/providers/cast/cast_activity_manager.h" +#include <memory> +#include <vector> + #include "base/bind.h" #include "chrome/browser/media/router/data_decoder_util.h" #include "chrome/common/media_router/discovery/media_sink_service_base.h" @@ -202,20 +205,6 @@ connection_binding_.Close(); } -CastActivityRecord::CastActivityRecord( - const MediaRoute& route, - const std::string& app_id, - MediaSinkServiceBase* media_sink_service, - cast_channel::CastMessageHandler* message_handler, - CastSessionTracker* session_tracker, - DataDecoder* data_decoder) - : route_(route), - app_id_(app_id), - media_sink_service_(media_sink_service), - message_handler_(message_handler), - session_tracker_(session_tracker), - data_decoder_(data_decoder) {} - CastActivityRecord::~CastActivityRecord() {} mojom::RoutePresentationConnectionPtr CastActivityRecord::AddClient( @@ -284,6 +273,21 @@ cast_message.client_id, std::move(callback)); } +void CastActivityRecord::SendStopSessionMessageToReceiver( + const base::Optional<std::string>& client_id, + mojom::MediaRouteProvider::TerminateRouteCallback callback) { + const std::string& sink_id = route_.media_sink_id(); + const MediaSinkInternal* sink = media_sink_service_->GetSinkById(sink_id); + DCHECK(sink); + DCHECK(session_id_); + + message_handler_->StopSession( + sink->cast_data().cast_channel_id, *session_id_, client_id, + base::BindOnce(&CastActivityManager::HandleStopSessionResponse, + activity_manager_->GetWeakPtr(), route_.media_route_id(), + std::move(callback))); +} + void CastActivityRecord::SendMessageToClient( const std::string& client_id, blink::mojom::PresentationConnectionMessagePtr message) { @@ -306,6 +310,22 @@ client.second->TerminateConnection(); } +CastActivityRecord::CastActivityRecord( + const MediaRoute& route, + const std::string& app_id, + MediaSinkServiceBase* media_sink_service, + cast_channel::CastMessageHandler* message_handler, + CastSessionTracker* session_tracker, + DataDecoder* data_decoder, + CastActivityManager* owner) + : route_(route), + app_id_(app_id), + media_sink_service_(media_sink_service), + message_handler_(message_handler), + session_tracker_(session_tracker), + data_decoder_(data_decoder), + activity_manager_(owner) {} + CastSession* CastActivityRecord::GetSession() { DCHECK(session_id_); CastSession* session = session_tracker_->GetSessionById(*session_id_); @@ -412,8 +432,7 @@ existing_route_id, base::BindOnce( &CastActivityManager::LaunchSessionAfterTerminatingExisting, - weak_ptr_factory_.GetWeakPtr(), existing_route_id, - std::move(params))); + GetWeakPtr(), existing_route_id, std::move(params))); } } @@ -431,19 +450,17 @@ << ", sink ID = " << sink.sink().id() << ", app ID = " << app_id << ", origin = " << params.origin << ", tab ID = " << params.tab_id; - auto activity = std::make_unique<CastActivityRecord>( + std::unique_ptr<CastActivityRecord> activity(new CastActivityRecord( route, app_id, media_sink_service_, message_handler_, session_tracker_, - data_decoder_.get()); + data_decoder_.get(), this)); auto* activity_ptr = activity.get(); activities_.emplace(route_id, std::move(activity)); NotifyAllOnRoutesUpdated(); - base::TimeDelta launch_timeout = cast_source.launch_timeout(); message_handler_->LaunchSession( sink.cast_data().cast_channel_id, app_id, launch_timeout, base::BindOnce(&CastActivityManager::HandleLaunchSessionResponse, - weak_ptr_factory_.GetWeakPtr(), route_id, sink, - cast_source)); + GetWeakPtr(), route_id, sink, cast_source)); mojom::RoutePresentationConnectionPtr presentation_connection; const std::string& client_id = cast_source.client_id(); @@ -521,22 +538,16 @@ } const MediaSinkInternal* sink = media_sink_service_->GetSinkByRoute(route); - if (!sink) { - RemoveActivity(activity_it); - std::move(callback).Run(base::nullopt, RouteRequestResult::OK); - return; - } + CHECK(sink); for (auto& client : activity->connected_clients()) { client.second->SendMessageToClient( CreateReceiverActionStopMessage(client.first, *sink, hash_token_)); } - message_handler_->StopSession( - sink->cast_data().cast_channel_id, *session_id, - base::BindOnce(&CastActivityManager::HandleStopSessionResponse, - weak_ptr_factory_.GetWeakPtr(), route_id, - std::move(callback))); + activity->SendStopSessionMessageToReceiver( + base::nullopt, // TODO(jrw): Get the real client ID. + std::move(callback)); } CastActivityManager::ActivityMap::iterator @@ -674,9 +685,9 @@ MediaRoute route(route_id, source, sink_id, /* description */ std::string(), /* is_local */ false, /* for_display */ true); - auto record = std::make_unique<CastActivityRecord>( + std::unique_ptr<CastActivityRecord> record(new CastActivityRecord( route, app_id, media_sink_service_, message_handler_, session_tracker_, - data_decoder_.get()); + data_decoder_.get(), this)); record->SetOrUpdateSession(session, sink, hash_token_); activities_.emplace(route_id, std::move(record)); } @@ -744,13 +755,12 @@ DVLOG(2) << "Sending new_session message for route " << route_id << ", client_id: " << client_id; activity_it->second->SendMessageToClient( - client_id, CreateNewSessionMessage(*session, cast_source.client_id(), - sink, hash_token_)); + client_id, + CreateNewSessionMessage(*session, client_id, sink, hash_token_)); - // TODO(imcheng): Query media status. + // TODO(jrw): Query media status. message_handler_->EnsureConnection(sink.cast_data().cast_channel_id, - cast_source.client_id(), - session->transport_id()); + client_id, session->transport_id()); } activity_it->second->SetOrUpdateSession(*session, sink, hash_token_); @@ -762,6 +772,8 @@ mojom::MediaRouteProvider::TerminateRouteCallback callback, cast_channel::Result result) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + VLOG(2) << __func__ << ": " << route_id; + auto activity_it = activities_.find(route_id); if (activity_it == activities_.end()) { // The activity could've been removed via RECEIVER_STATUS message. @@ -789,6 +801,10 @@ media_router_->OnIssue(info); } +base::WeakPtr<CastActivityManager> CastActivityManager::GetWeakPtr() { + return weak_ptr_factory_.GetWeakPtr(); +} + CastActivityManager::DoLaunchSessionParams::DoLaunchSessionParams( const MediaRoute& route, const CastMediaSource& cast_source,
diff --git a/chrome/browser/media/router/providers/cast/cast_activity_manager.h b/chrome/browser/media/router/providers/cast/cast_activity_manager.h index 08fe0ccc..0844a01 100644 --- a/chrome/browser/media/router/providers/cast/cast_activity_manager.h +++ b/chrome/browser/media/router/providers/cast/cast_activity_manager.h
@@ -135,12 +135,6 @@ // Instances of this class are associated with a specific session and app. class CastActivityRecord { public: - CastActivityRecord(const MediaRoute& route, - const std::string& app_id, - MediaSinkServiceBase* media_sink_service, - cast_channel::CastMessageHandler* message_handler, - CastSessionTracker* session_tracker, - DataDecoder* data_decoder); ~CastActivityRecord(); const MediaRoute& route() const { return route_; } @@ -168,6 +162,10 @@ void SendSetVolumeRequestToReceiver(const CastInternalMessage& cast_message, cast_channel::ResultCallback callback); + void SendStopSessionMessageToReceiver( + const base::Optional<std::string>& client_id, + mojom::MediaRouteProvider::TerminateRouteCallback callback); + // Adds a new client |client_id| to this session and returns the handles of // the two pipes to be held by Blink It is invalid to call this method if the // client already exists. @@ -198,6 +196,16 @@ private: friend class CastSessionClient; + friend class CastActivityManager; + + // Creates a new record owned by |owner|. + CastActivityRecord(const MediaRoute& route, + const std::string& app_id, + MediaSinkServiceBase* media_sink_service, + cast_channel::CastMessageHandler* message_handler, + CastSessionTracker* session_tracker, + DataDecoder* data_decoder, + CastActivityManager* owner); CastSession* GetSession(); int GetCastChannelId(); @@ -217,6 +225,7 @@ cast_channel::CastMessageHandler* const message_handler_; CastSessionTracker* const session_tracker_; DataDecoder* const data_decoder_; + CastActivityManager* const activity_manager_; DISALLOW_COPY_AND_ASSIGN(CastActivityRecord); }; @@ -280,6 +289,8 @@ base::Optional<int> request_id) override; private: + friend class CastActivityRecord; + using ActivityMap = base::flat_map<MediaRoute::Id, std::unique_ptr<CastActivityRecord>>; @@ -350,6 +361,8 @@ void SendFailedToCastIssue(const MediaSink::Id& sink_id, const MediaRoute::Id& route_id); + base::WeakPtr<CastActivityManager> GetWeakPtr(); + // These methods return |activities_.end()| when nothing is found. ActivityMap::iterator FindActivityByChannelId(int channel_id); ActivityMap::iterator FindActivityBySink(const MediaSinkInternal& sink);
diff --git a/chrome/browser/media/router/providers/cast/cast_activity_manager_unittest.cc b/chrome/browser/media/router/providers/cast/cast_activity_manager_unittest.cc index d5ca539..dddd0cd 100644 --- a/chrome/browser/media/router/providers/cast/cast_activity_manager_unittest.cc +++ b/chrome/browser/media/router/providers/cast/cast_activity_manager_unittest.cc
@@ -31,6 +31,7 @@ using testing::IsEmpty; using testing::Not; using testing::Return; +using testing::WithArg; namespace media_router { @@ -179,10 +180,9 @@ // A launch session request is sent to the sink. EXPECT_CALL(message_handler_, LaunchSession(kChannelId, "ABCDEFGH", kDefaultLaunchTimeout, _)) - .WillOnce( - [this](auto chanel_id, auto app_id, auto timeout, auto callback) { - launch_session_callback_ = std::move(callback); - }); + .WillOnce(WithArg<3>([this](auto callback) { + launch_session_callback_ = std::move(callback); + })); auto source = CastMediaSource::FromMediaSourceId(kSource1); ASSERT_TRUE(source); @@ -245,10 +245,11 @@ void TerminateSession(cast_channel::Result result) { cast_channel::ResultCallback stop_session_callback; - EXPECT_CALL(message_handler_, StopSession(kChannelId, "theSessionId", _)) - .WillOnce([&](auto channel_id, auto session_id, auto callback) { + EXPECT_CALL(message_handler_, StopSession(kChannelId, "theSessionId", + base::Optional<std::string>(), _)) + .WillOnce(WithArg<3>([&](auto callback) { stop_session_callback = std::move(callback); - }); + })); manager_->TerminateSession( route_->media_route_id(), base::BindOnce( @@ -267,7 +268,7 @@ // not called. void TerminateNoSession() { // Stop session message not sent because session has not launched yet. - EXPECT_CALL(message_handler_, StopSession(_, _, _)).Times(0); + EXPECT_CALL(message_handler_, StopSession(_, _, _, _)).Times(0); manager_->TerminateSession( route_->media_route_id(), base::BindOnce(&CastActivityManagerTest::ExpectTerminateResultSuccess, @@ -299,13 +300,12 @@ void ExpectSingleRouteUpdate(MediaRoute* route_ptr = nullptr) { EXPECT_CALL(mock_router_, OnRoutesUpdated(MediaRouteProviderId::CAST, Not(IsEmpty()), _, _)) - .WillOnce([=](auto provider_id, auto routes, auto media_source, - auto joinable_route_ids) { + .WillOnce(WithArg<1>([=](auto routes) { EXPECT_EQ(1u, routes.size()); if (route_ptr) { *route_ptr = routes[0]; } - }); + })); } // Expect a call to OnRoutesUpdated() with no routes. @@ -369,10 +369,10 @@ // Existing session will be terminated. cast_channel::ResultCallback stop_session_callback; - EXPECT_CALL(message_handler_, StopSession(kChannelId, "theSessionId", _)) - .WillOnce([&](auto channel_id, auto session_id, auto callback) { - stop_session_callback = std::move(callback); - }); + EXPECT_CALL(message_handler_, StopSession(kChannelId, "theSessionId", + base::Optional<std::string>(), _)) + .WillOnce(WithArg<3>( + [&](auto callback) { stop_session_callback = std::move(callback); })); // Launch a new session on the same sink. auto source = CastMediaSource::FromMediaSourceId(kSource2); @@ -642,8 +642,7 @@ EXPECT_CALL(message_handler_, SendSetVolumeRequest(kChannelId, IsJson(expected_message), "theClientId", _)) - .WillOnce([&](int channel_id, const base::Value& message, - const std::string& client_id, auto callback) { + .WillOnce(WithArg<3>([&](auto callback) { // Check message created by CastSessionClient::SendResultResponse(). EXPECT_CALL(*client_connection_, OnMessage(IsCastMessage(R"({ "clientId": "theClientId", @@ -654,7 +653,7 @@ })"))); std::move(callback).Run(cast_channel::Result::kOk); return cast_channel::Result::kOk; - }); + })); client_connection_->SendMessageToMediaRouter( blink::mojom::PresentationConnectionMessage::NewMessage(R"({ "type": "v2_message",
diff --git a/chrome/browser/net/chrome_mojo_proxy_resolver_factory_browsertest.cc b/chrome/browser/net/chrome_mojo_proxy_resolver_factory_browsertest.cc index 8f23df5..2e5096d 100644 --- a/chrome/browser/net/chrome_mojo_proxy_resolver_factory_browsertest.cc +++ b/chrome/browser/net/chrome_mojo_proxy_resolver_factory_browsertest.cc
@@ -145,7 +145,8 @@ void Alert(const std::string& error) override {} void OnError(int32_t line_number, const std::string& error) override {} void ResolveDns( - std::unique_ptr<net::HostResolver::RequestInfo> request_info, + const std::string& hostname, + net::ProxyResolveDnsOperation operation, proxy_resolver::mojom::HostResolverRequestClientPtr client) override {} proxy_resolver::mojom::ProxyResolverPtr resolver_;
diff --git a/chrome/browser/page_load_metrics/observers/signed_exchange_page_load_metrics_browsertest.cc b/chrome/browser/page_load_metrics/observers/signed_exchange_page_load_metrics_browsertest.cc new file mode 100644 index 0000000..97a5fa3 --- /dev/null +++ b/chrome/browser/page_load_metrics/observers/signed_exchange_page_load_metrics_browsertest.cc
@@ -0,0 +1,104 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/test/metrics/histogram_tester.h" +#include "chrome/browser/page_load_metrics/page_load_metrics_test_waiter.h" +#include "chrome/browser/ssl/cert_verifier_browser_test.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/test/base/ui_test_utils.h" +#include "components/ukm/test_ukm_recorder.h" +#include "content/public/common/content_features.h" +#include "content/public/test/browser_test_utils.h" +#include "content/public/test/signed_exchange_browser_test_helper.h" +#include "net/dns/mock_host_resolver.h" +#include "services/metrics/public/cpp/ukm_builders.h" + +class SignedExchangePageLoadMetricsBrowserTest + : public CertVerifierBrowserTest { + public: + SignedExchangePageLoadMetricsBrowserTest() { + feature_list_.InitWithFeatures( + {ukm::kUkmFeature, features::kSignedHTTPExchange}, {}); + } + ~SignedExchangePageLoadMetricsBrowserTest() override {} + + protected: + void PreRunTestOnMainThread() override { + InProcessBrowserTest::PreRunTestOnMainThread(); + test_ukm_recorder_ = std::make_unique<ukm::TestAutoSetUkmRecorder>(); + + sxg_test_helper_.InstallMockCert(mock_cert_verifier()); + sxg_test_helper_.InstallMockCertChainInterceptor(); + } + + // Force navigation to a new page, so the currently tracked page load runs its + // OnComplete callback. You should prefer to use PageLoadMetricsTestWaiter, + // and only use NavigateToUntrackedUrl for cases where the waiter isn't + // sufficient. + void NavigateToUntrackedUrl() { + ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)); + } + + void InstallUrlInterceptor(const GURL& url, const std::string& data_path) { + sxg_test_helper_.InstallUrlInterceptor(url, data_path); + } + + std::unique_ptr<page_load_metrics::PageLoadMetricsTestWaiter> + CreatePageLoadMetricsTestWaiter() { + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + return std::make_unique<page_load_metrics::PageLoadMetricsTestWaiter>( + web_contents); + } + + const ukm::TestAutoSetUkmRecorder& test_ukm_recorder() const { + return *test_ukm_recorder_; + } + + private: + void SetUp() override { + // Somehow tests actually run inside InProcessBrowserTest::SetUp(), + // so setup helper before InProcessBrowserTest::SetUp(). + sxg_test_helper_.SetUp(); + + InProcessBrowserTest::SetUp(); + } + + void TearDownOnMainThread() override { + sxg_test_helper_.TearDownOnMainThread(); + } + + base::test::ScopedFeatureList feature_list_; + std::unique_ptr<ukm::TestAutoSetUkmRecorder> test_ukm_recorder_; + content::SignedExchangeBrowserTestHelper sxg_test_helper_; + + DISALLOW_COPY_AND_ASSIGN(SignedExchangePageLoadMetricsBrowserTest); +}; + +IN_PROC_BROWSER_TEST_F(SignedExchangePageLoadMetricsBrowserTest, + UkmSignedExchangeMetric) { + embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data"); + ASSERT_TRUE(embedded_test_server()->Start()); + + const GURL inner_url("https://test.example.org/test/"); + const GURL url = + embedded_test_server()->GetURL("/sxg/test.example.org_test.sxg"); + ui_test_utils::NavigateToURL(browser(), url); + + // Force navigation to another page, which should force logging of histograms + // persisted at the end of the page load lifetime. + NavigateToUntrackedUrl(); + + using PageLoad = ukm::builders::PageLoad; + const auto entries = + test_ukm_recorder().GetMergedEntriesByName(PageLoad::kEntryName); + EXPECT_EQ(1u, entries.size()); + for (const auto& kv : entries) { + auto* const entry = kv.second.get(); + test_ukm_recorder().ExpectEntrySourceHasUrl(entry, inner_url); + + EXPECT_TRUE(test_ukm_recorder().EntryHasMetric( + entry, PageLoad::kIsSignedExchangeInnerResponseName)); + } +}
diff --git a/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.cc b/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.cc index 63a77f5..8968681 100644 --- a/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.cc +++ b/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.cc
@@ -4,12 +4,15 @@ #include "chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.h" +#include <cmath> #include <memory> #include "chrome/browser/browser_process.h" +#include "chrome/browser/engagement/site_engagement_service.h" #include "chrome/browser/page_load_metrics/page_load_metrics_util.h" #include "chrome/browser/profiles/profile.h" #include "components/metrics/net/network_metrics_provider.h" +#include "content/public/browser/web_contents.h" #include "net/base/load_timing_info.h" #include "net/http/http_response_headers.h" #include "services/metrics/public/cpp/metrics_utils.h" @@ -46,6 +49,8 @@ return CONTINUE_OBSERVING; } + browser_context_ = navigation_handle->GetWebContents()->GetBrowserContext(); + // When OnStart is invoked, we don't yet know whether we're observing a web // page load, vs another kind of load (e.g. a download or a PDF). Thus, // metrics and source information should not be recorded here. Instead, we @@ -80,6 +85,8 @@ // The PageTransition for the navigation may be updated on commit. page_transition_ = navigation_handle->GetPageTransition(); was_cached_ = navigation_handle->WasResponseCached(); + is_signed_exchange_inner_response_ = + navigation_handle->IsSignedExchangeInnerResponse(); navigation_start_ = navigation_handle->NavigationStart(); return CONTINUE_OBSERVING; } @@ -161,6 +168,13 @@ const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) { ukm::builders::PageLoad builder(info.source_id); + + base::Optional<int64_t> rounded_site_engagement_score = + GetRoundedSiteEngagementScore(info); + if (rounded_site_engagement_score) { + builder.SetSiteEngagementScore(rounded_site_engagement_score.value()); + } + if (timing.input_to_navigation_start) { builder.SetExperimental_InputToNavigationStart( timing.input_to_navigation_start.value().InMilliseconds()); @@ -330,6 +344,9 @@ if (info.did_commit && was_cached_) { builder.SetWasCached(1); } + if (info.did_commit && is_signed_exchange_inner_response_) { + builder.SetIsSignedExchangeInnerResponse(1); + } builder.Record(ukm::UkmRecorder::Get()); } @@ -420,3 +437,27 @@ UMA_HISTOGRAM_COUNTS_100("PageLoad.Experimental.LayoutStability.JankScore", uma_value); } + +base::Optional<int64_t> +UkmPageLoadMetricsObserver::GetRoundedSiteEngagementScore( + const page_load_metrics::PageLoadExtraInfo& info) const { + if (!browser_context_) + return base::nullopt; + + Profile* profile = Profile::FromBrowserContext(browser_context_); + SiteEngagementService* engagement_service = + SiteEngagementService::Get(profile); + + // UKM privacy requires the engagement score be rounded to nearest + // value of 10. + int64_t rounded_document_engagement_score = + static_cast<int>( + std::roundf(engagement_service->GetScore(info.url) / 10.0)) * + 10; + + DCHECK(rounded_document_engagement_score >= 0 && + rounded_document_engagement_score <= + engagement_service->GetMaxPoints()); + + return rounded_document_engagement_score; +}
diff --git a/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.h b/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.h index 9f60668..6f81d8c 100644 --- a/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.h +++ b/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.h
@@ -12,6 +12,10 @@ #include "services/metrics/public/cpp/ukm_source.h" #include "ui/base/page_transition_types.h" +namespace content { +class BrowserContext; +} + namespace network { class NetworkQualityTracker; } @@ -85,6 +89,11 @@ void ReportLayoutStability(const page_load_metrics::PageLoadExtraInfo& info); + // Captures the site engagement score for the commited URL and + // returns the score rounded to the nearest 10. + base::Optional<int64_t> GetRoundedSiteEngagementScore( + const page_load_metrics::PageLoadExtraInfo& info) const; + // Guaranteed to be non-null during the lifetime of |this|. network::NetworkQualityTracker* network_quality_tracker_; @@ -116,9 +125,15 @@ // True if the page main resource was served from disk cache. bool was_cached_ = false; + // True if the page main resource is inner response of a signed exchange. + bool is_signed_exchange_inner_response_ = false; + // The number of main frame redirects that occurred before commit. uint32_t main_frame_request_redirect_count_ = 0; + // The browser context this navigation is operating in. + content::BrowserContext* browser_context_ = nullptr; + DISALLOW_COPY_AND_ASSIGN(UkmPageLoadMetricsObserver); };
diff --git a/chrome/browser/page_load_metrics/page_load_metrics_browsertest.cc b/chrome/browser/page_load_metrics/page_load_metrics_browsertest.cc index 11066b5..b810d86f 100644 --- a/chrome/browser/page_load_metrics/page_load_metrics_browsertest.cc +++ b/chrome/browser/page_load_metrics/page_load_metrics_browsertest.cc
@@ -257,6 +257,8 @@ EXPECT_TRUE(test_ukm_recorder_->EntryHasMetric( kv.second.get(), PageLoad::kMainFrameResource_NavigationStartToRequestStartName)); + EXPECT_TRUE(test_ukm_recorder_->EntryHasMetric( + kv.second.get(), PageLoad::kSiteEngagementScoreName)); } // Verify that NoPageLoadMetricsRecorded returns false when PageLoad metrics
diff --git a/chrome/browser/performance_manager/performance_manager.cc b/chrome/browser/performance_manager/performance_manager.cc index bb590d9d..6c077ef 100644 --- a/chrome/browser/performance_manager/performance_manager.cc +++ b/chrome/browser/performance_manager/performance_manager.cc
@@ -13,6 +13,7 @@ #include "base/task/post_task.h" #include "base/task/task_traits.h" #include "build/build_config.h" +#include "chrome/browser/performance_manager/graph/system_node_impl.h" #include "chrome/browser/performance_manager/observers/metrics_collector.h" #include "chrome/browser/performance_manager/observers/page_signal_generator_impl.h" #include "chrome/browser/performance_manager/observers/working_set_trimmer_win.h" @@ -68,6 +69,14 @@ instance->task_runner_->DeleteSoon(FROM_HERE, instance.release()); } +void PerformanceManager::DistributeMeasurementBatch( + resource_coordinator::mojom::ProcessResourceMeasurementBatchPtr batch) { + task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&PerformanceManager::DistributeMeasurementBatchImpl, + base::Unretained(this), std::move(batch))); +} + void PerformanceManager::BindInterface( const std::string& interface_name, mojo::ScopedMessagePipeHandle message_pipe) { @@ -129,6 +138,14 @@ service_manager::BindSourceInfo()); } +void PerformanceManager::DistributeMeasurementBatchImpl( + resource_coordinator::mojom::ProcessResourceMeasurementBatchPtr batch) { + SystemNodeImpl* system_node = graph_.FindOrCreateSystemNode(nullptr); + DCHECK(system_node); + + system_node->DistributeMeasurementBatch(std::move(batch)); +} + void PerformanceManager::BindWebUIGraphDump( resource_coordinator::mojom::WebUIGraphDumpRequest request, const service_manager::BindSourceInfo& source_info) {
diff --git a/chrome/browser/performance_manager/performance_manager.h b/chrome/browser/performance_manager/performance_manager.h index 390e5ad..1b68984 100644 --- a/chrome/browser/performance_manager/performance_manager.h +++ b/chrome/browser/performance_manager/performance_manager.h
@@ -15,6 +15,7 @@ #include "chrome/browser/performance_manager/graph/graph_introspector_impl.h" #include "chrome/browser/performance_manager/performance_manager.h" #include "chrome/browser/performance_manager/webui_graph_dump_impl.h" +#include "services/resource_coordinator/public/mojom/coordination_unit.mojom.h" #include "services/resource_coordinator/public/mojom/coordination_unit_provider.mojom.h" #include "services/service_manager/public/cpp/bind_source_info.h" #include "services/service_manager/public/cpp/binder_registry.h" @@ -52,6 +53,13 @@ template <typename Interface> void BindInterface(mojo::InterfaceRequest<Interface> request); + // Dispatches a measurement batch to the SystemNode on the performance + // sequence. This is a temporary method to support the RenderProcessProbe, + // which will soon go away as the performance measurement moves to the + // performance sequence. + void DistributeMeasurementBatch( + resource_coordinator::mojom::ProcessResourceMeasurementBatchPtr batch); + private: using InterfaceRegistry = service_manager::BinderRegistryWithArgs< const service_manager::BindSourceInfo&>; @@ -65,6 +73,8 @@ void OnStartImpl(std::unique_ptr<service_manager::Connector> connector); void BindInterfaceImpl(const std::string& interface_name, mojo::ScopedMessagePipeHandle message_pipe); + void DistributeMeasurementBatchImpl( + resource_coordinator::mojom::ProcessResourceMeasurementBatchPtr batch); void BindWebUIGraphDump( resource_coordinator::mojom::WebUIGraphDumpRequest request,
diff --git a/chrome/browser/performance_monitor/OWNERS b/chrome/browser/performance_monitor/OWNERS index bf831d0..59e16be 100644 --- a/chrome/browser/performance_monitor/OWNERS +++ b/chrome/browser/performance_monitor/OWNERS
@@ -1,2 +1,3 @@ oysteine@chromium.org +sebmarchand@chromium.org simonhatch@chromium.org
diff --git a/chrome/browser/performance_monitor/metric_evaluator_helper_posix.cc b/chrome/browser/performance_monitor/metric_evaluator_helper_posix.cc new file mode 100644 index 0000000..63aae7b --- /dev/null +++ b/chrome/browser/performance_monitor/metric_evaluator_helper_posix.cc
@@ -0,0 +1,19 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/performance_monitor/metric_evaluator_helper_posix.h" + +#include "base/logging.h" + +namespace performance_monitor { + +MetricEvaluatorsHelperPosix::MetricEvaluatorsHelperPosix() = default; +MetricEvaluatorsHelperPosix::~MetricEvaluatorsHelperPosix() = default; + +base::Optional<int> MetricEvaluatorsHelperPosix::GetFreePhysicalMemoryMb() { + NOTREACHED(); + return base::nullopt; +} + +} // namespace performance_monitor
diff --git a/chrome/browser/performance_monitor/metric_evaluator_helper_posix.h b/chrome/browser/performance_monitor/metric_evaluator_helper_posix.h new file mode 100644 index 0000000..3f5febc --- /dev/null +++ b/chrome/browser/performance_monitor/metric_evaluator_helper_posix.h
@@ -0,0 +1,26 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_PERFORMANCE_MONITOR_METRIC_EVALUATOR_HELPER_POSIX_H_ +#define CHROME_BROWSER_PERFORMANCE_MONITOR_METRIC_EVALUATOR_HELPER_POSIX_H_ + +#include "chrome/browser/performance_monitor/system_monitor.h" + +namespace performance_monitor { + +class MetricEvaluatorsHelperPosix : public MetricEvaluatorsHelper { + public: + MetricEvaluatorsHelperPosix(); + ~MetricEvaluatorsHelperPosix() override; + + // MetricEvaluatorsHelper: + base::Optional<int> GetFreePhysicalMemoryMb() override; + + private: + DISALLOW_COPY_AND_ASSIGN(MetricEvaluatorsHelperPosix); +}; + +} // namespace performance_monitor + +#endif // CHROME_BROWSER_PERFORMANCE_MONITOR_METRIC_EVALUATOR_HELPER_POSIX_H_
diff --git a/chrome/browser/performance_monitor/metric_evaluator_helper_win.cc b/chrome/browser/performance_monitor/metric_evaluator_helper_win.cc new file mode 100644 index 0000000..d7e50c48 --- /dev/null +++ b/chrome/browser/performance_monitor/metric_evaluator_helper_win.cc
@@ -0,0 +1,31 @@ +// 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/performance_monitor/metric_evaluator_helper_win.h" + +#include <windows.h> + +#include "base/optional.h" + +namespace performance_monitor { + +namespace { + +const DWORDLONG kMBBytes = 1024 * 1024; + +} // namespace + +MetricEvaluatorsHelperWin::MetricEvaluatorsHelperWin() = default; +MetricEvaluatorsHelperWin::~MetricEvaluatorsHelperWin() = default; + +base::Optional<int> MetricEvaluatorsHelperWin::GetFreePhysicalMemoryMb() { + MEMORYSTATUSEX mem_status; + mem_status.dwLength = sizeof(mem_status); + if (!::GlobalMemoryStatusEx(&mem_status)) + return base::nullopt; + + return (mem_status.ullAvailPhys / kMBBytes); +} + +} // namespace performance_monitor
diff --git a/chrome/browser/performance_monitor/metric_evaluator_helper_win.h b/chrome/browser/performance_monitor/metric_evaluator_helper_win.h new file mode 100644 index 0000000..2a7d53c --- /dev/null +++ b/chrome/browser/performance_monitor/metric_evaluator_helper_win.h
@@ -0,0 +1,26 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_PERFORMANCE_MONITOR_METRIC_EVALUATOR_HELPER_WIN_H_ +#define CHROME_BROWSER_PERFORMANCE_MONITOR_METRIC_EVALUATOR_HELPER_WIN_H_ + +#include "chrome/browser/performance_monitor/system_monitor.h" + +namespace performance_monitor { + +class MetricEvaluatorsHelperWin : public MetricEvaluatorsHelper { + public: + MetricEvaluatorsHelperWin(); + ~MetricEvaluatorsHelperWin() override; + + // MetricEvaluatorsHelper: + base::Optional<int> GetFreePhysicalMemoryMb() override; + + private: + DISALLOW_COPY_AND_ASSIGN(MetricEvaluatorsHelperWin); +}; + +} // namespace performance_monitor + +#endif // CHROME_BROWSER_PERFORMANCE_MONITOR_METRIC_EVALUATOR_HELPER_WIN_H_
diff --git a/chrome/browser/performance_monitor/metric_evaluator_helper_win_unittest.cc b/chrome/browser/performance_monitor/metric_evaluator_helper_win_unittest.cc new file mode 100644 index 0000000..d01f9077 --- /dev/null +++ b/chrome/browser/performance_monitor/metric_evaluator_helper_win_unittest.cc
@@ -0,0 +1,20 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/performance_monitor/metric_evaluator_helper_win.h" + +#include "testing/gtest/include/gtest/gtest.h" + +namespace performance_monitor { + +using MetricEvaluatorsHelperWinTest = testing::Test; + +TEST_F(MetricEvaluatorsHelperWinTest, GetFreeMemory) { + MetricEvaluatorsHelperWin metric_evaluator_helper; + auto value = metric_evaluator_helper.GetFreePhysicalMemoryMb(); + EXPECT_TRUE(value); + EXPECT_GT(value.value(), 0); +} + +} // namespace performance_monitor
diff --git a/chrome/browser/performance_monitor/system_monitor.cc b/chrome/browser/performance_monitor/system_monitor.cc index 8832f44..11d4291 100644 --- a/chrome/browser/performance_monitor/system_monitor.cc +++ b/chrome/browser/performance_monitor/system_monitor.cc
@@ -13,9 +13,9 @@ #include "build/build_config.h" #if defined(OS_WIN) -#include "chrome/browser/performance_monitor/system_monitor_helper_win.h" +#include "chrome/browser/performance_monitor/metric_evaluator_helper_win.h" #elif defined(OS_POSIX) -#include "chrome/browser/performance_monitor/system_monitor_helper_posix.h" +#include "chrome/browser/performance_monitor/metric_evaluator_helper_posix.h" #endif namespace performance_monitor { @@ -28,14 +28,31 @@ // The global instance. SystemMonitor* g_system_metrics_monitor = nullptr; +// The default interval at which the metrics are refreshed. +constexpr base::TimeDelta kDefaultRefreshInterval = + base::TimeDelta::FromSeconds(2); + +std::unique_ptr<MetricEvaluatorsHelper> CreateMetricEvaluatorsHelper() { +#if defined(OS_WIN) + MetricEvaluatorsHelper* helper = new MetricEvaluatorsHelperWin(); +#elif defined(OS_POSIX) + MetricEvaluatorsHelper* helper = new MetricEvaluatorsHelperPosix(); +#else +#error Unsupported platform +#endif + return base::WrapUnique(helper); +} + } // namespace -SystemMonitor::SystemMonitor(std::unique_ptr<SystemMonitorHelper> helper) +SystemMonitor::SystemMonitor(std::unique_ptr<MetricEvaluatorsHelper> helper) : blocking_task_runner_(base::CreateSequencedTaskRunnerWithTraits( {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})), - async_helper_(helper.release(), - base::OnTaskRunnerDeleter(blocking_task_runner_)), + metric_evaluators_helper_( + helper.release(), + base::OnTaskRunnerDeleter(blocking_task_runner_)), + metric_evaluators_metadata_(CreateMetricMetadataArray()), weak_factory_(this) { DCHECK(!g_system_metrics_monitor); g_system_metrics_monitor = this; @@ -49,16 +66,7 @@ // static std::unique_ptr<SystemMonitor> SystemMonitor::Create() { DCHECK(!g_system_metrics_monitor); -#if defined(OS_WIN) - SystemMonitor* monitor = - new SystemMonitor(base::WrapUnique(new win::SystemMonitorHelperWin())); -#elif defined(OS_POSIX) - SystemMonitor* monitor = - new SystemMonitor(base::WrapUnique(new SystemMonitorHelperPosix())); -#else -#error Unsupported platform -#endif - return base::WrapUnique(monitor); + return base::WrapUnique(new SystemMonitor(CreateMetricEvaluatorsHelper())); } // static @@ -78,68 +86,91 @@ if (!observers_.HasObserver(observer)) observers_.AddObserver(observer); observer_metrics_[observer] = std::move(metrics_and_frequencies); - UpdateObservedMetricsSet(); + UpdateObservedMetrics(); } void SystemMonitor::RemoveObserver(SystemMonitor::SystemObserver* observer) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); observers_.RemoveObserver(observer); observer_metrics_.erase(observer); - UpdateObservedMetricsSet(); + UpdateObservedMetrics(); } -SystemMonitor::MetricsRefresh::MetricsRefresh() = default; -SystemMonitor::MetricsRefresh::MetricsRefresh(MetricsRefresh&&) = default; - -void SystemMonitor::UpdateObservedMetricsSet() { +SystemMonitor::MetricVector SystemMonitor::GetMetricsToEvaluate() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - // Reset the current metric frequencies. - metrics_refresh_frequencies_ = MetricRefreshFrequencies(); + SystemMonitor::MetricVector metrics_to_evaluate; + for (size_t i = 0; i < metrics_refresh_frequencies_.size(); ++i) { + if (metrics_refresh_frequencies_[i] == SamplingFrequency::kNoSampling) + continue; + metrics_to_evaluate.emplace_back( + metric_evaluators_metadata_[i].create_metric_evaluator_function( + metric_evaluators_helper_.get())); + } + return metrics_to_evaluate; +} + +// static +SystemMonitor::MetricVector SystemMonitor::EvaluateMetrics( + SystemMonitor::MetricVector metrics_to_evaluate) { + for (auto& metric : metrics_to_evaluate) + metric->Evaluate(); + + return metrics_to_evaluate; +} + +SystemMonitor::MetricMetadataArray SystemMonitor::CreateMetricMetadataArray() { +#define CREATE_METRIC_METADATA(metric_type, metric_value_type, \ + helper_function, notify_function, \ + metric_freq_field) \ + MetricMetadata( \ + [](MetricEvaluatorsHelper* helper) { \ + std::unique_ptr<MetricEvaluator> metric = \ + base::WrapUnique(new MetricEvaluatorImpl<metric_value_type>( \ + MetricEvaluator::Type::metric_type, \ + base::BindOnce(&MetricEvaluatorsHelper::helper_function, \ + base::Unretained(helper)), \ + &SystemObserver::notify_function)); \ + return metric; \ + }, \ + [](const SystemObserver::MetricRefreshFrequencies& \ + metric_refresh_frequencies) { \ + return metric_refresh_frequencies.metric_freq_field; \ + }) + return { + // kFreeMemoryMb: + CREATE_METRIC_METADATA(kFreeMemoryMb, int, GetFreePhysicalMemoryMb, + OnFreePhysicalMemoryMbSample, + free_phys_memory_mb_frequency), + }; +#undef CREATE_METRIC_METADATA +} // namespace performance_monitor + +void SystemMonitor::UpdateObservedMetrics() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + base::TimeDelta refresh_interval = base::TimeDelta::Max(); // Iterates over the |observer_metrics_| list to find the highest refresh // frequency for each metric. - for (const auto& iter : observer_metrics_) { - metrics_refresh_frequencies_.free_phys_memory_mb_frequency = - std::max(metrics_refresh_frequencies_.free_phys_memory_mb_frequency, - iter.second.free_phys_memory_mb_frequency); + for (size_t i = 0; i < metrics_refresh_frequencies_.size(); ++i) { + metrics_refresh_frequencies_[i] = SamplingFrequency::kNoSampling; + for (const auto& obs_iter : observer_metrics_) { + metrics_refresh_frequencies_[i] = std::max( + metrics_refresh_frequencies_[i], + metric_evaluators_metadata_[i].get_refresh_frequency_field_function( + obs_iter.second)); + } + if (metrics_refresh_frequencies_[i] != SamplingFrequency::kNoSampling) + refresh_interval = kDefaultRefreshInterval; } - // Check if there's still some metrics being tracked. - bool should_refresh_metrics = - (metrics_refresh_frequencies_.free_phys_memory_mb_frequency > - SamplingFrequency::kNoSampling); - - if (should_refresh_metrics) { - base::TimeDelta refresh_frequency = - async_helper_->GetRefreshInterval(metrics_refresh_frequencies_); - if (!refresh_timer_.IsRunning() || - refresh_frequency != refresh_timer_.GetCurrentDelay()) { - refresh_timer_.Start(FROM_HERE, refresh_frequency, - base::BindRepeating(&SystemMonitor::RefreshCallback, - base::Unretained(this))); - } - // Sanity check. - DCHECK_EQ(refresh_timer_.GetCurrentDelay(), refresh_frequency); - } else { + if (refresh_interval.is_max()) { refresh_timer_.Stop(); - } - - // Start or stop the timer if needed. - if (refresh_timer_.IsRunning() && !should_refresh_metrics) { - refresh_timer_.Stop(); - } else if (should_refresh_metrics) { - base::TimeDelta refresh_frequency = - async_helper_->GetRefreshInterval(metrics_refresh_frequencies_); - // Stop the timer if the refresh frequency has changed. - if (refresh_timer_.IsRunning() && - refresh_frequency != refresh_timer_.GetCurrentDelay()) { - refresh_timer_.Stop(); - } - if (!refresh_timer_.IsRunning()) { - refresh_timer_.Start(FROM_HERE, refresh_frequency, - base::BindRepeating(&SystemMonitor::RefreshCallback, - base::Unretained(this))); - } + } else if (!refresh_timer_.IsRunning() || + refresh_interval != refresh_timer_.GetCurrentDelay()) { + refresh_timer_.Start(FROM_HERE, refresh_interval, + base::BindRepeating(&SystemMonitor::RefreshCallback, + base::Unretained(this))); } } @@ -147,9 +178,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); base::PostTaskAndReplyWithResult( blocking_task_runner_.get(), FROM_HERE, - base::BindOnce(&SystemMonitorHelper::RefreshMetrics, - base::Unretained(async_helper_.get()), - metrics_refresh_frequencies_, base::TimeTicks::Now()), + base::BindOnce(&SystemMonitor::EvaluateMetrics, GetMetricsToEvaluate()), base::BindOnce(&SystemMonitor::NotifyObservers, weak_factory_.GetWeakPtr())); @@ -158,22 +187,60 @@ base::Unretained(this))); } -void SystemMonitor::NotifyObservers(const MetricsRefresh& metrics) { +void SystemMonitor::NotifyObservers(SystemMonitor::MetricVector metrics) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK_NE(SamplingFrequency::kNoSampling, - metrics.free_phys_memory_mb.refresh_reason); // Iterate over the observers and notify them if a metric has been refreshed // at the requested frequency. - for (auto& observer : observers_) { - const auto& iter = observer_metrics_.find(&observer); - DCHECK(iter != observer_metrics_.end()); - if (metrics.free_phys_memory_mb.refresh_reason <= - iter->second.free_phys_memory_mb_frequency) { - iter->first->OnFreePhysicalMemoryMbSample( - metrics.free_phys_memory_mb.metric_value); + for (const auto& metric : metrics) { + if (!metric->has_value()) + continue; + for (auto& observer : observers_) { + const auto& iter = observer_metrics_.find(&observer); + DCHECK(iter != observer_metrics_.end()); + if (metric_evaluators_metadata_[static_cast<size_t>(metric->type())] + .get_refresh_frequency_field_function(iter->second) != + SystemMonitor::SamplingFrequency::kNoSampling) { + metric->NotifyObserver(iter->first); + } } } } +SystemMonitor::MetricEvaluator::MetricEvaluator(Type type) : type_(type) {} +SystemMonitor::MetricEvaluator::~MetricEvaluator() = default; + +template <typename T> +SystemMonitor::MetricEvaluatorImpl<T>::MetricEvaluatorImpl( + Type type, + base::OnceCallback<base::Optional<T>()> evaluate_function, + void (SystemObserver::*notify_function)(T)) + : MetricEvaluator(type), + evaluate_function_(std::move(evaluate_function)), + notify_function_(notify_function) {} + +template <typename T> +SystemMonitor::MetricEvaluatorImpl<T>::~MetricEvaluatorImpl() = default; + +SystemMonitor::MetricMetadata::MetricMetadata( + std::unique_ptr<MetricEvaluator> (*create_function)( + MetricEvaluatorsHelper* helper), + SamplingFrequency (*get_refresh_field_function)( + const SystemMonitor::SystemObserver::MetricRefreshFrequencies&)) + : create_metric_evaluator_function(create_function), + get_refresh_frequency_field_function(get_refresh_field_function) {} + +template <typename T> +void SystemMonitor::MetricEvaluatorImpl<T>::NotifyObserver( + SystemObserver* observer) { + DCHECK(value()); + (observer->*notify_function_)(value().value()); +} + +template <typename T> +void SystemMonitor::MetricEvaluatorImpl<T>::Evaluate() { + DCHECK(evaluate_function_); + value_ = std::move(evaluate_function_).Run(); +} + } // namespace performance_monitor
diff --git a/chrome/browser/performance_monitor/system_monitor.h b/chrome/browser/performance_monitor/system_monitor.h index 6594bc02..3113588 100644 --- a/chrome/browser/performance_monitor/system_monitor.h +++ b/chrome/browser/performance_monitor/system_monitor.h
@@ -5,11 +5,14 @@ #ifndef CHROME_BROWSER_PERFORMANCE_MONITOR_SYSTEM_MONITOR_H_ #define CHROME_BROWSER_PERFORMANCE_MONITOR_SYSTEM_MONITOR_H_ +#include <array> #include <memory> +#include <vector> #include "base/containers/flat_map.h" #include "base/macros.h" #include "base/observer_list.h" +#include "base/optional.h" #include "base/sequence_checker.h" #include "base/task/post_task.h" #include "base/time/time.h" @@ -17,7 +20,7 @@ namespace performance_monitor { -class SystemMonitorHelper; +class MetricEvaluatorsHelper; // Monitors various various system metrics such as free memory, disk idle time, // etc. @@ -30,8 +33,7 @@ // metrics and frequencies can then be updated at runtime. // // Platforms that want to use this class need to provide a platform specific -// implementation of the SystemMonitorHelper class and update -// SystemMonitor::Create. +// implementation of the MetricEvaluatorHelper class. class SystemMonitor { public: // The frequency at which a metric will be collected. Exact frequencies are @@ -39,8 +41,8 @@ // // NOTE: Frequencies must be listed in increasing order in this enum. enum class SamplingFrequency : uint32_t { - kNoSampling = 0, - kDefaultFrequency = 1, + kNoSampling, + kDefaultFrequency, }; virtual ~SystemMonitor(); @@ -87,52 +89,141 @@ // will not receive notifications for any metric. void RemoveObserver(SystemObserver* observer); - const SystemObserver::MetricRefreshFrequencies& - metric_refresh_frequencies_for_testing() const { - return metrics_refresh_frequencies_; - } - - bool IsRefreshTimerRunningForTesting() { return refresh_timer_.IsRunning(); } - - void SetHelperForTesting(std::unique_ptr<SystemMonitorHelper> helper) { - async_helper_.reset(helper.release()); + const base::OneShotTimer& refresh_timer_for_testing() { + return refresh_timer_; } protected: - friend class SystemMonitorHelper; + friend class SystemMonitorTest; - // Creates SystemMonitor. Only one SystemMonitor instance per - // application is allowed. - explicit SystemMonitor(std::unique_ptr<SystemMonitorHelper> helper); + // Represents a metric. Overridden for each metric tracked by this monitor. + class MetricEvaluator { + public: + enum class Type : size_t { + kFreeMemoryMb, + kMax, + }; - // A struct that stores a refreshed metric and the reason why it has been - // refreshed. + explicit MetricEvaluator(Type type); + virtual ~MetricEvaluator(); + + // Called when the metric needs to be evaluated. + virtual void Evaluate() = 0; + + // Notify |observer| that a value is available, should only be called after + // Evaluate(). + virtual void NotifyObserver(SystemObserver* observer) = 0; + + // Returns the metric type. + Type type() const { return type_; } + + // Indicates if the metric has a valid value. + virtual bool has_value() const = 0; + + private: + const Type type_; + + DISALLOW_COPY_AND_ASSIGN(MetricEvaluator); + }; + + // Templated implementation of the MetricEvaluator interface. template <typename T> - struct MetricAndRefreshReason { - MetricAndRefreshReason() {} - MetricAndRefreshReason(T value, SamplingFrequency reason) - : metric_value(value), refresh_reason(reason) {} - T metric_value = {}; - SamplingFrequency refresh_reason = SamplingFrequency::kNoSampling; + class MetricEvaluatorImpl : public MetricEvaluator { + public: + MetricEvaluatorImpl<T>( + Type type, + base::OnceCallback<base::Optional<T>()> evaluate_function, + void (SystemObserver::*notify_function)(T)); + virtual ~MetricEvaluatorImpl(); + + // Called when the metrics needs to be refreshed. + void Evaluate() override; + + bool has_value() const override { return value_.has_value(); } + + base::Optional<T> value() { return value_; } + + void set_value_for_testing(T value) { value_ = value; } + + private: + void NotifyObserver(SystemObserver* observer) override; + + // The callback that should be run to evaluate the metric value. + base::OnceCallback<base::Optional<T>()> evaluate_function_; + + // A function pointer to the SystemObserver function that should be called + // to notify of a value refresh. + void (SystemObserver::*notify_function_)(T); + + // The value, initialized in |Evaluate|. + base::Optional<T> value_; + + DISALLOW_COPY_AND_ASSIGN(MetricEvaluatorImpl); }; - // Struct that will receive the refreshed metrics in the refresh callback. - struct MetricsRefresh { - MetricsRefresh(); - MetricsRefresh(MetricsRefresh&& o); - MetricAndRefreshReason<int> free_phys_memory_mb; + // Structure storing all the functions specific to a metric. + struct MetricMetadata { + MetricMetadata() = delete; + MetricMetadata(std::unique_ptr<MetricEvaluator> (*create_function)( + MetricEvaluatorsHelper* helper), + SamplingFrequency (*get_refresh_field_function)( + const SystemObserver::MetricRefreshFrequencies&)); + // A pointer to the function that creates the appropriate |MetricEvaluator| + // instance for a given metric. + std::unique_ptr<MetricEvaluator> (*const create_metric_evaluator_function)( + MetricEvaluatorsHelper* helper); + // A pointer to the function that extract the sampling frequency for a given + // metric from a MetricRefreshFrequencies struct. + SamplingFrequency (*get_refresh_frequency_field_function)( + const SystemObserver::MetricRefreshFrequencies&); }; + using MetricVector = std::vector<std::unique_ptr<MetricEvaluator>>; + using MetricSamplingFrequencyArray = + std::array<SamplingFrequency, + static_cast<size_t>(MetricEvaluator::Type::kMax)>; + + // Creates SystemMonitor. Only one SystemMonitor instance per application is + // allowed. + explicit SystemMonitor(std::unique_ptr<MetricEvaluatorsHelper> helper); + + // Returns a vector with all the metrics that should be evaluated given the + // current list of observers. + SystemMonitor::MetricVector GetMetricsToEvaluate() const; + + const MetricSamplingFrequencyArray& + GetMetricSamplingFrequencyArrayForTesting() { + return metrics_refresh_frequencies_; + } + + MetricMetadata* GetMetricEvaluatorMetadataForTesting( + MetricEvaluator::Type type) { + DCHECK_LT(static_cast<size_t>(type), metric_evaluators_metadata_.size()); + return const_cast<MetricMetadata*>( + &metric_evaluators_metadata_[static_cast<size_t>(type)]); + } + private: + using MetricMetadataArray = + const std::array<const MetricMetadata, + static_cast<size_t>(MetricEvaluator::Type::kMax)>; + // Evaluate the metrics in |metric_vector|. + static SystemMonitor::MetricVector EvaluateMetrics( + MetricVector metric_vector); + + // Create the array of MetricMetadata used to initialize + // |metric_evaluators_metadata_|. + static MetricMetadataArray CreateMetricMetadataArray(); + // Updates |observed_metrics_| with the list of metrics that need to be - // tracked. - void UpdateObservedMetricsSet(); + // tracked. Starts or stop |refresh_timer_| if needed. + void UpdateObservedMetrics(); // Function that gets called by every time the refresh callback triggers. void RefreshCallback(); // Notify the observers with the refreshed metrics. - void NotifyObservers(const MetricsRefresh& metrics); + void NotifyObservers(SystemMonitor::MetricVector metrics); // The list of observers. base::ObserverList<SystemObserver> observers_; @@ -142,7 +233,7 @@ // The current metrics that are being observed and the corresponding refresh // frequency. - SystemObserver::MetricRefreshFrequencies metrics_refresh_frequencies_; + MetricSamplingFrequencyArray metrics_refresh_frequencies_ = {}; // The timer responsible of refreshing the metrics and notifying the // observers. @@ -151,9 +242,14 @@ // The task runner used to run all the blocking operations. const scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_; - // The SystemMonitorHelper instance responsible for running all asynchronous - // operations. - std::unique_ptr<SystemMonitorHelper, base::OnTaskRunnerDeleter> async_helper_; + // The MetricEvaluatorsHelper instance used by the MetricEvaluator to evaluate + // the metrics. This should only be used on |blocking_task_runner_|. + std::unique_ptr<MetricEvaluatorsHelper, base::OnTaskRunnerDeleter> + metric_evaluators_helper_; + + // There should be one |MetricMetadata| for each value of + // |MetricEvaluator::Type|. + MetricMetadataArray metric_evaluators_metadata_; SEQUENCE_CHECKER(sequence_checker_); @@ -162,39 +258,18 @@ DISALLOW_COPY_AND_ASSIGN(SystemMonitor); }; -// Helper class used to run all the blocking operations posted by SystemMonitor -// on a sequence with the |MayBlock()| trait. -// -// Instances of this class should only be destructed once all the posted tasks -// have been run, in practice it means that they should ideally be stored in a -// std::unique_ptr<AsyncHelper, base::OnTaskRunnerDeleter>. -class SystemMonitorHelper { +// An helper class used by the MetricEvaluator object to retrieve the info +// they need. +class MetricEvaluatorsHelper { public: - using MetricsRefresh = SystemMonitor::MetricsRefresh; - template <typename T> - using MetricAndRefreshReason = SystemMonitor::MetricAndRefreshReason<T>; + MetricEvaluatorsHelper() = default; + virtual ~MetricEvaluatorsHelper() = default; - SystemMonitorHelper() = default; - virtual ~SystemMonitorHelper() = default; - - // Returns the refresh interval that should be used by the SystemMonitor - // refresh timer based on the current configuration of its observers. If no - // metrics are being observed then this returns base::TimeDelta::Max(). - // - // This can be called from any sequence. - virtual base::TimeDelta GetRefreshInterval( - const SystemMonitor::SystemObserver::MetricRefreshFrequencies& - metrics_and_frequencies) = 0; - - // Refresh the metrics according to |metrics_and_frequencies|. |refresh_time| - // indicates at which time the refresh has been requested. - virtual MetricsRefresh RefreshMetrics( - const SystemMonitor::SystemObserver::MetricRefreshFrequencies - metrics_and_frequencies, - const base::TimeTicks& refresh_time) = 0; + // Returns the free physical memory, in megabytes. + virtual base::Optional<int> GetFreePhysicalMemoryMb() = 0; private: - DISALLOW_COPY_AND_ASSIGN(SystemMonitorHelper); + DISALLOW_COPY_AND_ASSIGN(MetricEvaluatorsHelper); }; } // namespace performance_monitor
diff --git a/chrome/browser/performance_monitor/system_monitor_helper_posix.cc b/chrome/browser/performance_monitor/system_monitor_helper_posix.cc deleted file mode 100644 index 12df731..0000000 --- a/chrome/browser/performance_monitor/system_monitor_helper_posix.cc +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/performance_monitor/system_monitor_helper_posix.h" - -namespace performance_monitor { - -base::TimeDelta SystemMonitorHelperPosix::GetRefreshInterval( - const SystemMonitor::SystemObserver::MetricRefreshFrequencies& - metrics_and_frequencies) { - NOTIMPLEMENTED(); - return base::TimeDelta::Max(); -} - -SystemMonitorHelper::MetricsRefresh SystemMonitorHelperPosix::RefreshMetrics( - const SystemMonitor::SystemObserver::MetricRefreshFrequencies - metrics_and_frequencies, - const base::TimeTicks& refresh_time) { - NOTIMPLEMENTED(); - return {}; -} - -} // namespace performance_monitor
diff --git a/chrome/browser/performance_monitor/system_monitor_helper_posix.h b/chrome/browser/performance_monitor/system_monitor_helper_posix.h deleted file mode 100644 index f8bf83b..0000000 --- a/chrome/browser/performance_monitor/system_monitor_helper_posix.h +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_PERFORMANCE_MONITOR_SYSTEM_MONITOR_HELPER_POSIX_H_ -#define CHROME_BROWSER_PERFORMANCE_MONITOR_SYSTEM_MONITOR_HELPER_POSIX_H_ - -#include "chrome/browser/performance_monitor/system_monitor.h" - -namespace performance_monitor { - -// Posix implementation of the SystemMonitorHelper class. Do not use -// this directly, instead access the system metrics via the SystemMonitor -// interface. -class SystemMonitorHelperPosix : public SystemMonitorHelper { - public: - ~SystemMonitorHelperPosix() override = default; - - protected: - friend class ::performance_monitor::SystemMonitor; - - // Protected constructor so this can only be created by SystemMonitor. - SystemMonitorHelperPosix() = default; - - // SystemMonitorHelper: - base::TimeDelta GetRefreshInterval( - const SystemMonitor::SystemObserver::MetricRefreshFrequencies& - metrics_and_frequencies) override; - MetricsRefresh RefreshMetrics( - const SystemMonitor::SystemObserver::MetricRefreshFrequencies - metrics_and_frequencies, - const base::TimeTicks& refresh_time) override; - - private: - DISALLOW_COPY_AND_ASSIGN(SystemMonitorHelperPosix); -}; - -} // namespace performance_monitor - -#endif // CHROME_BROWSER_PERFORMANCE_MONITOR_SYSTEM_MONITOR_HELPER_POSIX_H_
diff --git a/chrome/browser/performance_monitor/system_monitor_helper_win.cc b/chrome/browser/performance_monitor/system_monitor_helper_win.cc deleted file mode 100644 index 2974d42..0000000 --- a/chrome/browser/performance_monitor/system_monitor_helper_win.cc +++ /dev/null
@@ -1,70 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/performance_monitor/system_monitor_helper_win.h" - -#include <windows.h> - -namespace performance_monitor { -namespace win { - -namespace { - -// The refresh period of the free physical memory metric when being tracked at -// the regular frequency. -constexpr base::TimeDelta kRefreshIntervalPhysMemoryMbRegFreq = - base::TimeDelta::FromSeconds(2); - -const DWORDLONG kMBBytes = 1024 * 1024; - -// Returns the amount of physical memory available on the system. -base::Optional<int> GetFreePhysMemoryMb() { - MEMORYSTATUSEX mem_status; - mem_status.dwLength = sizeof(mem_status); - if (!::GlobalMemoryStatusEx(&mem_status)) - return base::nullopt; - - return (mem_status.ullAvailPhys / kMBBytes); -} - -} // namespace - -SystemMonitorHelperWin::SystemMonitorHelperWin() { - DETACH_FROM_SEQUENCE(sequence_checker_); -} - -base::TimeDelta SystemMonitorHelperWin::GetRefreshInterval( - const SystemMonitor::SystemObserver::MetricRefreshFrequencies& - metrics_and_frequencies) { - if (metrics_and_frequencies.free_phys_memory_mb_frequency == - SystemMonitor::SamplingFrequency::kDefaultFrequency) { - return kRefreshIntervalPhysMemoryMbRegFreq; - } - return base::TimeDelta::Max(); -} - -SystemMonitorHelperWin::MetricsRefresh SystemMonitorHelperWin::RefreshMetrics( - const SystemMonitor::SystemObserver::MetricRefreshFrequencies - metrics_and_frequencies, - const base::TimeTicks& refresh_time) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - SystemMonitorHelper::MetricsRefresh metrics; - - if ((refresh_time - last_phys_memory_refresh_default_freq_) >= - kRefreshIntervalPhysMemoryMbRegFreq) { - last_phys_memory_refresh_default_freq_ = refresh_time; - auto free_phys_memory = GetFreePhysMemoryMb(); - if (free_phys_memory) { - metrics.free_phys_memory_mb = - SystemMonitorHelper::MetricAndRefreshReason<int>( - free_phys_memory.value(), - SystemMonitor::SamplingFrequency::kDefaultFrequency); - } - } - - return metrics; -} - -} // namespace win -} // namespace performance_monitor
diff --git a/chrome/browser/performance_monitor/system_monitor_helper_win.h b/chrome/browser/performance_monitor/system_monitor_helper_win.h deleted file mode 100644 index 7bf1250b..0000000 --- a/chrome/browser/performance_monitor/system_monitor_helper_win.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_PERFORMANCE_MONITOR_SYSTEM_MONITOR_HELPER_WIN_H_ -#define CHROME_BROWSER_PERFORMANCE_MONITOR_SYSTEM_MONITOR_HELPER_WIN_H_ - -#include "base/macros.h" -#include "base/sequence_checker.h" -#include "chrome/browser/performance_monitor/system_monitor.h" - -namespace performance_monitor { -namespace win { - -// Windows specific implementation of the SystemMonitorHelper class. Do not use -// this directly, instead access the system metrics via the SystemMonitor -// interface. -class SystemMonitorHelperWin : public SystemMonitorHelper { - public: - ~SystemMonitorHelperWin() override = default; - - protected: - friend class ::performance_monitor::SystemMonitor; - friend class SystemMonitorHelperWinTest; - - // Protected constructor so this can only be created by SystemMonitor. - SystemMonitorHelperWin(); - - // SystemMonitorHelperWin: - base::TimeDelta GetRefreshInterval( - const SystemMonitor::SystemObserver::MetricRefreshFrequencies& - metrics_and_frequencies) override; - MetricsRefresh RefreshMetrics( - const SystemMonitor::SystemObserver::MetricRefreshFrequencies - metrics_and_frequencies, - const base::TimeTicks& refresh_time) override; - - private: - // The last time the free physical memory value has been refreshed at the - // default frequency. - base::TimeTicks last_phys_memory_refresh_default_freq_; - - SEQUENCE_CHECKER(sequence_checker_); - - DISALLOW_COPY_AND_ASSIGN(SystemMonitorHelperWin); -}; - -} // namespace win -} // namespace performance_monitor - -#endif // CHROME_BROWSER_PERFORMANCE_MONITOR_SYSTEM_MONITOR_HELPER_WIN_H_
diff --git a/chrome/browser/performance_monitor/system_monitor_helper_win_unittest.cc b/chrome/browser/performance_monitor/system_monitor_helper_win_unittest.cc deleted file mode 100644 index 9b9f892..0000000 --- a/chrome/browser/performance_monitor/system_monitor_helper_win_unittest.cc +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/performance_monitor/system_monitor_helper_win.h" - -#include "testing/gtest/include/gtest/gtest.h" - -namespace performance_monitor { -namespace win { - -namespace { - -class TestSystemMonitorHelperWin : public SystemMonitorHelperWin { - public: - TestSystemMonitorHelperWin() = default; - ~TestSystemMonitorHelperWin() override = default; - - using SystemMonitorHelperWin::RefreshMetrics; - - private: - DISALLOW_COPY_AND_ASSIGN(TestSystemMonitorHelperWin); -}; - -using SystemMonitorHelperWinTest = testing::Test; - -TEST_F(SystemMonitorHelperWinTest, GetFreeMemory) { - TestSystemMonitorHelperWin helper; - auto refreshed_metrics = helper.RefreshMetrics( - {.free_phys_memory_mb_frequency = - SystemMonitor::SamplingFrequency::kDefaultFrequency}, - base::TimeTicks::Now()); - EXPECT_GT(refreshed_metrics.free_phys_memory_mb.metric_value, 0); -} - -} // namespace - -} // namespace win -} // namespace performance_monitor
diff --git a/chrome/browser/performance_monitor/system_monitor_unittest.cc b/chrome/browser/performance_monitor/system_monitor_unittest.cc index bb3c5be..3da0433 100644 --- a/chrome/browser/performance_monitor/system_monitor_unittest.cc +++ b/chrome/browser/performance_monitor/system_monitor_unittest.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/performance_monitor/system_monitor.h" +#include "base/memory/ptr_util.h" #include "base/test/scoped_task_environment.h" #include "base/time/time.h" #include "testing/gmock/include/gmock/gmock.h" @@ -13,16 +14,11 @@ namespace { +using SamplingFrequency = SystemMonitor::SamplingFrequency; using SystemObserver = SystemMonitor::SystemObserver; using MetricsRefreshFrequencies = SystemObserver::MetricRefreshFrequencies; -constexpr base::TimeDelta kRefreshInterval = base::TimeDelta::FromSeconds(1); - -bool operator==(const MetricsRefreshFrequencies& lhs, - const MetricsRefreshFrequencies& rhs) { - return std::tie(lhs.free_phys_memory_mb_frequency) == - std::tie(rhs.free_phys_memory_mb_frequency); -} +const int kFakeFreePhysMemoryMb = 42; class MockMetricsMonitorObserver : public SystemObserver { public: @@ -30,40 +26,45 @@ MOCK_METHOD1(OnFreePhysicalMemoryMbSample, void(int free_phys_memory_mb)); }; -class TestSystemMonitorHelper : public SystemMonitorHelper { +// Test version of a MetricEvaluatorsHelper that returns constant values. +class TestMetricEvaluatorsHelper : public MetricEvaluatorsHelper { public: - TestSystemMonitorHelper() = default; - ~TestSystemMonitorHelper() override = default; + TestMetricEvaluatorsHelper() = default; + ~TestMetricEvaluatorsHelper() override = default; - protected: - // SystemMonitorHelper: - base::TimeDelta GetRefreshInterval( - const SystemMonitor::SystemObserver::MetricRefreshFrequencies& - metrics_and_frequencies) override { - return kRefreshInterval; - } - MetricsRefresh RefreshMetrics( - const SystemMonitor::SystemObserver::MetricRefreshFrequencies - metrics_and_frequencies, - const base::TimeTicks& refresh_time) override { - SystemMonitorHelper::MetricsRefresh metrics; - metrics.free_phys_memory_mb = - SystemMonitorHelper::MetricAndRefreshReason<int>( - 42, SystemMonitor::SamplingFrequency::kDefaultFrequency); - return metrics; + base::Optional<int> GetFreePhysicalMemoryMb() override { + return kFakeFreePhysMemoryMb; } private: - DISALLOW_COPY_AND_ASSIGN(TestSystemMonitorHelper); + DISALLOW_COPY_AND_ASSIGN(TestMetricEvaluatorsHelper); }; +} // namespace + class SystemMonitorTest : public testing::Test { protected: SystemMonitorTest() : scoped_task_environment_( - base::test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME) { + base::test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME) {} + + void SetUp() override { EXPECT_EQ(nullptr, SystemMonitor::Get()); - system_monitor_ = SystemMonitor::Create(); + system_monitor_ = base::WrapUnique( + new SystemMonitor(std::make_unique<TestMetricEvaluatorsHelper>())); + } + + void TearDown() override { system_monitor_.reset(); } + + void EnsureMetricsAreObservedAtExpectedFrequency( + SamplingFrequency expected_free_memory_mb_freq) { + const auto& observed_metrics_and_frequencies = + system_monitor_->GetMetricSamplingFrequencyArrayForTesting(); + + EXPECT_EQ(1U, observed_metrics_and_frequencies.size()); + EXPECT_EQ(expected_free_memory_mb_freq, + observed_metrics_and_frequencies[static_cast<size_t>( + SystemMonitor::MetricEvaluator::Type::kFreeMemoryMb)]); } std::unique_ptr<SystemMonitor> system_monitor_; @@ -88,85 +89,56 @@ // The first observer doesn't observe anything yet. MetricsRefreshFrequencies obs1_metrics_frequencies = {}; system_monitor_->AddOrUpdateObserver(&obs1, obs1_metrics_frequencies); - MetricsRefreshFrequencies expected_metrics_frequencies = - obs1_metrics_frequencies; - auto observed_metrics_and_frequencies = - system_monitor_->metric_refresh_frequencies_for_testing(); - EXPECT_TRUE(observed_metrics_and_frequencies == expected_metrics_frequencies); + EnsureMetricsAreObservedAtExpectedFrequency(SamplingFrequency::kNoSampling); // Add a second observer that observes the amount of free memory at the // default frequency. MetricsRefreshFrequencies obs2_metrics_frequencies = { - .free_phys_memory_mb_frequency = - SystemMonitor::SamplingFrequency::kDefaultFrequency}; + .free_phys_memory_mb_frequency = SamplingFrequency::kDefaultFrequency}; system_monitor_->AddOrUpdateObserver(&obs2, obs2_metrics_frequencies); - expected_metrics_frequencies.free_phys_memory_mb_frequency = - SystemMonitor::SamplingFrequency::kDefaultFrequency; - observed_metrics_and_frequencies = - system_monitor_->metric_refresh_frequencies_for_testing(); - EXPECT_TRUE(observed_metrics_and_frequencies == expected_metrics_frequencies); + EnsureMetricsAreObservedAtExpectedFrequency( + SamplingFrequency::kDefaultFrequency); + + // Add a third observer that also observes the amount of free memory at the + // default frequency. + MetricsRefreshFrequencies obs3_metrics_frequencies = { + .free_phys_memory_mb_frequency = SamplingFrequency::kDefaultFrequency}; + system_monitor_->AddOrUpdateObserver(&obs3, obs3_metrics_frequencies); + EnsureMetricsAreObservedAtExpectedFrequency( + SamplingFrequency::kDefaultFrequency); // Stop observing any metric with the second observer. obs2_metrics_frequencies.free_phys_memory_mb_frequency = - SystemMonitor::SamplingFrequency::kNoSampling; + SamplingFrequency::kNoSampling; system_monitor_->AddOrUpdateObserver(&obs2, obs2_metrics_frequencies); - expected_metrics_frequencies.free_phys_memory_mb_frequency = - SystemMonitor::SamplingFrequency::kNoSampling; - observed_metrics_and_frequencies = - system_monitor_->metric_refresh_frequencies_for_testing(); - EXPECT_TRUE(observed_metrics_and_frequencies == expected_metrics_frequencies); + EnsureMetricsAreObservedAtExpectedFrequency( + SamplingFrequency::kDefaultFrequency); - // Add a second observer that observes the amount of free memory at the - // default frequency. - MetricsRefreshFrequencies obs3_metrics_frequencies = { - .free_phys_memory_mb_frequency = - SystemMonitor::SamplingFrequency::kDefaultFrequency}; - system_monitor_->AddOrUpdateObserver(&obs3, obs3_metrics_frequencies); - expected_metrics_frequencies.free_phys_memory_mb_frequency = - SystemMonitor::SamplingFrequency::kDefaultFrequency; - observed_metrics_and_frequencies = - system_monitor_->metric_refresh_frequencies_for_testing(); - EXPECT_TRUE(observed_metrics_and_frequencies == expected_metrics_frequencies); - - // Remove the third observe, ensure that no metrics are observed anymore. + // Remove the third observer, ensure that no metrics are observed anymore. system_monitor_->RemoveObserver(&obs3); - expected_metrics_frequencies.free_phys_memory_mb_frequency = - SystemMonitor::SamplingFrequency::kNoSampling; - observed_metrics_and_frequencies = - system_monitor_->metric_refresh_frequencies_for_testing(); - EXPECT_TRUE(observed_metrics_and_frequencies == expected_metrics_frequencies); + EnsureMetricsAreObservedAtExpectedFrequency(SamplingFrequency::kNoSampling); } TEST_F(SystemMonitorTest, ObserverGetsCalled) { - system_monitor_->SetHelperForTesting( - std::make_unique<TestSystemMonitorHelper>()); - - ::testing::StrictMock<MockMetricsMonitorObserver> mock_observer_1; + ::testing::StrictMock<MockMetricsMonitorObserver> mock_observer; system_monitor_->AddOrUpdateObserver( - &mock_observer_1, - {.free_phys_memory_mb_frequency = - SystemMonitor::SamplingFrequency::kDefaultFrequency}); - - ::testing::StrictMock<MockMetricsMonitorObserver> mock_observer_2; - system_monitor_->AddOrUpdateObserver(&mock_observer_2, {}); + &mock_observer, + {.free_phys_memory_mb_frequency = SamplingFrequency::kDefaultFrequency}); // Ensure that we get several samples to verify that the timer logic works. - EXPECT_CALL(mock_observer_1, OnFreePhysicalMemoryMbSample(::testing::Eq(42))) + EXPECT_CALL(mock_observer, OnFreePhysicalMemoryMbSample( + ::testing::Eq(kFakeFreePhysMemoryMb))) .Times(2); - // The second observer shouldn't be called. - EXPECT_CALL(mock_observer_2, OnFreePhysicalMemoryMbSample(::testing::_)) - .Times(0); + EXPECT_TRUE(system_monitor_->refresh_timer_for_testing().IsRunning()); // Fast forward by enough time to get multiple samples and wait for the tasks // to complete. - scoped_task_environment_.FastForwardBy(2 * kRefreshInterval); + scoped_task_environment_.FastForwardBy( + 2 * system_monitor_->refresh_timer_for_testing().GetCurrentDelay()); scoped_task_environment_.RunUntilIdle(); - ::testing::Mock::VerifyAndClear(&mock_observer_1); - ::testing::Mock::VerifyAndClear(&mock_observer_2); + ::testing::Mock::VerifyAndClear(&mock_observer); } -} // namespace - } // namespace performance_monitor
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index 8f3bb0a5..3ecf56d 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -23,7 +23,6 @@ #include "chrome/browser/policy/javascript_policy_handler.h" #include "chrome/browser/policy/managed_bookmarks_policy_handler.h" #include "chrome/browser/policy/network_prediction_policy_handler.h" -#include "chrome/browser/policy/webusb_allow_devices_for_urls_policy_handler.h" #include "chrome/browser/profiles/force_safe_search_policy_handler.h" #include "chrome/browser/profiles/force_youtube_safety_mode_policy_handler.h" #include "chrome/browser/profiles/guest_mode_policy_handler.h" @@ -101,6 +100,7 @@ #include "chrome/browser/download/download_dir_policy_handler.h" #include "chrome/browser/media/router/media_router_feature.h" #include "chrome/browser/policy/local_sync_policy_handler.h" +#include "chrome/browser/policy/webusb_allow_devices_for_urls_policy_handler.h" #endif #if !defined(OS_CHROMEOS) @@ -718,6 +718,9 @@ { key::kPluginVmImage, plugin_vm::prefs::kPluginVmImage, base::Value::Type::DICTIONARY }, + { key::kVoiceInteractionContextEnabled, + arc::prefs::kVoiceInteractionContextEnabled, + base::Value::Type::BOOLEAN }, #endif // defined(OS_CHROMEOS) // Metrics reporting is controlled by a platform specific policy for ChromeOS @@ -1066,8 +1069,6 @@ SCHEMA_STRICT, SimpleSchemaValidatingPolicyHandler::RECOMMENDED_PROHIBITED, SimpleSchemaValidatingPolicyHandler::MANDATORY_ALLOWED)); - handlers->AddHandler( - std::make_unique<WebUsbAllowDevicesForUrlsPolicyHandler>(chrome_schema)); // On most platforms, there is a legacy policy // kUnsafelyTreatInsecureOriginAsSecure which has been replaced by @@ -1194,6 +1195,13 @@ chrome_schema.GetValidationSchema(), SimpleSchemaValidatingPolicyHandler::RECOMMENDED_ALLOWED, SimpleSchemaValidatingPolicyHandler::MANDATORY_ALLOWED)); + // At the moment, the WebUsbAllowDevicesForUrls policy is not supported on + // Android because the Site Settings UI is not yet capable of displaying + // policy managed USB items. + // TODO(https://crbug.com/931459): Move this statement outside of this + // preprocessor if statement once Android supports the policy. + handlers->AddHandler( + std::make_unique<WebUsbAllowDevicesForUrlsPolicyHandler>(chrome_schema)); #endif #if !defined(OS_CHROMEOS)
diff --git a/chrome/browser/policy/policy_browsertest.cc b/chrome/browser/policy/policy_browsertest.cc index ef66f50..d3421ab 100644 --- a/chrome/browser/policy/policy_browsertest.cc +++ b/chrome/browser/policy/policy_browsertest.cc
@@ -2690,7 +2690,13 @@ EXPECT_FALSE(service->IsExtensionEnabled(kGoodCrxId)); } -IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionAllowedTypes) { +#if defined(OS_LINUX) +#define MAYBE_ExtensionAllowedTypes DISABLED_ExtensionAllowedTypes +#else +#define MAYBE_ExtensionAllowedTypes ExtensionAllowedTypes +#endif +// TODO(crbug.com/934297) The test is flaky (crashing) on Linux. +IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionAllowedTypes) { // Verifies that extensions are blocked if policy specifies an allowed types // list and the extension's type is not on that list. extensions::ExtensionService* service = extension_service();
diff --git a/chrome/browser/predictors/autocomplete_action_predictor.cc b/chrome/browser/predictors/autocomplete_action_predictor.cc index aa942f42b..6a7a984 100644 --- a/chrome/browser/predictors/autocomplete_action_predictor.cc +++ b/chrome/browser/predictors/autocomplete_action_predictor.cc
@@ -6,6 +6,7 @@ #include <math.h> #include <stddef.h> +#include <queue> #include "base/bind.h" #include "base/guid.h" @@ -49,6 +50,10 @@ const int kMinimumNumberOfHits = 3; const size_t kMaximumTransitionalMatchesSize = 1024 * 1024; // 1 MB. +// As of February 2019, 99% of users on Windows have less than 2000 entries in +// the database. +const size_t kMaximumCacheSize = 2000; + enum DatabaseAction { DATABASE_ACTION_ADD, DATABASE_ACTION_UPDATE, @@ -303,6 +308,18 @@ if (rows_to_add.size() > 0 || rows_to_update.size() > 0) AddAndUpdateRows(rows_to_add, rows_to_update); + std::vector<AutocompleteActionPredictorTable::Row::Id> ids_to_delete; + if (db_cache_.size() > kMaximumCacheSize) { + DeleteLowestConfidenceRowsFromCaches(db_cache_.size() - kMaximumCacheSize, + &ids_to_delete); + } + + if (!ids_to_delete.empty() && table_.get()) { + table_->GetTaskRunner()->PostTask( + FROM_HERE, base::BindOnce(&AutocompleteActionPredictorTable::DeleteRows, + table_, std::move(ids_to_delete))); + } + ClearTransitionalMatches(); // Check against tracked urls and log accuracy for the confidence we @@ -470,9 +487,16 @@ std::vector<AutocompleteActionPredictorTable::Row::Id> ids_to_delete; DeleteOldIdsFromCaches(url_db, &ids_to_delete); - table_->GetTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&AutocompleteActionPredictorTable::DeleteRows, - table_, ids_to_delete)); + if (db_cache_.size() > kMaximumCacheSize) { + DeleteLowestConfidenceRowsFromCaches(db_cache_.size() - kMaximumCacheSize, + &ids_to_delete); + } + + if (!ids_to_delete.empty()) { + table_->GetTaskRunner()->PostTask( + FROM_HERE, base::BindOnce(&AutocompleteActionPredictorTable::DeleteRows, + table_, std::move(ids_to_delete))); + } FinishInitialization(); if (incognito_predictor_) @@ -504,6 +528,52 @@ } } +void AutocompleteActionPredictor::DeleteLowestConfidenceRowsFromCaches( + size_t count, + std::vector<AutocompleteActionPredictorTable::Row::Id>* id_list) { + CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); + DCHECK(id_list); + + auto compare_confidence = [](const DBCacheMap::iterator& lhs, + const DBCacheMap::iterator& rhs) { + const DBCacheValue& lhs_value = lhs->second; + const DBCacheValue& rhs_value = rhs->second; + // Compare by confidence scores first. In case of equality, compare by + // number of hits. + int lhs_confidence_to_compare = + lhs_value.number_of_hits * + (rhs_value.number_of_hits + rhs_value.number_of_misses); + int rhs_confidence_to_compare = + rhs_value.number_of_hits * + (lhs_value.number_of_hits + lhs_value.number_of_misses); + return std::tie(lhs_confidence_to_compare, lhs_value.number_of_hits) < + std::tie(rhs_confidence_to_compare, rhs_value.number_of_hits); + }; + // Use max heap to find |count| smallest elements in |db_cache_|. + std::priority_queue<DBCacheMap::iterator, std::vector<DBCacheMap::iterator>, + decltype(compare_confidence)> + max_heap(compare_confidence); + + for (auto it = db_cache_.begin(); it != db_cache_.end(); ++it) { + max_heap.push(it); + if (max_heap.size() > count) + max_heap.pop(); + } + + // Only iterators to the erased elements are invalidated, so it's safe to keep + // using remaining iterators. + while (!max_heap.empty()) { + auto entry_to_delete = max_heap.top(); + auto id_it = db_id_cache_.find(entry_to_delete->first); + DCHECK(id_it != db_id_cache_.end()); + + id_list->push_back(id_it->second); + db_id_cache_.erase(id_it); + db_cache_.erase(entry_to_delete); + max_heap.pop(); + } +} + void AutocompleteActionPredictor::CopyFromMainProfile() { CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); DCHECK(profile_->IsOffTheRecord());
diff --git a/chrome/browser/predictors/autocomplete_action_predictor.h b/chrome/browser/predictors/autocomplete_action_predictor.h index ab22d97..085a6677 100644 --- a/chrome/browser/predictors/autocomplete_action_predictor.h +++ b/chrome/browser/predictors/autocomplete_action_predictor.h
@@ -211,6 +211,12 @@ history::URLDatabase* url_db, std::vector<AutocompleteActionPredictorTable::Row::Id>* id_list); + // Deletes up to |count| rows having lowest confidence scores from the local + // caches. Deleted row ids will be added to |id_list|. + void DeleteLowestConfidenceRowsFromCaches( + size_t count, + std::vector<AutocompleteActionPredictorTable::Row::Id>* id_list); + // Called on an incognito-owned predictor to copy the current caches from the // main profile. void CopyFromMainProfile();
diff --git a/chrome/browser/predictors/autocomplete_action_predictor_unittest.cc b/chrome/browser/predictors/autocomplete_action_predictor_unittest.cc index 6c80be1..4495f77 100644 --- a/chrome/browser/predictors/autocomplete_action_predictor_unittest.cc +++ b/chrome/browser/predictors/autocomplete_action_predictor_unittest.cc
@@ -87,6 +87,24 @@ AutocompleteActionPredictor::ACTION_NONE } }; +// List of urls sorted by the confidence score in ascending order. +TestUrlInfo test_url_confidence_db[] = { + {GURL("http://www.testsite.com/g.html"), ASCIIToUTF16("Test"), 1, + ASCIIToUTF16("test"), 0, 2, AutocompleteActionPredictor::ACTION_NONE}, + {GURL("http://www.testsite.com/f.html"), ASCIIToUTF16("Test"), 1, + ASCIIToUTF16("test"), 1, 2, AutocompleteActionPredictor::ACTION_NONE}, + {GURL("http://www.testsite.com/e.html"), ASCIIToUTF16("Test"), 1, + ASCIIToUTF16("test"), 2, 2, AutocompleteActionPredictor::ACTION_NONE}, + {GURL("http://www.testsite.com/d.html"), ASCIIToUTF16("Test"), 1, + ASCIIToUTF16("test"), 3, 3, AutocompleteActionPredictor::ACTION_NONE}, + {GURL("http://www.testsite.com/c.html"), ASCIIToUTF16("Test"), 1, + ASCIIToUTF16("test"), 3, 2, AutocompleteActionPredictor::ACTION_NONE}, + {GURL("http://www.testsite.com/b.html"), ASCIIToUTF16("Test"), 1, + ASCIIToUTF16("test"), 3, 0, AutocompleteActionPredictor::ACTION_NONE}, + {GURL("http://www.testsite.com/a.html"), ASCIIToUTF16("Test"), 1, + ASCIIToUTF16("test"), 5, 0, AutocompleteActionPredictor::ACTION_NONE}, +}; + GURL GenerateTestURL(size_t size) { std::string prefix = "http://b/"; // Cannot generate an URL shorter than |prefix|. @@ -260,6 +278,12 @@ predictor_->DeleteOldIdsFromCaches(url_db, id_list); } + void DeleteLowestConfidenceRowsFromCaches( + size_t count, + std::vector<AutocompleteActionPredictorTable::Row::Id>* id_list) { + predictor_->DeleteLowestConfidenceRowsFromCaches(count, id_list); + } + AutocompleteActionPredictor* predictor() { return predictor_.get(); } DBCacheMap* db_cache() { return &predictor_->db_cache_; } @@ -418,6 +442,53 @@ } } +TEST_F(AutocompleteActionPredictorTest, + DeleteLowestConfidenceRowsFromCaches_OneByOne) { + std::vector<AutocompleteActionPredictorTable::Row::Id> test_url_ids; + for (const auto& info : test_url_confidence_db) + test_url_ids.push_back(AddRow(info)); + + std::vector<AutocompleteActionPredictorTable::Row::Id> id_list; + std::vector<AutocompleteActionPredictorTable::Row::Id> expected; + + for (size_t i = 0; i < base::size(test_url_confidence_db); ++i) { + DeleteLowestConfidenceRowsFromCaches(1, &id_list); + expected.push_back(test_url_ids[i]); + EXPECT_THAT(id_list, ::testing::UnorderedElementsAreArray(expected)); + + DBCacheKey deleted_key = {test_url_confidence_db[i].user_text, + test_url_confidence_db[i].url}; + EXPECT_FALSE(base::ContainsKey(*db_cache(), deleted_key)); + EXPECT_FALSE(base::ContainsKey(*db_id_cache(), deleted_key)); + } +} + +TEST_F(AutocompleteActionPredictorTest, + DeleteLowestConfidenceRowsFromCaches_Bulk) { + std::vector<AutocompleteActionPredictorTable::Row::Id> test_url_ids; + for (const auto& info : test_url_confidence_db) + test_url_ids.push_back(AddRow(info)); + + std::vector<AutocompleteActionPredictorTable::Row::Id> id_list; + std::vector<AutocompleteActionPredictorTable::Row::Id> expected; + + const size_t count_to_remove = 4; + CHECK_LT(count_to_remove, base::size(test_url_confidence_db)); + + for (size_t i = 0; i < count_to_remove; ++i) + expected.push_back(test_url_ids[i]); + + DeleteLowestConfidenceRowsFromCaches(count_to_remove, &id_list); + ASSERT_THAT(id_list, ::testing::UnorderedElementsAreArray(expected)); + + for (size_t i = 0; i < count_to_remove; ++i) { + DBCacheKey deleted_key = {test_url_confidence_db[i].user_text, + test_url_confidence_db[i].url}; + EXPECT_FALSE(base::ContainsKey(*db_cache(), deleted_key)); + EXPECT_FALSE(base::ContainsKey(*db_id_cache(), deleted_key)); + } +} + TEST_F(AutocompleteActionPredictorTest, OnURLsDeletedExpired) { OnURLsDeletedTest(true); }
diff --git a/chrome/browser/previews/previews_browsertest.cc b/chrome/browser/previews/previews_browsertest.cc index 84c2546dc0..a502a289 100644 --- a/chrome/browser/previews/previews_browsertest.cc +++ b/chrome/browser/previews/previews_browsertest.cc
@@ -16,7 +16,10 @@ #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/metrics/subprocess_metrics_provider.h" +#include "chrome/browser/previews/previews_service.h" +#include "chrome/browser/previews/previews_service_factory.h" #include "chrome/browser/previews/previews_ui_tab_helper.h" +#include "chrome/browser/profiles/profile.h" #include "chrome/browser/ssl/cert_verifier_browser_test.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" @@ -26,6 +29,9 @@ #include "components/optimization_guide/optimization_guide_service.h" #include "components/optimization_guide/proto/hints.pb.h" #include "components/optimization_guide/test_hints_component_creator.h" +#include "components/previews/content/previews_decider_impl.h" +#include "components/previews/content/previews_optimization_guide.h" +#include "components/previews/content/previews_ui_service.h" #include "components/previews/core/previews_constants.h" #include "components/previews/core/previews_features.h" #include "components/previews/core/previews_switches.h" @@ -246,10 +252,18 @@ g_browser_process->optimization_guide_service()->MaybeUpdateHintsComponent( component_info); - RetryForHistogramUntilCountReached( - &histogram_tester, - previews::kPreviewsOptimizationGuideUpdateHintsResultHistogramString, - 1); + // Wait for hint update processing to complete. + base::RunLoop run_loop; + PreviewsServiceFactory::GetForProfile( + Profile::FromBrowserContext(browser() + ->tab_strip_model() + ->GetActiveWebContents() + ->GetBrowserContext())) + ->previews_ui_service() + ->previews_decider_impl() + ->previews_opt_guide() + ->ListenForNextUpdateForTesting(run_loop.QuitClosure()); + run_loop.Run(); // Navigate to |hint_setup_url| to prime the OptimizationGuide hints for the // url's host and ensure that they have been loaded from the store (via
diff --git a/chrome/browser/previews/previews_content_util.cc b/chrome/browser/previews/previews_content_util.cc index 02cb95e..b9c6d61f 100644 --- a/chrome/browser/previews/previews_content_util.cc +++ b/chrome/browser/previews/previews_content_util.cc
@@ -4,14 +4,152 @@ #include "chrome/browser/previews/previews_content_util.h" +#include <string> +#include <vector> + #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/strings/stringprintf.h" +#include "chrome/browser/content_settings/cookie_settings_factory.h" +#include "chrome/browser/previews/previews_lite_page_decider.h" +#include "chrome/browser/previews/previews_lite_page_navigation_throttle.h" +#include "chrome/browser/previews/previews_lite_page_navigation_throttle_manager.h" +#include "chrome/browser/previews/previews_service.h" +#include "chrome/browser/previews/previews_service_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "components/content_settings/core/browser/cookie_settings.h" #include "components/previews/content/previews_user_data.h" +#include "components/previews/core/previews_experiments.h" #include "components/previews/core/previews_lite_page_redirect.h" +#include "content/public/browser/browser_context.h" +#include "content/public/browser/navigation_handle.h" +#include "content/public/browser/web_contents.h" +#include "net/base/ip_address.h" +#include "net/base/url_util.h" +#include "net/nqe/effective_connection_type.h" namespace previews { +bool IsPrivateDomain(const GURL& url) { + if (url.host().find(".") == base::StringPiece::npos) + return true; + + // Allow localhost check to be skipped if needed, like in testing. + if (net::IsLocalhost(url)) + return !previews::params::LitePagePreviewsTriggerOnLocalhost(); + + net::IPAddress ip_addr; + if (url.HostIsIPAddress() && ip_addr.AssignFromIPLiteral(url.host()) && + !ip_addr.IsPubliclyRoutable()) { + return true; + } + return false; +} + +bool ShouldAllowRedirectPreview(content::NavigationHandle* navigation_handle) { + // This should only occur in unit tests, this behavior is tested in browser + // tests. + if (!navigation_handle) + return true; + + const GURL& url = navigation_handle->GetURL(); + content::WebContents* web_contents = navigation_handle->GetWebContents(); + auto* previews_service = PreviewsServiceFactory::GetForProfile( + Profile::FromBrowserContext(web_contents->GetBrowserContext())); + PreviewsLitePageNavigationThrottleManager* manager = + previews_service->previews_lite_page_decider(); + + std::vector<PreviewsLitePageNavigationThrottle::IneligibleReason> + ineligible_reasons; + + if (!url.SchemeIs(url::kHttpsScheme)) { + ineligible_reasons.push_back( + PreviewsLitePageNavigationThrottle::IneligibleReason::kNonHttpsScheme); + } + + if (manager->IsServerUnavailable()) { + ineligible_reasons.push_back(PreviewsLitePageNavigationThrottle:: + IneligibleReason::kServerUnavailable); + } + + content_settings::CookieSettings* cookie_settings = + CookieSettingsFactory::GetForProfile( + Profile::FromBrowserContext(web_contents->GetBrowserContext())) + .get(); + ContentSetting setting; + GURL previews_url = + PreviewsLitePageNavigationThrottle::GetPreviewsURLForURL(url); + cookie_settings->GetCookieSetting(previews_url, previews_url, nullptr, + &setting); + if (!content_settings::CookieSettingsBase::IsAllowed(setting)) { + ineligible_reasons.push_back( + PreviewsLitePageNavigationThrottle::IneligibleReason::kCookiesBlocked); + } + + // Record UMA. + for (PreviewsLitePageNavigationThrottle::IneligibleReason reason : + ineligible_reasons) { + PreviewsLitePageNavigationThrottle::LogIneligibleReason(reason); + } + if (!ineligible_reasons.empty()) + return false; + + // Check dynamic blacklists. + std::vector<PreviewsLitePageNavigationThrottle::BlacklistReason> + blacklist_reasons; + + if (IsPrivateDomain(url)) { + blacklist_reasons.push_back( + PreviewsLitePageNavigationThrottle::BlacklistReason:: + kNavigationToPrivateDomain); + } + + std::vector<std::string> blacklisted_path_suffixes = + previews::params::LitePagePreviewsBlacklistedPathSuffixes(); + for (const std::string& suffix : blacklisted_path_suffixes) { + if (base::EndsWith(url.path(), suffix, + base::CompareCase::INSENSITIVE_ASCII)) { + blacklist_reasons.push_back(PreviewsLitePageNavigationThrottle:: + BlacklistReason::kPathSuffixBlacklisted); + break; + } + } + + if (manager->HostBlacklistedFromBypass(url.host())) { + blacklist_reasons.push_back(PreviewsLitePageNavigationThrottle:: + BlacklistReason::kHostBypassBlacklisted); + } + + // Record UMA + for (PreviewsLitePageNavigationThrottle::BlacklistReason reason : + blacklist_reasons) { + UMA_HISTOGRAM_ENUMERATION("Previews.ServerLitePage.BlacklistReasons", + reason); + } + + if (!blacklist_reasons.empty()) + return false; + + // This should always be at the end, but before the control group check. + if (manager->NeedsToNotifyUser()) { + manager->NotifyUser(web_contents); + PreviewsLitePageNavigationThrottle::LogIneligibleReason( + PreviewsLitePageNavigationThrottle::IneligibleReason::kInfoBarNotSeen); + return false; + } + + // This should always be last. + if (previews::params::IsInLitePageRedirectControl()) { + previews::PreviewsUserData::ServerLitePageInfo* info = + PreviewsLitePageNavigationThrottle::GetOrCreateServerLitePageInfo( + navigation_handle, manager); + info->status = previews::ServerLitePageStatus::kControl; + return false; + } + + return true; +} + bool HasEnabledPreviews(content::PreviewsState previews_state) { return previews_state != content::PREVIEWS_UNSPECIFIED && !(previews_state & content::PREVIEWS_OFF) && @@ -24,9 +162,18 @@ bool is_reload, bool is_redirect, bool is_data_saver_user, - previews::PreviewsDecider* previews_decider) { + previews::PreviewsDecider* previews_decider, + content::NavigationHandle* navigation_handle) { content::PreviewsState previews_state = content::PREVIEWS_UNSPECIFIED; + // Either this is a navigation to the lite page via the redirect mechanism and + // only Lite Page redirect should be served, or this is a reload in which case + // the Lite Page mechanism should redirect to the original URL. Either way, + // set the allowed PreviewsState. + if (IsLitePageRedirectPreviewURL(url)) { + return previews_state = content::LITE_PAGE_REDIRECT_ON; + } + // Record whether the hint cache has a matching entry for this pre-commit URL. previews_decider->LogHintCacheMatch(url, false /* is_committed */); @@ -77,15 +224,11 @@ has_page_hints = previews_decider->LoadPageHints(url); } - // Note: this is for the beginning of navigation/redirect so we should not - // check for https here (since an http request may redirect to https). - // TODO(robertogden): Add other eligibility reasons and log scheme/other - // previews taking precedence, etc. https://crbug.com/921755 - if (url.SchemeIsCryptographic() && - (!has_page_hints || params::LitePagePreviewsOverridePageHints()) && + if ((!has_page_hints || params::LitePagePreviewsOverridePageHints()) && previews_decider->ShouldAllowPreviewAtNavigationStart( previews_data, url, is_reload, - previews::PreviewsType::LITE_PAGE_REDIRECT)) { + previews::PreviewsType::LITE_PAGE_REDIRECT) && + ShouldAllowRedirectPreview(navigation_handle)) { previews_state |= content::LITE_PAGE_REDIRECT_ON; }
diff --git a/chrome/browser/previews/previews_content_util.h b/chrome/browser/previews/previews_content_util.h index f26a3d49..0ddc358 100644 --- a/chrome/browser/previews/previews_content_util.h +++ b/chrome/browser/previews/previews_content_util.h
@@ -8,6 +8,10 @@ #include "components/previews/core/previews_decider.h" #include "content/public/common/previews_state.h" +namespace content { +class NavigationHandle; +} + namespace previews { // Returns whether |previews_state| has any enabled previews. @@ -19,13 +23,16 @@ // definitions for content::PreviewsState. // |is_reload| is used to eliminate certain preview types, and |previews_data| // is populated with relevant information. +// TODO(ryansturm): |navigation_handle| has all of the other information, so +// remove extra arguments. https://crbug.com/934400 content::PreviewsState DetermineAllowedClientPreviewsState( previews::PreviewsUserData* previews_data, const GURL& url, bool is_reload, bool is_redirect, bool is_data_saver_user, - previews::PreviewsDecider* previews_decider); + previews::PreviewsDecider* previews_decider, + content::NavigationHandle* navigation_handle); // Returns an updated PreviewsState given |previews_state| that has already // been updated wrt server previews. This should be called at Navigation Commit
diff --git a/chrome/browser/previews/previews_content_util_unittest.cc b/chrome/browser/previews/previews_content_util_unittest.cc index a6ab179..7e628e9 100644 --- a/chrome/browser/previews/previews_content_util_unittest.cc +++ b/chrome/browser/previews/previews_content_util_unittest.cc
@@ -107,14 +107,16 @@ bool is_reload = false; bool is_redirect = false; bool is_data_saver_user = true; - EXPECT_EQ(content::PREVIEWS_UNSPECIFIED, - previews::DetermineAllowedClientPreviewsState( - &user_data, GURL("http://www.google.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider())); - EXPECT_EQ(content::PREVIEWS_UNSPECIFIED, - previews::DetermineAllowedClientPreviewsState( - &user_data, GURL("http://www.google.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider())); + EXPECT_EQ( + content::PREVIEWS_UNSPECIFIED, + previews::DetermineAllowedClientPreviewsState( + &user_data, GURL("http://www.google.com"), is_reload, is_redirect, + is_data_saver_user, enabled_previews_decider(), nullptr)); + EXPECT_EQ( + content::PREVIEWS_UNSPECIFIED, + previews::DetermineAllowedClientPreviewsState( + &user_data, GURL("http://www.google.com"), is_reload, is_redirect, + is_data_saver_user, enabled_previews_decider(), nullptr)); } TEST_F(PreviewsContentUtilTest, @@ -127,16 +129,18 @@ bool is_reload = false; bool is_redirect = false; bool is_data_saver_user = true; - EXPECT_EQ(content::OFFLINE_PAGE_ON | content::CLIENT_LOFI_ON | - content::RESOURCE_LOADING_HINTS_ON | content::NOSCRIPT_ON, - previews::DetermineAllowedClientPreviewsState( - &user_data, GURL("http://www.google.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider())); + EXPECT_EQ( + content::OFFLINE_PAGE_ON | content::CLIENT_LOFI_ON | + content::RESOURCE_LOADING_HINTS_ON | content::NOSCRIPT_ON, + previews::DetermineAllowedClientPreviewsState( + &user_data, GURL("http://www.google.com"), is_reload, is_redirect, + is_data_saver_user, enabled_previews_decider(), nullptr)); is_data_saver_user = false; - EXPECT_EQ(content::OFFLINE_PAGE_ON, - previews::DetermineAllowedClientPreviewsState( - &user_data, GURL("http://www.google.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider())); + EXPECT_EQ( + content::OFFLINE_PAGE_ON, + previews::DetermineAllowedClientPreviewsState( + &user_data, GURL("http://www.google.com"), is_reload, is_redirect, + is_data_saver_user, enabled_previews_decider(), nullptr)); } TEST_F(PreviewsContentUtilTest, @@ -149,28 +153,32 @@ bool is_reload = false; bool is_redirect = false; bool is_data_saver_user = false; - EXPECT_EQ(content::OFFLINE_PAGE_ON, - previews::DetermineAllowedClientPreviewsState( - &user_data, GURL("http://www.google.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider())); + EXPECT_EQ( + content::OFFLINE_PAGE_ON, + previews::DetermineAllowedClientPreviewsState( + &user_data, GURL("http://www.google.com"), is_reload, is_redirect, + is_data_saver_user, enabled_previews_decider(), nullptr)); EXPECT_FALSE(user_data.is_redirect()); user_data.set_allowed_previews_state(content::OFFLINE_PAGE_ON); is_redirect = true; - EXPECT_EQ(content::OFFLINE_PAGE_ON, - previews::DetermineAllowedClientPreviewsState( - &user_data, GURL("http://www.google.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider())); + EXPECT_EQ( + content::OFFLINE_PAGE_ON, + previews::DetermineAllowedClientPreviewsState( + &user_data, GURL("http://www.google.com"), is_reload, is_redirect, + is_data_saver_user, enabled_previews_decider(), nullptr)); EXPECT_TRUE(user_data.is_redirect()); user_data.set_allowed_previews_state(content::PREVIEWS_OFF); - EXPECT_EQ(content::PREVIEWS_UNSPECIFIED, - previews::DetermineAllowedClientPreviewsState( - &user_data, GURL("http://www.google.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider())); + EXPECT_EQ( + content::PREVIEWS_UNSPECIFIED, + previews::DetermineAllowedClientPreviewsState( + &user_data, GURL("http://www.google.com"), is_reload, is_redirect, + is_data_saver_user, enabled_previews_decider(), nullptr)); is_redirect = false; - EXPECT_EQ(content::OFFLINE_PAGE_ON, - previews::DetermineAllowedClientPreviewsState( - &user_data, GURL("http://www.google.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider())); + EXPECT_EQ( + content::OFFLINE_PAGE_ON, + previews::DetermineAllowedClientPreviewsState( + &user_data, GURL("http://www.google.com"), is_reload, is_redirect, + is_data_saver_user, enabled_previews_decider(), nullptr)); } TEST_F(PreviewsContentUtilTest, DetermineAllowedClientPreviewsStateClientLoFi) { @@ -183,11 +191,13 @@ EXPECT_TRUE(content::CLIENT_LOFI_ON & previews::DetermineAllowedClientPreviewsState( &user_data, GURL("https://www.google.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider())); + is_redirect, is_data_saver_user, enabled_previews_decider(), + nullptr)); EXPECT_TRUE(content::CLIENT_LOFI_ON & previews::DetermineAllowedClientPreviewsState( &user_data, GURL("http://www.google.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider())); + is_redirect, is_data_saver_user, enabled_previews_decider(), + nullptr)); } TEST_F(PreviewsContentUtilTest, @@ -199,16 +209,16 @@ bool is_reload = false; bool is_redirect = false; bool is_data_saver_user = true; - EXPECT_LT( - 0, content::RESOURCE_LOADING_HINTS_ON & - previews::DetermineAllowedClientPreviewsState( - &user_data, GURL("https://www.google.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider())); - EXPECT_LT( - 0, content::RESOURCE_LOADING_HINTS_ON & - previews::DetermineAllowedClientPreviewsState( - &user_data, GURL("http://www.google.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider())); + EXPECT_LT(0, content::RESOURCE_LOADING_HINTS_ON & + previews::DetermineAllowedClientPreviewsState( + &user_data, GURL("https://www.google.com"), is_reload, + is_redirect, is_data_saver_user, + enabled_previews_decider(), nullptr)); + EXPECT_LT(0, content::RESOURCE_LOADING_HINTS_ON & + previews::DetermineAllowedClientPreviewsState( + &user_data, GURL("http://www.google.com"), is_reload, + is_redirect, is_data_saver_user, + enabled_previews_decider(), nullptr)); } TEST_F(PreviewsContentUtilTest, @@ -226,17 +236,19 @@ EXPECT_TRUE((content::NOSCRIPT_ON | content::CLIENT_LOFI_ON) & previews::DetermineAllowedClientPreviewsState( &user_data, GURL("https://www.google.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider())); + is_redirect, is_data_saver_user, enabled_previews_decider(), + nullptr)); EXPECT_TRUE((content::NOSCRIPT_ON | content::CLIENT_LOFI_ON) & previews::DetermineAllowedClientPreviewsState( &user_data, GURL("http://www.google.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider())); + is_redirect, is_data_saver_user, enabled_previews_decider(), + nullptr)); // Verify non-HTTP[S] URL has no previews enabled. EXPECT_EQ(content::PREVIEWS_UNSPECIFIED, previews::DetermineAllowedClientPreviewsState( &user_data, GURL("data://someblob"), is_reload, is_redirect, - is_data_saver_user, enabled_previews_decider())); + is_data_saver_user, enabled_previews_decider(), nullptr)); } TEST_F(PreviewsContentUtilTest, @@ -253,18 +265,17 @@ EXPECT_TRUE(content::LITE_PAGE_REDIRECT_ON & previews::DetermineAllowedClientPreviewsState( &user_data, GURL("https://www.google.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider())); - EXPECT_FALSE(content::LITE_PAGE_REDIRECT_ON & - previews::DetermineAllowedClientPreviewsState( - &user_data, GURL("http://www.google.com"), is_reload, - is_redirect, is_data_saver_user, - enabled_previews_decider())); + is_redirect, is_data_saver_user, enabled_previews_decider(), + nullptr)); // Verify non-HTTP[S] URL has no previews enabled. EXPECT_EQ(content::PREVIEWS_UNSPECIFIED, previews::DetermineAllowedClientPreviewsState( &user_data, GURL("data://someblob"), is_reload, is_redirect, - is_data_saver_user, enabled_previews_decider())); + is_data_saver_user, enabled_previews_decider(), nullptr)); + + // Other checks are performed in browser tests due to the nature of needing + // fully initialized browser state. } TEST_F(PreviewsContentUtilTest, @@ -281,7 +292,7 @@ // Verify Lite Page Redirect enabled for host without page hints. content::PreviewsState ps1 = previews::DetermineAllowedClientPreviewsState( &user_data, GURL("https://www.google.com"), is_reload, is_redirect, - is_data_saver_user, enabled_previews_decider()); + is_data_saver_user, enabled_previews_decider(), nullptr); EXPECT_TRUE(ps1 & content::LITE_PAGE_REDIRECT_ON); EXPECT_TRUE(ps1 & content::RESOURCE_LOADING_HINTS_ON); EXPECT_TRUE(ps1 & content::NOSCRIPT_ON); @@ -289,7 +300,7 @@ // Verify only page hint client previews enabled with known page hints. content::PreviewsState ps2 = previews::DetermineAllowedClientPreviewsState( &user_data, GURL("https://www.hintcachedhost.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider()); + is_redirect, is_data_saver_user, enabled_previews_decider(), nullptr); EXPECT_FALSE(ps2 & content::LITE_PAGE_REDIRECT_ON); EXPECT_TRUE(ps2 & content::RESOURCE_LOADING_HINTS_ON); EXPECT_TRUE(ps2 & content::NOSCRIPT_ON); @@ -305,7 +316,7 @@ // Verify Lite Page Redirect now enabled for host with page hints. content::PreviewsState ps = previews::DetermineAllowedClientPreviewsState( &user_data, GURL("https://www.hintcachedhost.com"), is_reload, - is_redirect, is_data_saver_user, enabled_previews_decider()); + is_redirect, is_data_saver_user, enabled_previews_decider(), nullptr); EXPECT_TRUE(ps & content::LITE_PAGE_REDIRECT_ON); EXPECT_TRUE(ps & content::RESOURCE_LOADING_HINTS_ON); EXPECT_TRUE(ps & content::NOSCRIPT_ON);
diff --git a/chrome/browser/previews/previews_lite_page_browsertest.cc b/chrome/browser/previews/previews_lite_page_browsertest.cc index 5575dfca..06d205e 100644 --- a/chrome/browser/previews/previews_lite_page_browsertest.cc +++ b/chrome/browser/previews/previews_lite_page_browsertest.cc
@@ -51,6 +51,9 @@ #include "components/optimization_guide/proto/hints.pb.h" #include "components/optimization_guide/test_hints_component_creator.h" #include "components/prefs/pref_service.h" +#include "components/previews/content/previews_decider_impl.h" +#include "components/previews/content/previews_optimization_guide.h" +#include "components/previews/content/previews_ui_service.h" #include "components/previews/content/previews_user_data.h" #include "components/previews/core/previews_constants.h" #include "components/previews/core/previews_experiments.h" @@ -75,11 +78,11 @@ const int kTimeoutMs = 250; const int kRedirectLoopCount = 3; -const std::string kOriginHost = "origin.com"; +const char kOriginHost[] = "origin.com"; // This should match the value in //components/google/core/common/google_util.cc // so that the X-Client-Data header is sent for subresources. -const std::string kPreviewsHost = "litepages.googlezip.net"; +const char kPreviewsHost[] = "litepages.googlezip.net"; } class PreviewsLitePageServerBrowserTest @@ -658,7 +661,7 @@ if (net::GetValueForKeyInQuery(original_url, "resp", &code_query_param)) base::StringToInt(code_query_param, &return_code); - GURL subresource_url("https://foo." + kPreviewsHost + ":" + + GURL subresource_url("https://foo." + std::string(kPreviewsHost) + ":" + previews_server_url().port() + "/subresource.png"); std::string subresource_body = "<html><body><img src=\"" + subresource_url.spec() + @@ -764,8 +767,6 @@ IN_PROC_BROWSER_TEST_P(PreviewsLitePageServerBrowserTest, DISABLE_ON_WIN_MAC(LitePagePreviewsTriggering)) { - if (GetParam()) - return; // TODO(crbug.com/874150): Use ExpectUniqueSample in these tests. // The histograms in these tests can only be checked by the expected bucket, // and not by a unique sample. This is because each navigation to a preview @@ -787,8 +788,10 @@ VerifyPreviewLoaded(); VerifyInfoStatus(&histogram_tester, previews::ServerLitePageStatus::kSuccess); - histogram_tester.ExpectBucketCount("Previews.ServerLitePage.Triggered", - true, 1); + if (!GetParam()) { + histogram_tester.ExpectBucketCount("Previews.ServerLitePage.Triggered", + true, 1); + } } { @@ -802,8 +805,10 @@ PreviewsLitePageNavigationThrottle::BlacklistReason:: kPathSuffixBlacklisted, 1); - histogram_tester.ExpectBucketCount("Previews.ServerLitePage.Triggered", - false, 1); + if (!GetParam()) { + histogram_tester.ExpectBucketCount("Previews.ServerLitePage.Triggered", + false, 1); + } } { @@ -833,15 +838,16 @@ // Verify the preview is not triggered when navigating to the previews // server. base::HistogramTester histogram_tester; - ui_test_utils::NavigateToURL(browser(), previews_server_url()); - EXPECT_EQ(GetLoadedURL(), previews_server_url()); - histogram_tester.ExpectBucketCount( - "Previews.ServerLitePage.BlacklistReasons", - PreviewsLitePageNavigationThrottle::BlacklistReason:: - kNavigationToPreviewsDomain, - 1); - histogram_tester.ExpectBucketCount("Previews.ServerLitePage.Triggered", - false, 1); + ui_test_utils::NavigateToURL( + browser(), PreviewsLitePageNavigationThrottle::GetPreviewsURLForURL( + HttpsLitePageURL(kSuccess))); + if (!GetParam()) { + VerifyPreviewNotLoaded(); + histogram_tester.ExpectBucketCount("Previews.ServerLitePage.Triggered", + false, 2); + } else { + VerifyPreviewLoaded(); + } } { @@ -853,8 +859,10 @@ PreviewsLitePageNavigationThrottle::BlacklistReason:: kNavigationToPrivateDomain, 1); - histogram_tester.ExpectBucketCount("Previews.ServerLitePage.Triggered", - false, 1); + if (!GetParam()) { + histogram_tester.ExpectBucketCount("Previews.ServerLitePage.Triggered", + false, 1); + } VerifyErrorPageLoaded(); } @@ -869,8 +877,10 @@ PreviewsLitePageNavigationThrottle::BlacklistReason:: kNavigationToPrivateDomain, 1); - histogram_tester.ExpectBucketCount("Previews.ServerLitePage.Triggered", - false, 1); + if (!GetParam()) { + histogram_tester.ExpectBucketCount("Previews.ServerLitePage.Triggered", + false, 1); + } } { @@ -884,12 +894,10 @@ VerifyPreviewNotLoaded(); ClearDeciderState(); - histogram_tester.ExpectBucketCount( - "Previews.ServerLitePage.IneligibleReasons", - PreviewsLitePageNavigationThrottle::IneligibleReason::kNetworkNotSlow, - 1); - histogram_tester.ExpectBucketCount("Previews.ServerLitePage.Triggered", - false, 1); + if (!GetParam()) { + histogram_tester.ExpectBucketCount("Previews.ServerLitePage.Triggered", + false, 1); + } // Reset ECT for future tests. g_browser_process->network_quality_tracker() @@ -908,11 +916,10 @@ VerifyPreviewNotLoaded(); ClearDeciderState(); - histogram_tester.ExpectBucketCount( - "Previews.ServerLitePage.IneligibleReasons", - PreviewsLitePageNavigationThrottle::IneligibleReason::kECTUnknown, 1); - histogram_tester.ExpectBucketCount("Previews.ServerLitePage.Triggered", - false, 1); + if (!GetParam()) { + histogram_tester.ExpectBucketCount("Previews.ServerLitePage.Triggered", + false, 1); + } // Reset ECT for future tests. g_browser_process->network_quality_tracker() @@ -942,7 +949,6 @@ CookieSettingsFactory::GetForProfile(browser()->profile()) ->SetDefaultCookieSetting(CONTENT_SETTING_ALLOW); } - { // Verify a preview is not shown for a redirect loop. base::HistogramTester histogram_tester; @@ -958,36 +964,42 @@ VerifyPreviewNotLoaded(); ClearDeciderState(); - // It takes a few redirects to reach the end case. Just make sure at least - // one sample has been recorded in the correct bucket. - histogram_tester.ExpectBucketCount( - "Previews.ServerLitePage.IneligibleReasons", - static_cast<int>(PreviewsLitePageNavigationThrottle::IneligibleReason:: - kExceededMaxNavigationRestarts), - 1); - } -} - -IN_PROC_BROWSER_TEST_P(PreviewsLitePageServerBrowserTest, - DISABLE_ON_WIN_MAC(LitePagePreviewsReloadEnabled)) { - base::test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitWithFeatures( - {}, {previews::features::kPreviewsDisallowedOnReloads}); - { - base::HistogramTester histogram_tester; - ui_test_utils::NavigateToURL(browser(), HttpsLitePageURL(kSuccess)); - VerifyPreviewLoaded(); - VerifyInfoStatus(&histogram_tester, - previews::ServerLitePageStatus::kSuccess); + if (!GetParam()) { + // It takes a few redirects to reach the end case. Just make sure at least + // one sample has been recorded in the correct bucket. + histogram_tester.ExpectBucketCount( + "Previews.ServerLitePage.IneligibleReasons", + static_cast<int>( + PreviewsLitePageNavigationThrottle::IneligibleReason:: + kExceededMaxNavigationRestarts), + 1); + } } { + // Verify a subframe navigation does not trigger a preview. + const base::string16 kSubframeTitle = base::ASCIIToUTF16("Subframe"); base::HistogramTester histogram_tester; - GetWebContents()->GetController().Reload(content::ReloadType::NORMAL, - false); - VerifyPreviewLoaded(); - VerifyInfoStatus(&histogram_tester, - previews::ServerLitePageStatus::kSuccess); + ui_test_utils::NavigateToURL(browser(), subframe_url()); + if (!GetParam()) { + histogram_tester.ExpectBucketCount("Previews.ServerLitePage.Triggered", + true, 0); + } + + // Navigate in the subframe and wait for it to finish. The waiting is + // accomplished by |ExecuteScriptAndExtractString| which waits for + // |window.domAutomationController.send| in the HTML page. + std::string result; + EXPECT_TRUE(ExecuteScriptAndExtractString( + GetWebContents()->GetMainFrame(), + "window.open(\"" + HttpsLitePageURL(kSuccess).spec() + + "\", \"subframe\")", + &result)); + EXPECT_EQ(kSubframeTitle, base::ASCIIToUTF16(result)); + if (!GetParam()) { + histogram_tester.ExpectBucketCount("Previews.ServerLitePage.Triggered", + true, 0); + } } } @@ -996,12 +1008,38 @@ base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitWithFeatures( {previews::features::kPreviewsDisallowedOnReloads}, {}); + // Start with a non-preview load. + g_browser_process->network_quality_tracker() + ->ReportEffectiveConnectionTypeForTesting( + net::EFFECTIVE_CONNECTION_TYPE_3G); + + ui_test_utils::NavigateToURL(browser(), HttpsLitePageURL(kSuccess)); + VerifyPreviewNotLoaded(); + + // Set the conditions so a Preview would trigger if not for the reload. + g_browser_process->network_quality_tracker() + ->ReportEffectiveConnectionTypeForTesting( + net::EFFECTIVE_CONNECTION_TYPE_2G); + GetWebContents()->GetController().Reload(content::ReloadType::NORMAL, false); + VerifyPreviewNotLoaded(); +} + +IN_PROC_BROWSER_TEST_P( + PreviewsLitePageServerBrowserTest, + DISABLE_ON_WIN_MAC(ReloadingLitePagesDisablesLitePages)) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures( + {previews::features::kPreviewsReloadsAreSoftOptOuts}, {}); ui_test_utils::NavigateToURL(browser(), HttpsLitePageURL(kSuccess)); VerifyPreviewLoaded(); GetWebContents()->GetController().Reload(content::ReloadType::NORMAL, false); VerifyPreviewNotLoaded(); + + // Check the the rule is still present. + ui_test_utils::NavigateToURL(browser(), HttpsLitePageURL(kSuccess)); + VerifyPreviewNotLoaded(); } IN_PROC_BROWSER_TEST_P(PreviewsLitePageServerBrowserTest, @@ -1306,8 +1344,6 @@ IN_PROC_BROWSER_TEST_P(PreviewsLitePageServerBrowserTest, DISABLE_ON_WIN_MAC(LitePagePreviewsClientRedirect)) { - if (GetParam()) - return; // Navigate to a non-preview first. ui_test_utils::NavigateToURL(browser(), https_media_url()); VerifyPreviewNotLoaded(); @@ -1467,8 +1503,6 @@ IN_PROC_BROWSER_TEST_P(PreviewsLitePageServerDataSaverBrowserTest, DISABLE_ON_WIN_MAC(LitePagePreviewsDSTriggering)) { - if (GetParam()) - return; // Verify the preview is not triggered on HTTPS pageloads without DataSaver. ui_test_utils::NavigateToURL(browser(), HttpsLitePageURL(kSuccess)); VerifyPreviewNotLoaded(); @@ -1541,8 +1575,6 @@ IN_PROC_BROWSER_TEST_P( PreviewsLitePageNotificationDSEnabledBrowserTest, DISABLE_ON_WIN_MAC(LitePagePreviewsInfoBarDataSaverUser)) { - if (GetParam()) - return; // Ensure the preview is not shown the first time before the infobar is shown // for users who have DRP enabled. base::HistogramTester histogram_tester; @@ -1637,8 +1669,6 @@ IN_PROC_BROWSER_TEST_P(PreviewsLitePageControlBrowserTest, DISABLE_ON_WIN_MAC(LitePagePreviewsControlGroup)) { - if (GetParam()) - return; base::HistogramTester histogram_tester; ui_test_utils::NavigateToURL(browser(), HttpsLitePageURL(kSuccess)); VerifyPreviewNotLoaded(); @@ -1655,15 +1685,21 @@ void ProcessHintsComponent( const optimization_guide::HintsComponentInfo& component_info) { - base::HistogramTester histogram_tester; - g_browser_process->optimization_guide_service()->MaybeUpdateHintsComponent( component_info); - RetryForHistogramUntilCountReached( - &histogram_tester, - previews::kPreviewsOptimizationGuideUpdateHintsResultHistogramString, - 1); + // Wait for hint update processing to complete. + base::RunLoop run_loop; + PreviewsServiceFactory::GetForProfile( + Profile::FromBrowserContext(browser() + ->tab_strip_model() + ->GetActiveWebContents() + ->GetBrowserContext())) + ->previews_ui_service() + ->previews_decider_impl() + ->previews_opt_guide() + ->ListenForNextUpdateForTesting(run_loop.QuitClosure()); + run_loop.Run(); } void SetResourceLoadingHints(const std::vector<std::string>& hints_sites) { @@ -1679,30 +1715,6 @@ } private: - // Retries fetching |histogram_name| until it contains at least |count| - // samples. - void RetryForHistogramUntilCountReached( - base::HistogramTester* histogram_tester, - const std::string& histogram_name, - size_t count) { - while (true) { - base::TaskScheduler::GetInstance()->FlushForTesting(); - base::RunLoop().RunUntilIdle(); - - content::FetchHistogramsFromChildProcesses(); - SubprocessMetricsProvider::MergeHistogramDeltasForTesting(); - - const std::vector<base::Bucket> buckets = - histogram_tester->GetAllSamples(histogram_name); - size_t total_count = 0; - for (const auto& bucket : buckets) { - total_count += bucket.count; - } - if (total_count >= count) { - break; - } - } - } optimization_guide::testing::TestHintsComponentCreator test_hints_component_creator_; @@ -1729,10 +1741,6 @@ base::RunLoop().RunUntilIdle(); content::WaitForLoadStop(GetWebContents()); - histogram_tester.ExpectBucketCount( - "Previews.ServerLitePage.IneligibleReasons", - PreviewsLitePageNavigationThrottle::IneligibleReason::kPreviewsState, 1); - // Verify the committed previews type is resource loading hints. PreviewsUITabHelper* ui_tab_helper = PreviewsUITabHelper::FromWebContents(GetWebContents());
diff --git a/chrome/browser/previews/previews_lite_page_decider.cc b/chrome/browser/previews/previews_lite_page_decider.cc index b35e5a4f..61c833be 100644 --- a/chrome/browser/previews/previews_lite_page_decider.cc +++ b/chrome/browser/previews/previews_lite_page_decider.cc
@@ -188,6 +188,9 @@ DCHECK(handle->GetWebContents()); DCHECK(handle->GetWebContents()->GetBrowserContext()); + if (!handle->IsInMainFrame()) + return nullptr; + if (base::FeatureList::IsEnabled( previews::features::kHTTPSServerPreviewsUsingURLLoader)) { return nullptr;
diff --git a/chrome/browser/previews/previews_lite_page_navigation_throttle.cc b/chrome/browser/previews/previews_lite_page_navigation_throttle.cc index d06aa1a..b1f8c77 100644 --- a/chrome/browser/previews/previews_lite_page_navigation_throttle.cc +++ b/chrome/browser/previews/previews_lite_page_navigation_throttle.cc
@@ -64,22 +64,6 @@ const base::TimeDelta kBlacklistDuration = base::TimeDelta::FromDays(30); -bool IsPrivateDomain(const GURL& url) { - if (url.host().find(".") == base::StringPiece::npos) - return true; - - // Allow localhost check to be skipped if needed, like in testing. - if (net::IsLocalhost(url)) - return !previews::params::LitePagePreviewsTriggerOnLocalhost(); - - net::IPAddress ip_addr; - if (url.HostIsIPAddress() && ip_addr.AssignFromIPLiteral(url.host()) && - !ip_addr.IsPubliclyRoutable()) { - return true; - } - return false; -} - content::OpenURLParams MakeOpenURLParams(content::NavigationHandle* handle, GURL url, const std::string& headers) { @@ -291,120 +275,42 @@ PreviewsLitePageNavigationThrottle::~PreviewsLitePageNavigationThrottle() = default; +// static +void PreviewsLitePageNavigationThrottle::LogIneligibleReason( + IneligibleReason reason) { + UMA_HISTOGRAM_ENUMERATION("Previews.ServerLitePage.IneligibleReasons", + + reason); +} + bool PreviewsLitePageNavigationThrottle::IsEligibleForPreview() const { DCHECK(navigation_handle()->IsInMainFrame()); DCHECK_NE(navigation_handle()->GetReloadType(), content::ReloadType::ORIGINAL_REQUEST_URL); - // TODO(crbug.com/921755): Move all eligibility reasons to PreviewsState - // decision code and remove |ineligible_reasons|. - std::vector<IneligibleReason> ineligible_reasons; - - PreviewsUITabHelper* tab_helper = PreviewsUITabHelper::FromWebContents( - navigation_handle()->GetWebContents()); - previews::PreviewsUserData* previews_data = - tab_helper ? tab_helper->GetPreviewsUserData(navigation_handle()) - : nullptr; - if (!previews_data || !(previews_data->allowed_previews_state() & - content::LITE_PAGE_REDIRECT_ON)) { - ineligible_reasons.push_back(IneligibleReason::kPreviewsState); - } - - const GURL& url = navigation_handle()->GetURL(); - if (!url.SchemeIs(url::kHttpsScheme)) - ineligible_reasons.push_back(IneligibleReason::kNonHttpsScheme); - - if (manager_->IsServerUnavailable()) - ineligible_reasons.push_back(IneligibleReason::kServerUnavailable); - - if (g_browser_process->network_quality_tracker() - ->GetEffectiveConnectionType() == - net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) { - ineligible_reasons.push_back(IneligibleReason::kECTUnknown); - } - - if (g_browser_process->network_quality_tracker() - ->GetEffectiveConnectionType() > - previews::params::GetECTThresholdForPreview( - previews::PreviewsType::LITE_PAGE_REDIRECT)) { - ineligible_reasons.push_back(IneligibleReason::kNetworkNotSlow); - } - - content_settings::CookieSettings* cookie_settings = - CookieSettingsFactory::GetForProfile( - Profile::FromBrowserContext( - navigation_handle()->GetWebContents()->GetBrowserContext())) - .get(); - ContentSetting setting; - GURL previews_url = GetPreviewsURLForURL(url); - cookie_settings->GetCookieSetting(previews_url, previews_url, nullptr, - &setting); - if (!content_settings::CookieSettingsBase::IsAllowed(setting)) { - ineligible_reasons.push_back(IneligibleReason::kCookiesBlocked); - } if (data_reduction_proxy::HasURLRedirectCycle( navigation_handle()->GetRedirectChain()) || (GetServerLitePageInfo() && GetServerLitePageInfo()->restart_count >= previews::params::LitePageRedirectPreviewMaxNavigationRestarts())) { - ineligible_reasons.push_back( - IneligibleReason::kExceededMaxNavigationRestarts); - } - - // Record UMA. - for (IneligibleReason reason : ineligible_reasons) { - UMA_HISTOGRAM_ENUMERATION("Previews.ServerLitePage.IneligibleReasons", - reason); - } - if (!ineligible_reasons.empty()) - return false; - - // Check dynamic blacklists. - std::vector<BlacklistReason> blacklist_reasons; - - if (previews::IsLitePageRedirectPreviewDomain(url)) - blacklist_reasons.push_back(BlacklistReason::kNavigationToPreviewsDomain); - - if (IsPrivateDomain(url)) - blacklist_reasons.push_back(BlacklistReason::kNavigationToPrivateDomain); - - std::vector<std::string> blacklisted_path_suffixes = - previews::params::LitePagePreviewsBlacklistedPathSuffixes(); - for (const std::string& suffix : blacklisted_path_suffixes) { - if (base::EndsWith(url.path(), suffix, - base::CompareCase::INSENSITIVE_ASCII)) { - blacklist_reasons.push_back(BlacklistReason::kPathSuffixBlacklisted); - break; - } - } - - if (manager_->HostBlacklistedFromBypass(url.host())) - blacklist_reasons.push_back(BlacklistReason::kHostBypassBlacklisted); - - // Record UMA - for (BlacklistReason reason : blacklist_reasons) { - UMA_HISTOGRAM_ENUMERATION("Previews.ServerLitePage.BlacklistReasons", - reason); - } - - if (!blacklist_reasons.empty()) - return false; - - // This should always be at the end, but before the control group check. - if (manager_->NeedsToNotifyUser()) { - manager_->NotifyUser(navigation_handle()->GetWebContents()); - UMA_HISTOGRAM_ENUMERATION("Previews.ServerLitePage.IneligibleReasons", - IneligibleReason::kInfoBarNotSeen); + LogIneligibleReason(IneligibleReason::kExceededMaxNavigationRestarts); return false; } - // This should always be last. - if (previews::params::IsInLitePageRedirectControl()) { - previews::PreviewsUserData::ServerLitePageInfo* info = - GetOrCreateServerLitePageInfo(); - info->status = previews::ServerLitePageStatus::kControl; + PreviewsUITabHelper* tab_helper = PreviewsUITabHelper::FromWebContents( + navigation_handle()->GetWebContents()); + previews::PreviewsUserData* previews_data = + tab_helper ? (tab_helper->GetPreviewsUserData(navigation_handle())) + : nullptr; + + if (!previews_data || !(previews_data->allowed_previews_state() & + content::LITE_PAGE_REDIRECT_ON)) { return false; } + + if (previews::IsLitePageRedirectPreviewDomain(navigation_handle()->GetURL())) + return false; + return true; } @@ -483,7 +389,7 @@ navigation_handle()->GetWebContents()->GetBrowserContext(); previews::PreviewsUserData::ServerLitePageInfo* info = - GetOrCreateServerLitePageInfo(); + GetOrCreateServerLitePageInfo(navigation_handle(), manager_); // Set DRP headers. DataReductionProxyChromeSettings* drp_settings = @@ -586,11 +492,13 @@ base::PostTaskWithTraits( FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&PreviewsWebContentsLifetimeHelper::PostNewNavigation, - helper->GetWeakPtr(), - MakeOpenURLParams(navigation_handle(), - GURL(original_url), std::string()), - GetOrCreateServerLitePageInfo()->Clone())); + base::BindOnce( + &PreviewsWebContentsLifetimeHelper::PostNewNavigation, + helper->GetWeakPtr(), + MakeOpenURLParams(navigation_handle(), GURL(original_url), + std::string()), + GetOrCreateServerLitePageInfo(navigation_handle(), manager_) + ->Clone())); return content::NavigationThrottle::CANCEL; } @@ -674,7 +582,7 @@ LoadAndBypass( navigation_handle()->GetWebContents(), manager_, MakeOpenURLParams(navigation_handle(), GURL(original_url), std::string()), - GetServerLitePageInfo() ? GetServerLitePageInfo()->Clone() : nullptr, + GetOrCreateServerLitePageInfo(navigation_handle(), manager_)->Clone(), true); return content::NavigationThrottle::CANCEL; } @@ -710,7 +618,7 @@ UMA_HISTOGRAM_ENUMERATION("Previews.ServerLitePage.ServerResponse", ServerResponse::kOk); - GetOrCreateServerLitePageInfo()->status = + GetOrCreateServerLitePageInfo(navigation_handle(), manager_)->status = previews::ServerLitePageStatus::kSuccess; return content::NavigationThrottle::PROCEED; @@ -738,7 +646,7 @@ } previews::PreviewsUserData::ServerLitePageInfo* info = - GetOrCreateServerLitePageInfo(); + GetOrCreateServerLitePageInfo(navigation_handle(), manager_); info->status = previews::ServerLitePageStatus::kFailure; LoadAndBypass( navigation_handle()->GetWebContents(), manager_, @@ -771,15 +679,18 @@ info->status = status; } +// static previews::PreviewsUserData::ServerLitePageInfo* -PreviewsLitePageNavigationThrottle::GetOrCreateServerLitePageInfo() const { - PreviewsUITabHelper* ui_tab_helper = PreviewsUITabHelper::FromWebContents( - navigation_handle()->GetWebContents()); +PreviewsLitePageNavigationThrottle::GetOrCreateServerLitePageInfo( + content::NavigationHandle* navigation_handle, + PreviewsLitePageNavigationThrottleManager* manager) { + PreviewsUITabHelper* ui_tab_helper = + PreviewsUITabHelper::FromWebContents(navigation_handle->GetWebContents()); if (!ui_tab_helper) return nullptr; previews::PreviewsUserData* previews_data = - ui_tab_helper->GetPreviewsUserData(navigation_handle()); + ui_tab_helper->GetPreviewsUserData(navigation_handle); if (!previews_data) return nullptr; @@ -792,7 +703,7 @@ DataReductionProxyChromeSettings* drp_settings = DataReductionProxyChromeSettingsFactory::GetForBrowserContext( - navigation_handle()->GetWebContents()->GetBrowserContext()); + navigation_handle->GetWebContents()->GetBrowserContext()); base::Optional<std::string> session_id; if (drp_settings) { session_id = data_reduction_proxy::DataReductionProxyRequestOptions:: @@ -801,10 +712,10 @@ previews::PreviewsUserData::ServerLitePageInfo* info = previews_data->server_lite_page_info(); - info->original_navigation_start = navigation_handle()->NavigationStart(); + info->original_navigation_start = navigation_handle->NavigationStart(); if (session_id.has_value()) info->drp_session_key = session_id.value(); - info->page_id = manager_->GeneratePageID(); + info->page_id = manager->GeneratePageID(); return info; }
diff --git a/chrome/browser/previews/previews_lite_page_navigation_throttle.h b/chrome/browser/previews/previews_lite_page_navigation_throttle.h index 7fdf7fb..95782d3b 100644 --- a/chrome/browser/previews/previews_lite_page_navigation_throttle.h +++ b/chrome/browser/previews/previews_lite_page_navigation_throttle.h
@@ -57,13 +57,13 @@ kSubframeNavigation = 2, kServerUnavailable = 3, kInfoBarNotSeen = 4, - kNetworkNotSlow = 5, + kNetworkNotSlow_DEPRECATED = 5, kLoadOriginalReload = 6, kCookiesBlocked = 7, - kECTUnknown = 8, + kECTUnknown_DEPRECATED = 8, kExceededMaxNavigationRestarts = 9, - kPreviewsState = 10, - kMaxValue = kPreviewsState, + kPreviewsState_DEPRECATED = 10, + kMaxValue = kPreviewsState_DEPRECATED, }; // The response type from the previews server. This enum must @@ -116,6 +116,18 @@ std::unique_ptr<previews::PreviewsUserData::ServerLitePageInfo> info, bool use_post_task); + // Records an entry in the ineligibility histogram. + static void LogIneligibleReason(IneligibleReason reason); + + // Gets the ServerLitePageInfo struct from an existing attempted lite page + // navigation, if there is one. If not, returns a new ServerLitePageInfo + // initialized with metadata from navigation_handle() and |this| that is owned + // by the PreviewsUserData associated with navigation_handle(). + static previews::PreviewsUserData::ServerLitePageInfo* + GetOrCreateServerLitePageInfo( + content::NavigationHandle* navigation_handle, + PreviewsLitePageNavigationThrottleManager* manager); + private: // The current effective connection type; net::EffectiveConnectionType GetECT() const; @@ -149,13 +161,6 @@ // attempted lite page navigation, if there is one. If not, does nothing. void SetServerLitePageInfoStatus(previews::ServerLitePageStatus status); - // Gets the ServerLitePageInfo struct from an existing attempted lite page - // navigation, if there is one. If not, returns a new ServerLitePageInfo - // initialized with metadata from navigation_handle() and |this| that is owned - // by the PreviewsUserData associated with navigation_handle(). - previews::PreviewsUserData::ServerLitePageInfo* - GetOrCreateServerLitePageInfo() const; - // content::NavigationThrottle implementation: content::NavigationThrottle::ThrottleCheckResult WillStartRequest() override; content::NavigationThrottle::ThrottleCheckResult WillRedirectRequest()
diff --git a/chrome/browser/previews/previews_ui_tab_helper.cc b/chrome/browser/previews/previews_ui_tab_helper.cc index a851b57..9551a1f5 100644 --- a/chrome/browser/previews/previews_ui_tab_helper.cc +++ b/chrome/browser/previews/previews_ui_tab_helper.cc
@@ -26,6 +26,7 @@ #include "components/network_time/network_time_tracker.h" #include "components/offline_pages/buildflags/buildflags.h" #include "components/offline_pages/core/offline_page_item.h" +#include "components/previews/content/previews_decider_impl.h" #include "components/previews/content/previews_ui_service.h" #include "components/previews/core/previews_experiments.h" #include "components/previews/core/previews_features.h" @@ -34,6 +35,7 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" +#include "content/public/browser/reload_type.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "net/http/http_response_headers.h" @@ -265,6 +267,30 @@ is_stale_reload_ = is_reload; } +void PreviewsUITabHelper::DidStartNavigation( + content::NavigationHandle* navigation_handle) { + // If reloads are treated as soft opt outs, and this is a main frame reload + // from a preview. Report the Preview reload to the decider. + if (!base::FeatureList::IsEnabled( + previews::features::kPreviewsReloadsAreSoftOptOuts)) { + return; + } + if (navigation_handle->GetReloadType() == content::ReloadType::NONE) + return; + if (!navigation_handle->IsInMainFrame()) + return; + if (!previews_user_data_) + return; + + PreviewsService* previews_service = PreviewsServiceFactory::GetForProfile( + Profile::FromBrowserContext(web_contents()->GetBrowserContext())); + if (previews_service && previews_service->previews_ui_service()) { + previews_service->previews_ui_service() + ->previews_decider_impl() + ->AddPreviewReload(); + } +} + void PreviewsUITabHelper::DidFinishNavigation( content::NavigationHandle* navigation_handle) { // Delete Previews information later, so that other DidFinishNavigation
diff --git a/chrome/browser/previews/previews_ui_tab_helper.h b/chrome/browser/previews/previews_ui_tab_helper.h index 803d922..a8c69dd 100644 --- a/chrome/browser/previews/previews_ui_tab_helper.h +++ b/chrome/browser/previews/previews_ui_tab_helper.h
@@ -127,6 +127,8 @@ // Overridden from content::WebContentsObserver: void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; + void DidStartNavigation( + content::NavigationHandle* navigation_handle) override; // True if the UI for a preview has been shown for the page. bool displayed_preview_ui_ = false;
diff --git a/chrome/browser/previews/resource_loading_hints/resource_loading_hints_browsertest.cc b/chrome/browser/previews/resource_loading_hints/resource_loading_hints_browsertest.cc index e2c5b70d..e98dd233 100644 --- a/chrome/browser/previews/resource_loading_hints/resource_loading_hints_browsertest.cc +++ b/chrome/browser/previews/resource_loading_hints/resource_loading_hints_browsertest.cc
@@ -16,6 +16,8 @@ #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/metrics/subprocess_metrics_provider.h" +#include "chrome/browser/previews/previews_service.h" +#include "chrome/browser/previews/previews_service_factory.h" #include "chrome/browser/previews/resource_loading_hints/resource_loading_hints_web_contents_observer.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" @@ -26,6 +28,8 @@ #include "components/optimization_guide/optimization_guide_service.h" #include "components/optimization_guide/proto/hints.pb.h" #include "components/optimization_guide/test_hints_component_creator.h" +#include "components/previews/content/previews_decider_impl.h" +#include "components/previews/content/previews_optimization_guide.h" #include "components/previews/content/previews_ui_service.h" #include "components/previews/core/previews_black_list.h" #include "components/previews/core/previews_constants.h" @@ -132,15 +136,21 @@ // processed before returning. void ProcessHintsComponent( const optimization_guide::HintsComponentInfo& component_info) { - base::HistogramTester histogram_tester; - g_browser_process->optimization_guide_service()->MaybeUpdateHintsComponent( component_info); - RetryForHistogramUntilCountReached( - &histogram_tester, - previews::kPreviewsOptimizationGuideUpdateHintsResultHistogramString, - 1); + // Wait for hint update processing to complete. + base::RunLoop run_loop; + PreviewsServiceFactory::GetForProfile( + Profile::FromBrowserContext(browser() + ->tab_strip_model() + ->GetActiveWebContents() + ->GetBrowserContext())) + ->previews_ui_service() + ->previews_decider_impl() + ->previews_opt_guide() + ->ListenForNextUpdateForTesting(run_loop.QuitClosure()); + run_loop.Run(); } // Performs a navigation to |url| and waits for the the url's host's hints to
diff --git a/chrome/browser/profiles/profile_window.cc b/chrome/browser/profiles/profile_window.cc index 45ce578..cd04070 100644 --- a/chrome/browser/profiles/profile_window.cc +++ b/chrome/browser/profiles/profile_window.cc
@@ -435,6 +435,9 @@ case BrowserWindow::AVATAR_BUBBLE_MODE_SHOW_ERROR: *bubble_view_mode = BUBBLE_VIEW_MODE_PROFILE_CHOOSER; return; + case BrowserWindow::AVATAR_BUBBLE_MODE_INCOGNITO: + *bubble_view_mode = BUBBLE_VIEW_MODE_INCOGNITO; + return; default: *bubble_view_mode = profiles::BUBBLE_VIEW_MODE_PROFILE_CHOOSER; }
diff --git a/chrome/browser/push_messaging/push_messaging_notification_manager.cc b/chrome/browser/push_messaging/push_messaging_notification_manager.cc index f505b2a..dd38c7f 100644 --- a/chrome/browser/push_messaging/push_messaging_notification_manager.cc +++ b/chrome/browser/push_messaging/push_messaging_notification_manager.cc
@@ -36,6 +36,7 @@ #include "content/public/common/url_constants.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "third_party/blink/public/common/notifications/notification_resources.h" +#include "third_party/blink/public/mojom/notifications/notification.mojom-shared.h" #include "ui/base/l10n/l10n_util.h" #include "url/gurl.h" @@ -78,7 +79,7 @@ notification_data.title = url_formatter::FormatUrlForSecurityDisplay( origin, url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS); notification_data.direction = - blink::PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT; + blink::mojom::NotificationDirection::LEFT_TO_RIGHT; notification_data.body = l10n_util::GetStringUTF16(IDS_PUSH_MESSAGING_GENERIC_NOTIFICATION_BODY); notification_data.tag = kPushMessagingForcedNotificationTag;
diff --git a/chrome/browser/resource_coordinator/render_process_probe.cc b/chrome/browser/resource_coordinator/render_process_probe.cc index 19e5c35c..b268363 100644 --- a/chrome/browser/resource_coordinator/render_process_probe.cc +++ b/chrome/browser/resource_coordinator/render_process_probe.cc
@@ -10,7 +10,6 @@ #include "base/metrics/histogram_macros.h" #include "base/task/post_task.h" #include "build/build_config.h" -#include "chrome/browser/performance_manager/performance_manager.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" @@ -254,25 +253,14 @@ return info.process.Pid(); } -performance_manager::SystemResourceCoordinator* -RenderProcessProbeImpl::EnsureSystemResourceCoordinator() { - if (!system_resource_coordinator_) { - system_resource_coordinator_ = - std::make_unique<performance_manager::SystemResourceCoordinator>( - performance_manager::PerformanceManager::GetInstance()); - } - - return system_resource_coordinator_.get(); -} - void RenderProcessProbeImpl::DispatchMetricsOnUIThread( mojom::ProcessResourceMeasurementBatchPtr batch) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - performance_manager::SystemResourceCoordinator* system_resource_coordinator = - EnsureSystemResourceCoordinator(); + performance_manager::PerformanceManager* performance_manager = + performance_manager::PerformanceManager::GetInstance(); - if (system_resource_coordinator && !batch->measurements.empty()) - system_resource_coordinator->DistributeMeasurementBatch(std::move(batch)); + if (performance_manager && !batch->measurements.empty()) + performance_manager->DistributeMeasurementBatch(std::move(batch)); } } // namespace resource_coordinator
diff --git a/chrome/browser/resource_coordinator/render_process_probe.h b/chrome/browser/resource_coordinator/render_process_probe.h index a0f6299..02679a70 100644 --- a/chrome/browser/resource_coordinator/render_process_probe.h +++ b/chrome/browser/resource_coordinator/render_process_probe.h
@@ -14,7 +14,7 @@ #include "base/process/process.h" #include "base/process/process_metrics.h" #include "base/timer/timer.h" -#include "chrome/browser/performance_manager/system_resource_coordinator.h" +#include "chrome/browser/performance_manager/performance_manager.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" namespace resource_coordinator { @@ -94,9 +94,6 @@ virtual base::ProcessId GetProcessId(int host_id, const RenderProcessInfo& info); - performance_manager::SystemResourceCoordinator* - EnsureSystemResourceCoordinator(); - // Dispatch the collected metrics. // Virtual for testing. virtual void DispatchMetricsOnUIThread( @@ -113,10 +110,6 @@ // True while a gathering cycle is underways on a background thread. bool is_gathering_ = false; - // Used to signal the end of a CPU measurement cycle to the RC. - std::unique_ptr<performance_manager::SystemResourceCoordinator> - system_resource_coordinator_; - DISALLOW_COPY_AND_ASSIGN(RenderProcessProbeImpl); };
diff --git a/chrome/browser/resources/BUILD.gn b/chrome/browser/resources/BUILD.gn index f0ce95b..bda9504c 100644 --- a/chrome/browser/resources/BUILD.gn +++ b/chrome/browser/resources/BUILD.gn
@@ -44,6 +44,7 @@ if (is_android) { deps += [ "eoc_internals:closure_compile", + "feed_internals:closure_compile", "offline_pages:closure_compile", "snippets_internals:closure_compile", "webapks:closure_compile",
diff --git a/chrome/browser/resources/OWNERS b/chrome/browser/resources/OWNERS index c8178173..d7b19b2 100644 --- a/chrome/browser/resources/OWNERS +++ b/chrome/browser/resources/OWNERS
@@ -5,6 +5,5 @@ per-file profile_signin_confirmation*=achuith@chromium.org per-file snippets_internals*=file://components/ntp_snippets/OWNERS per-file sync_file_system_internals_resources.*=tzik@chromium.org -per-file policy*=file://chromeos/policy/OWNERS # COMPONENT: UI
diff --git a/chrome/browser/resources/app_management/BUILD.gn b/chrome/browser/resources/app_management/BUILD.gn index 3573cff..98fe769 100644 --- a/chrome/browser/resources/app_management/BUILD.gn +++ b/chrome/browser/resources/app_management/BUILD.gn
@@ -38,7 +38,7 @@ js_library("actions") { deps = [ - "//chrome/browser/ui/webui/app_management:mojo_bindings_js_externs", + "//chrome/browser/ui/webui/app_management:mojo_bindings_js_library_for_compile", "//ui/webui/resources/js:cr", ] } @@ -67,7 +67,7 @@ ":store_client", ":types", ":util", - "//chrome/browser/ui/webui/app_management:mojo_bindings_js_externs", + "//chrome/browser/ui/webui/app_management:mojo_bindings_js_library_for_compile", ] } @@ -93,7 +93,7 @@ js_library("browser_proxy") { deps = [ ":fake_page_handler", - "//chrome/browser/ui/webui/app_management:mojo_bindings_js_externs", + "//chrome/browser/ui/webui/app_management:mojo_bindings_js_library_for_compile", "//ui/webui/resources/js:cr", ] } @@ -125,7 +125,7 @@ ":constants", ":types", ":util", - "//chrome/browser/ui/webui/app_management:mojo_bindings_js_externs", + "//chrome/browser/ui/webui/app_management:mojo_bindings_js_library_for_compile", "//ui/webui/resources/js:cr", ] } @@ -238,7 +238,7 @@ js_library("types") { deps = [ - "//chrome/browser/ui/webui/app_management:mojo_bindings_js_externs", + "//chrome/browser/ui/webui/app_management:mojo_bindings_js_library_for_compile", ] }
diff --git a/chrome/browser/resources/app_management/dom_switch.js b/chrome/browser/resources/app_management/dom_switch.js index c6f40cec3..98f8354 100644 --- a/chrome/browser/resources/app_management/dom_switch.js +++ b/chrome/browser/resources/app_management/dom_switch.js
@@ -95,6 +95,10 @@ * @param {string} newRouteId */ onRouteChanged_: function(newRouteId) { + if (!this.instance_) { + return; + } + const newSelectedChild = this.children_[newRouteId]; assert( newSelectedChild,
diff --git a/chrome/browser/resources/app_management/metadata_view.js b/chrome/browser/resources/app_management/metadata_view.js index 93a9a4d..8e460439 100644 --- a/chrome/browser/resources/app_management/metadata_view.js +++ b/chrome/browser/resources/app_management/metadata_view.js
@@ -57,7 +57,7 @@ } app_management.BrowserProxy.getInstance().handler.setPinned( - this.app_.id, newPinnedValue); + this.app_.id, assert(newPinnedValue)); }, /**
diff --git a/chrome/browser/resources/app_management/permission_toggle.js b/chrome/browser/resources/app_management/permission_toggle.js index 77c3060..b0099c3d 100644 --- a/chrome/browser/resources/app_management/permission_toggle.js +++ b/chrome/browser/resources/app_management/permission_toggle.js
@@ -82,7 +82,7 @@ return app_management.util.createPermission( app_management.util.permissionTypeHandle(app, permissionType), - PermissionValueType.kBool, newPermissionValue); + PermissionValueType.kBool, assert(newPermissionValue)); }, /** @@ -114,6 +114,6 @@ return app_management.util.createPermission( app_management.util.permissionTypeHandle(app, permissionType), - PermissionValueType.kTriState, newPermissionValue); + PermissionValueType.kTriState, assert(newPermissionValue)); }, });
diff --git a/chrome/browser/resources/bluetooth_internals/BUILD.gn b/chrome/browser/resources/bluetooth_internals/BUILD.gn index 87fee4b0..88abbb1 100644 --- a/chrome/browser/resources/bluetooth_internals/BUILD.gn +++ b/chrome/browser/resources/bluetooth_internals/BUILD.gn
@@ -31,7 +31,7 @@ ] deps = [ - "//chrome/browser/ui/webui/bluetooth_internals:mojo_bindings_js_externs", + "//chrome/browser/ui/webui/bluetooth_internals:mojo_bindings_js_library_for_compile", "//ui/webui/resources/js:cr", "//ui/webui/resources/js:util", "//ui/webui/resources/js/cr/ui:array_data_model",
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_predicate.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_predicate.js index 2171259..4b1591c 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_predicate.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_predicate.js
@@ -480,7 +480,13 @@ * @return {boolean} */ AutomationPredicate.clickable = AutomationPredicate.match({ - anyPredicate: [AutomationPredicate.button, AutomationPredicate.link], + anyPredicate: [ + AutomationPredicate.button, AutomationPredicate.link, + (node) => { + return node.defaultActionVerb == + chrome.automation.DefaultActionVerb.CLICK; + } + ], anyAttribute: {clickable: true} });
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js index b2bb04ee..a31c0238 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js
@@ -1436,9 +1436,9 @@ else msg = Msgs.getMsg(info.msgId); } else { - var errorMsg = 'Missing role info for ' + node.role; - ruleStr.writeError(errorMsg); - console.error(errorMsg); + // We can safely ignore this role. ChromeVox output tests cover + // message id validity. + return; } this.append_(buff, msg || '', options); ruleStr.writeTokenWithValue(token, msg);
diff --git a/chrome/browser/resources/discards/BUILD.gn b/chrome/browser/resources/discards/BUILD.gn index 28b2fbfa..a49c5cb9 100644 --- a/chrome/browser/resources/discards/BUILD.gn +++ b/chrome/browser/resources/discards/BUILD.gn
@@ -31,7 +31,7 @@ deps = [ ":discards", ":sorted_table_behavior", - "//chrome/browser/ui/webui/discards:mojo_bindings_js_externs", + "//chrome/browser/ui/webui/discards:mojo_bindings_js_library_for_compile", "//ui/webui/resources/js:assert", "//ui/webui/resources/js:cr", ] @@ -41,7 +41,7 @@ deps = [ ":discards", ":sorted_table_behavior", - "//chrome/browser/ui/webui/discards:mojo_bindings_js_externs", + "//chrome/browser/ui/webui/discards:mojo_bindings_js_library_for_compile", "//ui/webui/resources/js:assert", "//ui/webui/resources/js:icon", "//ui/webui/resources/js:util", @@ -50,8 +50,8 @@ js_library("graph_tab") { deps = [ - "//chrome/browser/ui/webui/discards:mojo_bindings_js_externs", - "//services/resource_coordinator/public/mojom:mojom_js_externs", + "//chrome/browser/ui/webui/discards:mojo_bindings_js_library_for_compile", + "//services/resource_coordinator/public/mojom:mojom_js_library_for_compile", "//ui/webui/resources/js:assert", "//ui/webui/resources/js:cr", ] @@ -59,7 +59,7 @@ js_library("graph_doc") { deps = [ - "//services/resource_coordinator/public/mojom:mojom_js_externs", + "//services/resource_coordinator/public/mojom:mojom_js_library_for_compile", ] externs_list = [ "../../../../third_party/d3/src/externs.js" ]
diff --git a/chrome/browser/resources/downloads/BUILD.gn b/chrome/browser/resources/downloads/BUILD.gn index a8df7cbb9..395503e 100644 --- a/chrome/browser/resources/downloads/BUILD.gn +++ b/chrome/browser/resources/downloads/BUILD.gn
@@ -34,7 +34,7 @@ js_library("browser_proxy") { deps = [ - "//chrome/browser/ui/webui/downloads:mojo_bindings_js_externs", + "//chrome/browser/ui/webui/downloads:mojo_bindings_js_library_for_compile", "//ui/webui/resources/js:cr", ] externs_list = [ "externs.js" ]
diff --git a/chrome/browser/resources/engagement/BUILD.gn b/chrome/browser/resources/engagement/BUILD.gn index a98dcfb..56a3ba2b 100644 --- a/chrome/browser/resources/engagement/BUILD.gn +++ b/chrome/browser/resources/engagement/BUILD.gn
@@ -12,7 +12,7 @@ js_library("site_engagement") { deps = [ - "//chrome/browser/engagement:mojo_bindings_js_externs", + "//chrome/browser/engagement:mojo_bindings_js_library_for_compile", "//ui/webui/resources/js:assert", "//ui/webui/resources/js:util", ]
diff --git a/chrome/browser/resources/feed_internals/BUILD.gn b/chrome/browser/resources/feed_internals/BUILD.gn index 2b2288c..ff214d9 100644 --- a/chrome/browser/resources/feed_internals/BUILD.gn +++ b/chrome/browser/resources/feed_internals/BUILD.gn
@@ -11,9 +11,8 @@ } js_library("feed_internals") { - extra_deps = [ "//chrome/browser/ui/webui/feed_internals:mojo_bindings_js" ] - externs_list = [ - "$root_gen_dir/chrome/browser/ui/webui/feed_internals/feed_internals.mojom-lite.externs.js", - "$externs_path/mojo.js", + deps = [ + "//chrome/browser/ui/webui/feed_internals:mojo_bindings_js_library_for_compile", + "//ui/webui/resources/js:util", ] }
diff --git a/chrome/browser/resources/feed_internals/feed_internals.css b/chrome/browser/resources/feed_internals/feed_internals.css new file mode 100644 index 0000000..e65f136 --- /dev/null +++ b/chrome/browser/resources/feed_internals/feed_internals.css
@@ -0,0 +1,27 @@ +/* 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. */ + +h2 { + color: rgb(74, 142, 230); + font-size: 100%; + margin-bottom: 0.3em; + margin-top: 1em; +} + +table { + width: 100%; +} + +table > tbody > tr:nth-child(odd) { + background: rgb(239, 243, 255); +} + +table td { + width: 50%; +} + +button { + display: block; + min-height: 30px; +}
diff --git a/chrome/browser/resources/feed_internals/feed_internals.html b/chrome/browser/resources/feed_internals/feed_internals.html index df5acf4..735dc83 100644 --- a/chrome/browser/resources/feed_internals/feed_internals.html +++ b/chrome/browser/resources/feed_internals/feed_internals.html
@@ -11,14 +11,40 @@ <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Feed Internals</title> <link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> + <link rel="stylesheet" href="feed_internals.css"> <script src="chrome://resources/js/mojo_bindings_lite.js"></script> + <script src="chrome://resources/js/util.js"></script> <script src="feed_internals.mojom-lite.js"></script> <script src="feed_internals.js"></script> </head> <body> - TODO(chouinard): Implement this. + <h2>Properties</h2> + <table id="tblProperties"> + <tr> + <td>Is Feed Enabled</td> + <td id="isFeedEnabled"></td> + </tr> + </table> + <h2>User Classifier</h2> + <table id="tblUserClass"> + <tr> + <td>User Class Description</td> + <td id="userClassDescription"></td> + </tr> + <tr> + <td>Average Hours Between Suggestion Views</td> + <td id="avgHoursBetweenViews"></td> + </tr> + <tr> + <td>Average Hours Between Suggestion Uses</td> + <td id="avgHoursBetweenUses"></td> + </tr> + </table> + <button id="btnClearUserClassification"> + Clear User Classification + </button> </body> </html>
diff --git a/chrome/browser/resources/feed_internals/feed_internals.js b/chrome/browser/resources/feed_internals/feed_internals.js index 57f55000..bba1724e 100644 --- a/chrome/browser/resources/feed_internals/feed_internals.js +++ b/chrome/browser/resources/feed_internals/feed_internals.js
@@ -7,7 +7,39 @@ // Reference to the backend. let pageHandler = null; +(function() { +// Get and display general properties. +function updatePageWithProperties() { + pageHandler.getGeneralProperties().then(response => { + const properties = response.properties; + $('isFeedEnabled').textContent = properties.isFeedEnabled; + }); +} + +// Get and display user classifier properties. +function updatePageWithUserClass() { + pageHandler.getUserClassifierProperties().then(response => { + const properties = response.properties; + $('userClassDescription').textContent = properties.userClassDescription; + $('avgHoursBetweenViews').textContent = properties.avgHoursBetweenViews; + $('avgHoursBetweenUses').textContent = properties.avgHoursBetweenUses; + }); +} + +// Hook up buttons to event listeners. +function setupEventListeners() { + $('btnClearUserClassification').addEventListener('click', function() { + pageHandler.clearUserClassifierProperties(); + updatePageWithUserClass(); + }); +} + document.addEventListener('DOMContentLoaded', function() { // Setup backend mojo. pageHandler = feedInternals.mojom.PageHandler.getProxy(); + + updatePageWithProperties(); + updatePageWithUserClass(); + setupEventListeners(); }); +})();
diff --git a/chrome/browser/resources/local_ntp/PRESUBMIT.py b/chrome/browser/resources/local_ntp/PRESUBMIT.py new file mode 100644 index 0000000..9afd56da --- /dev/null +++ b/chrome/browser/resources/local_ntp/PRESUBMIT.py
@@ -0,0 +1,22 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +'Presubmit script for changes affecting chrome/browser/resources/local_ntp/' + +def NTPPresubmitChecks(input_api, output_api): + affected = input_api.change.AffectedFiles() + warning_str = ('Test HTML files in chrome/test/data/local_ntp/ should be ' + 'updated when making changes to local_ntp.html'); + if (any(f for f in affected if + f.LocalPath().endswith('local_ntp.html')) and + not any(f for f in affected if + f.LocalPath().endswith('local_ntp_browsertest.html'))): + return [output_api.PresubmitPromptWarning(warning_str)] + return [] + +def CheckChangeOnUpload(input_api, output_api): + return NTPPresubmitChecks(input_api, output_api) + +def CheckChangeOnCommit(input_api, output_api): + return NTPPresubmitChecks(input_api, output_api)
diff --git a/chrome/browser/resources/local_ntp/local_ntp.html b/chrome/browser/resources/local_ntp/local_ntp.html index de6f32f..e5199ad 100644 --- a/chrome/browser/resources/local_ntp/local_ntp.html +++ b/chrome/browser/resources/local_ntp/local_ntp.html
@@ -29,8 +29,6 @@ <meta name="google" value="notranslate"> <meta name="referrer" content="strict-origin"> </head> -<!-- Remember to update the test HTML files in chrome/test/data/local_ntp/ - whenever making changes to this file.--> <body> <div id="custom-bg"></div> <!-- Container for the OneGoogleBar HTML. -->
diff --git a/chrome/browser/resources/md_extensions/activity_log/BUILD.gn b/chrome/browser/resources/md_extensions/activity_log/BUILD.gn index 409b3107..2b6d957 100644 --- a/chrome/browser/resources/md_extensions/activity_log/BUILD.gn +++ b/chrome/browser/resources/md_extensions/activity_log/BUILD.gn
@@ -8,13 +8,13 @@ deps = [ ":activity_log", ":activity_log_history", - ":activity_log_item", + ":activity_log_history_item", ":activity_log_stream", ":activity_log_stream_item", ] } -js_library("activity_log_item") { +js_library("activity_log_history_item") { deps = [ "//ui/webui/resources/js:cr", ] @@ -23,7 +23,7 @@ js_library("activity_log_history") { deps = [ - ":activity_log_item", + ":activity_log_history_item", "//ui/webui/resources/js:cr", ] externs_list = [ "$externs_path/activity_log_private.js" ]
diff --git a/chrome/browser/resources/md_extensions/activity_log/activity_log_history.html b/chrome/browser/resources/md_extensions/activity_log/activity_log_history.html index 6bcf9478..ed61731 100644 --- a/chrome/browser/resources/md_extensions/activity_log/activity_log_history.html +++ b/chrome/browser/resources/md_extensions/activity_log/activity_log_history.html
@@ -2,7 +2,7 @@ <link rel="import" href="chrome://resources/html/cr.html"> <link rel="import" href="chrome://resources/html/promise_resolver.html"> -<link rel="import" href="activity_log_item.html"> +<link rel="import" href="activity_log_history_item.html"> <link rel="import" href="../shared_style.html"> <dom-module id="activity-log-history"> @@ -21,8 +21,8 @@ <div id="activity-list" hidden$="[[!shouldShowActivities_(pageState_, activityData_)]]"> <template is="dom-repeat" items="[[activityData_]]"> - <activity-log-item data="[[item]]"> - </activity-log-item> + <activity-log-history-item data="[[item]]"> + </activity-log-history-item> </template> </div> </template>
diff --git a/chrome/browser/resources/md_extensions/activity_log/activity_log_item.html b/chrome/browser/resources/md_extensions/activity_log/activity_log_history_item.html similarity index 97% rename from chrome/browser/resources/md_extensions/activity_log/activity_log_item.html rename to chrome/browser/resources/md_extensions/activity_log/activity_log_history_item.html index 7fbcae5..386933d 100644 --- a/chrome/browser/resources/md_extensions/activity_log/activity_log_item.html +++ b/chrome/browser/resources/md_extensions/activity_log/activity_log_history_item.html
@@ -8,7 +8,7 @@ <link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html"> <link rel="import" href="../shared_vars.html"> -<dom-module id="activity-log-item"> +<dom-module id="activity-log-history-item"> <template> <style include="cr-icons cr-shared-style shared-style"> :host { @@ -113,5 +113,5 @@ </div> </iron-collapse> </template> - <script src="activity_log_item.js"></script> + <script src="activity_log_history_item.js"></script> </dom-module>
diff --git a/chrome/browser/resources/md_extensions/activity_log/activity_log_item.js b/chrome/browser/resources/md_extensions/activity_log/activity_log_history_item.js similarity index 92% rename from chrome/browser/resources/md_extensions/activity_log/activity_log_item.js rename to chrome/browser/resources/md_extensions/activity_log/activity_log_history_item.js index 44fc002..62869e4d 100644 --- a/chrome/browser/resources/md_extensions/activity_log/activity_log_item.js +++ b/chrome/browser/resources/md_extensions/activity_log/activity_log_history_item.js
@@ -26,10 +26,8 @@ */ let PageUrlItem; - // TODO(kelvinjiang): Replace |activity_log_item| with - // |activity_log_history_item|. - const ActivityLogItem = Polymer({ - is: 'activity-log-item', + const ActivityLogHistoryItem = Polymer({ + is: 'activity-log-history-item', properties: { /** @@ -105,7 +103,7 @@ }); return { - ActivityLogItem: ActivityLogItem, + ActivityLogHistoryItem: ActivityLogHistoryItem, ActivityGroup: ActivityGroup, }; });
diff --git a/chrome/browser/resources/md_extensions/extensions_resources.grd b/chrome/browser/resources/md_extensions/extensions_resources.grd index 3fa16bc6..4892a52 100644 --- a/chrome/browser/resources/md_extensions/extensions_resources.grd +++ b/chrome/browser/resources/md_extensions/extensions_resources.grd
@@ -41,11 +41,11 @@ <structure name="IDR_MD_EXTENSIONS_ACTIVITY_LOG_ACTIVITY_LOG_HISTORY_JS" file="activity_log/activity_log_history.js" type="chrome_html" /> - <structure name="IDR_MD_EXTENSIONS_ACTIVITY_LOG_ACTIVITY_LOG_ITEM_HTML" - file="activity_log/activity_log_item.html" + <structure name="IDR_MD_EXTENSIONS_ACTIVITY_LOG_ACTIVITY_LOG_HISTORY_ITEM_HTML" + file="activity_log/activity_log_history_item.html" type="chrome_html" /> - <structure name="IDR_MD_EXTENSIONS_ACTIVITY_LOG_ACTIVITY_LOG_ITEM_JS" - file="activity_log/activity_log_item.js" + <structure name="IDR_MD_EXTENSIONS_ACTIVITY_LOG_ACTIVITY_LOG_HISTORY_ITEM_JS" + file="activity_log/activity_log_history_item.js" type="chrome_html" /> <structure name="IDR_MD_EXTENSIONS_ACTIVITY_LOG_ACTIVITY_LOG_STREAM_HTML" file="activity_log/activity_log_stream.html"
diff --git a/chrome/browser/resources/omnibox/BUILD.gn b/chrome/browser/resources/omnibox/BUILD.gn index 155099d..43217f62 100644 --- a/chrome/browser/resources/omnibox/BUILD.gn +++ b/chrome/browser/resources/omnibox/BUILD.gn
@@ -12,16 +12,10 @@ js_library("omnibox") { deps = [ - "//ui/webui/resources/js:util", ":omnibox_element", ":omnibox_input", ":omnibox_output", - ] - extra_deps = [ "//chrome/browser/ui/webui/omnibox:mojo_bindings_js" ] - externs_list = [ - "$root_gen_dir/chrome/browser/ui/webui/omnibox/omnibox.mojom-lite.externs.js", - "$externs_path/mojo.js", - "$externs_path/pending.js", + "//chrome/browser/ui/webui/omnibox:mojo_bindings_js_library_for_compile", ] } @@ -32,4 +26,7 @@ } js_library("omnibox_output") { + deps = [ + "//ui/webui/resources/js:util", + ] }
diff --git a/chrome/browser/resources/policy/OWNERS b/chrome/browser/resources/policy/OWNERS new file mode 100644 index 0000000..65f14a9c --- /dev/null +++ b/chrome/browser/resources/policy/OWNERS
@@ -0,0 +1,3 @@ +file://chromeos/policy/OWNERS + +# COMPONENT: Enterprise \ No newline at end of file
diff --git a/chrome/browser/resources/policy.css b/chrome/browser/resources/policy/policy.css similarity index 92% rename from chrome/browser/resources/policy.css rename to chrome/browser/resources/policy/policy.css index 0744dea6..14a700e 100644 --- a/chrome/browser/resources/policy.css +++ b/chrome/browser/resources/policy/policy.css
@@ -5,7 +5,7 @@ @import 'policy_common.css'; #status-box-container { - display: -webkit-flex; + display: flex; } fieldset { @@ -20,7 +20,7 @@ } div.status-entry { - display: -webkit-flex; + display: flex; margin-bottom: .8em; }
diff --git a/chrome/browser/resources/policy.html b/chrome/browser/resources/policy/policy.html similarity index 98% rename from chrome/browser/resources/policy.html rename to chrome/browser/resources/policy/policy.html index 938c57a..20905be 100644 --- a/chrome/browser/resources/policy.html +++ b/chrome/browser/resources/policy/policy.html
@@ -6,7 +6,7 @@ <title>$i18n{title}</title> <link rel="stylesheet" href="chrome://resources/css/chrome_shared.css"> -<link rel="stylesheet" href="uber_shared.css"> +<link rel="stylesheet" href="../uber_shared.css"> <link rel="stylesheet" href="chrome://policy/policy.css"> <script src="chrome://resources/js/action_link.js"></script>
diff --git a/chrome/browser/resources/policy.js b/chrome/browser/resources/policy/policy.js similarity index 100% rename from chrome/browser/resources/policy.js rename to chrome/browser/resources/policy/policy.js
diff --git a/chrome/browser/resources/policy_android.css b/chrome/browser/resources/policy/policy_android.css similarity index 95% rename from chrome/browser/resources/policy_android.css rename to chrome/browser/resources/policy/policy_android.css index e511a0c0..d2dbfb2 100644 --- a/chrome/browser/resources/policy_android.css +++ b/chrome/browser/resources/policy/policy_android.css
@@ -26,7 +26,7 @@ } body header > h1 { - margin-left: 10px; + margin-inline-start: 10px; } body section { @@ -39,7 +39,7 @@ } #status-box-container { - display: -webkit-flex; + display: flex; } fieldset { @@ -54,7 +54,7 @@ } div.status-entry { - display: -webkit-flex; + display: flex; margin-bottom: .8em; } @@ -69,12 +69,12 @@ #show-unset-container { float: right; - text-align: right; + text-align: end; } html[dir='rtl'] #show-unset-container { float: left; - text-align: left; + text-align: start; } div.reload-policies-button {
diff --git a/chrome/browser/resources/policy_base.js b/chrome/browser/resources/policy/policy_base.js similarity index 99% rename from chrome/browser/resources/policy_base.js rename to chrome/browser/resources/policy/policy_base.js index d659374..c4c4217 100644 --- a/chrome/browser/resources/policy_base.js +++ b/chrome/browser/resources/policy/policy_base.js
@@ -3,7 +3,6 @@ // found in the LICENSE file. cr.define('policy', function() { - /** * A hack to check if we are displaying the mobile version of this page by * checking if the first column is hidden.
diff --git a/chrome/browser/resources/policy_common.css b/chrome/browser/resources/policy/policy_common.css similarity index 97% rename from chrome/browser/resources/policy_common.css rename to chrome/browser/resources/policy/policy_common.css index 2a456ce..1aff113 100644 --- a/chrome/browser/resources/policy_common.css +++ b/chrome/browser/resources/policy/policy_common.css
@@ -37,12 +37,12 @@ #show-unset-container { float: right; - text-align: right; + text-align: end; } html[dir='rtl'] #show-unset-container { float: left; - text-align: left; + text-align: start; } div.show-unset-checkbox {
diff --git a/chrome/browser/resources/settings/bluetooth_page/BUILD.gn b/chrome/browser/resources/settings/bluetooth_page/BUILD.gn index 3113995..c2fdc84 100644 --- a/chrome/browser/resources/settings/bluetooth_page/BUILD.gn +++ b/chrome/browser/resources/settings/bluetooth_page/BUILD.gn
@@ -61,6 +61,6 @@ js_library("bluetooth_system_on_extensions") { sources = [] deps = [ - "//services/device/public/mojom:mojom_js_externs", + "//services/device/public/mojom:mojom_js_library_for_compile", ] }
diff --git a/chrome/browser/resources/settings/multidevice_page/multidevice_page.html b/chrome/browser/resources/settings/multidevice_page/multidevice_page.html index 04fbc1ce..d16ab4e 100644 --- a/chrome/browser/resources/settings/multidevice_page/multidevice_page.html +++ b/chrome/browser/resources/settings/multidevice_page/multidevice_page.html
@@ -110,7 +110,8 @@ </template> </settings-animated-pages> <template is="dom-if" if="[[showPasswordPromptDialog_]]" restamp> - <settings-password-prompt-dialog id="multidevicePasswordPrompt"> + <settings-password-prompt-dialog id="multidevicePasswordPrompt" + auth-token="{{authToken_}}"> </settings-password-prompt-dialog> </template> </template>
diff --git a/chrome/browser/resources/settings/site_settings/site_entry.html b/chrome/browser/resources/settings/site_settings/site_entry.html index f646149..cf6385a1 100644 --- a/chrome/browser/resources/settings/site_settings/site_entry.html +++ b/chrome/browser/resources/settings/site_settings/site_entry.html
@@ -38,13 +38,13 @@ unicode-bidi: isolate; } - #collapseChild .data-unit { - padding-inline-start: 1ch; - } - .list-frame { padding-inline-end: 0; } + + .spacing { + padding-inline-start: 1ch; + } </style> <div id="collapseParent" focus-row-container> <div class$="settings-box list-item [[getClassForIndex_(listIndex)]]"> @@ -117,12 +117,17 @@ hidden$="[[!scheme_(siteGroup, index)]]"> [[scheme_(siteGroup, index)]] </span> + <!--Define a spacing span so that when the direction is rtl, + the spacing is still showing correctly. This is because the + data-unit class is set to be ltr so the padding will be in + wrong place if we put padding in that span.--> + <span class="spacing" hidden$="[[!item.usage]]"></span> <span class="secondary data-unit" hidden$="[[!item.usage]]"> [[originUsagesItem_(originUsages_.*, index)]] </span> - <span class="secondary data-unit" - hidden$="[[!item.numCookies]]"> - · [[originCookiesItem_(cookiesNum_.*, index)]] + <span class="secondary" hidden$="[[!item.numCookies]]"> + · + [[originCookiesItem_(cookiesNum_.*, index)]] </span> </div> <paper-icon-button-light class="subpage-arrow">
diff --git a/chrome/browser/resources/settings/site_settings/site_entry.js b/chrome/browser/resources/settings/site_settings/site_entry.js index b845ee4..ad387e8 100644 --- a/chrome/browser/resources/settings/site_settings/site_entry.js +++ b/chrome/browser/resources/settings/site_settings/site_entry.js
@@ -199,14 +199,34 @@ /** * Get an appropriate favicon that represents this group of eTLD+1 sites as a * whole. - * @param {SiteGroup} siteGroup The eTLD+1 group of origins. + * @param {!SiteGroup} siteGroup The eTLD+1 group of origins. * @return {string} URL that is used for fetching the favicon * @private */ getSiteGroupIcon_: function(siteGroup) { - // TODO(https://crbug.com/835712): Implement heuristic for finding a good - // favicon. - return siteGroup.origins[0].origin; + const origins = siteGroup.origins; + assert(origins); + assert(origins.length >= 1); + if (origins.length == 1) { + return origins[0].origin; + } + // If we can find a origin with format "www.etld+1", use the favicon of this + // origin. Otherwise find the origin with largest storage, and use the + // number of cookies as a tie breaker. + for (const originInfo of origins) { + if (this.toUrl(originInfo.origin).host == 'www.' + siteGroup.etldPlus1) { + return originInfo.origin; + } + } + const getMaxStorage = (max, originInfo) => { + return ( + max.usage > originInfo.usage || + (max.usage == originInfo.usage && + max.numCookies > originInfo.numCookies) ? + max : + originInfo); + }; + return origins.reduce(getMaxStorage, origins[0]).origin; }, /**
diff --git a/chrome/browser/resources/usb_internals/BUILD.gn b/chrome/browser/resources/usb_internals/BUILD.gn index 763a0faa..0a3f82b 100644 --- a/chrome/browser/resources/usb_internals/BUILD.gn +++ b/chrome/browser/resources/usb_internals/BUILD.gn
@@ -16,7 +16,7 @@ ] deps = [ - "//chrome/browser/ui/webui/usb_internals:mojo_bindings_js_externs", + "//chrome/browser/ui/webui/usb_internals:mojo_bindings_js_library_for_compile", "//ui/webui/resources/js:cr", "//ui/webui/resources/js:util", "//ui/webui/resources/js/cr/ui:tabs",
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/shared/chooser_shared_css.html b/chrome/browser/resources/welcome/onboarding_welcome/shared/chooser_shared_css.html index 9870fbc..f9e2430 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/shared/chooser_shared_css.html +++ b/chrome/browser/resources/welcome/onboarding_welcome/shared/chooser_shared_css.html
@@ -20,6 +20,7 @@ box-shadow: 0 1px 2px 0 rgba(0, 36, 100, .3), 0 3px 6px 2px rgba(0, 36, 100, .15); box-sizing: border-box; + cursor: pointer; display: inline-flex; flex-direction: column; font-family: inherit; @@ -105,7 +106,7 @@ margin-top: 4rem; } - :host-context([dir=rtl]) iron-icon { + :host-context([dir=rtl]) iron-icon[icon='cr:chevron-right'] { transform: scaleX(-1); }
diff --git a/chrome/browser/safe_browsing/download_protection/check_client_download_request.cc b/chrome/browser/safe_browsing/download_protection/check_client_download_request.cc index 5b0eb7b..5570560 100644 --- a/chrome/browser/safe_browsing/download_protection/check_client_download_request.cc +++ b/chrome/browser/safe_browsing/download_protection/check_client_download_request.cc
@@ -445,6 +445,8 @@ signature_info_ = results.signature_info; image_headers_.reset(new ClientDownloadRequest_ImageHeaders()); *image_headers_ = results.image_headers; + file_count_ = results.file_count; + directory_count_ = results.directory_count; #if defined(OS_MACOSX) if (!results.disk_image_signature.empty()) @@ -700,6 +702,8 @@ request->set_allocated_image_headers(image_headers_.release()); if (!archived_binaries_.empty()) request->mutable_archived_binary()->Swap(&archived_binaries_); + request->set_archive_file_count(file_count_); + request->set_archive_directory_count(directory_count_); if (!request->SerializeToString(&client_download_request_data_)) { FinishRequest(DownloadCheckResult::UNKNOWN, REASON_INVALID_REQUEST_PROTO); return;
diff --git a/chrome/browser/safe_browsing/download_protection/check_client_download_request.h b/chrome/browser/safe_browsing/download_protection/check_client_download_request.h index af72d113..5571249 100644 --- a/chrome/browser/safe_browsing/download_protection/check_client_download_request.h +++ b/chrome/browser/safe_browsing/download_protection/check_client_download_request.h
@@ -134,6 +134,8 @@ bool is_extended_reporting_; bool is_incognito_; bool is_under_advanced_protection_; + int file_count_; + int directory_count_; base::WeakPtrFactory<CheckClientDownloadRequest> weakptr_factory_;
diff --git a/chrome/browser/safe_browsing/download_protection/file_analyzer.cc b/chrome/browser/safe_browsing/download_protection/file_analyzer.cc index be01921a..8201624 100644 --- a/chrome/browser/safe_browsing/download_protection/file_analyzer.cc +++ b/chrome/browser/safe_browsing/download_protection/file_analyzer.cc
@@ -69,7 +69,7 @@ } // namespace -FileAnalyzer::Results::Results() {} +FileAnalyzer::Results::Results() : file_count(0), directory_count(0) {} FileAnalyzer::Results::~Results() {} FileAnalyzer::Results::Results(const FileAnalyzer::Results& other) = default; @@ -208,6 +208,9 @@ results_.type = ClientDownloadRequest::ZIPPED_EXECUTABLE; } + results_.file_count = archive_results.file_count; + results_.directory_count = archive_results.directory_count; + std::move(callback_).Run(std::move(results_)); }
diff --git a/chrome/browser/safe_browsing/download_protection/file_analyzer.h b/chrome/browser/safe_browsing/download_protection/file_analyzer.h index a1f5abf..99684ff 100644 --- a/chrome/browser/safe_browsing/download_protection/file_analyzer.h +++ b/chrome/browser/safe_browsing/download_protection/file_analyzer.h
@@ -72,6 +72,12 @@ ClientDownloadRequest::DetachedCodeSignature> detached_code_signatures; #endif + + // For archive files, the number of contained files. + int file_count; + + // For archive files, the number of contained directories. + int directory_count; }; explicit FileAnalyzer(
diff --git a/chrome/browser/safe_browsing/download_protection/file_analyzer_unittest.cc b/chrome/browser/safe_browsing/download_protection/file_analyzer_unittest.cc index 511f495..b00616c9 100644 --- a/chrome/browser/safe_browsing/download_protection/file_analyzer_unittest.cc +++ b/chrome/browser/safe_browsing/download_protection/file_analyzer_unittest.cc
@@ -768,4 +768,65 @@ EXPECT_TRUE(result_.archived_binaries.Get(0).digests().sha256().empty()); } +TEST_F(FileAnalyzerTest, ZipFilesGetFileCount) { + scoped_refptr<MockBinaryFeatureExtractor> extractor = + new testing::StrictMock<MockBinaryFeatureExtractor>(); + FileAnalyzer analyzer(extractor); + base::RunLoop run_loop; + + base::FilePath target_path(FILE_PATH_LITERAL("target.zip")); + base::FilePath tmp_path = + temp_dir_.GetPath().Append(FILE_PATH_LITERAL("tmp.crdownload")); + + base::ScopedTempDir zip_source_dir; + ASSERT_TRUE(zip_source_dir.CreateUniqueTempDir()); + std::string file_contents = "dummy file"; + ASSERT_EQ(static_cast<int>(file_contents.size()), + base::WriteFile( + zip_source_dir.GetPath().Append(FILE_PATH_LITERAL("file.exe")), + file_contents.data(), file_contents.size())); + ASSERT_TRUE(zip::Zip(zip_source_dir.GetPath(), tmp_path, + /* include_hidden_files= */ + false)); + + analyzer.Start( + target_path, tmp_path, + base::BindOnce(&FileAnalyzerTest::DoneCallback, base::Unretained(this), + run_loop.QuitClosure())); + run_loop.Run(); + + ASSERT_TRUE(has_result_); + EXPECT_EQ(1, result_.file_count); + EXPECT_EQ(0, result_.directory_count); +} + +TEST_F(FileAnalyzerTest, ZipFilesGetDirectoryCount) { + scoped_refptr<MockBinaryFeatureExtractor> extractor = + new testing::StrictMock<MockBinaryFeatureExtractor>(); + FileAnalyzer analyzer(extractor); + base::RunLoop run_loop; + + base::FilePath target_path(FILE_PATH_LITERAL("target.zip")); + base::FilePath tmp_path = + temp_dir_.GetPath().Append(FILE_PATH_LITERAL("tmp.crdownload")); + + base::ScopedTempDir zip_source_dir; + ASSERT_TRUE(zip_source_dir.CreateUniqueTempDir()); + ASSERT_TRUE(base::CreateDirectory( + zip_source_dir.GetPath().Append(FILE_PATH_LITERAL("direcotry")))); + ASSERT_TRUE(zip::Zip(zip_source_dir.GetPath(), tmp_path, + /* include_hidden_files= */ + false)); + + analyzer.Start( + target_path, tmp_path, + base::BindOnce(&FileAnalyzerTest::DoneCallback, base::Unretained(this), + run_loop.QuitClosure())); + run_loop.Run(); + + ASSERT_TRUE(has_result_); + EXPECT_EQ(0, result_.file_count); + EXPECT_EQ(1, result_.directory_count); +} + } // namespace safe_browsing
diff --git a/chrome/browser/sessions/session_restore_browsertest.cc b/chrome/browser/sessions/session_restore_browsertest.cc index 3d8427d..158fcf1 100644 --- a/chrome/browser/sessions/session_restore_browsertest.cc +++ b/chrome/browser/sessions/session_restore_browsertest.cc
@@ -1622,10 +1622,6 @@ } IN_PROC_BROWSER_TEST_F(SmartSessionRestoreTest, MAYBE_CorrectLoadingOrder) { - // TODO(https://crbug.com/923051): Flaky in single process mash. - if (features::IsSingleProcessMash()) - return; - const int activation_order[] = {4, 2, 5, 0, 3, 1}; Profile* profile = browser()->profile();
diff --git a/chrome/browser/signin/identity_manager_factory.cc b/chrome/browser/signin/identity_manager_factory.cc index e20ce31..3b4acc52 100644 --- a/chrome/browser/signin/identity_manager_factory.cc +++ b/chrome/browser/signin/identity_manager_factory.cc
@@ -17,6 +17,7 @@ #include "services/identity/public/cpp/accounts_cookie_mutator.h" #include "services/identity/public/cpp/accounts_cookie_mutator_impl.h" #include "services/identity/public/cpp/accounts_mutator.h" +#include "services/identity/public/cpp/diagnostics_provider_impl.h" #include "services/identity/public/cpp/identity_manager.h" #include "services/identity/public/cpp/primary_account_mutator.h" @@ -80,6 +81,9 @@ BuildPrimaryAccountMutator(profile), BuildAccountsMutator(profile), std::make_unique<identity::AccountsCookieMutatorImpl>( + GaiaCookieManagerServiceFactory::GetForProfile(profile)), + std::make_unique<identity::DiagnosticsProviderImpl>( + ProfileOAuth2TokenServiceFactory::GetForProfile(profile), GaiaCookieManagerServiceFactory::GetForProfile(profile))) {} };
diff --git a/chrome/browser/sync/profile_sync_service_android.cc b/chrome/browser/sync/profile_sync_service_android.cc index 6448034..1f71ac5 100644 --- a/chrome/browser/sync/profile_sync_service_android.cc +++ b/chrome/browser/sync/profile_sync_service_android.cc
@@ -4,57 +4,48 @@ #include "chrome/browser/sync/profile_sync_service_android.h" -#include <stddef.h> -#include <stdint.h> - #include <string> #include <vector> #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/bind.h" +#include "base/callback.h" #include "base/i18n/time_formatting.h" #include "base/json/json_writer.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" +#include "base/time/time.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/sync/device_info_sync_service_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/session_sync_service_factory.h" -#include "chrome/browser/sync/sync_ui_util.h" -#include "chrome/common/channel_info.h" #include "chrome/grit/generated_resources.h" #include "components/browser_sync/profile_sync_service.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/account_info.h" #include "components/strings/grit/components_strings.h" #include "components/sync/base/model_type.h" -#include "components/sync/base/pref_names.h" #include "components/sync/device_info/device_info.h" #include "components/sync/device_info/device_info_sync_service.h" #include "components/sync/device_info/device_info_tracker.h" -#include "components/sync/driver/about_sync_util.h" #include "components/sync/driver/sync_service_utils.h" #include "components/sync/engine/net/network_resources.h" #include "components/sync_sessions/session_sync_service.h" #include "components/unified_consent/url_keyed_data_collection_consent_helper.h" #include "content/public/browser/browser_thread.h" -#include "google/cacheinvalidation/types.pb.h" -#include "google_apis/gaia/gaia_constants.h" +#include "google_apis/gaia/google_service_auth_error.h" #include "jni/ProfileSyncService_jni.h" #include "ui/base/l10n/l10n_util.h" using base::android::AttachCurrentThread; -using base::android::CheckException; using base::android::ConvertJavaStringToUTF8; using base::android::ConvertUTF8ToJavaString; using base::android::JavaParamRef; using base::android::ScopedJavaLocalRef; -using browser_sync::ProfileSyncService; using content::BrowserThread; -using syncer::DeviceInfo; using unified_consent::UrlKeyedDataCollectionConsentHelper; namespace { @@ -105,8 +96,6 @@ return; } - sync_prefs_ = std::make_unique<syncer::SyncPrefs>(profile_->GetPrefs()); - sync_service_ = ProfileSyncServiceFactory::GetAsProfileSyncServiceForProfile(profile_); } @@ -391,19 +380,17 @@ return status.sync_protocol_error.action; } -// Pure SyncPrefs calls. - jboolean ProfileSyncServiceAndroid::IsPassphrasePrompted( JNIEnv* env, const JavaParamRef<jobject>& obj) { - return sync_prefs_->IsPassphrasePrompted(); + return sync_service_->IsPassphrasePrompted(); } void ProfileSyncServiceAndroid::SetPassphrasePrompted( JNIEnv* env, const JavaParamRef<jobject>& obj, jboolean prompted) { - sync_prefs_->SetPassphrasePrompted(prompted); + sync_service_->SetPassphrasePrompted(prompted); } void ProfileSyncServiceAndroid::SetSyncSessionsId( @@ -421,7 +408,7 @@ JNIEnv* env, const JavaParamRef<jobject>&) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - return sync_prefs_->HasKeepEverythingSynced(); + return sync_service_->GetUserSettings()->IsSyncEverythingEnabled(); } // UI string getters. @@ -477,7 +464,7 @@ if (!device_sync_service) { return 0; } - const std::vector<std::unique_ptr<DeviceInfo>>& all_devices = + const std::vector<std::unique_ptr<syncer::DeviceInfo>> all_devices = device_sync_service->GetDeviceInfoTracker()->GetAllDeviceInfo(); return all_devices.size(); } @@ -496,11 +483,9 @@ jlong ProfileSyncServiceAndroid::GetLastSyncedTimeForTest( JNIEnv* env, const JavaParamRef<jobject>& obj) { - // Use profile preferences here instead of SyncPrefs to avoid an extra - // conversion, since SyncPrefs::GetLastSyncedTime() converts the stored value - // to to base::Time. + base::Time last_sync_time = sync_service_->GetLastSyncedTime(); return static_cast<jlong>( - profile_->GetPrefs()->GetInt64(syncer::prefs::kSyncLastSyncedTime)); + (last_sync_time - base::Time::UnixEpoch()).InMicroseconds()); } void ProfileSyncServiceAndroid::OverrideNetworkResourcesForTest(
diff --git a/chrome/browser/sync/profile_sync_service_android.h b/chrome/browser/sync/profile_sync_service_android.h index de3c09f..354856af 100644 --- a/chrome/browser/sync/profile_sync_service_android.h +++ b/chrome/browser/sync/profile_sync_service_android.h
@@ -5,19 +5,11 @@ #ifndef CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_ANDROID_H_ #define CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_ANDROID_H_ -#include <map> #include <memory> #include "base/android/jni_weak_ref.h" -#include "base/callback.h" -#include "base/compiler_specific.h" #include "base/macros.h" -#include "base/time/time.h" -#include "components/invalidation/public/invalidation_util.h" -#include "components/sync/base/sync_prefs.h" #include "components/sync/driver/sync_service_observer.h" -#include "google/cacheinvalidation/include/types.h" -#include "google_apis/gaia/google_service_auth_error.h" class Profile; @@ -202,10 +194,6 @@ // Prevents Sync from running until configuration is complete. std::unique_ptr<syncer::SyncSetupInProgressHandle> sync_blocker_; - // The class that handles getting, setting, and persisting sync - // preferences. - std::unique_ptr<syncer::SyncPrefs> sync_prefs_; - // Java-side ProfileSyncService object. JavaObjectWeakGlobalRef weak_java_profile_sync_service_;
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 1506939..938eee5 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -415,6 +415,8 @@ "//components/favicon/core", "//components/feature_engagement", "//components/feed:feature_list", + "//components/feed/content:feed_content", + "//components/feed/core:feed_core", "//components/feedback", "//components/flags_ui", "//components/gcm_driver", @@ -1815,8 +1817,6 @@ "views/close_bubble_on_tab_activation_helper.h", "views/hats/hats_bubble_view.cc", "views/hats/hats_bubble_view.h", - "views/profiles/incognito_window_count_view.cc", - "views/profiles/incognito_window_count_view.h", "webui/discards/discards_ui.cc", "webui/discards/discards_ui.h", "webui/signin/inline_login_handler.cc",
diff --git a/chrome/browser/ui/app_list/app_list_client_impl.cc b/chrome/browser/ui/app_list/app_list_client_impl.cc index 9334114..38713223 100644 --- a/chrome/browser/ui/app_list/app_list_client_impl.cc +++ b/chrome/browser/ui/app_list/app_list_client_impl.cc
@@ -102,8 +102,7 @@ // Send training signal to search controller. search_controller_->Train( - result_id, - app_list::RankingItemTypeFromSearchResultType(result->result_type())); + result_id, app_list::RankingItemTypeFromSearchResult(*result)); } }
diff --git a/chrome/browser/ui/app_list/crostini/crostini_app_model_builder.cc b/chrome/browser/ui/app_list/crostini/crostini_app_model_builder.cc index a17929a..663f06a 100644 --- a/chrome/browser/ui/app_list/crostini/crostini_app_model_builder.cc +++ b/chrome/browser/ui/app_list/crostini/crostini_app_model_builder.cc
@@ -16,11 +16,45 @@ #include "components/prefs/pref_change_registrar.h" #include "ui/base/l10n/l10n_util.h" +// Folder items are created by the Ash process and their existence is +// communicated to chrome via the AppListClient. Therefore, crostini has an +// observer that listens for the creation of its folder, and updates the +// properties accordingly. +class CrostiniAppModelBuilder::CrostiniFolderObserver + : public AppListModelUpdaterObserver { + public: + explicit CrostiniFolderObserver(CrostiniAppModelBuilder* parent) + : parent_(parent) {} + + ~CrostiniFolderObserver() override = default; + + void OnAppListItemAdded(ChromeAppListItem* item) override { + if (item->id() != crostini::kCrostiniFolderId) + return; + // Persistence is not recorded by the sync, so we always set it. + item->SetIsPersistent(true); + + // Either the name and position will be in the sync, or we set them + // manually. + if (parent_->GetSyncItem(crostini::kCrostiniFolderId)) + return; + item->SetName( + l10n_util::GetStringUTF8(IDS_APP_LIST_CROSTINI_DEFAULT_FOLDER_NAME)); + item->SetDefaultPositionIfApplicable(parent_->model_updater()); + } + + private: + CrostiniAppModelBuilder* parent_; +}; + CrostiniAppModelBuilder::CrostiniAppModelBuilder( AppListControllerDelegate* controller) : AppListModelBuilder(controller, CrostiniAppItem::kItemType) {} CrostiniAppModelBuilder::~CrostiniAppModelBuilder() { + if (crostini_folder_observer_) { + model_updater()->RemoveObserver(crostini_folder_observer_.get()); + } // We don't need to remove ourself from the registry's observer list as these // are both KeyedServices (this class lives on AppListSyncableService). } @@ -40,6 +74,13 @@ crostini::prefs::kCrostiniEnabled, base::BindRepeating(&CrostiniAppModelBuilder::OnCrostiniEnabledChanged, base::Unretained(this))); + + // We register an observer against the model_updater in order to track + // creation and deletion of the crostini folder. + if (model_updater()) { + crostini_folder_observer_ = std::make_unique<CrostiniFolderObserver>(this); + model_updater()->AddObserver(crostini_folder_observer_.get()); + } } void CrostiniAppModelBuilder::InsertCrostiniAppItem( @@ -56,7 +97,6 @@ if (registration.NoDisplay()) return; - MaybeCreateRootFolder(); InsertApp(std::make_unique<CrostiniAppItem>(profile(), model_updater(), GetSyncItem(app_id), app_id, registration.Name())); @@ -120,21 +160,3 @@ RemoveApp(crostini::kCrostiniTerminalId, unsynced_change); } } - -void CrostiniAppModelBuilder::MaybeCreateRootFolder() { - // If a sync item exists for the root folder, then it has been created - // already. - const app_list::AppListSyncableService::SyncItem* sync_item = - GetSyncItem(crostini::kCrostiniFolderId); - if (sync_item) - return; - - std::unique_ptr<ChromeAppListItem> crositini_folder = - std::make_unique<ChromeAppListItem>( - profile(), crostini::kCrostiniFolderId, model_updater()); - crositini_folder->SetChromeIsFolder(true); - crositini_folder->SetName( - l10n_util::GetStringUTF8(IDS_APP_LIST_CROSTINI_DEFAULT_FOLDER_NAME)); - crositini_folder->SetDefaultPositionIfApplicable(model_updater()); - InsertApp(std::move(crositini_folder)); -}
diff --git a/chrome/browser/ui/app_list/crostini/crostini_app_model_builder.h b/chrome/browser/ui/app_list/crostini/crostini_app_model_builder.h index b0a2cbeb..e105a171 100644 --- a/chrome/browser/ui/app_list/crostini/crostini_app_model_builder.h +++ b/chrome/browser/ui/app_list/crostini/crostini_app_model_builder.h
@@ -4,6 +4,8 @@ #ifndef CHROME_BROWSER_UI_APP_LIST_CROSTINI_CROSTINI_APP_MODEL_BUILDER_H_ #define CHROME_BROWSER_UI_APP_LIST_CROSTINI_CROSTINI_APP_MODEL_BUILDER_H_ +#include <memory> + #include "base/macros.h" #include "chrome/browser/chromeos/crostini/crostini_registry_service.h" #include "chrome/browser/ui/app_list/app_list_model_builder.h" @@ -20,6 +22,10 @@ ~CrostiniAppModelBuilder() override; private: + // This observer will be used to update the properties of the crostini folder + // when ash creates it. + class CrostiniFolderObserver; + // AppListModelBuilder: void BuildModel() override; @@ -38,15 +44,13 @@ void OnCrostiniEnabledChanged(); - // Creates root folder for Crostini apps in case it was not created (in which - // case the sync item will not exist). Once it is created, a sync item is - // allocated, and it will be reused to restore the root folder on demand - // automatically. - void MaybeCreateRootFolder(); - // Observer Crostini installation so we can start showing The Terminal app. std::unique_ptr<PrefChangeRegistrar> pref_change_registrar_; + // Observer that listens for crostini folder creation and sets its properties + // accordingly. + std::unique_ptr<AppListModelUpdaterObserver> crostini_folder_observer_; + DISALLOW_COPY_AND_ASSIGN(CrostiniAppModelBuilder); };
diff --git a/chrome/browser/ui/app_list/crostini/crostini_app_model_builder_unittest.cc b/chrome/browser/ui/app_list/crostini/crostini_app_model_builder_unittest.cc index 3626519..1b1aceb 100644 --- a/chrome/browser/ui/app_list/crostini/crostini_app_model_builder_unittest.cc +++ b/chrome/browser/ui/app_list/crostini/crostini_app_model_builder_unittest.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/ui/app_list/crostini/crostini_app_model_builder.h" +#include <utility> #include <vector> #include "chrome/browser/chromeos/crostini/crostini_registry_service.h" @@ -23,6 +24,8 @@ #include "ui/base/l10n/l10n_util.h" using crostini::CrostiniTestHelper; +using ::testing::_; +using ::testing::Matcher; namespace { @@ -34,51 +37,18 @@ constexpr char kBananaAppId[] = "banana"; constexpr char kBananaAppName[] = "banana app name"; -// Returns map of items, key-ed by id. -std::map<std::string, ChromeAppListItem*> GetAppListItems( - AppListModelUpdater* model_updater) { - std::map<std::string, ChromeAppListItem*> result; - for (size_t i = 0; i < model_updater->ItemCount(); ++i) { - ChromeAppListItem* item = model_updater->ItemAtForTest(i); - result[item->id()] = item; - } - return result; +// Convenience matcher for some important fields of the chrome app. +MATCHER_P3(IsChromeApp, id, name, folder_id, "") { + Matcher<std::string> id_m(id); + Matcher<std::string> name_m(name); + Matcher<std::string> folder_id_m(folder_id); + return id_m.Matches(arg->id()) && name_m.Matches(arg->name()) && + folder_id_m.Matches(arg->folder_id()); } -std::vector<std::string> GetAppIds(AppListModelUpdater* model_updater) { - std::vector<std::string> result; - for (auto item : GetAppListItems(model_updater)) - result.push_back(item.first); - return result; -} - -// This also includes parent folder name, if applicable. -std::vector<std::string> GetAppNames(AppListModelUpdater* model_updater) { - std::vector<std::string> result; - std::map<std::string, ChromeAppListItem*> items = - GetAppListItems(model_updater); - for (auto item : items) { - const std::string folder_id = item.second->folder_id(); - if (folder_id.empty()) { - result.push_back(item.second->name()); - continue; - } - ChromeAppListItem* parent = items[folder_id]; - DCHECK(parent && parent->is_folder()); - result.push_back(parent->name() + "/" + item.second->name()); - } - return result; -} - -std::string GetFullName(const std::string& app_name) { - return std::string(kRootFolderName) + "/" + app_name; -} - -std::vector<std::string> AppendRootFolderId( - const std::vector<std::string> ids) { - std::vector<std::string> result = ids; - result.emplace_back(crostini::kCrostiniFolderId); - return result; +// Matches a chrome app item if its persistence field is set to true. +MATCHER(IsPersistentApp, "") { + return arg->is_persistent(); } // For testing purposes, we want to pretend there are only crostini apps on the @@ -107,11 +77,6 @@ void SetUp() override { AppListTestBase::SetUp(); test_helper_ = std::make_unique<CrostiniTestHelper>(profile()); - model_updater_factory_scope_ = std::make_unique< - app_list::AppListSyncableService::ScopedModelUpdaterFactoryForTest>( - base::BindRepeating([]() -> std::unique_ptr<AppListModelUpdater> { - return std::make_unique<FakeAppListModelUpdater>(); - })); CreateBuilder(); } @@ -130,18 +95,34 @@ return sync_service_->GetModelUpdater()->ItemCount(); } + std::vector<ChromeAppListItem*> GetAllApps() const { + std::vector<ChromeAppListItem*> result; + for (size_t i = 0; i < GetModelItemCount(); ++i) { + result.emplace_back(GetModelUpdater()->ItemAtForTest(i)); + } + return result; + } + void CreateBuilder() { + model_updater_factory_scope_ = std::make_unique< + app_list::AppListSyncableService::ScopedModelUpdaterFactoryForTest>( + base::BindRepeating( + [](Profile* profile) -> std::unique_ptr<AppListModelUpdater> { + return std::make_unique<FakeAppListModelUpdater>(profile); + }, + profile())); controller_ = std::make_unique<test::TestAppListControllerDelegate>(); - builder_ = std::make_unique<CrostiniAppModelBuilder>(controller_.get()); sync_service_ = std::make_unique<app_list::AppListSyncableService>( profile_.get(), extensions::ExtensionSystem::Get(profile_.get())); + builder_ = std::make_unique<CrostiniAppModelBuilder>(controller_.get()); RemoveNonCrostiniApps(sync_service_.get()); } void ResetBuilder() { builder_.reset(); - controller_.reset(); sync_service_.reset(); + controller_.reset(); + model_updater_factory_scope_.reset(); } crostini::CrostiniRegistryService* RegistryService() { @@ -177,129 +158,129 @@ EXPECT_EQ(0u, GetModelItemCount()); CrostiniTestHelper::EnableCrostini(profile()); - // Root folder + terminal app. - EXPECT_THAT(GetAppIds(GetModelUpdater()), - testing::UnorderedElementsAre(crostini::kCrostiniFolderId, - crostini::kCrostiniTerminalId)); - EXPECT_THAT(GetAppNames(GetModelUpdater()), - testing::UnorderedElementsAre(kRootFolderName, - GetFullName(TerminalAppName()))); + EXPECT_THAT(GetAllApps(), + testing::UnorderedElementsAre( + IsChromeApp(crostini::kCrostiniTerminalId, TerminalAppName(), + crostini::kCrostiniFolderId))); CrostiniTestHelper::DisableCrostini(profile()); - EXPECT_THAT(GetAppIds(GetModelUpdater()), - testing::ElementsAre(crostini::kCrostiniFolderId)); + EXPECT_THAT(GetAllApps(), testing::IsEmpty()); } TEST_F(CrostiniAppModelBuilderTest, AppInstallation) { - // Root folder + terminal app. - EXPECT_EQ(2u, GetModelItemCount()); + // Terminal app. + EXPECT_EQ(1u, GetModelItemCount()); test_helper_->SetupDummyApps(); - EXPECT_THAT(GetAppIds(GetModelUpdater()), - testing::UnorderedElementsAreArray(AppendRootFolderId( - RegistryService()->GetRegisteredAppIds()))); - EXPECT_THAT(GetAppNames(GetModelUpdater()), - testing::UnorderedElementsAre( - kRootFolderName, GetFullName(TerminalAppName()), - GetFullName(kDummpyApp1Name), GetFullName(kDummpyApp2Name))); + + EXPECT_THAT( + GetAllApps(), + testing::UnorderedElementsAre( + IsChromeApp(crostini::kCrostiniTerminalId, TerminalAppName(), + crostini::kCrostiniFolderId), + IsChromeApp(_, kDummpyApp1Name, crostini::kCrostiniFolderId), + IsChromeApp(_, kDummpyApp2Name, crostini::kCrostiniFolderId))); test_helper_->AddApp( CrostiniTestHelper::BasicApp(kBananaAppId, kBananaAppName)); - EXPECT_THAT(GetAppIds(GetModelUpdater()), - testing::UnorderedElementsAreArray(AppendRootFolderId( - RegistryService()->GetRegisteredAppIds()))); - EXPECT_THAT(GetAppNames(GetModelUpdater()), + EXPECT_THAT(GetAllApps(), testing::UnorderedElementsAre( - kRootFolderName, GetFullName(TerminalAppName()), - GetFullName(kDummpyApp1Name), GetFullName(kDummpyApp2Name), - GetFullName(kBananaAppName))); + IsChromeApp(crostini::kCrostiniTerminalId, TerminalAppName(), + crostini::kCrostiniFolderId), + IsChromeApp(_, kDummpyApp1Name, crostini::kCrostiniFolderId), + IsChromeApp(_, kDummpyApp2Name, crostini::kCrostiniFolderId), + IsChromeApp(_, kBananaAppName, crostini::kCrostiniFolderId))); } // Test that the app model builder correctly picks up changes to existing apps. TEST_F(CrostiniAppModelBuilderTest, UpdateApps) { test_helper_->SetupDummyApps(); - // 3 apps + root folder. - EXPECT_EQ(4u, GetModelItemCount()); + // 3 apps. + EXPECT_EQ(3u, GetModelItemCount()); // Setting NoDisplay to true should hide an app. vm_tools::apps::App dummy1 = test_helper_->GetApp(0); dummy1.set_no_display(true); test_helper_->AddApp(dummy1); - EXPECT_EQ(3u, GetModelItemCount()); - EXPECT_THAT(GetAppIds(GetModelUpdater()), - testing::UnorderedElementsAre( - crostini::kCrostiniFolderId, crostini::kCrostiniTerminalId, - CrostiniTestHelper::GenerateAppId(kDummpyApp2Id))); + EXPECT_THAT( + GetAllApps(), + testing::UnorderedElementsAre( + IsChromeApp(crostini::kCrostiniTerminalId, _, _), + IsChromeApp(CrostiniTestHelper::GenerateAppId(kDummpyApp2Name), _, + _))); // Setting NoDisplay to false should unhide an app. dummy1.set_no_display(false); test_helper_->AddApp(dummy1); - EXPECT_EQ(4u, GetModelItemCount()); - EXPECT_THAT(GetAppIds(GetModelUpdater()), - testing::UnorderedElementsAreArray(AppendRootFolderId( - RegistryService()->GetRegisteredAppIds()))); + EXPECT_THAT( + GetAllApps(), + testing::UnorderedElementsAre( + IsChromeApp(crostini::kCrostiniTerminalId, _, _), + IsChromeApp(CrostiniTestHelper::GenerateAppId(kDummpyApp1Name), _, _), + IsChromeApp(CrostiniTestHelper::GenerateAppId(kDummpyApp2Name), _, + _))); // Changes to app names should be detected. vm_tools::apps::App dummy2 = CrostiniTestHelper::BasicApp(kDummpyApp2Id, kAppNewName); test_helper_->AddApp(dummy2); - EXPECT_EQ(4u, GetModelItemCount()); - EXPECT_THAT(GetAppIds(GetModelUpdater()), - testing::UnorderedElementsAreArray(AppendRootFolderId( - RegistryService()->GetRegisteredAppIds()))); - EXPECT_THAT(GetAppNames(GetModelUpdater()), - testing::UnorderedElementsAre( - kRootFolderName, GetFullName(TerminalAppName()), - GetFullName(kDummpyApp1Name), GetFullName(kAppNewName))); + EXPECT_THAT( + GetAllApps(), + testing::UnorderedElementsAre( + IsChromeApp(crostini::kCrostiniTerminalId, _, _), + IsChromeApp(CrostiniTestHelper::GenerateAppId(kDummpyApp1Name), + kDummpyApp1Name, _), + IsChromeApp(CrostiniTestHelper::GenerateAppId(kDummpyApp2Name), + kAppNewName, _))); } // Test that the app model builder handles removed apps TEST_F(CrostiniAppModelBuilderTest, RemoveApps) { test_helper_->SetupDummyApps(); - // 3 apps + root folder. - EXPECT_EQ(4u, GetModelItemCount()); + // 3 apps. + EXPECT_EQ(3u, GetModelItemCount()); // Remove dummy1 test_helper_->RemoveApp(0); - EXPECT_EQ(3u, GetModelItemCount()); + EXPECT_EQ(2u, GetModelItemCount()); // Remove dummy2 test_helper_->RemoveApp(0); - EXPECT_EQ(2u, GetModelItemCount()); + EXPECT_EQ(1u, GetModelItemCount()); } -// Tests that the crostini folder is recreated on demand. -TEST_F(CrostiniAppModelBuilderTest, RecreateFolder) { - CrostiniTestHelper::EnableCrostini(profile()); - // Root folder + terminal app. - EXPECT_THAT(GetAppNames(GetModelUpdater()), - testing::UnorderedElementsAre(kRootFolderName, - GetFullName(TerminalAppName()))); +// Tests that the crostini folder is (re)created with the correct parameters. +TEST_F(CrostiniAppModelBuilderTest, CreatesFolder) { + EXPECT_THAT(GetAllApps(), + testing::UnorderedElementsAre( + IsChromeApp(crostini::kCrostiniTerminalId, TerminalAppName(), + crostini::kCrostiniFolderId))); - // Move the terminal out and delete the old folder. - GetModelUpdater()->MoveItemToFolder(crostini::kCrostiniTerminalId, ""); - GetModelUpdater()->RemoveItem(crostini::kCrostiniFolderId); - EXPECT_THAT(GetAppNames(GetModelUpdater()), - testing::UnorderedElementsAre(TerminalAppName())); + // We simulate ash creating the crostini folder and calling back into chrome + // (rather than use a full browser test). + ash::mojom::AppListItemMetadataPtr metadata = + ash::mojom::AppListItemMetadata::New(); + metadata->id = crostini::kCrostiniFolderId; + GetModelUpdater()->OnFolderCreated(std::move(metadata)); - // Adding a new app should recreate the folder. - test_helper_->AddApp( - CrostiniTestHelper::BasicApp(kDummpyApp2Id, kDummpyApp2Name)); - EXPECT_THAT(GetAppNames(GetModelUpdater()), - testing::UnorderedElementsAre(TerminalAppName(), kRootFolderName, - GetFullName(kDummpyApp2Name))); + EXPECT_THAT(GetAllApps(), + testing::UnorderedElementsAre( + IsChromeApp(crostini::kCrostiniTerminalId, TerminalAppName(), + crostini::kCrostiniFolderId), + testing::AllOf(IsChromeApp(crostini::kCrostiniFolderId, + kRootFolderName, ""), + IsPersistentApp()))); } // Test that the Terminal app is removed when Crostini is disabled. TEST_F(CrostiniAppModelBuilderTest, DisableCrostini) { test_helper_->SetupDummyApps(); - // 3 apps + root folder. - EXPECT_EQ(4u, GetModelItemCount()); + // 3 apps. + EXPECT_EQ(3u, GetModelItemCount()); // The uninstall flow removes all apps before setting the CrostiniEnabled pref // to false, so we need to do that explicitly too. RegistryService()->ClearApplicationList(crostini::kCrostiniDefaultVmName, ""); CrostiniTestHelper::DisableCrostini(profile()); - // Root folder is left. We rely on default handling of empty folder. - EXPECT_EQ(1u, GetModelItemCount()); + EXPECT_EQ(0u, GetModelItemCount()); }
diff --git a/chrome/browser/ui/app_list/search/app_search_provider.cc b/chrome/browser/ui/app_list/search/app_search_provider.cc index b228295..11a687a 100644 --- a/chrome/browser/ui/app_list/search/app_search_provider.cc +++ b/chrome/browser/ui/app_list/search/app_search_provider.cc
@@ -34,7 +34,6 @@ #include "chrome/browser/chromeos/crostini/crostini_registry_service_factory.h" #include "chrome/browser/chromeos/crostini/crostini_util.h" #include "chrome/browser/chromeos/extensions/gfx_utils.h" -#include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_ui_util.h" #include "chrome/browser/extensions/extension_util.h" @@ -620,14 +619,13 @@ AppSearchProvider::AppSearchProvider(Profile* profile, AppListControllerDelegate* list_controller, base::Clock* clock, - AppListModelUpdater* model_updater) + AppListModelUpdater* model_updater, + AppSearchResultRanker* ranker) : profile_(profile), list_controller_(list_controller), model_updater_(model_updater), clock_(clock), - ranker_(std::make_unique<AppSearchResultRanker>( - profile->GetPath(), - chromeos::ProfileHelper::IsEphemeralUserProfile(profile))), + ranker_(ranker), refresh_apps_factory_(this), update_results_factory_(this) { bool app_service_enabled =
diff --git a/chrome/browser/ui/app_list/search/app_search_provider.h b/chrome/browser/ui/app_list/search/app_search_provider.h index 82cfd88..550e3b4 100644 --- a/chrome/browser/ui/app_list/search/app_search_provider.h +++ b/chrome/browser/ui/app_list/search/app_search_provider.h
@@ -44,7 +44,8 @@ AppSearchProvider(Profile* profile, AppListControllerDelegate* list_controller, base::Clock* clock, - AppListModelUpdater* model_updater); + AppListModelUpdater* model_updater, + AppSearchResultRanker* ranker); ~AppSearchProvider() override; // SearchProvider overrides: @@ -88,7 +89,7 @@ AppListModelUpdater* const model_updater_; base::Clock* clock_; std::vector<std::unique_ptr<DataSource>> data_sources_; - std::unique_ptr<AppSearchResultRanker> ranker_; + AppSearchResultRanker* ranker_; sync_sessions::OpenTabsUIDelegate* open_tabs_ui_delegate_for_testing_ = nullptr; base::WeakPtrFactory<AppSearchProvider> refresh_apps_factory_;
diff --git a/chrome/browser/ui/app_list/search/arc/arc_app_shortcut_search_result.cc b/chrome/browser/ui/app_list/search/arc/arc_app_shortcut_search_result.cc index db343c2..0bbc6d5c 100644 --- a/chrome/browser/ui/app_list/search/arc/arc_app_shortcut_search_result.cc +++ b/chrome/browser/ui/app_list/search/arc/arc_app_shortcut_search_result.cc
@@ -37,6 +37,7 @@ set_id(kAppShortcutSearchPrefix + GetAppId() + "/" + data_->shortcut_id); SetDisplayType(ash::SearchResultDisplayType::kTile); SetAccessibleName(ComputeAccessibleName()); + SetResultType(ash::SearchResultType::kArcAppShortcut); const int icon_dimension = app_list::AppListConfig::instance().search_tile_icon_dimension();
diff --git a/chrome/browser/ui/app_list/search/arc/arc_app_shortcuts_search_provider.cc b/chrome/browser/ui/app_list/search/arc/arc_app_shortcuts_search_provider.cc index 8ba7586..c3a91c24 100644 --- a/chrome/browser/ui/app_list/search/arc/arc_app_shortcuts_search_provider.cc +++ b/chrome/browser/ui/app_list/search/arc/arc_app_shortcuts_search_provider.cc
@@ -7,11 +7,13 @@ #include <memory> #include <utility> +#include "ash/public/cpp/app_list/app_list_features.h" #include "base/bind.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/app_list/arc/arc_app_utils.h" #include "chrome/browser/ui/app_list/search/arc/arc_app_shortcut_search_result.h" +#include "chrome/browser/ui/app_list/search/search_result_ranker/app_search_result_ranker.h" #include "components/arc/arc_bridge_service.h" #include "components/arc/arc_service_manager.h" @@ -20,10 +22,12 @@ ArcAppShortcutsSearchProvider::ArcAppShortcutsSearchProvider( int max_results, Profile* profile, - AppListControllerDelegate* list_controller) + AppListControllerDelegate* list_controller, + AppSearchResultRanker* ranker) : max_results_(max_results), profile_(profile), list_controller_(list_controller), + ranker_(ranker), weak_ptr_factory_(this) {} ArcAppShortcutsSearchProvider::~ArcAppShortcutsSearchProvider() = default; @@ -66,7 +70,14 @@ continue; search_results.emplace_back(std::make_unique<ArcAppShortcutSearchResult>( std::move(item), profile_, list_controller_)); + + if (app_list_features::IsAppSearchResultRankerEnabled() && + ranker_ != nullptr) { + // TODO(crbug.com/931149): tweak the scores of each search result item + // using the ranker. + } } + SwapResults(&search_results); }
diff --git a/chrome/browser/ui/app_list/search/arc/arc_app_shortcuts_search_provider.h b/chrome/browser/ui/app_list/search/arc/arc_app_shortcuts_search_provider.h index c951990..af537a62 100644 --- a/chrome/browser/ui/app_list/search/arc/arc_app_shortcuts_search_provider.h +++ b/chrome/browser/ui/app_list/search/arc/arc_app_shortcuts_search_provider.h
@@ -18,11 +18,14 @@ namespace app_list { +class AppSearchResultRanker; + class ArcAppShortcutsSearchProvider : public SearchProvider { public: ArcAppShortcutsSearchProvider(int max_results, Profile* profile, - AppListControllerDelegate* list_controller); + AppListControllerDelegate* list_controller, + AppSearchResultRanker* ranker); ~ArcAppShortcutsSearchProvider() override; // SearchProvider: @@ -35,6 +38,9 @@ const int max_results_; Profile* const profile_; // Owned by ProfileInfo. AppListControllerDelegate* const list_controller_; // Owned by AppListClient. + // TODO(crbug.com/931149): train this ranker on app shortcut clicks, and use + // it to tweak their relevance scores. + AppSearchResultRanker* ranker_; base::WeakPtrFactory<ArcAppShortcutsSearchProvider> weak_ptr_factory_;
diff --git a/chrome/browser/ui/app_list/search/arc/arc_app_shortcuts_search_provider_unittest.cc b/chrome/browser/ui/app_list/search/arc/arc_app_shortcuts_search_provider_unittest.cc index 6046328..da831c6 100644 --- a/chrome/browser/ui/app_list/search/arc/arc_app_shortcuts_search_provider_unittest.cc +++ b/chrome/browser/ui/app_list/search/arc/arc_app_shortcuts_search_provider_unittest.cc
@@ -7,6 +7,7 @@ #include <memory> #include <utility> +#include "base/files/scoped_temp_dir.h" #include "base/macros.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -15,6 +16,7 @@ #include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" #include "chrome/browser/ui/app_list/arc/arc_app_test.h" #include "chrome/browser/ui/app_list/search/chrome_search_result.h" +#include "chrome/browser/ui/app_list/search/search_result_ranker/app_search_result_ranker.h" #include "chrome/browser/ui/app_list/test/test_app_list_controller_delegate.h" #include "testing/gtest/include/gtest/gtest.h" @@ -36,6 +38,10 @@ AppListTestBase::SetUp(); arc_test_.SetUp(profile()); controller_ = std::make_unique<test::TestAppListControllerDelegate>(); + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + ranker_ = + std::make_unique<AppSearchResultRanker>(temp_dir_.GetPath(), + /*is_ephemeral_user=*/true); } void TearDown() override { @@ -70,6 +76,8 @@ return app_id; } + base::ScopedTempDir temp_dir_; + std::unique_ptr<AppSearchResultRanker> ranker_; std::unique_ptr<test::TestAppListControllerDelegate> controller_; ArcAppTest arc_test_; @@ -88,7 +96,7 @@ constexpr char kQuery[] = "shortlabel"; auto provider = std::make_unique<ArcAppShortcutsSearchProvider>( - kMaxResults, profile(), controller_.get()); + kMaxResults, profile(), controller_.get(), ranker_.get()); EXPECT_TRUE(provider->results().empty()); arc::IconDecodeRequest::DisableSafeDecodingForTesting();
diff --git a/chrome/browser/ui/app_list/search/chrome_search_result.cc b/chrome/browser/ui/app_list/search/chrome_search_result.cc index 24a99aaf..03409c3 100644 --- a/chrome/browser/ui/app_list/search/chrome_search_result.cc +++ b/chrome/browser/ui/app_list/search/chrome_search_result.cc
@@ -215,6 +215,10 @@ return result; } +int ChromeSearchResult::GetSubType() const { + return -1; +} + app_list::AppContextMenu* ChromeSearchResult::GetAppContextMenu() { return nullptr; }
diff --git a/chrome/browser/ui/app_list/search/chrome_search_result.h b/chrome/browser/ui/app_list/search/chrome_search_result.h index b06f4f0..0de4454 100644 --- a/chrome/browser/ui/app_list/search/chrome_search_result.h +++ b/chrome/browser/ui/app_list/search/chrome_search_result.h
@@ -121,6 +121,11 @@ static std::string TagsDebugStringForTest(const std::string& text, const Tags& tags); + // Subtype of a search result. -1 means no sub type. Derived class + // can use this to return useful values for rankers etc. Currently, + // OmniboxResult overrides it to return AutocompleteMatch::Type. + virtual int GetSubType() const; + protected: // These id setters should be called in derived class constructors only. void set_id(const std::string& id) { metadata_->id = id; }
diff --git a/chrome/browser/ui/app_list/search/mixer.cc b/chrome/browser/ui/app_list/search/mixer.cc index e4893fb..6f3b25b 100644 --- a/chrome/browser/ui/app_list/search/mixer.cc +++ b/chrome/browser/ui/app_list/search/mixer.cc
@@ -11,11 +11,14 @@ #include <utility> #include <vector> +#include "ash/public/cpp/app_list/app_list_features.h" #include "base/macros.h" +#include "base/metrics/field_trial_params.h" #include "chrome/browser/ui/app_list/app_list_model_updater.h" #include "chrome/browser/ui/app_list/search/chrome_search_result.h" #include "chrome/browser/ui/app_list/search/search_provider.h" #include "chrome/browser/ui/app_list/search/search_result_ranker/ranking_item_util.h" +#include "chrome/browser/ui/app_list/search/search_result_ranker/recurrence_ranker.h" namespace app_list { @@ -76,8 +79,11 @@ }; Mixer::Mixer(AppListModelUpdater* model_updater) - : model_updater_(model_updater) {} - + : model_updater_(model_updater), + boost_coefficient_(base::GetFieldTrialParamByFeatureAsDouble( + app_list_features::kEnableAdaptiveResultRanker, + "boost_coefficient", + 0.1)) {} Mixer::~Mixer() = default; size_t Mixer::AddGroup(size_t max_results, double multiplier, double boost) { @@ -108,6 +114,25 @@ // number* will be kept (e.g., an app result takes priority over a web store // result with the same ID). RemoveDuplicates(&results); + + // Tweak the rankings using the ranker if it exists. + if (app_list_features::IsAdaptiveResultRankerEnabled() && ranker_) { + base::flat_map<std::string, float> ranks = ranker_->Rank(); + + for (auto& result : results) { + RankingItemType type = RankingItemTypeFromSearchResult(*result.result); + const auto& rank_it = ranks.find(std::to_string(static_cast<int>(type))); + // The ranker only contains entries trained with types + // |RankingItemType::kFile| and |RankingItemType::kOmnibox|. This means + // scores for apps and answer cards will be unchanged. + if (rank_it != ranks.end()) + // Ranker scores are guaranteed to be in [0,1]. But, enforce that the + // result of tweaking does not put the score above 3.0, as that may + // interfere with apps or answer cards. + result.score += std::min(rank_it->second * boost_coefficient_, 3.0f); + } + } + std::sort(results.begin(), results.end()); const size_t original_size = results.size(); @@ -156,9 +181,17 @@ group->FetchResults(); } +void Mixer::SetRecurrenceRanker(std::unique_ptr<RecurrenceRanker> ranker) { + ranker_ = std::move(ranker); +} + void Mixer::Train(const std::string& id, RankingItemType type) { - // TODO(https://crbug.com/931149)) train a ranking model using this training - // signal. + if (!ranker_) + return; + + if (type == RankingItemType::kFile || type == RankingItemType::kOmnibox) { + ranker_->Record(std::to_string(static_cast<int>(type))); + } } } // namespace app_list
diff --git a/chrome/browser/ui/app_list/search/mixer.h b/chrome/browser/ui/app_list/search/mixer.h index 2293429..c1bc958 100644 --- a/chrome/browser/ui/app_list/search/mixer.h +++ b/chrome/browser/ui/app_list/search/mixer.h
@@ -22,6 +22,7 @@ FORWARD_DECLARE_TEST(MixerTest, Publish); } +class RecurrenceRanker; class SearchProvider; enum class RankingItemType; @@ -48,6 +49,9 @@ // Collects the results, sorts and publishes them. void MixAndPublish(size_t num_max_results); + // Add a |RecurrenceRanker| to tweak mixing results. + void SetRecurrenceRanker(std::unique_ptr<RecurrenceRanker> ranker); + // Handle a training signal. void Train(const std::string& id, RankingItemType type); @@ -81,6 +85,13 @@ Groups groups_; + // Adaptive category ranking model, which tweaks the score of search results. + std::unique_ptr<RecurrenceRanker> ranker_; + + // How much the scores produced by |ranker_| affect the final scores. + // Controlled by Finch. + float boost_coefficient_; + DISALLOW_COPY_AND_ASSIGN(Mixer); };
diff --git a/chrome/browser/ui/app_list/search/omnibox_result.cc b/chrome/browser/ui/app_list/search/omnibox_result.cc index dd5d1e0..afa94ed 100644 --- a/chrome/browser/ui/app_list/search/omnibox_result.cc +++ b/chrome/browser/ui/app_list/search/omnibox_result.cc
@@ -187,8 +187,8 @@ } } -AutocompleteMatch::Type OmniboxResult::type() const { - return match_.type; +int OmniboxResult::GetSubType() const { + return static_cast<int>(match_.type); } void OmniboxResult::UpdateIcon() {
diff --git a/chrome/browser/ui/app_list/search/omnibox_result.h b/chrome/browser/ui/app_list/search/omnibox_result.h index f3a7e02..7746b6f 100644 --- a/chrome/browser/ui/app_list/search/omnibox_result.h +++ b/chrome/browser/ui/app_list/search/omnibox_result.h
@@ -38,9 +38,7 @@ // ChromeSearchResult overrides: void Open(int event_flags) override; void InvokeAction(int action_index, int event_flags) override; - - // Returns type of the matched result as a string. - AutocompleteMatch::Type type() const; + int GetSubType() const override; private: void UpdateIcon();
diff --git a/chrome/browser/ui/app_list/search/search_controller.cc b/chrome/browser/ui/app_list/search/search_controller.cc index 017f707..1704155 100644 --- a/chrome/browser/ui/app_list/search/search_controller.cc +++ b/chrome/browser/ui/app_list/search/search_controller.cc
@@ -13,17 +13,25 @@ #include "base/bind.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/browser/chromeos/profiles/profile_helper.h" +#include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/app_list/app_list_controller_delegate.h" #include "chrome/browser/ui/app_list/app_list_model_updater.h" #include "chrome/browser/ui/app_list/search/chrome_search_result.h" #include "chrome/browser/ui/app_list/search/search_provider.h" +#include "chrome/browser/ui/app_list/search/search_result_ranker/app_search_result_ranker.h" +#include "chrome/browser/ui/app_list/search/search_result_ranker/recurrence_ranker.h" #include "chrome/browser/ui/ash/tablet_mode_client.h" namespace app_list { SearchController::SearchController(AppListModelUpdater* model_updater, - AppListControllerDelegate* list_controller) + AppListControllerDelegate* list_controller, + Profile* profile) : mixer_(std::make_unique<Mixer>(model_updater)), + ranker_(std::make_unique<AppSearchResultRanker>( + profile->GetPath(), + chromeos::ProfileHelper::IsEphemeralUserProfile(profile))), list_controller_(list_controller) {} SearchController::~SearchController() {} @@ -114,10 +122,19 @@ return nullptr; } +void SearchController::SetRecurrenceRanker( + std::unique_ptr<RecurrenceRanker> ranker) { + mixer_->SetRecurrenceRanker(std::move(ranker)); +} + void SearchController::Train(const std::string& id, RankingItemType type) { for (const auto& provider : providers_) provider->Train(id, type); mixer_->Train(id, type); } +AppSearchResultRanker* SearchController::GetSearchResultRanker() { + return ranker_.get(); +} + } // namespace app_list
diff --git a/chrome/browser/ui/app_list/search/search_controller.h b/chrome/browser/ui/app_list/search/search_controller.h index 8a8340f..cbf9e9b 100644 --- a/chrome/browser/ui/app_list/search/search_controller.h +++ b/chrome/browser/ui/app_list/search/search_controller.h
@@ -18,9 +18,12 @@ class AppListControllerDelegate; class AppListModelUpdater; class ChromeSearchResult; +class Profile; namespace app_list { +class AppSearchResultRanker; +class RecurrenceRanker; class SearchProvider; enum class RankingItemType; @@ -30,7 +33,8 @@ class SearchController { public: SearchController(AppListModelUpdater* model_updater, - AppListControllerDelegate* list_controller); + AppListControllerDelegate* list_controller, + Profile* profile); virtual ~SearchController(); void Start(const base::string16& query); @@ -49,9 +53,15 @@ ChromeSearchResult* FindSearchResult(const std::string& result_id); ChromeSearchResult* GetResultByTitleForTest(const std::string& title); + // Set a |RecurrenceRanker| to tweak search results. + void SetRecurrenceRanker(std::unique_ptr<RecurrenceRanker> ranker); + // Sends training signal to each |providers_| void Train(const std::string& id, RankingItemType type); + // Get the app search result ranker owned by this object. + AppSearchResultRanker* GetSearchResultRanker(); + private: // Invoked when the search results are changed. void OnResultsChanged(); @@ -64,6 +74,7 @@ using Providers = std::vector<std::unique_ptr<SearchProvider>>; Providers providers_; std::unique_ptr<Mixer> mixer_; + std::unique_ptr<AppSearchResultRanker> ranker_; AppListControllerDelegate* list_controller_; DISALLOW_COPY_AND_ASSIGN(SearchController);
diff --git a/chrome/browser/ui/app_list/search/search_controller_factory.cc b/chrome/browser/ui/app_list/search/search_controller_factory.cc index ddacd97..2e6e05c 100644 --- a/chrome/browser/ui/app_list/search/search_controller_factory.cc +++ b/chrome/browser/ui/app_list/search/search_controller_factory.cc
@@ -8,10 +8,12 @@ #include "ash/public/cpp/app_list/app_list_features.h" #include "ash/public/cpp/app_list/app_list_switches.h" +#include "base/metrics/field_trial_params.h" #include "base/strings/string_util.h" #include "base/time/default_clock.h" #include "build/build_config.h" #include "chrome/browser/chromeos/arc/arc_util.h" +#include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/app_list/search/answer_card/answer_card_search_provider.h" #include "chrome/browser/ui/app_list/search/app_search_provider.h" @@ -24,6 +26,7 @@ #include "chrome/browser/ui/app_list/search/mixer.h" #include "chrome/browser/ui/app_list/search/omnibox_provider.h" #include "chrome/browser/ui/app_list/search/search_controller.h" +#include "chrome/browser/ui/app_list/search/search_result_ranker/recurrence_ranker.h" #include "chrome/browser/ui/app_list/search/settings_shortcut/settings_shortcut_provider.h" #include "chrome/common/chrome_features.h" #include "chrome/common/chrome_switches.h" @@ -70,7 +73,9 @@ AppListModelUpdater* model_updater, AppListControllerDelegate* list_controller) { std::unique_ptr<SearchController> controller = - std::make_unique<SearchController>(model_updater, list_controller); + std::make_unique<SearchController>(model_updater, list_controller, + profile); + AppSearchResultRanker* ranker = controller->GetSearchResultRanker(); // Add mixer groups. There are four main groups: answer card, apps // and omnibox. Each group has a "soft" maximum number of results. However, if @@ -86,10 +91,10 @@ size_t omnibox_group_id = controller->AddGroup(kMaxOmniboxResults, 1.0, 0.0); // Add search providers. - controller->AddProvider( - apps_group_id, std::make_unique<AppSearchProvider>( - profile, list_controller, - base::DefaultClock::GetInstance(), model_updater)); + controller->AddProvider(apps_group_id, std::make_unique<AppSearchProvider>( + profile, list_controller, + base::DefaultClock::GetInstance(), + model_updater, ranker)); controller->AddProvider(omnibox_group_id, std::make_unique<OmniboxProvider>( profile, list_controller)); if (app_list_features::IsAnswerCardEnabled()) { @@ -152,7 +157,7 @@ controller->AddProvider( app_shortcut_group_id, std::make_unique<ArcAppShortcutsSearchProvider>( - kMaxAppShortcutResults, profile, list_controller)); + kMaxAppShortcutResults, profile, list_controller, ranker)); } // TODO(https://crbug.com/921429): Put feature switch in ash/public/app_list/ @@ -165,6 +170,29 @@ std::make_unique<CrostiniRepositorySearchProvider>(profile)); } + if (app_list_features::IsAdaptiveResultRankerEnabled()) { + RecurrenceRankerConfigProto group_ranker_config; + group_ranker_config.set_min_seconds_between_saves(240u); + auto* predictor = + group_ranker_config.mutable_zero_state_frecency_predictor(); + predictor->set_target_limit(base::GetFieldTrialParamByFeatureAsInt( + app_list_features::kEnableAdaptiveResultRanker, "target_limit", 200)); + predictor->set_decay_coeff(base::GetFieldTrialParamByFeatureAsDouble( + app_list_features::kEnableAdaptiveResultRanker, "decay_coeff", 0.8f)); + auto* fallback = group_ranker_config.mutable_fallback_predictor(); + fallback->set_target_limit(base::GetFieldTrialParamByFeatureAsInt( + app_list_features::kEnableAdaptiveResultRanker, "fallback_target_limit", + 200)); + fallback->set_decay_coeff(base::GetFieldTrialParamByFeatureAsDouble( + app_list_features::kEnableAdaptiveResultRanker, "fallback_decay_coeff", + 0.8f)); + + controller->SetRecurrenceRanker(std::make_unique<RecurrenceRanker>( + profile->GetPath().AppendASCII("adaptive_result_ranker.proto"), + group_ranker_config, + chromeos::ProfileHelper::IsEphemeralUserProfile(profile))); + } + return controller; }
diff --git a/chrome/browser/ui/app_list/search/search_result_ranker/ranking_item_util.cc b/chrome/browser/ui/app_list/search/search_result_ranker/ranking_item_util.cc index b6dec57b..89aee7b 100644 --- a/chrome/browser/ui/app_list/search/search_result_ranker/ranking_item_util.cc +++ b/chrome/browser/ui/app_list/search/search_result_ranker/ranking_item_util.cc
@@ -7,14 +7,15 @@ #include "ash/public/cpp/app_list/app_list_types.h" #include "base/macros.h" #include "chrome/browser/ui/app_list/chrome_app_list_item.h" +#include "chrome/browser/ui/app_list/search/chrome_search_result.h" namespace app_list { using SearchResultType = ash::SearchResultType; -RankingItemType RankingItemTypeFromSearchResultType( - const ash::SearchResultType& type) { - switch (type) { +RankingItemType RankingItemTypeFromSearchResult( + const ChromeSearchResult& result) { + switch (result.result_type()) { case SearchResultType::kInstalledApp: case SearchResultType::kInternalApp: return RankingItemType::kApp; @@ -30,6 +31,8 @@ case SearchResultType::kPlayStoreReinstallApp: case SearchResultType::kWebStoreSearch: return RankingItemType::kIgnored; + case SearchResultType::kArcAppShortcut: + return RankingItemType::kArcAppShortcut; } }
diff --git a/chrome/browser/ui/app_list/search/search_result_ranker/ranking_item_util.h b/chrome/browser/ui/app_list/search/search_result_ranker/ranking_item_util.h index 5534b36..ddf3ca8 100644 --- a/chrome/browser/ui/app_list/search/search_result_ranker/ranking_item_util.h +++ b/chrome/browser/ui/app_list/search/search_result_ranker/ranking_item_util.h
@@ -5,11 +5,8 @@ #ifndef CHROME_BROWSER_UI_APP_LIST_SEARCH_SEARCH_RESULT_RANKER_RANKING_ITEM_UTIL_H_ #define CHROME_BROWSER_UI_APP_LIST_SEARCH_SEARCH_RESULT_RANKER_RANKING_ITEM_UTIL_H_ -namespace ash { -enum class SearchResultType; -} - class ChromeAppListItem; +class ChromeSearchResult; namespace app_list { @@ -21,11 +18,12 @@ kFile, kApp, kOmnibox, + kArcAppShortcut }; -// Convert the enum used by |ChromeSearchResult|s into a |RankingItemType|. -RankingItemType RankingItemTypeFromSearchResultType( - const ash::SearchResultType& type); +// Convert a |ChromeSearchResult| into its |RankingItemType|. +RankingItemType RankingItemTypeFromSearchResult( + const ChromeSearchResult& result); // Return the type of an |ChromeAppListItem|. We currently do not distinguish // between different kinds of apps, and all |AppServiceAppItem|s are apps, so we
diff --git a/chrome/browser/ui/app_list/search/tests/app_search_provider_unittest.cc b/chrome/browser/ui/app_list/search/tests/app_search_provider_unittest.cc index b23b589..8309994f 100644 --- a/chrome/browser/ui/app_list/search/tests/app_search_provider_unittest.cc +++ b/chrome/browser/ui/app_list/search/tests/app_search_provider_unittest.cc
@@ -80,6 +80,8 @@ constexpr char kSettingsInternalName[] = "Settings"; +constexpr bool kEphemeralUser = true; + // Waits for base::Time::Now() is updated. void WaitTimeUpdated() { base::RunLoop run_loop; @@ -108,18 +110,25 @@ model_updater_ = std::make_unique<FakeAppListModelUpdater>(); controller_ = std::make_unique<::test::TestAppListControllerDelegate>(); + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); } void CreateSearch() { clock_.SetNow(kTestCurrentTime); + // Create ranker here so that tests can modify feature flags. + ranker_ = std::make_unique<AppSearchResultRanker>(temp_dir_.GetPath(), + kEphemeralUser); app_search_ = std::make_unique<AppSearchProvider>( - profile_.get(), nullptr, &clock_, model_updater_.get()); + profile_.get(), nullptr, &clock_, model_updater_.get(), ranker_.get()); } void CreateSearchWithContinueReading() { clock_.SetNow(kTestCurrentTime); + // Create ranker here so that tests can modify feature flags. + ranker_ = std::make_unique<AppSearchResultRanker>(temp_dir_.GetPath(), + kEphemeralUser); app_search_ = std::make_unique<AppSearchProvider>( - profile_.get(), nullptr, &clock_, model_updater_.get()); + profile_.get(), nullptr, &clock_, model_updater_.get(), ranker_.get()); session_tracker_ = std::make_unique<sync_sessions::SyncedSessionTracker>( &mock_sync_sessions_client_); @@ -216,9 +225,11 @@ private: base::SimpleTestClock clock_; + base::ScopedTempDir temp_dir_; std::unique_ptr<FakeAppListModelUpdater> model_updater_; std::unique_ptr<AppSearchProvider> app_search_; std::unique_ptr<::test::TestAppListControllerDelegate> controller_; + std::unique_ptr<AppSearchResultRanker> ranker_; ArcAppTest arc_test_; // For continue reading.
diff --git a/chrome/browser/ui/app_list/search/tests/mixer_unittest.cc b/chrome/browser/ui/app_list/search/tests/mixer_unittest.cc index 0d797e22..52b567b 100644 --- a/chrome/browser/ui/app_list/search/tests/mixer_unittest.cc +++ b/chrome/browser/ui/app_list/search/tests/mixer_unittest.cc
@@ -12,11 +12,17 @@ #include "ash/public/cpp/app_list/app_list_config.h" #include "ash/public/cpp/app_list/app_list_features.h" +#include "ash/public/cpp/app_list/app_list_types.h" +#include "base/files/scoped_temp_dir.h" #include "base/stl_util.h" #include "base/strings/string16.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/scoped_feature_list.h" +#include "base/test/scoped_task_environment.h" #include "chrome/browser/ui/app_list/search/search_provider.h" +#include "chrome/browser/ui/app_list/search/search_result_ranker/ranking_item_util.h" +#include "chrome/browser/ui/app_list/search/search_result_ranker/recurrence_ranker.h" #include "chrome/browser/ui/app_list/test/fake_app_list_model_updater.h" #include "testing/gtest/include/gtest/gtest.h" @@ -25,11 +31,15 @@ namespace app_list { namespace test { +using ResultType = ash::SearchResultType; + // Maximum number of results to show in each mixer group. const size_t kMaxAppsGroupResults = 4; const size_t kMaxOmniboxResults = 4; const size_t kMaxWebstoreResults = 2; +const bool kEphemeralUser = false; + class TestSearchResult : public ChromeSearchResult { public: TestSearchResult(const std::string& id, double relevance) @@ -62,11 +72,13 @@ class TestSearchProvider : public SearchProvider { public: - explicit TestSearchProvider(const std::string& prefix) + TestSearchProvider(const std::string& prefix, ResultType result_type) : prefix_(prefix), count_(0), bad_relevance_range_(false), - display_type_(ash::SearchResultDisplayType::kList) {} + small_relevance_range_(false), + display_type_(ash::SearchResultDisplayType::kList), + result_type_(result_type) {} ~TestSearchProvider() override {} // SearchProvider overrides: @@ -80,8 +92,13 @@ // of the canonical [0.0, 1.0] range. if (bad_relevance_range_) relevance = 10.0 - i * 10; + // If |small_relevance_range_|, keep the relevances in the same order, but + // make the differences very small: 0.5, 0.499, 0.498, ... + if (small_relevance_range_) + relevance = 0.5 - i / 100.0; TestSearchResult* result = new TestSearchResult(id, relevance); result->SetDisplayType(display_type_); + result->SetResultType(result_type_); Add(std::unique_ptr<ChromeSearchResult>(result)); } } @@ -92,12 +109,15 @@ } void set_count(size_t count) { count_ = count; } void set_bad_relevance_range() { bad_relevance_range_ = true; } + void set_small_relevance_range() { small_relevance_range_ = true; } private: std::string prefix_; size_t count_; bool bad_relevance_range_; + bool small_relevance_range_; ChromeSearchResult::DisplayType display_type_; + ResultType result_type_; DISALLOW_COPY_AND_ASSIGN(TestSearchProvider); }; @@ -111,12 +131,46 @@ void SetUp() override { model_updater_ = std::make_unique<FakeAppListModelUpdater>(); - providers_.push_back(std::make_unique<TestSearchProvider>("app")); - providers_.push_back(std::make_unique<TestSearchProvider>("omnibox")); - providers_.push_back(std::make_unique<TestSearchProvider>("webstore")); + providers_.push_back( + std::make_unique<TestSearchProvider>("app", ResultType::kInternalApp)); + providers_.push_back( + std::make_unique<TestSearchProvider>("omnibox", ResultType::kOmnibox)); + providers_.push_back(std::make_unique<TestSearchProvider>( + "webstore", ResultType::kWebStoreApp)); + } + + void CreateMixer(bool use_adaptive_ranker, + const std::map<std::string, std::string>& params = {}) { + if (use_adaptive_ranker) { + scoped_feature_list_.InitAndEnableFeatureWithParameters( + app_list_features::kEnableAdaptiveResultRanker, params); + } else { + scoped_feature_list_.InitWithFeatures( + {}, {app_list_features::kEnableAdaptiveResultRanker}); + } mixer_ = std::make_unique<Mixer>(model_updater_.get()); + if (use_adaptive_ranker) { + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + + RecurrenceRankerConfigProto ranker_config; + ranker_config.set_min_seconds_between_saves(240u); + auto* predictor = ranker_config.mutable_zero_state_frecency_predictor(); + predictor->set_target_limit(200u); + predictor->set_decay_coeff(0.8f); + auto* fallback = ranker_config.mutable_fallback_predictor(); + fallback->set_target_limit(200u); + fallback->set_decay_coeff(0.8f); + + std::unique_ptr<RecurrenceRanker> ranker = + std::make_unique<RecurrenceRanker>( + temp_dir_.GetPath().AppendASCII("ranker_model.proto"), + ranker_config, kEphemeralUser); + Wait(); + mixer_->SetRecurrenceRanker(std::move(ranker)); + } + // TODO(warx): when fullscreen app list is default enabled, modify this test // to test answer card/apps group having relevance boost. size_t apps_group_id = mixer_->AddGroup(kMaxAppsGroupResults, 1.0, 0.0); @@ -150,12 +204,22 @@ return result; } + void Train(const std::string& id, const RankingItemType& type) { + mixer_->Train(id, type); + } + + void Wait() { scoped_task_environment_.RunUntilIdle(); } + Mixer* mixer() { return mixer_.get(); } TestSearchProvider* app_provider() { return providers_[0].get(); } TestSearchProvider* omnibox_provider() { return providers_[1].get(); } TestSearchProvider* webstore_provider() { return providers_[2].get(); } private: + base::test::ScopedTaskEnvironment scoped_task_environment_; + base::test::ScopedFeatureList scoped_feature_list_; + base::ScopedTempDir temp_dir_; + std::unique_ptr<Mixer> mixer_; std::unique_ptr<FakeAppListModelUpdater> model_updater_; @@ -165,6 +229,9 @@ }; TEST_F(MixerTest, Basic) { + // Create mixer without adaptive ranker. + CreateMixer(false); + // Note: Some cases in |expected| have vastly more results than others, due to // the "at least 6" mechanism. If it gets at least 6 results from all // providers, it stops at 6. If not, it fetches potentially many more results @@ -216,6 +283,9 @@ } TEST_F(MixerTest, RemoveDuplicates) { + // Create mixer without adaptive ranker. + CreateMixer(false); + const std::string dup = "dup"; // This gives "dup0,dup1,dup2". @@ -236,5 +306,40 @@ EXPECT_EQ("dup0,dup1,dup2", GetResults()); } +TEST_F(MixerTest, RankerIsDisabledWithFlag) { + CreateMixer(false); + + for (int i = 0; i < 20; ++i) + Train("omnibox2", RankingItemType::kOmnibox); + + app_provider()->set_count(4); + app_provider()->set_small_relevance_range(); + omnibox_provider()->set_count(4); + omnibox_provider()->set_small_relevance_range(); + RunQuery(); + + // Expect training calls to have not affected rankings. + EXPECT_EQ(GetResults(), + "app0,omnibox0,app1,omnibox1,app2,omnibox2,app3,omnibox3"); +} + +TEST_F(MixerTest, RankerImprovesScores) { + CreateMixer(true, {{"boost_coefficient", "10.0"}}); + + for (int i = 0; i < 20; ++i) + Train("omnibox2", RankingItemType::kOmnibox); + + app_provider()->set_count(4); + app_provider()->set_small_relevance_range(); + omnibox_provider()->set_count(4); + omnibox_provider()->set_small_relevance_range(); + RunQuery(); + + // Omnibox results exist in the ranker and should be up-weighted to the top of + // the list. + EXPECT_EQ(GetResults(), + "omnibox0,omnibox1,omnibox2,omnibox3,app0,app1,app2,app3"); +} + } // namespace test } // namespace app_list
diff --git a/chrome/browser/ui/app_list/test/fake_app_list_model_updater.cc b/chrome/browser/ui/app_list/test/fake_app_list_model_updater.cc index 41aa5bf..6fded37 100644 --- a/chrome/browser/ui/app_list/test/fake_app_list_model_updater.cc +++ b/chrome/browser/ui/app_list/test/fake_app_list_model_updater.cc
@@ -10,7 +10,8 @@ #include "chrome/browser/ui/app_list/chrome_app_list_item.h" #include "extensions/common/constants.h" -FakeAppListModelUpdater::FakeAppListModelUpdater() = default; +FakeAppListModelUpdater::FakeAppListModelUpdater(Profile* profile) + : profile_(profile) {} FakeAppListModelUpdater::~FakeAppListModelUpdater() = default; @@ -214,6 +215,17 @@ } } +void FakeAppListModelUpdater::OnFolderCreated( + ash::mojom::AppListItemMetadataPtr folder) { + std::unique_ptr<ChromeAppListItem> stub_folder = + std::make_unique<ChromeAppListItem>(profile_, folder->id, this); + + for (AppListModelUpdaterObserver& observer : observers_) + observer.OnAppListItemAdded(stub_folder.get()); + + AddItem(std::move(stub_folder)); +} + void FakeAppListModelUpdater::AddObserver( AppListModelUpdaterObserver* observer) { observers_.AddObserver(observer);
diff --git a/chrome/browser/ui/app_list/test/fake_app_list_model_updater.h b/chrome/browser/ui/app_list/test/fake_app_list_model_updater.h index ba9dfabef..97f4620 100644 --- a/chrome/browser/ui/app_list/test/fake_app_list_model_updater.h +++ b/chrome/browser/ui/app_list/test/fake_app_list_model_updater.h
@@ -18,7 +18,7 @@ class FakeAppListModelUpdater : public AppListModelUpdater { public: - FakeAppListModelUpdater(); + explicit FakeAppListModelUpdater(Profile* profile = nullptr); ~FakeAppListModelUpdater() override; // For AppListModel: @@ -62,7 +62,7 @@ return search_results_; } - void OnFolderCreated(ash::mojom::AppListItemMetadataPtr folder) override {} + void OnFolderCreated(ash::mojom::AppListItemMetadataPtr folder) override; void OnFolderDeleted(ash::mojom::AppListItemMetadataPtr item) override {} void OnItemUpdated(ash::mojom::AppListItemMetadataPtr item) override {} void OnPageBreakItemAdded(const std::string& id, @@ -77,6 +77,7 @@ std::vector<std::unique_ptr<ChromeAppListItem>> items_; std::vector<ChromeSearchResult*> search_results_; base::ObserverList<AppListModelUpdaterObserver> observers_; + Profile* profile_; ash::mojom::AppListItemMetadataPtr FindOrCreateOemFolder( const std::string& oem_folder_name,
diff --git a/chrome/browser/ui/ash/keyboard/chrome_keyboard_controller_client.cc b/chrome/browser/ui/ash/keyboard/chrome_keyboard_controller_client.cc index 82bd0d6..760395f 100644 --- a/chrome/browser/ui/ash/keyboard/chrome_keyboard_controller_client.cc +++ b/chrome/browser/ui/ash/keyboard/chrome_keyboard_controller_client.cc
@@ -248,11 +248,6 @@ if (!virtual_keyboard_url_for_test_.is_empty()) return virtual_keyboard_url_for_test_; - if (base::CommandLine::ForCurrentProcess()->HasSwitch( - keyboard::switches::kDisableInputView)) { - return GURL(keyboard::kKeyboardURL); - } - chromeos::input_method::InputMethodManager* ime_manager = chromeos::input_method::InputMethodManager::Get(); if (!ime_manager || !ime_manager->GetActiveIMEState())
diff --git a/chrome/browser/ui/browser_window.h b/chrome/browser/ui/browser_window.h index f43018b7..c5e2aa6 100644 --- a/chrome/browser/ui/browser_window.h +++ b/chrome/browser/ui/browser_window.h
@@ -414,6 +414,7 @@ AVATAR_BUBBLE_MODE_REAUTH, AVATAR_BUBBLE_MODE_CONFIRM_SIGNIN, AVATAR_BUBBLE_MODE_SHOW_ERROR, + AVATAR_BUBBLE_MODE_INCOGNITO, }; virtual void ShowAvatarBubbleFromAvatarButton( AvatarBubbleMode mode,
diff --git a/chrome/browser/ui/cocoa/color_chooser_mac.h b/chrome/browser/ui/cocoa/color_chooser_mac.h index 511000dc..9dbcc9f 100644 --- a/chrome/browser/ui/cocoa/color_chooser_mac.h +++ b/chrome/browser/ui/cocoa/color_chooser_mac.h
@@ -15,7 +15,7 @@ // A Listener class to act as a event target for NSColorPanel and send // the results to the C++ class, ColorChooserMac. -@interface ColorPanelCocoa : NSObject<NSWindowDelegate> { +@interface ColorPanelCocoa : NSObject { @protected // We don't call DidChooseColor if the change wasn't caused by the user // interacting with the panel. @@ -26,6 +26,8 @@ - (id)initWithChooser:(ColorChooserMac*)chooser; +- (void)windowWillClose:(NSNotification*)notification; + // Called from NSColorPanel. - (void)didChooseColor:(NSColorPanel*)panel; @@ -45,7 +47,7 @@ // Called from ColorPanelCocoa. void DidChooseColorInColorPanel(SkColor color); - void DidCloseColorPabel(); + void DidCloseColorPanel(); // Set the color programmatically. void SetSelectedColor(SkColor color) override;
diff --git a/chrome/browser/ui/cocoa/color_chooser_mac.mm b/chrome/browser/ui/cocoa/color_chooser_mac.mm index bf47154..e7cdab7a2 100644 --- a/chrome/browser/ui/cocoa/color_chooser_mac.mm +++ b/chrome/browser/ui/cocoa/color_chooser_mac.mm
@@ -39,16 +39,18 @@ web_contents_->DidChooseColorInColorChooser(color); } -void ColorChooserMac::DidCloseColorPabel() { +void ColorChooserMac::DidCloseColorPanel() { End(); } void ColorChooserMac::End() { - panel_.reset(); - DCHECK(current_color_chooser_ == this); - current_color_chooser_ = NULL; - if (web_contents_) + if (panel_) { + panel_.reset(); + DCHECK(current_color_chooser_ == this); + current_color_chooser_ = NULL; + if (web_contents_) web_contents_->DidEndColorChooser(); + } } void ColorChooserMac::SetSelectedColor(SkColor color) { @@ -67,9 +69,14 @@ chooser_ = chooser; NSColorPanel* panel = [NSColorPanel sharedColorPanel]; [panel setShowsAlpha:NO]; - [panel setDelegate:self]; [panel setTarget:self]; [panel setAction:@selector(didChooseColor:)]; + + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(windowWillClose:) + name:NSWindowWillCloseNotification + object:panel]; } return self; } @@ -82,19 +89,21 @@ // the ColorPanelCocoa is still the target. BOOL respondsToPrivateTargetMethod = [panel respondsToSelector:@selector(__target)]; - - if ([panel delegate] == self || - (respondsToPrivateTargetMethod && [panel __target] == self)) { - [panel setDelegate:nil]; + if (respondsToPrivateTargetMethod && [panel __target] == self) { [panel setTarget:nil]; [panel setAction:nullptr]; } + [[NSNotificationCenter defaultCenter] + removeObserver:self + name:NSWindowWillCloseNotification + object:panel]; + [super dealloc]; } - (void)windowWillClose:(NSNotification*)notification { - chooser_->DidCloseColorPabel(); + chooser_->DidCloseColorPanel(); nonUserChange_ = NO; }
diff --git a/chrome/browser/ui/cocoa/color_panel_cocoa_unittest.mm b/chrome/browser/ui/cocoa/color_panel_cocoa_unittest.mm index 83185ce..823365f 100644 --- a/chrome/browser/ui/cocoa/color_panel_cocoa_unittest.mm +++ b/chrome/browser/ui/cocoa/color_panel_cocoa_unittest.mm
@@ -28,28 +28,6 @@ } }; -TEST_F(ColorPanelCocoaTest, ClearTargetAndDelegateOnEnd) { - NSColorPanel* nscolor_panel = [NSColorPanel sharedColorPanel]; - @autoreleasepool { - EXPECT_TRUE([nscolor_panel respondsToSelector:@selector(__target)]); - - // Create a ColorPanelCocoa. - ColorChooserMac* color_chooser_mac = - ColorChooserMac::Open(nullptr, SK_ColorBLACK); - - // Confirm the NSColorPanel's configuration by the ColorChooserMac's - // ColorPanelCocoa. - EXPECT_TRUE([nscolor_panel delegate]); - EXPECT_TRUE([nscolor_panel __target]); - - // Release the ColorPanelCocoa and confirm it's no longer the NSColorPanel's - // target or delegate. - color_chooser_mac->End(); - } - EXPECT_EQ([nscolor_panel delegate], nil); - EXPECT_EQ([nscolor_panel __target], nil); -} - TEST_F(ColorPanelCocoaTest, ClearTargetOnEnd) { NSColorPanel* nscolor_panel = [NSColorPanel sharedColorPanel]; @autoreleasepool { @@ -61,19 +39,12 @@ // Confirm the NSColorPanel's configuration by the ColorChooserMac's // ColorPanelCocoa. - EXPECT_TRUE([nscolor_panel delegate]); EXPECT_TRUE([nscolor_panel __target]); - // Clear the delegate and release the ColorPanelCocoa. - [nscolor_panel setDelegate:nil]; - // Release the ColorPanelCocoa. color_chooser_mac->End(); } - // Confirm the ColorPanelCocoa is no longer the NSColorPanel's target or - // delegate. Previously the ColorPanelCocoa would not clear the target if - // the delegate had already been cleared. - EXPECT_EQ([nscolor_panel delegate], nil); + // Confirm the ColorPanelCocoa is no longer the NSColorPanel's target EXPECT_EQ([nscolor_panel __target], nil); }
diff --git a/chrome/browser/ui/libgtkui/select_file_dialog_impl_gtk.cc b/chrome/browser/ui/libgtkui/select_file_dialog_impl_gtk.cc index 5cab3f9e..1986b41 100644 --- a/chrome/browser/ui/libgtkui/select_file_dialog_impl_gtk.cc +++ b/chrome/browser/ui/libgtkui/select_file_dialog_impl_gtk.cc
@@ -43,11 +43,11 @@ const char kOpenLabel[] = "_Open"; const char kSaveLabel[] = "_Save"; #else -G_GNUC_BEGIN_IGNORE_DEPRECATIONS; +G_GNUC_BEGIN_IGNORE_DEPRECATIONS const char* const kCancelLabel = GTK_STOCK_CANCEL; const char* const kOpenLabel = GTK_STOCK_OPEN; const char* const kSaveLabel = GTK_STOCK_SAVE; -G_GNUC_END_IGNORE_DEPRECATIONS; +G_GNUC_END_IGNORE_DEPRECATIONS #endif // Makes sure that .jpg also shows .JPG.
diff --git a/chrome/browser/ui/login/login_handler.cc b/chrome/browser/ui/login/login_handler.cc index 7bf7e58..276d9cf 100644 --- a/chrome/browser/ui/login/login_handler.cc +++ b/chrome/browser/ui/login/login_handler.cc
@@ -193,19 +193,10 @@ : WebContentsObserver(web_contents), auth_info_(auth_info), auth_required_callback_(std::move(auth_required_callback)), + prompt_started_(false), weak_factory_(this) { DCHECK(web_contents); DCHECK(auth_info_) << "LoginHandler constructed with NULL auth info"; - - // This is probably OK; we need to listen to everything and we break out of - // the Observe() if we aren't handling the same auth_info(). - // - // TODO(davidben): We only need to listen to notifications within a single - // BrowserContext. - registrar_.Add(this, chrome::NOTIFICATION_AUTH_SUPPLIED, - content::NotificationService::AllBrowserContextsAndSources()); - registrar_.Add(this, chrome::NOTIFICATION_AUTH_CANCELLED, - content::NotificationService::AllBrowserContextsAndSources()); } LoginHandler::~LoginHandler() { @@ -362,7 +353,7 @@ void LoginHandler::NotifyAuthNeeded() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (WasAuthHandled()) + if (WasAuthHandled() || !prompt_started_) return; content::NotificationService* service = @@ -381,7 +372,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(WasAuthHandled()); - if (!web_contents()) + if (!web_contents() || !prompt_started_) return; content::NotificationService* service = @@ -399,6 +390,9 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(WasAuthHandled()); + if (!prompt_started_) + return; + content::NotificationService* service = content::NotificationService::current(); NavigationController* controller = @@ -528,6 +522,17 @@ return; } + // This is OK; we break out of the Observe() if we aren't handling the same + // auth_info() or BrowserContext. + // + // TODO(davidben): Only listen to notifications within a single + // BrowserContext. + registrar_.Add(this, chrome::NOTIFICATION_AUTH_SUPPLIED, + content::NotificationService::AllBrowserContextsAndSources()); + registrar_.Add(this, chrome::NOTIFICATION_AUTH_CANCELLED, + content::NotificationService::AllBrowserContextsAndSources()); + prompt_started_ = true; + // Check if this is a main frame navigation and // (a) if the request is cross origin or // (b) if an interstitial is already being shown or
diff --git a/chrome/browser/ui/login/login_handler.h b/chrome/browser/ui/login/login_handler.h index 18a2295..451e9b3a 100644 --- a/chrome/browser/ui/login/login_handler.h +++ b/chrome/browser/ui/login/login_handler.h
@@ -181,6 +181,9 @@ LoginAuthRequiredCallback auth_required_callback_; base::WeakPtr<LoginInterstitialDelegate> interstitial_delegate_; + + // True if the extensions logic has run and the prompt logic has started. + bool prompt_started_; base::WeakPtrFactory<LoginHandler> weak_factory_; };
diff --git a/chrome/browser/ui/login/login_handler_browsertest.cc b/chrome/browser/ui/login/login_handler_browsertest.cc index dd3d822..d84560170 100644 --- a/chrome/browser/ui/login/login_handler_browsertest.cc +++ b/chrome/browser/ui/login/login_handler_browsertest.cc
@@ -646,15 +646,6 @@ // Testing for recovery from an incorrect password for the case where // there are multiple authenticated resources. IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, IncorrectConfirmation) { -#if BUILDFLAG(ENABLE_EXTENSIONS) - // TODO(http://crbug.com/928465): This test has some timing issues that cause - // the asserts to fail when the webRequest proxy is enabled. - if (base::FeatureList::IsEnabled( - extensions_features::kForceWebRequestProxyForTest)) { - return; - } -#endif - ASSERT_TRUE(embedded_test_server()->Start()); GURL test_page = embedded_test_server()->GetURL(kSingleRealmTestPage);
diff --git a/chrome/browser/ui/login/login_handler_test_utils.cc b/chrome/browser/ui/login/login_handler_test_utils.cc index b7b6bd01..097a9c6 100644 --- a/chrome/browser/ui/login/login_handler_test_utils.cc +++ b/chrome/browser/ui/login/login_handler_test_utils.cc
@@ -41,6 +41,11 @@ auto i = std::find(handlers_.begin(), handlers_.end(), handler); // Cannot use ASSERT_NE, because gTest on Android confuses iterators with // containers. + // + // TODO(davidben): NOTIFICATION_AUTH_SUPPLIED and NOTIFICATION_AUTH_CANCELLED + // are not quite guaranteed to come after NOTIFICATION_AUTH_NEEDED. Either + // remove this assumption from the test class or fix things so this assumption + // holds. ASSERT_TRUE(i != handlers_.end()); handlers_.erase(i); }
diff --git a/chrome/browser/ui/profile_chooser_constants.h b/chrome/browser/ui/profile_chooser_constants.h index 8b69c3e..72584c56 100644 --- a/chrome/browser/ui/profile_chooser_constants.h +++ b/chrome/browser/ui/profile_chooser_constants.h
@@ -25,6 +25,8 @@ BUBBLE_VIEW_MODE_GAIA_REAUTH, // Shows a view for confirming account removal. BUBBLE_VIEW_MODE_ACCOUNT_REMOVAL, + // Shows a view for incognito that displays the number of incognito windows. + BUBBLE_VIEW_MODE_INCOGNITO, }; } // namespace profiles
diff --git a/chrome/browser/ui/settings_window_manager_chromeos.cc b/chrome/browser/ui/settings_window_manager_chromeos.cc index 01da3df..0c2776d 100644 --- a/chrome/browser/ui/settings_window_manager_chromeos.cc +++ b/chrome/browser/ui/settings_window_manager_chromeos.cc
@@ -17,6 +17,7 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "content/public/browser/web_contents.h" #include "ui/aura/client/aura_constants.h" +#include "ui/base/ui_base_features.h" #include "url/gurl.h" namespace chrome { @@ -76,8 +77,11 @@ auto* window = params.browser->window()->GetNativeWindow(); window->SetProperty(kOverrideWindowIconResourceIdKey, IDR_SETTINGS_LOGO_192); - window->SetProperty(aura::client::kAppType, - static_cast<int>(ash::AppType::CHROME_APP)); + // For Mash, this is set by BrowserFrameMash. + if (!features::IsUsingWindowService()) { + window->SetProperty(aura::client::kAppType, + static_cast<int>(ash::AppType::CHROME_APP)); + } for (SettingsWindowManagerObserver& observer : observers_) observer.OnNewSettingsWindow(params.browser);
diff --git a/chrome/browser/ui/toolbar/chrome_location_bar_model_delegate.cc b/chrome/browser/ui/toolbar/chrome_location_bar_model_delegate.cc index e6b0ed0..75c4de6 100644 --- a/chrome/browser/ui/toolbar/chrome_location_bar_model_delegate.cc +++ b/chrome/browser/ui/toolbar/chrome_location_bar_model_delegate.cc
@@ -18,7 +18,6 @@ #include "components/offline_pages/buildflags/buildflags.h" #include "components/omnibox/browser/autocomplete_input.h" #include "components/prefs/pref_service.h" -#include "components/security_interstitials/content/security_interstitial_tab_helper.h" #include "components/security_state/core/security_state.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" @@ -94,12 +93,6 @@ if (!entry) return true; - security_interstitials::SecurityInterstitialTabHelper* tab_helper = - security_interstitials::SecurityInterstitialTabHelper::FromWebContents( - GetActiveWebContents()); - if (tab_helper && tab_helper->IsDisplayingInterstitial()) - return tab_helper->ShouldDisplayURL(); - if (entry->IsViewSourceMode() || entry->GetPageType() == content::PAGE_TYPE_INTERSTITIAL) { return true;
diff --git a/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.cc b/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.cc index de6f7a6..360744b 100644 --- a/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.cc +++ b/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.cc
@@ -18,6 +18,7 @@ #include "ash/public/cpp/window_properties.h" #include "ash/public/cpp/window_state_type.h" #include "ash/public/interfaces/constants.mojom.h" +#include "ash/public/interfaces/window_properties.mojom.h" #include "ash/wm/window_state.h" // mash-ok #include "base/bind.h" #include "base/logging.h" @@ -108,8 +109,11 @@ const AppWindow::CreateParams& create_params) { ChromeNativeAppWindowViewsAura::InitializeWindow(app_window, create_params); aura::Window* window = GetNativeWindow(); - window->SetProperty(aura::client::kAppType, - static_cast<int>(ash::AppType::CHROME_APP)); + // For Mash, this property is set in OnBeforeWidgetInit. + if (!features::IsUsingWindowService()) { + window->SetProperty(aura::client::kAppType, + static_cast<int>(ash::AppType::CHROME_APP)); + } window->SetProperty( ash::kImmersiveWindowType, static_cast<int>( @@ -168,6 +172,9 @@ init_params ->mus_properties[ws::mojom::WindowManager::kWindowTitleShown_Property] = mojo::ConvertTo<std::vector<uint8_t>>(static_cast<int64_t>(false)); + init_params->mus_properties[ash::mojom::kAppType_Property] = + mojo::ConvertTo<std::vector<uint8_t>>( + static_cast<int64_t>(ash::AppType::CHROME_APP)); } views::NonClientFrameView*
diff --git a/chrome/browser/ui/views/color_chooser_dialog.cc b/chrome/browser/ui/views/color_chooser_dialog.cc index c26be85..1f568a2 100644 --- a/chrome/browser/ui/views/color_chooser_dialog.cc +++ b/chrome/browser/ui/views/color_chooser_dialog.cc
@@ -24,12 +24,14 @@ // static COLORREF ColorChooserDialog::g_custom_colors[16]; -ColorChooserDialog::ColorChooserDialog(views::ColorChooserListener* listener, - SkColor initial_color, - gfx::NativeWindow owning_window) +ColorChooserDialog::ColorChooserDialog(views::ColorChooserListener* listener) : listener_(listener) { DCHECK(listener_); CopyCustomColors(g_custom_colors, custom_colors_); +} + +void ColorChooserDialog::Open(SkColor initial_color, + gfx::NativeWindow owning_window) { HWND owning_hwnd = views::HWNDForNativeWindow(owning_window); std::unique_ptr<RunState> run_state = BeginRun(owning_hwnd);
diff --git a/chrome/browser/ui/views/color_chooser_dialog.h b/chrome/browser/ui/views/color_chooser_dialog.h index 838e22d..b2558ce 100644 --- a/chrome/browser/ui/views/color_chooser_dialog.h +++ b/chrome/browser/ui/views/color_chooser_dialog.h
@@ -23,9 +23,9 @@ public ui::BaseShellDialog, public ui::BaseShellDialogImpl { public: - ColorChooserDialog(views::ColorChooserListener* listener, - SkColor initial_color, - gfx::NativeWindow owning_window); + explicit ColorChooserDialog(views::ColorChooserListener* listener); + + void Open(SkColor initial_color, gfx::NativeWindow owning_window); // BaseShellDialog: bool IsRunning(gfx::NativeWindow owning_window) const override;
diff --git a/chrome/browser/ui/views/color_chooser_win.cc b/chrome/browser/ui/views/color_chooser_win.cc index 434842ba..ffc58eec 100644 --- a/chrome/browser/ui/views/color_chooser_win.cc +++ b/chrome/browser/ui/views/color_chooser_win.cc
@@ -61,9 +61,8 @@ ->GetWidget() ->GetView() ->GetNativeView()); - color_chooser_dialog_ = new ColorChooserDialog(this, - initial_color, - owning_window); + color_chooser_dialog_ = new ColorChooserDialog(this); + color_chooser_dialog_->Open(initial_color, owning_window); } ColorChooserWin::~ColorChooserWin() { @@ -90,11 +89,11 @@ if (color_chooser_dialog_.get()) { color_chooser_dialog_->ListenerDestroyed(); color_chooser_dialog_ = NULL; + DCHECK(current_color_chooser_ == this); + current_color_chooser_ = NULL; + if (web_contents_) + web_contents_->DidEndColorChooser(); } - DCHECK(current_color_chooser_ == this); - current_color_chooser_ = NULL; - if (web_contents_) - web_contents_->DidEndColorChooser(); } namespace chrome {
diff --git a/chrome/browser/ui/views/frame/browser_frame_mash.cc b/chrome/browser/ui/views/frame/browser_frame_mash.cc index 602de96..92eb1c3 100644 --- a/chrome/browser/ui/views/frame/browser_frame_mash.cc +++ b/chrome/browser/ui/views/frame/browser_frame_mash.cc
@@ -8,6 +8,7 @@ #include <memory> +#include "ash/public/cpp/app_types.h" #include "ash/public/cpp/shelf_types.h" #include "ash/public/cpp/window_properties.h" #include "ash/public/cpp/window_state_type.h" @@ -75,6 +76,11 @@ properties[ash::mojom::kCanConsumeSystemKeys_Property] = mojo::ConvertTo<std::vector<uint8_t>>( static_cast<int64_t>(browser->is_app())); + properties[ash::mojom::kAppType_Property] = + mojo::ConvertTo<std::vector<uint8_t>>(static_cast<int64_t>( + BrowserNonClientFrameViewAsh::UsePackagedAppHeaderStyle(browser) + ? ash::AppType::CHROME_APP + : ash::AppType::BROWSER)); aura::WindowTreeHostMusInitParams window_tree_host_init_params = aura::CreateInitParamsForTopLevel(
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc index a0ad731..3e03982 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc
@@ -181,10 +181,13 @@ UpdateProfileIcons(); aura::Window* window = frame()->GetNativeWindow(); - window->SetProperty( - aura::client::kAppType, - static_cast<int>(browser->is_app() ? ash::AppType::CHROME_APP - : ash::AppType::BROWSER)); + // For Mash, this property is set in BrowserFrameMash as an init property. + if (!features::IsUsingWindowService()) { + window->SetProperty( + aura::client::kAppType, + static_cast<int>(browser->is_app() ? ash::AppType::CHROME_APP + : ash::AppType::BROWSER)); + } window_observer_.Add(GetFrameWindow());
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index 9894b6a..20060be 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -2423,7 +2423,7 @@ void BrowserView::OnThemeChanged() { if (!IsRegularOrGuestSession()) { - // When the theme changes, the native theme may also change (in incognito, + // When the theme changes, the native theme may also change (in Incognito, // the usage of dark or normal hinges on the browser theme), so we have to // propagate both kinds of change. base::AutoReset<bool> reset(&handling_theme_changed_, true); @@ -2958,10 +2958,6 @@ signin_metrics::AccessPoint access_point, bool focus_first_profile_button) { #if !defined(OS_CHROMEOS) - // Never show any avatar bubble in Incognito. - if (!IsRegularOrGuestSession()) - return; - // Do not show avatar bubble if there is no avatar menu button. views::Button* avatar_button = toolbar_->avatar_button(); if (!avatar_button)
diff --git a/chrome/browser/ui/views/omnibox/omnibox_result_view.cc b/chrome/browser/ui/views/omnibox/omnibox_result_view.cc index 2ac62244..b475372 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_result_view.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_result_view.cc
@@ -163,6 +163,8 @@ // Answers use their own styling for additional content text and the // description text, whereas non-answer suggestions use the match text and // calculated classifications for the description text. + bool blue_search_query = base::FeatureList::IsEnabled( + omnibox::kUIExperimentBlueSearchLoopAndSearchQuery); if (match_.answer) { const bool reverse = OmniboxFieldTrial::IsReverseAnswersEnabled() && !match_.IsExceptedFromLineReversal(); @@ -171,14 +173,16 @@ suggestion_view_->description()->SetText(match_.contents, match_.contents_class, true); suggestion_view_->description()->ApplyTextColor( - OmniboxPart::RESULTS_TEXT_DIMMED); + blue_search_query ? OmniboxPart::RESULTS_TEXT_URL + : OmniboxPart::RESULTS_TEXT_DIMMED); suggestion_view_->description()->AppendExtraText( match_.answer->first_line()); } else { suggestion_view_->content()->SetText(match_.contents, match_.contents_class); suggestion_view_->content()->ApplyTextColor( - OmniboxPart::RESULTS_TEXT_DEFAULT); + blue_search_query ? OmniboxPart::RESULTS_TEXT_URL + : OmniboxPart::RESULTS_TEXT_DEFAULT); suggestion_view_->content()->AppendExtraText(match_.answer->first_line()); suggestion_view_->description()->SetText(match_.answer->second_line(), true); @@ -189,6 +193,10 @@ // adjustments like answers above. Pedals do likewise. suggestion_view_->content()->SetText(match_.contents, match_.contents_class); + if (blue_search_query) { + suggestion_view_->content()->ApplyTextColor( + OmniboxPart::RESULTS_TEXT_URL); + } suggestion_view_->description()->SetText(match_.description, match_.description_class, -1); suggestion_view_->description()->ApplyTextColor( @@ -207,6 +215,13 @@ suggestion_view_->content()->ReapplyStyling(); suggestion_view_->description()->ReapplyStyling(); } + + // If the blue search query experiment is on, search suggestions are + // recolored at the end. + if (blue_search_query && AutocompleteMatch::IsSearchType(match_.type)) { + suggestion_view_->content()->ApplyTextColor( + OmniboxPart::RESULTS_TEXT_URL); + } } AutocompleteMatch* keyword_match = match_.associated_keyword.get();
diff --git a/chrome/browser/ui/views/profiles/avatar_toolbar_button.cc b/chrome/browser/ui/views/profiles/avatar_toolbar_button.cc index 5f2a62d..56499ea 100644 --- a/chrome/browser/ui/views/profiles/avatar_toolbar_button.cc +++ b/chrome/browser/ui/views/profiles/avatar_toolbar_button.cc
@@ -23,7 +23,6 @@ #include "chrome/browser/ui/layout_constants.h" #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" -#include "chrome/browser/ui/views/profiles/incognito_window_count_view.h" #include "chrome/browser/ui/views/toolbar/toolbar_ink_drop_util.h" #include "chrome/common/chrome_features.h" #include "chrome/grit/generated_resources.h" @@ -161,21 +160,15 @@ // TODO(bsep): Other toolbar buttons have ToolbarView as a listener and let it // call ExecuteCommandWithDisposition on their behalf. Unfortunately, it's not // possible to plumb IsKeyEvent through, so this has to be a special case. - if (IsIncognitoCounterActive()) { - if (!IncognitoWindowCountView::IsShowing()) { - IncognitoWindowCountView::ShowBubble( - this, browser_, - BrowserList::GetIncognitoSessionsActiveForProfile(profile_)); - } - } else { - // TODO(https://crbug.com/896235): Call IncognitoWindowCountView::ShowBubble - // from this ShowAvatarBubbleFromAvatarButton. - browser_->window()->ShowAvatarBubbleFromAvatarButton( - BrowserWindow::AVATAR_BUBBLE_MODE_DEFAULT, - signin::ManageAccountsParams(), - signin_metrics::AccessPoint::ACCESS_POINT_AVATAR_BUBBLE_SIGN_IN, - event.IsKeyEvent()); - } + if (IsIncognito() && !IsIncognitoCounterActive()) + return; + + browser_->window()->ShowAvatarBubbleFromAvatarButton( + IsIncognito() ? BrowserWindow::AVATAR_BUBBLE_MODE_INCOGNITO + : BrowserWindow::AVATAR_BUBBLE_MODE_DEFAULT, + signin::ManageAccountsParams(), + signin_metrics::AccessPoint::ACCESS_POINT_AVATAR_BUBBLE_SIGN_IN, + event.IsKeyEvent()); } void AvatarToolbarButton::OnThemeChanged() { @@ -258,8 +251,12 @@ } bool AvatarToolbarButton::IsIncognitoCounterActive() const { +#if defined(OS_CHROMEOS) + return false; +#else return IsIncognito() && base::FeatureList::IsEnabled(features::kEnableIncognitoWindowCounter); +#endif // defined(OS_CHROMEOS) } bool AvatarToolbarButton::ShouldShowGenericIcon() const {
diff --git a/chrome/browser/ui/views/profiles/incognito_window_count_view.cc b/chrome/browser/ui/views/profiles/incognito_window_count_view.cc deleted file mode 100644 index 48e04e0..0000000 --- a/chrome/browser/ui/views/profiles/incognito_window_count_view.cc +++ /dev/null
@@ -1,113 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/views/profiles/incognito_window_count_view.h" - -#include "base/bind_helpers.h" -#include "chrome/app/vector_icons/vector_icons.h" -#include "chrome/browser/platform_util.h" -#include "chrome/browser/themes/theme_properties.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_list.h" -#include "chrome/browser/ui/browser_window.h" -#include "chrome/browser/ui/views/hover_button.h" -#include "chrome/grit/generated_resources.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/gfx/paint_vector_icon.h" -#include "ui/views/controls/separator.h" -#include "ui/views/layout/box_layout.h" - -// static -IncognitoWindowCountView* - IncognitoWindowCountView::incognito_window_counter_bubble_ = nullptr; - -// static -void IncognitoWindowCountView::ShowBubble(views::Button* anchor_button, - Browser* browser, - int incognito_window_count) { - // The IncognitoWindowCountView is self-owned, it deletes itself when the - // widget is closed or the parent browser is destroyed. - if (!IsShowing()) { - new IncognitoWindowCountView(anchor_button, browser, - incognito_window_count); - } -} - -// static -bool IncognitoWindowCountView::IsShowing() { - return incognito_window_counter_bubble_ != nullptr; -} - -IncognitoWindowCountView::IncognitoWindowCountView(views::Button* anchor_button, - Browser* browser, - int incognito_window_count) - : BubbleDialogDelegateView(anchor_button, views::BubbleBorder::TOP_RIGHT), - incognito_window_count_(incognito_window_count), - browser_(browser), - browser_list_observer_(this), - weak_ptr_factory_(this) { - DCHECK(incognito_window_counter_bubble_ == nullptr); - incognito_window_counter_bubble_ = this; - browser_list_observer_.Add(BrowserList::GetInstance()); - - // The lifetime of this bubble is tied to the lifetime of the browser. - set_parent_window( - platform_util::GetViewForWindow(browser_->window()->GetNativeWindow())); - - set_margins(gfx::Insets()); - views::BubbleDialogDelegateView::CreateBubble(this)->Show(); - chrome::RecordDialogCreation( - chrome::DialogIdentifier::INCOGNITO_WINDOW_COUNTER); -} - -IncognitoWindowCountView::~IncognitoWindowCountView() { - incognito_window_counter_bubble_ = nullptr; -} - -void IncognitoWindowCountView::OnBrowserRemoved(Browser* browser) { - if (browser_ == browser) - delete this; -} - -int IncognitoWindowCountView::GetDialogButtons() const { - return ui::DIALOG_BUTTON_NONE; -} - -void IncognitoWindowCountView::Init() { - SetLayoutManager(std::make_unique<views::BoxLayout>( - views::BoxLayout::Orientation::kVertical)); - - auto incognito_icon = std::make_unique<views::ImageView>(); - const SkColor icon_color = ThemeProperties::GetDefaultColor( - ThemeProperties::COLOR_NTP_BACKGROUND, true /* incognito */); - incognito_icon->SetImage( - gfx::CreateVectorIcon(kIncognitoProfileIcon, icon_color)); - - // TODO(https://crbug.com/915120): This Button is never clickable. Replace - // by an alternative list item. - HoverButton* title_line = new HoverButton( - nullptr, std::move(incognito_icon), - l10n_util::GetStringUTF16(IDS_INCOGNITO_WINDOW_COUNTER_TITLE), - l10n_util::GetPluralStringFUTF16(IDS_INCOGNITO_WINDOW_COUNTER_MESSAGE, - incognito_window_count_)); - title_line->SetState(views::Button::ButtonState::STATE_DISABLED); - - AddChildView(title_line); - AddChildView(new views::Separator()); - - AddChildView(new HoverButton( - this, gfx::CreateVectorIcon(kCloseAllIcon, 16, gfx::kChromeIconGrey), - l10n_util::GetStringUTF16(IDS_INCOGNITO_WINDOW_COUNTER_CLOSE_BUTTON))); -} - -bool IncognitoWindowCountView::ShouldSnapFrameWidth() const { - return true; -} - -void IncognitoWindowCountView::ButtonPressed(views::Button* sender, - const ui::Event& event) { - BrowserList::CloseAllBrowsersWithIncognitoProfile( - browser_->profile(), base::DoNothing(), base::DoNothing(), - false /* skip_beforeunload */); -}
diff --git a/chrome/browser/ui/views/profiles/incognito_window_count_view.h b/chrome/browser/ui/views/profiles/incognito_window_count_view.h deleted file mode 100644 index abfa622..0000000 --- a/chrome/browser/ui/views/profiles/incognito_window_count_view.h +++ /dev/null
@@ -1,59 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_VIEWS_PROFILES_INCOGNITO_WINDOW_COUNT_VIEW_H_ -#define CHROME_BROWSER_UI_VIEWS_PROFILES_INCOGNITO_WINDOW_COUNT_VIEW_H_ - -#include "base/macros.h" -#include "chrome/browser/ui/browser_list.h" -#include "chrome/browser/ui/browser_list_observer.h" -#include "ui/views/bubble/bubble_dialog_delegate_view.h" -#include "ui/views/controls/button/button.h" - -class Browser; - -// The implementation for a bubble that allows the user to close all open -// incognito windows. -// The IncognitoWindowCountView is self-owned and deletes itself when it is -// closed or the parent browser is being destroyed. -class IncognitoWindowCountView : public views::BubbleDialogDelegateView, - public BrowserListObserver, - public views::ButtonListener { - public: - static void ShowBubble(views::Button* anchor_button, - Browser* browser, - int incognito_window_count); - - static bool IsShowing(); - - // BubbleDialogDelegateView: - int GetDialogButtons() const override; - void Init() override; - bool ShouldSnapFrameWidth() const override; - - // BrowserListObserver: - void OnBrowserRemoved(Browser* browser) override; - - // views::ButtonListener: - void ButtonPressed(views::Button* sender, const ui::Event& event) override; - - private: - IncognitoWindowCountView(views::Button* anchor_button, - Browser* browser, - int incognito_window_count); - - ~IncognitoWindowCountView() override; - - int incognito_window_count_; - Browser* const browser_; - - static IncognitoWindowCountView* incognito_window_counter_bubble_; - - ScopedObserver<BrowserList, BrowserListObserver> browser_list_observer_; - base::WeakPtrFactory<IncognitoWindowCountView> weak_ptr_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(IncognitoWindowCountView); -}; - -#endif // CHROME_BROWSER_UI_VIEWS_PROFILES_INCOGNITO_WINDOW_COUNT_VIEW_H_
diff --git a/chrome/browser/ui/views/profiles/profile_chooser_view.cc b/chrome/browser/ui/views/profiles/profile_chooser_view.cc index caa8249d..74995a8 100644 --- a/chrome/browser/ui/views/profiles/profile_chooser_view.cc +++ b/chrome/browser/ui/views/profiles/profile_chooser_view.cc
@@ -18,6 +18,7 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" +#include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/profiles/profile_metrics.h" @@ -28,6 +29,7 @@ #include "chrome/browser/signin/signin_error_controller_factory.h" #include "chrome/browser/signin/signin_ui_util.h" #include "chrome/browser/sync/profile_sync_service_factory.h" +#include "chrome/browser/themes/theme_properties.h" #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/themes/theme_service_factory.h" #include "chrome/browser/ui/browser.h" @@ -522,6 +524,10 @@ layout = CreateSingleColumnLayout(this, menu_width_); sub_view = CreateProfileChooserView(avatar_menu); break; + case profiles::BUBBLE_VIEW_MODE_INCOGNITO: + layout = CreateSingleColumnLayout(this, menu_width_); + sub_view = CreateIncognitoWindowCountView(); + break; } views::ScrollView* scroll_view = new views::ScrollView; @@ -643,6 +649,14 @@ // If this is a guest session, close all the guest browser windows. if (browser_->profile()->IsGuestSession()) { profiles::CloseGuestProfileWindows(); + } else if (browser_->profile()->GetProfileType() == + Profile::INCOGNITO_PROFILE) { + // Skipping before-unload trigger to give incognito mode users a chance to + // close all incognito windows without needing to confirm closing the open + // forms. + BrowserList::CloseAllBrowsersWithIncognitoProfile( + browser_->profile(), base::DoNothing(), base::DoNothing(), + true /* skip_beforeunload */); } else { base::RecordAction( base::UserMetricsAction("ProfileChooser_ManageClicked")); @@ -827,6 +841,54 @@ chrome::ShowSettings(browser_); } +views::View* ProfileChooserView::CreateIncognitoWindowCountView() { + // TODO(https://crbug.com/896235): Refactor to merge this view with other + // views. + views::View* view = new views::View(); + views::GridLayout* layout = CreateSingleColumnLayout(view, menu_width_); + + ChromeLayoutProvider* provider = ChromeLayoutProvider::Get(); + int content_list_vert_spacing = + provider->GetDistanceMetric(DISTANCE_CONTENT_LIST_VERTICAL_SINGLE); + + int incognito_window_count = + BrowserList::GetIncognitoSessionsActiveForProfile(browser_->profile()); + auto incognito_icon = std::make_unique<views::ImageView>(); + const SkColor icon_color = ThemeProperties::GetDefaultColor( + ThemeProperties::COLOR_TOOLBAR, true /* incognito */); + incognito_icon->SetImage( + gfx::CreateVectorIcon(kIncognitoProfileIcon, icon_color)); + + // TODO(https://crbug.com/915120): This Button is never clickable. Replace + // by an alternative list item. + HoverButton* profile_card = new HoverButton( + nullptr, std::move(incognito_icon), + l10n_util::GetStringUTF16(IDS_INCOGNITO_PROFILE_MENU_TITLE), + incognito_window_count > 1 + ? l10n_util::GetPluralStringFUTF16(IDS_INCOGNITO_WINDOW_COUNT_MESSAGE, + incognito_window_count) + : base::string16()); + profile_card->SetEnabled(false); + + layout->StartRowWithPadding(1.0, 0, views::GridLayout::kFixedSize, + content_list_vert_spacing); + layout->AddView(profile_card); + + layout->StartRowWithPadding(1.0, 0, views::GridLayout::kFixedSize, + content_list_vert_spacing); + layout->AddView(new views::Separator()); + + users_button_ = new HoverButton( + this, gfx::CreateVectorIcon(kCloseAllIcon, 16, gfx::kChromeIconGrey), + l10n_util::GetStringUTF16(IDS_INCOGNITO_PROFILE_MENU_CLOSE_BUTTON)); + + layout->StartRowWithPadding(1.0, 0, views::GridLayout::kFixedSize, + content_list_vert_spacing); + layout->AddView(users_button_); + + return view; +} + views::View* ProfileChooserView::CreateProfileChooserView( AvatarMenu* avatar_menu) { views::View* view = new views::View();
diff --git a/chrome/browser/ui/views/profiles/profile_chooser_view.h b/chrome/browser/ui/views/profiles/profile_chooser_view.h index 5b2f65f..57c5868 100644 --- a/chrome/browser/ui/views/profiles/profile_chooser_view.h +++ b/chrome/browser/ui/views/profiles/profile_chooser_view.h
@@ -137,6 +137,9 @@ // Creates the profile chooser view. views::View* CreateProfileChooserView(AvatarMenu* avatar_menu); + // Creates the incognito window count view. + views::View* CreateIncognitoWindowCountView(); + // Creates the main profile card for the profile |avatar_item|. |is_guest| // is used to determine whether to show any Sign in/Sign out/Manage accounts // links.
diff --git a/chrome/browser/ui/views/tabs/tab_drag_controller.cc b/chrome/browser/ui/views/tabs/tab_drag_controller.cc index 6445b7fb..c330550 100644 --- a/chrome/browser/ui/views/tabs/tab_drag_controller.cc +++ b/chrome/browser/ui/views/tabs/tab_drag_controller.cc
@@ -334,7 +334,12 @@ last_move_screen_loc_(0), source_tab_index_(std::numeric_limits<size_t>::max()), initial_move_(true), +#if defined(USE_OZONE) && !defined(OS_CHROMEOS) + // TODO(crbug.com/896640): Support detachable tabs + detach_behavior_(NOT_DETACHABLE), +#else detach_behavior_(DETACHABLE), +#endif move_behavior_(REORDER), mouse_has_ever_moved_left_(false), mouse_has_ever_moved_right_(false),
diff --git a/chrome/browser/ui/views/tabs/window_finder_ozone.cc b/chrome/browser/ui/views/tabs/window_finder_ozone.cc index bb904744..f290223 100644 --- a/chrome/browser/ui/views/tabs/window_finder_ozone.cc +++ b/chrome/browser/ui/views/tabs/window_finder_ozone.cc
@@ -4,10 +4,19 @@ #include "chrome/browser/ui/views/tabs/window_finder.h" +#include "base/stl_util.h" +#include "ui/aura/window.h" +#include "ui/display/screen.h" +#include "ui/views/widget/widget.h" + gfx::NativeWindow WindowFinder::GetLocalProcessWindowAtPoint( const gfx::Point& screen_point, const std::set<gfx::NativeWindow>& ignore) { - NOTIMPLEMENTED() - << "For Ozone builds, window finder is not supported for now."; - return nullptr; + gfx::NativeWindow window = + display::Screen::GetScreen()->GetWindowAtScreenPoint(screen_point); + for (; window; window = window->parent()) { + if (views::Widget::GetWidgetForNativeWindow(window)) + break; + } + return (window && !base::ContainsKey(ignore, window)) ? window : nullptr; }
diff --git a/chrome/browser/ui/webauthn/sheet_models.cc b/chrome/browser/ui/webauthn/sheet_models.cc index fca6f7a..6abee61 100644 --- a/chrome/browser/ui/webauthn/sheet_models.cc +++ b/chrome/browser/ui/webauthn/sheet_models.cc
@@ -273,7 +273,7 @@ } base::string16 AuthenticatorNotRegisteredErrorModel::GetStepTitle() const { - return l10n_util::GetStringUTF16(IDS_WEBAUTHN_ERROR_WRONG_KEY_SIGN_TITLE); + return l10n_util::GetStringUTF16(IDS_WEBAUTHN_ERROR_WRONG_KEY_TITLE); } base::string16 AuthenticatorNotRegisteredErrorModel::GetStepDescription() @@ -299,7 +299,7 @@ } base::string16 AuthenticatorAlreadyRegisteredErrorModel::GetStepTitle() const { - return l10n_util::GetStringUTF16(IDS_WEBAUTHN_ERROR_WRONG_KEY_REGISTER_TITLE); + return l10n_util::GetStringUTF16(IDS_WEBAUTHN_ERROR_WRONG_KEY_TITLE); } base::string16 AuthenticatorAlreadyRegisteredErrorModel::GetStepDescription()
diff --git a/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc index fa78c670..964538da 100644 --- a/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc
@@ -240,15 +240,7 @@ void AssistantOptInFlowScreenHandler::OnStateChanged( ash::mojom::VoiceInteractionState state) { if (state != ash::mojom::VoiceInteractionState::NOT_READY) { - if (voice_enrollment_pending) { - voice_enrollment_pending = false; - DCHECK(settings_manager_.is_bound() && - base::FeatureList::IsEnabled( - assistant::features::kAssistantVoiceMatch)); - settings_manager_->StartSpeakerIdEnrollment(true, std::move(client_ptr_)); - } else { - BindAssistantSettingsManager(); - } + BindAssistantSettingsManager(); arc::VoiceInteractionControllerClient::Get()->RemoveObserver(this); } } @@ -449,14 +441,9 @@ ShowNextScreen(); } else if (action == kRecordPressed) { if (!prefs->GetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled)) { - // Turn on hotword will restart the Assistant service. Thus the enrollment - // request should be sent after the service restart complete. - voice_enrollment_pending = true; prefs->SetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled, true); - arc::VoiceInteractionControllerClient::Get()->AddObserver(this); - } else { - settings_manager_->StartSpeakerIdEnrollment(true, std::move(client_ptr_)); } + settings_manager_->StartSpeakerIdEnrollment(true, std::move(client_ptr_)); } }
diff --git a/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h b/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h index 3c6fd2e..53735a8e 100644 --- a/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h +++ b/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h
@@ -130,9 +130,6 @@ // Whether the screen has been initialized. bool initialized_ = false; - // Whether there is a pending voice match enrollment request. - bool voice_enrollment_pending = false; - mojo::Binding<assistant::mojom::SpeakerIdEnrollmentClient> client_binding_; assistant::mojom::SpeakerIdEnrollmentClientPtr client_ptr_; assistant::mojom::AssistantSettingsManagerPtr settings_manager_;
diff --git a/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc b/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc index 9192c59..def6426 100644 --- a/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc +++ b/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc
@@ -32,7 +32,7 @@ } // TODO(felixe): More context at crbug.com/738885 -const uint16_t kDeviceIds[] = {0x0457, 0x266e}; +const uint16_t kDeviceIds[] = {0x0457, 0x266e, 0x222a}; // Returns true if |vendor_id| is a valid vendor id that may be made the primary // display.
diff --git a/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc b/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc index 469e3f46..7af2b48 100644 --- a/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc +++ b/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc
@@ -290,7 +290,7 @@ activityLogHistory.whenDataFetched().then(() => { Polymer.dom.flush(); let item = activityLogHistory.shadowRoot.querySelector( - 'activity-log-item'); + 'activity-log-history-item'); let activityKey = item.shadowRoot.getElementById('activity-key'); window.domAutomationController.send( activityKey.innerText === 'test.sendMessage');
diff --git a/chrome/browser/ui/webui/feed_internals/feed_internals.mojom b/chrome/browser/ui/webui/feed_internals/feed_internals.mojom index 30142d68..d7bb4e7b 100644 --- a/chrome/browser/ui/webui/feed_internals/feed_internals.mojom +++ b/chrome/browser/ui/webui/feed_internals/feed_internals.mojom
@@ -4,8 +4,34 @@ module feed_internals.mojom; +// General properties of Feed suggestions. +struct Properties { + // Whether the Feed is enabled. + bool is_feed_enabled; +}; + +struct UserClassifier { + // User class description. + string user_class_description; + + // Estimated average length of time between two successive suggestion views of + // in hours. + float avg_hours_between_views; + + // Estimated average length of time between two successive uses of suggestions + // in hours. + float avg_hours_between_uses; +}; + // Browser interface for the page. Consists of calls for data and hooks for // interactivity. interface PageHandler { - // TODO(chouinard): Implement this. + // Get general property values. + GetGeneralProperties() => (Properties properties); + + // Get user classifier property values. + GetUserClassifierProperties() => (UserClassifier properties); + + // Clear stored properties for the user classifier. + ClearUserClassifierProperties(); };
diff --git a/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc b/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc index 8732a01..7770d18 100644 --- a/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc +++ b/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc
@@ -6,8 +6,47 @@ #include <utility> +#include "base/feature_list.h" +#include "components/feed/content/feed_host_service.h" +#include "components/feed/core/feed_scheduler_host.h" +#include "components/feed/core/user_classifier.h" +#include "components/feed/feed_feature_list.h" + FeedInternalsPageHandler::FeedInternalsPageHandler( - feed_internals::mojom::PageHandlerRequest request) - : binding_(this, std::move(request)) {} + feed_internals::mojom::PageHandlerRequest request, + feed::FeedHostService* feed_host_service) + : binding_(this, std::move(request)), + feed_scheduler_host_(feed_host_service->GetSchedulerHost()) {} FeedInternalsPageHandler::~FeedInternalsPageHandler() = default; + +void FeedInternalsPageHandler::GetGeneralProperties( + GetGeneralPropertiesCallback callback) { + auto properties = feed_internals::mojom::Properties::New(); + + properties->is_feed_enabled = + base::FeatureList::IsEnabled(feed::kInterestFeedContentSuggestions); + + std::move(callback).Run(std::move(properties)); +} + +void FeedInternalsPageHandler::GetUserClassifierProperties( + GetUserClassifierPropertiesCallback callback) { + auto properties = feed_internals::mojom::UserClassifier::New(); + + feed::UserClassifier* user_classifier = + feed_scheduler_host_->user_classifier(); + + properties->user_class_description = + user_classifier->GetUserClassDescriptionForDebugging(); + properties->avg_hours_between_views = user_classifier->GetEstimatedAvgTime( + feed::UserClassifier::Event::kSuggestionsViewed); + properties->avg_hours_between_uses = user_classifier->GetEstimatedAvgTime( + feed::UserClassifier::Event::kSuggestionsUsed); + + std::move(callback).Run(std::move(properties)); +} + +void FeedInternalsPageHandler::ClearUserClassifierProperties() { + feed_scheduler_host_->user_classifier()->ClearClassificationForDebugging(); +}
diff --git a/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h b/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h index 9709dfe..e51220cd 100644 --- a/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h +++ b/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h
@@ -9,16 +9,31 @@ #include "chrome/browser/ui/webui/feed_internals/feed_internals.mojom.h" #include "mojo/public/cpp/bindings/binding.h" +namespace feed { +class FeedHostService; +class FeedSchedulerHost; +} // namespace feed + // Concrete implementation of feed_internals::mojom::PageHandler. class FeedInternalsPageHandler : public feed_internals::mojom::PageHandler { public: - explicit FeedInternalsPageHandler( - feed_internals::mojom::PageHandlerRequest request); + FeedInternalsPageHandler(feed_internals::mojom::PageHandlerRequest request, + feed::FeedHostService* feed_host_service); ~FeedInternalsPageHandler() override; + // feed_internals::mojom::PageHandler + void GetGeneralProperties(GetGeneralPropertiesCallback) override; + void GetUserClassifierProperties( + GetUserClassifierPropertiesCallback) override; + void ClearUserClassifierProperties() override; + private: + // Binding from the mojo interface to concrete implementation. mojo::Binding<feed_internals::mojom::PageHandler> binding_; + // Services that provide the data and functionality. + feed::FeedSchedulerHost* feed_scheduler_host_; + DISALLOW_COPY_AND_ASSIGN(FeedInternalsPageHandler); };
diff --git a/chrome/browser/ui/webui/feed_internals/feed_internals_ui.cc b/chrome/browser/ui/webui/feed_internals/feed_internals_ui.cc index 569e525..2ebf8e4 100644 --- a/chrome/browser/ui/webui/feed_internals/feed_internals_ui.cc +++ b/chrome/browser/ui/webui/feed_internals/feed_internals_ui.cc
@@ -7,6 +7,7 @@ #include <utility> #include "base/bind.h" +#include "chrome/browser/android/feed/feed_host_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h" #include "chrome/common/url_constants.h" @@ -21,10 +22,14 @@ source->AddResourcePath("feed_internals.js", IDR_FEED_INTERNALS_JS); source->AddResourcePath("feed_internals.mojom-lite.js", IDR_FEED_INTERNALS_MOJO_JS); + source->AddResourcePath("feed_internals.css", IDR_FEED_INTERNALS_CSS); source->SetDefaultResource(IDR_FEED_INTERNALS_HTML); source->UseGzip(); Profile* profile = Profile::FromWebUI(web_ui); + feed_host_service_ = + feed::FeedHostServiceFactory::GetForBrowserContext(profile); + content::WebUIDataSource::Add(profile, source); // This class is the caller of the callback when an observer interface is // triggered. So this base::Unretained is safe. @@ -36,6 +41,6 @@ void FeedInternalsUI::BindFeedInternalsPageHandler( feed_internals::mojom::PageHandlerRequest request) { - page_handler_ = - std::make_unique<FeedInternalsPageHandler>(std::move(request)); + page_handler_ = std::make_unique<FeedInternalsPageHandler>( + std::move(request), feed_host_service_); }
diff --git a/chrome/browser/ui/webui/feed_internals/feed_internals_ui.h b/chrome/browser/ui/webui/feed_internals/feed_internals_ui.h index 7b6bed2..23282c95 100644 --- a/chrome/browser/ui/webui/feed_internals/feed_internals_ui.h +++ b/chrome/browser/ui/webui/feed_internals/feed_internals_ui.h
@@ -12,7 +12,11 @@ #include "chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h" #include "ui/webui/mojo_web_ui_controller.h" -// UI controller for chrome://feed-internals, hooks up a concrete implementation +// During the interim migration to Feed, this page will be co-located with +// snippets-internals. Once migration is complete, and snippets-internals is +// removed, this page will be moved to chrome://feed-internals. + +// UI controller for the Feed internals page, hooks up a concrete implementation // of feed_internals::mojom::PageHandler to requests for that page handler // that will come from the frontend. class FeedInternalsUI : public ui::MojoWebUIController { @@ -24,6 +28,8 @@ void BindFeedInternalsPageHandler( feed_internals::mojom::PageHandlerRequest request); + feed::FeedHostService* feed_host_service_; + std::unique_ptr<FeedInternalsPageHandler> page_handler_; DISALLOW_COPY_AND_ASSIGN(FeedInternalsUI);
diff --git a/chrome/browser/ui/webui/managed_ui_handler.cc b/chrome/browser/ui/webui/managed_ui_handler.cc index 3e5abf8a..90a1c22a 100644 --- a/chrome/browser/ui/webui/managed_ui_handler.cc +++ b/chrome/browser/ui/webui/managed_ui_handler.cc
@@ -7,6 +7,7 @@ #include <utility> #include "base/bind.h" +#include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/policy/profile_policy_connector.h" @@ -14,11 +15,16 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/managed_ui.h" #include "chrome/common/pref_names.h" +#include "chrome/common/url_constants.h" #include "chrome/grit/generated_resources.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "ui/base/l10n/l10n_util.h" +#if defined(OS_CHROMEOS) +#include "ui/chromeos/devicetype_utils.h" +#endif + namespace { policy::PolicyService* GetProfilePolicyService(Profile* profile) { @@ -113,9 +119,15 @@ std::unique_ptr<base::DictionaryValue> ManagedUIHandler::GetDataSourceUpdate() const { auto update = std::make_unique<base::DictionaryValue>(); - update->SetKey( - "managedByOrg", - base::Value(l10n_util::GetStringUTF8(IDS_MANAGED_BY_ORG_WITH_HYPERLINK))); + update->SetKey("managedByOrg", + base::Value(l10n_util::GetStringFUTF16( + IDS_MANAGED_BY_ORG_WITH_HYPERLINK, + base::UTF8ToUTF16(chrome::kManagedUiLearnMoreUrl) +#if defined(OS_CHROMEOS) + , + ui::GetChromeOSDeviceName() +#endif + ))); update->SetKey("isManaged", base::Value(managed_)); return update; }
diff --git a/chrome/browser/ui/webui/offline/OWNERS b/chrome/browser/ui/webui/offline/OWNERS new file mode 100644 index 0000000..f5dcbcc --- /dev/null +++ b/chrome/browser/ui/webui/offline/OWNERS
@@ -0,0 +1,4 @@ +file://components/offline_pages/OWNERS + +# TEAM: offline-dev@chromium.org +# COMPONENT: UI>Browser>Offline
diff --git a/chrome/browser/vr/test/webxr_browser_test.cc b/chrome/browser/vr/test/webxr_browser_test.cc index d043b14..6dd8c53 100644 --- a/chrome/browser/vr/test/webxr_browser_test.cc +++ b/chrome/browser/vr/test/webxr_browser_test.cc
@@ -18,27 +18,27 @@ } bool WebXrBrowserTestBase::XrDeviceFound() { - return XrDeviceFound(GetFirstTabWebContents()); + return XrDeviceFound(GetCurrentWebContents()); } void WebXrBrowserTestBase::EnterSessionWithUserGesture() { - EnterSessionWithUserGesture(GetFirstTabWebContents()); + EnterSessionWithUserGesture(GetCurrentWebContents()); } void WebXrBrowserTestBase::EnterSessionWithUserGestureAndWait() { - EnterSessionWithUserGestureAndWait(GetFirstTabWebContents()); + EnterSessionWithUserGestureAndWait(GetCurrentWebContents()); } void WebXrBrowserTestBase::EnterSessionWithUserGestureOrFail() { - EnterSessionWithUserGestureOrFail(GetFirstTabWebContents()); + EnterSessionWithUserGestureOrFail(GetCurrentWebContents()); } void WebXrBrowserTestBase::EndSession() { - EndSession(GetFirstTabWebContents()); + EndSession(GetCurrentWebContents()); } void WebXrBrowserTestBase::EndSessionOrFail() { - EndSessionOrFail(GetFirstTabWebContents()); + EndSessionOrFail(GetCurrentWebContents()); } } // namespace vr
diff --git a/chrome/browser/vr/test/webxr_browser_test.h b/chrome/browser/vr/test/webxr_browser_test.h index 810a7bc1..07fffae5a 100644 --- a/chrome/browser/vr/test/webxr_browser_test.h +++ b/chrome/browser/vr/test/webxr_browser_test.h
@@ -38,27 +38,27 @@ virtual void EndSessionOrFail(content::WebContents* web_contents) = 0; // Convenience function for calling XrDeviceFound with the return value of - // GetFirstTabWebContents. + // GetCurrentWebContents. bool XrDeviceFound(); // Convenience function for calling EnterSessionWithUserGesture with the - // return value of GetFirstTabWebContents. + // return value of GetCurrentWebContents. void EnterSessionWithUserGesture(); // Convenience function for calling EnterSessionWithUserGestureAndWait with - // the return value of GetFirstTabWebContents. + // the return value of GetCurrentWebContents. void EnterSessionWithUserGestureAndWait(); // Convenience function for calling EnterSessionWithUserGestureOrFail with the - // return value of GetFirstTabWebContents. + // return value of GetCurrentWebContents. void EnterSessionWithUserGestureOrFail(); // Convenience function for calling EndSession with the return value of - // GetFirstTabWebContents. + // GetCurrentWebContents. void EndSession(); // Convenience function for calling EndSessionOrFail with the return value of - // GetFirstTabWebContents. + // GetCurrentWebContents. void EndSessionOrFail(); };
diff --git a/chrome/browser/vr/test/xr_browser_test.cc b/chrome/browser/vr/test/xr_browser_test.cc index 0f04cb1..27ea1cf 100644 --- a/chrome/browser/vr/test/xr_browser_test.cc +++ b/chrome/browser/vr/test/xr_browser_test.cc
@@ -126,15 +126,15 @@ return server_.get(); } -content::WebContents* XrBrowserTestBase::GetFirstTabWebContents() { - return browser()->tab_strip_model()->GetWebContentsAt(0); +content::WebContents* XrBrowserTestBase::GetCurrentWebContents() { + return browser()->tab_strip_model()->GetActiveWebContents(); } void XrBrowserTestBase::LoadUrlAndAwaitInitialization(const GURL& url) { ui_test_utils::NavigateToURL(browser(), url); - EXPECT_TRUE(PollJavaScriptBoolean( - "isInitializationComplete()", kPollTimeoutMedium, - browser()->tab_strip_model()->GetActiveWebContents())) + EXPECT_TRUE(PollJavaScriptBoolean("isInitializationComplete()", + kPollTimeoutMedium, + GetCurrentWebContents())) << "Timed out waiting for JavaScript test initialization."; } @@ -333,49 +333,49 @@ } void XrBrowserTestBase::RunJavaScriptOrFail(const std::string& js_expression) { - RunJavaScriptOrFail(js_expression, GetFirstTabWebContents()); + RunJavaScriptOrFail(js_expression, GetCurrentWebContents()); } bool XrBrowserTestBase::RunJavaScriptAndExtractBoolOrFail( const std::string& js_expression) { return RunJavaScriptAndExtractBoolOrFail(js_expression, - GetFirstTabWebContents()); + GetCurrentWebContents()); } std::string XrBrowserTestBase::RunJavaScriptAndExtractStringOrFail( const std::string& js_expression) { return RunJavaScriptAndExtractStringOrFail(js_expression, - GetFirstTabWebContents()); + GetCurrentWebContents()); } bool XrBrowserTestBase::PollJavaScriptBoolean( const std::string& bool_expression, const base::TimeDelta& timeout) { return PollJavaScriptBoolean(bool_expression, timeout, - GetFirstTabWebContents()); + GetCurrentWebContents()); } void XrBrowserTestBase::PollJavaScriptBooleanOrFail( const std::string& bool_expression, const base::TimeDelta& timeout) { PollJavaScriptBooleanOrFail(bool_expression, timeout, - GetFirstTabWebContents()); + GetCurrentWebContents()); } void XrBrowserTestBase::WaitOnJavaScriptStep() { - WaitOnJavaScriptStep(GetFirstTabWebContents()); + WaitOnJavaScriptStep(GetCurrentWebContents()); } void XrBrowserTestBase::ExecuteStepAndWait(const std::string& step_function) { - ExecuteStepAndWait(step_function, GetFirstTabWebContents()); + ExecuteStepAndWait(step_function, GetCurrentWebContents()); } void XrBrowserTestBase::EndTest() { - EndTest(GetFirstTabWebContents()); + EndTest(GetCurrentWebContents()); } void XrBrowserTestBase::AssertNoJavaScriptErrors() { - AssertNoJavaScriptErrors(GetFirstTabWebContents()); + AssertNoJavaScriptErrors(GetCurrentWebContents()); } } // namespace vr
diff --git a/chrome/browser/vr/test/xr_browser_test.h b/chrome/browser/vr/test/xr_browser_test.h index cfa9f0f05..996d8df 100644 --- a/chrome/browser/vr/test/xr_browser_test.h +++ b/chrome/browser/vr/test/xr_browser_test.h
@@ -72,9 +72,9 @@ // HTML files, initializing and starting the server if necessary. net::EmbeddedTestServer* GetEmbeddedServer(); - // Convenience function for accessing the WebContents belonging to the first + // Convenience function for accessing the WebContents belonging to the current // tab open in the browser. - content::WebContents* GetFirstTabWebContents(); + content::WebContents* GetCurrentWebContents(); // Loads the given GURL and blocks until the JavaScript on the page has // signalled that pre-test initialization is complete. @@ -147,42 +147,42 @@ Browser* browser() { return InProcessBrowserTest::browser(); } // Convenience function for running RunJavaScriptOrFail with the return value - // of GetFirstTabWebContents. + // of GetCurrentWebContents. void RunJavaScriptOrFail(const std::string& js_expression); // Convenience function for running RunJavaScriptAndExtractBoolOrFail with the - // return value of GetFirstTabWebContents. + // return value of GetCurrentWebContents. bool RunJavaScriptAndExtractBoolOrFail(const std::string& js_expression); // Convenience function for running RunJavaScriptAndExtractStringOrFail with - // the return value of GetFirstTabWebContents. + // the return value of GetCurrentWebContents. std::string RunJavaScriptAndExtractStringOrFail( const std::string& js_expression); // Convenience function for running PollJavaScriptBoolean with the return - // value of GetFirstTabWebContents. + // value of GetCurrentWebContents. bool PollJavaScriptBoolean(const std::string& bool_expression, const base::TimeDelta& timeout); // Convenience function for running PollJavaScriptBooleanOrFail with the - // return value of GetFirstTabWebContents. + // return value of GetCurrentWebContents. void PollJavaScriptBooleanOrFail(const std::string& bool_expression, const base::TimeDelta& timeout); // Convenience function for running WaitOnJavaScriptStep with the return value - // of GetFirstTabWebContents. + // of GetCurrentWebContents. void WaitOnJavaScriptStep(); // Convenience function for running ExecuteStepAndWait with the return value - // of GetFirstTabWebContents. + // of GetCurrentWebContents. void ExecuteStepAndWait(const std::string& step_function); // Convenience function for running EndTest with the return value of - // GetFirstTabWebContents. + // GetCurrentWebContents. void EndTest(); // Convenience function for running AssertNoJavaScriptErrors with the return - // value of GetFirstTabWebContents. + // value of GetCurrentWebContents. void AssertNoJavaScriptErrors(); protected:
diff --git a/chrome/browser/vr/ui_host/vr_ui_host_impl.cc b/chrome/browser/vr/ui_host/vr_ui_host_impl.cc index 7ae324d..65a10b2 100644 --- a/chrome/browser/vr/ui_host/vr_ui_host_impl.cc +++ b/chrome/browser/vr/ui_host/vr_ui_host_impl.cc
@@ -7,6 +7,7 @@ #include "base/task/post_task.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ssl/security_state_tab_helper.h" +#include "chrome/browser/vr/metrics/session_metrics_helper.h" #include "chrome/browser/vr/service/browser_xr_runtime.h" #include "chrome/browser/vr/service/xr_runtime_manager.h" #include "chrome/browser/vr/vr_tab_helper.h" @@ -77,6 +78,27 @@ permission_request_manager_ = nullptr; } + if (web_contents_ != contents) { + if (web_contents_) { + auto* metrics_helper = + SessionMetricsHelper::FromWebContents(web_contents_); + metrics_helper->SetWebVREnabled(false); + metrics_helper->SetVRActive(false); + } + if (contents) { + auto* metrics_helper = + SessionMetricsHelper::FromWebContents(web_contents_); + if (!metrics_helper) { + metrics_helper = SessionMetricsHelper::CreateForWebContents( + contents, Mode::kWebXrVrPresentation); + } else { + metrics_helper->SetWebVREnabled(true); + metrics_helper->SetVRActive(true); + } + metrics_helper->RecordVrStartAction(VrStartAction::kPresentationRequest); + } + } + if (web_contents_) VrTabHelper::SetIsContentDisplayedInHeadset(web_contents_, false); if (contents)
diff --git a/chrome/browser/vr/webxr_vr_tab_browser_test.cc b/chrome/browser/vr/webxr_vr_tab_browser_test.cc index 56b3ddb..b7028ec 100644 --- a/chrome/browser/vr/webxr_vr_tab_browser_test.cc +++ b/chrome/browser/vr/webxr_vr_tab_browser_test.cc
@@ -19,10 +19,12 @@ std::string filename) { t->LoadUrlAndAwaitInitialization(t->GetFileUrlForHtmlTestFile(filename)); t->ExecuteStepAndWait("stepCheckFrameDataWhileFocusedTab()"); + auto* first_tab_web_contents = t->GetCurrentWebContents(); chrome::AddTabAt(t->browser(), GURL(url::kAboutBlankURL), -1 /* index, append to end */, true /* foreground */); - t->ExecuteStepAndWait("stepCheckFrameDataWhileNonFocusedTab()"); - t->EndTest(); + t->ExecuteStepAndWait("stepCheckFrameDataWhileNonFocusedTab()", + first_tab_web_contents); + t->EndTest(first_tab_web_contents); } IN_PROC_BROWSER_TEST_F(WebVrBrowserTestStandard, TestPoseDataUnfocusedTab) {
diff --git a/chrome/browser/web_applications/web_app_install_manager.cc b/chrome/browser/web_applications/web_app_install_manager.cc index 01d0696c..850e6d4 100644 --- a/chrome/browser/web_applications/web_app_install_manager.cc +++ b/chrome/browser/web_applications/web_app_install_manager.cc
@@ -190,6 +190,14 @@ WebApplicationInfo web_app_info_copy = *web_app_info; + DCHECK(install_source_ != kNoInstallSource); + + // This metric is recorded regardless of the installation result. + if (InstallableMetrics::IsReportableInstallSource(install_source_) && + for_installable_site == ForInstallableSite::kYes) { + InstallableMetrics::TrackInstallEvent(install_source_); + } + install_finalizer_->FinalizeInstall( web_app_info_copy, base::BindOnce(&WebAppInstallManager::OnInstallFinalized, @@ -198,15 +206,6 @@ // Check that the finalizer hasn't called OnInstallFinalized synchronously: DCHECK(install_callback_); - DCHECK(install_source_ != kNoInstallSource); - - // In BookmarkAppHelper this tracking happens right after - // crx_installer_->InstallWebApp call (not in FinishInstallation). - // TODO(loyso): Consider to shift this recording to OnInstallFinalized. - if (InstallableMetrics::IsReportableInstallSource(install_source_) && - for_installable_site == ForInstallableSite::kYes) { - InstallableMetrics::TrackInstallEvent(install_source_); - } } void WebAppInstallManager::OnInstallFinalized(
diff --git a/chrome/common/chrome_content_client.cc b/chrome/common/chrome_content_client.cc index 5504d700..45f0aa9 100644 --- a/chrome/common/chrome_content_client.cc +++ b/chrome/common/chrome_content_client.cc
@@ -660,6 +660,12 @@ return l10n_util::GetStringUTF16(message_id); } +base::string16 ChromeContentClient::GetLocalizedString( + int message_id, + const base::string16& replacement) const { + return l10n_util::GetStringFUTF16(message_id, replacement); +} + base::StringPiece ChromeContentClient::GetDataResource( int resource_id, ui::ScaleFactor scale_factor) const {
diff --git a/chrome/common/chrome_content_client.h b/chrome/common/chrome_content_client.h index 1d28aef9..667a1f19 100644 --- a/chrome/common/chrome_content_client.h +++ b/chrome/common/chrome_content_client.h
@@ -84,6 +84,9 @@ void AddAdditionalSchemes(Schemes* schemes) override; base::string16 GetLocalizedString(int message_id) const override; + base::string16 GetLocalizedString( + int message_id, + const base::string16& replacement) const override; base::StringPiece GetDataResource( int resource_id, ui::ScaleFactor scale_factor) const override;
diff --git a/chrome/common/chrome_features.cc b/chrome/common/chrome_features.cc index 09164b0..b28f040 100644 --- a/chrome/common/chrome_features.cc +++ b/chrome/common/chrome_features.cc
@@ -146,7 +146,7 @@ // Enables passing additional user authentication in requests to DMServer // (policy fetch, status report upload). const base::Feature kDMServerOAuthForChildUser{ - "DMServerOAuthForChildUser", base::FEATURE_DISABLED_BY_DEFAULT}; + "DMServerOAuthForChildUser", base::FEATURE_ENABLED_BY_DEFAULT}; #endif #if defined(OS_ANDROID)
diff --git a/chrome/common/safe_browsing/archive_analyzer_results.cc b/chrome/common/safe_browsing/archive_analyzer_results.cc index 2dfcdef..934efe5c 100644 --- a/chrome/common/safe_browsing/archive_analyzer_results.cc +++ b/chrome/common/safe_browsing/archive_analyzer_results.cc
@@ -81,7 +81,11 @@ } // namespace ArchiveAnalyzerResults::ArchiveAnalyzerResults() - : success(false), has_executable(false), has_archive(false) {} + : success(false), + has_executable(false), + has_archive(false), + file_count(0), + directory_count(0) {} ArchiveAnalyzerResults::ArchiveAnalyzerResults( const ArchiveAnalyzerResults& other) = default;
diff --git a/chrome/common/safe_browsing/archive_analyzer_results.h b/chrome/common/safe_browsing/archive_analyzer_results.h index 374bfac..86d1900 100644 --- a/chrome/common/safe_browsing/archive_analyzer_results.h +++ b/chrome/common/safe_browsing/archive_analyzer_results.h
@@ -33,6 +33,8 @@ ClientDownloadRequest_DetachedCodeSignature> detached_code_signatures; #endif // OS_MACOSX + int file_count; + int directory_count; ArchiveAnalyzerResults(); ArchiveAnalyzerResults(const ArchiveAnalyzerResults& other); ~ArchiveAnalyzerResults();
diff --git a/chrome/common/safe_browsing/zip_analyzer.cc b/chrome/common/safe_browsing/zip_analyzer.cc index 75f9ce7..773f8bb 100644 --- a/chrome/common/safe_browsing/zip_analyzer.cc +++ b/chrome/common/safe_browsing/zip_analyzer.cc
@@ -71,6 +71,8 @@ bool contains_zip = false; bool advanced = true; int zip_entry_count = 0; + results->file_count = 0; + results->directory_count = 0; for (; reader.HasMore(); advanced = reader.AdvanceToNextEntry()) { if (!advanced) { DVLOG(1) << "Could not advance to next entry, aborting zip scan."; @@ -95,6 +97,11 @@ FILE_PATH_LITERAL(".zip")) contains_zip = true; zip_entry_count++; + + if (reader.current_entry_info()->is_directory()) + results->directory_count++; + else + results->file_count++; } results->success = true;
diff --git a/chrome/credential_provider/gaiacp/BUILD.gn b/chrome/credential_provider/gaiacp/BUILD.gn index 82d1e7e..80e2dbc 100644 --- a/chrome/credential_provider/gaiacp/BUILD.gn +++ b/chrome/credential_provider/gaiacp/BUILD.gn
@@ -69,6 +69,8 @@ "gcp_crash_reporting.cc", "gcp_crash_reporting.h", "initguid.cc", + "internet_availability_checker.cc", + "internet_availability_checker.h", "os_process_manager.cc", "os_process_manager.h", "os_user_manager.cc", @@ -83,6 +85,8 @@ "scoped_user_profile.cc", "scoped_user_profile.h", "stdafx.h", + "token_handle_validator.cc", + "token_handle_validator.h", "win_http_url_fetcher.cc", "win_http_url_fetcher.h", ]
diff --git a/chrome/credential_provider/gaiacp/dllmain.cc b/chrome/credential_provider/gaiacp/dllmain.cc index 74a034c..c771fca 100644 --- a/chrome/credential_provider/gaiacp/dllmain.cc +++ b/chrome/credential_provider/gaiacp/dllmain.cc
@@ -73,7 +73,15 @@ return E_NOTIMPL; } - return _AtlModule.DllGetClassObject(rclsid, riid, ppv); + HRESULT hr = _AtlModule.DllGetClassObject(rclsid, riid, ppv); + + // Start refreshing token handle validity as soon as possible so that when + // their validity is requested later on by the credential providers they may + // already be available and no wait is needed. + if (SUCCEEDED(hr)) + _AtlModule.RefreshTokenHandleValidity(); + + return hr; } // DllRegisterServer - Adds entries to the system registry.
diff --git a/chrome/credential_provider/gaiacp/gaia_credential_base.cc b/chrome/credential_provider/gaiacp/gaia_credential_base.cc index 4965aa9..b02b1cac 100644 --- a/chrome/credential_provider/gaiacp/gaia_credential_base.cc +++ b/chrome/credential_provider/gaiacp/gaia_credential_base.cc
@@ -32,6 +32,7 @@ #include "chrome/credential_provider/gaiacp/gaia_resources.h" #include "chrome/credential_provider/gaiacp/gcp_utils.h" #include "chrome/credential_provider/gaiacp/grit/gaia_static_resources.h" +#include "chrome/credential_provider/gaiacp/internet_availability_checker.h" #include "chrome/credential_provider/gaiacp/logging.h" #include "chrome/credential_provider/gaiacp/os_process_manager.h" #include "chrome/credential_provider/gaiacp/os_user_manager.h" @@ -1027,7 +1028,7 @@ TellOmahaDidRun(); // If there is no internet connection, just abort right away. - if (provider_->HasInternetConnection() != S_OK) { + if (!InternetAvailabilityChecker::Get()->HasInternetConnection()) { BSTR error_message = AllocErrorString(IDS_NO_NETWORK_BASE); ::SHStrDupW(OLE2CW(error_message), status_text); ::SysFreeString(error_message);
diff --git a/chrome/credential_provider/gaiacp/gaia_credential_base_unittests.cc b/chrome/credential_provider/gaiacp/gaia_credential_base_unittests.cc index 6226d4d..6ced8fcc 100644 --- a/chrome/credential_provider/gaiacp/gaia_credential_base_unittests.cc +++ b/chrome/credential_provider/gaiacp/gaia_credential_base_unittests.cc
@@ -90,7 +90,8 @@ TEST_F(GcpGaiaCredentialBaseTest, GetSerialization_NoInternet) { FakeGaiaCredentialProvider provider; - ASSERT_EQ(S_OK, provider.SetHasInternetConnection(kHicForceNo)); + FakeInternetAvailabilityChecker internet_checker( + FakeInternetAvailabilityChecker::kHicForceNo); CComPtr<IGaiaCredential> gaia_cred; CComPtr<ICredentialProviderCredential> cred;
diff --git a/chrome/credential_provider/gaiacp/gaia_credential_provider.cc b/chrome/credential_provider/gaiacp/gaia_credential_provider.cc index 328c5fb..e98aea5 100644 --- a/chrome/credential_provider/gaiacp/gaia_credential_provider.cc +++ b/chrome/credential_provider/gaiacp/gaia_credential_provider.cc
@@ -4,8 +4,6 @@ #include "chrome/credential_provider/gaiacp/gaia_credential_provider.h" -#include <netlistmgr.h> - #include <iomanip> #include <map> @@ -23,6 +21,7 @@ #include "chrome/credential_provider/gaiacp/os_user_manager.h" #include "chrome/credential_provider/gaiacp/reauth_credential.h" #include "chrome/credential_provider/gaiacp/reg_utils.h" +#include "chrome/credential_provider/gaiacp/token_handle_validator.h" namespace credential_provider { @@ -48,7 +47,6 @@ HRESULT CGaiaCredentialProvider::FinalConstruct() { LOGFN(INFO); - CleanupStaleTokenHandles(); CleanupOlderVersions(); return S_OK; } @@ -117,28 +115,6 @@ index_ = std::numeric_limits<size_t>::max(); } -void CGaiaCredentialProvider::CleanupStaleTokenHandles() { - LOGFN(INFO); - std::map<base::string16, base::string16> handles; - - HRESULT hr = GetUserTokenHandles(&handles); - if (FAILED(hr)) { - LOGFN(ERROR) << "GetUserTokenHandles hr=" << putHR(hr); - return; - } - - OSUserManager* manager = OSUserManager::Get(); - for (auto it = handles.cbegin(); it != handles.cend(); ++it) { - HRESULT hr = - manager->FindUserBySID(it->first.c_str(), nullptr, 0, nullptr, 0); - if (hr == HRESULT_FROM_WIN32(ERROR_NONE_MAPPED)) { - RemoveAllUserProperties(it->first.c_str()); - } else if (FAILED(hr)) { - LOGFN(ERROR) << "manager->FindUserBySID hr=" << putHR(hr); - } - } -} - void CGaiaCredentialProvider::CleanupOlderVersions() { base::FilePath versions_directory = GetInstallDirectory(); if (!versions_directory.empty()) @@ -194,49 +170,13 @@ return hr; } -HRESULT CGaiaCredentialProvider::HasInternetConnection() { - if (has_internet_connection_ != kHicCheckAlways) - return has_internet_connection_ == kHicForceYes ? S_OK : S_FALSE; - - // If any errors occur, return that internet connection is available. At - // worst the credential provider will try to connect and fail. - - CComPtr<INetworkListManager> manager; - HRESULT hr = manager.CoCreateInstance(CLSID_NetworkListManager); - if (FAILED(hr)) { - LOGFN(ERROR) << "CoCreateInstance(NetworkListManager) hr=" << putHR(hr); - return S_OK; - } - - VARIANT_BOOL is_connected; - hr = manager->get_IsConnectedToInternet(&is_connected); - if (FAILED(hr)) { - LOGFN(ERROR) << "manager->get_IsConnectedToInternet hr=" << putHR(hr); - return S_OK; - } - - // Normally VARIANT_TRUE/VARIANT_FALSE are used with the type VARIANT_BOOL - // but in this case the docs explicitly say to use FALSE. - // https://docs.microsoft.com/en-us/windows/desktop/api/Netlistmgr/ - // nf-netlistmgr-inetworklistmanager-get_isconnectedtointernet - return is_connected != FALSE ? S_OK : S_FALSE; -} - -// IGaiaCredentialProviderForTesting ////////////////////////////////////////// - -HRESULT CGaiaCredentialProvider::SetHasInternetConnection( - HasInternetConnectionCheckType has_internet_connection) { - has_internet_connection_ = has_internet_connection; - return S_OK; -} - // ICredentialProvider //////////////////////////////////////////////////////// HRESULT CGaiaCredentialProvider::SetUserArray( ICredentialProviderUserArray* users) { LOGFN(INFO); std::map<base::string16, std::pair<base::string16, base::string16>> - sid_to_userinfo; + sid_to_username; // Get the SIDs of all users being shown in the logon UI. { @@ -280,7 +220,7 @@ } if (SUCCEEDED(hr)) { - sid_to_userinfo.emplace(sid, std::make_pair(domain, username)); + sid_to_username.emplace(sid, std::make_pair(domain, username)); } else { LOGFN(ERROR) << "Can't get sid or username hr=" << putHR(hr); } @@ -290,7 +230,7 @@ } // For each SID, check to see if this user requires reauth. - for (const auto& kv : sid_to_userinfo) { + for (const auto& kv : sid_to_username) { // Gaia id must exist in the registry for the user to be considered // registered. wchar_t gaia_id[64]; @@ -298,10 +238,15 @@ HRESULT hr = GetUserProperty(kv.first.c_str(), kUserId, gaia_id, &id_length); if (FAILED(hr)) { - // Local users that are not associated are disabled. + // Local users that are not associated do not create a credential. continue; } + // If the token handle is valid, no need to create a reauth credential. The + // user can just sign in using their password. + if (TokenHandleValidator::Get()->IsTokenHandleValidForUser(kv.first)) + continue; + // Get the user's email address. If not found, proceed anyway. The net // effect is that the user will need to enter their email address // manually instead of it being pre-filled.
diff --git a/chrome/credential_provider/gaiacp/gaia_credential_provider.h b/chrome/credential_provider/gaiacp/gaia_credential_provider.h index 6ccb31fe..96b54961 100644 --- a/chrome/credential_provider/gaiacp/gaia_credential_provider.h +++ b/chrome/credential_provider/gaiacp/gaia_credential_provider.h
@@ -21,7 +21,6 @@ public CComCoClass<CGaiaCredentialProvider, &CLSID_GaiaCredentialProvider>, public IGaiaCredentialProvider, - public IGaiaCredentialProviderForTesting, public ICredentialProviderSetUserArray, public ICredentialProvider { public: @@ -34,7 +33,6 @@ BEGIN_COM_MAP(CGaiaCredentialProvider) COM_INTERFACE_ENTRY(IGaiaCredentialProvider) - COM_INTERFACE_ENTRY(IGaiaCredentialProviderForTesting) COM_INTERFACE_ENTRY(ICredentialProviderSetUserArray) COM_INTERFACE_ENTRY(ICredentialProvider) END_COM_MAP() @@ -50,7 +48,6 @@ HRESULT CreateGaiaCredential(); HRESULT DestroyCredentials(); void ClearTransient(); - void CleanupStaleTokenHandles(); void CleanupOlderVersions(); // Checks of any of the Google account users need to re-auth. @@ -63,11 +60,6 @@ BSTR password, BSTR sid, BOOL fire_credentials_changed) override; - IFACEMETHODIMP HasInternetConnection() override; - - // IGaiaCredentialProviderForTesting - IFACEMETHODIMP SetHasInternetConnection( - HasInternetConnectionCheckType has_internet_connection) override; // ICredentialProviderSetUserArray IFACEMETHODIMP SetUserArray(ICredentialProviderUserArray* users) override; @@ -106,11 +98,6 @@ // Index in the |users_| array of the credential that performed the // authentication. size_t index_ = std::numeric_limits<size_t>::max(); - - // Used during tests to force the credential provider to believe if an - // internet connection is possible or not. In production the value is - // always set to HIC_CHECK_ALWAYS to perform a real check at runtime. - HasInternetConnectionCheckType has_internet_connection_ = kHicCheckAlways; }; OBJECT_ENTRY_AUTO(__uuidof(GaiaCredentialProvider), CGaiaCredentialProvider)
diff --git a/chrome/credential_provider/gaiacp/gaia_credential_provider_idl.templ b/chrome/credential_provider/gaiacp/gaia_credential_provider_idl.templ index b7e9df84..afd13b8 100644 --- a/chrome/credential_provider/gaiacp/gaia_credential_provider_idl.templ +++ b/chrome/credential_provider/gaiacp/gaia_credential_provider_idl.templ
@@ -20,22 +20,6 @@ [in] BSTR password, [in] BSTR sid, [in] BOOL fire_credentials_changed); - HRESULT HasInternetConnection(); -}; - -typedef enum { - kHicForceYes, - kHicForceNo, - kHicCheckAlways -} HasInternetConnectionCheckType; - -[ - object, - uuid(224CE2FB-2977-4585-BD46-1BAE8D7964DE), - pointer_default(unique) -] -interface IGaiaCredentialProviderForTesting : IUnknown { - HRESULT SetHasInternetConnection([in] HasInternetConnectionCheckType hic); }; [
diff --git a/chrome/credential_provider/gaiacp/gaia_credential_provider_module.cc b/chrome/credential_provider/gaiacp/gaia_credential_provider_module.cc index 2610142c..c56a347 100644 --- a/chrome/credential_provider/gaiacp/gaia_credential_provider_module.cc +++ b/chrome/credential_provider/gaiacp/gaia_credential_provider_module.cc
@@ -15,6 +15,7 @@ #include "chrome/credential_provider/gaiacp/gcp_crash_reporting.h" #include "chrome/credential_provider/gaiacp/grit/gaia_static_resources.h" #include "chrome/credential_provider/gaiacp/logging.h" +#include "chrome/credential_provider/gaiacp/token_handle_validator.h" #include "components/crash/content/app/crash_switches.h" #include "content/public/common/content_switches.h" @@ -66,6 +67,14 @@ IDR_GAIACREDENTIALPROVIDER, do_register, regmap); } +void CGaiaCredentialProviderModule::RefreshTokenHandleValidity() { + if (!token_handle_validity_refreshed_) { + credential_provider::TokenHandleValidator::Get() + ->StartRefreshingTokenHandleValidity(); + token_handle_validity_refreshed_ = true; + } +} + BOOL CGaiaCredentialProviderModule::DllMain(HINSTANCE /*hinstance*/, DWORD reason, LPVOID reserved) {
diff --git a/chrome/credential_provider/gaiacp/gaia_credential_provider_module.h b/chrome/credential_provider/gaiacp/gaia_credential_provider_module.h index 08b3513..5dfb838 100644 --- a/chrome/credential_provider/gaiacp/gaia_credential_provider_module.h +++ b/chrome/credential_provider/gaiacp/gaia_credential_provider_module.h
@@ -39,9 +39,14 @@ // Indicates if the instance is running in a test. void set_is_testing(bool is_testing) { is_testing_ = is_testing; } + // Performs a one time refresh of all valid token handles to ensure their + // validity is up to date. + void RefreshTokenHandleValidity(); + private: std::unique_ptr<base::AtExitManager> exit_manager_; bool is_testing_ = false; + bool token_handle_validity_refreshed_ = false; }; } // namespace credential_provider
diff --git a/chrome/credential_provider/gaiacp/gaia_credential_provider_unittests.cc b/chrome/credential_provider/gaiacp/gaia_credential_provider_unittests.cc index 60f1a0e..7993064 100644 --- a/chrome/credential_provider/gaiacp/gaia_credential_provider_unittests.cc +++ b/chrome/credential_provider/gaiacp/gaia_credential_provider_unittests.cc
@@ -16,6 +16,7 @@ #include "chrome/credential_provider/gaiacp/gaia_credential_provider.h" #include "chrome/credential_provider/gaiacp/gaia_credential_provider_i.h" #include "chrome/credential_provider/gaiacp/reg_utils.h" +#include "chrome/credential_provider/gaiacp/token_handle_validator.h" #include "chrome/credential_provider/test/com_fakes.h" #include "chrome/credential_provider/test/gcp_fakes.h" #include "testing/gtest/include/gtest/gtest.h" @@ -36,18 +37,6 @@ username, password, fullname, comment, gaia_id, email, sid)); } - void CreateDeletedGCPWUser(BSTR* sid) { - PSID sid_deleted; - ASSERT_EQ(S_OK, fake_os_user_manager_.CreateNewSID(&sid_deleted)); - wchar_t* user_sid_string = nullptr; - ASSERT_TRUE(ConvertSidToStringSid(sid_deleted, &user_sid_string)); - *sid = SysAllocString(W2COLE(user_sid_string)); - - ASSERT_EQ(S_OK, - SetUserProperty(user_sid_string, kUserTokenHandle, L"th_value")); - LocalFree(user_sid_string); - } - FakeOSUserManager* fake_os_user_manager() { return &fake_os_user_manager_; } private: @@ -70,33 +59,6 @@ nullptr, IID_IGaiaCredentialProvider, (void**)&provider)); } -TEST_F(GcpCredentialProviderTest, CleanupStaleTokenHandles) { - // Simulate a user created by GCPW that does not have a stale handle. - CComBSTR sid_good; - CreateGCPWUser(L"username", L"foo@gmail.com", L"password", L"Full Name", - L"Comment", L"gaia-id", &sid_good); - - // Simulate a user created by GCPW that was deleted from the machine. - CComBSTR sid_bad; - CreateDeletedGCPWUser(&sid_bad); - - // Now create the provider. - CComPtr<IGaiaCredentialProvider> provider; - ASSERT_EQ(S_OK, - CComCreator<CComObject<CGaiaCredentialProvider>>::CreateInstance( - nullptr, IID_IGaiaCredentialProvider, (void**)&provider)); - - // Expect "good" sid to still in the registry, "bad" one to be cleaned up. - base::win::RegKey key; - ASSERT_EQ(ERROR_SUCCESS, key.Open(HKEY_LOCAL_MACHINE, - GetUsersRootKeyForTesting(), KEY_READ)); - EXPECT_EQ(ERROR_SUCCESS, key.OpenKey(OLE2CW(sid_good), KEY_READ)); - - ASSERT_EQ(ERROR_SUCCESS, key.Open(HKEY_LOCAL_MACHINE, - GetUsersRootKeyForTesting(), KEY_READ)); - EXPECT_NE(ERROR_SUCCESS, key.OpenKey(OLE2CW(sid_bad), KEY_READ)); -} - TEST_F(GcpCredentialProviderTest, SetUserArray_NoGaiaUsers) { CComPtr<ICredentialProviderSetUserArray> user_array; ASSERT_EQ( @@ -123,40 +85,6 @@ EXPECT_FALSE(autologon); } -TEST_F(GcpCredentialProviderTest, SetUserArray_WithGaiaUsers) { - CComBSTR sid; - CreateGCPWUser(L"username", L"foo@gmail.com", L"password", L"Full Name", - L"Comment", L"gaia-id", &sid); - - CComPtr<ICredentialProviderSetUserArray> user_array; - ASSERT_EQ( - S_OK, - CComCreator<CComObject<CGaiaCredentialProvider>>::CreateInstance( - nullptr, IID_ICredentialProviderSetUserArray, (void**)&user_array)); - - FakeCredentialProviderUserArray array; - array.AddUser(OLE2CW(sid), L"username"); - ASSERT_EQ(S_OK, user_array->SetUserArray(&array)); - - CComPtr<ICredentialProvider> provider; - ASSERT_EQ(S_OK, user_array.QueryInterface(&provider)); - - // There should be 1 credential. It should implement IReauthCredential. - DWORD count; - DWORD default_index; - BOOL autologon; - ASSERT_EQ(S_OK, - provider->GetCredentialCount(&count, &default_index, &autologon)); - ASSERT_EQ(1u, count); - EXPECT_EQ(CREDENTIAL_PROVIDER_NO_DEFAULT, default_index); - EXPECT_FALSE(autologon); - - CComPtr<ICredentialProviderCredential> cred; - ASSERT_EQ(S_OK, provider->GetCredentialAt(0, &cred)); - CComPtr<IReauthCredential> reauth; - EXPECT_EQ(S_OK, cred.QueryInterface(&reauth)); -} - TEST_F(GcpCredentialProviderTest, CpusLogon) { CComPtr<ICredentialProvider> provider; ASSERT_EQ(S_OK, @@ -244,6 +172,9 @@ } TEST_F(GcpCredentialProviderTest, AddPersonAfterUserRemove) { + FakeTokenHandleValidator token_handle_validator; + FakeInternetAvailabilityChecker internet_checker; + // Set up such that MDM is enabled, mulit-users is not, and a user already // exists. ASSERT_EQ(S_OK, SetGlobalFlagForTesting(kRegMdmUrl, L"https://mdm.com")); @@ -272,12 +203,13 @@ } // Delete the OS user. At this point, info in the HKLM registry about this - // user will still exist. However it get properly cleaned up on contruction - // of the provider and so GetCredentialCount() will now return a valid - // credential. + // user will still exist. However it gets properly cleaned up when the token + // validator starts its refresh of token handle validity. ASSERT_EQ(S_OK, fake_os_user_manager()->RemoveUser(kDummyUsername, kDummyPassword)); + // Start token handle refresh threads. + token_handle_validator.StartRefreshingTokenHandleValidity(); { CComPtr<ICredentialProvider> provider; ASSERT_EQ(S_OK, @@ -350,4 +282,93 @@ testing::Range(0, 3), testing::Bool())); +// Check that reauth credentials only exist when the token handle for the +// associated user is no longer valid and internet is available. +// Parameters are: +// 1. bool - does the fake user have a token handle set. +// 2. bool - is the token handle for the fake user valid (i.e. the fetch of +// the token handle info from win_http_url_fetcher returns a valid json). +// 3. bool - is internet available. + +class GcpCredentialProviderWithGaiaUsersTest + : public GcpCredentialProviderTest, + public ::testing::WithParamInterface<std::tuple<bool, bool, bool>> { + public: + FakeWinHttpUrlFetcherFactory* fake_http_url_fetcher_factory() { + return &fake_http_url_fetcher_factory_; + } + + private: + FakeWinHttpUrlFetcherFactory fake_http_url_fetcher_factory_; +}; + +TEST_P(GcpCredentialProviderWithGaiaUsersTest, ReauthCredentialTest) { + const bool has_token_handle = std::get<0>(GetParam()); + const bool valid_token_handle = std::get<1>(GetParam()); + const bool has_internet = std::get<2>(GetParam()); + FakeTokenHandleValidator token_handle_validator; + FakeInternetAvailabilityChecker internet_checker( + has_internet ? FakeInternetAvailabilityChecker::kHicForceYes + : FakeInternetAvailabilityChecker::kHicForceNo); + + CComBSTR sid; + CreateGCPWUser(L"username", L"foo@gmail.com", L"password", L"Full Name", + L"Comment", L"gaia-id", &sid); + + if (!has_token_handle) + ASSERT_EQ(S_OK, SetUserProperty((BSTR)sid, kUserTokenHandle, L"")); + + // Token fetch result. + fake_http_url_fetcher_factory()->SetFakeResponse( + GURL(TokenHandleValidator::kTokenInfoUrl), + FakeWinHttpUrlFetcher::Headers(), + valid_token_handle ? "{\"expires_in\":1}" : "{}"); + + // Start token handle refresh threads. + token_handle_validator.StartRefreshingTokenHandleValidity(); + + CComPtr<ICredentialProviderSetUserArray> user_array; + ASSERT_EQ( + S_OK, + CComCreator<CComObject<CGaiaCredentialProvider>>::CreateInstance( + nullptr, IID_ICredentialProviderSetUserArray, (void**)&user_array)); + + FakeCredentialProviderUserArray array; + array.AddUser(OLE2CW(sid), L"username"); + ASSERT_EQ(S_OK, user_array->SetUserArray(&array)); + + CComPtr<ICredentialProvider> provider; + ASSERT_EQ(S_OK, user_array.QueryInterface(&provider)); + + bool should_reauth_user = + has_internet && (!has_token_handle || !valid_token_handle); + + // Check if there is a IReauthCredential depending on the state of the token + // handle. + DWORD count; + DWORD default_index; + BOOL autologon; + ASSERT_EQ(S_OK, + provider->GetCredentialCount(&count, &default_index, &autologon)); + // Since SetUsageScenario was not called on the provider, only the user + // associated credentials will be created so only expect 0 or 1 credentials + // in this test depending on if the user needs to reauth. + ASSERT_EQ(should_reauth_user ? 1u : 0u, count); + EXPECT_EQ(CREDENTIAL_PROVIDER_NO_DEFAULT, default_index); + EXPECT_FALSE(autologon); + + if (should_reauth_user) { + CComPtr<ICredentialProviderCredential> cred; + ASSERT_EQ(S_OK, provider->GetCredentialAt(0, &cred)); + CComPtr<IReauthCredential> reauth; + EXPECT_EQ(S_OK, cred.QueryInterface(&reauth)); + } +} + +INSTANTIATE_TEST_CASE_P(, + GcpCredentialProviderWithGaiaUsersTest, + ::testing::Combine(::testing::Bool(), + ::testing::Bool(), + ::testing::Bool())); + } // namespace credential_provider
diff --git a/chrome/credential_provider/gaiacp/internet_availability_checker.cc b/chrome/credential_provider/gaiacp/internet_availability_checker.cc new file mode 100644 index 0000000..86ebb67 --- /dev/null +++ b/chrome/credential_provider/gaiacp/internet_availability_checker.cc
@@ -0,0 +1,68 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/credential_provider/gaiacp/internet_availability_checker.h" + +#include <netlistmgr.h> // For CLSID_NetworkListManager + +#include <atlbase.h> +#include <atlcom.h> + +#include "chrome/credential_provider/gaiacp/gcp_utils.h" +#include "chrome/credential_provider/gaiacp/logging.h" + +namespace credential_provider { + +namespace { + +bool InternetConnectionAvailable() { + // If any errors occur, return that internet connection is available. At + // worst the credential provider will try to connect and fail. + + CComPtr<INetworkListManager> manager; + HRESULT hr = manager.CoCreateInstance(CLSID_NetworkListManager); + if (FAILED(hr)) { + LOGFN(ERROR) << "CoCreateInstance(NetworkListManager) hr=" << putHR(hr); + return true; + } + + VARIANT_BOOL is_connected; + hr = manager->get_IsConnectedToInternet(&is_connected); + if (FAILED(hr)) { + LOGFN(ERROR) << "manager->get_IsConnectedToInternet hr=" << putHR(hr); + return true; + } + + // Normally VARIANT_TRUE/VARIANT_FALSE are used with the type VARIANT_BOOL + // but in this case the docs explicitly say to use FALSE. + // https://docs.microsoft.com/en-us/windows/desktop/api/Netlistmgr/ + // nf-netlistmgr-inetworklistmanager-get_isconnectedtointernet + return is_connected != FALSE; +} + +} // namespace + +// static +InternetAvailabilityChecker* InternetAvailabilityChecker::Get() { + return *GetInstanceStorage(); +} + +// static +InternetAvailabilityChecker** +InternetAvailabilityChecker::GetInstanceStorage() { + static InternetAvailabilityChecker instance; + static InternetAvailabilityChecker* instance_storage = &instance; + + return &instance_storage; +} + +InternetAvailabilityChecker::InternetAvailabilityChecker() = default; + +InternetAvailabilityChecker::~InternetAvailabilityChecker() = default; + +bool InternetAvailabilityChecker::HasInternetConnection() { + return InternetConnectionAvailable(); +} + +} // namespace credential_provider
diff --git a/chrome/credential_provider/gaiacp/internet_availability_checker.h b/chrome/credential_provider/gaiacp/internet_availability_checker.h new file mode 100644 index 0000000..83a9e963 --- /dev/null +++ b/chrome/credential_provider/gaiacp/internet_availability_checker.h
@@ -0,0 +1,28 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_CREDENTIAL_PROVIDER_GAIACP_INTERNET_AVAILABILITY_CHECKER_H_ +#define CHROME_CREDENTIAL_PROVIDER_GAIACP_INTERNET_AVAILABILITY_CHECKER_H_ + +namespace credential_provider { + +// Checks the availability of an internet connection. In unit test this class +// can be overriden to return a forced value if desired. +class InternetAvailabilityChecker { + public: + static InternetAvailabilityChecker* Get(); + + virtual bool HasInternetConnection(); + + protected: + InternetAvailabilityChecker(); + virtual ~InternetAvailabilityChecker(); + + // Returns the storage used for the instance pointer. + static InternetAvailabilityChecker** GetInstanceStorage(); +}; + +} // namespace credential_provider + +#endif // CHROME_CREDENTIAL_PROVIDER_GAIACP_INTERNET_AVAILABILITY_CHECKER_H_
diff --git a/chrome/credential_provider/gaiacp/reg_utils.cc b/chrome/credential_provider/gaiacp/reg_utils.cc index 19d9266..d1a199e 100644 --- a/chrome/credential_provider/gaiacp/reg_utils.cc +++ b/chrome/credential_provider/gaiacp/reg_utils.cc
@@ -13,9 +13,6 @@ namespace credential_provider { - -namespace { - // Root registry key for GCP configuration and state. #if defined(GOOGLE_CHROME_BUILD) #define CREDENTIAL_PROVIDER_REGISTRY_KEY L"Software\\Google\\GCP" @@ -24,6 +21,12 @@ #endif // defined(GOOGLE_CHROME_BUILD) const wchar_t kGcpRootKeyName[] = CREDENTIAL_PROVIDER_REGISTRY_KEY; + +const wchar_t kGcpUsersRootKeyName[] = + CREDENTIAL_PROVIDER_REGISTRY_KEY L"\\Users"; + +namespace { + const wchar_t kAccountPicturesRootRegKey[] = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\AccountPicture\\Users"; const wchar_t kImageRegKey[] = L"Image"; @@ -58,7 +61,6 @@ return S_OK; } - HRESULT GetMachineRegString(const base::string16& key_name, const base::string16& name, wchar_t* value, @@ -135,7 +137,6 @@ return base::StringPrintf(L"%ls%i", kImageRegKey, image_size); } - base::string16 GetAccountPictureRegPathForUSer(const base::string16& user_sid) { return base::StringPrintf(L"%ls\\%ls", kAccountPicturesRootRegKey, user_sid.c_str()); @@ -194,7 +195,7 @@ const base::string16& name, DWORD* value) { wchar_t key_name[128]; - swprintf_s(key_name, base::size(key_name), L"%s\\Users\\%s", kGcpRootKeyName, + swprintf_s(key_name, base::size(key_name), L"%s\\%s", kGcpUsersRootKeyName, sid.c_str()); return GetRegDWORD(key_name, name, value); } @@ -204,7 +205,7 @@ wchar_t* value, ULONG* length) { wchar_t key_name[128]; - swprintf_s(key_name, base::size(key_name), L"%s\\Users\\%s", kGcpRootKeyName, + swprintf_s(key_name, base::size(key_name), L"%s\\%s", kGcpUsersRootKeyName, sid.c_str()); return GetMachineRegString(key_name, name, value, length); } @@ -213,7 +214,7 @@ const base::string16& name, DWORD value) { wchar_t key_name[128]; - swprintf_s(key_name, base::size(key_name), L"%s\\Users\\%s", kGcpRootKeyName, + swprintf_s(key_name, base::size(key_name), L"%s\\%s", kGcpUsersRootKeyName, sid.c_str()); return SetRegDWORD(key_name, name, value); } @@ -222,17 +223,14 @@ const base::string16& name, const base::string16& value) { wchar_t key_name[128]; - swprintf_s(key_name, base::size(key_name), L"%s\\Users\\%s", kGcpRootKeyName, + swprintf_s(key_name, base::size(key_name), L"%s\\%s", kGcpUsersRootKeyName, sid.c_str()); return SetMachineRegString(key_name, name, value); } HRESULT RemoveAllUserProperties(const base::string16& sid) { - wchar_t key_name[128]; - swprintf_s(key_name, base::size(key_name), L"%s\\Users", kGcpRootKeyName); - base::win::RegKey key; - LONG sts = key.Open(HKEY_LOCAL_MACHINE, key_name, KEY_WRITE); + LONG sts = key.Open(HKEY_LOCAL_MACHINE, kGcpUsersRootKeyName, KEY_WRITE); if (sts != ERROR_SUCCESS) return HRESULT_FROM_WIN32(sts); @@ -240,20 +238,25 @@ return sts != ERROR_SUCCESS ? HRESULT_FROM_WIN32(sts) : S_OK; } -HRESULT GetUserTokenHandles(std::map<base::string16, base::string16>* handles) { - DCHECK(handles); +HRESULT GetUserTokenHandles( + std::map<base::string16, UserTokenHandleInfo>* sid_to_handle_info) { + DCHECK(sid_to_handle_info); + sid_to_handle_info->clear(); - wchar_t key_name[128]; - swprintf_s(key_name, base::size(key_name), L"%s\\Users", kGcpRootKeyName); - - base::win::RegistryKeyIterator iter(HKEY_LOCAL_MACHINE, key_name); + base::win::RegistryKeyIterator iter(HKEY_LOCAL_MACHINE, kGcpUsersRootKeyName); for (; iter.Valid(); ++iter) { const wchar_t* sid = iter.Name(); + wchar_t gaia_id[256]; + ULONG length = base::size(gaia_id); + HRESULT gaia_id_hr = GetUserProperty(sid, kUserId, gaia_id, &length); wchar_t token_handle[256]; - ULONG length = base::size(token_handle); - HRESULT hr = GetUserProperty(sid, kUserTokenHandle, token_handle, &length); - if (SUCCEEDED(hr)) - handles->emplace(sid, token_handle); + length = base::size(token_handle); + HRESULT token_handle_hr = + GetUserProperty(sid, kUserTokenHandle, token_handle, &length); + sid_to_handle_info->emplace( + sid, + UserTokenHandleInfo{SUCCEEDED(gaia_id_hr) ? gaia_id : L"", + SUCCEEDED(token_handle_hr) ? token_handle : L""}); } return S_OK; } @@ -261,11 +264,9 @@ HRESULT GetSidFromId(const base::string16& id, wchar_t* sid, ULONG length) { DCHECK(sid); - wchar_t key_name[128]; - swprintf_s(key_name, base::size(key_name), L"%ls\\Users", kGcpRootKeyName); bool result_found = false; - base::win::RegistryKeyIterator iter(HKEY_LOCAL_MACHINE, key_name); + base::win::RegistryKeyIterator iter(HKEY_LOCAL_MACHINE, kGcpUsersRootKeyName); for (; iter.Valid(); ++iter) { const wchar_t* user_sid = iter.Name(); wchar_t user_id[256]; @@ -287,10 +288,7 @@ HRESULT GetIdFromSid(const wchar_t* sid, base::string16* id) { DCHECK(id); - wchar_t key_name[128]; - swprintf_s(key_name, base::size(key_name), L"%ls\\Users", kGcpRootKeyName); - - base::win::RegistryKeyIterator iter(HKEY_LOCAL_MACHINE, key_name); + base::win::RegistryKeyIterator iter(HKEY_LOCAL_MACHINE, kGcpUsersRootKeyName); for (; iter.Valid(); ++iter) { const wchar_t* user_sid = iter.Name(); @@ -307,8 +305,4 @@ return HRESULT_FROM_WIN32(ERROR_NONE_MAPPED); } -const wchar_t* GetUsersRootKeyForTesting() { - return CREDENTIAL_PROVIDER_REGISTRY_KEY L"\\Users"; -} - } // namespace credential_provider
diff --git a/chrome/credential_provider/gaiacp/reg_utils.h b/chrome/credential_provider/gaiacp/reg_utils.h index 331cc03..74807b42 100644 --- a/chrome/credential_provider/gaiacp/reg_utils.h +++ b/chrome/credential_provider/gaiacp/reg_utils.h
@@ -6,12 +6,19 @@ #define CHROME_CREDENTIAL_PROVIDER_GAIACP_REG_UTILS_H_ #include <map> +#include <vector> #include "base/strings/string16.h" #include "base/win/windows_types.h" namespace credential_provider { +// Root registry key where all settings and user information for GCPW is stored. +extern const wchar_t kGcpRootKeyName[]; + +// Root registry key where all user association information for GCPW is stored. +extern const wchar_t kGcpUsersRootKeyName[]; + // Gets global DWORD flag. HRESULT GetGlobalFlag(const base::string16& name, DWORD* value); @@ -58,8 +65,19 @@ // Removes all properties for the user. HRESULT RemoveAllUserProperties(const base::string16& sid); -// Gets token handles for all users created by this credential provider. -HRESULT GetUserTokenHandles(std::map<base::string16, base::string16>* handles); +struct UserTokenHandleInfo { + base::string16 gaia_id; + base::string16 token_handle; +}; + +// Gets basic user association info as stored in the registry. For each found +// sid under GCPW's Users registry key, this function will return: +// 1. The gaia id associated to the user (if any). +// 2. The value of the token handle (if any). +// This function does not provide any guarantee as to the validity of the +// information returned w.r.t. actual users that exist on the system. +HRESULT GetUserTokenHandles( + std::map<base::string16, UserTokenHandleInfo>* sid_to_handle_info); // Gets the SID associated with the given gaia id. If none exists, returns // HRESULT_FROM_WIN32(ERROR_NONE_MAPPED). @@ -69,19 +87,16 @@ // HRESULT_FROM_WIN32(ERROR_NONE_MAPPED). HRESULT GetIdFromSid(const wchar_t* sid, base::string16* id); -// Returns the root registry key that needs to be verified in unit tests. -const wchar_t* GetUsersRootKeyForTesting(); - // Gets a specific account picture registry key in HKEY_LOCAL_MACHINE HRESULT GetAccountPictureRegString(const base::string16& user_sid, int image_size, - wchar_t* value, - ULONG* length); + wchar_t* value, + ULONG* length); // Sets a specific account picture registry key in HKEY_LOCAL_MACHINE HRESULT SetAccountPictureRegString(const base::string16& user_sid, int image_size, - const base::string16& value); + const base::string16& value); } // namespace credential_provider #endif // CHROME_CREDENTIAL_PROVIDER_GAIACP_REG_UTILS_H_
diff --git a/chrome/credential_provider/gaiacp/token_handle_validator.cc b/chrome/credential_provider/gaiacp/token_handle_validator.cc new file mode 100644 index 0000000..4631847d --- /dev/null +++ b/chrome/credential_provider/gaiacp/token_handle_validator.cc
@@ -0,0 +1,338 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/credential_provider/gaiacp/token_handle_validator.h" + +#include <process.h> + +#include "base/json/json_reader.h" +#include "base/logging.h" +#include "base/strings/string16.h" +#include "base/strings/stringprintf.h" +#include "base/values.h" +#include "chrome/credential_provider/common/gcp_strings.h" +#include "chrome/credential_provider/gaiacp/gcp_utils.h" +#include "chrome/credential_provider/gaiacp/internet_availability_checker.h" +#include "chrome/credential_provider/gaiacp/logging.h" +#include "chrome/credential_provider/gaiacp/os_user_manager.h" +#include "chrome/credential_provider/gaiacp/reg_utils.h" +#include "chrome/credential_provider/gaiacp/win_http_url_fetcher.h" + +namespace credential_provider { + +const base::TimeDelta + TokenHandleValidator::kDefaultTokenHandleValidationTimeout = + base::TimeDelta::FromMilliseconds(3000); + +const base::TimeDelta TokenHandleValidator::kTokenHandleValidityLifetime = + base::TimeDelta::FromSeconds(30); + +const char TokenHandleValidator::kTokenInfoUrl[] = + "https://www.googleapis.com/oauth2/v2/tokeninfo"; + +namespace { + +struct CheckReauthParams { + base::string16 sid; + base::string16 token_handle; +}; + +// Queries google to see whether the user's token handle is no longer valid or +// is expired. Returns 1 if it is still valid, 0 if the user needs to reauth. +unsigned __stdcall CheckReauthStatus(void* param) { + DCHECK(param); + std::unique_ptr<CheckReauthParams> reauth_info( + reinterpret_cast<CheckReauthParams*>(param)); + + auto fetcher = + WinHttpUrlFetcher::Create(GURL(TokenHandleValidator::kTokenInfoUrl)); + + if (fetcher) { + fetcher->SetRequestHeader("Content-Type", + "application/x-www-form-urlencoded"); + + std::string body = base::StringPrintf("token_handle=%ls", + reauth_info->token_handle.c_str()); + HRESULT hr = fetcher->SetRequestBody(body.c_str()); + if (FAILED(hr)) { + LOGFN(ERROR) << "fetcher.SetRequestBody sid=" << reauth_info->sid + << " hr=" << putHR(hr); + return 1; + } + + std::vector<char> response; + hr = fetcher->Fetch(&response); + if (FAILED(hr)) { + LOGFN(INFO) << "fetcher.Fetch sid=" << reauth_info->sid + << " hr=" << putHR(hr); + return 1; + } + + base::DictionaryValue* dict = nullptr; + base::StringPiece response_string(response.data(), response.size()); + base::Optional<base::Value> properties(base::JSONReader::Read( + response_string, base::JSON_ALLOW_TRAILING_COMMAS)); + if (!properties || !properties->GetAsDictionary(&dict)) { + LOGFN(ERROR) << "base::JSONReader::Read failed forcing reauth"; + return 0; + } + + int expires_in; + if (dict->HasKey("error") || !dict->GetInteger("expires_in", &expires_in) || + expires_in < 0) { + LOGFN(INFO) << "Needs reauth sid=" << reauth_info->sid; + return 0; + } + } + + return 1; +} + +bool TokenHandleNeedsUpdate(const base::Time& last_refresh) { + return (base::Time::Now() - last_refresh) > + TokenHandleValidator::kTokenHandleValidityLifetime; +} + +bool WaitForQueryResult(const base::win::ScopedHandle& thread_handle, + const base::Time& until) { + if (!thread_handle.IsValid()) + return true; + + DWORD time_left = std::max<DWORD>( + static_cast<DWORD>((until - base::Time::Now()).InMilliseconds()), 0); + + // See if a response to the token info can be fetched in a reasonable + // amount of time. If not, assume there is no internet and that the handle + // is still valid. + HRESULT hr = ::WaitForSingleObject(thread_handle.Get(), time_left); + + bool token_handle_validity = false; + if (hr == WAIT_OBJECT_0) { + DWORD exit_code; + token_handle_validity = + !::GetExitCodeThread(thread_handle.Get(), &exit_code) || exit_code == 1; + } else if (hr == WAIT_TIMEOUT) { + token_handle_validity = true; + } + + return token_handle_validity; +} + +HRESULT CleanupStaleUsersAndGetTokenHandles( + std::map<base::string16, base::string16>* sid_to_handle) { + DCHECK(sid_to_handle); + std::map<base::string16, UserTokenHandleInfo> sids_to_handle_info; + + HRESULT hr = GetUserTokenHandles(&sids_to_handle_info); + if (FAILED(hr)) { + LOGFN(ERROR) << "GetUserAssociationInfo hr=" << putHR(hr); + return hr; + } + + OSUserManager* manager = OSUserManager::Get(); + for (const auto& sid_to_association : sids_to_handle_info) { + const base::string16& sid = sid_to_association.first; + const UserTokenHandleInfo& info = sid_to_association.second; + if (info.gaia_id.empty()) { + RemoveAllUserProperties(sid); + continue; + } + HRESULT hr = manager->FindUserBySID(sid.c_str(), nullptr, 0, nullptr, 0); + if (hr == HRESULT_FROM_WIN32(ERROR_NONE_MAPPED)) { + RemoveAllUserProperties(sid); + continue; + } else if (FAILED(hr)) { + LOGFN(ERROR) << "manager->FindUserBySID hr=" << putHR(hr); + } + + sid_to_handle->emplace(sid, info.token_handle); + } + + return S_OK; +} + +} // namespace + +TokenHandleValidator::TokenHandleInfo::TokenHandleInfo() = default; +TokenHandleValidator::TokenHandleInfo::~TokenHandleInfo() = default; + +TokenHandleValidator::TokenHandleInfo::TokenHandleInfo( + const base::string16& token_handle) + : queried_token_handle(token_handle), last_update(base::Time::Now()) {} + +TokenHandleValidator::TokenHandleInfo::TokenHandleInfo( + const base::string16& token_handle, + base::Time update_time, + base::win::ScopedHandle::Handle thread_handle) + : queried_token_handle(token_handle), + last_update(update_time), + pending_query_thread(thread_handle) {} + +// static +TokenHandleValidator* TokenHandleValidator::Get() { + return *GetInstanceStorage(); +} + +// static +TokenHandleValidator** TokenHandleValidator::GetInstanceStorage() { + static TokenHandleValidator instance(kDefaultTokenHandleValidationTimeout); + static TokenHandleValidator* instance_storage = &instance; + + return &instance_storage; +} + +TokenHandleValidator::TokenHandleValidator(base::TimeDelta validation_timeout) + : validation_timeout_(validation_timeout) {} + +TokenHandleValidator::~TokenHandleValidator() = default; + +bool TokenHandleValidator::HasInternetConnection() { + return InternetAvailabilityChecker::Get()->HasInternetConnection(); +} + +void TokenHandleValidator::StartRefreshingTokenHandleValidity() { + std::map<base::string16, base::string16> sid_to_handle; + HRESULT hr = CleanupStaleUsersAndGetTokenHandles(&sid_to_handle); + + if (FAILED(hr)) { + LOGFN(ERROR) << "CleanupStaleUsersAndGetTokenHandles hr=" << putHR(hr); + return; + } + + // Fire off the threads that will query the token handles but do not wait for + // them to complete. Later queries will do the wait. + CheckTokenHandleValidity(sid_to_handle); +} + +void TokenHandleValidator::CheckTokenHandleValidity( + const std::map<base::string16, base::string16>& handles_to_verify) { + for (auto it = handles_to_verify.cbegin(); it != handles_to_verify.cend(); + ++it) { + // Make sure the user actually exists. + if (FAILED(OSUserManager::Get()->FindUserBySID(it->first.c_str(), nullptr, + 0, nullptr, 0))) { + continue; + } + + // User exists, has a gaia id, but no token handle. Consider this an invalid + // token handle and the user needs to sign in with Gaia to get a new one. + if (it->second.empty()) { + user_to_token_handle_info_[it->first] = + std::make_unique<TokenHandleInfo>(base::string16()); + continue; + } + + // If there is already token handle info for the current user and it + // 1. Is NOT valid. + // AND + // 2. There is no query still pending on it. + // Then this means that the user has an invalid token handle. + // The state of this handle will never change during the execution of the + // sign in process (since a new token handle will only be written on + // successful sign in) so it does not need to update and the current state + // information is valid. + auto existing_validity_it = user_to_token_handle_info_.find(it->first); + if (existing_validity_it != user_to_token_handle_info_.end() && + !existing_validity_it->second->is_valid && + !existing_validity_it->second->pending_query_thread.IsValid()) { + continue; + } + + // Start a new token handle query if: + // 1. No token info entry yet exists for this token handle. + // OR + // 2. Token info exists but it is stale (either because it is a query that + // was started a while ago but for which we never tried to query the result + // because the last query result is from a while ago or because the last + // query result is older than |kTokenHandleValidityLifetime|). + if (existing_validity_it == user_to_token_handle_info_.end() || + TokenHandleNeedsUpdate(existing_validity_it->second->last_update)) { + StartTokenValidityQuery(it->first, it->second, validation_timeout_); + } + } +} + +void TokenHandleValidator::StartTokenValidityQuery( + const base::string16& sid, + const base::string16& token_handle, + base::TimeDelta timeout) { + base::Time max_end_time = base::Time::Now() + timeout; + + // Fire off a thread to check with Gaia if a re-auth is required. The thread + // does not reference this object nor does this object have any reference + // directly on the thread. This object only checks for the return code of the + // thread within a given timeout. If no return code is given in that timeout + // then assume that the token handle is valid. The running thread can continue + // running and finish its execution without worrying about notifying anything + // about the result. + unsigned wait_thread_id; + CheckReauthParams* params = new CheckReauthParams{sid, token_handle}; + uintptr_t wait_thread = + _beginthreadex(nullptr, 0, CheckReauthStatus, + reinterpret_cast<void*>(params), 0, &wait_thread_id); + if (wait_thread == 0) { + user_to_token_handle_info_[sid] = + std::make_unique<TokenHandleInfo>(token_handle); + delete params; + return; + } + + user_to_token_handle_info_[sid] = std::make_unique<TokenHandleInfo>( + token_handle, max_end_time, reinterpret_cast<HANDLE>(wait_thread)); +} + +bool TokenHandleValidator::IsTokenHandleValidForUser( + const base::string16& sid) { + // All token handles are valid when no internet connection is available. + if (!HasInternetConnection()) + return true; + + // If at this point there is not token info entry for this user, assume the + // user is not associated and does not need a token handle and is thus always + // valid. On initial startup we should have already called + // StartRefreshingTokenHandleValidity to create all the token info for all the + // current associated users. Between the first creation of all the token infos + // and the eventual successful sign in there should be no new token handles + // created so we can immediately assign that an absence of token handle info + // for this user means that they are not associated and do not need to + // validate any token handles. + auto validity_it = user_to_token_handle_info_.find(sid); + + if (validity_it == user_to_token_handle_info_.end()) + return true; + + // This function will start a new query if the current info for the token + // handle is stale or has not yet been queried. At the end of this function, + // either we will already have the validity of the token handle or we have a + // handle to a pending query that we wait to complete before finally having + // the validity. + CheckTokenHandleValidity({{sid, validity_it->second->queried_token_handle}}); + + // If a query is still pending, wait for it and update the validity. + if (validity_it->second->pending_query_thread.IsValid()) { + validity_it->second->is_valid = + WaitForQueryResult(validity_it->second->pending_query_thread, + validity_it->second->last_update); + validity_it->second->pending_query_thread.Close(); + base::Time now = base::Time::Now(); + // NOTE: Don't always update |last_update| because the result of this query + // may still be old. E.g.: + // 1. At time X thread is started to query. The maximum end time of this + // query is X + timeout + // 2. At time Y (X + timeout + lifetime > Y >> X + timeout) we ask for + // the validity of the token handle. The time Y might still be valid + // when considering the lifetime but may still be relatively old + // depending on how long after time X the request is made. So keep the + // original end time of the query as the last update (if the end time + // occurs before time Y) so that the token handle is updated earlier on + // the next query. + validity_it->second->last_update = now > validity_it->second->last_update + ? validity_it->second->last_update + : now; + } + + return validity_it->second->is_valid; +} + +} // namespace credential_provider
diff --git a/chrome/credential_provider/gaiacp/token_handle_validator.h b/chrome/credential_provider/gaiacp/token_handle_validator.h new file mode 100644 index 0000000..bcff4cf --- /dev/null +++ b/chrome/credential_provider/gaiacp/token_handle_validator.h
@@ -0,0 +1,99 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_CREDENTIAL_PROVIDER_GAIACP_TOKEN_HANDLE_VALIDATOR_H_ +#define CHROME_CREDENTIAL_PROVIDER_GAIACP_TOKEN_HANDLE_VALIDATOR_H_ + +#include <map> + +#include <base/strings/string16.h> +#include <base/time/time.h> +#include <base/win/scoped_handle.h> + +#include "chrome/credential_provider/gaiacp/gaia_credential_provider_i.h" + +namespace credential_provider { + +// Caches the current validity of token handles and updates the validity if +// it is older than a specified validity lifetime. +class TokenHandleValidator { + public: + // Default timeout when querying token info for token handles. If a timeout + // occurs the token handle is assumed to be valid. + static const base::TimeDelta kDefaultTokenHandleValidationTimeout; + + // Minimum time between token handle info refreshes. When trying to get token + // info, if the info is older than this value, a new token info query will + // be made. + static const base::TimeDelta kTokenHandleValidityLifetime; + + // Default URL used to fetch token info for token handles. + static const char kTokenInfoUrl[]; + + static TokenHandleValidator* Get(); + + // Get all the token handles for all associated users and start queries + // for their validity. The queries are fired in separate threads but + // no wait is done for the result. This allows background processing of + // the queries until they are actually needed. An eventual call to + // IsTokenHandleValidForUser will cause the wait for the result as needed. + void StartRefreshingTokenHandleValidity(); + + // Checks whether the token handle for the given user is valid or not. + // This function is blocking and may fire off a query for a token handle that + // needs to complete before the function returns. + bool IsTokenHandleValidForUser(const base::string16& sid); + + protected: + explicit TokenHandleValidator(base::TimeDelta validation_timeout); + virtual ~TokenHandleValidator(); + + bool HasInternetConnection(); + void CheckTokenHandleValidity( + const std::map<base::string16, base::string16>& handles_to_verify); + void StartTokenValidityQuery(const base::string16& sid, + const base::string16& token_handle, + base::TimeDelta timeout); + + // Returns the storage used for the instance pointer. + static TokenHandleValidator** GetInstanceStorage(); + + // Stores information about the current state of a user's token handle. + // This information includes: + // * The last token handle found for the user. + // * The validity of this last token handle (if checked). + // * The time of the last update of the validity of this token handle. + // This will often be the max end time of the last query that was made on + // the token handle. + // * The handle to the current thread being executed to verify the + // validity of the last token handle. + struct TokenHandleInfo { + TokenHandleInfo(); + ~TokenHandleInfo(); + + // Used when the handle is empty or invalid. + explicit TokenHandleInfo(const base::string16& token_handle); + + // Used to create a new token handle info that needs to query validity. + // The validity is assumed to be invalid at the time of construction. + TokenHandleInfo(const base::string16& token_handle, + base::Time update_time, + base::win::ScopedHandle::Handle thread_handle); + + base::string16 queried_token_handle; + bool is_valid = false; + base::Time last_update; + base::win::ScopedHandle pending_query_thread; + }; + + // Maps a user's sid to the token handle info associated with this user (if + // any). + std::map<base::string16, std::unique_ptr<TokenHandleInfo>> + user_to_token_handle_info_; + base::TimeDelta validation_timeout_; +}; + +} // namespace credential_provider + +#endif // CHROME_CREDENTIAL_PROVIDER_GAIACP_TOKEN_HANDLE_VALIDATOR_H_
diff --git a/chrome/credential_provider/gaiacp/token_handle_validator_unittests.cc b/chrome/credential_provider/gaiacp/token_handle_validator_unittests.cc new file mode 100644 index 0000000..b2d080b --- /dev/null +++ b/chrome/credential_provider/gaiacp/token_handle_validator_unittests.cc
@@ -0,0 +1,306 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/credential_provider/gaiacp/stdafx.h" + +#include "base/stl_util.h" +#include "base/strings/string16.h" +#include "base/synchronization/waitable_event.h" +#include "base/test/test_reg_util_win.h" +#include "base/time/time_override.h" +#include "chrome/credential_provider/common/gcp_strings.h" +#include "chrome/credential_provider/gaiacp/reg_utils.h" +#include "chrome/credential_provider/gaiacp/token_handle_validator.h" +#include "chrome/credential_provider/test/gcp_fakes.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace credential_provider { + +namespace { + +base::string16 GetNewSidString(FakeOSUserManager* fake_os_user_manager) { + PSID sid; + HRESULT hr = fake_os_user_manager->CreateNewSID(&sid); + if (FAILED(hr)) + return base::string16(); + + LPWSTR sid_string; + bool convert = ::ConvertSidToStringSid(sid, &sid_string); + ::FreeSid(sid); + + base::string16 result; + if (convert) + result = (sid_string); + + ::LocalFree(sid_string); + return result; +} + +} // namespace + +namespace testing { + +class TokenHandleValidatorTest : public ::testing::Test { + protected: + void CreateDeletedGCPWUser(BSTR* sid) { + PSID sid_deleted; + ASSERT_EQ(S_OK, fake_os_user_manager_.CreateNewSID(&sid_deleted)); + wchar_t* user_sid_string = nullptr; + ASSERT_TRUE(ConvertSidToStringSid(sid_deleted, &user_sid_string)); + *sid = SysAllocString(W2COLE(user_sid_string)); + + ASSERT_EQ(S_OK, SetUserProperty(user_sid_string, kUserId, L"id_value")); + ASSERT_EQ(S_OK, + SetUserProperty(user_sid_string, kUserTokenHandle, L"th_value")); + LocalFree(user_sid_string); + } + + TokenHandleValidatorTest(); + ~TokenHandleValidatorTest() override; + + void SetUp() override; + + FakeOSUserManager* fake_os_user_manager() { return &fake_os_user_manager_; } + FakeWinHttpUrlFetcherFactory* fake_http_url_fetcher_factory() { + return &fake_http_url_fetcher_factory_; + } + + private: + FakeOSUserManager fake_os_user_manager_; + FakeWinHttpUrlFetcherFactory fake_http_url_fetcher_factory_; + registry_util::RegistryOverrideManager registry_override_; +}; + +TokenHandleValidatorTest::TokenHandleValidatorTest() = default; +TokenHandleValidatorTest ::~TokenHandleValidatorTest() = default; + +void TokenHandleValidatorTest::SetUp() { + ASSERT_NO_FATAL_FAILURE( + registry_override_.OverrideRegistry(HKEY_LOCAL_MACHINE)); +} + +TEST_F(TokenHandleValidatorTest, CleanupStaleUsers) { + // Simulate a user created by GCPW that does not have a stale handle. + CComBSTR sid_good; + ASSERT_EQ(S_OK, fake_os_user_manager()->CreateTestOSUser( + L"username", L"password", L"Full Name", L"Comment", + L"gaia-id", L"foo@gmail.com", &sid_good)); + ASSERT_EQ(S_OK, + SetUserProperty(OLE2W(sid_good), kUserTokenHandle, L"good-th")); + + // Simulate a user created by GCPW that was deleted from the machine. + CComBSTR sid_bad; + CreateDeletedGCPWUser(&sid_bad); + + // Simulate a user created by GCPW that has no gaia id. + CComBSTR sid_no_gaia_id; + ASSERT_EQ(S_OK, fake_os_user_manager()->CreateTestOSUser( + L"username2", L"password", L"Full Name", L"Comment", L"", + L"foo2@gmail.com", &sid_no_gaia_id)); + + // Simulate a user created by GCPW that has a gaia id, but no token handle + // set. + CComBSTR sid_no_token_handle; + ASSERT_EQ(S_OK, fake_os_user_manager()->CreateTestOSUser( + L"username3", L"password", L"Full Name", L"Comment", + L"gaia-id3", L"foo3@gmail.com", &sid_no_token_handle)); + // Clear the token handle automatically created by CreateTestOSUser. + EXPECT_EQ(S_OK, + SetUserProperty((BSTR)sid_no_token_handle, kUserTokenHandle, L"")); + + wchar_t token_handle[256]; + DWORD length = base::size(token_handle); + EXPECT_NE(S_OK, GetUserProperty((BSTR)sid_no_token_handle, kUserTokenHandle, + token_handle, &length)); + + // Create a token handle validator and start a refresh so that + // stale token handles are cleaned. + FakeTokenHandleValidator validator; + validator.StartRefreshingTokenHandleValidity(); + + // Expect "good" sid to still in the registry. + base::win::RegKey key; + ASSERT_EQ(ERROR_SUCCESS, + key.Open(HKEY_LOCAL_MACHINE, kGcpUsersRootKeyName, KEY_READ)); + EXPECT_EQ(ERROR_SUCCESS, key.OpenKey(OLE2CW(sid_good), KEY_READ)); + + // For all bad users, token handle should be valid since the assumption is + // that if no user entry is found internally in the validator then it is an + // unassociated user and thus always has a valid token handle. + EXPECT_TRUE(validator.IsTokenHandleValidForUser(OLE2CW(sid_bad))); + EXPECT_TRUE(validator.IsTokenHandleValidForUser(OLE2CW(sid_no_gaia_id))); + EXPECT_FALSE( + validator.IsTokenHandleValidForUser(OLE2CW(sid_no_token_handle))); + + // Expect deleted user and user with no gaia id to be deleted. + EXPECT_NE(ERROR_SUCCESS, key.OpenKey(OLE2CW(sid_bad), KEY_READ)); + EXPECT_NE(ERROR_SUCCESS, key.OpenKey(OLE2CW(sid_no_gaia_id), KEY_READ)); + + // Expect user with no token handle to still not have a token handle set in + // the registry. + length = base::size(token_handle); + EXPECT_NE(S_OK, GetUserProperty((BSTR)sid_no_token_handle, kUserTokenHandle, + token_handle, &length)); +} + +TEST_F(TokenHandleValidatorTest, NoTokenHandles) { + FakeTokenHandleValidator validator; + validator.StartRefreshingTokenHandleValidity(); + + // If there is no associated user then all token handles are valid. + EXPECT_TRUE(validator.IsTokenHandleValidForUser( + GetNewSidString(fake_os_user_manager()))); + EXPECT_EQ(0u, fake_http_url_fetcher_factory()->requests_created()); +} + +TEST_F(TokenHandleValidatorTest, ValidTokenHandle) { + FakeTokenHandleValidator validator; + CComBSTR sid; + ASSERT_EQ(S_OK, fake_os_user_manager()->CreateTestOSUser( + L"username", L"password", L"fullname", L"comment", + L"gaia-id", base::string16(), &sid)); + ASSERT_EQ(S_OK, SetUserProperty(OLE2W(sid), kUserTokenHandle, L"th")); + + validator.StartRefreshingTokenHandleValidity(); + + // Valid token fetch result. + fake_http_url_fetcher_factory()->SetFakeResponse( + GURL(TokenHandleValidator::kTokenInfoUrl), + FakeWinHttpUrlFetcher::Headers(), "{\"expires_in\":1}"); + + EXPECT_TRUE(validator.IsTokenHandleValidForUser(OLE2W(sid))); + EXPECT_EQ(1u, fake_http_url_fetcher_factory()->requests_created()); +} + +TEST_F(TokenHandleValidatorTest, InvalidTokenHandle) { + FakeTokenHandleValidator validator; + CComBSTR sid; + ASSERT_EQ(S_OK, fake_os_user_manager()->CreateTestOSUser( + L"username", L"password", L"fullname", L"comment", + L"gaia-id", base::string16(), &sid)); + ASSERT_EQ(S_OK, SetUserProperty(OLE2W(sid), kUserTokenHandle, L"th")); + + validator.StartRefreshingTokenHandleValidity(); + + // Invalid token fetch result. + fake_http_url_fetcher_factory()->SetFakeResponse( + GURL(TokenHandleValidator::kTokenInfoUrl), + FakeWinHttpUrlFetcher::Headers(), "{}"); + + EXPECT_FALSE(validator.IsTokenHandleValidForUser(OLE2W(sid))); + EXPECT_EQ(1u, fake_http_url_fetcher_factory()->requests_created()); +} + +TEST_F(TokenHandleValidatorTest, InvalidTokenHandleNoInternet) { + FakeTokenHandleValidator validator; + FakeInternetAvailabilityChecker internet_checker( + FakeInternetAvailabilityChecker::kHicForceNo); + + CComBSTR sid; + ASSERT_EQ(S_OK, fake_os_user_manager()->CreateTestOSUser( + L"username", L"password", L"fullname", L"comment", + L"gaia-id", base::string16(), &sid)); + ASSERT_EQ(S_OK, SetUserProperty(OLE2W(sid), kUserTokenHandle, L"th")); + + validator.StartRefreshingTokenHandleValidity(); + EXPECT_TRUE(validator.IsTokenHandleValidForUser(OLE2W(sid))); + EXPECT_EQ(0u, fake_http_url_fetcher_factory()->requests_created()); +} + +TEST_F(TokenHandleValidatorTest, InvalidTokenHandleTimeout) { + FakeTokenHandleValidator validator(base::TimeDelta::FromMilliseconds(50)); + CComBSTR sid; + ASSERT_EQ(S_OK, fake_os_user_manager()->CreateTestOSUser( + L"username", L"password", L"fullname", L"comment", + L"gaia-id", base::string16(), &sid)); + ASSERT_EQ(S_OK, SetUserProperty(OLE2W(sid), kUserTokenHandle, L"th")); + + validator.StartRefreshingTokenHandleValidity(); + + base::WaitableEvent http_fetcher_event; + // Invalid token fetch result. + fake_http_url_fetcher_factory()->SetFakeResponse( + GURL(TokenHandleValidator::kTokenInfoUrl), + FakeWinHttpUrlFetcher::Headers(), "{}", http_fetcher_event.handle()); + + EXPECT_TRUE(validator.IsTokenHandleValidForUser(OLE2W(sid))); + EXPECT_EQ(1u, fake_http_url_fetcher_factory()->requests_created()); + + http_fetcher_event.Signal(); +} + +TEST_F(TokenHandleValidatorTest, TokenHandleValidityStillFresh) { + FakeTokenHandleValidator validator; + + CComBSTR sid; + ASSERT_EQ(S_OK, fake_os_user_manager()->CreateTestOSUser( + L"username", L"password", L"fullname", L"comment", + L"gaia-id", base::string16(), &sid)); + ASSERT_EQ(S_OK, SetUserProperty(OLE2W(sid), kUserTokenHandle, L"th")); + + validator.StartRefreshingTokenHandleValidity(); + + // Valid token fetch result. + fake_http_url_fetcher_factory()->SetFakeResponse( + GURL(TokenHandleValidator::kTokenInfoUrl), + FakeWinHttpUrlFetcher::Headers(), "{\"expires_in\":1}"); + + EXPECT_TRUE(validator.IsTokenHandleValidForUser(OLE2W(sid))); + EXPECT_TRUE(validator.IsTokenHandleValidForUser(OLE2W(sid))); + EXPECT_EQ(1u, fake_http_url_fetcher_factory()->requests_created()); +} + +class TimeClockOverrideValue { + public: + static base::Time NowOverride() { return current_time_; } + static base::Time current_time_; +}; + +base::Time TimeClockOverrideValue::current_time_; + +TEST_F(TokenHandleValidatorTest, ValidTokenHandle_Refresh) { + // Save the current time and then override the time clock to return a fake + // time. + TimeClockOverrideValue::current_time_ = base::Time::Now(); + base::subtle::ScopedTimeClockOverrides time_override( + &TimeClockOverrideValue::NowOverride, nullptr, nullptr); + FakeTokenHandleValidator validator; + + CComBSTR sid; + ASSERT_EQ(S_OK, fake_os_user_manager()->CreateTestOSUser( + L"username", L"password", L"fullname", L"comment", + L"gaia-id", base::string16(), &sid)); + ASSERT_EQ(S_OK, SetUserProperty(OLE2W(sid), kUserTokenHandle, L"th")); + + validator.StartRefreshingTokenHandleValidity(); + + // Valid token fetch result. + fake_http_url_fetcher_factory()->SetFakeResponse( + GURL(TokenHandleValidator::kTokenInfoUrl), + FakeWinHttpUrlFetcher::Headers(), "{\"expires_in\":1}"); + + EXPECT_TRUE(validator.IsTokenHandleValidForUser(OLE2W(sid))); + + // Make the next token fetch result invalid. + fake_http_url_fetcher_factory()->SetFakeResponse( + GURL(TokenHandleValidator::kTokenInfoUrl), + FakeWinHttpUrlFetcher::Headers(), "{}"); + + // If the lifetime of the validity has not expired, even if the token is + // invalid, no new fetch will be performed yet. + EXPECT_TRUE(validator.IsTokenHandleValidForUser(OLE2W(sid))); + EXPECT_EQ(1u, fake_http_url_fetcher_factory()->requests_created()); + + // Advance the time so that a new fetch will be done and retrieve the + // invalid result now. + TimeClockOverrideValue::current_time_ += + TokenHandleValidator::kTokenHandleValidityLifetime + + base::TimeDelta::FromMilliseconds(1); + EXPECT_FALSE(validator.IsTokenHandleValidForUser(OLE2W(sid))); + EXPECT_EQ(2u, fake_http_url_fetcher_factory()->requests_created()); +} + +} // namespace testing + +} // namespace credential_provider
diff --git a/chrome/credential_provider/test/BUILD.gn b/chrome/credential_provider/test/BUILD.gn index cd2c78f..b139b51 100644 --- a/chrome/credential_provider/test/BUILD.gn +++ b/chrome/credential_provider/test/BUILD.gn
@@ -11,6 +11,7 @@ "../gaiacp/gaia_credential_unittests.cc", "../gaiacp/gcp_utils_unittests.cc", "../gaiacp/reauth_credential_unittests.cc", + "../gaiacp/token_handle_validator_unittests.cc", "com_fakes.cc", "com_fakes.h", "fake_gls_run_helper.cc",
diff --git a/chrome/credential_provider/test/com_fakes.cc b/chrome/credential_provider/test/com_fakes.cc index f1f07e92..41ee810 100644 --- a/chrome/credential_provider/test/com_fakes.cc +++ b/chrome/credential_provider/test/com_fakes.cc
@@ -129,19 +129,6 @@ return S_OK; } -HRESULT FakeGaiaCredentialProvider::HasInternetConnection() { - return has_internet_connection_ == kHicForceYes ? S_OK : S_FALSE; -} - -// IGaiaCredentialProviderForTesting ////////////////////////////////////////// - -HRESULT FakeGaiaCredentialProvider::SetHasInternetConnection( - HasInternetConnectionCheckType has_internet_connection) { - DCHECK(has_internet_connection != kHicCheckAlways); - has_internet_connection_ = has_internet_connection; - return S_OK; -} - IMPL_IUNKOWN_NOQI_NOREF(FakeGaiaCredentialProvider); } // namespace credential_provider
diff --git a/chrome/credential_provider/test/com_fakes.h b/chrome/credential_provider/test/com_fakes.h index d6b0b81..7896ce6 100644 --- a/chrome/credential_provider/test/com_fakes.h +++ b/chrome/credential_provider/test/com_fakes.h
@@ -88,8 +88,7 @@ /////////////////////////////////////////////////////////////////////////////// // Fake the GaiaCredentialProvider COM object. -class FakeGaiaCredentialProvider : public IGaiaCredentialProvider, - public IGaiaCredentialProviderForTesting { +class FakeGaiaCredentialProvider : public IGaiaCredentialProvider { public: FakeGaiaCredentialProvider(); virtual ~FakeGaiaCredentialProvider(); @@ -110,18 +109,12 @@ BSTR password, BSTR sid, BOOL fire_credentials_changed) override; - IFACEMETHODIMP HasInternetConnection() override; - - // IGaiaCredentialProviderForTesting - IFACEMETHODIMP SetHasInternetConnection( - HasInternetConnectionCheckType has_internet_connection) override; private: CComBSTR username_; CComBSTR password_; CComBSTR sid_; BOOL credentials_changed_fired_ = FALSE; - HasInternetConnectionCheckType has_internet_connection_ = kHicForceYes; }; } // namespace credential_provider
diff --git a/chrome/credential_provider/test/gcp_fakes.cc b/chrome/credential_provider/test/gcp_fakes.cc index 8caaf3e..a0a4296 100644 --- a/chrome/credential_provider/test/gcp_fakes.cc +++ b/chrome/credential_provider/test/gcp_fakes.cc
@@ -12,13 +12,12 @@ #include <atlcomcli.h> #include <atlconv.h> -#include <utility> - #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/strings/utf_string_conversions.h" +#include "base/synchronization/waitable_event.h" #include "base/win/scoped_handle.h" #include "base/win/scoped_process_information.h" #include "chrome/credential_provider/common/gcp_strings.h" @@ -322,6 +321,10 @@ hr = SetUserProperty(OLE2CW(*sid), kUserId, gaia_id); if (FAILED(hr)) return hr; + + hr = SetUserProperty(OLE2CW(*sid), kUserTokenHandle, L"token_handle"); + if (FAILED(hr)) + return hr; } if (!email.empty()) { @@ -330,10 +333,6 @@ return hr; } - hr = SetUserProperty(OLE2CW(*sid), kUserTokenHandle, L"token_handle"); - if (FAILED(hr)) - return hr; - return S_OK; } @@ -453,4 +452,117 @@ return S_OK; } +/////////////////////////////////////////////////////////////////////////////// + +FakeWinHttpUrlFetcherFactory::Response::Response() {} + +FakeWinHttpUrlFetcherFactory::Response::Response(const Response& rhs) + : headers(rhs.headers), + response(rhs.response), + send_response_event_handle(rhs.send_response_event_handle) {} + +FakeWinHttpUrlFetcherFactory::Response::Response( + const WinHttpUrlFetcher::Headers& new_headers, + const std::string& new_response, + HANDLE new_send_response_event_handle) + : headers(new_headers), + response(new_response), + send_response_event_handle(new_send_response_event_handle) {} + +FakeWinHttpUrlFetcherFactory::Response::~Response() = default; + +FakeWinHttpUrlFetcherFactory::FakeWinHttpUrlFetcherFactory() + : original_creator_(*WinHttpUrlFetcher::GetCreatorFunctionStorage()) { + *WinHttpUrlFetcher::GetCreatorFunctionStorage() = base::BindRepeating( + &FakeWinHttpUrlFetcherFactory::Create, base::Unretained(this)); +} + +FakeWinHttpUrlFetcherFactory::~FakeWinHttpUrlFetcherFactory() { + *WinHttpUrlFetcher::GetCreatorFunctionStorage() = original_creator_; +} + +void FakeWinHttpUrlFetcherFactory::SetFakeResponse( + const GURL& url, + const WinHttpUrlFetcher::Headers& headers, + const std::string& response, + HANDLE send_response_event_handle /*=INVALID_HANDLE_VALUE*/) { + fake_responses_[url] = + Response(headers, response, send_response_event_handle); +} + +std::unique_ptr<WinHttpUrlFetcher> FakeWinHttpUrlFetcherFactory::Create( + const GURL& url) { + if (fake_responses_.count(url) == 0) + return nullptr; + + const Response& response = fake_responses_[url]; + + FakeWinHttpUrlFetcher* fetcher = new FakeWinHttpUrlFetcher(std::move(url)); + fetcher->response_headers_ = response.headers; + fetcher->response_ = response.response; + fetcher->send_response_event_handle_ = response.send_response_event_handle; + ++requests_created_; + + return std::unique_ptr<WinHttpUrlFetcher>(fetcher); +} + +FakeWinHttpUrlFetcher::FakeWinHttpUrlFetcher(const GURL& url) + : WinHttpUrlFetcher() {} + +FakeWinHttpUrlFetcher::~FakeWinHttpUrlFetcher() {} + +bool FakeWinHttpUrlFetcher::IsValid() const { + return true; +} + +HRESULT FakeWinHttpUrlFetcher::Fetch(std::vector<char>* response) { + if (send_response_event_handle_ != INVALID_HANDLE_VALUE) + ::WaitForSingleObject(send_response_event_handle_, INFINITE); + + response->resize(response_.size()); + memcpy(response->data(), response_.c_str(), response->size()); + return S_OK; +} + +HRESULT FakeWinHttpUrlFetcher::Close() { + return S_OK; +} + +/////////////////////////////////////////////////////////////////////////////// + +FakeTokenHandleValidator::FakeTokenHandleValidator() + : TokenHandleValidator( + TokenHandleValidator::kDefaultTokenHandleValidationTimeout), + original_validator_(*GetInstanceStorage()) { + *GetInstanceStorage() = this; +} + +FakeTokenHandleValidator::FakeTokenHandleValidator( + base::TimeDelta validation_timeout) + : TokenHandleValidator(validation_timeout), + original_validator_(*GetInstanceStorage()) { + *GetInstanceStorage() = this; +} + +FakeTokenHandleValidator::~FakeTokenHandleValidator() { + *GetInstanceStorage() = original_validator_; +} + +/////////////////////////////////////////////////////////////////////////////// + +FakeInternetAvailabilityChecker::FakeInternetAvailabilityChecker( + HasInternetConnectionCheckType has_internet_connection /*=kHicForceYes*/) + : original_checker_(*GetInstanceStorage()), + has_internet_connection_(has_internet_connection) { + *GetInstanceStorage() = this; +} + +FakeInternetAvailabilityChecker::~FakeInternetAvailabilityChecker() { + *GetInstanceStorage() = original_checker_; +} + +bool FakeInternetAvailabilityChecker::HasInternetConnection() { + return has_internet_connection_ == kHicForceYes; +} + } // namespace credential_provider
diff --git a/chrome/credential_provider/test/gcp_fakes.h b/chrome/credential_provider/test/gcp_fakes.h index 8eca555..2cb13bb7 100644 --- a/chrome/credential_provider/test/gcp_fakes.h +++ b/chrome/credential_provider/test/gcp_fakes.h
@@ -12,12 +12,18 @@ #include "base/strings/string16.h" #include "base/win/scoped_handle.h" +#include "chrome/credential_provider/gaiacp/internet_availability_checker.h" #include "chrome/credential_provider/gaiacp/os_process_manager.h" #include "chrome/credential_provider/gaiacp/os_user_manager.h" #include "chrome/credential_provider/gaiacp/scoped_lsa_policy.h" #include "chrome/credential_provider/gaiacp/scoped_user_profile.h" +#include "chrome/credential_provider/gaiacp/token_handle_validator.h" #include "chrome/credential_provider/gaiacp/win_http_url_fetcher.h" +namespace base { +class WaitableEvent; +} + namespace credential_provider { /////////////////////////////////////////////////////////////////////////////// @@ -207,6 +213,97 @@ bool is_valid_ = false; }; +/////////////////////////////////////////////////////////////////////////////// + +// A scoped FakeWinHttpUrlFetcher factory. Installs itself when constructed +// and removes itself when deleted. +class FakeWinHttpUrlFetcherFactory { + public: + FakeWinHttpUrlFetcherFactory(); + ~FakeWinHttpUrlFetcherFactory(); + + void SetFakeResponse( + const GURL& url, + const WinHttpUrlFetcher::Headers& headers, + const std::string& response, + HANDLE send_response_event_handle = INVALID_HANDLE_VALUE); + size_t requests_created() const { return requests_created_; } + + private: + std::unique_ptr<WinHttpUrlFetcher> Create(const GURL& url); + + WinHttpUrlFetcher::CreatorCallback original_creator_; + + struct Response { + Response(); + Response(const Response& rhs); + Response(const WinHttpUrlFetcher::Headers& new_headers, + const std::string& new_response, + HANDLE new_send_response_event_handle); + ~Response(); + WinHttpUrlFetcher::Headers headers; + std::string response; + HANDLE send_response_event_handle; + }; + + std::map<GURL, Response> fake_responses_; + size_t requests_created_ = 0; +}; + +class FakeWinHttpUrlFetcher : public WinHttpUrlFetcher { + public: + explicit FakeWinHttpUrlFetcher(const GURL& url); + ~FakeWinHttpUrlFetcher() override; + + using WinHttpUrlFetcher::Headers; + + const Headers& response_headers() const { return response_headers_; } + + // WinHttpUrlFetcher + bool IsValid() const override; + HRESULT Fetch(std::vector<char>* response) override; + HRESULT Close() override; + + private: + friend FakeWinHttpUrlFetcherFactory; + + Headers response_headers_; + std::string response_; + HANDLE send_response_event_handle_; +}; + +/////////////////////////////////////////////////////////////////////////////// + +class FakeTokenHandleValidator : public TokenHandleValidator { + public: + FakeTokenHandleValidator(); + explicit FakeTokenHandleValidator(base::TimeDelta validation_timeout); + ~FakeTokenHandleValidator() override; + + private: + TokenHandleValidator* original_validator_ = nullptr; +}; + +/////////////////////////////////////////////////////////////////////////////// + +class FakeInternetAvailabilityChecker : public InternetAvailabilityChecker { + public: + enum HasInternetConnectionCheckType { kHicForceYes, kHicForceNo }; + + FakeInternetAvailabilityChecker( + HasInternetConnectionCheckType has_internet_connection = kHicForceYes); + ~FakeInternetAvailabilityChecker() override; + + bool HasInternetConnection() override; + + private: + InternetAvailabilityChecker* original_checker_ = nullptr; + + // Used during tests to force the credential provider to believe if an + // internet connection is possible or not. In production the value is + // always set to HIC_CHECK_ALWAYS to perform a real check at runtime. + HasInternetConnectionCheckType has_internet_connection_ = kHicForceYes; +}; } // namespace credential_provider #endif // CHROME_CREDENTIAL_PROVIDER_TEST_GCP_FAKES_H_
diff --git a/chrome/credential_provider/test/gls_runner_test_base.h b/chrome/credential_provider/test/gls_runner_test_base.h index 677dd9b..e474656 100644 --- a/chrome/credential_provider/test/gls_runner_test_base.h +++ b/chrome/credential_provider/test/gls_runner_test_base.h
@@ -34,6 +34,7 @@ FakeScopedUserProfileFactory fake_scoped_user_profile_factory_; registry_util::RegistryOverrideManager registry_override_; FakeGlsRunHelper run_helper_; + FakeInternetAvailabilityChecker internet_checker_; }; } // namespace testing
diff --git a/chrome/install_static/install_util.cc b/chrome/install_static/install_util.cc index df87bd9..7c7b6c5 100644 --- a/chrome/install_static/install_util.cc +++ b/chrome/install_static/install_util.cc
@@ -847,13 +847,15 @@ std::wstring GetSwitchValueFromCommandLine(const std::wstring& command_line, const std::wstring& switch_name) { + static constexpr wchar_t kSwitchTerminator[] = L"--"; assert(!command_line.empty()); assert(!switch_name.empty()); std::vector<std::wstring> as_array = TokenizeCommandLineToArray(command_line); std::wstring switch_with_equal = L"--" + switch_name + L"="; - for (size_t i = 1; i < as_array.size(); ++i) { - const std::wstring& arg = as_array[i]; + auto end = std::find(as_array.cbegin(), as_array.cend(), kSwitchTerminator); + for (auto scan = as_array.cbegin(); scan != end; ++scan) { + const std::wstring& arg = *scan; if (arg.compare(0, switch_with_equal.size(), switch_with_equal) == 0) return arg.substr(switch_with_equal.size()); }
diff --git a/chrome/install_static/install_util.h b/chrome/install_static/install_util.h index d62af72..27a55e3 100644 --- a/chrome/install_static/install_util.h +++ b/chrome/install_static/install_util.h
@@ -275,9 +275,10 @@ std::vector<std::wstring> TokenizeCommandLineToArray( const std::wstring& command_line); -// We assume that the command line |command_line| contains multiple switches -// with the format --<switch name>=<switch value>. This function returns the -// value of the |switch_name| passed in. +// Returns the value of a switch of the form "--<switch name>=<switch value>" in +// |command_line|. An empty switch in |command_line| ("--") denotes the end of +// switches and the beginning of args. Anything of the form --<switch +// name>=<switch value> following "--" is ignored. std::wstring GetSwitchValueFromCommandLine(const std::wstring& command_line, const std::wstring& switch_name);
diff --git a/chrome/install_static/install_util_unittest.cc b/chrome/install_static/install_util_unittest.cc index 355be3e..a057946 100644 --- a/chrome/install_static/install_util_unittest.cc +++ b/chrome/install_static/install_util_unittest.cc
@@ -96,6 +96,10 @@ // Bad command line without closing quotes. Should not crash. value = GetSwitchValueFromCommandLine(L"\"blah --type=\t\t\t", L"type"); EXPECT_TRUE(value.empty()); + + // Anything following "--" should be considered args and therfore ignored. + value = GetSwitchValueFromCommandLine(L"blah -- --type=bleh", L"type"); + EXPECT_TRUE(value.empty()); } TEST(InstallStaticTest, SpacesAndQuotesInCommandLineArguments) {
diff --git a/chrome/renderer/autofill/password_autofill_agent_browsertest.cc b/chrome/renderer/autofill/password_autofill_agent_browsertest.cc index 5da9b611..a289370 100644 --- a/chrome/renderer/autofill/password_autofill_agent_browsertest.cc +++ b/chrome/renderer/autofill/password_autofill_agent_browsertest.cc
@@ -3772,7 +3772,7 @@ password_autofill_agent_->UserGestureObserved(); // It's a way to call PasswordValueGatekeeper::Reset(). - password_autofill_agent_->DidStartProvisionalLoad(nullptr, false); + password_autofill_agent_->ReadyToCommitNavigation(nullptr); fill_data_.username_may_use_prefilled_placeholder = true; fill_data_.password_field.value = ASCIIToUTF16(kBobPassword);
diff --git a/chrome/renderer/chrome_render_frame_observer.cc b/chrome/renderer/chrome_render_frame_observer.cc index c401d6c..73fcbc4 100644 --- a/chrome/renderer/chrome_render_frame_observer.cc +++ b/chrome/renderer/chrome_render_frame_observer.cc
@@ -376,9 +376,8 @@ #endif } -void ChromeRenderFrameObserver::DidStartProvisionalLoad( - WebDocumentLoader* document_loader, - bool is_content_initiated) { +void ChromeRenderFrameObserver::ReadyToCommitNavigation( + WebDocumentLoader* document_loader) { // Let translate_helper do any preparatory work for loading a URL. if (!translate_helper_) return;
diff --git a/chrome/renderer/chrome_render_frame_observer.h b/chrome/renderer/chrome_render_frame_observer.h index 9bab7def..65d080f 100644 --- a/chrome/renderer/chrome_render_frame_observer.h +++ b/chrome/renderer/chrome_render_frame_observer.h
@@ -52,8 +52,8 @@ const std::string& interface_name, mojo::ScopedInterfaceEndpointHandle* handle) override; bool OnMessageReceived(const IPC::Message& message) override; - void DidStartProvisionalLoad(blink::WebDocumentLoader* document_loader, - bool is_content_initiated) override; + void ReadyToCommitNavigation( + blink::WebDocumentLoader* document_loader) override; void DidFinishLoad() override; void DidCreateNewDocument() override; void DidCommitProvisionalLoad(bool is_same_document_navigation,
diff --git a/chrome/renderer/net/net_error_helper.cc b/chrome/renderer/net/net_error_helper.cc index b3b3885..1296ef5 100644 --- a/chrome/renderer/net/net_error_helper.cc +++ b/chrome/renderer/net/net_error_helper.cc
@@ -86,9 +86,7 @@ // suggestions. If it takes too long, just use the local error page. const int kNavigationCorrectionFetchTimeoutSec = 3; -NetErrorHelperCore::PageType GetLoadingPageType( - blink::WebDocumentLoader* document_loader) { - GURL url = document_loader->GetUrl(); +NetErrorHelperCore::PageType GetLoadingPageType(const GURL& url) { if (!url.is_valid() || url.spec() != kUnreachableWebDataURL) return NetErrorHelperCore::NON_ERROR_PAGE; return NetErrorHelperCore::ERROR_PAGE; @@ -308,11 +306,10 @@ supervised_user_interface_->Feedback(); } -void NetErrorHelper::DidStartProvisionalLoad( - blink::WebDocumentLoader* document_loader, - bool is_content_initiated) { - core_->OnStartLoad(GetFrameType(render_frame()), - GetLoadingPageType(document_loader)); +void NetErrorHelper::DidStartNavigation( + const GURL& url, + base::Optional<blink::WebNavigationType> navigation_type) { + core_->OnStartLoad(GetFrameType(render_frame()), GetLoadingPageType(url)); } void NetErrorHelper::DidCommitProvisionalLoad(bool is_same_document_navigation,
diff --git a/chrome/renderer/net/net_error_helper.h b/chrome/renderer/net/net_error_helper.h index 472440ee..cf104cf8 100644 --- a/chrome/renderer/net/net_error_helper.h +++ b/chrome/renderer/net/net_error_helper.h
@@ -85,8 +85,9 @@ void Feedback() override; // RenderFrameObserver implementation. - void DidStartProvisionalLoad(blink::WebDocumentLoader* loader, - bool is_content_initiated) override; + void DidStartNavigation( + const GURL& url, + base::Optional<blink::WebNavigationType> navigation_type) override; void DidCommitProvisionalLoad(bool is_same_document_navigation, ui::PageTransition transition) override; void DidFinishLoad() override;
diff --git a/chrome/renderer/page_load_metrics/metrics_render_frame_observer.cc b/chrome/renderer/page_load_metrics/metrics_render_frame_observer.cc index 0239e2f..c96eed3 100644 --- a/chrome/renderer/page_load_metrics/metrics_render_frame_observer.cc +++ b/chrome/renderer/page_load_metrics/metrics_render_frame_observer.cc
@@ -160,10 +160,9 @@ page_timing_metrics_sender_.reset(); } -void MetricsRenderFrameObserver::DidStartProvisionalLoad( - blink::WebDocumentLoader* document_loader, - bool is_content_initiated) { - // Create a new data use tracker for the new provisional load. +void MetricsRenderFrameObserver::ReadyToCommitNavigation( + blink::WebDocumentLoader* document_loader) { + // Create a new data use tracker for the new document load. provisional_frame_resource_data_use_ = std::make_unique<PageResourceDataUse>(); provisional_frame_resource_id = 0;
diff --git a/chrome/renderer/page_load_metrics/metrics_render_frame_observer.h b/chrome/renderer/page_load_metrics/metrics_render_frame_observer.h index 43915ad..ee5545f 100644 --- a/chrome/renderer/page_load_metrics/metrics_render_frame_observer.h +++ b/chrome/renderer/page_load_metrics/metrics_render_frame_observer.h
@@ -57,8 +57,8 @@ int request_id, const network::URLLoaderCompletionStatus& status) override; void DidCancelResponse(int request_id) override; - void DidStartProvisionalLoad(blink::WebDocumentLoader* document_loader, - bool is_content_initiated) override; + void ReadyToCommitNavigation( + blink::WebDocumentLoader* document_loader) override; void DidFailProvisionalLoad(const blink::WebURLError& error) override; void DidCommitProvisionalLoad(bool is_same_document_navigation, ui::PageTransition transition) override;
diff --git a/chrome/renderer/page_load_metrics/metrics_render_frame_observer_unittest.cc b/chrome/renderer/page_load_metrics/metrics_render_frame_observer_unittest.cc index 3ba040ac..42855d67 100644 --- a/chrome/renderer/page_load_metrics/metrics_render_frame_observer_unittest.cc +++ b/chrome/renderer/page_load_metrics/metrics_render_frame_observer_unittest.cc
@@ -14,6 +14,7 @@ #include "chrome/common/page_load_metrics/test/weak_mock_timer.h" #include "chrome/renderer/page_load_metrics/fake_page_timing_sender.h" #include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" namespace page_load_metrics { @@ -81,7 +82,8 @@ page_load_metrics::InitPageLoadTimingForTest(&timing); timing.navigation_start = nav_start; observer.ExpectPageLoadTiming(timing); - observer.DidStartProvisionalLoad(nullptr, true); + observer.DidStartNavigation(GURL(), base::nullopt); + observer.ReadyToCommitNavigation(nullptr); observer.DidCommitProvisionalLoad(false, ui::PAGE_TRANSITION_LINK); observer.GetMockTimer()->Fire(); @@ -104,7 +106,8 @@ page_load_metrics::InitPageLoadTimingForTest(&timing); timing.navigation_start = nav_start; observer.ExpectPageLoadTiming(timing); - observer.DidStartProvisionalLoad(nullptr, true); + observer.DidStartNavigation(GURL(), base::nullopt); + observer.ReadyToCommitNavigation(nullptr); observer.DidCommitProvisionalLoad(false, ui::PAGE_TRANSITION_LINK); observer.GetMockTimer()->Fire(); @@ -151,7 +154,8 @@ page_load_metrics::InitPageLoadTimingForTest(&timing); timing.navigation_start = nav_start; observer.ExpectPageLoadTiming(timing); - observer.DidStartProvisionalLoad(nullptr, true); + observer.DidStartNavigation(GURL(), base::nullopt); + observer.ReadyToCommitNavigation(nullptr); observer.DidCommitProvisionalLoad(false, ui::PAGE_TRANSITION_LINK); observer.GetMockTimer()->Fire(); @@ -178,7 +182,8 @@ observer.SetMockTimer(nullptr); observer.ExpectPageLoadTiming(timing_2); - observer.DidStartProvisionalLoad(nullptr, true); + observer.DidStartNavigation(GURL(), base::nullopt); + observer.ReadyToCommitNavigation(nullptr); observer.DidCommitProvisionalLoad(false, ui::PAGE_TRANSITION_LINK); observer.GetMockTimer()->Fire();
diff --git a/chrome/services/file_util/public/mojom/safe_archive_analyzer_param_traits.h b/chrome/services/file_util/public/mojom/safe_archive_analyzer_param_traits.h index a0b7080..a297d76 100644 --- a/chrome/services/file_util/public/mojom/safe_archive_analyzer_param_traits.h +++ b/chrome/services/file_util/public/mojom/safe_archive_analyzer_param_traits.h
@@ -3,6 +3,8 @@ // found in the LICENSE file. // Multiply-included param traits file, so no include guard. +// Disabling the presubmit warning with: +// no-include-guard-because-multiply-included #if !defined(FULL_SAFE_BROWSING) #error FULL_SAFE_BROWSING should be defined. @@ -103,4 +105,6 @@ IPC_STRUCT_TRAITS_MEMBER(signature_blob) IPC_STRUCT_TRAITS_MEMBER(detached_code_signatures) #endif // OS_MACOSX + IPC_STRUCT_TRAITS_MEMBER(file_count) + IPC_STRUCT_TRAITS_MEMBER(directory_count) IPC_STRUCT_TRAITS_END()
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index a7e5d6cc..e34d19b 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -783,6 +783,7 @@ "../browser/page_load_metrics/observers/live_tab_count_page_load_metrics_observer_browsertest.cc", "../browser/page_load_metrics/observers/multi_tab_loading_page_load_metrics_observer_browsertest.cc", "../browser/page_load_metrics/observers/security_state_page_load_metrics_observer_browsertest.cc", + "../browser/page_load_metrics/observers/signed_exchange_page_load_metrics_browsertest.cc", "../browser/page_load_metrics/page_load_metrics_browsertest.cc", "../browser/page_load_metrics/page_load_metrics_test_waiter.cc", "../browser/page_load_metrics/page_load_metrics_test_waiter.h", @@ -1716,7 +1717,9 @@ "../browser/chromeos/accessibility/select_to_speak_browsertest.cc", "../browser/chromeos/accessibility/speech_monitor.cc", "../browser/chromeos/accessibility/speech_monitor.h", + "../browser/chromeos/accessibility/spoken_feedback_app_list_browsertest.cc", "../browser/chromeos/accessibility/spoken_feedback_browsertest.cc", + "../browser/chromeos/accessibility/spoken_feedback_browsertest.h", "../browser/chromeos/accessibility/sticky_keys_browsertest.cc", "../browser/chromeos/accessibility/switch_access_browsertest.cc", "../browser/chromeos/accessibility/touch_exploration_controller_browsertest.cc", @@ -1862,6 +1865,8 @@ "../browser/chromeos/login/session_login_browsertest.cc", "../browser/chromeos/login/signin/device_id_browsertest.cc", "../browser/chromeos/login/signin/oauth2_browsertest.cc", + "../browser/chromeos/login/test/enrollment_helper_mixin.cc", + "../browser/chromeos/login/test/enrollment_helper_mixin.h", "../browser/chromeos/login/test/hid_controller_mixin.cc", "../browser/chromeos/login/test/hid_controller_mixin.h", "../browser/chromeos/login/test/https_forwarder.cc", @@ -2748,7 +2753,7 @@ "../browser/performance_manager/observers/working_set_trimmer_win_unittest.cc", "../browser/performance_manager/performance_manager_unittest.cc", "../browser/performance_manager/webui_graph_dump_impl_unittest.cc", - "../browser/performance_monitor/system_monitor_helper_win_unittest.cc", + "../browser/performance_monitor/metric_evaluator_helper_win_unittest.cc", "../browser/performance_monitor/system_monitor_unittest.cc", "../browser/permissions/chooser_context_base_mock_permission_observer.cc", "../browser/permissions/chooser_context_base_mock_permission_observer.h", @@ -2775,7 +2780,6 @@ "../browser/policy/javascript_policy_handler_unittest.cc", "../browser/policy/managed_bookmarks_policy_handler_unittest.cc", "../browser/policy/profile_policy_connector_unittest.cc", - "../browser/policy/webusb_allow_devices_for_urls_policy_handler_unittest.cc", "../browser/predictors/autocomplete_action_predictor_table_unittest.cc", "../browser/predictors/autocomplete_action_predictor_unittest.cc", "../browser/predictors/loading_data_collector_unittest.cc", @@ -3320,6 +3324,11 @@ "../browser/notifications/notification_ui_manager_unittest.cc", "../browser/platform_util_unittest.cc", "../browser/policy/policy_path_parser_unittest.cc", + + # The WebUsbAllowDevicesForUrls policy is not yet supported on Android. + # TODO(https://crbug.com/931459): Move this up to the main "sources" + # property once the policy is supported. + "../browser/policy/webusb_allow_devices_for_urls_policy_handler_unittest.cc", "../browser/profile_resetter/profile_resetter_unittest.cc", "../browser/profile_resetter/reset_report_uploader_unittest.cc", "../browser/profile_resetter/triggered_profile_resetter_win_unittest.cc", @@ -5755,6 +5764,15 @@ "//chrome/test/data/autofill/captured_sites/", ] + if (is_linux || is_win) { + data += [ + "$root_out_dir/chrome_100_percent.pak", + "$root_out_dir/chrome_200_percent.pak", + "$root_out_dir/locales/en-US.pak", + "$root_out_dir/resources.pak", + ] + } + defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] ldflags = []
diff --git a/chrome/test/chromedriver/test/run_all_tests.py b/chrome/test/chromedriver/test/run_all_tests.py index 2a96cdc..cca595e 100755 --- a/chrome/test/chromedriver/test/run_all_tests.py +++ b/chrome/test/chromedriver/test/run_all_tests.py
@@ -27,7 +27,6 @@ def _GenerateTestCommand(script, chromedriver, - ref_chromedriver=None, chrome=None, android_package=None, verbose=False): @@ -39,8 +38,6 @@ '--chromedriver=%s' % chromedriver, '--log-path=%s' % log_path, ] - if ref_chromedriver: - cmd.append('--reference-chromedriver=' + ref_chromedriver) if chrome: cmd.append('--chrome=' + chrome) @@ -73,14 +70,13 @@ return code -def RunPythonTests(chromedriver, ref_chromedriver, +def RunPythonTests(chromedriver, chrome=None, android_package=None): util.MarkBuildStepStart('python_tests') code = util.RunCommand( _GenerateTestCommand('run_py_tests.py', chromedriver, - ref_chromedriver=ref_chromedriver, chrome=chrome, android_package=android_package)) if code: @@ -95,7 +91,6 @@ code = util.RunCommand( _GenerateTestCommand('run_java_tests.py', chromedriver, - ref_chromedriver=None, chrome=chrome, android_package=android_package, verbose=verbose)) @@ -168,11 +163,6 @@ platform_name = util.GetPlatformName() if util.IsLinux() and util.Is64Bit(): platform_name += '64' - ref_chromedriver = os.path.join( - chrome_paths.GetSrc(), - 'chrome', 'test', 'chromedriver', 'third_party', 'java_tests', - 'reference_builds', - 'chromedriver_%s%s' % (platform_name, exe_postfix)) if options.android_packages: os.environ['PATH'] += os.pathsep + os.path.join( @@ -180,7 +170,6 @@ code = 0 for package in options.android_packages.split(','): code1 = RunPythonTests(chromedriver, - ref_chromedriver, chrome_version_name=package, android_package=package) code2 = RunJavaTests(chromedriver, @@ -198,7 +187,6 @@ if not chrome_path: code = 1 code1 = RunPythonTests(chromedriver, - ref_chromedriver, chrome=chrome_path) code2 = RunJavaTests(chromedriver, verbose=True,
diff --git a/chrome/test/chromedriver/test/run_py_tests.py b/chrome/test/chromedriver/test/run_py_tests.py index 549c398..a488bed 100755 --- a/chrome/test/chromedriver/test/run_py_tests.py +++ b/chrome/test/chromedriver/test/run_py_tests.py
@@ -3091,42 +3091,29 @@ class PerfTest(ChromeDriverBaseTest): """Tests for ChromeDriver perf.""" - def setUp(self): - self.assertTrue(_REFERENCE_CHROMEDRIVER is not None, - 'must supply a reference-chromedriver arg') def _RunDriverPerfTest(self, name, test_func): - """Runs a perf test comparing a reference and new ChromeDriver server. + """Runs a perf test ChromeDriver server. Args: name: The name of the perf test. test_func: Called with the server url to perform the test action. Must return the time elapsed. """ - class Results(object): - ref = [] - new = [] + result = [] - ref_server = server.Server(_REFERENCE_CHROMEDRIVER) - results = Results() - result_url_pairs = zip([results.new, results.ref], - [_CHROMEDRIVER_SERVER_URL, ref_server.GetUrl()]) for iteration in range(10): - for result, url in result_url_pairs: - result += [test_func(url)] - # Reverse the order for the next run. - result_url_pairs = result_url_pairs[::-1] + result += [test_func(_CHROMEDRIVER_SERVER_URL)] - def PrintResult(build, result): + def PrintResult(result): mean = sum(result) / len(result) avg_dev = sum([abs(sample - mean) for sample in result]) / len(result) - print 'perf result', build, name, mean, avg_dev, result - util.AddBuildStepText('%s %s: %.3f+-%.3f' % ( - build, name, mean, avg_dev)) + print 'perf result', name, mean, avg_dev, result + util.AddBuildStepText('%s: %.3f+-%.3f' % ( + name, mean, avg_dev)) # Discard first result, which may be off due to cold start. - PrintResult('new', results.new[1:]) - PrintResult('ref', results.ref[1:]) + PrintResult(result[1:]) def testSessionStartTime(self): def Run(url): @@ -3248,9 +3235,6 @@ help="Don't truncate long strings in the log so that the log can be " "replayed.") parser.add_option( - '', '--reference-chromedriver', - help='Path to the reference chromedriver server') - parser.add_option( '', '--chrome', help='Path to a build of the chrome binary') parser.add_option( '', '--filter', type='string', default='', @@ -3298,9 +3282,6 @@ global _CHROMEDRIVER_SERVER_URL _CHROMEDRIVER_SERVER_URL = chromedriver_server.GetUrl() - global _REFERENCE_CHROMEDRIVER - _REFERENCE_CHROMEDRIVER = util.GetAbsolutePathOfUserPath( - options.reference_chromedriver) global _CHROME_BINARY if options.chrome:
diff --git a/chrome/test/data/extensions/api_test/permissions/file_access_no/background.js b/chrome/test/data/extensions/api_test/permissions/file_access_no/background.js index bc54ecb..1cfc4fe6 100644 --- a/chrome/test/data/extensions/api_test/permissions/file_access_no/background.js +++ b/chrome/test/data/extensions/api_test/permissions/file_access_no/background.js
@@ -5,7 +5,7 @@ var callbackFail = chrome.test.callbackFail; var callbackPass = chrome.test.callbackPass; var expectedError = - "Invalid value for origin pattern file:///*: Invalid scheme."; + "Extension must have file access enabled to request 'file:///*'."; function test() { chrome.permissions.request({"origins": ["file:///*"]},
diff --git a/chrome/test/data/extensions/api_test/webrequest/auth_parallel/index.html b/chrome/test/data/extensions/api_test/webrequest/auth_parallel/index.html new file mode 100644 index 0000000..6dbde8f --- /dev/null +++ b/chrome/test/data/extensions/api_test/webrequest/auth_parallel/index.html
@@ -0,0 +1,15 @@ +<html> +<body> +<script> + const params = new URLSearchParams(location.search); + + const img1 = new Image(); + img1.src = params.get('img1'); + document.body.appendChild(img1); + + const img2 = new Image(); + img2.src = params.get('img2'); + document.body.appendChild(img2); +</script> +</body> +</html>
diff --git a/chrome/test/data/extensions/api_test/webrequest/framework.js b/chrome/test/data/extensions/api_test/webrequest/framework.js index 17e8804..2bad3eab 100644 --- a/chrome/test/data/extensions/api_test/webrequest/framework.js +++ b/chrome/test/data/extensions/api_test/webrequest/framework.js
@@ -10,6 +10,7 @@ var expectedEventOrder; var networkServiceState = "unknown"; var tabId; +var tabIsIncognito; var tabIdMap; var frameIdMap; var testWebSocketPort; @@ -50,6 +51,7 @@ tabId = tab.id; tabIdMap = {"-1": -1}; tabIdMap[tabId] = 0; + tabIsIncognito = tab.incognito; chrome.test.getConfig(function(config) { testServerPort = config.testServer.port; testWebSocketPort = config.testWebSocketPort; @@ -132,11 +134,36 @@ chrome.tabs.update(tabId, {url: url}); } +function deepCopy(obj) { + if (obj === null) + return null; + if (typeof(obj) != 'object') + return obj; + if (Array.isArray(obj)) { + var tmp_array = new Array; + for (var i = 0; i < obj.length; i++) { + tmp_array.push(deepCopy(obj[i])); + } + return tmp_array; + } + + var tmp_object = {} + for (var p in obj) { + tmp_object[p] = deepCopy(obj[p]); + } + return tmp_object; +} + // data: array of expected events, each one is a dictionary: // { label: "<unique identifier>", // event: "<webrequest event type>", // details: { <expected details of the webrequest event> }, // retval: { <dictionary that the event handler shall return> } (optional) +// retval_function: <function to run when the event occurs, this overrides +// any retval handling. The function takes +// (name, details, optional callback). The value it +// returns is returned out of the event +// handler> (optional) // } // order: an array of sequences, e.g. [ ["a", "b", "c"], ["d", "e"] ] means that // event with label "a" needs to occur before event with label "b". The @@ -288,17 +315,7 @@ return; } - // Pull the extra per-event options out of the expected data. These let - // us specify special return values per event. - var currentIndex = capturedEventData.length; - var extraOptions; - var retval; - if (expectedEventData.length > currentIndex) { - retval = - expectedEventData[currentIndex].retval_function ? - expectedEventData[currentIndex].retval_function(name, details) : - expectedEventData[currentIndex].retval; - } + var originalDetails = deepCopy(details); // Check that the frameId can be used to reliably determine the URL of the // frame that caused requests. @@ -356,41 +373,51 @@ } }); - // find |details| in expectedEventData - var found = false; - var label = undefined; + // find |details| in matchingExpectedEventData + var matchingExpectedEvent = undefined; expectedEventData.forEach(function (exp) { if (deepEq(exp.event, name) && deepEq(exp.details, details)) { - if (found) { + if (matchingExpectedEvent) { chrome.test.fail("Duplicated expectation entry '" + exp.label + "' should be identified by |eventCount|: " + JSON.stringify(details)); } else { - found = true; - label = exp.label; + matchingExpectedEvent = exp; } } }); - if (!found && !ignoreUnexpected) { + if (!matchingExpectedEvent && !ignoreUnexpected) { console.log("Expected events: " + JSON.stringify(expectedEventData, null, 2)); chrome.test.fail("Received unexpected event '" + name + "':" + JSON.stringify(details, null, 2)); } - if (found) { + var retval; + var retval_function; + if (matchingExpectedEvent) { if (logAllRequests) { console.log("Expected: " + name + ": " + JSON.stringify(details)); } - capturedEventData.push({label: label, event: name, details: details}); + capturedEventData.push( + {label: matchingExpectedEvent.label, event: name, details: details}); // checkExpecations decrements the counter of pending events. We may only // call it if an expected event has occurred. checkExpectations(); + + // Pull the extra per-event options out of the expected data. These let us + // specify special return values per event. + retval = matchingExpectedEvent.retval; + retval_function = matchingExpectedEvent.retval_function; } else { if (logAllRequests) { - console.log("NOT Expected: " + name + ": " + JSON.stringify(details)); + console.log('NOT Expected: ' + name + ': ' + JSON.stringify(details)); } - capturedUnexpectedData.push({label: label, event: name, details: details}); + capturedUnexpectedData.push({event: name, details: details}); + } + + if (retval_function) { + return retval_function(name, originalDetails, callback); } if (callback) {
diff --git a/chrome/test/data/extensions/api_test/webrequest/test_auth_required.js b/chrome/test/data/extensions/api_test/webrequest/test_auth_required.js index 6b6c5ac..7a26f78 100644 --- a/chrome/test/data/extensions/api_test/webrequest/test_auth_required.js +++ b/chrome/test/data/extensions/api_test/webrequest/test_auth_required.js
@@ -5,8 +5,9 @@ // Generates a unique authentication URL so each test can run // without hitting the HTTP authentication cache. Each test // must use a unique realm, however. -function getURLAuthRequired(realm) { - return getServerURL('auth-basic/' + realm + '/subpath?realm=' + realm); +function getURLAuthRequired(realm, subpath = 'subpath') { + return getServerURL( + 'auth-basic/' + realm + '/' + subpath + '?realm=' + realm); } runTests([ @@ -585,4 +586,255 @@ ["responseHeaders", "asyncBlocking"]); navigateAndWait(url); }, + + // Test that two parallel onAuthRequired signals do not interfere with each + // other. This is a regression test for https://crbug.com/931479. + function authRequiredParallel() { + const realm = 'parallelasync'; + + const imgUrl1 = getURLAuthRequired(realm, '1'); + const imgUrl2 = getURLAuthRequired(realm, '2'); + // TODO(https://crbug.com/934398): We incorrectly filter out the initiator + // for requests from incognito contexts for split mode extensions. + const initiator = + tabIsIncognito ? undefined : getServerDomain(initiators.WEB_INITIATED); + const parallelAuthRequestsUrl = getServerURL( + 'extensions/api_test/webrequest/auth_parallel?img1=' + + encodeURIComponent(imgUrl1) + '&img2=' + encodeURIComponent(imgUrl2)); + + function createExternallyResolvablePromise() { + let _resolve; + const promise = new Promise((resolve, reject) => _resolve = resolve); + promise.resolve = _resolve; + return promise; + } + + // Create some promises that will resolved to callbacks when onAuthRequired + // and onComplete fire. + const authRequired1 = createExternallyResolvablePromise(); + const completed1 = createExternallyResolvablePromise(); + const authRequired2 = createExternallyResolvablePromise(); + + // responseStarted2 is whether the request for |imgUrl2| has signalled + // |onResponseStarted| yet. + let responseStarted2 = false; + + expect( + [ // events + { label: 'onBeforeRequest-1', + event: 'onBeforeRequest', + details: { + url: imgUrl1, + type: 'image', + initiator: initiator, + // The testing framework cannot recover the frame URL because the + // URL filter below does not capture the top-level request. + frameUrl: 'unknown frame URL', + }, + }, + { label: 'onBeforeSendHeaders-1', + event: 'onBeforeSendHeaders', + details: { + url: imgUrl1, + type: 'image', + initiator: initiator, + // Note: no requestHeaders because we don't ask for them. + }, + retval: {} + }, + { label: 'onSendHeaders-1', + event: 'onSendHeaders', + details: { + url: imgUrl1, + type: 'image', + initiator: initiator, + } + }, + { label: 'onHeadersReceived-1', + event: 'onHeadersReceived', + details: { + url: imgUrl1, + type: 'image', + initiator: initiator, + responseHeadersExist: true, + statusLine: 'HTTP/1.1 401 Unauthorized', + statusCode: 401, + } + }, + { label: 'onAuthRequired-1', + event: 'onAuthRequired', + details: { + url: imgUrl1, + type: 'image', + initiator: initiator, + isProxy: false, + scheme: 'basic', + realm: realm, + challenger: {host: testServer, port: testServerPort}, + responseHeadersExist: true, + statusLine: 'HTTP/1.1 401 Unauthorized', + statusCode: 401, + }, + retval_function: + (name, details, callback) => authRequired1.resolve(callback), + }, + { label: 'onResponseStarted-1', + event: 'onResponseStarted', + details: { + url: imgUrl1, + type: 'image', + initiator: initiator, + fromCache: false, + statusCode: 200, + ip: '127.0.0.1', + responseHeadersExist: true, + statusLine: 'HTTP/1.1 200 OK', + } + }, + { label: 'onCompleted-1', + event: 'onCompleted', + details: { + url: imgUrl1, + type: 'image', + initiator: initiator, + fromCache: false, + statusCode: 200, + ip: '127.0.0.1', + responseHeadersExist: true, + statusLine: 'HTTP/1.1 200 OK', + }, + retval_function: (name, details) => completed1.resolve(), + }, + { label: 'onBeforeRequest-2', + event: 'onBeforeRequest', + details: { + url: imgUrl2, + type: 'image', + initiator: initiator, + // The testing framework cannot recover the frame URL because the + // URL filter below does not capture the top-level request. + frameUrl: 'unknown frame URL', + }, + }, + { label: 'onBeforeSendHeaders-2', + event: 'onBeforeSendHeaders', + details: { + url: imgUrl2, + type: 'image', + initiator: initiator, + // Note: no requestHeaders because we don't ask for them. + }, + retval: {} + }, + { label: 'onSendHeaders-2', + event: 'onSendHeaders', + details: { + url: imgUrl2, + type: 'image', + initiator: initiator, + } + }, + { label: 'onHeadersReceived-2', + event: 'onHeadersReceived', + details: { + url: imgUrl2, + type: 'image', + initiator: initiator, + responseHeadersExist: true, + statusLine: 'HTTP/1.1 401 Unauthorized', + statusCode: 401, + } + }, + { label: 'onAuthRequired-2', + event: 'onAuthRequired', + details: { + url: imgUrl2, + type: 'image', + initiator: initiator, + isProxy: false, + scheme: 'basic', + realm: realm, + challenger: {host: testServer, port: testServerPort}, + responseHeadersExist: true, + statusLine: 'HTTP/1.1 401 Unauthorized', + statusCode: 401, + }, + retval_function: + (name, details, callback) => authRequired2.resolve(callback), + }, + { label: 'onResponseStarted-2', + event: 'onResponseStarted', + details: { + url: imgUrl2, + type: 'image', + initiator: initiator, + fromCache: false, + statusCode: 401, + ip: '127.0.0.1', + responseHeadersExist: true, + statusLine: 'HTTP/1.1 401 Unauthorized', + }, + retval_function: (name, details) => responseStarted2 = true, + }, + { label: 'onCompleted-2', + event: 'onCompleted', + details: { + url: imgUrl2, + type: 'image', + initiator: initiator, + fromCache: false, + statusCode: 401, + ip: '127.0.0.1', + responseHeadersExist: true, + statusLine: 'HTTP/1.1 401 Unauthorized', + } + }, + ], + [ // event order + ['onBeforeRequest-1', 'onBeforeSendHeaders-1', 'onSendHeaders-1', + 'onHeadersReceived-1', 'onAuthRequired-1', 'onResponseStarted-1', + 'onCompleted-1'], + ['onBeforeRequest-2', 'onBeforeSendHeaders-2', 'onSendHeaders-2', + 'onHeadersReceived-2', 'onAuthRequired-2', 'onResponseStarted-2', + 'onCompleted-2'] + ], + // Only pay attention to |imgUrl1| and |imgUrl2|, not + // |parallelAuthRequestsUrl|. + {urls: ['<all_urls>'], types: ['image']}, + ['responseHeaders', 'asyncBlocking']); + + navigateAndWait(parallelAuthRequestsUrl); + (async function() { + // Wait for onAuthRequired to be signaled for both requests before doing + // anything. + const callback1 = await authRequired1; + const callback2 = await authRequired2; + + // Resolve the first request and let it complete. + callback1({authCredentials: {username: 'foo', password: 'secret'}}); + await completed1; + + // We wish to test that this did not resolve |callback2| with the same + // credentials internally. This would cause |imgUrl2| to signal + // |onResponseStarted| and |onCompleted| though it should be blocked. + chrome.test.assertFalse(responseStarted2); + + // However it's possible that the second request may be much slower than + // the first, causing the above check to pass even if we don't correctly + // isolate the two authentication requests. + // + // Per the webRequest documentation, |onBeforeSendHeaders| should be + // signaled after a resolved |onAuthRequired|. This happens without a + // network delay, so it would make a fairly reliable test. However, + // webRequest does not match the documentation and does not signal it. See + // https://crbug.com/809761. + // + // Instead, resolve the second request, this time canceling the + // authentication request. This should result in |imgUrl2| completing with + // a 401 response. If the credentials were incorrectly propagated from + // |imgUrl1|, this will be ignored and |imgUrl2| will complete with a 200 + // response. + callback2({cancel: true}); + })(); + }, ]);
diff --git a/chrome/test/data/pdf/annotations_feature_disabled_test.js b/chrome/test/data/pdf/annotations_feature_disabled_test.js index f96531f..82851ed 100644 --- a/chrome/test/data/pdf/annotations_feature_disabled_test.js +++ b/chrome/test/data/pdf/annotations_feature_disabled_test.js
@@ -5,8 +5,11 @@ chrome.test.runTests([ function testAnnotationsDisabled() { const toolbar = document.body.querySelector('#toolbar'); - chrome.test.assertFalse(toolbar.pdfAnnotationsEnabled); - chrome.test.assertEq(null, toolbar.shadowRoot.querySelector('#annotate')); + if (toolbar.pdfAnnotationsEnabled) { + chrome.test.assertTrue(!!toolbar.shadowRoot.querySelector('#annotate')); + } else { + chrome.test.assertFalse(!!toolbar.shadowRoot.querySelector('#annotate')); + } chrome.test.succeed(); }, ]);
diff --git a/chrome/test/data/pdf/basic_test.js b/chrome/test/data/pdf/basic_test.js index 99dd1a0..3a46c8f 100644 --- a/chrome/test/data/pdf/basic_test.js +++ b/chrome/test/data/pdf/basic_test.js
@@ -45,7 +45,7 @@ chrome.test.assertTrue(shouldIgnoreKeyEvents(toolbar)); // Test case where the active element has a shadow root of its own. - toolbar.$.buttons.children[1].focus(); + toolbar.$['rotate-right'].focus(); chrome.test.assertFalse(shouldIgnoreKeyEvents(toolbar)); chrome.test.assertFalse(
diff --git a/chrome/test/data/policy/policy_test_cases.json b/chrome/test/data/policy/policy_test_cases.json index a208dbe..a38fcd87 100644 --- a/chrome/test/data/policy/policy_test_cases.json +++ b/chrome/test/data/policy/policy_test_cases.json
@@ -4227,6 +4227,12 @@ "pref_mappings": [{ "pref": "certificate_management_allowed" }] }, + "VoiceInteractionContextEnabled": { + "os": ["chromeos"], + "test_policy": { "VoiceInteractionContextEnabled": true }, + "pref_mappings": [{ "pref": "settings.voice_interaction.context.enabled" }] + }, + "DeviceRebootOnUserSignout": { "os": ["chromeos"], "test_policy": {
diff --git a/chrome/test/data/webui/app_management/app_test.js b/chrome/test/data/webui/app_management/app_test.js index 057689d..22fa5e6 100644 --- a/chrome/test/data/webui/app_management/app_test.js +++ b/chrome/test/data/webui/app_management/app_test.js
@@ -9,7 +9,7 @@ setup(function() { app = document.createElement('app-management-app'); - document.body.appendChild(app); + replaceBody(app); }); test('loads', async function() {
diff --git a/chrome/test/data/webui/cr_components/managed_footnote_test.js b/chrome/test/data/webui/cr_components/managed_footnote_test.js index 3a20334..d586aa9b 100644 --- a/chrome/test/data/webui/cr_components/managed_footnote_test.js +++ b/chrome/test/data/webui/cr_components/managed_footnote_test.js
@@ -42,19 +42,6 @@ assertTrue(footnote.shadowRoot.textContent.includes(message)); }); - test('Substitutes URL', function() { - const message = - 'Your <a target="_blank" href="$1">browser is managed</a> by your ' + - 'organization'; - const targetMessage = 'Your browser is managed by your organization'; - const supportUrl = 'https://support.google.com/chromebook/answer/1331549'; - - const footnote = setupTestElement(true, message); - assertTrue(footnote.shadowRoot.textContent.includes(targetMessage)); - // The <a> element should have the right link. - assertEquals(supportUrl, footnote.$$('a').href); - }); - test('Responds to is-managed-changed events', function() { const footnote = setupTestElement(false, ''); assertEquals('none', getComputedStyle(footnote).display);
diff --git a/chrome/test/data/webui/extensions/activity_log_item_test.js b/chrome/test/data/webui/extensions/activity_log_history_item_test.js similarity index 73% rename from chrome/test/data/webui/extensions/activity_log_item_test.js rename to chrome/test/data/webui/extensions/activity_log_history_item_test.js index 152c200..505e4fd 100644 --- a/chrome/test/data/webui/extensions/activity_log_item_test.js +++ b/chrome/test/data/webui/extensions/activity_log_history_item_test.js
@@ -2,17 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/** @fileoverview Suite of tests for activity-log-item. */ -suite('ExtensionsActivityLogItemTest', function() { +/** @fileoverview Suite of tests for activity-log-history-item. */ +suite('ExtensionsActivityLogHistoryItemTest', function() { /** - * Extension activityLogItem created before each test. - * @type {extensions.ActivityLogItem} + * Extension activityLogHistoryItem created before each test. + * @type {extensions.ActivityLogHistoryItem} */ - let activityLogItem; + let activityLogHistoryItem; let testVisible; /** - * ActivityGroup data for the activityLogItem + * ActivityGroup data for the activityLogHistoryItem * @type {extensions.ActivityGroup} */ let testActivityGroup; @@ -28,15 +28,16 @@ countsByUrl: new Map() }; - activityLogItem = new extensions.ActivityLogItem(); - activityLogItem.data = testActivityGroup; - testVisible = extension_test_util.testVisible.bind(null, activityLogItem); + activityLogHistoryItem = new extensions.ActivityLogHistoryItem(); + activityLogHistoryItem.data = testActivityGroup; + testVisible = + extension_test_util.testVisible.bind(null, activityLogHistoryItem); - document.body.appendChild(activityLogItem); + document.body.appendChild(activityLogHistoryItem); }); teardown(function() { - activityLogItem.remove(); + activityLogHistoryItem.remove(); }); test('no page URLs shown when activity has no associated page', function() { @@ -57,14 +58,14 @@ chrome.activityLogPrivate.ExtensionActivityFilter.DOM_ACCESS, countsByUrl }; - activityLogItem.set('data', testActivityGroup); + activityLogHistoryItem.set('data', testActivityGroup); Polymer.dom.flush(); testVisible('#activity-item-main-row', true); testVisible('#page-url-list', false); - activityLogItem.$$('#activity-item-main-row').click(); + activityLogHistoryItem.$$('#activity-item-main-row').click(); testVisible('#page-url-list', true); }); @@ -80,8 +81,8 @@ countsByUrl }; - activityLogItem.set('data', testActivityGroup); - activityLogItem.$$('#activity-item-main-row').click(); + activityLogHistoryItem.set('data', testActivityGroup); + activityLogHistoryItem.$$('#activity-item-main-row').click(); Polymer.dom.flush(); @@ -102,8 +103,8 @@ chrome.activityLogPrivate.ExtensionActivityFilter.DOM_ACCESS, countsByUrl }; - activityLogItem.set('data', testActivityGroup); - activityLogItem.$$('#activity-item-main-row').click(); + activityLogHistoryItem.set('data', testActivityGroup); + activityLogHistoryItem.$$('#activity-item-main-row').click(); Polymer.dom.flush(); @@ -111,7 +112,8 @@ testVisible('#page-url-list', true); testVisible('.page-url-count', true); - const pageUrls = activityLogItem.shadowRoot.querySelectorAll('.page-url'); + const pageUrls = + activityLogHistoryItem.shadowRoot.querySelectorAll('.page-url'); expectEquals(pageUrls.length, 2); // Test the order of the page URLs and activity count for the activity
diff --git a/chrome/test/data/webui/extensions/activity_log_history_test.js b/chrome/test/data/webui/extensions/activity_log_history_test.js index b22c83d..1f73862 100644 --- a/chrome/test/data/webui/extensions/activity_log_history_test.js +++ b/chrome/test/data/webui/extensions/activity_log_history_test.js
@@ -148,8 +148,8 @@ testVisible('#loading-activities', false); testVisible('#activity-list', true); - const activityLogItems = - activityLogHistory.shadowRoot.querySelectorAll('activity-log-item'); + const activityLogItems = activityLogHistory.shadowRoot.querySelectorAll( + 'activity-log-history-item'); expectEquals(activityLogItems.length, 2); // Test the order of the activity log items here. This test is in this @@ -171,8 +171,8 @@ return setupActivityLogHistory().then(() => { Polymer.dom.flush(); - const activityLogItems = - activityLogHistory.shadowRoot.querySelectorAll('activity-log-item'); + const activityLogItems = activityLogHistory.shadowRoot.querySelectorAll( + 'activity-log-history-item'); // One activity should be shown for each content script name. expectEquals(activityLogItems.length, 2); @@ -189,8 +189,8 @@ return setupActivityLogHistory().then(() => { Polymer.dom.flush(); - const activityLogItems = - activityLogHistory.shadowRoot.querySelectorAll('activity-log-item'); + const activityLogItems = activityLogHistory.shadowRoot.querySelectorAll( + 'activity-log-history-item'); // First activity should be split into two groups as it has two actions // recorded in the other.webRequest object. We display the names of these @@ -223,7 +223,7 @@ Polymer.dom.flush(); const activityLogItems = activityLogHistory.shadowRoot.querySelectorAll( - 'activity-log-item'); + 'activity-log-history-item'); expectEquals(activityLogItems.length, 2); proxyDelegate.resetResolver('getExtensionActivityLog'); @@ -238,7 +238,7 @@ expectEquals( 1, activityLogHistory.shadowRoot - .querySelectorAll('activity-log-item') + .querySelectorAll('activity-log-history-item') .length); }); }); @@ -255,7 +255,8 @@ testVisible('#loading-activities', false); testVisible('#activity-list', false); expectEquals( - activityLogHistory.shadowRoot.querySelectorAll('activity-log-item') + activityLogHistory.shadowRoot + .querySelectorAll('activity-log-history-item') .length, 0); });
diff --git a/chrome/test/data/webui/extensions/activity_log_test.js b/chrome/test/data/webui/extensions/activity_log_test.js index 8ea7528..c05d5a2 100644 --- a/chrome/test/data/webui/extensions/activity_log_test.js +++ b/chrome/test/data/webui/extensions/activity_log_test.js
@@ -103,7 +103,7 @@ const activityLogItems = activityLogHistory.shadowRoot.querySelectorAll( - 'activity-log-item'); + 'activity-log-history-item'); // Since we searched for an API call, we expect only one match as // activity log entries are grouped by their API call. @@ -127,7 +127,7 @@ expectEquals( activityLogHistory.shadowRoot - .querySelectorAll('activity-log-item') + .querySelectorAll('activity-log-history-item') .length, 0); @@ -143,7 +143,7 @@ const activityLogItems = activityLogHistory.shadowRoot.querySelectorAll( - 'activity-log-item'); + 'activity-log-history-item'); expectEquals(activityLogItems.length, 2); }); }); @@ -163,7 +163,7 @@ testVisible('#activity-list', false); expectEquals( activityLogHistory.shadowRoot - .querySelectorAll('activity-log-item') + .querySelectorAll('activity-log-history-item') .length, 0); });
diff --git a/chrome/test/data/webui/extensions/cr_extensions_browsertest.js b/chrome/test/data/webui/extensions/cr_extensions_browsertest.js index a848a5a4..195c8c6 100644 --- a/chrome/test/data/webui/extensions/cr_extensions_browsertest.js +++ b/chrome/test/data/webui/extensions/cr_extensions_browsertest.js
@@ -239,7 +239,7 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Activity Log Item Tests -CrExtensionsActivityLogItemTest = class extends CrExtensionsBrowserTest { +CrExtensionsActivityLogHistoryItemTest = class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/activity_log/activity_log_item.html'; @@ -247,12 +247,12 @@ get extraLibraries() { return super.extraLibraries.concat([ - 'activity_log_item_test.js', + 'activity_log_history_item_test.js', ]); } }; -TEST_F('CrExtensionsActivityLogItemTest', 'All', () => { +TEST_F('CrExtensionsActivityLogHistoryItemTest', 'All', () => { mocha.run(); });
diff --git a/chrome/test/data/webui/settings/a11y/sign_out_a11y_test.js b/chrome/test/data/webui/settings/a11y/sign_out_a11y_test.js index 7612fc28..05be4d50 100644 --- a/chrome/test/data/webui/settings/a11y/sign_out_a11y_test.js +++ b/chrome/test/data/webui/settings/a11y/sign_out_a11y_test.js
@@ -86,6 +86,7 @@ if (this.peoplePage.diceEnabled_) { const syncAccountControl = this.peoplePage.$$('settings-sync-account-control'); + syncAccountControl.unifiedConsentEnabled = true; syncAccountControl.syncStatus = { setupInProgress: false, signedIn: true,
diff --git a/chrome/test/data/webui/settings/bluetooth_page_tests.js b/chrome/test/data/webui/settings/bluetooth_page_tests.js index 544b347b..5e143d3 100644 --- a/chrome/test/data/webui/settings/bluetooth_page_tests.js +++ b/chrome/test/data/webui/settings/bluetooth_page_tests.js
@@ -104,6 +104,11 @@ bluetoothStartConnecting: 'bluetoothStartConnecting', }); + // Disable animations so sub-pages open within one event loop. + testing.Test.disableAnimationsAndTransitions(); + }); + + setup(function() { bluetoothApi = new settings.FakeBluetooth(); bluetoothPrivateApi = new settings.FakeBluetoothPrivate(bluetoothApi); @@ -111,11 +116,6 @@ bluetoothApis.bluetoothApiForTest = bluetoothApi; bluetoothApis.bluetoothPrivateApiForTest = bluetoothPrivateApi; - // Disable animations so sub-pages open within one event loop. - testing.Test.disableAnimationsAndTransitions(); - }); - - setup(function() { PolymerTest.clearBody(); bluetoothPage = document.createElement('settings-bluetooth-page'); bluetoothPage.prefs = getFakePrefs(); @@ -133,12 +133,54 @@ test('MainPage', function() { assertFalse(bluetoothApi.getAdapterStateForTest().powered); assertFalse(bluetoothPage.bluetoothToggleState_); + assertTrue(bluetoothPage.isToggleEnabled_()); + // Test that tapping the single settings-box div enables bluetooth. const div = bluetoothPage.$$('div.settings-box'); assertTrue(!!div); div.click(); + + assertTrue( + bluetoothPrivateApi.getLastSetAdapterStateValueForTest().powered); + assertFalse(bluetoothPage.isToggleEnabled_()); + + bluetoothPrivateApi.simulateSuccessfulSetAdapterStateCallForTest(); + assertTrue(bluetoothPage.isToggleEnabled_()); assertTrue(bluetoothPage.bluetoothToggleState_); - assertTrue(bluetoothApi.getAdapterStateForTest().powered); + }); + + // Tests that the adapter changing states affects the toggle. + test('Main Page: State changed', function() { + // The default adapter starts available and powered off. + assertFalse(bluetoothApi.getAdapterStateForTest().powered); + assertTrue(bluetoothApi.getAdapterStateForTest().available); + + assertFalse(bluetoothPage.bluetoothToggleState_); + assertTrue(bluetoothPage.isToggleEnabled_()); + + // Make the adapter unavailable. + bluetoothApi.simulateAdapterStateChangedForTest({ + available: false, + powered: false, + }); + assertFalse(bluetoothPage.bluetoothToggleState_); + assertFalse(bluetoothPage.isToggleEnabled_()); + + // Make the adapter available again. + bluetoothApi.simulateAdapterStateChangedForTest({ + available: true, + powered: false, + }); + assertFalse(bluetoothPage.bluetoothToggleState_); + assertTrue(bluetoothPage.isToggleEnabled_()); + + // Powered on the adapter. + bluetoothApi.simulateAdapterStateChangedForTest({ + available: true, + powered: true, + }); + assertTrue(bluetoothPage.bluetoothToggleState_); + assertTrue(bluetoothPage.isToggleEnabled_()); }); suite('SubPage', function() { @@ -152,7 +194,11 @@ } setup(async function() { - bluetoothApi.setEnabled(true); + bluetoothApi.simulateAdapterStateChangedForTest({ + available: true, + powered: true, + }); + Polymer.dom.flush(); const div = bluetoothPage.$$('div.settings-box'); div.click(); @@ -169,15 +215,22 @@ test('toggle', function() { assertTrue(subpage.bluetoothToggleState); + assertTrue(subpage.isToggleEnabled_()); const enableButton = subpage.$.enableBluetooth; assertTrue(!!enableButton); assertTrue(enableButton.checked); + // Changing the toggle should power off the adapter. subpage.bluetoothToggleState = false; assertFalse(enableButton.checked); - assertFalse(bluetoothApi.getAdapterStateForTest().powered); + assertFalse( + bluetoothPrivateApi.getLastSetAdapterStateValueForTest().powered); + assertFalse(subpage.isToggleEnabled_()); + + bluetoothPrivateApi.simulateSuccessfulSetAdapterStateCallForTest(); assertFalse(bluetoothPage.bluetoothToggleState_); + assertTrue(subpage.isToggleEnabled_()); }); async function waitForListUpdateTimeout() {
diff --git a/chrome/test/data/webui/settings/fake_bluetooth.js b/chrome/test/data/webui/settings/fake_bluetooth.js index c9cadea..c88f660 100644 --- a/chrome/test/data/webui/settings/fake_bluetooth.js +++ b/chrome/test/data/webui/settings/fake_bluetooth.js
@@ -25,14 +25,18 @@ FakeBluetooth.prototype = { // Public testing methods. - /** @param {boolean} enabled */ - setEnabled: function(enabled) { - this.setAdapterState({powered: enabled}); - }, - /** @param {!chrome.bluetooth.AdapterState} state*/ - setAdapterState: function(state) { - Object.assign(this.adapterState_, state); + /** + * @param {!{ + * address: (string|undefined), + * name: (string|undefined), + * powered: (boolean|undefined), + * available: (boolean|undefined), + * discovering: (boolean|undefined) + * }} newState + */ + simulateAdapterStateChangedForTest: function(newState) { + Object.assign(this.adapterState_, newState); this.onAdapterStateChanged.callListeners( Object.assign({}, this.adapterState_)); },
diff --git a/chrome/test/data/webui/settings/fake_bluetooth_private.js b/chrome/test/data/webui/settings/fake_bluetooth_private.js index 6c79605..daf4886 100644 --- a/chrome/test/data/webui/settings/fake_bluetooth_private.js +++ b/chrome/test/data/webui/settings/fake_bluetooth_private.js
@@ -17,17 +17,53 @@ /** @type {!Set<string>} */ this.connectedDevices_ = new Set(); + /** @private {?chrome.bluetoothPrivate.NewAdapterState} */ + this.lastSetAdapterStateValue_ = null; + + /** @private {?function()} */ + this.lastSetAdapterStateCallback_ = null; + /** @type {!Object<!chrome.bluetoothPrivate.SetPairingResponseOptions>} */ this.pairingResponses_ = {}; } FakeBluetoothPrivate.prototype = { + // Public testing methods. + + simulateSuccessfulSetAdapterStateCallForTest: function() { + // Swap values here to avoid reentrancy issues when we run the callback. + const lastStateValue = this.lastSetAdapterStateValue_; + this.lastSetAdapterStateValue_ = null; + const callback = this.lastSetAdapterStateCallback_; + this.lastSetAdapterStateCallback_ = null; + + // The underlying Bluetooth API runs the SetAdapterState callback before + // notifying the that the adapter changed states. + // + // setAdapterState()'s callback parameter is optional. + if (callback) { + callback(); + } + + const newState = Object.assign( + this.bluetoothApi_.getAdapterStateForTest(), lastStateValue); + + this.bluetoothApi_.simulateAdapterStateChangedForTest(newState); + }, + + /** @returns {?chrome.bluetoothPrivate.NewAdapterState} */ + getLastSetAdapterStateValueForTest: function() { + return this.lastSetAdapterStateValue_; + }, + /** @override */ setAdapterState: function(state, opt_callback) { - this.bluetoothApi_.setAdapterState(state); - if (opt_callback) { - opt_callback(); + this.lastSetAdapterStateValue_ = state; + if (opt_callback !== undefined) { + this.lastSetAdapterStateCallback_ = opt_callback; } + // Use simulateSuccessfulSetAdapterStateCallForTest to complete the + // action. }, /** @override */
diff --git a/chrome/test/data/webui/settings/multidevice_page_tests.js b/chrome/test/data/webui/settings/multidevice_page_tests.js index 1dd431c..a3d15f39 100644 --- a/chrome/test/data/webui/settings/multidevice_page_tests.js +++ b/chrome/test/data/webui/settings/multidevice_page_tests.js
@@ -59,7 +59,8 @@ if (authRequired) { assertTrue(multidevicePage.showPasswordPromptDialog_); // Simulate the user entering a valid password, then closing the dialog. - multidevicePage.fire('auth-token-changed', {value: 'validAuthToken'}); + multidevicePage.$$('#multidevicePasswordPrompt').authToken = + 'validAuthToken'; // Simulate closing the password prompt dialog multidevicePage.$$('#multidevicePasswordPrompt').fire('close'); Polymer.dom.flush();
diff --git a/chrome/test/data/webui/settings/site_entry_tests.js b/chrome/test/data/webui/settings/site_entry_tests.js index 3ced1fab..1e600aa4 100644 --- a/chrome/test/data/webui/settings/site_entry_tests.js +++ b/chrome/test/data/webui/settings/site_entry_tests.js
@@ -240,4 +240,48 @@ }); }); + + test('favicon with www.etld+1 chosen for site group', function() { + // Clone this object to avoid propagating changes made in this test. + const testSiteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); + testSiteGroup.origins[0].usage = 0; + testSiteGroup.origins[1].usage = 1274; + testSiteGroup.origins[2].usage = 74622; + testElement.siteGroup = testSiteGroup; + Polymer.dom.flush(); + assertEquals( + testElement.$.collapseParent.querySelector('site-favicon').url, + 'https://www.example.com'); + }); + + test('favicon with largest storage chosen for site group', function() { + // Clone this object to avoid propagating changes made in this test. + const testSiteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); + testSiteGroup.origins[0].usage = 0; + testSiteGroup.origins[1].usage = 1274; + testSiteGroup.origins[2].usage = 74622; + testSiteGroup.origins[1].origin = 'https://abc.example.com'; + testElement.siteGroup = testSiteGroup; + Polymer.dom.flush(); + assertEquals( + testElement.$.collapseParent.querySelector('site-favicon').url, + 'https://login.example.com'); + }); + + test('favicon with largest cookies number chosen for site group', function() { + // Clone this object to avoid propagating changes made in this test. + const testSiteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); + testSiteGroup.origins[0].usage = 0; + testSiteGroup.origins[1].usage = 1274; + testSiteGroup.origins[2].usage = 1274; + testSiteGroup.origins[0].numCookies = 10; + testSiteGroup.origins[1].numCookies = 3; + testSiteGroup.origins[2].numCookies = 1; + testSiteGroup.origins[1].origin = 'https://abc.example.com'; + testElement.siteGroup = testSiteGroup; + Polymer.dom.flush(); + assertEquals( + testElement.$.collapseParent.querySelector('site-favicon').url, + 'https://abc.example.com'); + }); });
diff --git a/chrome/tools/build/linux/FILES.cfg b/chrome/tools/build/linux/FILES.cfg index 912c886..c1a1c0f 100644 --- a/chrome/tools/build/linux/FILES.cfg +++ b/chrome/tools/build/linux/FILES.cfg
@@ -277,9 +277,9 @@ { 'filename': 'chromedriver', 'arch': ['64bit'], - 'buildtype': ['official'], + 'buildtype': ['dev', 'official'], 'archive': 'chromedriver_linux64.zip', - 'optional': ['official'], + 'optional': ['dev', 'official'], }, # Headless shell files: {
diff --git a/chrome/tools/build/mac/FILES.cfg b/chrome/tools/build/mac/FILES.cfg index f3a6592..0a3ce42d 100644 --- a/chrome/tools/build/mac/FILES.cfg +++ b/chrome/tools/build/mac/FILES.cfg
@@ -126,9 +126,9 @@ { 'filename': 'chromedriver', 'arch': ['64bit'], - 'buildtype': ['official'], + 'buildtype': ['dev', 'official'], 'archive': 'chromedriver_mac64.zip', - 'optional': ['official'], + 'optional': ['dev', 'official'], }, # DevTools front-end files: {
diff --git a/chrome/tools/build/win/FILES.cfg b/chrome/tools/build/win/FILES.cfg index 9389474..e91b265 100644 --- a/chrome/tools/build/win/FILES.cfg +++ b/chrome/tools/build/win/FILES.cfg
@@ -827,16 +827,16 @@ { 'filename': 'chromedriver.exe', 'arch': ['32bit'], - 'buildtype': ['official'], + 'buildtype': ['dev', 'official'], 'archive': 'chromedriver_win32.zip', - 'optional': ['official'], + 'optional': ['dev', 'official'], 'filegroup': ['symsrc'], }, { 'filename': 'chromedriver.exe.pdb', - 'buildtype': ['official'], + 'buildtype': ['dev', 'official'], 'archive': 'chromedriver_win32-syms.zip', - 'optional': ['official'], + 'optional': ['dev', 'official'], }, # Elevation service files: {
diff --git a/chrome/updater/BUILD.gn b/chrome/updater/BUILD.gn index 4134fa1d..ff3b6181 100644 --- a/chrome/updater/BUILD.gn +++ b/chrome/updater/BUILD.gn
@@ -32,7 +32,6 @@ "//components/update_client", "//components/version_info", "//mojo/core/embedder", - "//net", "//url", ] } @@ -44,7 +43,15 @@ "updater_unittest.cc", ] + deps = [ + ":updater", + "//base/test:test_support", + "//testing/gtest", + ] + if (is_win) { + deps += [ "//chrome/updater/win:unittest" ] + data_deps = [ "//chrome/updater/win:updater", ] @@ -55,10 +62,4 @@ "//chrome/updater/mac:updater", ] } - - deps = [ - ":updater", - "//base/test:test_support", - "//testing/gtest", - ] }
diff --git a/chrome/updater/configurator.cc b/chrome/updater/configurator.cc index 1a34f3c..e78f9a0 100644 --- a/chrome/updater/configurator.cc +++ b/chrome/updater/configurator.cc
@@ -5,12 +5,17 @@ #include "chrome/updater/configurator.h" #include "base/version.h" +#include "build/build_config.h" #include "components/update_client/network.h" #include "components/update_client/protocol_handler.h" #include "components/version_info/version_info.h" #include "services/service_manager/public/cpp/connector.h" #include "url/gurl.h" +#if defined(OS_WIN) +#include "chrome/updater/win/net/network.h" +#endif + namespace { // Default time constants. @@ -86,7 +91,15 @@ scoped_refptr<update_client::NetworkFetcherFactory> Configurator::GetNetworkFetcherFactory() { +#if defined(OS_WIN) + if (!network_fetcher_factory_) { + network_fetcher_factory_ = + base::MakeRefCounted<NetworkFetcherWinHTTPFactory>(); + } + return network_fetcher_factory_; +#else return nullptr; +#endif } std::unique_ptr<service_manager::Connector>
diff --git a/chrome/updater/configurator.h b/chrome/updater/configurator.h index d33eede..62034e4 100644 --- a/chrome/updater/configurator.h +++ b/chrome/updater/configurator.h
@@ -75,6 +75,7 @@ friend class base::RefCountedThreadSafe<Configurator>; ~Configurator() override; + scoped_refptr<update_client::NetworkFetcherFactory> network_fetcher_factory_; DISALLOW_COPY_AND_ASSIGN(Configurator); };
diff --git a/chrome/updater/win/BUILD.gn b/chrome/updater/win/BUILD.gn index 61a1b5b..d5e222e 100644 --- a/chrome/updater/win/BUILD.gn +++ b/chrome/updater/win/BUILD.gn
@@ -3,6 +3,7 @@ # found in the LICENSE file. import("//chrome/process_version_rc_template.gni") +import("//testing/test.gni") group("win") { deps = [ @@ -18,7 +19,9 @@ configs += [ "//build/config/win:windowed" ] + libs = [ "winhttp.lib" ] deps = [ + ":code", ":version_resources", "//build/win:default_exe_manifest", "//chrome/updater:common", @@ -31,3 +34,31 @@ ] output = "$target_gen_dir/updater_exe.rc" } + +source_set("code") { + sources = [ + "net/network.h", + "net/network_winhttp.cc", + "net/network_winhttp.h", + "net/scoped_hinternet.h", + ] + + deps = [ + "//base", + "//components/update_client", + ] +} + +source_set("unittest") { + testonly = true + + sources = [ + "net/network_unittest.cc", + ] + + deps = [ + ":code", + "//base/test:test_support", + "//testing/gtest", + ] +}
diff --git a/chrome/updater/win/net/network.h b/chrome/updater/win/net/network.h new file mode 100644 index 0000000..5fea779 --- /dev/null +++ b/chrome/updater/win/net/network.h
@@ -0,0 +1,35 @@ +// 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_UPDATER_WIN_NET_NETWORK_H_ +#define CHROME_UPDATER_WIN_NET_NETWORK_H_ + +#include <memory> + +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "chrome/updater/win/net/scoped_hinternet.h" +#include "components/update_client/network.h" + +namespace updater { + +class NetworkFetcherWinHTTPFactory + : public update_client::NetworkFetcherFactory { + public: + NetworkFetcherWinHTTPFactory(); + + std::unique_ptr<update_client::NetworkFetcher> Create() const override; + + protected: + ~NetworkFetcherWinHTTPFactory() override; + + private: + ScopedHInternet session_handle_; + + DISALLOW_COPY_AND_ASSIGN(NetworkFetcherWinHTTPFactory); +}; + +} // namespace updater + +#endif // CHROME_UPDATER_WIN_NET_NETWORK_H_
diff --git a/chrome/updater/win/net/network_unittest.cc b/chrome/updater/win/net/network_unittest.cc new file mode 100644 index 0000000..b550968 --- /dev/null +++ b/chrome/updater/win/net/network_unittest.cc
@@ -0,0 +1,16 @@ +// 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/updater/win/net/network.h" +#include "base/memory/ref_counted.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace updater { + +TEST(UpdaterTestNetwork, NetworkFetcherWinHTTPFactory) { + auto fetcher = base::MakeRefCounted<NetworkFetcherWinHTTPFactory>()->Create(); + EXPECT_NE(nullptr, fetcher.get()); +} + +} // namespace updater
diff --git a/chrome/updater/win/net/network_winhttp.cc b/chrome/updater/win/net/network_winhttp.cc new file mode 100644 index 0000000..cda07053 --- /dev/null +++ b/chrome/updater/win/net/network_winhttp.cc
@@ -0,0 +1,43 @@ +// 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/updater/win/net/network_winhttp.h" + +#include "base/callback.h" +#include "chrome/updater/win/net/network.h" +#include "chrome/updater/win/net/scoped_hinternet.h" + +namespace updater { + +NetworkFetcherWinHTTP::NetworkFetcherWinHTTP() = default; +NetworkFetcherWinHTTP::~NetworkFetcherWinHTTP() = default; + +void NetworkFetcherWinHTTP::PostRequest( + const GURL& url, + const std::string& post_data, + const base::flat_map<std::string, std::string>& post_additional_headers, + ResponseStartedCallback response_started_callback, + PostRequestCompleteCallback post_request_complete_callback) {} + +void NetworkFetcherWinHTTP::DownloadToFile( + const GURL& url, + const base::FilePath& file_path, + ResponseStartedCallback response_started_callback, + DownloadToFileCompleteCallback download_to_file_complete_callback) {} + +NetworkFetcherWinHTTPFactory::NetworkFetcherWinHTTPFactory() + : session_handle_(WinHttpOpen(L"Chrome Updater", + WINHTTP_ACCESS_TYPE_NO_PROXY, + WINHTTP_NO_PROXY_NAME, + WINHTTP_NO_PROXY_BYPASS, + WINHTTP_FLAG_ASYNC)) {} +NetworkFetcherWinHTTPFactory::~NetworkFetcherWinHTTPFactory() = default; + +std::unique_ptr<update_client::NetworkFetcher> +NetworkFetcherWinHTTPFactory::Create() const { + return session_handle_.get() ? std::make_unique<NetworkFetcherWinHTTP>() + : nullptr; +} + +} // namespace updater
diff --git a/chrome/updater/win/net/network_winhttp.h b/chrome/updater/win/net/network_winhttp.h new file mode 100644 index 0000000..ba21b8480 --- /dev/null +++ b/chrome/updater/win/net/network_winhttp.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 CHROME_UPDATER_WIN_NET_NETWORK_WINHTTP_H_ +#define CHROME_UPDATER_WIN_NET_NETWORK_WINHTTP_H_ + +#include <memory> +#include <string> + +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "components/update_client/network.h" + +namespace updater { + +class NetworkFetcherWinHTTP : public update_client::NetworkFetcher { + public: + using ResponseStartedCallback = + update_client::NetworkFetcher::ResponseStartedCallback; + using PostRequestCompleteCallback = + update_client::NetworkFetcher::PostRequestCompleteCallback; + using DownloadToFileCompleteCallback = + update_client::NetworkFetcher::DownloadToFileCompleteCallback; + + NetworkFetcherWinHTTP(); + ~NetworkFetcherWinHTTP() override; + + // NetworkFetcher overrides. + void PostRequest( + const GURL& url, + const std::string& post_data, + const base::flat_map<std::string, std::string>& post_additional_headers, + ResponseStartedCallback response_started_callback, + PostRequestCompleteCallback post_request_complete_callback) override; + void DownloadToFile(const GURL& url, + const base::FilePath& file_path, + ResponseStartedCallback response_started_callback, + DownloadToFileCompleteCallback + download_to_file_complete_callback) override; + + private: + DISALLOW_COPY_AND_ASSIGN(NetworkFetcherWinHTTP); +}; + +} // namespace updater + +#endif // CHROME_UPDATER_WIN_NET_NETWORK_WINHTTP_H_
diff --git a/chrome/updater/win/net/scoped_hinternet.h b/chrome/updater/win/net/scoped_hinternet.h new file mode 100644 index 0000000..ca4ca6b --- /dev/null +++ b/chrome/updater/win/net/scoped_hinternet.h
@@ -0,0 +1,37 @@ +// 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_UPDATER_WIN_NET_SCOPED_HINTERNET_H_ +#define CHROME_UPDATER_WIN_NET_SCOPED_HINTERNET_H_ + +#include <windows.h> +#include <winhttp.h> + +#include "base/scoped_generic.h" + +namespace updater { + +namespace internal { + +struct ScopedHInternetTraits { + static HINTERNET InvalidValue() { return nullptr; } + static void Free(HINTERNET handle) { + if (handle != InvalidValue()) + WinHttpCloseHandle(handle); + } +}; + +} // namespace internal + +// Manages the lifetime of HINTERNET handles allocated by WinHTTP. +class ScopedHInternet + : public base::ScopedGeneric<HINTERNET, + updater::internal::ScopedHInternetTraits> { + public: + explicit ScopedHInternet(HINTERNET handle) : ScopedGeneric(handle) {} +}; + +} // namespace updater + +#endif // CHROME_UPDATER_WIN_NET_SCOPED_HINTERNET_H_
diff --git a/chromecast/app/BUILD.gn b/chromecast/app/BUILD.gn index c18b2a8..5166e88 100644 --- a/chromecast/app/BUILD.gn +++ b/chromecast/app/BUILD.gn
@@ -98,10 +98,7 @@ "//testing/gtest", ] - if (is_fuchsia) { - sources += [ "cast_main_delegate_unittest.cc" ] - deps += [ ":app" ] - } else { + if (!is_fuchsia) { deps += [ # TODO(crbug.com/753619): Enable crash reporting on Fuchsia. ":cast_crash_client",
diff --git a/chromecast/app/android/cast_jni_loader.cc b/chromecast/app/android/cast_jni_loader.cc index cb9350b..705d49b 100644 --- a/chromecast/app/android/cast_jni_loader.cc +++ b/chromecast/app/android/cast_jni_loader.cc
@@ -23,7 +23,6 @@ return false; content::Compositor::Initialize(); - content::SetContentMainDelegate( - new chromecast::shell::CastMainDelegate(0, nullptr)); + content::SetContentMainDelegate(new chromecast::shell::CastMainDelegate); return JNI_VERSION_1_4; }
diff --git a/chromecast/app/cast_main.cc b/chromecast/app/cast_main.cc index 682a1e21..6c6c0b4f 100644 --- a/chromecast/app/cast_main.cc +++ b/chromecast/app/cast_main.cc
@@ -6,9 +6,9 @@ #include "content/public/app/content_main.h" int main(int argc, const char** argv) { - chromecast::shell::CastMainDelegate delegate(argc, argv); + chromecast::shell::CastMainDelegate delegate; content::ContentMainParams params(&delegate); - params.argc = delegate.argc(); - params.argv = delegate.argv(); + params.argc = argc; + params.argv = argv; return content::ContentMain(params); }
diff --git a/chromecast/app/cast_main_delegate.cc b/chromecast/app/cast_main_delegate.cc index f3a3afa4..979a80b1 100644 --- a/chromecast/app/cast_main_delegate.cc +++ b/chromecast/app/cast_main_delegate.cc
@@ -10,15 +10,14 @@ #include "base/command_line.h" #include "base/cpu.h" +#include "base/files/file.h" #include "base/files/file_enumerator.h" -#include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/metrics/field_trial.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/posix/global_descriptors.h" -#include "base/strings/string_tokenizer.h" #include "build/build_config.h" #include "chromecast/base/cast_paths.h" #include "chromecast/base/chromecast_switches.h" @@ -45,10 +44,6 @@ #include "services/service_manager/sandbox/switches.h" #endif // defined(OS_LINUX) -#if defined(OS_FUCHSIA) -#include "base/base_paths_fuchsia.h" -#endif - namespace { #if defined(OS_LINUX) @@ -63,43 +58,12 @@ const int kMaxCrashFiles = 10; #endif // defined(OS_ANDROID) -base::FilePath GetDefaultCommandLineFile() { -#if defined(OS_FUCHSIA) - base::FilePath command_line_dir; - base::PathService::Get(base::DIR_APP_DATA, &command_line_dir); - return command_line_dir.Append("cast/castagent-command-line"); -#else - return base::FilePath(); -#endif -} - } // namespace namespace chromecast { namespace shell { -CastMainDelegate::CastMainDelegate(int argc, const char** argv) - : CastMainDelegate(argc, argv, GetDefaultCommandLineFile()) {} - -CastMainDelegate::CastMainDelegate(int argc, - const char** argv, - base::FilePath command_line_path) - : argv_(argv, argv + argc) { -#if defined(OS_FUCHSIA) - // Read the command-line from the filesystem. - std::string command_line_str; - if (base::ReadFileToString(command_line_path, &command_line_str)) { - LOG(INFO) << "Appending command-line args from " << command_line_path; - base::StringTokenizer tokenizer(command_line_str, "\n"); - while (tokenizer.GetNext()) - argv_strs_.push_back(tokenizer.token()); - for (int i = 0; i < static_cast<int>(argv_strs_.size()); ++i) - argv_.push_back(argv_strs_[i].c_str()); - } else { - LOG(INFO) << "Unable to read command-line args from " << command_line_path; - } -#endif // defined(OS_FUCHSIA) -} +CastMainDelegate::CastMainDelegate() {} CastMainDelegate::~CastMainDelegate() {}
diff --git a/chromecast/app/cast_main_delegate.h b/chromecast/app/cast_main_delegate.h index e83d3de..2fd26f8 100644 --- a/chromecast/app/cast_main_delegate.h +++ b/chromecast/app/cast_main_delegate.h
@@ -6,10 +6,7 @@ #define CHROMECAST_APP_CAST_MAIN_DELEGATE_H_ #include <memory> -#include <string> -#include <vector> -#include "base/files/file_path.h" #include "base/macros.h" #include "build/build_config.h" #include "chromecast/common/cast_content_client.h" @@ -36,7 +33,7 @@ class CastMainDelegate : public content::ContentMainDelegate { public: - CastMainDelegate(int argc, const char** argv); + CastMainDelegate(); ~CastMainDelegate() override; // content::ContentMainDelegate implementation: @@ -54,16 +51,7 @@ content::ContentRendererClient* CreateContentRendererClient() override; content::ContentUtilityClient* CreateContentUtilityClient() override; - int argc() const { return argv_.size(); } - const char** argv() const { return const_cast<const char**>(argv_.data()); } - private: - friend class CastMainDelegateTest; - - // Used for testing. - CastMainDelegate(int argc, - const char** argv, - base::FilePath command_line_path); void InitializeResourceBundle(); std::unique_ptr<CastContentBrowserClient> browser_client_; @@ -84,11 +72,6 @@ std::unique_ptr<CastFeatureListCreator> cast_feature_list_creator_; - // Combined list of args passed through the main function, and a specified - // command-line file. - std::vector<std::string> argv_strs_; - std::vector<const char*> argv_; - DISALLOW_COPY_AND_ASSIGN(CastMainDelegate); };
diff --git a/chromecast/app/cast_main_delegate_unittest.cc b/chromecast/app/cast_main_delegate_unittest.cc deleted file mode 100644 index f698a11c..0000000 --- a/chromecast/app/cast_main_delegate_unittest.cc +++ /dev/null
@@ -1,83 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <memory> -#include <string> - -#include "base/files/file.h" -#include "base/memory/ptr_util.h" -#include "chromecast/app/cast_main_delegate.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace shell { -namespace { - -const char kTestCommandLineContents[] = "--file1\n--file2\n"; -const char kTestCommandLinePath[] = "/tmp/test-command-line"; - -void WriteTestCommandLine() { - base::File command_line( - base::FilePath(kTestCommandLinePath), - base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); - ASSERT_GE(command_line.Write(0, kTestCommandLineContents, - sizeof(kTestCommandLineContents) - 1), - 0); -} - -} // namespace - -class CastMainDelegateTest : public testing::Test { - public: - CastMainDelegateTest() { WriteTestCommandLine(); } - - ~CastMainDelegateTest() override {} - - // testing::Test implementation: - void SetUp() override { - test_argv_strs_.push_back("--main1"); - test_argv_strs_.push_back("--main2"); - test_argv_.push_back(test_argv_strs_[0].c_str()); - test_argv_.push_back(test_argv_strs_[1].c_str()); - } - - void CreateCastMainDelegate(int argc, - const char** argv, - std::string command_line_path) { - delegate_ = base::WrapUnique( - new CastMainDelegate(argc, argv, base::FilePath(command_line_path))); - } - - protected: - std::unique_ptr<CastMainDelegate> delegate_; - std::vector<std::string> test_argv_strs_; - std::vector<const char*> test_argv_; -}; - -TEST_F(CastMainDelegateTest, AddsArgsFromFile) { - CreateCastMainDelegate(0, nullptr, kTestCommandLinePath); - EXPECT_EQ(2, delegate_->argc()); - EXPECT_EQ("--file1", std::string(delegate_->argv()[0])); - EXPECT_EQ("--file2", std::string(delegate_->argv()[1])); -} - -TEST_F(CastMainDelegateTest, AddsArgsFromMain) { - CreateCastMainDelegate(test_argv_.size(), &test_argv_[0], ""); - EXPECT_EQ(2, delegate_->argc()); - EXPECT_EQ("--main1", std::string(delegate_->argv()[0])); - EXPECT_EQ("--main2", std::string(delegate_->argv()[1])); -} - -TEST_F(CastMainDelegateTest, MergesArgsFromFileAndMain) { - CreateCastMainDelegate(test_argv_.size(), &test_argv_[0], - kTestCommandLinePath); - EXPECT_EQ(4, delegate_->argc()); - EXPECT_EQ("--main1", std::string(delegate_->argv()[0])); - EXPECT_EQ("--main2", std::string(delegate_->argv()[1])); - EXPECT_EQ("--file1", std::string(delegate_->argv()[2])); - EXPECT_EQ("--file2", std::string(delegate_->argv()[3])); -} - -} // namespace shell -} // namespace chromecast
diff --git a/chromecast/app/cast_test_launcher.cc b/chromecast/app/cast_test_launcher.cc index a2fa071..73c44ea 100644 --- a/chromecast/app/cast_test_launcher.cc +++ b/chromecast/app/cast_test_launcher.cc
@@ -35,7 +35,7 @@ protected: content::ContentMainDelegate* CreateContentMainDelegate() override { - return new CastMainDelegate(0, nullptr); + return new CastMainDelegate(); } private:
diff --git a/chromecast/cast_shell_sandbox_policy b/chromecast/cast_shell_sandbox_policy index 21f32309..db22c8d 100644 --- a/chromecast/cast_shell_sandbox_policy +++ b/chromecast/cast_shell_sandbox_policy
@@ -21,6 +21,5 @@ "fuchsia.ui.scenic.Scenic", "fuchsia.vulkan.loader.Loader", "fuchsia.wlan.service.Wlan" - ], - "system": [ "data/cast" ] + ] }
diff --git a/chromecast/media/cma/backend/BUILD.gn b/chromecast/media/cma/backend/BUILD.gn index 5dc651c..0841728 100644 --- a/chromecast/media/cma/backend/BUILD.gn +++ b/chromecast/media/cma/backend/BUILD.gn
@@ -191,6 +191,51 @@ ] } +cast_source_set("mixer_pipeline") { + sources = [ + "audio_output_redirector_input.h", + "filter_group.cc", + "filter_group.h", + "mixer_input.cc", + "mixer_input.h", + "mixer_pipeline.cc", + "mixer_pipeline.h", + "post_processing_pipeline.h", + "post_processing_pipeline_impl.cc", + "post_processing_pipeline_impl.h", + "post_processing_pipeline_parser.cc", + "post_processing_pipeline_parser.h", + ] + deps = [ + ":audio_buildflags", + ":audio_helpers", + ":audio_resampler", + ":cast_audio_json", + ":post_processor_factory", + ":public", + "//base", + "//chromecast/base", + "//chromecast/media/base", + "//chromecast/media/cma/base", + "//chromecast/media/cma/decoder", + "//chromecast/public", + "//chromecast/public/media", + "//media", + "//media:shared_memory_support", + ] +} + +cast_source_set("volume_map") { + sources = [ + "volume_map.cc", + "volume_map.h", + ] + deps = [ + ":cast_audio_json", + "//base", + ] +} + cast_source_set("for_mixer_audio") { sources = [ "audio_decoder_for_mixer.cc", @@ -202,24 +247,11 @@ "cast_media_shlib_mixer_audio.cc", "direct_mixer_source.cc", "direct_mixer_source.h", - "filter_group.cc", - "filter_group.h", "media_pipeline_backend_for_mixer.cc", "media_pipeline_backend_for_mixer.h", - "mixer_input.cc", - "mixer_input.h", - "mixer_pipeline.cc", - "mixer_pipeline.h", - "post_processing_pipeline.h", - "post_processing_pipeline_impl.cc", - "post_processing_pipeline_impl.h", - "post_processing_pipeline_parser.cc", - "post_processing_pipeline_parser.h", "stream_mixer.cc", "stream_mixer.h", "volume_control.cc", - "volume_map.cc", - "volume_map.h", ] deps = [ @@ -227,8 +259,10 @@ ":audio_helpers", ":audio_resampler", ":cast_audio_json", + ":mixer_pipeline", ":post_processor_factory", ":public", + ":volume_map", "//base", "//chromecast/base", "//chromecast/media/audio:libcast_external_audio_pipeline_1.0", @@ -278,8 +312,10 @@ ":av_sync_dummy", ":cast_audio_json", ":for_mixer_audio", + ":mixer_pipeline", ":null_video", ":public", + ":volume_map", "//base", "//base/test:run_all_unittests", "//chromecast/media/audio:fake_external_audio_pipeline",
diff --git a/chromecast/media/cma/backend/audio_output_redirector.cc b/chromecast/media/cma/backend/audio_output_redirector.cc index ced8651..c2243d53 100644 --- a/chromecast/media/cma/backend/audio_output_redirector.cc +++ b/chromecast/media/cma/backend/audio_output_redirector.cc
@@ -12,6 +12,7 @@ #include "base/strings/pattern.h" #include "base/values.h" #include "chromecast/media/cma/backend/audio_fader.h" +#include "chromecast/media/cma/backend/audio_output_redirector_input.h" #include "chromecast/media/cma/backend/mixer_input.h" #include "chromecast/media/cma/backend/stream_mixer.h" #include "chromecast/public/cast_media_shlib.h"
diff --git a/chromecast/media/cma/backend/audio_output_redirector.h b/chromecast/media/cma/backend/audio_output_redirector.h index 6eb4231..4d1b48d 100644 --- a/chromecast/media/cma/backend/audio_output_redirector.h +++ b/chromecast/media/cma/backend/audio_output_redirector.h
@@ -25,32 +25,6 @@ namespace media { class MixerInput; -// Interface used by matching MixerInputs to pass audio data to an output -// redirector. -class AudioOutputRedirectorInput { - public: - // Returns the relative order of the output redirector (used if there are - // multiple output redirectors that match a given MixerInput). - virtual int Order() = 0; - - // Returns any extra delay that the output redirector will add. Used for A/V - // sync. - virtual int64_t GetDelayMicroseconds() = 0; - - // Called to handle audio from a single input stream. Note that all audio - // output redirectors will receive this data, even if they are not first in - // the queue of redirectors; this is to allow smooth fading in/out when - // redirectors are added or removed. - virtual void Redirect( - ::media::AudioBus* const buffer, - int num_frames, - MediaPipelineBackend::AudioDecoder::RenderingDelay rendering_delay, - bool redirected) = 0; - - protected: - virtual ~AudioOutputRedirectorInput() = default; -}; - // Empty interface so we can use a pointer to AudioOutputRedirector as the // token. class AudioOutputRedirectorToken {};
diff --git a/chromecast/media/cma/backend/audio_output_redirector_input.h b/chromecast/media/cma/backend/audio_output_redirector_input.h new file mode 100644 index 0000000..914ae8d2 --- /dev/null +++ b/chromecast/media/cma/backend/audio_output_redirector_input.h
@@ -0,0 +1,44 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROMECAST_MEDIA_CMA_BACKEND_AUDIO_OUTPUT_REDIRECTOR_INPUT_H_ +#define CHROMECAST_MEDIA_CMA_BACKEND_AUDIO_OUTPUT_REDIRECTOR_INPUT_H_ + +namespace media { +class AudioBus; +} // namespace media + +namespace chromecast { +namespace media { + +// Interface used by matching MixerInputs to pass audio data to an output +// redirector. +class AudioOutputRedirectorInput { + public: + // Returns the relative order of the output redirector (used if there are + // multiple output redirectors that match a given MixerInput). + virtual int Order() = 0; + + // Returns any extra delay that the output redirector will add. Used for A/V + // sync. + virtual int64_t GetDelayMicroseconds() = 0; + + // Called to handle audio from a single input stream. Note that all audio + // output redirectors will receive this data, even if they are not first in + // the queue of redirectors; this is to allow smooth fading in/out when + // redirectors are added or removed. + virtual void Redirect( + ::media::AudioBus* const buffer, + int num_frames, + MediaPipelineBackend::AudioDecoder::RenderingDelay rendering_delay, + bool redirected) = 0; + + protected: + virtual ~AudioOutputRedirectorInput() = default; +}; + +} // namespace media +} // namespace chromecast + +#endif // CHROMECAST_MEDIA_CMA_BACKEND_AUDIO_OUTPUT_REDIRECTOR_INPUT_H_
diff --git a/chromecast/media/cma/backend/cplay/BUILD.gn b/chromecast/media/cma/backend/cplay/BUILD.gn new file mode 100644 index 0000000..de9c6c4 --- /dev/null +++ b/chromecast/media/cma/backend/cplay/BUILD.gn
@@ -0,0 +1,20 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +executable("cplay") { + sources = [ + "cplay.cc", + "wav_header.h", + ] + deps = [ + "//base", + "//chromecast/media/cma/backend:cast_audio_json", + "//chromecast/media/cma/backend:mixer_pipeline", + "//chromecast/media/cma/backend:public", + "//chromecast/media/cma/backend:volume_map", + "//chromecast/public", + "//chromecast/public/media", + "//media", + ] +}
diff --git a/chromecast/media/cma/backend/cplay/cplay.cc b/chromecast/media/cma/backend/cplay/cplay.cc new file mode 100644 index 0000000..386386a --- /dev/null +++ b/chromecast/media/cma/backend/cplay/cplay.cc
@@ -0,0 +1,351 @@ +// 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. + +// A standalone utility for processing audio files through the cast +// MixerPipeline. This can be used to pre-process files for offline testing. + +#include <unistd.h> + +#include <algorithm> +#include <limits> +#include <memory> +#include <string> +#include <vector> + +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/json/json_reader.h" +#include "base/logging.h" +#include "base/macros.h" +#include "base/no_destructor.h" +#include "chromecast/media/cma/backend/cast_audio_json.h" +#include "chromecast/media/cma/backend/cplay/wav_header.h" +#include "chromecast/media/cma/backend/mixer_input.h" +#include "chromecast/media/cma/backend/mixer_pipeline.h" +#include "chromecast/media/cma/backend/post_processing_pipeline_impl.h" +#include "chromecast/media/cma/backend/post_processing_pipeline_parser.h" +#include "chromecast/media/cma/backend/volume_map.h" +#include "chromecast/public/media/media_pipeline_backend.h" +#include "media/audio/sounds/wav_audio_handler.h" +#include "media/base/audio_bus.h" +#include "media/base/audio_sample_types.h" + +namespace chromecast { +namespace media { + +// Need an implementation of DbFSToVolume, but volume_control.cc pulls in too +// too many dependencies. +VolumeMap& GetVolumeMap() { + static base::NoDestructor<VolumeMap> volume_map; + return *volume_map; +} + +// static +float VolumeControl::DbFSToVolume(float db) { + return GetVolumeMap().DbFSToVolume(db); +} + +namespace { + +const int kReadSize = 256; + +void PrintHelp(const std::string& command) { + LOG(INFO) << "Usage: " << command; + LOG(INFO) << " -i input .wav file"; + LOG(INFO) << " -o output .wav file"; + LOG(INFO) << " [-c cast_audio.json path]"; + LOG(INFO) << " [-v cast volume as fraction of 1 (0.0-1.0)]"; + LOG(INFO) << " [-d max duration (s)]"; +} + +struct Parameters { + double cast_volume = 1.0; + double duration_s = std::numeric_limits<double>::infinity(); + int output_samples_per_second = -1.0; + std::string device_id = "default"; + base::FilePath input_file_path; + base::FilePath output_file_path; + base::FilePath cast_audio_json_path; +}; + +std::string ReadInputFile(const Parameters& params) { + if (!base::PathExists(params.input_file_path)) { + NOTREACHED() << "File " << params.input_file_path << " does not exist."; + } + std::string wav_data; + if (!base::ReadFileToString(params.input_file_path, &wav_data)) { + NOTREACHED() << "Unable to open wav file, " << params.input_file_path; + } + return wav_data; +} + +// MixerInput::Source that reads from a .wav file. +class WavMixerInputSource : public MixerInput::Source { + public: + WavMixerInputSource(const Parameters& params) + : wav_data_(ReadInputFile(params)), + input_handler_(::media::WavAudioHandler::Create(wav_data_)), + device_id_(params.device_id), + bytes_per_frame_(input_handler_->num_channels() * + input_handler_->bits_per_sample() / 8) { + DCHECK(input_handler_); + LOG(INFO) << "Loaded " << params.input_file_path << ":"; + LOG(INFO) << " Channels: " << input_handler_->num_channels() + << " Bit Depth: " << input_handler_->bits_per_sample() + << " Duration: " << input_handler_->GetDuration().InSecondsF() + << "s."; + } + + ~WavMixerInputSource() override = default; + + bool AtEnd() { return input_handler_->AtEnd(cursor_); } + + // MixerInput::Source implementation: + int num_channels() override { return input_handler_->num_channels(); } + int input_samples_per_second() override { + return input_handler_->sample_rate(); + } + bool primary() override { return true; } + const std::string& device_id() override { return device_id_; } + AudioContentType content_type() override { return AudioContentType::kMedia; } + int desired_read_size() override { return kReadSize; } + int playout_channel() override { return -1; } + + void InitializeAudioPlayback( + int read_size, + MixerInput::RenderingDelay initial_rendering_delay) override {} + + int FillAudioPlaybackFrames(int num_frames, + MixerInput::RenderingDelay rendering_delay, + ::media::AudioBus* buffer) override { + CHECK(buffer); + size_t bytes_written; + CHECK_EQ(num_frames, buffer->frames()); + CHECK(input_handler_->CopyTo(buffer, cursor_, &bytes_written)); + cursor_ += bytes_written; + return bytes_written / bytes_per_frame_; + } + + void OnAudioPlaybackError(MixerError error) override {} + void FinalizeAudioPlayback() override {} + + private: + const std::string wav_data_; + std::unique_ptr<::media::WavAudioHandler> input_handler_; + size_t cursor_ = 0; + const std::string device_id_; + const size_t bytes_per_frame_; + + DISALLOW_COPY_AND_ASSIGN(WavMixerInputSource); +}; + +// Implementation of CastAudioJsonProvider that reads from a specified path. +class FixedCastAudioJsonProvider : public CastAudioJsonProvider { + public: + FixedCastAudioJsonProvider(const base::FilePath& path) : file_path_(path) {} + ~FixedCastAudioJsonProvider() override = default; + + std::unique_ptr<base::Value> GetCastAudioConfig() override { + std::string contents; + base::ReadFileToString(file_path_, &contents); + return base::JSONReader::Read(contents); + } + + void SetTuningChangedCallback(TuningChangedCallback callback) override {} + + private: + const base::FilePath file_path_; + + DISALLOW_COPY_AND_ASSIGN(FixedCastAudioJsonProvider); +}; + +// OutputHandler interface to allow switching between alsa and file output. +// TODO(bshaya): Add option to play directly to an output device! +class OutputHandler { + public: + virtual ~OutputHandler() = default; + virtual void WriteData(float* data, int num_frames) = 0; +}; + +class WavOutputHandler : public OutputHandler { + public: + WavOutputHandler(const base::FilePath& path, + int num_channels, + int sample_rate) + : wav_file_(path, + base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE), + num_channels_(num_channels) { + header_.SetNumChannels(num_channels); + header_.SetSampleRate(sample_rate); + header_.SetBitsPerSample(sizeof(int16_t) * 8); + + // Write wav file header to fill space. We'll need to go back and fill in + // the size later. + wav_file_.WriteAtCurrentPos(reinterpret_cast<char*>(&header_), + sizeof(header_)); + } + + ~WavOutputHandler() override { + // Update size and re-write header. We only really need to overwrite 8 bytes + // but it is easy and cheap to overwrite the whole header. + int size = wav_file_.GetLength(); + int data_size = size - sizeof(header_); + header_.SetDataSize(data_size); + wav_file_.Write(0 /* offset */, reinterpret_cast<char*>(&header_), + sizeof(header_)); + } + + void WriteData(float* data, int num_frames) override { + std::vector<int16_t> fixed_data(num_frames * num_channels_); + for (size_t i = 0; i < fixed_data.size(); ++i) { + fixed_data[i] = + ::media::FixedSampleTypeTraits<int16_t>::FromFloat(data[i]); + } + wav_file_.WriteAtCurrentPos(reinterpret_cast<char*>(fixed_data.data()), + sizeof(fixed_data[0]) * fixed_data.size()); + } + + private: + WavHeader header_; + base::File wav_file_; + const int num_channels_; + + DISALLOW_COPY_AND_ASSIGN(WavOutputHandler); +}; + +class ClippingDetector { + public: + ClippingDetector(int num_channels) : num_channels_(num_channels) {} + ~ClippingDetector() = default; + + void ProcessFrames(float* data, int num_frames) { + for (int i = 0; i < num_frames * num_channels_; ++i) { + if (std::fabs(data[i]) > 1.0) { + ++clipped_samples_; + largest_sample_ = std::max(largest_sample_, std::fabs(data[i])); + } + } + total_samples_ += num_frames * num_channels_; + } + + void PrintReport() { + if (clipped_samples_ == 0) { + return; + } + LOG(WARNING) << "Detected " << clipped_samples_ << " clipped samples (" + << 100.0 * clipped_samples_ / total_samples_ << "%)."; + LOG(WARNING) << "Largest sample: " << largest_sample_; + } + + private: + const int num_channels_; + int clipped_samples_ = 0; + int total_samples_ = 0; + float largest_sample_ = 0.0f; + + DISALLOW_COPY_AND_ASSIGN(ClippingDetector); +}; + +Parameters ReadArgs(int argc, char* argv[]) { + Parameters params; + params.cast_audio_json_path = CastAudioJson::GetFilePath(); + int opt; + while ((opt = getopt(argc, argv, "i:o:c:v:d:")) != -1) { + switch (opt) { + case 'i': + params.input_file_path = base::FilePath(optarg); + break; + case 'o': + params.output_file_path = base::FilePath(optarg); + break; + case 'c': + params.cast_audio_json_path = base::FilePath(optarg); + break; + case 'v': + params.cast_volume = strtod(optarg, nullptr); + CHECK_LE(params.cast_volume, 1.0); + CHECK_GE(params.cast_volume, 0.0); + break; + case 'd': + params.duration_s = strtod(optarg, nullptr); + break; + default: + PrintHelp(argv[0]); + exit(1); + } + } + if (params.input_file_path.empty()) { + PrintHelp(argv[0]); + exit(1); + } + if (params.output_file_path.empty()) { + PrintHelp(argv[0]); + exit(1); + } + return params; +} + +// Real main() inside namespace. +int CplayMain(int argc, char* argv[]) { + Parameters params = ReadArgs(argc, argv); + + // Read input file. + WavMixerInputSource input_source(params); + params.output_samples_per_second = input_source.input_samples_per_second(); + + // Build Processing Pipeline. + PostProcessingPipelineParser parser(params.cast_audio_json_path); + auto factory = std::make_unique<PostProcessingPipelineFactoryImpl>(); + auto pipeline = MixerPipeline::CreateMixerPipeline(&parser, factory.get()); + CHECK(pipeline); + pipeline->Initialize(params.output_samples_per_second); + LOG(INFO) << "Initialized Cast Audio Pipeline at " + << params.output_samples_per_second << " samples per second"; + + // Add |input_source| to |pipeline| + FilterGroup* input_group = pipeline->GetInputGroup(params.device_id); + CHECK(input_group); + MixerInput mixer_input(&input_source, params.output_samples_per_second, + kReadSize, MixerInput::RenderingDelay(), input_group); + + // Set volume. + std::string contents; + base::ReadFileToString(params.cast_audio_json_path, &contents); + GetVolumeMap().LoadVolumeMap(base::JSONReader::Read(contents)); + float volume_dbfs = GetVolumeMap().VolumeToDbFS(params.cast_volume); + float volume_multiplier = std::pow(10.0, volume_dbfs / 20.0); + mixer_input.SetVolumeMultiplier(1.0); + mixer_input.SetContentTypeVolume(volume_multiplier, 0 /* fade_ms */); + LOG(INFO) << "Volume set to level " << params.cast_volume << " | " + << volume_dbfs << "dBFS | multiplier=" << volume_multiplier; + + // Prepare output. + std::unique_ptr<OutputHandler> output_handler_ = + std::make_unique<WavOutputHandler>(params.output_file_path, + pipeline->GetOutputChannelCount(), + params.output_samples_per_second); + ClippingDetector clip_detector(pipeline->GetOutputChannelCount()); + + // Play! + int frames_written = 0; + while (!input_source.AtEnd() && + frames_written / params.output_samples_per_second < + params.duration_s) { + pipeline->MixAndFilter(kReadSize, MixerInput::RenderingDelay()); + clip_detector.ProcessFrames(pipeline->GetOutput(), kReadSize); + output_handler_->WriteData(pipeline->GetOutput(), kReadSize); + } + + clip_detector.PrintReport(); + return 0; +} + +} // namespace +} // namespace media +} // namespace chromecast + +int main(int argc, char* argv[]) { + return chromecast::media::CplayMain(argc, argv); +}
diff --git a/chromecast/media/cma/backend/cplay/wav_header.h b/chromecast/media/cma/backend/cplay/wav_header.h new file mode 100644 index 0000000..d081b6ee --- /dev/null +++ b/chromecast/media/cma/backend/cplay/wav_header.h
@@ -0,0 +1,60 @@ +// 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 CHROMECAST_MEDIA_CMA_BACKEND_CPLAY_WAV_HEADER_H_ +#define CHROMECAST_MEDIA_CMA_BACKEND_CPLAY_WAV_HEADER_H_ + +#include <stdint.h> + +namespace chromecast { +namespace media { + +// From http://soundfile.sapp.org/doc/WaveFormat/ +struct __attribute__((packed)) WavHeader { + const char riff[4] = {'R', 'I', 'F', 'F'}; + uint32_t chunk_size; // size of file - 8 + const char wave[4] = {'W', 'A', 'V', 'E'}; + const char fmt[4] = {'f', 'm', 't', ' '}; + const uint32_t subchunk_size = 16; + const uint16_t audio_format = 1; // PCM + uint16_t num_channels; + uint32_t sample_rate; + uint32_t byte_rate; // sample_rate * num_channels * bytes per sample + uint16_t block_align; // num_channels * bytes per sample + uint16_t bits_per_sample; + const char data[4] = {'d', 'a', 't', 'a'}; + uint32_t subchunk_2_size; // bytes in the data + + WavHeader(); + ~WavHeader() = default; + + void SetDataSize(int size_bytes) { + chunk_size = 36 + size_bytes; + subchunk_2_size = size_bytes; + } + + void SetNumChannels(int num_channels_in) { + num_channels = num_channels_in; + byte_rate = sample_rate * num_channels * bits_per_sample / 8; + block_align = num_channels * bits_per_sample / 8; + } + + void SetSampleRate(int sample_rate_in) { + sample_rate = sample_rate_in; + byte_rate = sample_rate * num_channels * bits_per_sample / 8; + } + + void SetBitsPerSample(int bits_per_sample_in) { + bits_per_sample = bits_per_sample_in; + byte_rate = sample_rate * num_channels * bits_per_sample / 8; + block_align = num_channels * bits_per_sample / 8; + } +}; + +WavHeader::WavHeader() = default; + +} // namespace media +} // namespace chromecast + +#endif // CHROMECAST_MEDIA_CMA_BACKEND_CPLAY_WAV_HEADER_H_
diff --git a/chromecast/media/cma/backend/mixer_input.cc b/chromecast/media/cma/backend/mixer_input.cc index 63c1e266..6a80a06 100644 --- a/chromecast/media/cma/backend/mixer_input.cc +++ b/chromecast/media/cma/backend/mixer_input.cc
@@ -14,7 +14,7 @@ #include "base/bind_helpers.h" #include "base/logging.h" #include "chromecast/media/cma/backend/audio_fader.h" -#include "chromecast/media/cma/backend/audio_output_redirector.h" +#include "chromecast/media/cma/backend/audio_output_redirector_input.h" #include "chromecast/media/cma/backend/filter_group.h" #include "media/base/audio_bus.h" #include "media/base/audio_timestamp_helper.h"
diff --git a/chromecast/media/cma/backend/volume_map.h b/chromecast/media/cma/backend/volume_map.h index c326a963..0a5e2658 100644 --- a/chromecast/media/cma/backend/volume_map.h +++ b/chromecast/media/cma/backend/volume_map.h
@@ -32,13 +32,14 @@ float DbFSToVolume(float db); + void LoadVolumeMap(std::unique_ptr<base::Value> cast_audio_config); + private: struct LevelToDb { float level; float db; }; - void LoadVolumeMap(std::unique_ptr<base::Value> cast_audio_config); void UseDefaultVolumeMap(); // |volume_map_| must be accessed with |lock_|.
diff --git a/chromeos/CHROMEOS_LKGM b/chromeos/CHROMEOS_LKGM index 6196680..c5671dbf 100644 --- a/chromeos/CHROMEOS_LKGM +++ b/chromeos/CHROMEOS_LKGM
@@ -1 +1 @@ -11760.0.0 \ No newline at end of file +11801.0.0 \ No newline at end of file
diff --git a/chromeos/components/proximity_auth/unlock_manager_impl.cc b/chromeos/components/proximity_auth/unlock_manager_impl.cc index ce7ae90f..d545594 100644 --- a/chromeos/components/proximity_auth/unlock_manager_impl.cc +++ b/chromeos/components/proximity_auth/unlock_manager_impl.cc
@@ -115,17 +115,12 @@ life_cycle_(nullptr), proximity_auth_client_(proximity_auth_client), pref_manager_(pref_manager), - is_locked_(false), is_attempting_auth_(false), is_waking_up_(false), screenlock_state_(ScreenlockState::INACTIVE), clear_waking_up_state_weak_ptr_factory_(this), reject_auth_attempt_weak_ptr_factory_(this), weak_ptr_factory_(this) { - ScreenlockBridge* screenlock_bridge = ScreenlockBridge::Get(); - screenlock_bridge->AddObserver(this); - OnScreenLockedOrUnlocked(screenlock_bridge->IsLocked()); - DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver(this); SetWakingUpState(true /* is_waking_up */); @@ -144,8 +139,6 @@ if (proximity_monitor_) proximity_monitor_->RemoveObserver(this); - ScreenlockBridge::Get()->RemoveObserver(this); - DBusThreadManager::Get()->GetPowerManagerClient()->RemoveObserver(this); if (bluetooth_adapter_) @@ -196,11 +189,16 @@ if (!proximity_monitor_) { proximity_monitor_ = CreateProximityMonitor(life_cycle_, pref_manager_); proximity_monitor_->AddObserver(this); + proximity_monitor_->Start(); } GetMessenger()->AddObserver(this); attempt_get_remote_status_start_time_ = base::DefaultClock::GetInstance()->Now(); + } else if (proximity_monitor_) { + proximity_monitor_->RemoveObserver(this); + proximity_monitor_->Stop(); + proximity_monitor_.reset(); } if (state == RemoteDeviceLifeCycle::State::AUTHENTICATION_FAILED) @@ -302,26 +300,6 @@ UpdateLockScreen(); } -void UnlockManagerImpl::OnScreenDidLock( - ScreenlockBridge::LockHandler::ScreenType screen_type) { - OnScreenLockedOrUnlocked(true); -} - -void UnlockManagerImpl::OnScreenDidUnlock( - ScreenlockBridge::LockHandler::ScreenType screen_type) { - OnScreenLockedOrUnlocked(false); -} - -void UnlockManagerImpl::OnFocusedUserChanged(const AccountId& account_id) {} - -void UnlockManagerImpl::OnScreenLockedOrUnlocked(bool is_locked) { - if (is_locked && IsBluetoothPresentAndPowered() && life_cycle_) - SetWakingUpState(true /* is_waking_up */); - - is_locked_ = is_locked; - UpdateProximityMonitorState(); -} - void UnlockManagerImpl::OnBluetoothAdapterInitialized( scoped_refptr<device::BluetoothAdapter> adapter) { bluetooth_adapter_ = adapter; @@ -515,8 +493,6 @@ void UnlockManagerImpl::UpdateLockScreen() { AttemptToStartRemoteDeviceLifecycle(); - UpdateProximityMonitorState(); - ScreenlockState new_state = GetScreenlockState(); if (screenlock_state_ == new_state) return; @@ -531,19 +507,6 @@ screenlock_state_ = new_state; } -void UnlockManagerImpl::UpdateProximityMonitorState() { - if (!proximity_monitor_) - return; - - if (is_locked_ && life_cycle_ && - life_cycle_->GetState() == - RemoteDeviceLifeCycle::State::SECURE_CHANNEL_ESTABLISHED) { - proximity_monitor_->Start(); - } else { - proximity_monitor_->Stop(); - } -} - void UnlockManagerImpl::SetWakingUpState(bool is_waking_up) { is_waking_up_ = is_waking_up;
diff --git a/chromeos/components/proximity_auth/unlock_manager_impl.h b/chromeos/components/proximity_auth/unlock_manager_impl.h index 0da19963..497913e 100644 --- a/chromeos/components/proximity_auth/unlock_manager_impl.h +++ b/chromeos/components/proximity_auth/unlock_manager_impl.h
@@ -35,7 +35,6 @@ class UnlockManagerImpl : public UnlockManager, public MessengerObserver, public ProximityMonitorObserver, - public ScreenlockBridge::Observer, chromeos::PowerManagerClient::Observer, public device::BluetoothAdapter::Observer { public: @@ -79,13 +78,6 @@ // ProximityMonitorObserver: void OnProximityStateChanged() override; - // ScreenlockBridge::Observer - void OnScreenDidLock( - ScreenlockBridge::LockHandler::ScreenType screen_type) override; - void OnScreenDidUnlock( - ScreenlockBridge::LockHandler::ScreenType screen_type) override; - void OnFocusedUserChanged(const AccountId& account_id) override; - // Called when the screenlock state changes. void OnScreenLockedOrUnlocked(bool is_locked); @@ -184,9 +176,6 @@ // Used to access the common prefs. Expected to outlive |this| instance. ProximityAuthPrefManager* pref_manager_; - // Whether the screen is currently locked. - bool is_locked_; - // True if the manager is currently processing a user-initiated authentication // attempt, which is initiated when the user pod is clicked. bool is_attempting_auth_;
diff --git a/chromeos/components/proximity_auth/unlock_manager_impl_unittest.cc b/chromeos/components/proximity_auth/unlock_manager_impl_unittest.cc index 81d9606..ac049bd1 100644 --- a/chromeos/components/proximity_auth/unlock_manager_impl_unittest.cc +++ b/chromeos/components/proximity_auth/unlock_manager_impl_unittest.cc
@@ -22,7 +22,6 @@ #include "chromeos/components/proximity_auth/proximity_monitor.h" #include "chromeos/components/proximity_auth/remote_device_life_cycle.h" #include "chromeos/components/proximity_auth/remote_status_update.h" -#include "chromeos/components/proximity_auth/screenlock_bridge.h" #include "chromeos/constants/chromeos_features.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/services/secure_channel/public/cpp/client/fake_client_channel.h" @@ -76,22 +75,22 @@ class MockProximityMonitor : public ProximityMonitor { public: - MockProximityMonitor() : started_(false), stopped_(false) { + MockProximityMonitor(base::OnceClosure destroy_callback) + : destroy_callback_(std::move(destroy_callback)), started_(false) { ON_CALL(*this, IsUnlockAllowed()).WillByDefault(Return(true)); } - ~MockProximityMonitor() override {} + ~MockProximityMonitor() override { std::move(destroy_callback_).Run(); } void Start() override { started_ = true; } - void Stop() override { stopped_ = true; } + void Stop() override {} MOCK_CONST_METHOD0(IsUnlockAllowed, bool()); MOCK_METHOD0(RecordProximityMetricsOnAuthSuccess, void()); bool started() { return started_; } - bool stopped() { return stopped_; } private: + base::OnceClosure destroy_callback_; bool started_; - bool stopped_; DISALLOW_COPY_AND_ASSIGN(MockProximityMonitor); }; @@ -100,8 +99,7 @@ public: TestUnlockManager(ProximityAuthSystem::ScreenlockType screenlock_type, ProximityAuthClient* proximity_auth_client) - : UnlockManagerImpl(screenlock_type, proximity_auth_client, nullptr), - proximity_monitor_(nullptr) {} + : UnlockManagerImpl(screenlock_type, proximity_auth_client, nullptr) {} ~TestUnlockManager() override {} using UnlockManager::OnAuthAttempted; @@ -110,24 +108,29 @@ using MessengerObserver::OnDecryptResponse; using MessengerObserver::OnUnlockResponse; using MessengerObserver::OnDisconnected; - using ScreenlockBridge::Observer::OnScreenDidLock; - using ScreenlockBridge::Observer::OnScreenDidUnlock; - using ScreenlockBridge::Observer::OnFocusedUserChanged; MockProximityMonitor* proximity_monitor() { return proximity_monitor_; } + bool proximity_monitor_destroyed() { return proximity_monitor_destroyed_; } private: std::unique_ptr<ProximityMonitor> CreateProximityMonitor( RemoteDeviceLifeCycle* life_cycle, ProximityAuthPrefManager* pref_manager) override { std::unique_ptr<MockProximityMonitor> proximity_monitor( - new NiceMock<MockProximityMonitor>()); + new NiceMock<MockProximityMonitor>( + base::BindOnce(&TestUnlockManager::OnProximityMonitorDestroyed, + base::Unretained(this)))); + proximity_monitor_destroyed_ = false; + proximity_monitor_ = proximity_monitor.get(); return std::move(proximity_monitor); } + void OnProximityMonitorDestroyed() { proximity_monitor_destroyed_ = true; } + // Owned by the super class. - MockProximityMonitor* proximity_monitor_; + MockProximityMonitor* proximity_monitor_ = nullptr; + bool proximity_monitor_destroyed_ = false; DISALLOW_COPY_AND_ASSIGN(TestUnlockManager); }; @@ -170,8 +173,6 @@ unlock_manager_.reset(); chromeos::DBusThreadManager::Shutdown(); - - ScreenlockBridge::Get()->SetLockHandler(nullptr); } void SetUp() override { @@ -183,7 +184,6 @@ life_cycle_.set_messenger(&messenger_); life_cycle_.set_channel(fake_client_channel_.get()); - ScreenlockBridge::Get()->SetLockHandler(&lock_handler_); chromeos::DBusThreadManager::Initialize(); } @@ -208,6 +208,11 @@ return unlock_manager_ ? unlock_manager_->proximity_monitor() : nullptr; } + bool proximity_monitor_destroyed() { + return unlock_manager_ ? unlock_manager_->proximity_monitor_destroyed() + : false; + } + protected: chromeos::multidevice::RemoteDeviceRef remote_device_; chromeos::multidevice::RemoteDeviceRef local_device_; @@ -443,7 +448,7 @@ unlock_manager_->OnLifeCycleStateChanged(); life_cycle_.ChangeState(RemoteDeviceLifeCycle::State::FINDING_CONNECTION); unlock_manager_->OnLifeCycleStateChanged(); - EXPECT_TRUE(proximity_monitor()->stopped()); + EXPECT_TRUE(proximity_monitor_destroyed()); } TEST_F( @@ -459,6 +464,34 @@ EXPECT_TRUE(proximity_monitor()->started()); } +// Regression test for crbug.com/931929. Capture the case where the phone is +// connected to, connection is lost, and then a new connection is made shortly +// after. +TEST_F(ProximityAuthUnlockManagerImplTest, + SetRemoteDeviceLifeCycle_TwiceConnectedRemoteDeviceLifeCycle) { + CreateUnlockManager(ProximityAuthSystem::SESSION_LOCK); + + unlock_manager_->SetRemoteDeviceLifeCycle(&life_cycle_); + unlock_manager_->OnLifeCycleStateChanged(); + + life_cycle_.ChangeState( + RemoteDeviceLifeCycle::State::SECURE_CHANNEL_ESTABLISHED); + unlock_manager_->OnLifeCycleStateChanged(); + EXPECT_TRUE(proximity_monitor()->started()); + + // Simulate the phone connection being lost. The ProximityMonitor is stale + // and should have been destroyed. + life_cycle_.ChangeState(RemoteDeviceLifeCycle::State::FINDING_CONNECTION); + unlock_manager_->OnLifeCycleStateChanged(); + EXPECT_TRUE(proximity_monitor_destroyed()); + + life_cycle_.ChangeState( + RemoteDeviceLifeCycle::State::SECURE_CHANNEL_ESTABLISHED); + unlock_manager_->OnLifeCycleStateChanged(); + EXPECT_FALSE(proximity_monitor_destroyed()); + EXPECT_TRUE(proximity_monitor()->started()); +} + TEST_F(ProximityAuthUnlockManagerImplTest, BluetoothAdapterNotPresent) { ON_CALL(*bluetooth_adapter_, IsPresent()).WillByDefault(Return(false)); @@ -513,7 +546,7 @@ unlock_manager_->OnLifeCycleStateChanged(); life_cycle_.ChangeState(RemoteDeviceLifeCycle::State::AUTHENTICATION_FAILED); unlock_manager_->OnLifeCycleStateChanged(); - EXPECT_TRUE(proximity_monitor()->stopped()); + EXPECT_TRUE(proximity_monitor_destroyed()); } TEST_F(ProximityAuthUnlockManagerImplTest, @@ -562,44 +595,6 @@ } TEST_F(ProximityAuthUnlockManagerImplTest, - OnScreenDidUnlock_StopsProximityMonitor) { - CreateUnlockManager(ProximityAuthSystem::SESSION_LOCK); - SimulateUserPresentState(); - - unlock_manager_.get()->OnScreenDidUnlock( - ScreenlockBridge::LockHandler::LOCK_SCREEN); - EXPECT_TRUE(proximity_monitor()->stopped()); -} - -TEST_F(ProximityAuthUnlockManagerImplTest, - OnScreenDidLock_StartsProximityMonitor) { - CreateUnlockManager(ProximityAuthSystem::SESSION_LOCK); - unlock_manager_->SetRemoteDeviceLifeCycle(&life_cycle_); - - unlock_manager_.get()->OnScreenDidLock( - ScreenlockBridge::LockHandler::LOCK_SCREEN); - - life_cycle_.ChangeState( - RemoteDeviceLifeCycle::State::SECURE_CHANNEL_ESTABLISHED); - unlock_manager_->OnLifeCycleStateChanged(); - EXPECT_TRUE(proximity_monitor()->started()); -} - -TEST_F(ProximityAuthUnlockManagerImplTest, OnScreenDidLock_SetsWakingUpState) { - CreateUnlockManager(ProximityAuthSystem::SESSION_LOCK); - - EXPECT_CALL(proximity_auth_client_, - UpdateScreenlockState(ScreenlockState::BLUETOOTH_CONNECTING)); - - life_cycle_.ChangeState(RemoteDeviceLifeCycle::State::FINDING_CONNECTION); - unlock_manager_->SetRemoteDeviceLifeCycle(&life_cycle_); - unlock_manager_.get()->OnScreenDidLock( - ScreenlockBridge::LockHandler::LOCK_SCREEN); - - unlock_manager_->OnLifeCycleStateChanged(); -} - -TEST_F(ProximityAuthUnlockManagerImplTest, OnDecryptResponse_NoAuthAttemptInProgress) { CreateUnlockManager(ProximityAuthSystem::SESSION_LOCK); SimulateUserPresentState();
diff --git a/chromeos/constants/chromeos_switches.cc b/chromeos/constants/chromeos_switches.cc index 1c4e236..1ae5364 100644 --- a/chromeos/constants/chromeos_switches.cc +++ b/chromeos/constants/chromeos_switches.cc
@@ -242,9 +242,6 @@ // Disables the multiple display layout UI. const char kDisableMultiDisplayLayout[] = "disable-multi-display-layout"; -// Disables the new File System Provider API based ZIP unpacker. -const char kDisableNewZIPUnpacker[] = "disable-new-zip-unpacker"; - // Disables Office Editing for Docs, Sheets & Slides component app so handlers // won't be registered, making it possible to install another version for // testing. @@ -297,9 +294,6 @@ // Enables ARC VM. const char kEnableArcVm[] = "enable-arcvm"; -// Enables using a random url for captive portal detection. -const char kEnableCaptivePortalRandomUrl[] = "enable-captive-portal-random-url"; - // Enables the Cast Receiver. const char kEnableCastReceiver[] = "enable-cast-receiver";
diff --git a/chromeos/constants/chromeos_switches.h b/chromeos/constants/chromeos_switches.h index e20ad18..23ca5c4 100644 --- a/chromeos/constants/chromeos_switches.h +++ b/chromeos/constants/chromeos_switches.h
@@ -86,7 +86,6 @@ CHROMEOS_EXPORT extern const char kEnableArc[]; CHROMEOS_EXPORT extern const char kEnableArcOobeOptinNoSkip[]; CHROMEOS_EXPORT extern const char kEnableArcVm[]; -CHROMEOS_EXPORT extern const char kEnableCaptivePortalRandomUrl[]; CHROMEOS_EXPORT extern const char kEnableCastReceiver[]; CHROMEOS_EXPORT extern const char kEnableChromevoxDeveloperOption[]; CHROMEOS_EXPORT extern const char kEnableConsumerKiosk[];
diff --git a/chromeos/dbus/OWNERS b/chromeos/dbus/OWNERS index 7058090..97637bf0 100644 --- a/chromeos/dbus/OWNERS +++ b/chromeos/dbus/OWNERS
@@ -10,5 +10,7 @@ per-file *diagnosticsd*=emaxx@chromium.org per-file *diagnosticsd*=pmarko@chromium.org per-file *power*=derat@chromium.org +per-file *smb_provider*=amistry@chromium.org per-file *smb_provider*=baileyberro@chromium.org +per-file *smb_provider*=slangley@chromium.org per-file *smb_provider*=zentaro@chromium.org
diff --git a/chromeos/network/network_configuration_handler.cc b/chromeos/network/network_configuration_handler.cc index 939c91f0..ff4788dd 100644 --- a/chromeos/network/network_configuration_handler.cc +++ b/chromeos/network/network_configuration_handler.cc
@@ -347,12 +347,6 @@ std::string network_id = shill_property_util::GetNetworkIdFromProperties(shill_properties); - if (NetworkTypePattern::Ethernet().MatchesType(type)) { - InvokeErrorCallback(network_id, error_callback, - "ConfigureServiceForProfile: Invalid type: " + type); - return; - } - std::unique_ptr<base::DictionaryValue> properties_to_set( shill_properties.DeepCopy());
diff --git a/chromeos/network/policy_applicator.cc b/chromeos/network/policy_applicator.cc index ae35431..c9b4cf70 100644 --- a/chromeos/network/policy_applicator.cc +++ b/chromeos/network/policy_applicator.cc
@@ -43,6 +43,10 @@ return it->second.get(); } +// Special service name in shill remembering settings across ethernet services. +// Chrome should not attempt to configure / delete this. +const char kEthernetAnyService[] = "ethernet_any"; + } // namespace PolicyApplicator::PolicyApplicator( @@ -99,6 +103,12 @@ std::string entry; it->GetAsString(&entry); + // Skip "ethernet_any", as this is used by shill internally to persist + // ethernet settings and the policy application logic should not mess with + // it. + if (entry == kEthernetAnyService) + continue; + pending_get_entry_calls_.insert(entry); DBusThreadManager::Get()->GetShillProfileClient()->GetEntry( dbus::ObjectPath(profile_.path),
diff --git a/components/arc/BUILD.gn b/components/arc/BUILD.gn index e645d896..1ca32ba 100644 --- a/components/arc/BUILD.gn +++ b/components/arc/BUILD.gn
@@ -68,7 +68,6 @@ "volume_mounter/arc_volume_mounter_bridge.h", "wake_lock/arc_wake_lock_bridge.cc", "wake_lock/arc_wake_lock_bridge.h", - "wake_lock/wake_lock_observer.h", ] public_deps = [
diff --git a/components/arc/volume_mounter/arc_volume_mounter_bridge.cc b/components/arc/volume_mounter/arc_volume_mounter_bridge.cc index 7b131a3..6cab4b1 100644 --- a/components/arc/volume_mounter/arc_volume_mounter_bridge.cc +++ b/components/arc/volume_mounter/arc_volume_mounter_bridge.cc
@@ -8,6 +8,7 @@ #include "base/logging.h" #include "base/memory/singleton.h" #include "base/task/post_task.h" +#include "chromeos/constants/chromeos_features.h" #include "chromeos/disks/disk.h" #include "chromeos/disks/disk_mount_manager.h" #include "components/arc/arc_bridge_service.h" @@ -20,6 +21,11 @@ namespace { +// TODO(crbug.com/929031): Move MyFiles constants to a common place. +constexpr char kMyFilesPath[] = "/home/chronos/user/MyFiles"; +constexpr char kMyFilesVolumeName[] = "My files"; +// Dummy UUID for MyFiles volume. +constexpr char kMyFilesUuid[] = "0000000000000000000000000000CAFEF00D2019"; constexpr char kDummyUuid[] = "00000000000000000000000000000000DEADBEEF"; // Singleton factory for ArcVolumeMounterBridge. @@ -66,12 +72,35 @@ // Sends MountEvents of all existing MountPoints in cros-disks. void ArcVolumeMounterBridge::SendAllMountEvents() { + if (base::FeatureList::IsEnabled(chromeos::features::kMyFilesVolume)) + SendMountEventForMyFiles(); + for (const auto& keyValue : DiskMountManager::GetInstance()->mount_points()) { OnMountEvent(DiskMountManager::MountEvent::MOUNTING, chromeos::MountError::MOUNT_ERROR_NONE, keyValue.second); } } +// Notifies ARC of MyFiles volume by sending a mount event. +void ArcVolumeMounterBridge::SendMountEventForMyFiles() { + mojom::VolumeMounterInstance* volume_mounter_instance = + ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service_->volume_mounter(), + OnMountEvent); + + if (!volume_mounter_instance) + return; + + // TODO(niwa): Send localized string for "My files". + std::string device_label = kMyFilesVolumeName; + + // TODO(niwa): Add a new DeviceType enum value for MyFiles. + chromeos::DeviceType device_type = chromeos::DeviceType::DEVICE_TYPE_SD; + + volume_mounter_instance->OnMountEvent(mojom::MountPointInfo::New( + chromeos::disks::DiskMountManager::MOUNTING, kMyFilesPath, kMyFilesPath, + kMyFilesUuid, device_label, device_type)); +} + void ArcVolumeMounterBridge::OnConnectionReady() { // Deferring the SendAllMountEvents as a task to current thread to not // block the mojo request since SendAllMountEvents might takes non trivial
diff --git a/components/arc/volume_mounter/arc_volume_mounter_bridge.h b/components/arc/volume_mounter/arc_volume_mounter_bridge.h index 6da3adde..1e01b646 100644 --- a/components/arc/volume_mounter/arc_volume_mounter_bridge.h +++ b/components/arc/volume_mounter/arc_volume_mounter_bridge.h
@@ -55,6 +55,8 @@ private: void SendAllMountEvents(); + void SendMountEventForMyFiles(); + ArcBridgeService* const arc_bridge_service_; // Owned by ArcServiceManager. base::WeakPtrFactory<ArcVolumeMounterBridge> weak_ptr_factory_;
diff --git a/components/arc/wake_lock/arc_wake_lock_bridge.cc b/components/arc/wake_lock/arc_wake_lock_bridge.cc index 9cb81ea..8c526ca 100644 --- a/components/arc/wake_lock/arc_wake_lock_bridge.cc +++ b/components/arc/wake_lock/arc_wake_lock_bridge.cc
@@ -8,9 +8,6 @@ #include "base/bind.h" #include "base/logging.h" #include "base/memory/singleton.h" -#include "base/observer_list.h" -#include "base/task/post_task.h" -#include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power_policy_controller.h" #include "components/arc/arc_bridge_service.h" #include "components/arc/arc_browser_context_keyed_service_factory_base.h" @@ -50,8 +47,7 @@ // WakeLockRequester requests a wake lock from the device service in response // to wake lock requests of a given type from Android. A count is kept of -// outstanding Android requests so that only a single actual wake lock is -// used. +// outstanding Android requests so that only a single actual wake lock is used. class ArcWakeLockBridge::WakeLockRequester { public: WakeLockRequester(device::mojom::WakeLockType type, @@ -81,9 +77,6 @@ } wake_lock_->RequestWakeLock(); - - for (auto& observer : observers_) - observer.OnWakeLockAcquire(); } // Decrements the number of outstanding Android requests. Cancels the device @@ -102,27 +95,10 @@ } DCHECK(wake_lock_); - DVLOG(1) << "Partial wake lock force release. Count: " << wake_lock_count_; + DVLOG(1) << "Partial wake force release. Count: " << wake_lock_count_; wake_lock_->CancelWakeLock(); - - for (auto& observer : observers_) - observer.OnWakeLockRelease(); } - bool IsWakeLockHeld() const { return wake_lock_count_ > 0; } - - void AddObserver(WakeLockObserver* observer) { - DCHECK(observer); - observers_.AddObserver(observer); - } - - void RemoveObserver(WakeLockObserver* observer) { - DCHECK(observer); - observers_.RemoveObserver(observer); - } - - bool HasObservers() const { return observers_.might_have_observers(); } - // Runs the message loop until replies have been received for all pending // requests on |wake_lock_|. void FlushForTesting() { @@ -143,8 +119,6 @@ // Lazily initialized in response to first request. device::mojom::WakeLockPtr wake_lock_; - base::ObserverList<WakeLockObserver>::Unchecked observers_; - DISALLOW_COPY_AND_ASSIGN(WakeLockRequester); }; @@ -165,9 +139,6 @@ return ArcWakeLockBridgeFactory::GetForBrowserContextForTesting(context); } -constexpr base::TimeDelta ArcWakeLockBridge::kDarkResumeWakeLockCheckTimeout; -constexpr base::TimeDelta ArcWakeLockBridge::kDarkResumeHardTimeout; - ArcWakeLockBridge::ArcWakeLockBridge(content::BrowserContext* context, ArcBridgeService* bridge_service) : arc_bridge_service_(bridge_service), @@ -175,16 +146,11 @@ weak_ptr_factory_(this) { arc_bridge_service_->wake_lock()->SetHost(this); arc_bridge_service_->wake_lock()->AddObserver(this); - chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver( - this); } ArcWakeLockBridge::~ArcWakeLockBridge() { arc_bridge_service_->wake_lock()->RemoveObserver(this); arc_bridge_service_->wake_lock()->SetHost(nullptr); - // In case some this wasn't cleared while handling a dark resume. - GetWakeLockRequester(device::mojom::WakeLockType::kPreventAppSuspension) - ->RemoveObserver(this); } void ArcWakeLockBridge::OnConnectionClosed() { @@ -192,6 +158,11 @@ wake_lock_requesters_.clear(); } +void ArcWakeLockBridge::FlushWakeLocksForTesting() { + for (const auto& it : wake_lock_requesters_) + it.second->FlushForTesting(); +} + void ArcWakeLockBridge::AcquirePartialWakeLock( AcquirePartialWakeLockCallback callback) { GetWakeLockRequester(device::mojom::WakeLockType::kPreventAppSuspension) @@ -206,104 +177,6 @@ std::move(callback).Run(true); } -void ArcWakeLockBridge::DarkSuspendImminent() { - DVLOG(1) << __func__; - suspend_readiness_cb_ = chromeos::DBusThreadManager::Get() - ->GetPowerManagerClient() - ->GetSuspendReadinessCallback(FROM_HERE); - // Post task that will check for any wake locks acquired in dark resume. - base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&ArcWakeLockBridge::HandleDarkResumeWakeLockCheckTimeout, - dark_resume_weak_ptr_factory_.GetWeakPtr()), - kDarkResumeWakeLockCheckTimeout); -} - -void ArcWakeLockBridge::SuspendDone(const base::TimeDelta& sleep_duration) { - DVLOG(1) << __func__; - // Clear any dark resume state when the device resumes. - ClearDarkResumeState(); -} - -void ArcWakeLockBridge::OnWakeLockRelease() { - // This observer is only registered once dark resume starts. - DCHECK(suspend_readiness_cb_); - DVLOG(1) << __func__; - - // At this point the instance has done its work, tell the power daemon to - // re-suspend. - std::move(suspend_readiness_cb_).Run(); - ClearDarkResumeState(); -} - -void ArcWakeLockBridge::FlushWakeLocksForTesting() { - for (const auto& it : wake_lock_requesters_) - it.second->FlushForTesting(); -} - -bool ArcWakeLockBridge::IsSuspendReadinessStateSetForTesting() const { - return !suspend_readiness_cb_.is_null(); -} - -bool ArcWakeLockBridge::WakeLockHasObserversForTesting( - device::mojom::WakeLockType type) { - return GetWakeLockRequester( - device::mojom::WakeLockType::kPreventAppSuspension) - ->HasObservers(); -} - -void ArcWakeLockBridge::HandleDarkResumeWakeLockCheckTimeout() { - DVLOG(1) << __func__; - DCHECK_CALLED_ON_VALID_SEQUENCE(dark_resume_tasks_sequence_checker_); - // Check if any wake locks are held at this point. If not, then it's assumed - // the instance either acquired and released one or had no reason to acquire - // one in the first place. If it wants to after this then too bad, tell the - // power daemon to re-suspend and invalidate any other state associated with - // dark resume. - if (!GetWakeLockRequester(device::mojom::WakeLockType::kPreventAppSuspension) - ->IsWakeLockHeld()) { - DVLOG(1) << "Wake lock not held during check"; - std::move(suspend_readiness_cb_).Run(); - ClearDarkResumeState(); - return; - } - - DVLOG(1) << "Wake lock held during check"; - // If a wake lock is held then register for a wake lock release - // notification. As soon as it's released tell power daemon to re-suspend. - // If the instance takes a long time then tell powerd daemon to re-suspend - // after a hard timeout irrespective of wake locks held. - GetWakeLockRequester(device::mojom::WakeLockType::kPreventAppSuspension) - ->AddObserver(this); - - // Post task that will tell the power daemon to re-suspend after a dark - // resume irrespective of any state. This is a last resort timeout to ensure - // the device doesn't stay up indefinitely in dark resume. - base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&ArcWakeLockBridge::HandleDarkResumeHardTimeout, - dark_resume_weak_ptr_factory_.GetWeakPtr()), - kDarkResumeHardTimeout); -} - -void ArcWakeLockBridge::HandleDarkResumeHardTimeout() { - DVLOG(1) << __func__; - DCHECK_CALLED_ON_VALID_SEQUENCE(dark_resume_tasks_sequence_checker_); - // Enough is enough. Tell power daemon it's okay to suspend. - DCHECK(suspend_readiness_cb_); - std::move(suspend_readiness_cb_).Run(); - ClearDarkResumeState(); -} - -void ArcWakeLockBridge::ClearDarkResumeState() { - DVLOG(1) << __func__; - // Invalidate all other state associated with dark resume. - suspend_readiness_cb_.Reset(); - GetWakeLockRequester(device::mojom::WakeLockType::kPreventAppSuspension) - ->RemoveObserver(this); - dark_resume_weak_ptr_factory_.InvalidateWeakPtrs(); -} - ArcWakeLockBridge::WakeLockRequester* ArcWakeLockBridge::GetWakeLockRequester( device::mojom::WakeLockType type) { auto it = wake_lock_requesters_.find(type);
diff --git a/components/arc/wake_lock/arc_wake_lock_bridge.h b/components/arc/wake_lock/arc_wake_lock_bridge.h index 545b9b0..67ce3ee 100644 --- a/components/arc/wake_lock/arc_wake_lock_bridge.h +++ b/components/arc/wake_lock/arc_wake_lock_bridge.h
@@ -10,11 +10,8 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" -#include "chromeos/dbus/power_manager_client.h" #include "components/arc/common/wake_lock.mojom.h" #include "components/arc/connection_observer.h" -#include "components/arc/wake_lock/wake_lock_observer.h" #include "components/keyed_service/core/keyed_service.h" #include "content/public/common/service_manager_connection.h" #include "mojo/public/cpp/bindings/binding.h" @@ -33,9 +30,7 @@ // Sets wake up timers / alarms based on calls from the instance. class ArcWakeLockBridge : public KeyedService, public ConnectionObserver<mojom::WakeLockInstance>, - public mojom::WakeLockHost, - public chromeos::PowerManagerClient::Observer, - public WakeLockObserver { + public mojom::WakeLockHost { public: // Returns the factory instance for this class. static BrowserContextKeyedServiceFactory* GetFactory(); @@ -59,36 +54,13 @@ // ConnectionObserver<mojom::WakeLockInstance>::Observer overrides. void OnConnectionClosed() override; - // mojom::WakeLockHost overrides. - void AcquirePartialWakeLock(AcquirePartialWakeLockCallback callback) override; - void ReleasePartialWakeLock(ReleasePartialWakeLockCallback callback) override; - - // chromeos::PowerManagerClient::Observer overrides. - void DarkSuspendImminent() override; - void SuspendDone(const base::TimeDelta& sleep_duration) override; - - // WakeLockObserver override. - void OnWakeLockRelease() override; - // Runs the message loop until replies have been received for all pending // device service requests in |wake_lock_requesters_|. void FlushWakeLocksForTesting(); - // Checks if |suspend_readiness_cb_| is set. - bool IsSuspendReadinessStateSetForTesting() const; - - // Returns true iff wake lock of |type| has observers. - bool WakeLockHasObserversForTesting(device::mojom::WakeLockType type); - - // Time after a dark resume when wake lock count is checked and a decision is - // made to re-suspend or wait for wake lock release. - static constexpr base::TimeDelta kDarkResumeWakeLockCheckTimeout = - base::TimeDelta::FromSeconds(3); - - // Max time to wait for wake lock release after a wake lock check after a dark - // resume. After this time the system is asked to re-suspend. - static constexpr base::TimeDelta kDarkResumeHardTimeout = - base::TimeDelta::FromSeconds(10); + // mojom::WakeLockHost overrides. + void AcquirePartialWakeLock(AcquirePartialWakeLockCallback callback) override; + void ReleasePartialWakeLock(ReleasePartialWakeLockCallback callback) override; private: class WakeLockRequester; @@ -96,20 +68,6 @@ // Returns the WakeLockRequester for |type|, creating one if needed. WakeLockRequester* GetWakeLockRequester(device::mojom::WakeLockType type); - // Runs |kDarkResumeWakeLockCheckTimeout| time delta after a dark resume. - // Checks if app suspension wake locks (partial wake locks for Android) are - // held. If no wake locks are held then re-suspends the device else schedules - // |HandleDarkResumeHardTimeout|. - void HandleDarkResumeWakeLockCheckTimeout(); - - // Runs |kDarkResumeHardTimeout| time delta after a - // |HandleDarkResumeWakeLockCheckTimeout|. Clears all dark resume state and - // re-suspends the device. - void HandleDarkResumeHardTimeout(); - - // Clears all state associated with dark resume. - void ClearDarkResumeState(); - ArcBridgeService* const arc_bridge_service_; // Owned by ArcServiceManager. // If non-null, used instead of the process-wide connector to fetch services. @@ -120,21 +78,8 @@ std::map<device::mojom::WakeLockType, std::unique_ptr<WakeLockRequester>> wake_lock_requesters_; - // Called when system is ready to supend after a |DarkSupendImminent| i.e. - // after a dark resume. - base::OnceClosure suspend_readiness_cb_; - mojo::Binding<mojom::WakeLockHost> binding_; - // Used for checking if |DarkResumeWakeLockCheckTimeout| and - // |DarkResumeHardTimeout| run on the same sequence. - SEQUENCE_CHECKER(dark_resume_tasks_sequence_checker_); - - // Factory used to schedule and cancel - // |HandleDarkResumeWakeLockCheckTimeout| and |HandleDarkResumeHardTimeout|. - // At any point either none or one of these tasks is in flight. - base::WeakPtrFactory<ArcWakeLockBridge> dark_resume_weak_ptr_factory_{this}; - base::WeakPtrFactory<ArcWakeLockBridge> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(ArcWakeLockBridge);
diff --git a/components/arc/wake_lock/arc_wake_lock_bridge_unittest.cc b/components/arc/wake_lock/arc_wake_lock_bridge_unittest.cc index 216bed0..e1d7f05 100644 --- a/components/arc/wake_lock/arc_wake_lock_bridge_unittest.cc +++ b/components/arc/wake_lock/arc_wake_lock_bridge_unittest.cc
@@ -10,8 +10,6 @@ #include "base/bind.h" #include "base/run_loop.h" #include "base/test/scoped_task_environment.h" -#include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_power_manager_client.h" #include "components/arc/arc_bridge_service.h" #include "components/arc/common/power.mojom.h" #include "components/arc/test/connection_holder_util.h" @@ -33,10 +31,6 @@ base::test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME), wake_lock_provider_( connector_factory_.RegisterInstance(device::mojom::kServiceName)) { - fake_power_manager_client_ = new chromeos::FakePowerManagerClient; - chromeos::DBusThreadManager::GetSetterForTesting()->SetPowerManagerClient( - base::WrapUnique(fake_power_manager_client_)); - bridge_service_ = std::make_unique<ArcBridgeService>(); wake_lock_bridge_ = std::make_unique<ArcWakeLockBridge>(nullptr, bridge_service_.get()); @@ -48,27 +42,6 @@ ~ArcWakeLockBridgeTest() override { DestroyWakeLockInstance(); } protected: - // Creates a FakeWakeLockInstance for |bridge_service_|. This results in - // ArcWakeLockBridge::OnInstanceReady() being called. - void CreateWakeLockInstance() { - instance_ = std::make_unique<FakeWakeLockInstance>(); - bridge_service_->wake_lock()->SetInstance(instance_.get()); - WaitForInstanceReady(bridge_service_->wake_lock()); - } - - // Destroys the FakeWakeLockInstance. This results in - // ArcWakeLockBridge::OnInstanceClosed() being called. - void DestroyWakeLockInstance() { - if (!instance_) - return; - bridge_service_->wake_lock()->CloseInstance(instance_.get()); - instance_.reset(); - } - - device::TestWakeLockProvider* GetWakeLockProvider() { - return &wake_lock_provider_; - } - // Returns true iff there is no failure acquiring a system wake lock. bool AcquirePartialWakeLock() { base::RunLoop loop; @@ -91,29 +64,30 @@ return result; } - // Return true iff all dark resume related state is set i.e the suspend - // readiness callback is set and wake lock release event has observers. - bool IsDarkResumeStateSet() const { - return wake_lock_bridge_->IsSuspendReadinessStateSetForTesting() && - wake_lock_bridge_->WakeLockHasObserversForTesting( - WakeLockType::kPreventAppSuspension); + // Creates a FakeWakeLockInstance for |bridge_service_|. This results in + // ArcWakeLockBridge::OnInstanceReady() being called. + void CreateWakeLockInstance() { + instance_ = std::make_unique<FakeWakeLockInstance>(); + bridge_service_->wake_lock()->SetInstance(instance_.get()); + WaitForInstanceReady(bridge_service_->wake_lock()); } - // Return true iff all dark resume related state is reset. This should be true - // when device exits dark resume either by re-suspending or transitioning to - // full resume. - bool IsDarkResumeStateReset() const { - return !wake_lock_bridge_->WakeLockHasObserversForTesting( - WakeLockType::kPreventAppSuspension) && - !wake_lock_bridge_->IsSuspendReadinessStateSetForTesting(); + // Destroys the FakeWakeLockInstance. This results in + // ArcWakeLockBridge::OnInstanceClosed() being called. + void DestroyWakeLockInstance() { + if (!instance_) + return; + bridge_service_->wake_lock()->CloseInstance(instance_.get()); + instance_.reset(); } - base::test::ScopedTaskEnvironment scoped_task_environment_; - - // Owned by chromeos::DBusThreadManager. - chromeos::FakePowerManagerClient* fake_power_manager_client_; + device::TestWakeLockProvider* GetWakeLockProvider() { + return &wake_lock_provider_; + } private: + base::test::ScopedTaskEnvironment scoped_task_environment_; + service_manager::TestConnectorFactory connector_factory_; device::TestWakeLockProvider wake_lock_provider_; @@ -178,94 +152,4 @@ WakeLockType::kPreventAppSuspension)); } -TEST_F(ArcWakeLockBridgeTest, CheckSuspendAfterDarkResumeNoWakeLocksHeld) { - // Trigger a dark resume event, move time forward to trigger a wake lock check - // and check if a re-suspend happened if no wake locks were acquired. - fake_power_manager_client_->SendDarkSuspendImminent(); - scoped_task_environment_.FastForwardBy( - ArcWakeLockBridge::kDarkResumeWakeLockCheckTimeout); - base::RunLoop run_loop; - run_loop.RunUntilIdle(); - EXPECT_TRUE(IsDarkResumeStateReset()); - - // Trigger a dark resume event, acquire and release a wake lock and move time - // forward to trigger a wake lock check. The device should re-suspend in this - // case since no wake locks were held at the time of the wake lock check. - fake_power_manager_client_->SendDarkSuspendImminent(); - EXPECT_TRUE(AcquirePartialWakeLock()); - EXPECT_TRUE(ReleasePartialWakeLock()); - scoped_task_environment_.FastForwardBy( - ArcWakeLockBridge::kDarkResumeWakeLockCheckTimeout); - base::RunLoop run_loop2; - run_loop2.RunUntilIdle(); - EXPECT_TRUE(IsDarkResumeStateReset()); -} - -TEST_F(ArcWakeLockBridgeTest, CheckSuspendAfterDarkResumeWakeLocksHeld) { - // Trigger a dark resume event, acquire a wake lock and move time forward to a - // wake lock check. At this point the system shouldn't re-suspend i.e. the - // suspend readiness callback should be set and wake lock release should have - // observers. - fake_power_manager_client_->SendDarkSuspendImminent(); - EXPECT_TRUE(AcquirePartialWakeLock()); - scoped_task_environment_.FastForwardBy( - ArcWakeLockBridge::kDarkResumeWakeLockCheckTimeout); - base::RunLoop run_loop; - run_loop.RunUntilIdle(); - EXPECT_TRUE(IsDarkResumeStateSet()); - - // Move time forward by < |kDarkResumeHardTimeout| and release the - // partial wake lock.This should instantaneously re-suspend the device. - scoped_task_environment_.FastForwardBy( - ArcWakeLockBridge::kDarkResumeHardTimeout - - base::TimeDelta::FromSeconds(1)); - EXPECT_TRUE(ReleasePartialWakeLock()); - base::RunLoop run_loop2; - run_loop2.RunUntilIdle(); - EXPECT_TRUE(IsDarkResumeStateReset()); -} - -TEST_F(ArcWakeLockBridgeTest, CheckSuspendAfterDarkResumeHardTimeout) { - // Trigger a dark resume event, acquire a wake lock and move time forward to a - // wake lock check. At this point the system shouldn't re-suspend i.e. the - // suspend readiness callback should be set and wake lock release should have - // observers. - fake_power_manager_client_->SendDarkSuspendImminent(); - EXPECT_TRUE(AcquirePartialWakeLock()); - scoped_task_environment_.FastForwardBy( - ArcWakeLockBridge::kDarkResumeWakeLockCheckTimeout); - base::RunLoop run_loop; - run_loop.RunUntilIdle(); - EXPECT_TRUE(IsDarkResumeStateSet()); - - // Move time forward by |kDarkResumeHardTimeout|. At this point the - // device should re-suspend even though the wake lock is acquired. - scoped_task_environment_.FastForwardBy( - ArcWakeLockBridge::kDarkResumeHardTimeout); - EXPECT_EQ(1, GetWakeLockProvider()->GetActiveWakeLocksOfType( - WakeLockType::kPreventAppSuspension)); - base::RunLoop run_loop2; - run_loop2.RunUntilIdle(); - EXPECT_TRUE(IsDarkResumeStateReset()); -} - -TEST_F(ArcWakeLockBridgeTest, CheckStateResetAfterSuspendDone) { - // Trigger a dark resume event, acquire a wake lock and move time forward to a - // wake lock check. At this point the system shouldn't re-suspend i.e. the - // suspend readiness callback should be set and wake lock release should have - // observers. - fake_power_manager_client_->SendDarkSuspendImminent(); - EXPECT_TRUE(AcquirePartialWakeLock()); - scoped_task_environment_.FastForwardBy( - ArcWakeLockBridge::kDarkResumeWakeLockCheckTimeout); - base::RunLoop run_loop; - run_loop.RunUntilIdle(); - EXPECT_TRUE(IsDarkResumeStateSet()); - - // Trigger suspend done event. Check if state is reset as dark resume would be - // exited. - fake_power_manager_client_->SendSuspendDone(); - EXPECT_TRUE(IsDarkResumeStateReset()); -} - } // namespace arc
diff --git a/components/arc/wake_lock/wake_lock_observer.h b/components/arc/wake_lock/wake_lock_observer.h deleted file mode 100644 index 45072a67..0000000 --- a/components/arc/wake_lock/wake_lock_observer.h +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_ARC_WAKE_LOCK_WAKE_LOCK_OBSERVER_H_ -#define COMPONENTS_ARC_WAKE_LOCK_WAKE_LOCK_OBSERVER_H_ - -namespace arc { - -// This is an interface for classes that want to learn when Android wake locks -// are acquired or released. Observer should register themselves by calling the -// overriding class's AddObserver() method. -class WakeLockObserver { - public: - virtual ~WakeLockObserver() = default; - - // Called when the tracked wake lock is acquired the first time i.e. - // number of holders increases to 1. - virtual void OnWakeLockAcquire() {} - - // Called when the tracked wake lock is released the last time i.e. the number - // of holders goes to 0. - virtual void OnWakeLockRelease() {} -}; - -} // namespace arc - -#endif // COMPONENTS_ARC_WAKE_LOCK_WAKE_LOCK_OBSERVER_H_
diff --git a/components/autofill/content/renderer/form_tracker.cc b/components/autofill/content/renderer/form_tracker.cc index 5aef042..f5360b1 100644 --- a/components/autofill/content/renderer/form_tracker.cc +++ b/components/autofill/content/renderer/form_tracker.cc
@@ -156,8 +156,9 @@ FireSubmissionIfFormDisappear(SubmissionSource::SAME_DOCUMENT_NAVIGATION); } -void FormTracker::DidStartProvisionalLoad(WebDocumentLoader* document_loader, - bool is_content_initiated) { +void FormTracker::DidStartNavigation( + const GURL& url, + base::Optional<blink::WebNavigationType> navigation_type) { DCHECK_CALLED_ON_VALID_SEQUENCE(form_tracker_sequence_checker_); blink::WebLocalFrame* navigated_frame = render_frame()->GetWebFrame(); // Ony handle main frame. @@ -168,15 +169,11 @@ // the user is performing actions outside the page (e.g. typed url, // history navigation). We don't want to trigger saving in these cases. - // We are interested only in content initiated navigations. Explicit browser - // initiated navigations (e.g. via omnibox) are discarded here. Similarly - // PlzNavigate navigations originating from the browser are discarded because - // they were already processed as a content initiated one - // (i.e. DidStartProvisionalLoad is called twice in this case). The check for - // kWebNavigationTypeLinkClicked is reliable only for content initiated - // navigations. - if (is_content_initiated && document_loader->GetNavigationType() != - blink::kWebNavigationTypeLinkClicked) { + // We are interested only in content-initiated navigations. Explicit browser + // initiated navigations (e.g. via omnibox) don't have a navigation type + // and are discarded here. + if (navigation_type.has_value() && + navigation_type.value() != blink::kWebNavigationTypeLinkClicked) { FireProbablyFormSubmitted(); } }
diff --git a/components/autofill/content/renderer/form_tracker.h b/components/autofill/content/renderer/form_tracker.h index b7e7bcd4..b31d9b0 100644 --- a/components/autofill/content/renderer/form_tracker.h +++ b/components/autofill/content/renderer/form_tracker.h
@@ -91,8 +91,9 @@ // content::RenderFrameObserver: void DidCommitProvisionalLoad(bool is_same_document_navigation, ui::PageTransition transition) override; - void DidStartProvisionalLoad(blink::WebDocumentLoader* document_loader, - bool is_content_initiated) override; + void DidStartNavigation( + const GURL& url, + base::Optional<blink::WebNavigationType> navigation_type) override; void FrameDetached() override; void WillSendSubmitEvent(const blink::WebFormElement& form) override; void WillSubmitForm(const blink::WebFormElement& form) override;
diff --git a/components/autofill/content/renderer/password_autofill_agent.cc b/components/autofill/content/renderer/password_autofill_agent.cc index f628dd6..e46c751 100644 --- a/components/autofill/content/renderer/password_autofill_agent.cc +++ b/components/autofill/content/renderer/password_autofill_agent.cc
@@ -1347,9 +1347,8 @@ base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); } -void PasswordAutofillAgent::DidStartProvisionalLoad( - blink::WebDocumentLoader* document_loader, - bool is_content_initiated) { +void PasswordAutofillAgent::ReadyToCommitNavigation( + blink::WebDocumentLoader* document_loader) { std::unique_ptr<RendererSavePasswordProgressLogger> logger; if (logging_state_active_) { logger.reset(new RendererSavePasswordProgressLogger(
diff --git a/components/autofill/content/renderer/password_autofill_agent.h b/components/autofill/content/renderer/password_autofill_agent.h index 01cc65b..520d2ccb 100644 --- a/components/autofill/content/renderer/password_autofill_agent.h +++ b/components/autofill/content/renderer/password_autofill_agent.h
@@ -248,8 +248,8 @@ // RenderFrameObserver: void DidFinishDocumentLoad() override; void DidFinishLoad() override; - void DidStartProvisionalLoad(blink::WebDocumentLoader* document_loader, - bool is_content_initiated) override; + void ReadyToCommitNavigation( + blink::WebDocumentLoader* document_loader) override; void WillCommitProvisionalLoad() override; void DidCommitProvisionalLoad(bool is_same_document_navigation, ui::PageTransition transition) override;
diff --git a/components/autofill/core/browser/personal_data_manager.cc b/components/autofill/core/browser/personal_data_manager.cc index 9c45f39..30383df 100644 --- a/components/autofill/core/browser/personal_data_manager.cc +++ b/components/autofill/core/browser/personal_data_manager.cc
@@ -1122,7 +1122,7 @@ const AutofillType& type, const base::string16& field_contents, bool field_is_autofilled, - const std::vector<ServerFieldType>& other_field_types) { + const std::vector<ServerFieldType>& field_types) { if (IsInAutofillSuggestionsDisabledExperiment()) return std::vector<Suggestion>(); @@ -1159,15 +1159,15 @@ // Don't show two suggestions if one is a subset of the other. std::vector<AutofillProfile*> unique_matched_profiles; std::vector<Suggestion> unique_suggestions = - suggestion_selection::GetUniqueSuggestions(other_field_types, app_locale_, + suggestion_selection::GetUniqueSuggestions(field_types, app_locale_, matched_profiles, suggestions, &unique_matched_profiles); // Generate disambiguating labels based on the list of matches. std::vector<base::string16> labels; - AutofillProfile::CreateInferredLabels( - unique_matched_profiles, &other_field_types, type.GetStorableType(), 1, - app_locale_, &labels); + AutofillProfile::CreateInferredLabels(unique_matched_profiles, &field_types, + type.GetStorableType(), 1, app_locale_, + &labels); DCHECK_EQ(unique_suggestions.size(), labels.size()); for (size_t i = 0; i < labels.size(); i++) { unique_suggestions[i].label = labels[i];
diff --git a/components/autofill/core/browser/personal_data_manager.h b/components/autofill/core/browser/personal_data_manager.h index 69e4b90..d1d364ee 100644 --- a/components/autofill/core/browser/personal_data_manager.h +++ b/components/autofill/core/browser/personal_data_manager.h
@@ -269,15 +269,16 @@ const AutofillType& type, std::vector<AutofillProfile*>* profiles); - // Loads profiles that can suggest data for |type|. |field_contents| is the - // part the user has already typed. |field_is_autofilled| is true if the field - // has already been autofilled. |other_field_types| represents the rest of - // form. + // Returns Suggestions corresponding to the focused field's |type| and + // |field_contents|, i.e. what the user has typed. |field_is_autofilled| is + // true if the field has already been autofilled, and |field_types| stores the + // types of all the form's input fields, including the field with which the + // user is interacting. std::vector<Suggestion> GetProfileSuggestions( const AutofillType& type, const base::string16& field_contents, bool field_is_autofilled, - const std::vector<ServerFieldType>& other_field_types); + const std::vector<ServerFieldType>& field_types); // Tries to delete disused addresses once per major version if the // feature is enabled.
diff --git a/components/autofill/core/browser/strike_database.cc b/components/autofill/core/browser/strike_database.cc index 1f4e4aa..4bcc900 100644 --- a/components/autofill/core/browser/strike_database.cc +++ b/components/autofill/core/browser/strike_database.cc
@@ -72,7 +72,8 @@ ClearAllProtoStrikesForKey(key, base::DoNothing()); } -void StrikeDatabase::ClearAllStrikes(const std::string& project_prefix) { +void StrikeDatabase::ClearAllStrikesForProject( + const std::string& project_prefix) { std::vector<std::string> keys_to_delete; for (std::pair<std::string, StrikeData> entry : strike_map_cache_) { if (entry.first.find(project_prefix) == 0) { @@ -83,6 +84,11 @@ ClearStrikes(key); } +void StrikeDatabase::ClearAllStrikes() { + strike_map_cache_.clear(); + ClearAllProtoStrikes(base::DoNothing()); +} + StrikeDatabase::StrikeDatabase() : db_(nullptr), database_dir_(base::FilePath(nullptr)),
diff --git a/components/autofill/core/browser/strike_database.h b/components/autofill/core/browser/strike_database.h index 479a549..3359224 100644 --- a/components/autofill/core/browser/strike_database.h +++ b/components/autofill/core/browser/strike_database.h
@@ -63,13 +63,17 @@ // Returns strike count from in-memory cache. int GetStrikes(const std::string key); - // Removes all database entries from in-memory cache and underlying + // Removes database entry for |key| from in-memory cache and underlying // ProtoDatabase. void ClearStrikes(const std::string key); // Removes all database entries from in-memory cache and underlying // ProtoDatabase for the whole project. - void ClearAllStrikes(const std::string& project_prefix); + void ClearAllStrikesForProject(const std::string& project_prefix); + + // Removes all database entries from in-memory cache and underlying + // ProtoDatabase. + void ClearAllStrikes(); protected: friend class StrikeDatabaseIntegratorBase; @@ -112,7 +116,7 @@ std::unique_ptr<std::map<std::string, StrikeData>> entries); // Updates the StrikeData for |key| in the cache and ProtoDatabase to have - // |num_stikes|, and the current time as timestamp. + // |num_strikes|, and the current time as timestamp. void SetStrikeData(const std::string key, int num_strikes); // Passes the number of strikes for |key| to |outer_callback|. In the case
diff --git a/components/autofill/core/browser/strike_database_integrator_base.cc b/components/autofill/core/browser/strike_database_integrator_base.cc index ed4ac89..9d97f53 100644 --- a/components/autofill/core/browser/strike_database_integrator_base.cc +++ b/components/autofill/core/browser/strike_database_integrator_base.cc
@@ -69,7 +69,7 @@ } void StrikeDatabaseIntegratorBase::ClearAllStrikes() { - strike_database_->ClearAllStrikes(GetProjectPrefix()); + strike_database_->ClearAllStrikesForProject(GetProjectPrefix()); } void StrikeDatabaseIntegratorBase::RemoveExpiredStrikes() {
diff --git a/components/autofill/core/browser/suggestion_selection.cc b/components/autofill/core/browser/suggestion_selection.cc index c4f1237..c244831 100644 --- a/components/autofill/core/browser/suggestion_selection.cc +++ b/components/autofill/core/browser/suggestion_selection.cc
@@ -117,7 +117,7 @@ } std::vector<Suggestion> GetUniqueSuggestions( - const std::vector<ServerFieldType>& other_field_types, + const std::vector<ServerFieldType>& field_types, const std::string app_locale, const std::vector<AutofillProfile*> matched_profiles, const std::vector<Suggestion>& suggestions, @@ -126,7 +126,7 @@ // Limit number of unique profiles as having too many makes the browser hang // due to drawing calculations (and is also not very useful for the user). - ServerFieldTypeSet types(other_field_types.begin(), other_field_types.end()); + ServerFieldTypeSet types(field_types.begin(), field_types.end()); for (size_t i = 0; i < matched_profiles.size() && unique_suggestions.size() < kMaxUniqueSuggestionsCount; ++i) {
diff --git a/components/autofill/core/browser/suggestion_selection.h b/components/autofill/core/browser/suggestion_selection.h index 09c64924..0e6909e 100644 --- a/components/autofill/core/browser/suggestion_selection.h +++ b/components/autofill/core/browser/suggestion_selection.h
@@ -34,8 +34,10 @@ // Dedupes given suggestions based on if one is a subset of the other. // Returns unique_suggestions, and adds the corresponding profiles to // |unique_matched_profiles|. At most |kMaxUniqueSuggestionsCount| are returned. +// |field_types| stores all of the form's ServerFieldTypes, including that of +// the field on which the user is currently focused. std::vector<Suggestion> GetUniqueSuggestions( - const std::vector<ServerFieldType>& other_field_types, + const std::vector<ServerFieldType>& field_types, const std::string app_locale, const std::vector<AutofillProfile*> matched_profiles, const std::vector<Suggestion>& suggestions,
diff --git a/components/autofill_assistant/browser/actions/show_details_action.cc b/components/autofill_assistant/browser/actions/show_details_action.cc index e1f2626..c92e55cd 100644 --- a/components/autofill_assistant/browser/actions/show_details_action.cc +++ b/components/autofill_assistant/browser/actions/show_details_action.cc
@@ -34,12 +34,10 @@ return; } - Details details; - details.proto = proto_.show_details().details(); - details.changes = proto_.show_details().change_flags(); + Details details(proto_.show_details()); delegate->SetDetails(details); - if (!details.changes.user_approval_required()) { + if (!details.proto().change_flags().user_approval_required()) { OnActionProcessed(ACTION_APPLIED); return; } @@ -83,8 +81,8 @@ OnActionProcessed(MANUAL_FALLBACK); } else { // Same details, without highlights. - Details details; - details.proto = proto_.show_details().details(); + Details details(proto_.show_details()); + details.ClearChanges(); delegate->SetDetails(details); // Restore status message delegate->SetStatusMessage(previous_status_message);
diff --git a/components/autofill_assistant/browser/batch_element_checker_unittest.cc b/components/autofill_assistant/browser/batch_element_checker_unittest.cc index 8a5d239b..de579347 100644 --- a/components/autofill_assistant/browser/batch_element_checker_unittest.cc +++ b/components/autofill_assistant/browser/batch_element_checker_unittest.cc
@@ -272,7 +272,7 @@ // The first try should have run, not fully successful, and should now be // waiting for the second try. - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_TRUE(scoped_task_environment_.NextTaskIsDelayed()); EXPECT_THAT(element_exists_results_, Contains(Pair("1", true))); EXPECT_THAT(element_exists_results_, Not(Contains(Key("2")))); EXPECT_THAT(all_done_, Not(Contains("all_done"))); @@ -280,7 +280,7 @@ // The second try should have found 2 and finished. AdvanceTime(); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); EXPECT_THAT(element_exists_results_, Contains(Pair("2", true))); EXPECT_THAT(all_done_, Contains("all_done")); EXPECT_TRUE(checks_.all_found()); @@ -306,19 +306,19 @@ // The first try should have run, not fully successful, and should now be // waiting for the second try. - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_TRUE(scoped_task_environment_.NextTaskIsDelayed()); EXPECT_THAT(element_exists_results_, Contains(Pair("1", true))); EXPECT_THAT(element_exists_results_, Not(Contains(Key("2")))); EXPECT_THAT(all_done_, Not(Contains("all_done"))); // The second try still doesn't work' AdvanceTime(); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_TRUE(scoped_task_environment_.NextTaskIsDelayed()); EXPECT_THAT(element_exists_results_, Not(Contains(Key("2")))); // Give up after the third try AdvanceTime(); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); EXPECT_THAT(element_exists_results_, Contains(Pair("2", false))); EXPECT_THAT(all_done_, Contains("all_done")); EXPECT_FALSE(checks_.all_found()); @@ -356,7 +356,7 @@ checks_.Run(base::TimeDelta::FromMilliseconds(10), base::DoNothing(), DoneCallback("all_done")); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); EXPECT_THAT(element_exists_results_, Contains(Pair("does_not_exist", false))); EXPECT_THAT(all_done_, Contains("all_done")); EXPECT_FALSE(checks_.all_found());
diff --git a/components/autofill_assistant/browser/details.cc b/components/autofill_assistant/browser/details.cc index f1fe4eaf..16100560 100644 --- a/components/autofill_assistant/browser/details.cc +++ b/components/autofill_assistant/browser/details.cc
@@ -9,40 +9,52 @@ namespace autofill_assistant { +Details::Details(const ShowDetailsProto& proto) : proto_(proto) { + // Legacy treatment for old proto fields. Can be removed once the backend + // is updated to set the description_line1/line2 fields. + if (details().has_description() && !details().has_description_line2()) { + proto_.mutable_details()->set_description_line2(details().description()); + } +} + base::Value Details::GetDebugContext() const { base::Value dict(base::Value::Type::DICTIONARY); - if (!proto.title().empty()) - dict.SetKey("title", base::Value(proto.title())); + if (!details().title().empty()) + dict.SetKey("title", base::Value(details().title())); - if (!proto.url().empty()) - dict.SetKey("url", base::Value(proto.url())); + if (!details().image_url().empty()) + dict.SetKey("image_url", base::Value(details().image_url())); - if (!proto.m_id().empty()) - dict.SetKey("mId", base::Value(proto.m_id())); + if (!details().total_price().empty()) + dict.SetKey("total_price", base::Value(details().total_price())); - if (!proto.total_price().empty()) - dict.SetKey("total_price", base::Value(proto.total_price())); + if (!details().description_line1().empty()) + dict.SetKey("description_line1", + base::Value(details().description_line1())); - if (!proto.description().empty()) - dict.SetKey("description", base::Value(proto.description())); + if (!details().description_line2().empty()) + dict.SetKey("description_line2", + base::Value(details().description_line2())); - if (proto.has_datetime()) { - dict.SetKey( - "datetime", - base::Value(base::StringPrintf( - "%d-%02d-%02dT%02d:%02d:%02d", - static_cast<int>(proto.datetime().date().year()), - proto.datetime().date().month(), proto.datetime().date().day(), - proto.datetime().time().hour(), proto.datetime().time().minute(), - proto.datetime().time().second()))); + if (details().has_datetime()) { + dict.SetKey("datetime", + base::Value(base::StringPrintf( + "%d-%02d-%02dT%02d:%02d:%02d", + static_cast<int>(details().datetime().date().year()), + details().datetime().date().month(), + details().datetime().date().day(), + details().datetime().time().hour(), + details().datetime().time().minute(), + details().datetime().time().second()))); } - if (!datetime.empty()) - dict.SetKey("datetime_str", base::Value(datetime)); + if (!datetime_.empty()) + dict.SetKey("datetime_str", base::Value(datetime_)); dict.SetKey("user_approval_required", - base::Value(changes.user_approval_required())); - dict.SetKey("highlight_title", base::Value(changes.highlight_title())); - dict.SetKey("highlight_date", base::Value(changes.highlight_date())); + base::Value(changes().user_approval_required())); + dict.SetKey("highlight_title", base::Value(changes().highlight_title())); + dict.SetKey("highlight_line1", base::Value(changes().highlight_line1())); + dict.SetKey("highlight_line2", base::Value(changes().highlight_line2())); return dict; } @@ -52,28 +64,22 @@ bool is_updated = false; for (const auto& iter : parameters) { std::string key = iter.first; - if (base::EndsWith(key, "E_NAME", base::CompareCase::SENSITIVE)) { - proto.set_title(iter.second); - is_updated = true; - continue; - } - - if (base::EndsWith(key, "R_NAME", base::CompareCase::SENSITIVE)) { - proto.set_description(iter.second); - is_updated = true; - continue; - } - - if (base::EndsWith(key, "MID", base::CompareCase::SENSITIVE)) { - proto.set_m_id(iter.second); + if (base::EndsWith(key, "MOVIE_NAME", base::CompareCase::SENSITIVE)) { + proto_.mutable_details()->set_title(iter.second); is_updated = true; continue; } if (base::EndsWith(key, "DATETIME", base::CompareCase::SENSITIVE)) { - // TODO(crbug.com/806868): Parse the string here and fill proto.datetime, - // then get rid of the field datetime in Details. - datetime = iter.second; + // TODO(crbug.com/806868): Parse the string here and fill + // proto.description_line1, then get rid of datetime_ in Details. + datetime_ = iter.second; + is_updated = true; + continue; + } + + if (base::EndsWith(key, "THEATER_NAME", base::CompareCase::SENSITIVE)) { + proto_.mutable_details()->set_description_line2(iter.second); is_updated = true; continue; } @@ -81,4 +87,8 @@ return is_updated; } +void Details::ClearChanges() { + proto_.clear_change_flags(); +} + } // namespace autofill_assistant
diff --git a/components/autofill_assistant/browser/details.h b/components/autofill_assistant/browser/details.h index fb00f1fd..79adfdb 100644 --- a/components/autofill_assistant/browser/details.h +++ b/components/autofill_assistant/browser/details.h
@@ -13,16 +13,13 @@ namespace autofill_assistant { -struct Details { - DetailsProto proto; - DetailsChanges changes; +class Details { + public: + Details() = default; + Details(const ShowDetailsProto& proto); - // RFC 3339 date-time. Ignore if proto.datetime is set. - // - // TODO(crbug.com/806868): parse RFC 3339 date-time on the C++ side and fill - // proto.datetime with the result instead of carrying a string representation - // of the datetime. - std::string datetime; + const ShowDetailsProto& proto() const { return proto_; } + const std::string GetDatetime() const { return datetime_; } // Returns a dictionary describing the current execution context, which // is intended to be serialized as JSON string. The execution context is @@ -33,6 +30,21 @@ // made. bool UpdateFromParameters( const std::map<std::string, std::string>& parameters); + + // Clears all change flags. + void ClearChanges(); + + private: + const DetailsProto& details() const { return proto_.details(); } + const DetailsChangesProto& changes() const { return proto_.change_flags(); } + + ShowDetailsProto proto_; + // RFC 3339 date-time. Ignore if proto.description_line1 is set. + // + // TODO(crbug.com/806868): parse RFC 3339 date-time on the C++ side and fill + // proto.description_line1 with the result instead of carrying a string + // representation of the datetime. + std::string datetime_; }; } // namespace autofill_assistant
diff --git a/components/autofill_assistant/browser/script_executor_unittest.cc b/components/autofill_assistant/browser/script_executor_unittest.cc index f954e1dc..ff22d3d 100644 --- a/components/autofill_assistant/browser/script_executor_unittest.cc +++ b/components/autofill_assistant/browser/script_executor_unittest.cc
@@ -350,14 +350,14 @@ // executor_callback_.Run() not expected to be run just yet, as the action is // delayed. executor_->Run(executor_callback_.Get()); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_TRUE(scoped_task_environment_.NextTaskIsDelayed()); // Moving forward in time triggers action execution. EXPECT_CALL(executor_callback_, Run(Field(&ScriptExecutor::Result::success, true))); scoped_task_environment_.FastForwardBy( base::TimeDelta::FromMilliseconds(1000)); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); } TEST_F(ScriptExecutorTest, ClearDetailsWhenFinished) {
diff --git a/components/autofill_assistant/browser/service.proto b/components/autofill_assistant/browser/service.proto index e718ff9..0af6f541 100644 --- a/components/autofill_assistant/browser/service.proto +++ b/components/autofill_assistant/browser/service.proto
@@ -631,33 +631,41 @@ optional TimeProto time = 2; } -message DetailsChanges { +message DetailsChangesProto { // Whether the changes require user approval. optional bool user_approval_required = 1; // Whether the title should be highlighted. optional bool highlight_title = 2; - // Whether the date should be highlighted. - optional bool highlight_date = 3; + // Whether the first description line should be highlighted. + optional bool highlight_line1 = 3; + + // Whether the second description line should be highlighted. + optional bool highlight_line2 = 4; } message DetailsProto { optional string title = 1; - optional string url = 2; + optional string image_url = 2; - optional DateTimeProto datetime = 3; - - optional string description = 4; - - // Mid that comes from Knowledge Graph. Uniquely identify the object that this - // proto describes. - optional string m_id = 5; - - // Price label containing the total amount and the currency to pay, formatted + // Optional label to provide additional price information. + optional string total_price_label = 9; + // The price containing the total amount and the currency to pay, formatted // in the client's locale (e.g., $123.00). optional string total_price = 6; + + optional string description_line1 = 7; + optional string description_line2 = 8; + + // Deprecated, but currently still necessary and supported. We can get rid of + // these fields when the backend starts setting description_line1 and 2. + optional DateTimeProto datetime = 3; + optional string description = 4; + + // Deprecated, no longer supported. + reserved 5; } // Show contextual information. @@ -665,7 +673,7 @@ optional DetailsProto details = 1; // Flags indicating which parts of the details (if any) have changed. - optional DetailsChanges change_flags = 2; + optional DetailsChangesProto change_flags = 2; } // Set the value of an form element.
diff --git a/components/browser_sync/profile_sync_service.cc b/components/browser_sync/profile_sync_service.cc index 0508795..fb5a377 100644 --- a/components/browser_sync/profile_sync_service.cc +++ b/components/browser_sync/profile_sync_service.cc
@@ -456,7 +456,7 @@ // The major version has changed and a local syncable change was made. // Reset the passphrase prompt state. passphrase_prompt_triggered_by_version_ = false; - sync_prefs_.SetPassphrasePrompted(false); + SetPassphrasePrompted(false); NotifyObservers(); } @@ -1924,6 +1924,14 @@ engine_->FlushDirectory(); } +bool ProfileSyncService::IsPassphrasePrompted() const { + return sync_prefs_.IsPassphrasePrompted(); +} + +void ProfileSyncService::SetPassphrasePrompted(bool prompted) { + sync_prefs_.SetPassphrasePrompted(prompted); +} + scoped_refptr<base::SingleThreadTaskRunner> ProfileSyncService::GetSyncThreadTaskRunnerForTest() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
diff --git a/components/browser_sync/profile_sync_service.h b/components/browser_sync/profile_sync_service.h index 8a5269a9..a987979 100644 --- a/components/browser_sync/profile_sync_service.h +++ b/components/browser_sync/profile_sync_service.h
@@ -333,6 +333,9 @@ // killed in the near future. void FlushDirectory() const; + bool IsPassphrasePrompted() const; + void SetPassphrasePrompted(bool prompted); + void SyncAllowedByPlatformChanged(bool allowed); // Sometimes we need to wait for tasks on the sync thread in tests.
diff --git a/components/cast_channel/cast_message_handler.cc b/components/cast_channel/cast_message_handler.cc index 920c3af..8baa632 100644 --- a/components/cast_channel/cast_message_handler.cc +++ b/components/cast_channel/cast_message_handler.cc
@@ -6,6 +6,7 @@ #include <tuple> #include <utility> +#include <vector> #include "base/bind.h" #include "base/rand_util.h" @@ -191,9 +192,11 @@ } } -void CastMessageHandler::StopSession(int channel_id, - const std::string& session_id, - ResultCallback callback) { +void CastMessageHandler::StopSession( + int channel_id, + const std::string& session_id, + const base::Optional<std::string>& client_id, + ResultCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); CastSocket* socket = socket_service_->GetSocket(channel_id); if (!socket) { @@ -207,8 +210,8 @@ << ", request_id: " << request_id; if (requests->AddStopRequest(std::make_unique<StopSessionRequest>( request_id, std::move(callback), clock_))) { - SendCastMessage(socket, - CreateStopRequest(sender_id_, request_id, session_id)); + SendCastMessage(socket, CreateStopRequest(client_id.value_or(sender_id_), + request_id, session_id)); } }
diff --git a/components/cast_channel/cast_message_handler.h b/components/cast_channel/cast_message_handler.h index e6049ad..9023302 100644 --- a/components/cast_channel/cast_message_handler.h +++ b/components/cast_channel/cast_message_handler.h
@@ -11,6 +11,7 @@ #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "base/optional.h" #include "base/sequence_checker.h" #include "base/time/tick_clock.h" #include "base/timer/timer.h" @@ -176,6 +177,7 @@ // request. virtual void StopSession(int channel_id, const std::string& session_id, + const base::Optional<std::string>& client_id, ResultCallback callback); // Sends |message| to the device given by |channel_id|. The caller may use
diff --git a/components/cast_channel/cast_message_handler_unittest.cc b/components/cast_channel/cast_message_handler_unittest.cc index cab1fdbe..908f75e 100644 --- a/components/cast_channel/cast_message_handler_unittest.cc +++ b/components/cast_channel/cast_message_handler_unittest.cc
@@ -144,7 +144,7 @@ R"({"sessionId": "theSessionId", "type": "SET_VOLUME"})"), "theSourceId", set_volume_callback_.Get())); } - handler_.StopSession(channel_id_, "theSessionId", + handler_.StopSession(channel_id_, "theSessionId", "theSourceId", stop_session_callback_.Get()); }
diff --git a/components/cast_channel/cast_test_util.h b/components/cast_channel/cast_test_util.h index 335b78d59..d037bc14 100644 --- a/components/cast_channel/cast_test_util.h +++ b/components/cast_channel/cast_test_util.h
@@ -7,6 +7,7 @@ #include <string> #include <utility> +#include <vector> #include "base/bind.h" #include "base/macros.h" @@ -164,9 +165,10 @@ const std::string&, base::TimeDelta, LaunchSessionCallback callback)); - MOCK_METHOD3(StopSession, + MOCK_METHOD4(StopSession, void(int channel_id, const std::string& session_id, + const base::Optional<std::string>& client_id, ResultCallback callback)); MOCK_METHOD2(SendAppMessage, Result(int channel_id, const CastMessage& message));
diff --git a/components/cdm/browser/media_drm_storage_impl.cc b/components/cdm/browser/media_drm_storage_impl.cc index 7bbe3d6..ed34b837 100644 --- a/components/cdm/browser/media_drm_storage_impl.cc +++ b/components/cdm/browser/media_drm_storage_impl.cc
@@ -11,6 +11,7 @@ #include "base/bind.h" #include "base/logging.h" #include "base/no_destructor.h" +#include "base/optional.h" #include "base/strings/string_util.h" #include "base/value_conversions.h" #include "components/prefs/pref_registry_simple.h" @@ -510,17 +511,19 @@ } private: - void OnOriginIdObtained(PrefService* pref_service, - const url::Origin& origin, - bool success, - const base::UnguessableToken& origin_id) { + void OnOriginIdObtained( + PrefService* pref_service, + const url::Origin& origin, + bool success, + const MediaDrmStorageImpl::MediaDrmOriginId& origin_id) { DVLOG(3) << __func__ << " origin: " << origin; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); // Save the origin ID in the preference as long as it is not null. if (origin_id) { DictionaryPrefUpdate update(pref_service, kMediaDrmStorage); - CreateOriginDictAndReturnSessionsDict(update.Get(), origin, origin_id); + CreateOriginDictAndReturnSessionsDict(update.Get(), origin, + origin_id.value()); } // Now call any callbacks waiting for this origin ID to be allocated. @@ -657,7 +660,7 @@ DVLOG(1) << __func__; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (init_cb_) - std::move(init_cb_).Run(false, base::UnguessableToken()); + std::move(init_cb_).Run(false, base::nullopt); } void MediaDrmStorageImpl::Initialize(InitializeCallback callback) { @@ -685,9 +688,11 @@ void MediaDrmStorageImpl::OnOriginIdObtained( bool success, - const base::UnguessableToken& origin_id) { + const MediaDrmOriginId& origin_id) { is_initialized_ = true; - origin_id_ = origin_id; + if (success) + origin_id_ = origin_id; + std::move(init_cb_).Run(success, origin_id_); } @@ -715,7 +720,8 @@ // Update origin dict once origin provisioning completes. There may be // orphaned session info from a previous provisioning. Clear them by // recreating the dicts. - CreateOriginDictAndReturnSessionsDict(storage_dict, origin(), origin_id_); + CreateOriginDictAndReturnSessionsDict(storage_dict, origin(), + origin_id_.value()); std::move(callback).Run(true); } @@ -752,15 +758,15 @@ // branch. Deleting the profile causes reprovisioning of the origin. if (!sessions_dict) { DVLOG(1) << __func__ << ": No entry for origin " << origin(); - sessions_dict = CreateOriginDictAndReturnSessionsDict(storage_dict, - origin(), origin_id_); + sessions_dict = CreateOriginDictAndReturnSessionsDict( + storage_dict, origin(), origin_id_.value()); DCHECK(sessions_dict); } DVLOG_IF(1, sessions_dict->FindKey(session_id)) << __func__ << ": Session ID already exists and will be replaced."; - // The key type of the session should be valid. MeidaDrmKeyType::MIN/UNKNOWN + // The key type of the session should be valid. MediaDrmKeyType::MIN/UNKNOWN // is an invalid type and caller should never pass it here. DCHECK_GT(session_data->key_type, media::MediaDrmKeyType::MIN); DCHECK_LE(session_data->key_type, media::MediaDrmKeyType::MAX);
diff --git a/components/cdm/browser/media_drm_storage_impl.h b/components/cdm/browser/media_drm_storage_impl.h index 7afc1e2..48a3c4ce 100644 --- a/components/cdm/browser/media_drm_storage_impl.h +++ b/components/cdm/browser/media_drm_storage_impl.h
@@ -11,6 +11,7 @@ #include "base/callback.h" #include "base/memory/weak_ptr.h" +#include "base/optional.h" #include "base/threading/thread_checker.h" #include "base/time/time.h" #include "base/unguessable_token.h" @@ -37,10 +38,14 @@ class MediaDrmStorageImpl final : public content::FrameServiceBase<media::mojom::MediaDrmStorage> { public: + // When using per-origin provisioning, this is the ID for the origin. + // If not specified, the device specific origin ID is to be used. + using MediaDrmOriginId = base::Optional<base::UnguessableToken>; + // |success| is true if an origin ID was obtained and |origin_id| is // specified, false otherwise. using OriginIdObtainedCB = - base::OnceCallback<void(bool success, const base::UnguessableToken&)>; + base::OnceCallback<void(bool success, const MediaDrmOriginId& origin_id)>; using GetOriginIdCB = base::RepeatingCallback<void(OriginIdObtainedCB)>; static void RegisterProfilePrefs(PrefRegistrySimple* registry); @@ -89,15 +94,15 @@ // Called when |get_origin_id_cb_| asynchronously returns a origin ID as part // of Initialize(). - void OnOriginIdObtained(bool success, - const base::UnguessableToken& origin_id); + void OnOriginIdObtained(bool success, const MediaDrmOriginId& origin_id); PrefService* const pref_service_; GetOriginIdCB get_origin_id_cb_; // ID for the current origin. Per EME spec on individualization, // implementation should not expose application-specific information. - base::UnguessableToken origin_id_; + // If not specified, the device specific origin ID is to be used. + MediaDrmOriginId origin_id_; // As Initialize() may be asynchronous, save the InitializeCallback when // necessary.
diff --git a/components/cdm/browser/media_drm_storage_impl_unittest.cc b/components/cdm/browser/media_drm_storage_impl_unittest.cc index 53385e3c..ec7149a 100644 --- a/components/cdm/browser/media_drm_storage_impl_unittest.cc +++ b/components/cdm/browser/media_drm_storage_impl_unittest.cc
@@ -8,6 +8,7 @@ #include <utility> #include "base/bind.h" +#include "base/optional.h" #include "base/run_loop.h" #include "base/threading/thread_task_runner_handle.h" #include "base/unguessable_token.h" @@ -29,12 +30,14 @@ const char kTestOrigin[] = "https://www.testorigin.com:80"; const char kTestOrigin2[] = "https://www.testorigin2.com:80"; -void OnMediaDrmStorageInit(base::UnguessableToken* out_origin_id, +using MediaDrmOriginId = MediaDrmStorageImpl::MediaDrmOriginId; + +void OnMediaDrmStorageInit(bool expected_success, + MediaDrmOriginId* out_origin_id, bool success, - const base::UnguessableToken& origin_id) { + const MediaDrmOriginId& origin_id) { DCHECK(out_origin_id); - DCHECK(success); - DCHECK(origin_id); + DCHECK_EQ(success, expected_success); *out_origin_id = origin_id; } @@ -42,6 +45,10 @@ std::move(callback).Run(true, base::UnguessableToken::Create()); } +void CreateEmptyOriginId(MediaDrmStorageImpl::OriginIdObtainedCB callback) { + std::move(callback).Run(true, base::nullopt); +} + void CreateOriginIdAsync(MediaDrmStorageImpl::OriginIdObtainedCB callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&CreateOriginId, std::move(callback))); @@ -90,7 +97,7 @@ std::unique_ptr<media::MediaDrmStorage> CreateAndInitMediaDrmStorage( const GURL& origin, - base::UnguessableToken* origin_id) { + MediaDrmOriginId* origin_id) { DCHECK(origin_id); std::unique_ptr<media::MediaDrmStorage> media_drm_storage = @@ -98,7 +105,7 @@ base::BindRepeating(&CreateOriginId)); media_drm_storage->Initialize( - base::BindOnce(OnMediaDrmStorageInit, origin_id)); + base::BindOnce(OnMediaDrmStorageInit, true, origin_id)); base::RunLoop().RunUntilIdle(); @@ -191,7 +198,7 @@ std::unique_ptr<TestingPrefServiceSimple> pref_service_; std::unique_ptr<media::MediaDrmStorage> media_drm_storage_; - base::UnguessableToken origin_id_; + MediaDrmOriginId origin_id_; }; // MediaDrmStorageImpl should write origin ID to persistent storage when @@ -200,10 +207,10 @@ // fully initialized. // TODO(yucliu): Test origin ID is re-generated after clearing licenses. TEST_F(MediaDrmStorageImplTest, Initialize_OriginIdNotChanged) { - base::UnguessableToken original_origin_id = origin_id_; + MediaDrmOriginId original_origin_id = origin_id_; ASSERT_TRUE(original_origin_id); - base::UnguessableToken origin_id; + MediaDrmOriginId origin_id; std::unique_ptr<media::MediaDrmStorage> storage = CreateAndInitMediaDrmStorage(GURL(kTestOrigin), &origin_id); EXPECT_EQ(origin_id, original_origin_id); @@ -220,12 +227,16 @@ std::unique_ptr<media::MediaDrmStorage> storage2 = CreateMediaDrmStorage(rfh, base::BindRepeating(&CreateOriginId)); - base::UnguessableToken origin_id_1; - storage1->Initialize(base::BindOnce(OnMediaDrmStorageInit, &origin_id_1)); - base::UnguessableToken origin_id_2; - storage2->Initialize(base::BindOnce(OnMediaDrmStorageInit, &origin_id_2)); + MediaDrmOriginId origin_id_1; + storage1->Initialize( + base::BindOnce(OnMediaDrmStorageInit, true, &origin_id_1)); + MediaDrmOriginId origin_id_2; + storage2->Initialize( + base::BindOnce(OnMediaDrmStorageInit, true, &origin_id_2)); base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(origin_id_1); + EXPECT_TRUE(origin_id_2); EXPECT_EQ(origin_id_1, origin_id_2); } @@ -237,20 +248,24 @@ std::unique_ptr<media::MediaDrmStorage> storage2 = CreateMediaDrmStorage(rfh, base::BindRepeating(&CreateOriginIdAsync)); - base::UnguessableToken origin_id_1; - storage1->Initialize(base::BindOnce(OnMediaDrmStorageInit, &origin_id_1)); - base::UnguessableToken origin_id_2; - storage2->Initialize(base::BindOnce(OnMediaDrmStorageInit, &origin_id_2)); + MediaDrmOriginId origin_id_1; + storage1->Initialize( + base::BindOnce(OnMediaDrmStorageInit, true, &origin_id_1)); + MediaDrmOriginId origin_id_2; + storage2->Initialize( + base::BindOnce(OnMediaDrmStorageInit, true, &origin_id_2)); base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(origin_id_1); + EXPECT_TRUE(origin_id_2); EXPECT_EQ(origin_id_1, origin_id_2); } TEST_F(MediaDrmStorageImplTest, Initialize_DifferentOrigins) { - base::UnguessableToken origin_id_1 = origin_id_; + MediaDrmOriginId origin_id_1 = origin_id_; ASSERT_TRUE(origin_id_1); - base::UnguessableToken origin_id_2; + MediaDrmOriginId origin_id_2; auto storage2 = CreateAndInitMediaDrmStorage(GURL(kTestOrigin2), &origin_id_2); ASSERT_TRUE(origin_id_2); @@ -370,4 +385,17 @@ EXPECT_EQ(origins4, std::vector<GURL>{GURL(kTestOrigin)}); } +TEST_F(MediaDrmStorageImplTest, AllowEmptyOriginId) { + content::RenderFrameHost* rfh = SimulateNavigation(GURL(kTestOrigin2)); + + std::unique_ptr<media::MediaDrmStorage> storage = + CreateMediaDrmStorage(rfh, base::BindRepeating(&CreateEmptyOriginId)); + + MediaDrmOriginId origin_id; + storage->Initialize(base::BindOnce(OnMediaDrmStorageInit, true, &origin_id)); + base::RunLoop().RunUntilIdle(); + + EXPECT_FALSE(origin_id); +} + } // namespace cdm
diff --git a/components/crash/content/app/breakpad_win.cc b/components/crash/content/app/breakpad_win.cc index 8de4938..172cf5b 100644 --- a/components/crash/content/app/breakpad_win.cc +++ b/components/crash/content/app/breakpad_win.cc
@@ -634,7 +634,7 @@ env->UnSetVar(kPipeNameVar); } -#ifdef _WIN64 +#ifdef _M_X64 int CrashForExceptionInNonABICompliantCodeRange( PEXCEPTION_RECORD ExceptionRecord, ULONG64 EstablisherFrame,
diff --git a/components/dom_distiller/content/renderer/distiller_js_render_frame_observer.cc b/components/dom_distiller/content/renderer/distiller_js_render_frame_observer.cc index e249ce90..29ff33b 100644 --- a/components/dom_distiller/content/renderer/distiller_js_render_frame_observer.cc +++ b/components/dom_distiller/content/renderer/distiller_js_render_frame_observer.cc
@@ -32,9 +32,9 @@ DistillerJsRenderFrameObserver::~DistillerJsRenderFrameObserver() {} -void DistillerJsRenderFrameObserver::DidStartProvisionalLoad( - blink::WebDocumentLoader* document_loader, - bool is_content_initiated) { +void DistillerJsRenderFrameObserver::DidStartNavigation( + const GURL& url, + base::Optional<blink::WebNavigationType> navigation_type) { load_active_ = true; }
diff --git a/components/dom_distiller/content/renderer/distiller_js_render_frame_observer.h b/components/dom_distiller/content/renderer/distiller_js_render_frame_observer.h index f32e4e451..0868b85a 100644 --- a/components/dom_distiller/content/renderer/distiller_js_render_frame_observer.h +++ b/components/dom_distiller/content/renderer/distiller_js_render_frame_observer.h
@@ -28,8 +28,9 @@ ~DistillerJsRenderFrameObserver() override; // RenderFrameObserver implementation. - void DidStartProvisionalLoad(blink::WebDocumentLoader* document_loader, - bool is_content_initiated) override; + void DidStartNavigation( + const GURL& url, + base::Optional<blink::WebNavigationType> navigation_type) override; void DidFinishLoad() override; void DidCreateScriptContext(v8::Local<v8::Context> context, int world_id) override;
diff --git a/components/exo/pointer.cc b/components/exo/pointer.cc index 0b18079..c2098b4 100644 --- a/components/exo/pointer.cc +++ b/components/exo/pointer.cc
@@ -8,14 +8,17 @@ #include "ash/public/cpp/shell_window_ids.h" #include "base/bind.h" +#include "base/feature_list.h" #include "components/exo/pointer_delegate.h" #include "components/exo/pointer_gesture_pinch_delegate.h" +#include "components/exo/relative_pointer_delegate.h" #include "components/exo/shell_surface_util.h" #include "components/exo/surface.h" #include "components/exo/wm_helper.h" #include "components/exo/wm_helper_chromeos.h" #include "components/viz/common/frame_sinks/copy_output_request.h" #include "components/viz/common/frame_sinks/copy_output_result.h" +#include "ui/aura/client/capture_client.h" #include "ui/aura/client/cursor_client.h" #include "ui/aura/env.h" #include "ui/aura/window.h" @@ -37,6 +40,11 @@ #endif namespace exo { + +// Controls Pointer capture in exo/wayland. +const base::Feature kPointerCapture{"ExoPointerCapture", + base::FEATURE_ENABLED_BY_DEFAULT}; + namespace { // TODO(oshima): Some accessibility features, including large cursors, disable @@ -91,6 +99,7 @@ aura::client::CursorClient* cursor_client = helper->GetCursorClient(); if (cursor_client) cursor_client->AddObserver(this); + helper->AddFocusObserver(this); } Pointer::~Pointer() { @@ -100,6 +109,8 @@ } if (pinch_delegate_) pinch_delegate_->OnPointerDestroying(this); + if (relative_pointer_delegate_) + relative_pointer_delegate_->OnPointerDestroying(this); WMHelperChromeOS* helper = WMHelperChromeOS::GetInstance(); helper->RemoveDisplayConfigurationObserver(this); helper->RemovePreTargetHandler(this); @@ -110,6 +121,7 @@ cursor_client->RemoveObserver(this); if (root_surface()) root_surface()->RemoveSurfaceObserver(this); + helper->RemoveFocusObserver(this); } void Pointer::SetCursor(Surface* surface, const gfx::Point& hotspot) { @@ -174,6 +186,89 @@ pinch_delegate_ = delegate; } +void Pointer::EnablePointerCapture(RelativePointerDelegate* delegate) { + if (!base::FeatureList::IsEnabled(kPointerCapture)) + return; + + if (!delegate) { + DLOG(ERROR) << "Failed to enable pointer capture: " + "relative pointer delegate is null"; + return; + } + + // If pointer capture is already enabled, disable it first. + if (relative_pointer_delegate_) + DisablePointerCapture(); + + // TODO(b/124059008): Find the correct window to set capture. + aura::Window* active_window = WMHelper::GetInstance()->GetActiveWindow(); + if (!active_window) { + LOG(ERROR) << "Failed to enable pointer capture: " + "active window not found"; + return; + } + auto* top_level_widget = + views::Widget::GetTopLevelWidgetForNativeView(active_window); + + if (!top_level_widget) { + LOG(ERROR) << "Failed to enable pointer capture: " + "active window does not have associated widget"; + return; + } + Surface* root_surface = + GetShellMainSurface(top_level_widget->GetNativeWindow()); + if (!root_surface || + !delegate_->CanAcceptPointerEventsForSurface(root_surface)) { + LOG(ERROR) << "Failed to enable pointer capture: " + "cannot find window for capture"; + return; + } + capture_window_ = root_surface->window(); + + auto* capture_client = WMHelper::GetInstance()->GetCaptureClient(); + capture_client->SetCapture(capture_window_); + capture_client->AddObserver(this); + + auto* cursor_client = WMHelper::GetInstance()->GetCursorClient(); + cursor_client->HideCursor(); + cursor_client->LockCursor(); + + relative_pointer_delegate_ = delegate; + location_when_pointer_capture_enabled_ = gfx::ToRoundedPoint(location_); + + if (ShouldMoveToCenter()) + MoveCursorToCenterOfActiveDisplay(); +} + +void Pointer::DisablePointerCapture() { + // Early out if pointer capture is not enabled. + if (!relative_pointer_delegate_) + return; + + auto* capture_client = WMHelper::GetInstance()->GetCaptureClient(); + capture_client->RemoveObserver(this); + if (capture_window_ && capture_window_->HasCapture()) + capture_client->ReleaseCapture(capture_window_); + capture_window_ = nullptr; + + auto* cursor_client = WMHelper::GetInstance()->GetCursorClient(); + cursor_client->UnlockCursor(); + cursor_client->ShowCursor(); + + aura::Window* focusedWindow = WMHelper::GetInstance()->GetFocusedWindow(); + aura::Window* root = focusedWindow->GetRootWindow(); + gfx::Point p = location_when_pointer_capture_enabled_ + ? *location_when_pointer_capture_enabled_ + : root->bounds().CenterPoint(); + root->MoveCursorTo(p); + + focus_surface_ = nullptr; + location_when_pointer_capture_enabled_.reset(); + UpdateCursor(); + + relative_pointer_delegate_ = nullptr; +} + //////////////////////////////////////////////////////////////////////////////// // SurfaceDelegate overrides: @@ -216,6 +311,8 @@ if (target != focus_surface_) SetFocus(target, location_in_target, event->button_flags()); + gfx::PointF location_in_root = GetLocationInRoot(target, location_in_target); + if (!focus_surface_) return; @@ -230,12 +327,15 @@ // so to avoid generating mouse event jitter we consider the location of // these events to be the same as |location| if floored values match. bool same_location = !event->IsSynthesized() - ? SameLocation(location_in_target, location_) - : gfx::ToFlooredPoint(location_in_target) == + ? SameLocation(location_in_root, location_) + : gfx::ToFlooredPoint(location_in_root) == gfx::ToFlooredPoint(location_); if (!same_location) { - location_ = location_in_target; - delegate_->OnPointerMotion(event->time_stamp(), location_); + if (relative_pointer_delegate_) + HandleRelativePointerMotion(event->time_stamp(), location_in_root); + else + delegate_->OnPointerMotion(event->time_stamp(), location_in_target); + location_ = location_in_root; delegate_->OnPointerFrame(); } } @@ -342,7 +442,17 @@ } //////////////////////////////////////////////////////////////////////////////// -// ui::client::CursorClientObserver overrides: +// aura::client::CaptureClientObserver overrides: + +void Pointer::OnCaptureChanged(aura::Window* lost_capture, + aura::Window* gained_capture) { + // Note: This observer is only set when pointer capture in enabled. + if (relative_pointer_delegate_ && gained_capture != capture_window_) + DisablePointerCapture(); +} + +//////////////////////////////////////////////////////////////////////////////// +// aura::client::CursorClientObserver overrides: void Pointer::OnCursorSizeChanged(ui::CursorSize cursor_size) { if (!focus_surface_) @@ -368,6 +478,15 @@ } //////////////////////////////////////////////////////////////////////////////// +// aura::client::FocusChangeObserver overrides: + +void Pointer::OnWindowFocused(aura::Window* gained_focus, + aura::Window* lost_focus) { + if (relative_pointer_delegate_) + DisablePointerCapture(); +} + +//////////////////////////////////////////////////////////////////////////////// // ash::WindowTreeHostManager::Observer overrides: void Pointer::OnDisplayConfigurationChanged() { @@ -404,7 +523,7 @@ // Second generate an enter event if focus moved to a new surface. if (surface) { delegate_->OnPointerEnter(surface, location, button_flags); - location_ = location; + location_ = GetLocationInRoot(surface, location); focus_surface_ = surface; focus_surface_->AddSurfaceObserver(this); } @@ -540,4 +659,56 @@ } } +gfx::PointF Pointer::GetLocationInRoot(Surface* target, + gfx::PointF location_in_target) { + if (!target || !target->window()) + return location_in_target; + aura::Window* w = target->window(); + gfx::PointF p(location_in_target.x(), location_in_target.y()); + aura::Window::ConvertPointToTarget(w, w->GetRootWindow(), &p); + return gfx::PointF(p.x(), p.y()); +} + +bool Pointer::ShouldMoveToCenter() { + // Early out if the pointer doesn't have a surface in focus. + if (!focus_surface_) + return false; + + gfx::Rect rect = + WMHelper::GetInstance()->GetFocusedWindow()->GetRootWindow()->bounds(); + + rect.Inset(rect.width() / 6, rect.height() / 6); + return !rect.Contains(location_.x(), location_.y()); +} + +void Pointer::MoveCursorToCenterOfActiveDisplay() { + aura::Window* focusedWindow = WMHelper::GetInstance()->GetFocusedWindow(); + aura::Window* root = focusedWindow->GetRootWindow(); + gfx::Point p = root->bounds().CenterPoint(); + location_synthetic_move_ = p; + root->MoveCursorTo(p); +} + +void Pointer::HandleRelativePointerMotion(base::TimeTicks time_stamp, + gfx::PointF location_in_root) { + if (location_synthetic_move_) { + gfx::Point synthetic = *location_synthetic_move_; + // Since MoveCursorTo() takes integer coordinates, the resulting move could + // have a conversion error of up to 2 due to fractional scale factors. + if (std::abs(location_in_root.x() - synthetic.x()) <= 2 && + std::abs(location_in_root.y() - synthetic.y()) <= 2) { + // This was a synthetic move event, so do not forward it and clear the + // synthetic move. + location_synthetic_move_.reset(); + return; + } + } + + gfx::PointF delta(location_in_root.x() - location_.x(), + location_in_root.y() - location_.y()); + relative_pointer_delegate_->OnPointerRelativeMotion(time_stamp, delta); + if (ShouldMoveToCenter()) + MoveCursorToCenterOfActiveDisplay(); +} + } // namespace exo
diff --git a/components/exo/pointer.h b/components/exo/pointer.h index 1d66994f..30d46e0 100644 --- a/components/exo/pointer.h +++ b/components/exo/pointer.h
@@ -10,12 +10,15 @@ #include "ash/display/window_tree_host_manager.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "base/optional.h" #include "base/unguessable_token.h" #include "components/exo/surface_observer.h" #include "components/exo/surface_tree_host.h" #include "components/exo/wm_helper.h" #include "third_party/skia/include/core/SkBitmap.h" +#include "ui/aura/client/capture_client_observer.h" #include "ui/aura/client/cursor_client_observer.h" +#include "ui/aura/client/focus_change_observer.h" #include "ui/base/cursor/cursor.h" #include "ui/events/event_constants.h" #include "ui/events/event_handler.h" @@ -35,6 +38,7 @@ namespace exo { class PointerDelegate; class PointerGesturePinchDelegate; +class RelativePointerDelegate; class Surface; class SurfaceTreeHost; @@ -43,7 +47,9 @@ class Pointer : public SurfaceTreeHost, public SurfaceObserver, public ui::EventHandler, + public aura::client::CaptureClientObserver, public aura::client::CursorClientObserver, + public aura::client::FocusChangeObserver, public ash::WindowTreeHostManager::Observer { public: explicit Pointer(PointerDelegate* delegate); @@ -68,7 +74,7 @@ // Overridden from SurfaceDelegate: void OnSurfaceCommit() override; - // Overriden from SurfaceObserver: + // Overridden from SurfaceObserver: void OnSurfaceDestroying(Surface* surface) override; // Overridden from ui::EventHandler: @@ -76,13 +82,25 @@ void OnScrollEvent(ui::ScrollEvent* event) override; void OnGestureEvent(ui::GestureEvent* event) override; - // Overridden from ui::client::CursorClientObserver: + // Overridden from aura::client::CaptureClientObserver: + void OnCaptureChanged(aura::Window* lost_capture, + aura::Window* gained_capture) override; + + // Overridden from aura::client::CursorClientObserver: void OnCursorSizeChanged(ui::CursorSize cursor_size) override; void OnCursorDisplayChanged(const display::Display& display) override; + // Overridden from aura::client::FocusChangeObserver; + void OnWindowFocused(aura::Window* gained_focus, + aura::Window* lost_focus) override; + // Overridden from ash::WindowTreeHostManager::Observer: void OnDisplayConfigurationChanged() override; + // Pointer capture toggles: + void EnablePointerCapture(RelativePointerDelegate* delegate); + void DisablePointerCapture(); + private: // Returns the effective target for |event|. Surface* GetEffectiveTargetForEvent(ui::LocatedEvent* event) const; @@ -107,18 +125,47 @@ // Update |cursor_| to |cursor_bitmap_| transformed for the current display. void UpdateCursor(); + // Convert the given |location_in_target| to coordinates in the root window. + gfx::PointF GetLocationInRoot(Surface* target, + gfx::PointF location_in_target); + + // Called to check if cursor should be moved to the center of the window when + // sending relative movements. + bool ShouldMoveToCenter(); + + // Moves the cursor to center of the active display. + void MoveCursorToCenterOfActiveDisplay(); + + // Process the delta for relative pointer motion. + void HandleRelativePointerMotion(base::TimeTicks time_stamp, + gfx::PointF location_in_target); + // The delegate instance that all events are dispatched to. PointerDelegate* const delegate_; // The delegate instance that all pinch related events are dispatched to. PointerGesturePinchDelegate* pinch_delegate_ = nullptr; + // The delegate instance that relative movement events are dispatched to. + // Pointer capture is enabled if and only if this is not nullptr. + RelativePointerDelegate* relative_pointer_delegate_ = nullptr; + // The current focus surface for the pointer. Surface* focus_surface_ = nullptr; // The location of the pointer in the current focus surface. gfx::PointF location_; + // The location of the pointer when pointer capture is first enabled. + base::Optional<gfx::Point> location_when_pointer_capture_enabled_; + + // If this is not nullptr, a synthetic move was sent and this points to the + // location of a generated move that was sent which should not be forwarded. + base::Optional<gfx::Point> location_synthetic_move_; + + // The window with input capture. + aura::Window* capture_window_ = nullptr; + // The position of the pointer surface relative to the pointer location. gfx::Point hotspot_;
diff --git a/components/exo/relative_pointer_delegate.h b/components/exo/relative_pointer_delegate.h new file mode 100644 index 0000000..82edd0a --- /dev/null +++ b/components/exo/relative_pointer_delegate.h
@@ -0,0 +1,29 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_EXO_RELATIVE_POINTER_DELEGATE_H_ +#define COMPONENTS_EXO_RELATIVE_POINTER_DELEGATE_H_ + +#include "base/time/time.h" + +namespace exo { +class Pointer; + +// Handles sending relative mouse movements. +class RelativePointerDelegate { + public: + // Called at the top of the pointer's destructor, to give observers a + // chance to remove themselves. + virtual void OnPointerDestroying(Pointer* pointer) = 0; + + virtual void OnPointerRelativeMotion(base::TimeTicks time_stamp, + const gfx::PointF& relativeMotion) = 0; + + protected: + virtual ~RelativePointerDelegate() {} +}; + +} // namespace exo + +#endif // COMPONENTS_EXO_RELATIVE_POINTER_DELEGATE_H_
diff --git a/components/exo/shell_surface_util.cc b/components/exo/shell_surface_util.cc index 3c6d24f6..49d304c 100644 --- a/components/exo/shell_surface_util.cc +++ b/components/exo/shell_surface_util.cc
@@ -10,6 +10,7 @@ #include "ui/aura/client/capture_client.h" #include "ui/aura/window.h" #include "ui/events/event.h" +#include "ui/views/widget/widget.h" #include "ui/wm/core/window_util.h" namespace exo { @@ -72,8 +73,14 @@ Surface* main_surface = GetShellMainSurface(window); // Skip if the event is captured by non exo windows. - if (!main_surface) - return nullptr; + if (!main_surface) { + auto* widget = views::Widget::GetTopLevelWidgetForNativeView(window); + if (!widget) + return nullptr; + main_surface = GetShellMainSurface(widget->GetNativeWindow()); + if (!main_surface) + return nullptr; + } while (true) { aura::Window* focused = window->GetEventHandlerForPoint(
diff --git a/components/exo/wayland/BUILD.gn b/components/exo/wayland/BUILD.gn index d1626ea7..e419eb5 100644 --- a/components/exo/wayland/BUILD.gn +++ b/components/exo/wayland/BUILD.gn
@@ -93,6 +93,8 @@ "zwp_linux_explicit_synchronization.h", "zwp_pointer_gestures.cc", "zwp_pointer_gestures.h", + "zwp_relative_pointer_manager.cc", + "zwp_relative_pointer_manager.h", "zwp_text_input_manager.cc", "zwp_text_input_manager.h", "zxdg_shell.cc", @@ -118,6 +120,7 @@ "//third_party/wayland-protocols:notification_shell_protocol", "//third_party/wayland-protocols:pointer_gestures_protocol", "//third_party/wayland-protocols:presentation_time_protocol", + "//third_party/wayland-protocols:relative_pointer_protocol", "//third_party/wayland-protocols:remote_shell_protocol", "//third_party/wayland-protocols:secure_output_protocol", "//third_party/wayland-protocols:stylus_protocol",
diff --git a/components/exo/wayland/server.cc b/components/exo/wayland/server.cc index 9ce26d4..8009398 100644 --- a/components/exo/wayland/server.cc +++ b/components/exo/wayland/server.cc
@@ -18,6 +18,7 @@ #include <notification-shell-unstable-v1-server-protocol.h> #include <pointer-gestures-unstable-v1-server-protocol.h> #include <presentation-time-server-protocol.h> +#include <relative-pointer-unstable-v1-server-protocol.h> #include <remote-shell-unstable-v1-server-protocol.h> #include <secure-output-unstable-v1-server-protocol.h> #include <stddef.h> @@ -110,6 +111,7 @@ #include "components/exo/wayland/zwp_input_timestamps_manager.h" #include "components/exo/wayland/zwp_linux_explicit_synchronization.h" #include "components/exo/wayland/zwp_pointer_gestures.h" +#include "components/exo/wayland/zwp_relative_pointer_manager.h" #include "components/exo/wayland/zwp_text_input_manager.h" #include "components/exo/wayland/zxdg_shell.h" #include "components/exo/wm_helper_chromeos.h" @@ -735,6 +737,9 @@ bind_input_timestamps_manager); wl_global_create(wl_display_.get(), &zwp_pointer_gestures_v1_interface, 1, display_, bind_pointer_gestures); + wl_global_create(wl_display_.get(), + &zwp_relative_pointer_manager_v1_interface, 1, display_, + bind_relative_pointer_manager); wl_global_create(wl_display_.get(), &zwp_text_input_manager_v1_interface, 1, display_, bind_text_input_manager); wl_global_create(wl_display_.get(), &zxdg_shell_v6_interface, 1, display_,
diff --git a/components/exo/wayland/zwp_relative_pointer_manager.cc b/components/exo/wayland/zwp_relative_pointer_manager.cc new file mode 100644 index 0000000..fcf9079 --- /dev/null +++ b/components/exo/wayland/zwp_relative_pointer_manager.cc
@@ -0,0 +1,102 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/exo/wayland/zwp_relative_pointer_manager.h" + +#include <relative-pointer-unstable-v1-server-protocol.h> +#include <wayland-server-core.h> +#include <wayland-server-protocol-core.h> + +#include <memory> + +#include "components/exo/pointer.h" +#include "components/exo/relative_pointer_delegate.h" +#include "components/exo/wayland/server_util.h" + +namespace exo { +namespace wayland { + +namespace { + +//////////////////////////////////////////////////////////////////////////////// +// relative_pointer_v1 interface: + +class WaylandRelativePointerDelegate : public RelativePointerDelegate { + public: + WaylandRelativePointerDelegate(wl_resource* resource, Pointer* pointer) + : resource_(resource), pointer_(pointer) { + pointer_->EnablePointerCapture(this); + } + + ~WaylandRelativePointerDelegate() override { + if (pointer_) + pointer_->DisablePointerCapture(); + } + void OnPointerDestroying(Pointer* pointer) override { pointer_ = nullptr; } + void OnPointerRelativeMotion(base::TimeTicks time_stamp, + const gfx::PointF& relativeMotion) override { + zwp_relative_pointer_v1_send_relative_motion( + resource_, // resource + 0, // utime_hi + TimeTicksToMilliseconds(time_stamp), // utime_lo + wl_fixed_from_double(relativeMotion.x()), // dx + wl_fixed_from_double(relativeMotion.y()), // dy + wl_fixed_from_double(relativeMotion.x()), // dx_unaccel + wl_fixed_from_double(relativeMotion.y())); // dy_unaccel + } + + private: + wl_resource* const resource_; + Pointer* pointer_; + + DISALLOW_COPY_AND_ASSIGN(WaylandRelativePointerDelegate); +}; + +void relative_pointer_destroy(wl_client* client, wl_resource* resource) { + wl_resource_destroy(resource); +} + +const struct zwp_relative_pointer_v1_interface relative_pointer_impl = { + relative_pointer_destroy}; + +//////////////////////////////////////////////////////////////////////////////// +// relative_pointer_manager_v1 interface: + +void relative_pointer_manager_destroy(wl_client* client, + wl_resource* resource) { + wl_resource_destroy(resource); +} + +void relative_pointer_manager_get_relative_pointer( + wl_client* client, + wl_resource* resource, + uint32_t id, + wl_resource* pointer_resource) { + Pointer* pointer = GetUserDataAs<Pointer>(pointer_resource); + wl_resource* relative_pointer_resource = + wl_resource_create(client, &zwp_relative_pointer_v1_interface, 1, id); + SetImplementation(relative_pointer_resource, &relative_pointer_impl, + std::make_unique<WaylandRelativePointerDelegate>( + relative_pointer_resource, pointer)); +} + +const struct zwp_relative_pointer_manager_v1_interface + relative_pointer_manager_impl = { + relative_pointer_manager_destroy, + relative_pointer_manager_get_relative_pointer}; + +} // namespace + +void bind_relative_pointer_manager(wl_client* client, + void* data, + uint32_t version, + uint32_t id) { + wl_resource* resource = wl_resource_create( + client, &zwp_relative_pointer_manager_v1_interface, version, id); + wl_resource_set_implementation(resource, &relative_pointer_manager_impl, data, + nullptr); +} + +} // namespace wayland +} // namespace exo
diff --git a/components/exo/wayland/zwp_relative_pointer_manager.h b/components/exo/wayland/zwp_relative_pointer_manager.h new file mode 100644 index 0000000..a5e87b80 --- /dev/null +++ b/components/exo/wayland/zwp_relative_pointer_manager.h
@@ -0,0 +1,23 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_EXO_WAYLAND_ZWP_RELATIVE_POINTER_MANAGER_H_ +#define COMPONENTS_EXO_WAYLAND_ZWP_RELATIVE_POINTER_MANAGER_H_ + +#include <stdint.h> + +struct wl_client; + +namespace exo { +namespace wayland { + +void bind_relative_pointer_manager(wl_client* client, + void* data, + uint32_t version, + uint32_t id); + +} // namespace wayland +} // namespace exo + +#endif // COMPONENTS_EXO_WAYLAND_ZWP_RELATIVE_POINTER_MANAGER_H_ \ No newline at end of file
diff --git a/components/feed/OWNERS b/components/feed/OWNERS index 90e498d..2efa28a 100644 --- a/components/feed/OWNERS +++ b/components/feed/OWNERS
@@ -4,6 +4,5 @@ skym@chromium.org zea@chromium.org -per-file *Test.java=aluo@chromium.org # Team: chrome-jardin-team@google.com # COMPONENT: UI>Browser>ContentSuggestions>Feed
diff --git a/components/feed/core/feed_scheduler_host.cc b/components/feed/core/feed_scheduler_host.cc index cd032e4..2859788b 100644 --- a/components/feed/core/feed_scheduler_host.cc +++ b/components/feed/core/feed_scheduler_host.cc
@@ -557,4 +557,8 @@ } } +UserClassifier* FeedSchedulerHost::user_classifier() { + return &user_classifier_; +} + } // namespace feed
diff --git a/components/feed/core/feed_scheduler_host.h b/components/feed/core/feed_scheduler_host.h index a0d00d0..ff1b7d7 100644 --- a/components/feed/core/feed_scheduler_host.h +++ b/components/feed/core/feed_scheduler_host.h
@@ -134,6 +134,9 @@ // the return value, and if true, the caller should start a refresh. bool OnArticlesCleared(bool suppress_refreshes); + // Surface user classifier data for internals debugging page. + UserClassifier* user_classifier(); + private: FRIEND_TEST_ALL_PREFIXES(FeedSchedulerHostTest, GetTriggerThreshold);
diff --git a/components/omnibox/browser/autocomplete_provider.cc b/components/omnibox/browser/autocomplete_provider.cc index 19fd94d..72f8163 100644 --- a/components/omnibox/browser/autocomplete_provider.cc +++ b/components/omnibox/browser/autocomplete_provider.cc
@@ -127,17 +127,6 @@ std::swap(class_of_find_text, class_of_additional_text); } - // For this experiment, we want to color the search query text blue like URLs. - // Therefore, we add the URL class to the find and additional text. - if (base::FeatureList::IsEnabled( - omnibox::kUIExperimentBlueSearchLoopAndSearchQuery) && - text_is_search_query) { - class_of_find_text = (ACMatchClassification::Style)( - class_of_find_text | ACMatchClassification::URL); - class_of_additional_text = (ACMatchClassification::Style)( - class_of_additional_text | ACMatchClassification::URL); - } - ACMatchClassifications match_class; size_t current_position = 0;
diff --git a/components/pdf_strings.grdp b/components/pdf_strings.grdp index 05d00fc..0290c9c79 100644 --- a/components/pdf_strings.grdp +++ b/components/pdf_strings.grdp
@@ -61,10 +61,24 @@ other {Page #}} </message> <if expr="chromeos"> + <message name="IDS_PDF_DISCARD_FORM_CHANGES" desc="Title for a dialog that informs the user that the changes they have made to a form will be lost if they continue"> + Discard changes? + </message> + <message name="IDS_PDF_DISCARD_FORM_CHANGES_DETAIL" desc="Warning message in dialog that informs the user that the changes they have made to a form will be lost if they continue"> + Form changes will be lost. Are you sure you want to continue? + </message> + <message name="IDS_PDF_KEEP_EDITING" desc="Button label for the button that lets the user return and keep editing the changes they made"> + Keep editing + </message> + <message name="IDS_PDF_DISCARD" desc="Button label for the button that lets the user discard their unneeded changes"> + Discard + </message> <message name="IDS_PDF_ANNOTATION_ANNOTATE" desc="Button tooltip for entering the 'Annotation mode' which allows writing, drawing and highlighting of the PDF document"> Annotate </message> - + <message name="IDS_PDF_ANNOTATION_UNAVAILABLE" desc="Button tooltip to explain that 'Annotation mode' which allows writing, drawing and highlighting of the PDF document is not available"> + Annotation not available + </message> <message name="IDS_PDF_ANNOTATION_DOCUMENT_TOO_LARGE" desc="Button tooltip to indicate why 'Annotation mode' which allows writing, drawing and highlighting of the PDF document is not available due to the document being too large"> Document is too large to be annotated </message>
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index 326820d..6b26cf0 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -957,6 +957,15 @@ ] }, { + 'name': 'GoogleAssistant', + 'type': 'group', + 'caption': '''Google Assistant''', + 'desc': '''Controls settings for Google Assistant.''', + 'policies': [ + 'VoiceInteractionContextEnabled', + ] + }, + { 'name': 'HomepageLocation', 'type': 'string', 'schema': { 'type': 'string' }, @@ -4590,8 +4599,7 @@ 'required': ['devices', 'urls'] } }, - 'supported_on': ['chrome_os:71-', 'android:71-', 'chrome.*:71-'], - 'future': True, + 'supported_on': ['chrome_os:74-', 'chrome.*:74-'], 'features': { 'dynamic_refresh': True, 'per_profile': True, @@ -14771,6 +14779,24 @@ If this policy is not set, networking code may run out of the browser process depending on field trials of the NetworkService experiment.''', }, + { + 'name': 'VoiceInteractionContextEnabled', + 'type': 'main', + 'schema': { 'type': 'boolean' }, + 'supported_on': ['chrome_os:74-'], + 'tags' : ['google-sharing'], + 'features': { + 'dynamic_refresh': True, + 'per_profile': True, + }, + 'example_value': True, + 'id': 527, + 'caption': '''"Allow Google Assistant to access screen context"''', + 'desc': '''This policy gives Google Assistant permission to access screen context and send the info to server. + If the policy is enabled, Google Assistant will be allowed to access screen context. + If the policy is disabled, Google Assistant will not be allowed to access screen context. + If not set, users can decide whether to allow Google Assistant to access screen context or not''', + }, ], 'messages': { @@ -14936,5 +14962,5 @@ }, 'placeholders': [], 'deleted_policy_ids': [412], - 'highest_id_currently_used': 526 + 'highest_id_currently_used': 527 }
diff --git a/components/previews/content/previews_decider_impl.cc b/components/previews/content/previews_decider_impl.cc index 8d89de0..db9dbd09 100644 --- a/components/previews/content/previews_decider_impl.cc +++ b/components/previews/content/previews_decider_impl.cc
@@ -94,7 +94,7 @@ // Returns true if ECT should be checked for |type| only at the commit time. If // true is returned, then ECT need not be checked at the navigation time. -bool CheckForUnknownECTOnlyAtCommitTime(PreviewsType type) { +bool CheckECTOnlyAtCommitTime(PreviewsType type) { switch (type) { case PreviewsType::NOSCRIPT: case PreviewsType::RESOURCE_LOADING_HINTS: @@ -278,6 +278,14 @@ if (url.has_username() || url.has_password()) return PreviewsEligibilityReason::URL_HAS_BASIC_AUTH; + // Trigger the USER_RECENTLY_OPTED_OUT rule when a reload on a preview has + // occurred recently. + if (recent_preview_reload_time_ && + recent_preview_reload_time_.value() + params::SingleOptOutDuration() > + clock_->Now()) { + return PreviewsEligibilityReason::USER_RECENTLY_OPTED_OUT; + } + // In the case that the user has chosen to ignore the normal blacklist rules // (flags or interventions-internals), a preview should still not be served // for 5 seconds after the last opt out. This allows "show original" to @@ -314,9 +322,8 @@ // hints. This defers checking ECT for server previews because the server will // perform its own ECT check and for previews with hints because the hints may // specify variable ECT thresholds for slow page hints. - if (!is_drp_server_preview && !ShouldCheckOptimizationHints(type)) { - if (effective_connection_type_ == net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN && - !CheckForUnknownECTOnlyAtCommitTime(type)) { + if (!is_drp_server_preview && !CheckECTOnlyAtCommitTime(type)) { + if (effective_connection_type_ == net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) { return PreviewsEligibilityReason::NETWORK_QUALITY_UNAVAILABLE; } passed_reasons->push_back( @@ -492,7 +499,7 @@ // connectivity as null. See https://crbug.com/838969. So, we do not trigger // previews when |ect| is net::EFFECTIVE_CONNECTION_TYPE_OFFLINE. net::EffectiveConnectionType ect = previews_data->navigation_ect(); - if (CheckForUnknownECTOnlyAtCommitTime(type) && + if (CheckECTOnlyAtCommitTime(type) && ect == net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) { // Update the |ect| to the current value. ect = effective_connection_type_; @@ -540,4 +547,10 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); effective_connection_type_ = effective_connection_type; } + +void PreviewsDeciderImpl::AddPreviewReload() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + recent_preview_reload_time_ = clock_->Now(); +} + } // namespace previews
diff --git a/components/previews/content/previews_decider_impl.h b/components/previews/content/previews_decider_impl.h index aab49cc..89581818 100644 --- a/components/previews/content/previews_decider_impl.h +++ b/components/previews/content/previews_decider_impl.h
@@ -131,6 +131,14 @@ void SetEffectiveConnectionType( net::EffectiveConnectionType effective_connection_type); + PreviewsOptimizationGuide* previews_opt_guide() const { + return previews_opt_guide_.get(); + } + + // When a preview is reloaded, this is called. No Previews are allowed for + // params::SingleOptOutDuration after that reload is reported. + void AddPreviewReload(); + protected: // Sets a blacklist for testing. void SetPreviewsBlacklistForTesting( @@ -201,6 +209,8 @@ base::Clock* clock_; + base::Optional<base::Time> recent_preview_reload_time_; + // Whether the preview is enabled. Valid after Initialize() is called. PreviewsIsEnabledCallback is_enabled_callback_;
diff --git a/components/previews/content/previews_decider_impl_unittest.cc b/components/previews/content/previews_decider_impl_unittest.cc index 7fed0ce..afd5115e 100644 --- a/components/previews/content/previews_decider_impl_unittest.cc +++ b/components/previews/content/previews_decider_impl_unittest.cc
@@ -1555,6 +1555,38 @@ ::testing::Contains(PreviewsEligibilityReason::USER_RECENTLY_OPTED_OUT)); } +TEST_F(PreviewsDeciderImplTest, ReloadsTriggerFiveMinuteRule) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures( + {features::kPreviews, features::kClientLoFi, + features::kPreviewsReloadsAreSoftOptOuts}, + {}); + InitializeUIService(); + ReportEffectiveConnectionType(net::EFFECTIVE_CONNECTION_TYPE_2G); + + PreviewsUserData user_data(kDefaultPageId); + EXPECT_TRUE(previews_decider_impl()->ShouldAllowPreviewAtNavigationStart( + &user_data, GURL("https://www.google.com"), false, PreviewsType::LOFI)); + + previews_decider_impl()->AddPreviewNavigation( + GURL("http://wwww.somedomain.com"), false, PreviewsType::LOFI, 1); + + previews_decider_impl()->AddPreviewReload(); + + EXPECT_FALSE(previews_decider_impl()->ShouldAllowPreviewAtNavigationStart( + &user_data, GURL("https://www.google.com"), false, PreviewsType::LOFI)); + EXPECT_EQ(PreviewsEligibilityReason::USER_RECENTLY_OPTED_OUT, + ui_service()->decision_reasons().back()); + + clock_.Advance(base::TimeDelta::FromMinutes(6)); + + EXPECT_TRUE(previews_decider_impl()->ShouldAllowPreviewAtNavigationStart( + &user_data, GURL("https://www.google.com"), false, PreviewsType::LOFI)); + EXPECT_THAT( + ui_service()->decision_passed_reasons().back(), + ::testing::Contains(PreviewsEligibilityReason::USER_RECENTLY_OPTED_OUT)); +} + TEST_F(PreviewsDeciderImplTest, LoFi_LogDecisionMadeNetworkQualityNotAvailable) { base::test::ScopedFeatureList scoped_feature_list;
diff --git a/components/previews/content/previews_optimization_guide.cc b/components/previews/content/previews_optimization_guide.cc index cc16e22f..2caf0e3 100644 --- a/components/previews/content/previews_optimization_guide.cc +++ b/components/previews/content/previews_optimization_guide.cc
@@ -251,6 +251,9 @@ void PreviewsOptimizationGuide::OnHintsUpdated() { DCHECK(ui_task_runner_->BelongsToCurrentThread()); + if (!next_update_closure_.is_null()) + std::move(next_update_closure_).Run(); + // Record the result of updating the hints. This is used as a signal for the // hints being fully processed in testing. LOCAL_HISTOGRAM_BOOLEAN( @@ -258,4 +261,11 @@ hints_ != NULL); } +void PreviewsOptimizationGuide::ListenForNextUpdateForTesting( + base::OnceClosure next_update_closure) { + DCHECK(next_update_closure_.is_null()) + << "Only one update closure is supported at a time"; + next_update_closure_ = std::move(next_update_closure); +} + } // namespace previews
diff --git a/components/previews/content/previews_optimization_guide.h b/components/previews/content/previews_optimization_guide.h index 6b300a9b..8f8cafd3 100644 --- a/components/previews/content/previews_optimization_guide.h +++ b/components/previews/content/previews_optimization_guide.h
@@ -9,6 +9,7 @@ #include <string> #include <vector> +#include "base/callback_forward.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" @@ -90,6 +91,9 @@ PreviewsHints* GetHintsForTesting() { return hints_.get(); } + // |next_update_closure| is called the next time the hints have been updated. + void ListenForNextUpdateForTesting(base::OnceClosure next_update_closure); + private: // Callback run after the hint cache is fully initialized. At this point, the // PreviewsOptimizationGuide is ready to process components from the @@ -126,6 +130,9 @@ // The current hints used for this optimization guide. std::unique_ptr<PreviewsHints> hints_; + // Used in testing to subscribe to an update event in this class. + base::OnceClosure next_update_closure_; + // Used to get |weak_ptr_| to self on the UI thread. base::WeakPtrFactory<PreviewsOptimizationGuide> ui_weak_ptr_factory_;
diff --git a/components/previews/core/previews_features.cc b/components/previews/core/previews_features.cc index 3816111..7bd129d 100644 --- a/components/previews/core/previews_features.cc +++ b/components/previews/core/previews_features.cc
@@ -109,5 +109,10 @@ const base::Feature kDataSaverLiteModeRebranding{ "DataSaverLiteModeRebranding", base::FEATURE_DISABLED_BY_DEFAULT}; +// When enabled, reloading on a preview will cause the session (5 minute) rule +// to trigger. +const base::Feature kPreviewsReloadsAreSoftOptOuts{ + "PreviewsReloadsAreSoftOptOuts", base::FEATURE_DISABLED_BY_DEFAULT}; + } // namespace features } // namespace previews
diff --git a/components/previews/core/previews_features.h b/components/previews/core/previews_features.h index 9266dde..99a43ac5 100644 --- a/components/previews/core/previews_features.h +++ b/components/previews/core/previews_features.h
@@ -25,6 +25,7 @@ extern const base::Feature kPreviewsDisallowedOnReloads; extern const base::Feature kHTTPSServerPreviewsUsingURLLoader; extern const base::Feature kDataSaverLiteModeRebranding; +extern const base::Feature kPreviewsReloadsAreSoftOptOuts; } // namespace features } // namespace previews
diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc index 6ed56df6..560a6e4 100644 --- a/components/printing/renderer/print_render_frame_helper.cc +++ b/components/printing/renderer/print_render_frame_helper.cc
@@ -1068,9 +1068,9 @@ scripting_throttler_.IsAllowed(frame); } -void PrintRenderFrameHelper::DidStartProvisionalLoad( - blink::WebDocumentLoader* document_loader, - bool is_content_initiated) { +void PrintRenderFrameHelper::DidStartNavigation( + const GURL& url, + base::Optional<blink::WebNavigationType> navigation_type) { is_loading_ = true; }
diff --git a/components/printing/renderer/print_render_frame_helper.h b/components/printing/renderer/print_render_frame_helper.h index 3469080..c4effb05 100644 --- a/components/printing/renderer/print_render_frame_helper.h +++ b/components/printing/renderer/print_render_frame_helper.h
@@ -184,8 +184,9 @@ // RenderFrameObserver implementation. void OnDestruct() override; - void DidStartProvisionalLoad(blink::WebDocumentLoader* document_loader, - bool is_content_initiated) override; + void DidStartNavigation( + const GURL& url, + base::Optional<blink::WebNavigationType> navigation_type) override; void DidFailProvisionalLoad(const blink::WebURLError& error) override; void DidFinishLoad() override; void ScriptedPrint(bool user_initiated) override;
diff --git a/components/security_interstitials/content/security_interstitial_page.cc b/components/security_interstitials/content/security_interstitial_page.cc index bebef31..f81a05e 100644 --- a/components/security_interstitials/content/security_interstitial_page.cc +++ b/components/security_interstitials/content/security_interstitial_page.cc
@@ -66,10 +66,6 @@ create_view_ = false; } -bool SecurityInterstitialPage::ShouldDisplayURL() const { - return true; -} - std::string SecurityInterstitialPage::GetHTMLContents() { base::DictionaryValue load_time_data; PopulateInterstitialStrings(&load_time_data);
diff --git a/components/security_interstitials/content/security_interstitial_page.h b/components/security_interstitials/content/security_interstitial_page.h index 7450fb0..0855d45 100644 --- a/components/security_interstitials/content/security_interstitial_page.h +++ b/components/security_interstitials/content/security_interstitial_page.h
@@ -50,10 +50,6 @@ // to e.g. update metrics. virtual void OnInterstitialClosing() = 0; - // Whether a URL should be displayed on this interstitial page. This is - // respected by committed interstitials only. - virtual bool ShouldDisplayURL() const; - protected: // Returns true if the interstitial should create a new navigation entry. virtual bool ShouldCreateNewNavigation() const = 0;
diff --git a/components/security_interstitials/content/security_interstitial_tab_helper.cc b/components/security_interstitials/content/security_interstitial_tab_helper.cc index 4458f5db..0971008 100644 --- a/components/security_interstitials/content/security_interstitial_tab_helper.cc +++ b/components/security_interstitials/content/security_interstitial_tab_helper.cc
@@ -60,15 +60,6 @@ helper->SetBlockingPage(navigation_id, std::move(blocking_page)); } -bool SecurityInterstitialTabHelper::ShouldDisplayURL() const { - CHECK(IsDisplayingInterstitial()); - return blocking_page_for_currently_committed_navigation_->ShouldDisplayURL(); -} - -bool SecurityInterstitialTabHelper::IsDisplayingInterstitial() const { - return blocking_page_for_currently_committed_navigation_ != nullptr; -} - security_interstitials::SecurityInterstitialPage* SecurityInterstitialTabHelper:: GetBlockingPageForCurrentlyCommittedNavigationForTesting() {
diff --git a/components/security_interstitials/content/security_interstitial_tab_helper.h b/components/security_interstitials/content/security_interstitial_tab_helper.h index 62dbb0d3..bafc5e6 100644 --- a/components/security_interstitials/content/security_interstitial_tab_helper.h +++ b/components/security_interstitials/content/security_interstitial_tab_helper.h
@@ -43,12 +43,6 @@ std::unique_ptr<security_interstitials::SecurityInterstitialPage> blocking_page); - // Determines whether a URL should be shown on the current navigation page. - bool ShouldDisplayURL() const; - - // Whether this tab helper is tracking a currently-displaying interstitial. - bool IsDisplayingInterstitial() const; - security_interstitials::SecurityInterstitialPage* GetBlockingPageForCurrentlyCommittedNavigationForTesting();
diff --git a/components/send_tab_to_self/send_tab_to_self_entry.h b/components/send_tab_to_self/send_tab_to_self_entry.h index b8c9003..06d36495 100644 --- a/components/send_tab_to_self/send_tab_to_self_entry.h +++ b/components/send_tab_to_self/send_tab_to_self_entry.h
@@ -22,6 +22,7 @@ // A tab that is being shared. The URL is a unique identifier for an entry, as // such it should not be empty and is the only thing considered when comparing // entries. +// The java version of this class: SendTabToSelfEntry.java class SendTabToSelfEntry { public: // Creates a SendTabToSelf entry. |url| and |title| are the main fields of the
diff --git a/components/services/heap_profiling/json_exporter.cc b/components/services/heap_profiling/json_exporter.cc index 9a03102..8d87039 100644 --- a/components/services/heap_profiling/json_exporter.cc +++ b/components/services/heap_profiling/json_exporter.cc
@@ -160,7 +160,7 @@ } void WriteMemoryMaps(const ExportParams& params, std::ostream& out) { - base::trace_event::TracedValue traced_value; + base::trace_event::TracedValue traced_value(0, /*force_json=*/true); memory_instrumentation::TracingObserver::MemoryMapsAsValueInto( params.maps, &traced_value, params.strip_path_from_mapped_files); out << "\"process_mmaps\":" << traced_value.ToString();
diff --git a/components/signin/core/browser/account_fetcher_service.cc b/components/signin/core/browser/account_fetcher_service.cc index ad52d28..45c022a 100644 --- a/components/signin/core/browser/account_fetcher_service.cc +++ b/components/signin/core/browser/account_fetcher_service.cc
@@ -116,8 +116,11 @@ } void AccountFetcherService::EnableNetworkFetchesForTest() { - OnNetworkInitialized(); - OnRefreshTokensLoaded(); + if (!network_initialized_) + OnNetworkInitialized(); + + if (!refresh_tokens_loaded_) + OnRefreshTokensLoaded(); } void AccountFetcherService::RefreshAllAccountInfo(bool only_fetch_if_invalid) {
diff --git a/components/signin/core/browser/account_reconcilor_unittest.cc b/components/signin/core/browser/account_reconcilor_unittest.cc index 14e0cfc..2140932 100644 --- a/components/signin/core/browser/account_reconcilor_unittest.cc +++ b/components/signin/core/browser/account_reconcilor_unittest.cc
@@ -22,17 +22,10 @@ #include "components/image_fetcher/core/fake_image_decoder.h" #include "components/prefs/pref_registry_simple.h" #include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/account_fetcher_service.h" #include "components/signin/core/browser/account_reconcilor.h" -#include "components/signin/core/browser/account_tracker_service.h" -#include "components/signin/core/browser/fake_account_fetcher_service.h" -#include "components/signin/core/browser/fake_profile_oauth2_token_service.h" -#include "components/signin/core/browser/fake_signin_manager.h" #include "components/signin/core/browser/list_accounts_test_utils.h" #include "components/signin/core/browser/mirror_account_reconcilor_delegate.h" -#include "components/signin/core/browser/profile_oauth2_token_service.h" #include "components/signin/core/browser/signin_buildflags.h" -#include "components/signin/core/browser/signin_manager.h" #include "components/signin/core/browser/signin_metrics.h" #include "components/signin/core/browser/signin_pref_names.h" #include "components/signin/core/browser/test_signin_client.h" @@ -236,7 +229,6 @@ return &identity_test_env_; } TestSigninClient* test_signin_client() { return &test_signin_client_; } - AccountTrackerService* account_tracker() { return &account_tracker_; } base::HistogramTester* histogram_tester() { return &histogram_tester_; } MockAccountReconcilor* GetMockReconcilor(); @@ -275,11 +267,6 @@ signin::AccountConsistencyMethod account_consistency_; sync_preferences::TestingPrefServiceSyncable pref_service_; TestSigninClient test_signin_client_; - FakeProfileOAuth2TokenService token_service_; - AccountTrackerService account_tracker_; - FakeAccountFetcherService account_fetcher_; - GaiaCookieManagerService cookie_manager_service_; - FakeSigninManagerForTesting signin_manager_; identity::IdentityTestEnvironment identity_test_env_; std::unique_ptr<MockAccountReconcilor> mock_reconcilor_; base::HistogramTester histogram_tester_; @@ -327,46 +314,14 @@ AccountReconcilorTest::AccountReconcilorTest() : account_consistency_(signin::AccountConsistencyMethod::kDisabled), test_signin_client_(&pref_service_), - token_service_(&pref_service_), - cookie_manager_service_( - &token_service_, - &test_signin_client_, - base::BindRepeating( - [](network::TestURLLoaderFactory* test_url_loader_factory) - -> scoped_refptr<network::SharedURLLoaderFactory> { - return test_url_loader_factory->GetSafeWeakWrapper(); - }, - &test_url_loader_factory_)), -#if defined(OS_CHROMEOS) - signin_manager_(&test_signin_client_, &token_service_, &account_tracker_), -#else - signin_manager_(&test_signin_client_, - &token_service_, - &account_tracker_, - &cookie_manager_service_), - -#endif - identity_test_env_(&pref_service_, - &account_tracker_, - &account_fetcher_, - &token_service_, - &signin_manager_, - &cookie_manager_service_, - &test_url_loader_factory_) { - AccountTrackerService::RegisterPrefs(pref_service_.registry()); - AccountFetcherService::RegisterPrefs(pref_service_.registry()); - ProfileOAuth2TokenService::RegisterProfilePrefs(pref_service_.registry()); - SigninManagerBase::RegisterProfilePrefs(pref_service_.registry()); - SigninManagerBase::RegisterPrefs(pref_service_.registry()); + identity_test_env_(&test_url_loader_factory_, + &pref_service_, + account_consistency_, + &test_signin_client_) { pref_service_.registry()->RegisterBooleanPref( prefs::kTokenServiceDiceCompatible, false); - account_tracker_.Initialize(&pref_service_, base::FilePath()); - account_fetcher_.Initialize( - &test_signin_client_, &token_service_, &account_tracker_, - std::make_unique<image_fetcher::FakeImageDecoder>()); signin::SetListAccountsResponseHttpNotFound(&test_url_loader_factory_); - signin_manager_.Initialize(nullptr); // The reconcilor should not be built before the test can set the account // consistency method. @@ -395,12 +350,7 @@ AccountReconcilorTest::~AccountReconcilorTest() { if (mock_reconcilor_) mock_reconcilor_->Shutdown(); - signin_manager_.Shutdown(); - cookie_manager_service_.Shutdown(); - account_fetcher_.Shutdown(); - account_tracker_.Shutdown(); test_signin_client_.Shutdown(); - token_service_.Shutdown(); } AccountInfo AccountReconcilorTest::ConnectProfileToAccount( @@ -413,13 +363,18 @@ std::string AccountReconcilorTest::PickAccountIdForAccount( const std::string& gaia_id, const std::string& username) { - return account_tracker()->PickAccountIdForAccount(gaia_id, username); + return identity_test_env()->identity_manager()->LegacyPickAccountIdForAccount( + gaia_id, username); } std::string AccountReconcilorTest::SeedAccountInfo( const std::string& gaia_id, const std::string& username) { - return account_tracker()->SeedAccountInfo(gaia_id, username); + AccountInfo account_info; + account_info.gaia = gaia_id; + account_info.email = username; + return identity_test_env()->identity_manager()->LegacySeedAccountInfo( + account_info); } void AccountReconcilorTest::SimulateAddAccountToCookieCompleted( @@ -926,8 +881,8 @@ if (token.is_authenticated) { account_id = ConnectProfileToAccount(token.email).account_id; } else { - account_id = SeedAccountInfo(token.gaia_id, token.email); - identity_test_env()->SetRefreshTokenForAccount(account_id); + account_id = + identity_test_env()->MakeAccountAvailable(token.email).account_id; } if (token.has_error) { identity::UpdatePersistentErrorOfRefreshTokenForAccount( @@ -1045,8 +1000,8 @@ if (token.is_authenticated) { account_id = ConnectProfileToAccount(token.email).account_id; } else { - account_id = SeedAccountInfo(token.gaia_id, token.email); - identity_test_env()->SetRefreshTokenForAccount(account_id); + account_id = + identity_test_env()->MakeAccountAvailable(token.email).account_id; } if (token.has_error) { identity::UpdatePersistentErrorOfRefreshTokenForAccount( @@ -1746,8 +1701,8 @@ if (token.is_authenticated) { account_id = ConnectProfileToAccount(token.email).account_id; } else { - account_id = SeedAccountInfo(token.gaia_id, token.email); - identity_test_env()->SetRefreshTokenForAccount(account_id); + account_id = + identity_test_env()->MakeAccountAvailable(token.email).account_id; } if (token.has_error) { identity::UpdatePersistentErrorOfRefreshTokenForAccount( @@ -2093,8 +2048,9 @@ // token service, will be considered the same as "dots@gmail.com" as returned // by gaia::ParseListAccountsData(). TEST_P(AccountReconcilorMirrorEndpointParamTest, StartReconcileNoopWithDots) { - if (account_tracker()->GetMigrationState() != - AccountTrackerService::MIGRATION_NOT_STARTED) { + if (identity_test_env()->identity_manager()->GetAccountIdMigrationState() != + identity::IdentityManager::AccountIdMigrationState:: + MIGRATION_NOT_STARTED) { return; }
diff --git a/components/signin/core/browser/fake_profile_oauth2_token_service.cc b/components/signin/core/browser/fake_profile_oauth2_token_service.cc index 511bfc94..9e92a4e 100644 --- a/components/signin/core/browser/fake_profile_oauth2_token_service.cc +++ b/components/signin/core/browser/fake_profile_oauth2_token_service.cc
@@ -134,6 +134,12 @@ bool scope_matches = all_scopes || it->scopes == scope; bool account_matches = account_id.empty() || account_id == it->account_id; if (account_matches && scope_matches) { + for (auto& diagnostic_observer : GetDiagnicsObservers()) { + diagnostic_observer.OnFetchAccessTokenComplete( + account_id, it->request->GetConsumerId(), scope, error, + base::Time()); + } + it->request->InformConsumer( error, OAuth2AccessTokenConsumer::TokenResponse( token_response.access_token, @@ -189,7 +195,7 @@ FROM_HERE, base::BindOnce(&FakeProfileOAuth2TokenService::CompleteRequests, weak_ptr_factory_.GetWeakPtr(), account_id, - /*all_scoped=*/true, ScopeSet(), + /*all_scoped=*/true, scopes, GoogleServiceAuthError::AuthErrorNone(), OAuth2AccessTokenConsumer::TokenResponse( "access_token", base::Time::Max(), std::string())));
diff --git a/components/signin/core/browser/signin_manager.cc b/components/signin/core/browser/signin_manager.cc index dbe01004..8e30618 100644 --- a/components/signin/core/browser/signin_manager.cc +++ b/components/signin/core/browser/signin_manager.cc
@@ -155,11 +155,9 @@ base::Bind(&SigninManager::OnSigninAllowedPrefChanged, base::Unretained(this))); - std::string account_id = - signin_client()->GetPrefs()->GetString(prefs::kGoogleServicesAccountId); - std::string user = account_id.empty() ? std::string() : - account_tracker_service()->GetAccountInfo(account_id).email; - if (!account_id.empty() && (!IsAllowedUsername(user) || !IsSigninAllowed())) { + AccountInfo account_info = GetAuthenticatedAccountInfo(); + if (!account_info.account_id.empty() && + (!IsAllowedUsername(account_info.email) || !IsSigninAllowed())) { // User is signed in, but the username is invalid or signin is no longer // allowed, so the user must be sign out. //
diff --git a/components/signin/core/browser/signin_manager_unittest.cc b/components/signin/core/browser/signin_manager_unittest.cc index 517a5738..0e1db82 100644 --- a/components/signin/core/browser/signin_manager_unittest.cc +++ b/components/signin/core/browser/signin_manager_unittest.cc
@@ -347,10 +347,10 @@ TEST_F(SigninManagerTest, SigninNotAllowed) { std::string user("user@google.com"); - user_prefs_.SetString(prefs::kGoogleServicesAccountId, user); + std::string account_id = AddToAccountTracker("gaia_id", user); + user_prefs_.SetString(prefs::kGoogleServicesAccountId, account_id); user_prefs_.SetBoolean(prefs::kSigninAllowed, false); CreateSigninManager(); - AddToAccountTracker("gaia_id", user); // Currently signing in is prohibited by policy, so should be signed out. EXPECT_EQ("", manager_->GetAuthenticatedAccountInfo().email); EXPECT_EQ("", manager_->GetAuthenticatedAccountId());
diff --git a/components/subresource_filter/content/renderer/subresource_filter_agent_unittest.cc b/components/subresource_filter/content/renderer/subresource_filter_agent_unittest.cc index 3963044..c038b95f 100644 --- a/components/subresource_filter/content/renderer/subresource_filter_agent_unittest.cc +++ b/components/subresource_filter/content/renderer/subresource_filter_agent_unittest.cc
@@ -138,12 +138,14 @@ } void StartLoadWithoutSettingActivationState() { - agent_as_rfo()->DidStartProvisionalLoad(nullptr, true); + agent_as_rfo()->DidStartNavigation(GURL(), base::nullopt); + agent_as_rfo()->ReadyToCommitNavigation(nullptr); agent_as_rfo()->DidCreateNewDocument(); } void PerformSameDocumentNavigationWithoutSettingActivationLevel() { - agent_as_rfo()->DidStartProvisionalLoad(nullptr, true); + agent_as_rfo()->DidStartNavigation(GURL(), base::nullopt); + agent_as_rfo()->ReadyToCommitNavigation(nullptr); // No DidCreateNewDocument, since same document navigations by definition // don't create a new document. // No DidFinishLoad is called in this case. @@ -160,7 +162,8 @@ void StartLoadAndSetActivationState( mojom::ActivationState state, AdFrameType ad_type = AdFrameType::kNonAd) { - agent_as_rfo()->DidStartProvisionalLoad(nullptr, true); + agent_as_rfo()->DidStartNavigation(GURL(), base::nullopt); + agent_as_rfo()->ReadyToCommitNavigation(nullptr); agent()->ActivateForNextCommittedLoad(state.Clone(), ad_type); agent_as_rfo()->DidCreateNewDocument(); } @@ -464,7 +467,8 @@ ASSERT_NO_FATAL_FAILURE( SetTestRulesetToDisallowURLsWithPathSuffix(kTestBothURLsPathSuffix)); ExpectNoSubresourceFilterGetsInjected(); - agent_as_rfo()->DidStartProvisionalLoad(nullptr, true); + agent_as_rfo()->DidStartNavigation(GURL(), base::nullopt); + agent_as_rfo()->ReadyToCommitNavigation(nullptr); mojom::ActivationStatePtr state = mojom::ActivationState::New(); state->activation_level = mojom::ActivationLevel::kEnabled; state->measure_performance = true; @@ -472,7 +476,8 @@ AdFrameType::kNonAd /* ad_type */); agent_as_rfo()->DidFailProvisionalLoad( blink::WebURLError(net::ERR_FAILED, blink::WebURL())); - agent_as_rfo()->DidStartProvisionalLoad(nullptr, true); + agent_as_rfo()->DidStartNavigation(GURL(), base::nullopt); + agent_as_rfo()->ReadyToCommitNavigation(nullptr); agent_as_rfo()->DidCommitProvisionalLoad( false /* is_same_document_navigation */, ui::PAGE_TRANSITION_LINK); FinishLoad();
diff --git a/components/update_client/net/network_impl.cc b/components/update_client/net/network_impl.cc index bd97998..e09e112 100644 --- a/components/update_client/net/network_impl.cc +++ b/components/update_client/net/network_impl.cc
@@ -21,19 +21,26 @@ const net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("update_client", R"( semantics { - sender: "Component Updater" + sender: "Component Updater and Extension Updater" description: - "The component updater in Chrome is responsible for updating code " - "and data modules such as Flash, CrlSet, Origin Trials, etc. These " - "modules are updated on cycles independent of the Chrome release " - "tracks. It runs in the browser process and communicates with a " - "set of servers using the Omaha protocol to find the latest " - "versions of components, download them, and register them with the " - "rest of Chrome." + "This network module is used by both the component and the " + "extension updaters in Chrome. " + "The component updater is responsible for updating code and data " + "modules such as Flash, CrlSet, Origin Trials, etc. These modules " + "are updated on cycles independent of the Chrome release tracks. " + "It runs in the browser process and communicates with a set of " + "servers using the Omaha protocol to find the latest versions of " + "components, download them, and register them with the rest of " + "Chrome. " + "The extension updater works similarly, but it updates user " + "extensions instead of Chrome components. " trigger: "Manual or automatic software updates." data: "Various OS and Chrome parameters such as version, bitness, " - "release tracks, etc." + "release tracks, etc. The component and the extension ids are also " + "present in both the request and the response from the servers. " + "The URL that refers to a component CRX payload is obfuscated for " + "most components." destination: GOOGLE_OWNED_SERVICE } policy {
diff --git a/components/viz/service/BUILD.gn b/components/viz/service/BUILD.gn index 0a2dadf..c6b79568 100644 --- a/components/viz/service/BUILD.gn +++ b/components/viz/service/BUILD.gn
@@ -6,6 +6,7 @@ import("//components/viz/viz.gni") import("//gpu/vulkan/features.gni") import("//testing/libfuzzer/fuzzer_test.gni") +import("//third_party/protobuf/proto_library.gni") config("viz_service_implementation") { } @@ -474,6 +475,32 @@ ] } +proto_library("compositor_frame_fuzzer_proto") { + sources = [ + "compositor_frame_fuzzer/compositor_frame_fuzzer.proto", + ] +} + +fuzzer_test("compositor_frame_fuzzer") { + sources = [ + "compositor_frame_fuzzer/compositor_frame_fuzzer.cc", + "compositor_frame_fuzzer/compositor_frame_fuzzer_util.cc", + "compositor_frame_fuzzer/compositor_frame_fuzzer_util.h", + "compositor_frame_fuzzer/fuzzer_browser_process.cc", + "compositor_frame_fuzzer/fuzzer_browser_process.h", + "compositor_frame_fuzzer/fuzzer_software_display_provider.cc", + "compositor_frame_fuzzer/fuzzer_software_display_provider.h", + ] + + deps = [ + ":compositor_frame_fuzzer_proto", + ":service", + "//components/viz/test:test_support", + "//mojo/core/embedder", + "//third_party/libprotobuf-mutator", + ] +} + fuzzer_test("hit_test_manager_fuzzer") { sources = [ "hit_test/hit_test_manager_fuzzer.cc",
diff --git a/components/viz/service/compositor_frame_fuzzer/DEPS b/components/viz/service/compositor_frame_fuzzer/DEPS new file mode 100644 index 0000000..0594bae --- /dev/null +++ b/components/viz/service/compositor_frame_fuzzer/DEPS
@@ -0,0 +1,10 @@ +include_rules = [ + "+components/viz/service", + "+components/viz/test", +] + +specific_include_rules = { + "compositor_frame_fuzzer.cc": [ + "+mojo/core/embedder", + ] +}
diff --git a/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.cc b/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.cc new file mode 100644 index 0000000..0412aed9 --- /dev/null +++ b/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.cc
@@ -0,0 +1,54 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/command_line.h" +#include "base/message_loop/message_loop.h" +#include "base/no_destructor.h" +#include "components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.h" +#include "components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.h" +#include "mojo/core/embedder/embedder.h" +#include "testing/libfuzzer/proto/lpm_interface.h" + +#include "components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.pb.h" + +namespace { + +struct Env { + public: + Env() { + mojo::core::Init(); + + // Run fuzzer with the flag --dump-to-png[=dir-name] to dump the browser + // display into PNG files for debugging purposes. + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + auto png_dir_path = + command_line->HasSwitch("dump-to-png") + ? base::Optional<base::FilePath>( + command_line->GetSwitchValuePath("dump-to-png")) + : base::nullopt; + + browser_process = std::make_unique<viz::FuzzerBrowserProcess>(png_dir_path); + } + ~Env() = default; + + std::unique_ptr<viz::FuzzerBrowserProcess> browser_process; + + private: + base::MessageLoop message_loop; +}; + +} // namespace + +extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv) { + base::CommandLine::Init(*argc, *argv); + return 0; +} + +DEFINE_BINARY_PROTO_FUZZER( + const content::fuzzing::proto::RenderPass& render_pass_spec) { + static base::NoDestructor<Env> env; + viz::CompositorFrame frame = + viz::GenerateFuzzedCompositorFrame(render_pass_spec); + env->browser_process->EmbedFuzzedCompositorFrame(std::move(frame)); +}
diff --git a/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.proto b/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.proto new file mode 100644 index 0000000..41ab2374 --- /dev/null +++ b/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.proto
@@ -0,0 +1,31 @@ +// 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. + +syntax = "proto2"; + +package content.fuzzing.proto; + +message RenderPass { + required Rect output_rect = 1; + required Rect damage_rect = 2; + required SolidColorDrawQuad draw_quad = 3; +} + +message SolidColorDrawQuad { + required Rect rect = 1; + required Rect visible_rect = 2; + required fixed32 color = 3 [default = 0xffffffff]; + required bool force_anti_aliasing_off = 4; +} + +// Spec to initialize a gfx::Rect. +// Defaults to the size of the renderer frame as defined in +// fuzzer_browser_process.cc, in the hopes that this generally yields more +// interesting values more quickly. +message Rect { + required sint32 x = 1 [default = 0]; + required sint32 y = 2 [default = 0]; + required sint32 width = 3 [default = 620]; + required sint32 height = 4 [default = 400]; +} \ No newline at end of file
diff --git a/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.cc b/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.cc new file mode 100644 index 0000000..2357181 --- /dev/null +++ b/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.cc
@@ -0,0 +1,93 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.h" + +#include <memory> +#include <utility> + +#include "components/viz/common/quads/solid_color_draw_quad.h" +#include "components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.h" + +namespace viz { + +namespace { + +gfx::Rect GetRectFromProtobuf(const content::fuzzing::proto::Rect& proto_rect) { + return gfx::Rect(proto_rect.x(), proto_rect.y(), proto_rect.width(), + proto_rect.height()); +} + +// Mutates a gfx::Rect to ensure width and height are both at least min_size. +// Use in case e.g. a 0-width/height Rect would cause a validation error on +// deserialization. +void ExpandToMinSize(gfx::Rect* rect, int min_size) { + if (rect->width() < min_size) { + // grow width to min_size in +x direction + // (may be clamped if x + min_size overflows) + rect->set_width(min_size); + } + + // if previous attempt failed due to overflow + if (rect->width() < min_size) { + // grow width to min_size in -x direction + rect->Offset(-(min_size - rect->width()), 0); + rect->set_width(min_size); + } + + if (rect->height() < min_size) { + // grow height to min_size in +y direction + // (may be clamped if y + min_size overflows) + rect->set_height(min_size); + } + + // if previous attempt failed due to overflow + if (rect->height() < min_size) { + // grow height to min_size in -y direction + rect->Offset(0, -(min_size - rect->height())); + rect->set_height(min_size); + } +} + +} // namespace + +CompositorFrame GenerateFuzzedCompositorFrame( + const content::fuzzing::proto::RenderPass& render_pass_spec) { + CompositorFrame frame; + + frame.metadata.begin_frame_ack.source_id = BeginFrameArgs::kManualSourceId; + frame.metadata.begin_frame_ack.sequence_number = + BeginFrameArgs::kStartingFrameNumber; + frame.metadata.begin_frame_ack.has_damage = true; + frame.metadata.frame_token = 1; + frame.metadata.device_scale_factor = 1; + frame.metadata.local_surface_id_allocation_time = base::TimeTicks::Now(); + + std::unique_ptr<RenderPass> pass = RenderPass::Create(); + gfx::Rect rp_output_rect = + GetRectFromProtobuf(render_pass_spec.output_rect()); + ExpandToMinSize(&rp_output_rect, 1); + pass->SetNew(1, rp_output_rect, + GetRectFromProtobuf(render_pass_spec.damage_rect()), + gfx::Transform()); + + content::fuzzing::proto::SolidColorDrawQuad quad_spec = + render_pass_spec.draw_quad(); + gfx::Rect quad_rect = GetRectFromProtobuf(quad_spec.rect()); + gfx::Rect quad_visible_rect = GetRectFromProtobuf(quad_spec.visible_rect()); + auto* shared_quad_state = pass->CreateAndAppendSharedQuadState(); + shared_quad_state->SetAll(gfx::Transform(), gfx::Rect(quad_rect), + gfx::Rect(quad_rect), gfx::Rect(quad_rect), + /*is_clipped=*/false, + /*are_contents_opaque=*/false, 1, + SkBlendMode::kSrcOver, /*sorting_context_id=*/0); + auto* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); + color_quad->SetNew(shared_quad_state, quad_visible_rect, gfx::Rect(quad_rect), + quad_spec.color(), quad_spec.force_anti_aliasing_off()); + + frame.render_pass_list.push_back(std::move(pass)); + return frame; +} + +} // namespace viz
diff --git a/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.h b/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.h new file mode 100644 index 0000000..633bc08d --- /dev/null +++ b/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.h
@@ -0,0 +1,25 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_VIZ_SERVICE_COMPOSITOR_FRAME_FUZZER_COMPOSITOR_FRAME_FUZZER_UTIL_H_ +#define COMPONENTS_VIZ_SERVICE_COMPOSITOR_FRAME_FUZZER_COMPOSITOR_FRAME_FUZZER_UTIL_H_ + +#include "components/viz/common/quads/compositor_frame.h" +#include "components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.pb.h" + +namespace viz { + +// Converts a fuzzed specification in the form of a RenderPass protobuf message +// (as defined in compositor_frame_fuzzer.proto) into a CompositorFrame with a +// RenderPass member. +// +// Performs minimal validation and corrections to ensure that submitting the +// frame to a CompositorFrameSink will not result in a mojo deserialization +// validation error. +CompositorFrame GenerateFuzzedCompositorFrame( + const content::fuzzing::proto::RenderPass& render_pass_spec); + +} // namespace viz + +#endif // COMPONENTS_VIZ_SERVICE_COMPOSITOR_FRAME_FUZZER_COMPOSITOR_FRAME_FUZZER_UTIL_H_
diff --git a/components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.cc b/components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.cc new file mode 100644 index 0000000..bd61021 --- /dev/null +++ b/components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.cc
@@ -0,0 +1,141 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.h" + +#include <memory> +#include <utility> + +#include "base/run_loop.h" +#include "components/viz/common/quads/solid_color_draw_quad.h" +#include "components/viz/common/quads/surface_draw_quad.h" +#include "components/viz/common/surfaces/surface_range.h" + +namespace viz { + +namespace { + +// If modifying these sizes, consider also updating the default values in +// compositor_frame_fuzzer.proto to match. +constexpr gfx::Size kBrowserSize(620, 480); +constexpr gfx::Size kTopBarSize(620, 80); +constexpr gfx::Size kRendererFrameSize(620, 400); + +constexpr FrameSinkId kEmbeddedFrameSinkId(2, 1); +constexpr FrameSinkId kRootFrameSinkId(1, 1); + +} // namespace + +FuzzerBrowserProcess::FuzzerBrowserProcess( + base::Optional<base::FilePath> png_dir_path) + : root_local_surface_id_(1, 1, base::UnguessableToken::Create()), + display_provider_(std::move(png_dir_path)), + frame_sink_manager_(&shared_bitmap_manager_, + base::nullopt, + &display_provider_) { + frame_sink_manager_.RegisterFrameSinkId(kEmbeddedFrameSinkId, + /*report_activation=*/false); + frame_sink_manager_.RegisterFrameSinkId(kRootFrameSinkId, + /*report_activation=*/false); + frame_sink_manager_.CreateRootCompositorFrameSink( + BuildRootCompositorFrameSinkParams()); + display_private_->SetDisplayVisible(true); + display_private_->Resize(kBrowserSize); +} + +FuzzerBrowserProcess::~FuzzerBrowserProcess() { + frame_sink_manager_.InvalidateFrameSinkId(kRootFrameSinkId); + frame_sink_manager_.InvalidateFrameSinkId(kEmbeddedFrameSinkId); +} + +void FuzzerBrowserProcess::EmbedFuzzedCompositorFrame( + CompositorFrame fuzzed_frame) { + mojom::CompositorFrameSinkPtr sink_ptr; + FakeCompositorFrameSinkClient sink_client; + frame_sink_manager_.CreateCompositorFrameSink(kEmbeddedFrameSinkId, + mojo::MakeRequest(&sink_ptr), + sink_client.BindInterfacePtr()); + + lsi_allocator_.GenerateId(); + SurfaceId embedded_surface_id( + kEmbeddedFrameSinkId, + lsi_allocator_.GetCurrentLocalSurfaceIdAllocation().local_surface_id()); + sink_ptr->SubmitCompositorFrame(embedded_surface_id.local_surface_id(), + std::move(fuzzed_frame), base::nullopt, 0); + + CompositorFrame browser_frame = + BuildBrowserUICompositorFrame(embedded_surface_id); + root_compositor_frame_sink_ptr_->SubmitCompositorFrame( + root_local_surface_id_, std::move(browser_frame), base::nullopt, 0); + display_private_->ForceImmediateDrawAndSwapIfPossible(); + + base::RunLoop().RunUntilIdle(); // needed to actually run queued messages + + frame_sink_manager_.DestroyCompositorFrameSink(kEmbeddedFrameSinkId, + base::DoNothing()); +} + +mojom::RootCompositorFrameSinkParamsPtr +FuzzerBrowserProcess::BuildRootCompositorFrameSinkParams() { + auto params = mojom::RootCompositorFrameSinkParams::New(); + params->frame_sink_id = kRootFrameSinkId; + params->widget = gpu::kNullSurfaceHandle; + params->gpu_compositing = false; + params->compositor_frame_sink = mojo::MakeRequestAssociatedWithDedicatedPipe( + &root_compositor_frame_sink_ptr_); + params->compositor_frame_sink_client = + root_compositor_frame_sink_client_.BindInterfacePtr().PassInterface(); + params->display_private = + MakeRequestAssociatedWithDedicatedPipe(&display_private_); + params->display_client = display_client_.BindInterfacePtr().PassInterface(); + return params; +} + +CompositorFrame FuzzerBrowserProcess::BuildBrowserUICompositorFrame( + SurfaceId renderer_surface_id) { + CompositorFrame frame; + + frame.metadata.begin_frame_ack.source_id = BeginFrameArgs::kManualSourceId; + frame.metadata.begin_frame_ack.sequence_number = + BeginFrameArgs::kStartingFrameNumber; + frame.metadata.device_scale_factor = 1; + frame.metadata.local_surface_id_allocation_time = base::TimeTicks::Now(); + frame.metadata.referenced_surfaces.push_back( + SurfaceRange(base::nullopt, renderer_surface_id)); + + std::unique_ptr<RenderPass> pass = RenderPass::Create(); + pass->SetNew(/*id=*/1, gfx::Rect(kBrowserSize), gfx::Rect(kBrowserSize), + gfx::Transform()); + + auto* renderer_sqs = pass->CreateAndAppendSharedQuadState(); + renderer_sqs->SetAll(gfx::Transform(1.0, 0.0, 0.0, 1.0, 0, 80), + gfx::Rect(kRendererFrameSize), + gfx::Rect(kRendererFrameSize), + gfx::Rect(kRendererFrameSize), /*is_clipped=*/false, + /*are_contents_opaque=*/false, /*opacity=*/1, + SkBlendMode::kSrcOver, /*sorting_context_id=*/0); + auto* surface_quad = pass->CreateAndAppendDrawQuad<SurfaceDrawQuad>(); + surface_quad->SetNew(renderer_sqs, gfx::Rect(kRendererFrameSize), + gfx::Rect(kRendererFrameSize), + SurfaceRange(base::nullopt, renderer_surface_id), + SK_ColorWHITE, + /*stretch_content_to_fill_bounds=*/false, + /*ignores_input_event=*/false); + + auto* toolbar_sqs = pass->CreateAndAppendSharedQuadState(); + toolbar_sqs->SetAll(gfx::Transform(), gfx::Rect(kTopBarSize), + gfx::Rect(kTopBarSize), gfx::Rect(kTopBarSize), + /*is_clipped=*/false, /*are_contents_opaque=*/false, + /*opacity=*/1, SkBlendMode::kSrcOver, + /*sorting_context_id=*/0); + auto* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); + color_quad->SetNew(toolbar_sqs, gfx::Rect(kTopBarSize), + gfx::Rect(kTopBarSize), SK_ColorLTGRAY, + /*force_antialiasing_off=*/false); + frame.render_pass_list.push_back(std::move(pass)); + + return frame; +} + +} // namespace viz
diff --git a/components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.h b/components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.h new file mode 100644 index 0000000..d080d6a --- /dev/null +++ b/components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.h
@@ -0,0 +1,58 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_VIZ_SERVICE_COMPOSITOR_FRAME_FUZZER_FUZZER_BROWSER_PROCESS_H_ +#define COMPONENTS_VIZ_SERVICE_COMPOSITOR_FRAME_FUZZER_FUZZER_BROWSER_PROCESS_H_ + +#include "components/viz/common/surfaces/frame_sink_id.h" +#include "components/viz/common/surfaces/parent_local_surface_id_allocator.h" +#include "components/viz/service/compositor_frame_fuzzer/fuzzer_software_display_provider.h" +#include "components/viz/service/display_embedder/server_shared_bitmap_manager.h" +#include "components/viz/service/frame_sinks/frame_sink_manager_impl.h" +#include "components/viz/test/fake_compositor_frame_sink_client.h" +#include "components/viz/test/fake_display_client.h" + +namespace viz { + +// A fake browser process to use as a fuzzer target. +// Uses software compositing. +class FuzzerBrowserProcess { + public: + explicit FuzzerBrowserProcess(base::Optional<base::FilePath> png_dir_path); + ~FuzzerBrowserProcess(); + + // Fuzz target mimicking the process of submitting a rendered CompositorFrame + // to be embedded in the browser UI. + // + // Submits the provided fuzzed CompositorFrame to a new + // CompositorFrameSinkImpl. + // + // Submits a CompositorFrame to the RootCompositorFrameSinkImpl + // with a SolidColorDrawQuad "toolbar" and a SurfaceDrawQuad "renderer frame" + // embedding the fuzzed CompositorFrame. + void EmbedFuzzedCompositorFrame(CompositorFrame fuzzed_frame); + + private: + mojom::RootCompositorFrameSinkParamsPtr BuildRootCompositorFrameSinkParams(); + CompositorFrame BuildBrowserUICompositorFrame(SurfaceId renderer_surface_id); + + const LocalSurfaceId root_local_surface_id_; + + ServerSharedBitmapManager shared_bitmap_manager_; + FuzzerSoftwareDisplayProvider display_provider_; + FrameSinkManagerImpl frame_sink_manager_; + + mojom::CompositorFrameSinkAssociatedPtr root_compositor_frame_sink_ptr_; + FakeCompositorFrameSinkClient root_compositor_frame_sink_client_; + mojom::DisplayPrivateAssociatedPtr display_private_; + FakeDisplayClient display_client_; + + ParentLocalSurfaceIdAllocator lsi_allocator_; + + DISALLOW_COPY_AND_ASSIGN(FuzzerBrowserProcess); +}; + +} // namespace viz + +#endif // COMPONENTS_VIZ_SERVICE_COMPOSITOR_FRAME_FUZZER_FUZZER_BROWSER_PROCESS_H_
diff --git a/components/viz/service/compositor_frame_fuzzer/fuzzer_software_display_provider.cc b/components/viz/service/compositor_frame_fuzzer/fuzzer_software_display_provider.cc new file mode 100644 index 0000000..dda5a2fb --- /dev/null +++ b/components/viz/service/compositor_frame_fuzzer/fuzzer_software_display_provider.cc
@@ -0,0 +1,118 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/viz/service/compositor_frame_fuzzer/fuzzer_software_display_provider.h" + +#include <string> +#include <utility> +#include <vector> + +#include "base/files/file_util.h" +#include "components/viz/service/display/software_output_device.h" +#include "components/viz/service/display_embedder/software_output_surface.h" +#include "third_party/skia/include/encode/SkPngEncoder.h" +#include "ui/gfx/codec/png_codec.h" + +namespace viz { + +namespace { + +// SoftwareOutputDevice that dumps the display's pixmap into a new PNG file per +// paint event. For debugging only: this significantly slows down fuzzing +// iterations and will not handle more than UINT32_MAX files. +class PNGSoftwareOutputDevice : public SoftwareOutputDevice { + public: + explicit PNGSoftwareOutputDevice(base::FilePath output_dir) + : output_dir_(output_dir) {} + + // SoftwareOutputDevice implementation + void EndPaint() override { + SkPixmap input_pixmap; + surface_->peekPixels(&input_pixmap); + + gfx::PNGCodec::ColorFormat color_format; + switch (input_pixmap.colorType()) { + case kRGBA_8888_SkColorType: + color_format = gfx::PNGCodec::FORMAT_RGBA; + break; + case kBGRA_8888_SkColorType: + color_format = gfx::PNGCodec::FORMAT_BGRA; + break; + default: + // failing to find a better default, this one is OK; PNGCodec::Encode + // will convert this to kN32_SkColorType + color_format = gfx::PNGCodec::FORMAT_SkBitmap; + break; + } + + std::vector<unsigned char> output; + gfx::PNGCodec::Encode( + static_cast<const unsigned char*>(input_pixmap.addr()), color_format, + gfx::Size(input_pixmap.width(), input_pixmap.height()), + input_pixmap.rowBytes(), + /*discard_transparency=*/false, + /*comments=*/{}, &output); + + base::WriteFile(NextOutputFilePath(), + reinterpret_cast<char*>(output.data()), output.size()); + } + + private: + // Return path of next output file. Will not handle overflow of file_id_. + base::FilePath NextOutputFilePath() { + // maximum possible length of next_file_id_ (in characters) + constexpr int kPaddedIntLength = 10; + + std::string file_name = + base::StringPrintf("%0*u.png", kPaddedIntLength, next_file_id_++); + + return output_dir_.Append(base::FilePath::FromUTF8Unsafe(file_name)); + } + + base::FilePath output_dir_; + uint32_t next_file_id_ = 0; +}; + +} // namespace + +FuzzerSoftwareDisplayProvider::FuzzerSoftwareDisplayProvider( + base::Optional<base::FilePath> png_dir_path) + : png_dir_path_(png_dir_path), + begin_frame_source_(std::make_unique<StubBeginFrameSource>()) {} + +FuzzerSoftwareDisplayProvider::~FuzzerSoftwareDisplayProvider() = default; + +std::unique_ptr<Display> FuzzerSoftwareDisplayProvider::CreateDisplay( + const FrameSinkId& frame_sink_id, + gpu::SurfaceHandle surface_handle, + bool gpu_compositing, + mojom::DisplayClient* display_client, + ExternalBeginFrameSource* external_begin_frame_source, + SyntheticBeginFrameSource* synthetic_begin_frame_source, + const RendererSettings& renderer_settings, + bool send_swap_size_notifications) { + auto task_runner = base::ThreadTaskRunnerHandle::Get(); + DCHECK(task_runner); + + std::unique_ptr<SoftwareOutputDevice> software_output_device = + png_dir_path_ ? std::make_unique<PNGSoftwareOutputDevice>(*png_dir_path_) + : std::make_unique<SoftwareOutputDevice>(); + + auto output_surface = std::make_unique<SoftwareOutputSurface>( + std::move(software_output_device), synthetic_begin_frame_source); + + auto scheduler = std::make_unique<DisplayScheduler>( + begin_frame_source_.get(), task_runner.get(), + output_surface->capabilities().max_frames_pending); + + return std::make_unique<Display>(&shared_bitmap_manager_, renderer_settings, + frame_sink_id, std::move(output_surface), + std::move(scheduler), task_runner); +} + +uint32_t FuzzerSoftwareDisplayProvider::GetRestartId() const { + return BeginFrameSource::kNotRestartableId; +} + +} // namespace viz
diff --git a/components/viz/service/compositor_frame_fuzzer/fuzzer_software_display_provider.h b/components/viz/service/compositor_frame_fuzzer/fuzzer_software_display_provider.h new file mode 100644 index 0000000..ee236bf --- /dev/null +++ b/components/viz/service/compositor_frame_fuzzer/fuzzer_software_display_provider.h
@@ -0,0 +1,51 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_VIZ_SERVICE_COMPOSITOR_FRAME_FUZZER_FUZZER_SOFTWARE_DISPLAY_PROVIDER_H_ +#define COMPONENTS_VIZ_SERVICE_COMPOSITOR_FRAME_FUZZER_FUZZER_SOFTWARE_DISPLAY_PROVIDER_H_ + +#include <memory> + +#include "components/viz/service/display/display.h" +#include "components/viz/service/display_embedder/display_provider.h" +#include "components/viz/service/display_embedder/server_shared_bitmap_manager.h" + +namespace viz { + +// DisplayProvider implementation that provides Displays that use a +// SoftwareOutputSurface (no-op by default, with an option to dump pixmap to a +// PNG for debugging). +// +// Provided Displays will only draw when explicitly asked to +// (e.g. if Display::ForceImmediateDrawAndSwapIfPossible() is called), +// ignoring the BeginFrameSource parameters passed to CreateDisplay. +class FuzzerSoftwareDisplayProvider : public DisplayProvider { + public: + explicit FuzzerSoftwareDisplayProvider( + base::Optional<base::FilePath> png_dir_path); + ~FuzzerSoftwareDisplayProvider() override; + + // DisplayProvider implementation. + std::unique_ptr<Display> CreateDisplay( + const FrameSinkId& frame_sink_id, + gpu::SurfaceHandle surface_handle, + bool gpu_compositing, + mojom::DisplayClient* display_client, + ExternalBeginFrameSource* external_begin_frame_source, + SyntheticBeginFrameSource* synthetic_begin_frame_source, + const RendererSettings& renderer_settings, + bool send_swap_size_notifications) override; + uint32_t GetRestartId() const override; + + private: + base::Optional<base::FilePath> png_dir_path_; + ServerSharedBitmapManager shared_bitmap_manager_; + std::unique_ptr<StubBeginFrameSource> begin_frame_source_; + + DISALLOW_COPY_AND_ASSIGN(FuzzerSoftwareDisplayProvider); +}; + +} // namespace viz + +#endif // COMPONENTS_VIZ_SERVICE_COMPOSITOR_FRAME_FUZZER_FUZZER_SOFTWARE_DISPLAY_PROVIDER_H_
diff --git a/components/viz/service/frame_sinks/surface_synchronization_unittest.cc b/components/viz/service/frame_sinks/surface_synchronization_unittest.cc index 0c7902d..9e54cd1 100644 --- a/components/viz/service/frame_sinks/surface_synchronization_unittest.cc +++ b/components/viz/service/frame_sinks/surface_synchronization_unittest.cc
@@ -2390,11 +2390,55 @@ // This test verifies that if a child submits a LocalSurfaceId newer that the // parent's dependency, then the parent will drop its dependency and activate -// if possible. -TEST_F(SurfaceSynchronizationTest, DropDependenciesThatWillNeverArrive) { +// if possible. In this version of the test, parent sequence number of the +// activated surface is larger than that in the dependency, while the child +// sequence number is smaller. +TEST_F(SurfaceSynchronizationTest, DropDependenciesThatWillNeverArrive1) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); - const SurfaceId child_id11 = MakeSurfaceId(kChildFrameSink1, 1); - const SurfaceId child_id12 = MakeSurfaceId(kChildFrameSink1, 2); + const SurfaceId child_id11 = MakeSurfaceId(kChildFrameSink1, 1, 2); + const SurfaceId child_id12 = MakeSurfaceId(kChildFrameSink1, 2, 1); + const SurfaceId child_id21 = MakeSurfaceId(kChildFrameSink2, 1); + + // |parent_id| depends on { child_id11, child_id21 }. It shouldn't activate. + parent_support().SubmitCompositorFrame( + parent_id.local_surface_id(), + MakeCompositorFrame({child_id11, child_id21}, empty_surface_ranges(), + std::vector<TransferableResource>())); + EXPECT_FALSE(parent_surface()->HasActiveFrame()); + EXPECT_TRUE(parent_surface()->HasPendingFrame()); + + // The first child submits a new CompositorFrame to |child_id12|. |parent_id| + // no longer depends on |child_id11| because it cannot expect it to arrive. + // However, the parent is still blocked on |child_id21|. + child_support1().SubmitCompositorFrame( + child_id12.local_surface_id(), + MakeCompositorFrame(empty_surface_ids(), empty_surface_ranges(), + std::vector<TransferableResource>())); + EXPECT_FALSE(parent_surface()->HasActiveFrame()); + EXPECT_TRUE(parent_surface()->HasPendingFrame()); + EXPECT_THAT(parent_surface()->activation_dependencies(), + UnorderedElementsAre(child_id21)); + + // Finally, the second child submits a frame to the remaining dependency and + // the parent activates. + child_support2().SubmitCompositorFrame( + child_id21.local_surface_id(), + MakeCompositorFrame(empty_surface_ids(), empty_surface_ranges(), + std::vector<TransferableResource>())); + EXPECT_TRUE(parent_surface()->HasActiveFrame()); + EXPECT_FALSE(parent_surface()->HasPendingFrame()); + EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); +} + +// This test verifies that if a child submits a LocalSurfaceId newer that the +// parent's dependency, then the parent will drop its dependency and activate +// if possible. In this version of the test, parent sequence number of the +// activated surface is smaller than that in the dependency, while the child +// sequence number is larger. +TEST_F(SurfaceSynchronizationTest, DropDependenciesThatWillNeverArrive2) { + const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); + const SurfaceId child_id11 = MakeSurfaceId(kChildFrameSink1, 2, 1); + const SurfaceId child_id12 = MakeSurfaceId(kChildFrameSink1, 1, 2); const SurfaceId child_id21 = MakeSurfaceId(kChildFrameSink2, 1); // |parent_id| depends on { child_id11, child_id21 }. It shouldn't activate.
diff --git a/components/viz/service/surfaces/surface.cc b/components/viz/service/surfaces/surface.cc index a634f504..738b07c 100644 --- a/components/viz/service/surfaces/surface.cc +++ b/components/viz/service/surfaces/surface.cc
@@ -296,27 +296,45 @@ return; // TODO(samans): Take into account the embed token. - if (surface_id.local_surface_id().parent_sequence_number() >= - it->second.parent_sequence_number && - surface_id.local_surface_id().child_sequence_number() >= - it->second.child_sequence_number) { + if (surface_id.local_surface_id().parent_sequence_number() > + it->second.parent_sequence_number || + surface_id.local_surface_id().child_sequence_number() > + it->second.child_sequence_number || + (surface_id.local_surface_id().parent_sequence_number() == + it->second.parent_sequence_number && + surface_id.local_surface_id().child_sequence_number() == + it->second.child_sequence_number)) { frame_sink_id_dependencies_.erase(it); surface_manager_->SurfaceDependenciesChanged(this, {}, {surface_id.frame_sink_id()}); } - // LocalSurfaceIds of a given FrameSinkId are monotonically increasing in time - // so if LocalSurfaceId j arrives then all LocalSurfaceIds i<j will never - // arrive and so we just drop these invalid activation dependencies here. // TODO(fsamuel): This is a linear scan which is probably fine today because // a given surface has a small number of dependencies. We might need to // revisit this in the future if the number of dependencies grows // significantly. - base::EraseIf( - activation_dependencies_, [surface_id](const SurfaceId& dependency) { - return dependency.frame_sink_id() == surface_id.frame_sink_id() && - dependency.local_surface_id() <= surface_id.local_surface_id(); - }); + auto delete_fn = [surface_id](const SurfaceId& dependency) { + if (dependency.frame_sink_id() != surface_id.frame_sink_id()) + return false; + // The dependency will never get satisfied if the child is already using a + // larger parent or child sequence number, so drop the dependency in that + // case. + if (dependency.local_surface_id().parent_sequence_number() < + surface_id.local_surface_id().parent_sequence_number() || + dependency.local_surface_id().child_sequence_number() < + surface_id.local_surface_id().child_sequence_number()) { + return true; + } + // For the dependency to get satisfied, both parent and child sequence + // numbers of the activated SurfaceId must be equal to those of the + // dependency. + return dependency.local_surface_id().parent_sequence_number() == + surface_id.local_surface_id().parent_sequence_number() && + dependency.local_surface_id().child_sequence_number() == + surface_id.local_surface_id().child_sequence_number(); + }; + + base::EraseIf(activation_dependencies_, delete_fn); // We cannot activate this CompositorFrame if there are still missing // activation dependencies or this surface is blocked on its parent arriving
diff --git a/components/viz/test/BUILD.gn b/components/viz/test/BUILD.gn index d83a217b..a3c905b 100644 --- a/components/viz/test/BUILD.gn +++ b/components/viz/test/BUILD.gn
@@ -17,6 +17,8 @@ "fake_compositor_frame_sink_client.h", "fake_delay_based_time_source.cc", "fake_delay_based_time_source.h", + "fake_display_client.cc", + "fake_display_client.h", "fake_external_begin_frame_source.cc", "fake_external_begin_frame_source.h", "fake_host_frame_sink_client.cc",
diff --git a/components/viz/test/fake_compositor_frame_sink_client.cc b/components/viz/test/fake_compositor_frame_sink_client.cc index f73b2e3..0e6434f 100644 --- a/components/viz/test/fake_compositor_frame_sink_client.cc +++ b/components/viz/test/fake_compositor_frame_sink_client.cc
@@ -6,7 +6,8 @@ namespace viz { -FakeCompositorFrameSinkClient::FakeCompositorFrameSinkClient() = default; +FakeCompositorFrameSinkClient::FakeCompositorFrameSinkClient() + : binding_(this) {} FakeCompositorFrameSinkClient::~FakeCompositorFrameSinkClient() = default; void FakeCompositorFrameSinkClient::DidReceiveCompositorFrameAck( @@ -31,4 +32,11 @@ resources.end()); } +mojom::CompositorFrameSinkClientPtr +FakeCompositorFrameSinkClient::BindInterfacePtr() { + mojom::CompositorFrameSinkClientPtr ptr; + binding_.Bind(MakeRequest(&ptr)); + return ptr; +} + } // namespace viz
diff --git a/components/viz/test/fake_compositor_frame_sink_client.h b/components/viz/test/fake_compositor_frame_sink_client.h index 5bfb364..c8e8c34 100644 --- a/components/viz/test/fake_compositor_frame_sink_client.h +++ b/components/viz/test/fake_compositor_frame_sink_client.h
@@ -8,6 +8,7 @@ #include <vector> #include "components/viz/common/surfaces/local_surface_id.h" +#include "mojo/public/cpp/bindings/binding.h" #include "services/viz/public/interfaces/compositing/compositor_frame_sink.mojom.h" namespace viz { @@ -17,6 +18,8 @@ FakeCompositorFrameSinkClient(); ~FakeCompositorFrameSinkClient() override; + mojom::CompositorFrameSinkClientPtr BindInterfacePtr(); + // mojom::CompositorFrameSinkClient implementation. void DidReceiveCompositorFrameAck( const std::vector<ReturnedResource>& resources) override; @@ -37,6 +40,8 @@ std::vector<ReturnedResource> returned_resources_; + mojo::Binding<mojom::CompositorFrameSinkClient> binding_; + DISALLOW_COPY_AND_ASSIGN(FakeCompositorFrameSinkClient); };
diff --git a/components/viz/test/fake_display_client.cc b/components/viz/test/fake_display_client.cc new file mode 100644 index 0000000..6c7d89a --- /dev/null +++ b/components/viz/test/fake_display_client.cc
@@ -0,0 +1,31 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/viz/test/fake_display_client.h" + +namespace viz { + +FakeDisplayClient::FakeDisplayClient() : binding_(this) {} +FakeDisplayClient::~FakeDisplayClient() = default; + +void FakeDisplayClient::DidSwapAfterSnapshotRequestReceived( + const std::vector<ui::LatencyInfo>&) {} + +mojom::DisplayClientPtr FakeDisplayClient::BindInterfacePtr() { + mojom::DisplayClientPtr ptr; + binding_.Bind(MakeRequest(&ptr)); + return ptr; +} + +#if defined(OS_MACOSX) +void FakeDisplayClient::OnDisplayReceivedCALayerParams( + const gfx::CALayerParams& ca_layer_params) {} +#endif + +#if defined(OS_WIN) +void FakeDisplayClient::CreateLayeredWindowUpdater( + mojom::LayeredWindowUpdaterRequest request) {} +#endif + +} // namespace viz
diff --git a/components/viz/test/fake_display_client.h b/components/viz/test/fake_display_client.h new file mode 100644 index 0000000..3ac840f --- /dev/null +++ b/components/viz/test/fake_display_client.h
@@ -0,0 +1,45 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_VIZ_TEST_FAKE_DISPLAY_CLIENT_H_ +#define COMPONENTS_VIZ_TEST_FAKE_DISPLAY_CLIENT_H_ + +#include <vector> + +#include "build/build_config.h" +#include "mojo/public/cpp/bindings/binding.h" +#include "services/viz/privileged/interfaces/compositing/display_private.mojom.h" + +namespace viz { + +class FakeDisplayClient : public mojom::DisplayClient { + public: + FakeDisplayClient(); + ~FakeDisplayClient() override; + + mojom::DisplayClientPtr BindInterfacePtr(); + + // mojom::DisplayClient implementation. + void DidSwapAfterSnapshotRequestReceived( + const std::vector<ui::LatencyInfo>&) override; + +#if defined(OS_MACOSX) + void OnDisplayReceivedCALayerParams( + const gfx::CALayerParams& ca_layer_params) override; +#endif + +#if defined(OS_WIN) + void CreateLayeredWindowUpdater( + mojom::LayeredWindowUpdaterRequest request) override; +#endif + + private: + mojo::Binding<mojom::DisplayClient> binding_; + + DISALLOW_COPY_AND_ASSIGN(FakeDisplayClient); +}; + +} // namespace viz + +#endif // COMPONENTS_VIZ_TEST_FAKE_DISPLAY_CLIENT_H_
diff --git a/content/DEPS b/content/DEPS index bd076e3..b010e3e 100644 --- a/content/DEPS +++ b/content/DEPS
@@ -5,6 +5,7 @@ # directories in content/ so we disallow all of them. "-content", "+content/app/resources/grit/content_resources.h", + "+content/app/strings/grit", # For generated headers "+content/common", "+content/grit", "+content/public/common",
diff --git a/content/app/strings/content_strings.grd b/content/app/strings/content_strings.grd index bc295409..bfec834 100644 --- a/content/app/strings/content_strings.grd +++ b/content/app/strings/content_strings.grd
@@ -633,6 +633,12 @@ <message name="IDS_AX_IMAGE_ANNOTATION_PROCESS_FAILED" desc="Accessibility message spoken out loud to screen reader users that the browser was not able to get a description for an image."> Unable to get a description. </message> + <message name="IDS_AX_IMAGE_ANNOTATION_OCR_CONTEXT" desc="Accessibility message spoken out loud to screen reader users when reading text that was automatically extracted from an image, for an example the word 'stop' could be extracted from a photo of a stop sign. Because automatic text extraction sometimes contains errors it is important that the language used indicates some uncertainty - it may say 'stop' or it appears to say 'stop', not it definitely says 'stop'."> + Appears to say: <ph name="OCR_TEXT">$1<ex>Stop</ex></ph> + </message> + <message name="IDS_AX_IMAGE_ANNOTATION_DESCRIPTION_CONTEXT" desc="Accessibility message spoken out loud to screen reader users when reading a computer-generated description of an image, for example a photo of the president at a press conference might be described as 'A person at a podium'. Because automatic image description is sometimes incorrect, it is important that the langauge used indicates some uncertainty - it may be a person, it appears to be a person, not it definitely is a person."> + Appears to be: <ph name="DESCRIPTION">$1<ex>A person at a podium</ex></ph> + </message> <message name="IDS_AX_AM_PM_FIELD_TEXT" desc="Accessible description of the AM/PM field in a date/time control"> AM/PM @@ -990,6 +996,10 @@ Couldn't load plugin. </message> + <message name="IDS_MEDIA_PLAYBACK_ERROR" desc="Message informing that the user that there were issues playing back their media."> + Unable to play media. + </message> + <!-- Byte size units --> <message name="IDS_UNITS_KIBIBYTES" desc="Units tag indicating a quantity of kilobytes"> <ph name="QUANTITY">$1<ex>42.0</ex></ph> KB @@ -1007,6 +1017,15 @@ <ph name="QUANTITY">$1<ex>42.0</ex></ph> PB </message> + <message name="CONTENT_INVALID_TRUE" desc="Error message for aria-invalid = true"> + Invalid entry + </message> + <message name="CONTENT_INVALID_SPELLING" desc="Error message for aria-invalid = spelling"> + Invalid spelling + </message> + <message name="CONTENT_INVALID_GRAMMAR" desc="Error message for aria-invalid = grammar"> + Invalid grammar + </message> </messages> </release> </grit>
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 57ef4d7b..765c9d898b 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -356,8 +356,6 @@ "appcache/appcache_disk_cache.cc", "appcache/appcache_disk_cache.h", "appcache/appcache_entry.h", - "appcache/appcache_frontend_proxy.cc", - "appcache/appcache_frontend_proxy.h", "appcache/appcache_group.cc", "appcache/appcache_group.h", "appcache/appcache_histograms.cc", @@ -1827,8 +1825,6 @@ "web_contents/web_drag_utils_win.h", "web_package/http_structured_header.cc", "web_package/http_structured_header.h", - "web_package/origins_list.cc", - "web_package/origins_list.h", "web_package/signed_exchange_cert_fetcher.cc", "web_package/signed_exchange_cert_fetcher.h", "web_package/signed_exchange_cert_fetcher_factory.cc",
diff --git a/content/browser/DEPS b/content/browser/DEPS index 7b0078f3..38894ae 100644 --- a/content/browser/DEPS +++ b/content/browser/DEPS
@@ -28,7 +28,6 @@ "+components/viz", "+components/cbor", - "+content/app/strings/grit", # For generated headers "+content/public/app", "+content/public/browser", "+device/base/synchronization",
diff --git a/content/browser/accessibility/accessibility_event_recorder.cc b/content/browser/accessibility/accessibility_event_recorder.cc index e558d871..70fcaf3f 100644 --- a/content/browser/accessibility/accessibility_event_recorder.cc +++ b/content/browser/accessibility/accessibility_event_recorder.cc
@@ -24,6 +24,19 @@ const base::StringPiece& application_name_match_pattern) { return std::make_unique<AccessibilityEventRecorder>(manager); } + +// static +std::vector<AccessibilityEventRecorder::EventRecorderFactory> +AccessibilityEventRecorder::GetTestPasses() { + return { +#if !defined(OS_ANDROID) + // Note: Android doesn't do a "blink" pass; the blink tree is different on + // Android because we exclude inline text boxes, for performance. + &AccessibilityEventRecorder::Create, +#endif + &AccessibilityEventRecorder::Create, + }; +} #endif void AccessibilityEventRecorder::OnEvent(const std::string& event) {
diff --git a/content/browser/accessibility/accessibility_event_recorder.h b/content/browser/accessibility/accessibility_event_recorder.h index c6276b8..e31c564 100644 --- a/content/browser/accessibility/accessibility_event_recorder.h +++ b/content/browser/accessibility/accessibility_event_recorder.h
@@ -44,6 +44,14 @@ const base::StringPiece& application_name_match_pattern = base::StringPiece()); + // Get a set of factory methods to create event-recorders, one for each test + // pass; see |DumpAccessibilityTestBase|. + using EventRecorderFactory = std::unique_ptr<AccessibilityEventRecorder> (*)( + BrowserAccessibilityManager* manager, + base::ProcessId pid, + const base::StringPiece& application_name_match_pattern); + static std::vector<EventRecorderFactory> GetTestPasses(); + AccessibilityEventRecorder(BrowserAccessibilityManager* manager); virtual ~AccessibilityEventRecorder();
diff --git a/content/browser/accessibility/accessibility_event_recorder_auralinux.cc b/content/browser/accessibility/accessibility_event_recorder_auralinux.cc index 2eb1b62..2d5cbad 100644 --- a/content/browser/accessibility/accessibility_event_recorder_auralinux.cc +++ b/content/browser/accessibility/accessibility_event_recorder_auralinux.cc
@@ -97,6 +97,15 @@ manager, pid, application_name_match_pattern); } +std::vector<AccessibilityEventRecorder::EventRecorderFactory> +AccessibilityEventRecorder::GetTestPasses() { + // Both the Blink pass and native pass use the same recorder + return { + &AccessibilityEventRecorder::Create, + &AccessibilityEventRecorder::Create, + }; +} + bool AccessibilityEventRecorderAuraLinux::ShouldUseATSPI() { return pid_ != base::GetCurrentProcId() || !application_name_match_pattern_.empty();
diff --git a/content/browser/accessibility/accessibility_event_recorder_mac.mm b/content/browser/accessibility/accessibility_event_recorder_mac.mm index 9b037b4..472c5f3 100644 --- a/content/browser/accessibility/accessibility_event_recorder_mac.mm +++ b/content/browser/accessibility/accessibility_event_recorder_mac.mm
@@ -73,6 +73,15 @@ return std::make_unique<AccessibilityEventRecorderMac>(manager, pid); } +std::vector<AccessibilityEventRecorder::EventRecorderFactory> +AccessibilityEventRecorder::GetTestPasses() { + // Both the Blink pass and native pass use the same recorder + return { + &AccessibilityEventRecorder::Create, + &AccessibilityEventRecorder::Create, + }; +} + AccessibilityEventRecorderMac::AccessibilityEventRecorderMac( BrowserAccessibilityManager* manager, base::ProcessId pid)
diff --git a/content/browser/accessibility/accessibility_event_recorder_uia_win.cc b/content/browser/accessibility/accessibility_event_recorder_uia_win.cc new file mode 100644 index 0000000..efe13e61 --- /dev/null +++ b/content/browser/accessibility/accessibility_event_recorder_uia_win.cc
@@ -0,0 +1,147 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/accessibility/accessibility_event_recorder_uia_win.h" + +#include <string> + +#include "base/strings/stringprintf.h" +#include "base/strings/utf_string_conversions.h" +#include "base/win/scoped_bstr.h" +#include "base/win/scoped_variant.h" +#include "content/browser/accessibility/browser_accessibility_com_win.h" +#include "content/browser/accessibility/browser_accessibility_manager.h" +#include "ui/base/win/atl_module.h" + +namespace content { + +namespace { + +std::string BstrToUTF8(BSTR bstr) { + base::string16 str16(bstr, SysStringLen(bstr)); + return base::UTF16ToUTF8(str16); +} + +} // namespace + +// static +AccessibilityEventRecorderUia* AccessibilityEventRecorderUia::instance_ = + nullptr; + +// static +std::unique_ptr<AccessibilityEventRecorder> +AccessibilityEventRecorderUia::CreateUia( + BrowserAccessibilityManager* manager, + base::ProcessId pid, + const base::StringPiece& application_name_match_pattern) { + return std::make_unique<AccessibilityEventRecorderUia>( + manager, pid, application_name_match_pattern); +} + +AccessibilityEventRecorderUia::AccessibilityEventRecorderUia( + BrowserAccessibilityManager* manager, + base::ProcessId pid, + const base::StringPiece& application_name_match_pattern) + : AccessibilityEventRecorder(manager) { + CHECK(!instance_) << "There can be only one instance of" + << " AccessibilityEventRecorder at a time."; + + // Create an instance of the CUIAutomation class. + CoCreateInstance(CLSID_CUIAutomation, NULL, CLSCTX_INPROC_SERVER, + IID_IUIAutomation, &uia_); + CHECK(uia_.Get()); + + uia_->CreateCacheRequest(&cache_request_); + CHECK(cache_request_.Get()); + + // Find the root IUIAutomationElement for the content window + HWND hwnd = manager->GetRoot()->GetTargetForNativeAccessibilityEvent(); + CHECK(hwnd); + + Microsoft::WRL::ComPtr<IUIAutomationElement> root; + uia_->ElementFromHandle(hwnd, &root); + CHECK(root.Get()); + + // Create the event handler + ui::win::CreateATLModuleIfNeeded(); + CHECK( + SUCCEEDED(CComObject<EventHandler>::CreateInstance(&uia_event_handler_))); + uia_event_handler_->Init(this, root); + + // Subscribe to focus events + uia_->AddFocusChangedEventHandler(nullptr, uia_event_handler_.Get()); + + instance_ = this; +} + +AccessibilityEventRecorderUia::~AccessibilityEventRecorderUia() { + uia_event_handler_->owner_ = nullptr; + uia_event_handler_.Reset(); + instance_ = nullptr; +} + +AccessibilityEventRecorderUia::EventHandler::EventHandler() {} + +AccessibilityEventRecorderUia::EventHandler::~EventHandler() {} + +void AccessibilityEventRecorderUia::EventHandler::Init( + AccessibilityEventRecorderUia* owner, + Microsoft::WRL::ComPtr<IUIAutomationElement> root) { + owner_ = owner; + root_ = root; +} + +STDMETHODIMP +AccessibilityEventRecorderUia::EventHandler::HandleFocusChangedEvent( + IUIAutomationElement* sender) { + if (!owner_) + return S_OK; + + base::win::ScopedBstr id; + sender->get_CurrentAutomationId(id.Receive()); + base::win::ScopedVariant id_variant(id, id.Length()); + + Microsoft::WRL::ComPtr<IUIAutomationElement> element_found; + Microsoft::WRL::ComPtr<IUIAutomationCondition> condition; + + owner_->uia_->CreatePropertyCondition(UIA_AutomationIdPropertyId, id_variant, + &condition); + CHECK(condition); + root_->FindFirst(TreeScope::TreeScope_Subtree, condition.Get(), + &element_found); + if (!element_found) { + VLOG(1) << "Ignoring UIA focus event outside our frame"; + return S_OK; + } + + std::string log = base::StringPrintf("UIA_AutomationFocusChangedEventId %s", + GetSenderInfo(sender).c_str()); + owner_->OnEvent(log); + + return S_OK; +} + +std::string AccessibilityEventRecorderUia::EventHandler::GetSenderInfo( + IUIAutomationElement* sender) { + std::string sender_info = ""; + + auto append_property = [&](const char* name, auto getter) { + base::win::ScopedBstr bstr; + (sender->*getter)(bstr.Receive()); + if (bstr.Length() > 0) { + sender_info += + base::StringPrintf("%s%s=%s", sender_info.empty() ? "" : ", ", name, + BstrToUTF8(bstr).c_str()); + } + }; + + append_property("role", &IUIAutomationElement::get_CurrentAriaRole); + append_property("name", &IUIAutomationElement::get_CurrentName); + + if (!sender_info.empty()) + sender_info = "on " + sender_info; + return sender_info; +} + +} // namespace content
diff --git a/content/browser/accessibility/accessibility_event_recorder_uia_win.h b/content/browser/accessibility/accessibility_event_recorder_uia_win.h new file mode 100644 index 0000000..e3aecc2 --- /dev/null +++ b/content/browser/accessibility/accessibility_event_recorder_uia_win.h
@@ -0,0 +1,73 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_ACCESSIBILITY_ACCESSIBILITY_EVENT_RECORDER_UIA_WIN_H_ +#define CONTENT_BROWSER_ACCESSIBILITY_ACCESSIBILITY_EVENT_RECORDER_UIA_WIN_H_ + +#include <ole2.h> +#include <stdint.h> +#include <uiautomation.h> +#include <wrl/client.h> + +#include "base/win/atl.h" +#include "content/browser/accessibility/accessibility_event_recorder.h" + +namespace content { + +class AccessibilityEventRecorderUia : public AccessibilityEventRecorder { + public: + AccessibilityEventRecorderUia( + BrowserAccessibilityManager* manager = nullptr, + base::ProcessId pid = 0, + const base::StringPiece& application_name_match_pattern = + base::StringPiece()); + ~AccessibilityEventRecorderUia() override; + + static std::unique_ptr<AccessibilityEventRecorder> CreateUia( + BrowserAccessibilityManager* manager = nullptr, + base::ProcessId pid = 0, + const base::StringPiece& application_name_match_pattern = + base::StringPiece()); + + private: + Microsoft::WRL::ComPtr<IUIAutomation> uia_; + Microsoft::WRL::ComPtr<IUIAutomationCacheRequest> cache_request_; + static AccessibilityEventRecorderUia* instance_; + + // An implementation of various UIA interface that forward event + // notifications to the owning event recorder. + class EventHandler : public CComObjectRootEx<CComMultiThreadModel>, + public IUIAutomationFocusChangedEventHandler { + public: + explicit EventHandler(); + virtual ~EventHandler(); + + void Init(AccessibilityEventRecorderUia* owner, + Microsoft::WRL::ComPtr<IUIAutomationElement> root); + + BEGIN_COM_MAP(EventHandler) + COM_INTERFACE_ENTRY(IUIAutomationFocusChangedEventHandler) + END_COM_MAP() + + // IUIAutomationFocusChangedEventHandler interface. + STDMETHOD(HandleFocusChangedEvent)(IUIAutomationElement* sender) override; + + // Points to the event recorder to receive notifications. + AccessibilityEventRecorderUia* owner_; + + private: + std::string GetSenderInfo(IUIAutomationElement* sender); + + Microsoft::WRL::ComPtr<IUIAutomationElement> root_; + + DISALLOW_COPY_AND_ASSIGN(EventHandler); + }; + Microsoft::WRL::ComPtr<CComObject<EventHandler>> uia_event_handler_; + + DISALLOW_COPY_AND_ASSIGN(AccessibilityEventRecorderUia); +}; + +} // namespace content + +#endif
diff --git a/content/browser/accessibility/accessibility_event_recorder_win.cc b/content/browser/accessibility/accessibility_event_recorder_win.cc index 287b437..73258215 100644 --- a/content/browser/accessibility/accessibility_event_recorder_win.cc +++ b/content/browser/accessibility/accessibility_event_recorder_win.cc
@@ -17,6 +17,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/win/scoped_bstr.h" #include "base/win/scoped_variant.h" +#include "content/browser/accessibility/accessibility_event_recorder_uia_win.h" #include "content/browser/accessibility/accessibility_tree_formatter_utils_win.h" #include "content/browser/accessibility/browser_accessibility_manager.h" #include "content/browser/accessibility/browser_accessibility_win.h" @@ -53,7 +54,7 @@ service_provider->QueryService(IID_IAccessibleText, accessible_text) : hr; } -std::string BstrToUTF8(BSTR bstr) { +std::string BstrToPrettyUTF8(BSTR bstr) { base::string16 str16(bstr, SysStringLen(bstr)); // IAccessibleText returns the text you get by appending all static text @@ -131,6 +132,18 @@ manager, pid, application_name_match_pattern); } +std::vector<AccessibilityEventRecorder::EventRecorderFactory> +AccessibilityEventRecorder::GetTestPasses() { + // In addition to the 'Blink' pass, Windows includes two accessibility APIs + // that need to be tested independently (MSAA & UIA); the Blink pass uses the + // same recorder as the MSAA pass. + return { + &AccessibilityEventRecorder::Create, + &AccessibilityEventRecorder::Create, + &AccessibilityEventRecorderUia::CreateUia, + }; +} + // static CALLBACK void AccessibilityEventRecorderWin::WinEventHookThunk( HWINEVENTHOOK handle, @@ -318,15 +331,17 @@ log += base::StringPrintf(" role=%s", RoleVariantToString(role).c_str()); if (name_bstr.Length() > 0) - log += base::StringPrintf(" name=\"%s\"", BstrToUTF8(name_bstr).c_str()); + log += + base::StringPrintf(" name=\"%s\"", BstrToPrettyUTF8(name_bstr).c_str()); if (value_bstr.Length() > 0) { bool is_document = role.type() == VT_I4 && ROLE_SYSTEM_DOCUMENT == V_I4(role.ptr()); // Don't show actual document value, which is a URL, in order to avoid // machine-based differences in tests. - log += is_document ? " value~=[doc-url]" - : base::StringPrintf(" value=\"%s\"", - BstrToUTF8(value_bstr).c_str()); + log += is_document + ? " value~=[doc-url]" + : base::StringPrintf(" value=\"%s\"", + BstrToPrettyUTF8(value_bstr).c_str()); } log += " "; log += base::UTF16ToUTF8(IAccessibleStateToString(ia_state)); @@ -355,7 +370,7 @@ IA2TextSegment old_text; if (SUCCEEDED(accessible_text->get_oldText(&old_text))) { log += base::StringPrintf(" old_text={'%s' start=%ld end=%ld}", - BstrToUTF8(old_text.text).c_str(), + BstrToPrettyUTF8(old_text.text).c_str(), old_text.start, old_text.end); } } @@ -363,7 +378,7 @@ IA2TextSegment new_text; if (SUCCEEDED(accessible_text->get_newText(&new_text))) { log += base::StringPrintf(" new_text={'%s' start=%ld end=%ld}", - BstrToUTF8(new_text.text).c_str(), + BstrToPrettyUTF8(new_text.text).c_str(), new_text.start, new_text.end); } }
diff --git a/content/browser/accessibility/accessibility_tree_formatter.cc b/content/browser/accessibility/accessibility_tree_formatter.cc index 7186571..5605e0b 100644 --- a/content/browser/accessibility/accessibility_tree_formatter.cc +++ b/content/browser/accessibility/accessibility_tree_formatter.cc
@@ -211,4 +211,7 @@ return true; } +void AccessibilityTreeFormatter::SetUpCommandLineForTestPass( + base::CommandLine* command_line) {} + } // namespace content
diff --git a/content/browser/accessibility/accessibility_tree_formatter.h b/content/browser/accessibility/accessibility_tree_formatter.h index 7dbe695c3f..51f3210 100644 --- a/content/browser/accessibility/accessibility_tree_formatter.h +++ b/content/browser/accessibility/accessibility_tree_formatter.h
@@ -24,6 +24,10 @@ const char kChildrenDictAttr[] = "children"; } +namespace base { +class CommandLine; +} + namespace content { // A utility class for formatting platform-specific accessibility information, @@ -68,6 +72,14 @@ // Create the appropriate native subclass of AccessibilityTreeFormatter. static std::unique_ptr<AccessibilityTreeFormatter> Create(); + // Get a set of factory methods to create tree-formatters, one for each test + // pass; see |DumpAccessibilityTestBase|. + using FormatterFactory = std::unique_ptr<AccessibilityTreeFormatter> (*)(); + static std::vector<FormatterFactory> GetTestPasses(); + + // Called to allow each test pass to alter the command-line + virtual void SetUpCommandLineForTestPass(base::CommandLine* command_line); + static bool MatchesPropertyFilters( const std::vector<PropertyFilter>& property_filters, const base::string16& text,
diff --git a/content/browser/accessibility/accessibility_tree_formatter_android.cc b/content/browser/accessibility/accessibility_tree_formatter_android.cc index 33fb318..3fa16b1a 100644 --- a/content/browser/accessibility/accessibility_tree_formatter_android.cc +++ b/content/browser/accessibility/accessibility_tree_formatter_android.cc
@@ -86,6 +86,16 @@ return std::make_unique<AccessibilityTreeFormatterAndroid>(); } +// static +std::vector<AccessibilityTreeFormatter::FormatterFactory> +AccessibilityTreeFormatter::GetTestPasses() { + // Note: Android doesn't do a "blink" pass; the blink tree is different on + // Android because we exclude inline text boxes, for performance. + return { + &AccessibilityTreeFormatter::Create, + }; +} + AccessibilityTreeFormatterAndroid::AccessibilityTreeFormatterAndroid() { }
diff --git a/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc b/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc index dda48cb..ea88671 100644 --- a/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc +++ b/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc
@@ -17,6 +17,7 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" +#include "content/browser/accessibility/accessibility_tree_formatter_blink.h" #include "content/browser/accessibility/accessibility_tree_formatter_utils_auralinux.h" #include "content/browser/accessibility/browser_accessibility_auralinux.h" #include "ui/accessibility/platform/ax_platform_node_auralinux.h" @@ -65,6 +66,15 @@ return std::make_unique<AccessibilityTreeFormatterAuraLinux>(); } +// static +std::vector<AccessibilityTreeFormatter::FormatterFactory> +AccessibilityTreeFormatter::GetTestPasses() { + return { + &AccessibilityTreeFormatterBlink::CreateBlink, + &AccessibilityTreeFormatter::Create, + }; +} + AccessibilityTreeFormatterAuraLinux::AccessibilityTreeFormatterAuraLinux() { }
diff --git a/content/browser/accessibility/accessibility_tree_formatter_blink.cc b/content/browser/accessibility/accessibility_tree_formatter_blink.cc index 250227f1..2d30f64 100644 --- a/content/browser/accessibility/accessibility_tree_formatter_blink.cc +++ b/content/browser/accessibility/accessibility_tree_formatter_blink.cc
@@ -138,6 +138,12 @@ AccessibilityTreeFormatterBlink::~AccessibilityTreeFormatterBlink() {} +// static +std::unique_ptr<AccessibilityTreeFormatter> +AccessibilityTreeFormatterBlink::CreateBlink() { + return std::make_unique<AccessibilityTreeFormatterBlink>(); +} + const char* const TREE_DATA_ATTRIBUTES[] = {"TreeData.textSelStartOffset", "TreeData.textSelEndOffset"};
diff --git a/content/browser/accessibility/accessibility_tree_formatter_blink.h b/content/browser/accessibility/accessibility_tree_formatter_blink.h index 796d73f..54fe9c83 100644 --- a/content/browser/accessibility/accessibility_tree_formatter_blink.h +++ b/content/browser/accessibility/accessibility_tree_formatter_blink.h
@@ -18,6 +18,8 @@ explicit AccessibilityTreeFormatterBlink(); ~AccessibilityTreeFormatterBlink() override; + static std::unique_ptr<AccessibilityTreeFormatter> CreateBlink(); + private: const base::FilePath::StringType GetExpectedFileSuffix() override; const std::string GetAllowEmptyString() override;
diff --git a/content/browser/accessibility/accessibility_tree_formatter_mac.mm b/content/browser/accessibility/accessibility_tree_formatter_mac.mm index 4a6e915..fadac15 100644 --- a/content/browser/accessibility/accessibility_tree_formatter_mac.mm +++ b/content/browser/accessibility/accessibility_tree_formatter_mac.mm
@@ -13,6 +13,7 @@ #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" +#include "content/browser/accessibility/accessibility_tree_formatter_blink.h" #include "content/browser/accessibility/browser_accessibility_cocoa.h" #include "content/browser/accessibility/browser_accessibility_mac.h" #include "content/browser/accessibility/browser_accessibility_manager.h" @@ -174,6 +175,7 @@ @"AXARIAPosInSet", @"AXAutocomplete", @"AXAutocompleteValue", + @"AXBlockQuoteLevel", NSAccessibilityColumnHeaderUIElementsAttribute, NSAccessibilityColumnIndexRangeAttribute, @"AXDOMIdentifier", @@ -237,6 +239,15 @@ return std::make_unique<AccessibilityTreeFormatterMac>(); } +// static +std::vector<AccessibilityTreeFormatter::FormatterFactory> +AccessibilityTreeFormatter::GetTestPasses() { + return { + &AccessibilityTreeFormatterBlink::CreateBlink, + &AccessibilityTreeFormatter::Create, + }; +} + AccessibilityTreeFormatterMac::AccessibilityTreeFormatterMac() { }
diff --git a/content/browser/accessibility/accessibility_tree_formatter_stub.cc b/content/browser/accessibility/accessibility_tree_formatter_stub.cc index 9e6dbcf..854abca7 100644 --- a/content/browser/accessibility/accessibility_tree_formatter_stub.cc +++ b/content/browser/accessibility/accessibility_tree_formatter_stub.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "base/strings/string_number_conversions.h" +#include "content/browser/accessibility/accessibility_tree_formatter_blink.h" #include "content/browser/accessibility/accessibility_tree_formatter_browser.h" namespace content { @@ -32,6 +33,15 @@ AccessibilityTreeFormatter::Create() { return std::make_unique<AccessibilityTreeFormatterStub>(); } + +// static +std::vector<AccessibilityTreeFormatter::FormatterFactory> +AccessibilityTreeFormatter::GetTestPasses() { + return { + &AccessibilityTreeFormatterBlink::CreateBlink, + &AccessibilityTreeFormatter::Create, + }; +} #endif AccessibilityTreeFormatterStub::AccessibilityTreeFormatterStub()
diff --git a/content/browser/accessibility/accessibility_tree_formatter_win.cc b/content/browser/accessibility/accessibility_tree_formatter_win.cc index aa2315e..550caa5 100644 --- a/content/browser/accessibility/accessibility_tree_formatter_win.cc +++ b/content/browser/accessibility/accessibility_tree_formatter_win.cc
@@ -14,6 +14,7 @@ #include <string> #include <utility> +#include "base/command_line.h" #include "base/files/file_path.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" @@ -24,10 +25,12 @@ #include "base/win/com_init_util.h" #include "base/win/scoped_bstr.h" #include "base/win/scoped_variant.h" +#include "content/browser/accessibility/accessibility_tree_formatter_blink.h" #include "content/browser/accessibility/accessibility_tree_formatter_utils_win.h" #include "content/browser/accessibility/browser_accessibility_manager.h" #include "content/browser/accessibility/browser_accessibility_win.h" #include "third_party/iaccessible2/ia2_api_all.h" +#include "ui/accessibility/accessibility_switches.h" #include "ui/base/win/atl_module.h" #include "ui/gfx/win/hwnd_util.h" @@ -78,6 +81,8 @@ LONG window_x = 0, LONG window_y = 0); + void SetUpCommandLineForTestPass(base::CommandLine* command_line) override; + private: void RecursiveBuildAccessibilityTree( const Microsoft::WRL::ComPtr<IAccessible> node, @@ -119,6 +124,23 @@ base::DictionaryValue* filtered_dict_result = nullptr) override; }; +// This is currently a clone of the base Windows MSAA formatter in order to +// override the GetExpectedFileSuffix function for UIA tests; it will +// eventually be replaced with a full UIA implementation. +class AccessibilityTreeFormatterUia : public AccessibilityTreeFormatterWin { + public: + AccessibilityTreeFormatterUia() {} + ~AccessibilityTreeFormatterUia() override {} + + static std::unique_ptr<AccessibilityTreeFormatter> CreateUia(); + + void SetUpCommandLineForTestPass(base::CommandLine* command_line) override; + + const base::FilePath::StringType GetExpectedFileSuffix() override { + return FILE_PATH_LITERAL("-expected-win-uia.txt"); + } +}; + // static std::unique_ptr<AccessibilityTreeFormatter> AccessibilityTreeFormatter::Create() { @@ -126,6 +148,36 @@ return std::make_unique<AccessibilityTreeFormatterWin>(); } +// static +std::unique_ptr<AccessibilityTreeFormatter> +AccessibilityTreeFormatterUia::CreateUia() { + base::win::AssertComInitialized(); + return std::make_unique<AccessibilityTreeFormatterUia>(); +} + +// static +std::vector<AccessibilityTreeFormatter::FormatterFactory> +AccessibilityTreeFormatter::GetTestPasses() { + // In addition to the 'Blink' pass, Windows includes two accessibility APIs + // that need to be tested independently (MSAA & UIA). + return { + &AccessibilityTreeFormatterBlink::CreateBlink, + &AccessibilityTreeFormatter::Create, + &AccessibilityTreeFormatterUia::CreateUia, + }; +} + +void AccessibilityTreeFormatterWin::SetUpCommandLineForTestPass( + base::CommandLine* command_line) { + base::CommandLine::ForCurrentProcess()->RemoveSwitch( + ::switches::kEnableExperimentalUIAutomation); +} +void AccessibilityTreeFormatterUia::SetUpCommandLineForTestPass( + base::CommandLine* command_line) { + base::CommandLine::ForCurrentProcess()->AppendSwitch( + ::switches::kEnableExperimentalUIAutomation); +} + AccessibilityTreeFormatterWin::AccessibilityTreeFormatterWin() { ui::win::CreateATLModuleIfNeeded(); }
diff --git a/content/browser/accessibility/browser_accessibility_android.cc b/content/browser/accessibility/browser_accessibility_android.cc index 8c5949b..05db626 100644 --- a/content/browser/accessibility/browser_accessibility_android.cc +++ b/content/browser/accessibility/browser_accessibility_android.cc
@@ -101,6 +101,8 @@ namespace content { +const float kContentInvalidTimeoutMillisecs = 6000.0; + // static BrowserAccessibility* BrowserAccessibility::Create() { return new BrowserAccessibilityAndroid(); @@ -264,6 +266,20 @@ } bool BrowserAccessibilityAndroid::IsContentInvalid() const { + if (IsFocused()) { + // When a node has focus, only report that it's invalid for a short period + // of time. Otherwise it's annoying to hear the invalid message every time + // a character is entered. + if (content_invalid_timer_.Elapsed().InMillisecondsF() < + kContentInvalidTimeoutMillisecs) { + bool invalid_state = + HasIntAttribute(ax::mojom::IntAttribute::kInvalidState) && + GetData().GetInvalidState() != ax::mojom::InvalidState::kFalse; + if (invalid_state) + return true; + } + return false; + } return HasIntAttribute(ax::mojom::IntAttribute::kInvalidState) && GetData().GetInvalidState() != ax::mojom::InvalidState::kFalse; } @@ -1713,4 +1729,42 @@ return count; } +base::string16 BrowserAccessibilityAndroid::GetContentInvalidErrorMessage() + const { + content::ContentClient* content_client = content::GetContentClient(); + int message_id = -1; + + if (!IsContentInvalid()) + return base::string16(); + + switch (GetData().GetInvalidState()) { + case ax::mojom::InvalidState::kNone: + case ax::mojom::InvalidState::kFalse: + // No error message necessary + break; + + case ax::mojom::InvalidState::kTrue: + case ax::mojom::InvalidState::kOther: + message_id = CONTENT_INVALID_TRUE; + break; + + case ax::mojom::InvalidState::kSpelling: + message_id = CONTENT_INVALID_SPELLING; + break; + + case ax::mojom::InvalidState::kGrammar: + message_id = CONTENT_INVALID_GRAMMAR; + break; + } + + if (message_id != -1) + return content_client->GetLocalizedString(message_id); + + return base::string16(); +} + +void BrowserAccessibilityAndroid::ResetContentInvalidTimer() { + content_invalid_timer_ = base::ElapsedTimer(); +} + } // namespace content
diff --git a/content/browser/accessibility/browser_accessibility_android.h b/content/browser/accessibility/browser_accessibility_android.h index e87b171f..a8ea72ae 100644 --- a/content/browser/accessibility/browser_accessibility_android.h +++ b/content/browser/accessibility/browser_accessibility_android.h
@@ -10,6 +10,7 @@ #include "base/android/scoped_java_ref.h" #include "base/macros.h" +#include "base/timer/elapsed_timer.h" #include "content/browser/accessibility/browser_accessibility.h" #include "ui/accessibility/platform/ax_platform_node.h" @@ -84,6 +85,8 @@ std::string GetRoleString() const; + base::string16 GetContentInvalidErrorMessage() const; + base::string16 GetRoleDescription() const; int GetItemIndex() const; @@ -148,6 +151,11 @@ std::vector<int32_t>* word_ends, int offset); + // Used to keep track of when to stop reporting content_invalid. + // Timer only applies if node has focus. + void ResetContentInvalidTimer(); + base::ElapsedTimer content_invalid_timer_ = base::ElapsedTimer(); + private: // This gives BrowserAccessibility::Create access to the class constructor. friend class BrowserAccessibility;
diff --git a/content/browser/accessibility/browser_accessibility_cocoa.mm b/content/browser/accessibility/browser_accessibility_cocoa.mm index 16ad32bd..ae2e164 100644 --- a/content/browser/accessibility/browser_accessibility_cocoa.mm +++ b/content/browser/accessibility/browser_accessibility_cocoa.mm
@@ -16,6 +16,7 @@ #include "base/mac/availability.h" #include "base/mac/foundation_util.h" #include "base/mac/scoped_cftyperef.h" +#include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" @@ -68,10 +69,13 @@ NSString* const NSAccessibilityAccessKeyAttribute = @"AXAccessKey"; NSString* const NSAccessibilityAutocompleteValueAttribute = @"AXAutocompleteValue"; +NSString* const NSAccessibilityBlockQuoteLevelAttribute = @"AXBlockQuoteLevel"; +NSString* const NSAccessibilityDOMClassList = @"AXDOMClassList"; NSString* const NSAccessibilityDOMIdentifierAttribute = @"AXDOMIdentifier"; NSString* const NSAccessibilityDropEffectsAttribute = @"AXDropEffects"; NSString* const NSAccessibilityEditableAncestorAttribute = @"AXEditableAncestor"; +NSString* const NSAccessibilityElementBusyAttribute = @"AXElementBusy"; NSString* const NSAccessibilityFocusableAncestorAttribute = @"AXFocusableAncestor"; NSString* const NSAccessibilityGrabbedAttribute = @"AXGrabbed"; @@ -591,6 +595,7 @@ {NSAccessibilityARIASetSizeAttribute, @"ariaSetSize"}, {NSAccessibilityAccessKeyAttribute, @"accessKey"}, {NSAccessibilityAutocompleteValueAttribute, @"autocompleteValue"}, + {NSAccessibilityBlockQuoteLevelAttribute, @"blockQuoteLevel"}, {NSAccessibilityChildrenAttribute, @"children"}, {NSAccessibilityColumnsAttribute, @"columns"}, {NSAccessibilityColumnHeaderUIElementsAttribute, @"columnHeaders"}, @@ -602,8 +607,10 @@ {NSAccessibilityDisclosureLevelAttribute, @"disclosureLevel"}, {NSAccessibilityDisclosedRowsAttribute, @"disclosedRows"}, {NSAccessibilityDropEffectsAttribute, @"dropEffects"}, + {NSAccessibilityDOMClassList, @"domClassList"}, {NSAccessibilityDOMIdentifierAttribute, @"domIdentifier"}, {NSAccessibilityEditableAncestorAttribute, @"editableAncestor"}, + {NSAccessibilityElementBusyAttribute, @"elementBusy"}, {NSAccessibilityEnabledAttribute, @"enabled"}, {NSAccessibilityEndTextMarkerAttribute, @"endTextMarker"}, {NSAccessibilityExpandedAttribute, @"expanded"}, @@ -781,6 +788,22 @@ ax::mojom::StringAttribute::kAutoComplete); } +- (id)blockQuoteLevel { + if (![self instanceActive]) + return nil; + // TODO(accessibility) This is for the number of ancestors that are a + // <blockquote>, including self, useful for tracking replies to replies etc. + // in an email. + int level = 0; + BrowserAccessibility* ancestor = owner_; + while (ancestor) { + if (ancestor->GetRole() == ax::mojom::Role::kBlockquote) + ++level; + ancestor = ancestor->PlatformGetParent(); + } + return [NSNumber numberWithInt:level]; +} + // Returns an array of BrowserAccessibilityCocoa objects, representing the // accessibility children of this object. - (NSArray*)children { @@ -1053,6 +1076,22 @@ return nil; } +- (NSArray*)domClassList { + if (![self instanceActive]) + return nil; + + NSMutableArray* ret = [[[NSMutableArray alloc] init] autorelease]; + + std::string classes; + if (owner_->GetHtmlAttribute("class", &classes)) { + std::vector<std::string> split_classes = base::SplitString( + classes, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); + for (const auto& className : split_classes) + [ret addObject:(base::SysUTF8ToNSString(className))]; + } + return ret; +} + - (NSString*)domIdentifier { if (![self instanceActive]) return nil; @@ -1061,7 +1100,7 @@ if (owner_->GetHtmlAttribute("id", &id)) return base::SysUTF8ToNSString(id); - return nil; + return @""; } - (id)editableAncestor { @@ -1081,6 +1120,13 @@ return editableRoot; } +- (NSNumber*)elementBusy { + if (![self instanceActive]) + return nil; + return [NSNumber numberWithBool:owner_->GetData().GetBoolAttribute( + ax::mojom::BoolAttribute::kBusy)]; +} + - (NSNumber*)enabled { if (![self instanceActive]) return nil; @@ -1380,8 +1426,6 @@ [self addLinkedUIElementsFromAttribute:ax::mojom::IntListAttribute:: kRadioGroupIds addTo:ret]; - if ([ret count] == 0) - return nil; return ret; } @@ -1961,6 +2005,8 @@ return base::SysUTF16ToNSString(value.substr(selStart, selLength)); } +// Example, caret at offset 5: +// AXSelectedTextRange: “pos=5 len=0” - (NSValue*)selectedTextRange { if (![self instanceActive]) return nil; @@ -1970,6 +2016,7 @@ if (!owner_->GetIntAttribute(ax::mojom::IntAttribute::kTextSelStart, &selStart) || !owner_->GetIntAttribute(ax::mojom::IntAttribute::kTextSelEnd, &selEnd)) { + // TODO(accessibility) Incorrectly reaches this line in a rich text area. return nil; } @@ -2127,7 +2174,7 @@ ax::mojom::StringAttribute::kName); } - return nil; + return @""; } - (id)titleUIElement { @@ -2895,26 +2942,27 @@ // General attributes. NSMutableArray* ret = [NSMutableArray - arrayWithObjects:NSAccessibilityAccessKeyAttribute, + arrayWithObjects:NSAccessibilityBlockQuoteLevelAttribute, NSAccessibilityChildrenAttribute, NSAccessibilityDescriptionAttribute, + NSAccessibilityDOMClassList, NSAccessibilityDOMIdentifierAttribute, + NSAccessibilityElementBusyAttribute, NSAccessibilityEnabledAttribute, NSAccessibilityEndTextMarkerAttribute, NSAccessibilityFocusedAttribute, NSAccessibilityHelpAttribute, - NSAccessibilityInvalidAttribute, NSAccessibilityLinkedUIElementsAttribute, NSAccessibilityParentAttribute, NSAccessibilityPositionAttribute, NSAccessibilityRoleAttribute, NSAccessibilityRoleDescriptionAttribute, + NSAccessibilitySelectedAttribute, NSAccessibilitySelectedTextMarkerRangeAttribute, NSAccessibilitySizeAttribute, NSAccessibilityStartTextMarkerAttribute, NSAccessibilitySubroleAttribute, NSAccessibilityTitleAttribute, - NSAccessibilityTitleUIElementAttribute, NSAccessibilityTopLevelUIElementAttribute, NSAccessibilityValueAttribute, NSAccessibilityVisitedAttribute, @@ -3005,10 +3053,21 @@ // Caret navigation and text selection attributes. if (owner_->HasState(ax::mojom::State::kEditable)) { + // Add ancestor attributes if not a web area. + if (![role isEqualToString:@"AXWebArea"]) { + [ret addObjectsFromArray:@[ + NSAccessibilityEditableAncestorAttribute, + NSAccessibilityFocusableAncestorAttribute, + NSAccessibilityHighestEditableAncestorAttribute + ]]; + } + } + + if (owner_->GetBoolAttribute(ax::mojom::BoolAttribute::kEditableRoot)) { [ret addObjectsFromArray:@[ - NSAccessibilityAutocompleteValueAttribute, NSAccessibilityInsertionPointLineNumberAttribute, NSAccessibilityNumberOfCharactersAttribute, + NSAccessibilityPlaceholderValueAttribute, NSAccessibilitySelectedTextAttribute, NSAccessibilitySelectedTextRangeAttribute, NSAccessibilityVisibleCharacterRangeAttribute, @@ -3020,15 +3079,6 @@ ]]; } - // Add ancestor attributes if not a web area. - if (![role isEqualToString:@"AXWebArea"]) { - [ret addObjectsFromArray:@[ - NSAccessibilityEditableAncestorAttribute, - NSAccessibilityFocusableAncestorAttribute, - NSAccessibilityHighestEditableAncestorAttribute - ]]; - } - // Add the url attribute only if it has a valid url. if ([self url] != nil) { [ret addObjectsFromArray:@[ NSAccessibilityURLAttribute ]]; @@ -3087,14 +3137,19 @@ [ret addObjectsFromArray:@[ NSAccessibilityOrientationAttribute ]]; } - if (owner_->HasStringAttribute(ax::mojom::StringAttribute::kPlaceholder)) { - [ret addObjectsFromArray:@[ NSAccessibilityPlaceholderValueAttribute ]]; + // Anything focusable or any control: + if (owner_->HasIntAttribute(ax::mojom::IntAttribute::kRestriction) || + owner_->HasIntAttribute(ax::mojom::IntAttribute::kInvalidState) || + owner_->HasState(ax::mojom::State::kFocusable)) { + [ret addObjectsFromArray:@[ + NSAccessibilityAccessKeyAttribute, + NSAccessibilityInvalidAttribute, + @"AXRequired", + ]]; } - if (GetState(owner_, ax::mojom::State::kRequired)) { - [ret addObjectsFromArray:@[ @"AXRequired" ]]; - } - + // TODO(accessibility) What nodes should language be exposed on given new + // auto detection features? if (owner_->HasStringAttribute(ax::mojom::StringAttribute::kLanguage)) { [ret addObjectsFromArray:@[ NSAccessibilityLanguageAttribute ]]; } @@ -3112,6 +3167,13 @@ .size() > 0) { [ret addObjectsFromArray:@[ NSAccessibilityTitleUIElementAttribute ]]; } + + if (owner_->HasStringAttribute(ax::mojom::StringAttribute::kAutoComplete)) + [ret addObject:NSAccessibilityAutocompleteValueAttribute]; + + if ([self shouldExposeTitleUIElement]) + [ret addObject:NSAccessibilityTitleUIElementAttribute]; + // TODO(aboxhall): expose NSAccessibilityServesAsTitleForUIElementsAttribute // for elements which are referred to by labelledby or are labels
diff --git a/content/browser/accessibility/browser_accessibility_manager_android.cc b/content/browser/accessibility/browser_accessibility_manager_android.cc index 7cb40422..50ab10a 100644 --- a/content/browser/accessibility/browser_accessibility_manager_android.cc +++ b/content/browser/accessibility/browser_accessibility_manager_android.cc
@@ -77,9 +77,9 @@ WebContentsAccessibilityAndroid* wcax = GetWebContentsAXFromRootManager(); if (!wcax) return; - BrowserAccessibilityAndroid* android_node = static_cast<BrowserAccessibilityAndroid*>(node); + android_node->ResetContentInvalidTimer(); wcax->HandleFocusChanged(android_node->unique_id()); }
diff --git a/content/browser/accessibility/browser_accessibility_manager_win.cc b/content/browser/accessibility/browser_accessibility_manager_win.cc index 6a54cd2..ccadab5 100644 --- a/content/browser/accessibility/browser_accessibility_manager_win.cc +++ b/content/browser/accessibility/browser_accessibility_manager_win.cc
@@ -88,6 +88,7 @@ BrowserAccessibilityManager::FireFocusEvent(node); DCHECK(node); FireWinAccessibilityEvent(EVENT_OBJECT_FOCUS, node); + FireUiaAccessibilityEvent(UIA_AutomationFocusChangedEventId, node); } void BrowserAccessibilityManagerWin::FireBlinkEvent( @@ -196,30 +197,15 @@ void BrowserAccessibilityManagerWin::FireWinAccessibilityEvent( LONG win_event_type, BrowserAccessibility* node) { - if (!node->CanFireEvents()) + if (::switches::IsExperimentalAccessibilityPlatformUIAEnabled()) + return; + if (!ShouldFireEventForNode(node)) return; - // If there's no root delegate, this may be a new frame that hasn't - // yet been swapped in or added to the frame tree. Suppress firing events - // until then. - BrowserAccessibilityDelegate* root_delegate = GetDelegateFromRootManager(); - if (!root_delegate) - return; - - HWND hwnd = root_delegate->AccessibilityGetAcceleratedWidget(); + HWND hwnd = GetParentHWND(); if (!hwnd) return; - // Don't fire events when this document might be stale as the user has - // started navigating to a new document. - if (user_is_navigating_away_) - return; - - // Inline text boxes are an internal implementation detail, we don't - // expose them to Windows. - if (node->GetRole() == ax::mojom::Role::kInlineTextBox) - return; - // Pass the negation of this node's unique id in the |child_id| // argument to NotifyWinEvent; the AT client will then call get_accChild // on the HWND's accessibility object and pass it that same id, which @@ -228,6 +214,18 @@ ::NotifyWinEvent(win_event_type, hwnd, OBJID_CLIENT, child_id); } +void BrowserAccessibilityManagerWin::FireUiaAccessibilityEvent( + LONG uia_event, + BrowserAccessibility* node) { + if (!::switches::IsExperimentalAccessibilityPlatformUIAEnabled()) + return; + if (!ShouldFireEventForNode(node)) + return; + + ::UiaRaiseAutomationEvent(ToBrowserAccessibilityWin(node)->GetCOM(), + uia_event); +} + bool BrowserAccessibilityManagerWin::CanFireEvents() { BrowserAccessibilityDelegate* root_delegate = GetDelegateFromRootManager(); if (!root_delegate) @@ -345,4 +343,29 @@ } } +bool BrowserAccessibilityManagerWin::ShouldFireEventForNode( + BrowserAccessibility* node) { + if (!node || !node->CanFireEvents()) + return false; + + // If there's no root delegate, this may be a new frame that hasn't + // yet been swapped in or added to the frame tree. Suppress firing events + // until then. + BrowserAccessibilityDelegate* root_delegate = GetDelegateFromRootManager(); + if (!root_delegate) + return false; + + // Don't fire events when this document might be stale as the user has + // started navigating to a new document. + if (user_is_navigating_away_) + return false; + + // Inline text boxes are an internal implementation detail, we don't + // expose them to Windows. + if (node->GetRole() == ax::mojom::Role::kInlineTextBox) + return false; + + return true; +} + } // namespace content
diff --git a/content/browser/accessibility/browser_accessibility_manager_win.h b/content/browser/accessibility/browser_accessibility_manager_win.h index e3a887e..a298243 100644 --- a/content/browser/accessibility/browser_accessibility_manager_win.h +++ b/content/browser/accessibility/browser_accessibility_manager_win.h
@@ -45,6 +45,7 @@ BrowserAccessibility* node) override; void FireWinAccessibilityEvent(LONG win_event, BrowserAccessibility* node); + void FireUiaAccessibilityEvent(LONG uia_event, BrowserAccessibility* node); // Track this object and post a VISIBLE_DATA_CHANGED notification when // its container scrolls. @@ -61,6 +62,8 @@ bool root_changed, const std::vector<ui::AXTreeObserver::Change>& changes) override; + bool ShouldFireEventForNode(BrowserAccessibility* node); + private: // Give BrowserAccessibilityManager::Create access to our constructor. friend class BrowserAccessibilityManager;
diff --git a/content/browser/accessibility/dump_accessibility_browsertest_base.cc b/content/browser/accessibility/dump_accessibility_browsertest_base.cc index 1d38171..567d5bc5 100644 --- a/content/browser/accessibility/dump_accessibility_browsertest_base.cc +++ b/content/browser/accessibility/dump_accessibility_browsertest_base.cc
@@ -15,11 +15,12 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/scoped_command_line.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" +#include "content/browser/accessibility/accessibility_event_recorder.h" #include "content/browser/accessibility/accessibility_tree_formatter.h" -#include "content/browser/accessibility/accessibility_tree_formatter_blink.h" #include "content/browser/accessibility/browser_accessibility.h" #include "content/browser/accessibility/browser_accessibility_manager.h" #include "content/browser/accessibility/browser_accessibility_state_impl.h" @@ -80,9 +81,9 @@ typedef AccessibilityTreeFormatter::NodeFilter NodeFilter; DumpAccessibilityTestBase::DumpAccessibilityTestBase() - : is_blink_pass_(false), - enable_accessibility_after_navigating_(false) { -} + : formatter_factory_(nullptr), + event_recorder_factory_(nullptr), + enable_accessibility_after_navigating_(false) {} DumpAccessibilityTestBase::~DumpAccessibilityTestBase() { } @@ -100,8 +101,7 @@ base::string16 DumpAccessibilityTestBase::DumpUnfilteredAccessibilityTreeAsString() { - std::unique_ptr<AccessibilityTreeFormatter> formatter( - CreateAccessibilityTreeFormatter()); + std::unique_ptr<AccessibilityTreeFormatter> formatter(formatter_factory_()); std::vector<PropertyFilter> property_filters; property_filters.push_back( PropertyFilter(base::ASCIIToUTF16("*"), PropertyFilter::ALLOW)); @@ -188,29 +188,30 @@ } } -std::unique_ptr<AccessibilityTreeFormatter> -DumpAccessibilityTestBase::CreateAccessibilityTreeFormatter() { - if (is_blink_pass_) - return std::make_unique<AccessibilityTreeFormatterBlink>(); - else - return AccessibilityTreeFormatter::Create(); -} - void DumpAccessibilityTestBase::RunTest( const base::FilePath file_path, const char* file_dir) { -#if !defined(OS_ANDROID) - // The blink tree is different on Android because we exclude inline - // text boxes, for performance. - is_blink_pass_ = true; - RunTestForPlatform(file_path, file_dir); -#endif - is_blink_pass_ = false; - RunTestForPlatform(file_path, file_dir); + // Get all the tree formatters; the test is run independently on each one. + auto formatters = AccessibilityTreeFormatter::GetTestPasses(); + auto event_recorders = AccessibilityEventRecorder::GetTestPasses(); + DCHECK(event_recorders.size() == formatters.size()); + + int pass_count = formatters.size(); + for (int pass = 0; pass < pass_count; ++pass) { + formatter_factory_ = formatters[pass]; + event_recorder_factory_ = event_recorders[pass]; + RunTestForPlatform(file_path, file_dir); + } + formatter_factory_ = nullptr; + event_recorder_factory_ = nullptr; } void DumpAccessibilityTestBase::RunTestForPlatform( const base::FilePath file_path, const char* file_dir) { - formatter_ = CreateAccessibilityTreeFormatter(); + formatter_ = formatter_factory_(); + + base::test::ScopedCommandLine scoped_command_line; + formatter_->SetUpCommandLineForTestPass( + scoped_command_line.GetProcessCommandLine()); // Disable the "hot tracked" state (set when the mouse is hovering over // an object) because it makes test output change based on the mouse position.
diff --git a/content/browser/accessibility/dump_accessibility_browsertest_base.h b/content/browser/accessibility/dump_accessibility_browsertest_base.h index 058fe0b..4dff2327 100644 --- a/content/browser/accessibility/dump_accessibility_browsertest_base.h +++ b/content/browser/accessibility/dump_accessibility_browsertest_base.h
@@ -11,6 +11,7 @@ #include "base/debug/leak_annotations.h" #include "base/strings/string16.h" #include "build/build_config.h" +#include "content/browser/accessibility/accessibility_event_recorder.h" #include "content/browser/accessibility/accessibility_tree_formatter.h" #include "content/public/test/content_browser_test.h" @@ -96,10 +97,6 @@ std::vector<std::string>* wait_for, std::vector<std::string>* run_until); - // Create the right AccessibilityTreeFormatter subclass. - std::unique_ptr<AccessibilityTreeFormatter> - CreateAccessibilityTreeFormatter(); - void RunTestForPlatform(const base::FilePath file_path, const char* file_dir); // The default property filters plus the property filters loaded from the test @@ -114,12 +111,13 @@ ScopedLeakSanitizerDisabler lsan_disabler; #endif + // The current tree-formatter and event-recorder factories. + AccessibilityTreeFormatter::FormatterFactory formatter_factory_; + AccessibilityEventRecorder::EventRecorderFactory event_recorder_factory_; + // The current AccessibilityTreeFormatter. std::unique_ptr<AccessibilityTreeFormatter> formatter_; - // Whether we're doing a native pass or internal/blink tree pass. - bool is_blink_pass_; - // Whether we should enable accessibility after navigating to the page, // otherwise we enable it first. bool enable_accessibility_after_navigating_;
diff --git a/content/browser/accessibility/dump_accessibility_events_browsertest.cc b/content/browser/accessibility/dump_accessibility_events_browsertest.cc index fb483fb..308a50c7 100644 --- a/content/browser/accessibility/dump_accessibility_events_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_events_browsertest.cc
@@ -104,9 +104,10 @@ WebContentsImpl* web_contents = static_cast<WebContentsImpl*>( shell()->web_contents()); base::ProcessId pid = base::GetCurrentProcId(); - std::unique_ptr<AccessibilityEventRecorder> event_recorder( - AccessibilityEventRecorder::Create( - web_contents->GetRootBrowserAccessibilityManager(), pid)); + std::unique_ptr<AccessibilityEventRecorder> event_recorder = + event_recorder_factory_( + web_contents->GetRootBrowserAccessibilityManager(), pid, + base::StringPiece{}); event_recorder->set_only_web_events(true); // Save a copy of the accessibility tree (as a text dump); we'll
diff --git a/content/browser/accessibility/dump_accessibility_tree_browsertest.cc b/content/browser/accessibility/dump_accessibility_tree_browsertest.cc index 7d9e0ac..4cd471c5 100644 --- a/content/browser/accessibility/dump_accessibility_tree_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_tree_browsertest.cc
@@ -130,8 +130,7 @@ } std::vector<std::string> Dump(std::vector<std::string>& unused) override { - std::unique_ptr<AccessibilityTreeFormatter> formatter( - CreateAccessibilityTreeFormatter()); + std::unique_ptr<AccessibilityTreeFormatter> formatter(formatter_factory_()); formatter->SetPropertyFilters(property_filters_); formatter->SetNodeFilters(node_filters_); base::string16 actual_contents_utf16; @@ -1084,6 +1083,11 @@ RunHtmlTest(FILE_PATH_LITERAL("blockquote.html")); } +IN_PROC_BROWSER_TEST_F(DumpAccessibilityTreeTest, + AccessibilityBlockquoteLevels) { + RunHtmlTest(FILE_PATH_LITERAL("blockquote-levels.html")); +} + IN_PROC_BROWSER_TEST_F(DumpAccessibilityTreeTest, AccessibilityBody) { RunHtmlTest(FILE_PATH_LITERAL("body.html")); } @@ -1953,6 +1957,12 @@ // TODO(crbug.com/916003): Fix race condition. IN_PROC_BROWSER_TEST_F(DumpAccessibilityTreeTest, + DISABLED_AccessibilityNoSourceVideo) { + RunHtmlTest(FILE_PATH_LITERAL("no-source-video.html")); +} + +// TODO(crbug.com/916003): Fix race condition. +IN_PROC_BROWSER_TEST_F(DumpAccessibilityTreeTest, DISABLED_AccessibilityVideoControls) { RunHtmlTest(FILE_PATH_LITERAL("video-controls.html")); }
diff --git a/content/browser/accessibility/web_contents_accessibility_android.cc b/content/browser/accessibility/web_contents_accessibility_android.cc index d04d18a..af4cc7c 100644 --- a/content/browser/accessibility/web_contents_accessibility_android.cc +++ b/content/browser/accessibility/web_contents_accessibility_android.cc
@@ -719,12 +719,14 @@ base::android::ConvertUTF16ToJavaString(env, node->GetHint()), node->GetIntAttribute(ax::mojom::IntAttribute::kTextSelStart), node->GetIntAttribute(ax::mojom::IntAttribute::kTextSelEnd), - node->HasImage()); + node->HasImage(), node->IsContentInvalid()); Java_WebContentsAccessibilityImpl_setAccessibilityNodeInfoLollipopAttributes( env, obj, info, node->CanOpenPopup(), node->IsContentInvalid(), node->IsDismissable(), node->IsMultiLine(), node->AndroidInputType(), - node->AndroidLiveRegionType()); + node->AndroidLiveRegionType(), + base::android::ConvertUTF16ToJavaString( + env, node->GetContentInvalidErrorMessage())); bool has_character_locations = node->HasCharacterLocations(); Java_WebContentsAccessibilityImpl_setAccessibilityNodeInfoOAttributes(
diff --git a/content/browser/appcache/appcache_backend_impl.cc b/content/browser/appcache/appcache_backend_impl.cc index f4efa9b..c8c75951 100644 --- a/content/browser/appcache/appcache_backend_impl.cc +++ b/content/browser/appcache/appcache_backend_impl.cc
@@ -21,8 +21,6 @@ AppCacheBackendImpl::AppCacheBackendImpl(AppCacheServiceImpl* service, int process_id) : service_(service), - frontend_proxy_(process_id), - frontend_(&frontend_proxy_), process_id_(process_id) { DCHECK(service); service_->RegisterBackend(this); @@ -35,6 +33,7 @@ void AppCacheBackendImpl::RegisterHost( blink::mojom::AppCacheHostRequest host_request, + blink::mojom::AppCacheFrontendPtr frontend, int32_t id, int32_t render_frame_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); @@ -50,10 +49,10 @@ if (host) { // Switch the frontend proxy so that the host can make IPC calls from // here on. - host->set_frontend(frontend_, render_frame_id); + host->set_frontend(std::move(frontend), render_frame_id); } else { host = std::make_unique<AppCacheHost>(id, process_id(), render_frame_id, - frontend_, service_); + std::move(frontend), service_); } host->BindRequest(std::move(host_request));
diff --git a/content/browser/appcache/appcache_backend_impl.h b/content/browser/appcache/appcache_backend_impl.h index 39cb9dd..a4ff77d 100644 --- a/content/browser/appcache/appcache_backend_impl.h +++ b/content/browser/appcache/appcache_backend_impl.h
@@ -8,7 +8,6 @@ #include <stdint.h> #include <memory> -#include "content/browser/appcache/appcache_frontend_proxy.h" #include "content/browser/appcache/appcache_host.h" #include "content/common/content_export.h" #include "third_party/blink/public/mojom/appcache/appcache.mojom.h" @@ -27,6 +26,7 @@ // blink::mojom::AppCacheBackend void RegisterHost(blink::mojom::AppCacheHostRequest host_request, + blink::mojom::AppCacheFrontendPtr frontend, int32_t host_id, int32_t render_frame_id) override; void UnregisterHost(int32_t host_id); @@ -40,16 +40,10 @@ using HostMap = std::unordered_map<int, std::unique_ptr<AppCacheHost>>; const HostMap& hosts() { return hosts_; } - void set_frontend_for_testing(blink::mojom::AppCacheFrontend* frontend) { - frontend_ = frontend; - } - private: // Raw pointer is safe because instances of this class are owned by // |service_|. AppCacheServiceImpl* service_; - AppCacheFrontendProxy frontend_proxy_; - blink::mojom::AppCacheFrontend* frontend_; int process_id_; HostMap hosts_;
diff --git a/content/browser/appcache/appcache_frontend_proxy.cc b/content/browser/appcache/appcache_frontend_proxy.cc deleted file mode 100644 index 8b8694f..0000000 --- a/content/browser/appcache/appcache_frontend_proxy.cc +++ /dev/null
@@ -1,85 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/appcache/appcache_frontend_proxy.h" - -#include "base/bind.h" -#include "base/task/post_task.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/render_process_host.h" -#include "content/public/common/bind_interface_helpers.h" -#include "third_party/blink/public/mojom/appcache/appcache.mojom.h" -#include "third_party/blink/public/mojom/appcache/appcache_info.mojom.h" -#include "third_party/blink/public/mojom/devtools/console_message.mojom.h" - -namespace content { - -AppCacheFrontendProxy::AppCacheFrontendProxy(int process_id) - : process_id_(process_id) {} - -AppCacheFrontendProxy::~AppCacheFrontendProxy() {} - -namespace { -void BindOnUIThread(int process_id, - blink::mojom::AppCacheFrontendRequest request) { - if (auto* render_process_host = RenderProcessHost::FromID(process_id)) { - BindInterface(render_process_host, std::move(request)); - } -} -} // namespace - -blink::mojom::AppCacheFrontend* AppCacheFrontendProxy::GetAppCacheFrontend() { - if (!app_cache_renderer_ptr_) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&BindOnUIThread, process_id_, - mojo::MakeRequest(&app_cache_renderer_ptr_))); - } - return app_cache_renderer_ptr_.get(); -} - -void AppCacheFrontendProxy::CacheSelected(int32_t host_id, - blink::mojom::AppCacheInfoPtr info) { - GetAppCacheFrontend()->CacheSelected(host_id, std::move(info)); -} - -void AppCacheFrontendProxy::EventRaised( - const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheEventID event_id) { - DCHECK_NE(blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT, - event_id); // See OnProgressEventRaised. - GetAppCacheFrontend()->EventRaised(host_ids, event_id); -} - -void AppCacheFrontendProxy::ProgressEventRaised( - const std::vector<int32_t>& host_ids, - const GURL& url, - int32_t num_total, - int32_t num_complete) { - GetAppCacheFrontend()->ProgressEventRaised(host_ids, url, num_total, - num_complete); -} - -void AppCacheFrontendProxy::ErrorEventRaised( - const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheErrorDetailsPtr details) { - GetAppCacheFrontend()->ErrorEventRaised(host_ids, std::move(details)); -} - -void AppCacheFrontendProxy::LogMessage( - int32_t host_id, - blink::mojom::ConsoleMessageLevel log_level, - const std::string& message) { - GetAppCacheFrontend()->LogMessage(host_id, log_level, message); -} - -void AppCacheFrontendProxy::SetSubresourceFactory( - int32_t host_id, - network::mojom::URLLoaderFactoryPtr url_loader_factory) { - GetAppCacheFrontend()->SetSubresourceFactory(host_id, - std::move(url_loader_factory)); -} - -} // namespace content
diff --git a/content/browser/appcache/appcache_frontend_proxy.h b/content/browser/appcache/appcache_frontend_proxy.h deleted file mode 100644 index b00e601..0000000 --- a/content/browser/appcache/appcache_frontend_proxy.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_BROWSER_APPCACHE_APPCACHE_FRONTEND_PROXY_H_ -#define CONTENT_BROWSER_APPCACHE_APPCACHE_FRONTEND_PROXY_H_ - -#include <string> -#include <vector> - -#include "third_party/blink/public/mojom/appcache/appcache.mojom.h" -#include "third_party/blink/public/mojom/appcache/appcache_info.mojom.h" -#include "third_party/blink/public/mojom/devtools/console_message.mojom.h" - -namespace content { - -// Sends appcache related messages to a child process. -class AppCacheFrontendProxy : public blink::mojom::AppCacheFrontend { - public: - explicit AppCacheFrontendProxy(int process_id); - ~AppCacheFrontendProxy() override; - - // AppCacheFrontend methods - void CacheSelected(int32_t host_id, - blink::mojom::AppCacheInfoPtr info) override; - void EventRaised(const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheEventID event_id) override; - void ProgressEventRaised(const std::vector<int32_t>& host_ids, - const GURL& url, - int32_t num_total, - int32_t num_complete) override; - void ErrorEventRaised(const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheErrorDetailsPtr details) override; - void LogMessage(int32_t host_id, - blink::mojom::ConsoleMessageLevel log_level, - const std::string& message) override; - void SetSubresourceFactory( - int32_t host_id, - network::mojom::URLLoaderFactoryPtr url_loader_factory) override; - - private: - blink::mojom::AppCacheFrontend* GetAppCacheFrontend(); - - const int process_id_; - blink::mojom::AppCacheFrontendPtr app_cache_renderer_ptr_; -}; - -} // namespace content - -#endif // CONTENT_BROWSER_APPCACHE_APPCACHE_FRONTEND_PROXY_H_
diff --git a/content/browser/appcache/appcache_fuzzer.cc b/content/browser/appcache/appcache_fuzzer.cc index ce74d0d..6727d2be 100644 --- a/content/browser/appcache/appcache_fuzzer.cc +++ b/content/browser/appcache/appcache_fuzzer.cc
@@ -157,8 +157,10 @@ switch (command.command_case()) { case fuzzing::proto::Command::kRegisterHost: { int32_t host_id = command.register_host().host_id(); + blink::mojom::AppCacheFrontendPtr frontend; + mojo::MakeRequest(&frontend); host->RegisterHost(mojo::MakeRequest(®istered_hosts[host_id]), - host_id, MSG_ROUTING_NONE); + std::move(frontend), host_id, MSG_ROUTING_NONE); break; } case fuzzing::proto::Command::kUnregisterHost: {
diff --git a/content/browser/appcache/appcache_group_unittest.cc b/content/browser/appcache/appcache_group_unittest.cc index b2321f1..6991084 100644 --- a/content/browser/appcache/appcache_group_unittest.cc +++ b/content/browser/appcache/appcache_group_unittest.cc
@@ -12,6 +12,7 @@ #include "content/browser/appcache/appcache_host.h" #include "content/browser/appcache/appcache_update_job.h" #include "content/browser/appcache/mock_appcache_service.h" +#include "mojo/public/cpp/bindings/binding_set.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/mojom/appcache/appcache.mojom.h" #include "third_party/blink/public/mojom/appcache/appcache_info.mojom.h" @@ -26,54 +27,53 @@ last_cache_id_(-1), last_status_(blink::mojom::AppCacheStatus::APPCACHE_STATUS_OBSOLETE) {} - void CacheSelected(int32_t host_id, - blink::mojom::AppCacheInfoPtr info) override { - last_host_id_ = host_id; + void CacheSelected(blink::mojom::AppCacheInfoPtr info) override { + last_host_id_ = bindings_.dispatch_context(); last_cache_id_ = info->cache_id; last_status_ = info->status; } - void EventRaised(const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheEventID event_id) override {} + void EventRaised(blink::mojom::AppCacheEventID event_id) override {} void ErrorEventRaised( - const std::vector<int32_t>& host_ids, blink::mojom::AppCacheErrorDetailsPtr details) override {} - void ProgressEventRaised(const std::vector<int32_t>& host_ids, - const GURL& url, + void ProgressEventRaised(const GURL& url, int32_t num_total, int32_t num_complete) override {} - void LogMessage(int32_t host_id, - blink::mojom::ConsoleMessageLevel log_level, + void LogMessage(blink::mojom::ConsoleMessageLevel log_level, const std::string& message) override {} void SetSubresourceFactory( - int32_t host_id, network::mojom::URLLoaderFactoryPtr url_loader_factory) override {} + blink::mojom::AppCacheFrontendPtr Bind(int32_t host_id) { + blink::mojom::AppCacheFrontendPtr result; + bindings_.AddBinding(this, mojo::MakeRequest(&result), host_id); + return result; + } + int32_t last_host_id_; int64_t last_cache_id_; blink::mojom::AppCacheStatus last_status_; + mojo::BindingSet<blink::mojom::AppCacheFrontend, int32_t> bindings_; }; -} // namespace anon +} // namespace namespace content { class TestUpdateObserver : public AppCacheGroup::UpdateObserver { public: - TestUpdateObserver() : update_completed_(false), group_has_cache_(false) { - } + TestUpdateObserver() : update_completed_(false), group_has_cache_(false) {} void OnUpdateComplete(AppCacheGroup* group) override { update_completed_ = true; group_has_cache_ = group->HasCache(); } - virtual void OnContentBlocked(AppCacheGroup* group) { - } + virtual void OnContentBlocked(AppCacheGroup* group) {} bool update_completed_; bool group_has_cache_; @@ -82,12 +82,12 @@ class TestAppCacheHost : public AppCacheHost { public: TestAppCacheHost(int host_id, - blink::mojom::AppCacheFrontend* frontend, + TestAppCacheFrontend* frontend, AppCacheServiceImpl* service) : AppCacheHost(host_id, /*process_id=*/456, /*render_frame_id=*/789, - frontend, + frontend->Bind(host_id), service), update_completed_(false) {} @@ -159,9 +159,9 @@ group->RemoveCache(cache5.get()); EXPECT_FALSE(cache5->owning_group()); EXPECT_EQ(cache4.get(), group->newest_complete_cache()); // newest unchanged - group->RemoveCache(cache4.get()); // newest removed + group->RemoveCache(cache4.get()); // newest removed EXPECT_FALSE(cache4->owning_group()); - EXPECT_FALSE(group->newest_complete_cache()); // no more newest cache + EXPECT_FALSE(group->newest_complete_cache()); // no more newest cache // Can remove newest cache if there are older caches. group->AddCache(cache1.get()); @@ -180,9 +180,9 @@ new AppCacheGroup(service.storage(), GURL("http://foo.com"), 111); AppCacheHost host1(/*host_id=*/1, /*process_id=*/1, /*render_frame_id=*/1, - &frontend, &service); + frontend.Bind(/*host_id=*/1), &service); AppCacheHost host2(/*host_id=*/2, /*process_id=*/2, /*render_frame_id=*/2, - &frontend, &service); + frontend.Bind(/*host_id=*/2), &service); base::Time now = base::Time::Now(); @@ -193,12 +193,14 @@ EXPECT_EQ(cache1, group->newest_complete_cache()); host1.AssociateCompleteCache(cache1); + base::RunLoop().RunUntilIdle(); EXPECT_EQ(frontend.last_host_id_, host1.host_id()); EXPECT_EQ(frontend.last_cache_id_, cache1->cache_id()); EXPECT_EQ(frontend.last_status_, blink::mojom::AppCacheStatus::APPCACHE_STATUS_IDLE); host2.AssociateCompleteCache(cache1); + base::RunLoop().RunUntilIdle(); EXPECT_EQ(frontend.last_host_id_, host2.host_id()); EXPECT_EQ(frontend.last_cache_id_, cache1->cache_id()); EXPECT_EQ(frontend.last_status_, @@ -213,6 +215,7 @@ // Unassociate all hosts from older cache. host1.AssociateNoCache(GURL()); host2.AssociateNoCache(GURL()); + base::RunLoop().RunUntilIdle(); EXPECT_EQ(frontend.last_host_id_, host2.host_id()); EXPECT_EQ(frontend.last_cache_id_, blink::mojom::kAppCacheNoCacheId); EXPECT_EQ(frontend.last_status_,
diff --git a/content/browser/appcache/appcache_host.cc b/content/browser/appcache/appcache_host.cc index e44d85e..4d058e4 100644 --- a/content/browser/appcache/appcache_host.cc +++ b/content/browser/appcache/appcache_host.cc
@@ -61,7 +61,7 @@ AppCacheHost::AppCacheHost(int host_id, int process_id, int render_frame_id, - blink::mojom::AppCacheFrontend* frontend, + blink::mojom::AppCacheFrontendPtr frontend, AppCacheServiceImpl* service) : host_id_(host_id), process_id_(process_id), @@ -72,7 +72,8 @@ pending_selected_cache_id_(blink::mojom::kAppCacheNoCacheId), was_select_cache_called_(false), is_cache_selection_enabled_(true), - frontend_(frontend), + frontend_ptr_(std::move(frontend)), + frontend_(frontend_ptr_.get()), render_frame_id_(render_frame_id), service_(service), storage_(service->storage()), @@ -137,8 +138,7 @@ DCHECK(pending_start_update_callback_.is_null() && pending_swap_cache_callback_.is_null() && - pending_get_status_callback_.is_null() && - !is_selection_pending()); + pending_get_status_callback_.is_null() && !is_selection_pending()); was_select_cache_called_ = true; if (!is_cache_selection_enabled_) { @@ -178,18 +178,14 @@ // continue whether it was set or not. AppCachePolicy* policy = service()->appcache_policy(); - if (policy && - !policy->CanCreateAppCache(manifest_url, first_party_url_)) { + if (policy && !policy->CanCreateAppCache(manifest_url, first_party_url_)) { FinishCacheSelection(nullptr, nullptr, mojo::ReportBadMessageCallback()); - std::vector<int> host_ids(1, host_id_); - frontend_->EventRaised( - host_ids, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); - frontend_->ErrorEventRaised( - host_ids, - blink::mojom::AppCacheErrorDetails::New( - "Cache creation was blocked by the content policy", - blink::mojom::AppCacheErrorReason::APPCACHE_POLICY_ERROR, GURL(), - 0, false /*is_cross_origin*/)); + frontend()->EventRaised( + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + frontend()->ErrorEventRaised(blink::mojom::AppCacheErrorDetails::New( + "Cache creation was blocked by the content policy", + blink::mojom::AppCacheErrorReason::APPCACHE_POLICY_ERROR, GURL(), 0, + false /*is_cross_origin*/)); OnContentBlocked(manifest_url); return; } @@ -214,8 +210,7 @@ DCHECK(pending_start_update_callback_.is_null() && pending_swap_cache_callback_.is_null() && - pending_get_status_callback_.is_null() && - !is_selection_pending()); + pending_get_status_callback_.is_null() && !is_selection_pending()); was_select_cache_called_ = true; if (appcache_id != blink::mojom::kAppCacheNoCacheId) { @@ -475,8 +470,8 @@ AppCacheGroup* owning_group = cache->owning_group(); const char* kFormatString = "Document was loaded from Application Cache with manifest %s"; - frontend_->LogMessage( - host_id_, blink::mojom::ConsoleMessageLevel::kInfo, + frontend()->LogMessage( + blink::mojom::ConsoleMessageLevel::kInfo, base::StringPrintf(kFormatString, owning_group->manifest_url().spec().c_str())); AssociateCompleteCache(cache); @@ -493,11 +488,12 @@ DCHECK(!group->is_obsolete()); DCHECK(new_master_entry_url_.is_valid()); DCHECK_EQ(group->manifest_url(), preferred_manifest_url_); - const char* kFormatString = group->HasCache() ? - "Adding master entry to Application Cache with manifest %s" : - "Creating Application Cache with manifest %s"; - frontend_->LogMessage( - host_id_, blink::mojom::ConsoleMessageLevel::kInfo, + const char* kFormatString = + group->HasCache() + ? "Adding master entry to Application Cache with manifest %s" + : "Creating Application Cache with manifest %s"; + frontend()->LogMessage( + blink::mojom::ConsoleMessageLevel::kInfo, base::StringPrintf(kFormatString, group->manifest_url().spec().c_str())); // The UpdateJob may produce one for us later. @@ -557,7 +553,7 @@ // This ensures that they can be served out of the AppCache. MaybePassSubresourceFactory(); OnAppCacheAccessed(info->manifest_url, false); - frontend_->CacheSelected(host_id_, std::move(info)); + frontend()->CacheSelected(std::move(info)); } } @@ -619,7 +615,7 @@ AppCacheSubresourceURLFactory::CreateURLLoaderFactory(GetWeakPtr(), &factory_ptr); - frontend_->SetSubresourceFactory(host_id(), std::move(factory_ptr)); + frontend()->SetSubresourceFactory(std::move(factory_ptr)); } void AppCacheHost::SetAppCacheSubresourceFactory( @@ -665,7 +661,7 @@ MaybePassSubresourceFactory(); OnAppCacheAccessed(info->manifest_url, false); - frontend_->CacheSelected(host_id_, std::move(info)); + frontend()->CacheSelected(std::move(info)); } void AppCacheHost::OnContentBlocked(const GURL& manifest_url) {
diff --git a/content/browser/appcache/appcache_host.h b/content/browser/appcache/appcache_host.h index 2dbdff7..8653c57 100644 --- a/content/browser/appcache/appcache_host.h +++ b/content/browser/appcache/appcache_host.h
@@ -29,12 +29,6 @@ #include "url/gurl.h" #include "url/origin.h" -namespace blink { -namespace mojom { -class AppCacheFrontend; -} // namespace mojom -} // namespace blink - namespace net { class URLRequest; } // namespace net @@ -79,7 +73,7 @@ AppCacheHost(int host_id, int process_id, int render_frame_id, - blink::mojom::AppCacheFrontend* frontend, + blink::mojom::AppCacheFrontendPtr frontend, AppCacheServiceImpl* service); ~AppCacheHost() override; @@ -109,9 +103,7 @@ // spawning host context was never identified. const AppCacheHost* GetSpawningHost() const; - const GURL& preferred_manifest_url() const { - return preferred_manifest_url_; - } + const GURL& preferred_manifest_url() const { return preferred_manifest_url_; } void set_preferred_manifest_url(const GURL& url) { preferred_manifest_url_ = url; } @@ -164,9 +156,7 @@ // Used by the update job to keep track of which hosts are associated // with which pending master entries. - const GURL& pending_master_entry_url() const { - return new_master_entry_url_; - } + const GURL& pending_master_entry_url() const { return new_master_entry_url_; } int host_id() const { return host_id_; } @@ -185,15 +175,20 @@ blink::mojom::AppCacheFrontend* frontend() const { return frontend_; } // PlzNavigate: - // The AppCacheHost instance is created with a dummy AppCacheFrontend + // The AppCacheHost instance is created with a null AppCacheFrontend // pointer when the navigation starts. We need to switch it to the // actual frontend when the navigation commits. - void set_frontend(blink::mojom::AppCacheFrontend* frontend, + void set_frontend(blink::mojom::AppCacheFrontendPtr frontend, int render_frame_id) { - frontend_ = frontend; + frontend_ptr_ = std::move(frontend); + frontend_ = frontend_ptr_.get(); render_frame_id_ = render_frame_id; } + void set_frontend_for_testing(blink::mojom::AppCacheFrontend* frontend) { + frontend_ = frontend; + } + AppCache* associated_cache() const { return associated_cache_.get(); } void enable_cache_selection(bool enable) { @@ -340,7 +335,8 @@ // A new master entry to be added to the cache, may be empty. GURL new_master_entry_url_; - // The frontend proxy to deliver notifications to the child process. + // The frontend to deliver notifications to the child process. + blink::mojom::AppCacheFrontendPtr frontend_ptr_; blink::mojom::AppCacheFrontend* frontend_; int render_frame_id_;
diff --git a/content/browser/appcache/appcache_host_unittest.cc b/content/browser/appcache/appcache_host_unittest.cc index 4d7db79..fc13cb4 100644 --- a/content/browser/appcache/appcache_host_unittest.cc +++ b/content/browser/appcache/appcache_host_unittest.cc
@@ -61,45 +61,36 @@ public: MockFrontend(WebContents* web_contents) : WebContentsObserver(web_contents), - last_host_id_(-222), last_cache_id_(-222), last_status_(blink::mojom::AppCacheStatus::APPCACHE_STATUS_OBSOLETE), last_event_id_( blink::mojom::AppCacheEventID::APPCACHE_OBSOLETE_EVENT), content_blocked_(false) {} - void CacheSelected(int32_t host_id, - blink::mojom::AppCacheInfoPtr info) override { - last_host_id_ = host_id; + void CacheSelected(blink::mojom::AppCacheInfoPtr info) override { last_cache_id_ = info->cache_id; last_status_ = info->status; } - - void EventRaised(const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheEventID event_id) override { + void EventRaised(blink::mojom::AppCacheEventID event_id) override { last_event_id_ = event_id; } void ErrorEventRaised( - const std::vector<int32_t>& host_ids, blink::mojom::AppCacheErrorDetailsPtr details) override { last_event_id_ = blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT; } - void ProgressEventRaised(const std::vector<int32_t>& host_ids, - const GURL& url, + void ProgressEventRaised(const GURL& url, int32_t num_total, int32_t num_complete) override { last_event_id_ = blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT; } - void LogMessage(int32_t host_id, - blink::mojom::ConsoleMessageLevel log_level, + void LogMessage(blink::mojom::ConsoleMessageLevel log_level, const std::string& message) override {} void SetSubresourceFactory( - int32_t host_id, network::mojom::URLLoaderFactoryPtr url_loader_factory) override {} // WebContentsObserver: @@ -110,7 +101,6 @@ content_blocked_ = true; } - int32_t last_host_id_; int64_t last_cache_id_; blink::mojom::AppCacheStatus last_status_; blink::mojom::AppCacheEventID last_event_id_; @@ -150,9 +140,7 @@ int GetInUseCount(const url::Origin& origin) { return inuse_[origin]; } - void reset() { - inuse_.clear(); - } + void reset() { inuse_.clear(); } // Map from origin to count of inuse notifications. std::map<url::Origin, int> inuse_; @@ -192,11 +180,11 @@ TEST_F(AppCacheHostTest, Basic) { // Construct a host and test what state it appears to be in. AppCacheHost host(kHostIdForTest, kProcessIdForTest, kRenderFrameIdForTest, - &mock_frontend_, &service_); + nullptr, &service_); + host.set_frontend_for_testing(&mock_frontend_); EXPECT_EQ(kHostIdForTest, host.host_id()); EXPECT_EQ(kProcessIdForTest, host.process_id()); EXPECT_EQ(&service_, host.service()); - EXPECT_EQ(&mock_frontend_, host.frontend()); EXPECT_EQ(nullptr, host.associated_cache()); EXPECT_FALSE(host.is_selection_pending()); @@ -225,7 +213,6 @@ // Reset our mock frontend mock_frontend_.last_cache_id_ = -333; - mock_frontend_.last_host_id_ = -333; mock_frontend_.last_status_ = blink::mojom::AppCacheStatus::APPCACHE_STATUS_OBSOLETE; @@ -233,13 +220,13 @@ const url::Origin kOrigin(url::Origin::Create(kDocAndOriginUrl)); { AppCacheHost host(kHostIdForTest, kProcessIdForTest, kRenderFrameIdForTest, - &mock_frontend_, &service_); + nullptr, &service_); + host.set_frontend_for_testing(&mock_frontend_); host.SelectCache(kDocAndOriginUrl, blink::mojom::kAppCacheNoCacheId, GURL()); EXPECT_EQ(1, mock_quota_proxy->GetInUseCount(kOrigin)); // We should have received an OnCacheSelected msg - EXPECT_EQ(kHostIdForTest, mock_frontend_.last_host_id_); EXPECT_EQ(blink::mojom::kAppCacheNoCacheId, mock_frontend_.last_cache_id_); EXPECT_EQ(blink::mojom::AppCacheStatus::APPCACHE_STATUS_UNCACHED, mock_frontend_.last_status_); @@ -247,7 +234,6 @@ // Otherwise, see that it respond as if there is no cache selected. EXPECT_EQ(kHostIdForTest, host.host_id()); EXPECT_EQ(&service_, host.service()); - EXPECT_EQ(&mock_frontend_, host.frontend()); EXPECT_EQ(nullptr, host.associated_cache()); EXPECT_FALSE(host.is_selection_pending()); EXPECT_TRUE(host.preferred_manifest_url().is_empty()); @@ -259,7 +245,6 @@ TEST_F(AppCacheHostTest, ForeignEntry) { // Reset our mock frontend mock_frontend_.last_cache_id_ = -333; - mock_frontend_.last_host_id_ = -333; mock_frontend_.last_status_ = blink::mojom::AppCacheStatus::APPCACHE_STATUS_OBSOLETE; @@ -270,11 +255,11 @@ cache->AddEntry(kDocumentURL, AppCacheEntry(AppCacheEntry::EXPLICIT)); AppCacheHost host(kHostIdForTest, kProcessIdForTest, kRenderFrameIdForTest, - &mock_frontend_, &service_); + nullptr, &service_); + host.set_frontend_for_testing(&mock_frontend_); host.MarkAsForeignEntry(kDocumentURL, kCacheId); // We should have received an OnCacheSelected msg for kAppCacheNoCacheId. - EXPECT_EQ(kHostIdForTest, mock_frontend_.last_host_id_); EXPECT_EQ(blink::mojom::kAppCacheNoCacheId, mock_frontend_.last_cache_id_); EXPECT_EQ(blink::mojom::AppCacheStatus::APPCACHE_STATUS_UNCACHED, mock_frontend_.last_status_); @@ -282,7 +267,6 @@ // See that it respond as if there is no cache selected. EXPECT_EQ(kHostIdForTest, host.host_id()); EXPECT_EQ(&service_, host.service()); - EXPECT_EQ(&mock_frontend_, host.frontend()); EXPECT_EQ(nullptr, host.associated_cache()); EXPECT_FALSE(host.is_selection_pending()); @@ -293,7 +277,6 @@ TEST_F(AppCacheHostTest, ForeignFallbackEntry) { // Reset our mock frontend mock_frontend_.last_cache_id_ = -333; - mock_frontend_.last_host_id_ = -333; mock_frontend_.last_status_ = blink::mojom::AppCacheStatus::APPCACHE_STATUS_OBSOLETE; @@ -305,12 +288,12 @@ cache->AddEntry(kFallbackURL, AppCacheEntry(AppCacheEntry::FALLBACK)); AppCacheHost host(kHostIdForTest, kProcessIdForTest, kRenderFrameIdForTest, - &mock_frontend_, &service_); + nullptr, &service_); + host.set_frontend_for_testing(&mock_frontend_); host.NotifyMainResourceIsNamespaceEntry(kFallbackURL); host.MarkAsForeignEntry(GURL("http://origin/missing_document"), kCacheId); // We should have received an OnCacheSelected msg for kAppCacheNoCacheId. - EXPECT_EQ(kHostIdForTest, mock_frontend_.last_host_id_); EXPECT_EQ(blink::mojom::kAppCacheNoCacheId, mock_frontend_.last_cache_id_); EXPECT_EQ(blink::mojom::AppCacheStatus::APPCACHE_STATUS_UNCACHED, mock_frontend_.last_status_); @@ -322,12 +305,12 @@ TEST_F(AppCacheHostTest, FailedCacheLoad) { // Reset our mock frontend mock_frontend_.last_cache_id_ = -333; - mock_frontend_.last_host_id_ = -333; mock_frontend_.last_status_ = blink::mojom::AppCacheStatus::APPCACHE_STATUS_OBSOLETE; AppCacheHost host(kHostIdForTest, kProcessIdForTest, kRenderFrameIdForTest, - &mock_frontend_, &service_); + nullptr, &service_); + host.set_frontend_for_testing(&mock_frontend_); EXPECT_FALSE(host.is_selection_pending()); const int kMockCacheId = 333; @@ -348,7 +331,6 @@ // Cache selection should have finished EXPECT_FALSE(host.is_selection_pending()); - EXPECT_EQ(kHostIdForTest, mock_frontend_.last_host_id_); EXPECT_EQ(blink::mojom::kAppCacheNoCacheId, mock_frontend_.last_cache_id_); EXPECT_EQ(blink::mojom::AppCacheStatus::APPCACHE_STATUS_UNCACHED, mock_frontend_.last_status_); @@ -360,7 +342,8 @@ TEST_F(AppCacheHostTest, FailedGroupLoad) { AppCacheHost host(kHostIdForTest, kProcessIdForTest, kRenderFrameIdForTest, - &mock_frontend_, &service_); + nullptr, &service_); + host.set_frontend_for_testing(&mock_frontend_); const GURL kMockManifestUrl("http://foo.bar/baz"); @@ -380,7 +363,6 @@ // Cache selection should have finished EXPECT_FALSE(host.is_selection_pending()); - EXPECT_EQ(kHostIdForTest, mock_frontend_.last_host_id_); EXPECT_EQ(blink::mojom::kAppCacheNoCacheId, mock_frontend_.last_cache_id_); EXPECT_EQ(blink::mojom::AppCacheStatus::APPCACHE_STATUS_UNCACHED, mock_frontend_.last_status_); @@ -392,7 +374,8 @@ TEST_F(AppCacheHostTest, SetSwappableCache) { AppCacheHost host(kHostIdForTest, kProcessIdForTest, kRenderFrameIdForTest, - &mock_frontend_, &service_); + nullptr, &service_); + host.set_frontend_for_testing(&mock_frontend_); host.SetSwappableCache(nullptr); EXPECT_FALSE(host.swappable_cache_.get()); @@ -409,14 +392,14 @@ host.SetSwappableCache(group1.get()); EXPECT_EQ(cache1, host.swappable_cache_.get()); - mock_frontend_.last_host_id_ = -222; // to verify we received OnCacheSelected + mock_frontend_.last_cache_id_ = + -222; // to verify we received OnCacheSelected host.AssociateCompleteCache(cache1.get()); EXPECT_FALSE(host.swappable_cache_.get()); // was same as associated cache EXPECT_EQ(blink::mojom::AppCacheStatus::APPCACHE_STATUS_IDLE, host.GetStatusSync()); // verify OnCacheSelected was called - EXPECT_EQ(host.host_id(), mock_frontend_.last_host_id_); EXPECT_EQ(cache1->cache_id(), mock_frontend_.last_cache_id_); EXPECT_EQ(blink::mojom::AppCacheStatus::APPCACHE_STATUS_IDLE, mock_frontend_.last_status_); @@ -484,7 +467,6 @@ // Reset our mock frontend mock_frontend_.last_cache_id_ = -333; - mock_frontend_.last_host_id_ = -333; mock_frontend_.last_status_ = blink::mojom::AppCacheStatus::APPCACHE_STATUS_OBSOLETE; mock_frontend_.last_event_id_ = @@ -497,7 +479,8 @@ const GURL kManifestUrl(GURL("http://whatever/cache.manifest")); { AppCacheHost host(kHostIdForTest, kProcessIdForTest, kRenderFrameIdForTest, - &mock_frontend_, &service_); + nullptr, &service_); + host.set_frontend_for_testing(&mock_frontend_); host.SetFirstPartyUrlForTesting(kDocAndOriginUrl); host.SelectCache(kDocAndOriginUrl, blink::mojom::kAppCacheNoCacheId, kManifestUrl); @@ -505,7 +488,6 @@ // MockAppCacheService::LoadOrCreateGroup is asynchronous, so we shouldn't // have received an OnCacheSelected msg yet. - EXPECT_EQ(-333, mock_frontend_.last_host_id_); EXPECT_EQ(-333, mock_frontend_.last_cache_id_); EXPECT_EQ(blink::mojom::AppCacheStatus::APPCACHE_STATUS_OBSOLETE, mock_frontend_.last_status_); @@ -534,7 +516,6 @@ // Reset our mock frontend mock_frontend_.last_cache_id_ = -333; - mock_frontend_.last_host_id_ = -333; mock_frontend_.last_status_ = blink::mojom::AppCacheStatus::APPCACHE_STATUS_OBSOLETE; mock_frontend_.last_event_id_ = @@ -547,14 +528,14 @@ const GURL kManifestUrl(GURL("http://whatever/cache.manifest")); { AppCacheHost host(kHostIdForTest, kProcessIdForTest, kRenderFrameIdForTest, - &mock_frontend_, &service_); + nullptr, &service_); + host.set_frontend_for_testing(&mock_frontend_); host.SetFirstPartyUrlForTesting(kDocAndOriginUrl); host.SelectCache(kDocAndOriginUrl, blink::mojom::kAppCacheNoCacheId, kManifestUrl); EXPECT_EQ(1, mock_quota_proxy->GetInUseCount(kOrigin)); // We should have received an OnCacheSelected msg - EXPECT_EQ(kHostIdForTest, mock_frontend_.last_host_id_); EXPECT_EQ(blink::mojom::kAppCacheNoCacheId, mock_frontend_.last_cache_id_); EXPECT_EQ(blink::mojom::AppCacheStatus::APPCACHE_STATUS_UNCACHED, mock_frontend_.last_status_); @@ -566,7 +547,6 @@ // Otherwise, see that it respond as if there is no cache selected. EXPECT_EQ(kHostIdForTest, host.host_id()); EXPECT_EQ(&service_, host.service()); - EXPECT_EQ(&mock_frontend_, host.frontend()); EXPECT_EQ(nullptr, host.associated_cache()); EXPECT_FALSE(host.is_selection_pending()); EXPECT_TRUE(host.preferred_manifest_url().is_empty()); @@ -582,7 +562,8 @@ TEST_F(AppCacheHostTest, SelectCacheTwice) { const GURL kDocAndOriginUrl(GURL("http://whatever/").GetOrigin()); AppCacheHost host(kHostIdForTest, kProcessIdForTest, kRenderFrameIdForTest, - &mock_frontend_, &service_); + nullptr, &service_); + host.set_frontend_for_testing(&mock_frontend_); blink::mojom::AppCacheHostPtr host_ptr; host.BindRequest(mojo::MakeRequest(&host_ptr)); @@ -626,7 +607,8 @@ const GURL kDocumentURL("http://origin/document"); scoped_refptr<AppCache> cache = new AppCache(service_.storage(), kCacheId); AppCacheHost host(kHostIdForTest, kProcessIdForTest, kRenderFrameIdForTest, - &mock_frontend_, &service_); + nullptr, &service_); + host.set_frontend_for_testing(&mock_frontend_); blink::mojom::AppCacheHostPtr host_ptr; host.BindRequest(mojo::MakeRequest(&host_ptr));
diff --git a/content/browser/appcache/appcache_navigation_handle_core.cc b/content/browser/appcache/appcache_navigation_handle_core.cc index 615d8a7..1e3fb2754 100644 --- a/content/browser/appcache/appcache_navigation_handle_core.cc +++ b/content/browser/appcache/appcache_navigation_handle_core.cc
@@ -55,7 +55,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(precreated_host_.get() == nullptr); precreated_host_ = std::make_unique<AppCacheHost>( - appcache_host_id_, process_id_, MSG_ROUTING_NONE, this, + appcache_host_id_, process_id_, MSG_ROUTING_NONE, nullptr, GetAppCacheService()); DCHECK(g_appcache_handle_map.Get().find(appcache_host_id_) == @@ -88,48 +88,4 @@ precreated_host_->SetProcessId(process_id); } -void AppCacheNavigationHandleCore::CacheSelected( - int host_id, - blink::mojom::AppCacheInfoPtr info) { - DCHECK(false); -} - -void AppCacheNavigationHandleCore::EventRaised( - const std::vector<int>& host_ids, - blink::mojom::AppCacheEventID event_id) { - // Should never be called. - DCHECK(false); -} - -void AppCacheNavigationHandleCore::ProgressEventRaised( - const std::vector<int>& host_ids, - const GURL& url, - int num_total, - int num_complete) { - // Should never be called. - DCHECK(false); -} - -void AppCacheNavigationHandleCore::ErrorEventRaised( - const std::vector<int>& host_ids, - blink::mojom::AppCacheErrorDetailsPtr details) { - // Should never be called. - DCHECK(false); -} - -void AppCacheNavigationHandleCore::LogMessage( - int host_id, - blink::mojom::ConsoleMessageLevel log_level, - const std::string& message) { - // Should never be called. - DCHECK(false); -} - -void AppCacheNavigationHandleCore::SetSubresourceFactory( - int host_id, - network::mojom::URLLoaderFactoryPtr url_loader_factory) { - // Should never be called. - DCHECK(false); -} - } // namespace content
diff --git a/content/browser/appcache/appcache_navigation_handle_core.h b/content/browser/appcache/appcache_navigation_handle_core.h index 695cc5ea..565b794 100644 --- a/content/browser/appcache/appcache_navigation_handle_core.h +++ b/content/browser/appcache/appcache_navigation_handle_core.h
@@ -12,7 +12,6 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" -#include "third_party/blink/public/mojom/appcache/appcache.mojom.h" #include "third_party/blink/public/mojom/appcache/appcache_info.mojom.h" #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" @@ -30,12 +29,12 @@ // pendant of AppCacheNavigationHandle. See the // AppCacheNavigationHandle header for more details about the lifetime of // both classes. -class AppCacheNavigationHandleCore : public blink::mojom::AppCacheFrontend { +class AppCacheNavigationHandleCore { public: AppCacheNavigationHandleCore(ChromeAppCacheService* appcache_service, int appcache_host_id, int process_id); - ~AppCacheNavigationHandleCore() override; + ~AppCacheNavigationHandleCore(); // Returns the raw AppCacheHost pointer. Ownership remains with this class. AppCacheHost* host() { return precreated_host_.get(); } @@ -55,27 +54,6 @@ // |process_id| until ReadyToCommit time). void SetProcessId(int process_id); - protected: - // AppCacheFrontend methods - // We don't expect calls on the AppCacheFrontend methods while the - // AppCacheHost is not registered with the AppCacheBackend. - void CacheSelected(int32_t host_id, - blink::mojom::AppCacheInfoPtr info) override; - void EventRaised(const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheEventID event_id) override; - void ProgressEventRaised(const std::vector<int32_t>& host_ids, - const GURL& url, - int32_t num_total, - int32_t num_complete) override; - void ErrorEventRaised(const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheErrorDetailsPtr details) override; - void LogMessage(int32_t host_id, - blink::mojom::ConsoleMessageLevel log_level, - const std::string& message) override; - void SetSubresourceFactory( - int32_t host_id, - network::mojom::URLLoaderFactoryPtr url_loader_factory) override; - private: std::unique_ptr<AppCacheHost> precreated_host_; scoped_refptr<ChromeAppCacheService> appcache_service_;
diff --git a/content/browser/appcache/appcache_request_handler_unittest.cc b/content/browser/appcache/appcache_request_handler_unittest.cc index 07ff7a9a..422b3bd 100644 --- a/content/browser/appcache/appcache_request_handler_unittest.cc +++ b/content/browser/appcache/appcache_request_handler_unittest.cc
@@ -71,32 +71,6 @@ class AppCacheRequestHandlerTest : public testing::TestWithParam<RequestHandlerType> { public: - class MockFrontend : public blink::mojom::AppCacheFrontend { - public: - void CacheSelected(int32_t host_id, - blink::mojom::AppCacheInfoPtr info) override {} - - void EventRaised(const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheEventID event_id) override {} - - void ErrorEventRaised( - const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheErrorDetailsPtr details) override {} - - void ProgressEventRaised(const std::vector<int32_t>& host_ids, - const GURL& url, - int32_t num_total, - int32_t num_complete) override {} - - void LogMessage(int32_t host_id, - blink::mojom::ConsoleMessageLevel log_level, - const std::string& message) override {} - - void SetSubresourceFactory( - int32_t host_id, - network::mojom::URLLoaderFactoryPtr url_loader_factory) override {} - }; - // Helper callback to run a test on our io_thread. The io_thread is spun up // once and reused for all tests. template <class Method> @@ -248,14 +222,14 @@ mock_service_->set_request_context(empty_context_.get()); mock_policy_.reset(new MockAppCachePolicy); mock_service_->set_appcache_policy(mock_policy_.get()); - mock_frontend_.reset(new MockFrontend); backend_impl_ = std::make_unique<AppCacheBackendImpl>(mock_service_.get(), kMockProcessId); - backend_impl_->set_frontend_for_testing(mock_frontend_.get()); const int kHostId = 1; const int kRenderFrameId = 2; - backend_impl_->RegisterHost(mojo::MakeRequest(&host_ptr_), kHostId, - kRenderFrameId); + blink::mojom::AppCacheFrontendPtr frontend; + mojo::MakeRequest(&frontend); + backend_impl_->RegisterHost(mojo::MakeRequest(&host_ptr_), + std::move(frontend), kHostId, kRenderFrameId); host_ = backend_impl_->GetHost(kHostId); job_factory_.reset(new MockURLRequestJobFactory()); empty_context_->set_job_factory(job_factory_.get()); @@ -271,7 +245,6 @@ request_ = nullptr; url_request_.reset(); backend_impl_.reset(); - mock_frontend_.reset(); mock_service_.reset(); mock_policy_.reset(); job_factory_.reset(); @@ -382,9 +355,8 @@ EXPECT_TRUE(handler_.get()); mock_storage()->SimulateFindMainResource( - AppCacheEntry(AppCacheEntry::EXPLICIT, 1), - GURL(), AppCacheEntry(), - 1, 2, GURL("http://blah/manifest/")); + AppCacheEntry(AppCacheEntry::EXPLICIT, 1), GURL(), AppCacheEntry(), 1, + 2, GURL("http://blah/manifest/")); SetAppCacheJob(handler_->MaybeLoadResource(nullptr)); EXPECT_TRUE(job()); @@ -408,8 +380,7 @@ SetAppCacheJob(handler_->MaybeLoadFallbackForResponse(nullptr)); EXPECT_FALSE(job()); - EXPECT_EQ(GURL("http://blah/manifest/"), - host_->preferred_manifest_url()); + EXPECT_EQ(GURL("http://blah/manifest/"), host_->preferred_manifest_url()); TestFinished(); } @@ -426,10 +397,9 @@ EXPECT_TRUE(handler_.get()); mock_storage()->SimulateFindMainResource( - AppCacheEntry(), - GURL("http://blah/fallbackurl"), - AppCacheEntry(AppCacheEntry::EXPLICIT, 1), - 1, 2, GURL("http://blah/manifest/")); + AppCacheEntry(), GURL("http://blah/fallbackurl"), + AppCacheEntry(AppCacheEntry::EXPLICIT, 1), 1, 2, + GURL("http://blah/manifest/")); SetAppCacheJob(handler_->MaybeLoadResource(nullptr)); EXPECT_TRUE(job()); @@ -504,8 +474,7 @@ EXPECT_TRUE(host_->main_resource_was_namespace_entry_); EXPECT_EQ(GURL("http://blah/fallbackurl"), host_->namespace_entry_url_); - EXPECT_EQ(GURL("http://blah/manifest/"), - host_->preferred_manifest_url()); + EXPECT_EQ(GURL("http://blah/manifest/"), host_->preferred_manifest_url()); TestFinished(); } @@ -522,10 +491,9 @@ EXPECT_TRUE(handler_.get()); mock_storage()->SimulateFindMainResource( - AppCacheEntry(), - GURL("http://blah/fallbackurl"), - AppCacheEntry(AppCacheEntry::EXPLICIT, 1), - 1, 2, GURL("http://blah/manifest/")); + AppCacheEntry(), GURL("http://blah/fallbackurl"), + AppCacheEntry(AppCacheEntry::EXPLICIT, 1), 1, 2, + GURL("http://blah/manifest/")); SetAppCacheJob(handler_->MaybeLoadResource(nullptr)); EXPECT_TRUE(job()); @@ -725,8 +693,8 @@ // retrieval. host_->AssociateCompleteCache(MakeNewCache()); - mock_storage()->SimulateFindSubResource( - AppCacheEntry(), AppCacheEntry(), true); + mock_storage()->SimulateFindSubResource(AppCacheEntry(), AppCacheEntry(), + true); EXPECT_TRUE(CreateRequestAndHandler(GURL("http://blah/"), host_, RESOURCE_TYPE_SUB_RESOURCE)); @@ -809,7 +777,6 @@ EXPECT_TRUE(job()); backend_impl_.reset(); - mock_frontend_.reset(); mock_service_.reset(); mock_policy_.reset(); host_ = nullptr; @@ -888,9 +855,8 @@ mock_policy_->can_load_return_value_ = false; mock_storage()->SimulateFindMainResource( - AppCacheEntry(AppCacheEntry::EXPLICIT, 1), - GURL(), AppCacheEntry(), - 1, 2, GURL("http://blah/manifest/")); + AppCacheEntry(AppCacheEntry::EXPLICIT, 1), GURL(), AppCacheEntry(), 1, + 2, GURL("http://blah/manifest/")); SetAppCacheJob(handler_->MaybeLoadResource(nullptr)); EXPECT_TRUE(job()); @@ -917,12 +883,12 @@ // Test case helpers -------------------------------------------------- AppCache* MakeNewCache() { - AppCache* cache = new AppCache( - mock_storage(), mock_storage()->NewCacheId()); + AppCache* cache = + new AppCache(mock_storage(), mock_storage()->NewCacheId()); cache->set_complete(true); - AppCacheGroup* group = new AppCacheGroup( - mock_storage(), GURL("http://blah/manifest"), - mock_storage()->NewGroupId()); + AppCacheGroup* group = + new AppCacheGroup(mock_storage(), GURL("http://blah/manifest"), + mock_storage()->NewGroupId()); group->AddCache(cache); return cache; } @@ -964,7 +930,6 @@ base::stack<base::OnceClosure> task_stack_; std::unique_ptr<MockAppCacheService> mock_service_; std::unique_ptr<AppCacheBackendImpl> backend_impl_; - std::unique_ptr<MockFrontend> mock_frontend_; std::unique_ptr<MockAppCachePolicy> mock_policy_; AppCacheHost* host_; blink::mojom::AppCacheHostPtr host_ptr_; @@ -1003,8 +968,7 @@ } TEST_P(AppCacheRequestHandlerTest, MainResource_FallbackOverride) { - RunTestOnIOThread( - &AppCacheRequestHandlerTest::MainResource_FallbackOverride); + RunTestOnIOThread(&AppCacheRequestHandlerTest::MainResource_FallbackOverride); } TEST_P(AppCacheRequestHandlerTest, SubResource_Miss_WithNoCacheSelected) { @@ -1032,7 +996,7 @@ TEST_P(AppCacheRequestHandlerTest, SubResource_NoRedirectFallback) { RunTestOnIOThread( - &AppCacheRequestHandlerTest::SubResource_NoRedirectFallback); + &AppCacheRequestHandlerTest::SubResource_NoRedirectFallback); } TEST_P(AppCacheRequestHandlerTest, SubResource_Network) {
diff --git a/content/browser/appcache/appcache_storage_impl_unittest.cc b/content/browser/appcache/appcache_storage_impl_unittest.cc index a3ebc31..1a25f933 100644 --- a/content/browser/appcache/appcache_storage_impl_unittest.cc +++ b/content/browser/appcache/appcache_storage_impl_unittest.cc
@@ -371,9 +371,7 @@ task_stack_.pop(); } - static void SignalEvent(base::WaitableEvent* event) { - event->Signal(); - } + static void SignalEvent(base::WaitableEvent* event) { event->Signal(); } void FlushAllTasks() { FlushTasks(storage()->db_task_runner_.get()); @@ -467,8 +465,8 @@ // Should not have been stored in the database. AppCacheDatabase::GroupRecord record; - EXPECT_FALSE(database()->FindGroup( - delegate()->loaded_group_->group_id(), &record)); + EXPECT_FALSE( + database()->FindGroup(delegate()->loaded_group_->group_id(), &record)); EXPECT_EQ(0, mock_quota_manager_proxy_->notify_storage_accessed_count_); EXPECT_EQ(0, mock_quota_manager_proxy_->notify_storage_modified_count_); @@ -541,8 +539,8 @@ // Setup some preconditions. Create a group and newest cache that // appear to be "unstored". - group_ = new AppCacheGroup( - storage(), kManifestUrl, storage()->NewGroupId()); + group_ = + new AppCacheGroup(storage(), kManifestUrl, storage()->NewGroupId()); cache_ = new AppCache(storage(), storage()->NewCacheId()); cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::EXPLICIT, 1, kDefaultEntrySize)); @@ -597,8 +595,8 @@ kDefaultEntrySize + 100)); // Conduct the test. - storage()->StoreGroupAndNewestCache( - group_.get(), cache2_.get(), delegate()); + storage()->StoreGroupAndNewestCache(group_.get(), cache2_.get(), + delegate()); EXPECT_FALSE(delegate()->stored_group_success_); } @@ -653,8 +651,7 @@ EXPECT_FALSE(delegate()->stored_group_success_); } - void Verify_StoreExistingGroupExistingCache( - base::Time expected_update_time) { + void Verify_StoreExistingGroupExistingCache(base::Time expected_update_time) { EXPECT_TRUE(delegate()->stored_group_success_); EXPECT_EQ(cache_.get(), group_->newest_complete_cache()); @@ -671,7 +668,7 @@ EXPECT_EQ(2U, entry_records.size()); if (entry_records[0].url == kDefaultEntryUrl) entry_records.erase(entry_records.begin()); - EXPECT_EQ(1 , entry_records[0].cache_id); + EXPECT_EQ(1, entry_records[0].cache_id); EXPECT_EQ(kEntryUrl, entry_records[0].url); EXPECT_EQ(AppCacheEntry::MASTER, entry_records[0].flags); EXPECT_EQ(1, entry_records[0].response_id); @@ -696,8 +693,8 @@ // Setup some preconditions. Create a group and newest cache that // appear to be "unstored" and big enough to exceed the 5M limit. const int64_t kTooBig = 10 * 1024 * 1024; // 10M - group_ = new AppCacheGroup( - storage(), kManifestUrl, storage()->NewGroupId()); + group_ = + new AppCacheGroup(storage(), kManifestUrl, storage()->NewGroupId()); cache_ = new AppCache(storage(), storage()->NewCacheId()); cache_->AddEntry(kManifestUrl, AppCacheEntry(AppCacheEntry::MANIFEST, 1, kTooBig)); @@ -781,8 +778,8 @@ EXPECT_TRUE(entry_records.empty()); std::vector<AppCacheDatabase::NamespaceRecord> intercept_records; std::vector<AppCacheDatabase::NamespaceRecord> fallback_records; - database()->FindNamespacesForCache( - 1, &intercept_records, &fallback_records); + database()->FindNamespacesForCache(1, &intercept_records, + &fallback_records); EXPECT_TRUE(fallback_records.empty()); std::vector<AppCacheDatabase::OnlineWhiteListRecord> whitelist_records; database()->FindOnlineWhiteListForCache(1, &whitelist_records); @@ -902,13 +899,9 @@ // BasicFindMainResponse ------------------------------- - void BasicFindMainResponseInDatabase() { - BasicFindMainResponse(true); - } + void BasicFindMainResponseInDatabase() { BasicFindMainResponse(true); } - void BasicFindMainResponseInWorkingSet() { - BasicFindMainResponse(false); - } + void BasicFindMainResponseInWorkingSet() { BasicFindMainResponse(false); } void BasicFindMainResponse(bool drop_from_working_set) { PushNextTask( @@ -936,7 +929,7 @@ // Conduct the test. storage()->FindResponseForMainRequest(kEntryUrl, GURL(), delegate()); - EXPECT_NE(kEntryUrl, delegate()->found_url_); + EXPECT_NE(kEntryUrl, delegate()->found_url_); } void Verify_BasicFindMainResponse() { @@ -970,27 +963,17 @@ MakeCacheAndGroup(kManifestUrl, 2, 1, true); cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::FALLBACK, 1)); cache_->AddEntry(kEntryUrl2, AppCacheEntry(AppCacheEntry::FALLBACK, 2)); - cache_->fallback_namespaces_.push_back( - AppCacheNamespace(APPCACHE_FALLBACK_NAMESPACE, - kFallbackNamespace2, - kEntryUrl2, - false)); - cache_->fallback_namespaces_.push_back( - AppCacheNamespace(APPCACHE_FALLBACK_NAMESPACE, - kFallbackNamespace, - kEntryUrl, - false)); + cache_->fallback_namespaces_.push_back(AppCacheNamespace( + APPCACHE_FALLBACK_NAMESPACE, kFallbackNamespace2, kEntryUrl2, false)); + cache_->fallback_namespaces_.push_back(AppCacheNamespace( + APPCACHE_FALLBACK_NAMESPACE, kFallbackNamespace, kEntryUrl, false)); AppCacheDatabase::CacheRecord cache_record; std::vector<AppCacheDatabase::EntryRecord> entries; std::vector<AppCacheDatabase::NamespaceRecord> intercepts; std::vector<AppCacheDatabase::NamespaceRecord> fallbacks; std::vector<AppCacheDatabase::OnlineWhiteListRecord> whitelists; - cache_->ToDatabaseRecords(group_.get(), - &cache_record, - &entries, - &intercepts, - &fallbacks, - &whitelists); + cache_->ToDatabaseRecords(group_.get(), &cache_record, &entries, + &intercepts, &fallbacks, &whitelists); for (const auto& entry : entries) { // MakeCacheAndGroup has inserted the default entry record already. @@ -1045,23 +1028,17 @@ MakeCacheAndGroup(kManifestUrl, 2, 1, true); cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::INTERCEPT, 1)); cache_->AddEntry(kEntryUrl2, AppCacheEntry(AppCacheEntry::INTERCEPT, 2)); - cache_->intercept_namespaces_.push_back( - AppCacheNamespace(APPCACHE_INTERCEPT_NAMESPACE, kInterceptNamespace2, - kEntryUrl2, false)); - cache_->intercept_namespaces_.push_back( - AppCacheNamespace(APPCACHE_INTERCEPT_NAMESPACE, kInterceptNamespace, - kEntryUrl, false)); + cache_->intercept_namespaces_.push_back(AppCacheNamespace( + APPCACHE_INTERCEPT_NAMESPACE, kInterceptNamespace2, kEntryUrl2, false)); + cache_->intercept_namespaces_.push_back(AppCacheNamespace( + APPCACHE_INTERCEPT_NAMESPACE, kInterceptNamespace, kEntryUrl, false)); AppCacheDatabase::CacheRecord cache_record; std::vector<AppCacheDatabase::EntryRecord> entries; std::vector<AppCacheDatabase::NamespaceRecord> intercepts; std::vector<AppCacheDatabase::NamespaceRecord> fallbacks; std::vector<AppCacheDatabase::OnlineWhiteListRecord> whitelists; - cache_->ToDatabaseRecords(group_.get(), - &cache_record, - &entries, - &intercepts, - &fallbacks, - &whitelists); + cache_->ToDatabaseRecords(group_.get(), &cache_record, &entries, + &intercepts, &fallbacks, &whitelists); for (const auto& entry : entries) { // MakeCacheAndGroup has inserted the default entry record already @@ -1080,8 +1057,8 @@ // Conduct the test. The test url is in both intercept namespaces, // but should match the longer of the two. - storage()->FindResponseForMainRequest( - kInterceptTestUrl, GURL(), delegate()); + storage()->FindResponseForMainRequest(kInterceptTestUrl, GURL(), + delegate()); EXPECT_NE(kInterceptTestUrl, delegate()->found_url_); } @@ -1114,18 +1091,14 @@ cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::INTERCEPT, 1)); cache_->intercept_namespaces_.push_back( AppCacheNamespace(APPCACHE_INTERCEPT_NAMESPACE, - kInterceptPatternNamespace, kEntryUrl, true)); + kInterceptPatternNamespace, kEntryUrl, true)); AppCacheDatabase::CacheRecord cache_record; std::vector<AppCacheDatabase::EntryRecord> entries; std::vector<AppCacheDatabase::NamespaceRecord> intercepts; std::vector<AppCacheDatabase::NamespaceRecord> fallbacks; std::vector<AppCacheDatabase::OnlineWhiteListRecord> whitelists; - cache_->ToDatabaseRecords(group_.get(), - &cache_record, - &entries, - &intercepts, - &fallbacks, - &whitelists); + cache_->ToDatabaseRecords(group_.get(), &cache_record, &entries, + &intercepts, &fallbacks, &whitelists); for (const auto& entry : entries) { // MakeCacheAndGroup has inserted the default entry record already @@ -1145,8 +1118,8 @@ PushNextTask(base::BindOnce( &AppCacheStorageImplTest::Verify_FindInterceptPatternMatchNegative, base::Unretained(this))); - storage()->FindResponseForMainRequest( - kInterceptPatternTestNegativeUrl, GURL(), delegate()); + storage()->FindResponseForMainRequest(kInterceptPatternTestNegativeUrl, + GURL(), delegate()); EXPECT_EQ(GURL(), delegate()->found_url_); // Is always async. } @@ -1166,8 +1139,8 @@ PushNextTask(base::BindOnce( &AppCacheStorageImplTest::Verify_FindInterceptPatternMatchPositive, base::Unretained(this))); - storage()->FindResponseForMainRequest( - kInterceptPatternTestPositiveUrl, GURL(), delegate()); + storage()->FindResponseForMainRequest(kInterceptPatternTestPositiveUrl, + GURL(), delegate()); } void Verify_FindInterceptPatternMatchPositive() { @@ -1184,9 +1157,7 @@ // FindFallbackPatternMatch ------------------------------- - void FindFallbackPatternMatchInDatabase() { - FindFallbackPatternMatch(true); - } + void FindFallbackPatternMatchInDatabase() { FindFallbackPatternMatch(true); } void FindFallbackPatternMatchInWorkingSet() { FindFallbackPatternMatch(false); @@ -1199,18 +1170,14 @@ cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::FALLBACK, 1)); cache_->fallback_namespaces_.push_back( AppCacheNamespace(APPCACHE_FALLBACK_NAMESPACE, - kFallbackPatternNamespace, kEntryUrl, true)); + kFallbackPatternNamespace, kEntryUrl, true)); AppCacheDatabase::CacheRecord cache_record; std::vector<AppCacheDatabase::EntryRecord> entries; std::vector<AppCacheDatabase::NamespaceRecord> intercepts; std::vector<AppCacheDatabase::NamespaceRecord> fallbacks; std::vector<AppCacheDatabase::OnlineWhiteListRecord> whitelists; - cache_->ToDatabaseRecords(group_.get(), - &cache_record, - &entries, - &intercepts, - &fallbacks, - &whitelists); + cache_->ToDatabaseRecords(group_.get(), &cache_record, &entries, + &intercepts, &fallbacks, &whitelists); for (const auto& entry : entries) { // MakeCacheAndGroup has inserted the default entry record already. @@ -1230,29 +1197,29 @@ PushNextTask(base::BindOnce( &AppCacheStorageImplTest::Verify_FindFallbackPatternMatchNegative, base::Unretained(this))); - storage()->FindResponseForMainRequest( - kFallbackPatternTestNegativeUrl, GURL(), delegate()); + storage()->FindResponseForMainRequest(kFallbackPatternTestNegativeUrl, + GURL(), delegate()); EXPECT_EQ(GURL(), delegate()->found_url_); // Is always async. } void Verify_FindFallbackPatternMatchNegative() { EXPECT_EQ(kFallbackPatternTestNegativeUrl, delegate()->found_url_); - EXPECT_TRUE(delegate()->found_manifest_url_.is_empty()); - EXPECT_EQ(blink::mojom::kAppCacheNoCacheId, delegate()->found_cache_id_); - EXPECT_EQ(blink::mojom::kAppCacheNoResponseId, - delegate()->found_entry_.response_id()); - EXPECT_EQ(blink::mojom::kAppCacheNoResponseId, - delegate()->found_fallback_entry_.response_id()); - EXPECT_TRUE(delegate()->found_namespace_entry_url_.is_empty()); - EXPECT_EQ(0, delegate()->found_entry_.types()); - EXPECT_EQ(0, delegate()->found_fallback_entry_.types()); + EXPECT_TRUE(delegate()->found_manifest_url_.is_empty()); + EXPECT_EQ(blink::mojom::kAppCacheNoCacheId, delegate()->found_cache_id_); + EXPECT_EQ(blink::mojom::kAppCacheNoResponseId, + delegate()->found_entry_.response_id()); + EXPECT_EQ(blink::mojom::kAppCacheNoResponseId, + delegate()->found_fallback_entry_.response_id()); + EXPECT_TRUE(delegate()->found_namespace_entry_url_.is_empty()); + EXPECT_EQ(0, delegate()->found_entry_.types()); + EXPECT_EQ(0, delegate()->found_fallback_entry_.types()); - // Then test something that matches. - PushNextTask(base::BindOnce( - &AppCacheStorageImplTest::Verify_FindFallbackPatternMatchPositive, - base::Unretained(this))); - storage()->FindResponseForMainRequest( - kFallbackPatternTestPositiveUrl, GURL(), delegate()); + // Then test something that matches. + PushNextTask(base::BindOnce( + &AppCacheStorageImplTest::Verify_FindFallbackPatternMatchPositive, + base::Unretained(this))); + storage()->FindResponseForMainRequest(kFallbackPatternTestPositiveUrl, + GURL(), delegate()); } void Verify_FindFallbackPatternMatchPositive() { @@ -1297,9 +1264,8 @@ entry_record.flags = AppCacheEntry::EXPLICIT; entry_record.response_id = id; EXPECT_TRUE(database()->InsertEntry(&entry_record)); - cache_->AddEntry( - entry_record.url, - AppCacheEntry(entry_record.flags, entry_record.response_id)); + cache_->AddEntry(entry_record.url, AppCacheEntry(entry_record.flags, + entry_record.response_id)); // Add an entry for the manifestUrl entry_record.cache_id = id; @@ -1307,9 +1273,8 @@ entry_record.flags = AppCacheEntry::MANIFEST; entry_record.response_id = id + kManifestEntryIdOffset; EXPECT_TRUE(database()->InsertEntry(&entry_record)); - cache_->AddEntry( - entry_record.url, - AppCacheEntry(entry_record.flags, entry_record.response_id)); + cache_->AddEntry(entry_record.url, AppCacheEntry(entry_record.flags, + entry_record.response_id)); // Add a fallback entry and namespace entry_record.cache_id = id; @@ -1317,20 +1282,16 @@ entry_record.flags = AppCacheEntry::FALLBACK; entry_record.response_id = id + kFallbackEntryIdOffset; EXPECT_TRUE(database()->InsertEntry(&entry_record)); - cache_->AddEntry( - entry_record.url, - AppCacheEntry(entry_record.flags, entry_record.response_id)); + cache_->AddEntry(entry_record.url, AppCacheEntry(entry_record.flags, + entry_record.response_id)); AppCacheDatabase::NamespaceRecord fallback_namespace_record; fallback_namespace_record.cache_id = id; fallback_namespace_record.namespace_.target_url = entry_record.url; fallback_namespace_record.namespace_.namespace_url = kFallbackNamespace; fallback_namespace_record.origin = url::Origin::Create(manifest_url); EXPECT_TRUE(database()->InsertNamespace(&fallback_namespace_record)); - cache_->fallback_namespaces_.push_back( - AppCacheNamespace(APPCACHE_FALLBACK_NAMESPACE, - kFallbackNamespace, - kEntryUrl2, - false)); + cache_->fallback_namespaces_.push_back(AppCacheNamespace( + APPCACHE_FALLBACK_NAMESPACE, kFallbackNamespace, kEntryUrl2, false)); } void Verify_FindMainResponseWithMultipleHits() { @@ -1383,8 +1344,7 @@ PushNextTask(base::BindOnce( &AppCacheStorageImplTest::Verify_FindMainResponseWithMultipleHits4, base::Unretained(this))); - storage()->FindResponseForMainRequest( - kFallbackTestUrl, GURL(), delegate()); + storage()->FindResponseForMainRequest(kFallbackTestUrl, GURL(), delegate()); EXPECT_NE(kFallbackTestUrl, delegate()->found_url_); } @@ -1404,8 +1364,8 @@ PushNextTask(base::BindOnce( &AppCacheStorageImplTest::Verify_FindMainResponseWithMultipleHits5, base::Unretained(this))); - storage()->FindResponseForMainRequest( - kFallbackTestUrl, kManifestUrl2, delegate()); + storage()->FindResponseForMainRequest(kFallbackTestUrl, kManifestUrl2, + delegate()); EXPECT_NE(kFallbackTestUrl, delegate()->found_url_); } @@ -1438,20 +1398,17 @@ // foreign entry, an online namespace, and a second online // namespace nested within a fallback namespace. MakeCacheAndGroup(kManifestUrl, 1, 1, true); - cache_->AddEntry(kEntryUrl, + cache_->AddEntry( + kEntryUrl, AppCacheEntry(AppCacheEntry::EXPLICIT | AppCacheEntry::FOREIGN, 1)); cache_->AddEntry(kEntryUrl2, AppCacheEntry(AppCacheEntry::FALLBACK, 2)); - cache_->fallback_namespaces_.push_back( - AppCacheNamespace(APPCACHE_FALLBACK_NAMESPACE, - kFallbackNamespace, - kEntryUrl2, - false)); - cache_->online_whitelist_namespaces_.push_back( - AppCacheNamespace(APPCACHE_NETWORK_NAMESPACE, kOnlineNamespace, - GURL(), false)); + cache_->fallback_namespaces_.push_back(AppCacheNamespace( + APPCACHE_FALLBACK_NAMESPACE, kFallbackNamespace, kEntryUrl2, false)); + cache_->online_whitelist_namespaces_.push_back(AppCacheNamespace( + APPCACHE_NETWORK_NAMESPACE, kOnlineNamespace, GURL(), false)); cache_->online_whitelist_namespaces_.push_back( AppCacheNamespace(APPCACHE_NETWORK_NAMESPACE, - kOnlineNamespaceWithinFallback, GURL(), false)); + kOnlineNamespaceWithinFallback, GURL(), false)); AppCacheDatabase::EntryRecord entry_record; entry_record.cache_id = 1; @@ -1502,8 +1459,8 @@ PushNextTask( base::BindOnce(&AppCacheStorageImplTest::Verify_ExclusionNotFound, base::Unretained(this), kOnlineNamespace, 2)); - storage()->FindResponseForMainRequest( - kOnlineNamespace, GURL(), delegate()); + storage()->FindResponseForMainRequest(kOnlineNamespace, GURL(), + delegate()); return; } if (phase == 2) { @@ -1512,8 +1469,8 @@ PushNextTask(base::BindOnce( &AppCacheStorageImplTest::Verify_ExclusionNotFound, base::Unretained(this), kOnlineNamespaceWithinFallback, 3)); - storage()->FindResponseForMainRequest( - kOnlineNamespaceWithinFallback, GURL(), delegate()); + storage()->FindResponseForMainRequest(kOnlineNamespaceWithinFallback, + GURL(), delegate()); return; } @@ -1528,8 +1485,7 @@ class MockServiceObserver : public AppCacheServiceImpl::Observer { public: - explicit MockServiceObserver(AppCacheStorageImplTest* test) - : test_(test) {} + explicit MockServiceObserver(AppCacheStorageImplTest* test) : test_(test) {} void OnServiceReinitialized( AppCacheStorageReference* old_storage_ref) override { @@ -1545,33 +1501,27 @@ public: MockAppCacheFrontend() : error_event_was_raised_(false) {} - void CacheSelected(int32_t host_id, - blink::mojom::AppCacheInfoPtr info) override {} - void EventRaised(const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheEventID event_id) override {} - void ProgressEventRaised(const std::vector<int32_t>& host_ids, - const GURL& url, + void CacheSelected(blink::mojom::AppCacheInfoPtr info) override {} + void EventRaised(blink::mojom::AppCacheEventID event_id) override {} + void ProgressEventRaised(const GURL& url, int32_t num_total, int32_t num_complete) override {} void ErrorEventRaised( - const std::vector<int32_t>& host_ids, blink::mojom::AppCacheErrorDetailsPtr details) override { error_event_was_raised_ = true; } - void LogMessage(int32_t host_id, - blink::mojom::ConsoleMessageLevel log_level, + void LogMessage(blink::mojom::ConsoleMessageLevel log_level, const std::string& message) override {} void SetSubresourceFactory( - int32_t host_id, network::mojom::URLLoaderFactoryPtr url_loader_factory) override {} bool error_event_was_raised_; }; enum ReinitTestCase { - CORRUPT_CACHE_ON_INSTALL, - CORRUPT_CACHE_ON_LOAD_EXISTING, - CORRUPT_SQL_ON_INSTALL + CORRUPT_CACHE_ON_INSTALL, + CORRUPT_CACHE_ON_LOAD_EXISTING, + CORRUPT_SQL_ON_INSTALL }; void Reinitialize1() { @@ -1612,8 +1562,8 @@ ASSERT_TRUE(base::CreateDirectory(disk_cache_directory)); base::FilePath index_file = disk_cache_directory.AppendASCII("index"); EXPECT_EQ(static_cast<int>(kCorruptData.length()), - base::WriteFile( - index_file, kCorruptData.data(), kCorruptData.length())); + base::WriteFile(index_file, kCorruptData.data(), + kCorruptData.length())); // Also add a corrupt entry file so that simple disk_cache does not try // to automatically recover from the corrupted index. @@ -1681,7 +1631,6 @@ const int kMockRenderFrameId = MSG_ROUTING_NONE; backend_ = std::make_unique<AppCacheBackendImpl>(service_.get(), kMockProcessId); - backend_->set_frontend_for_testing(&frontend_); if (test_case == CORRUPT_SQL_ON_INSTALL) { // Break the db file @@ -1690,12 +1639,12 @@ temp_directory_.GetPath().AppendASCII("Index"))); } - if (test_case == CORRUPT_CACHE_ON_INSTALL || + if (test_case == CORRUPT_CACHE_ON_INSTALL || test_case == CORRUPT_SQL_ON_INSTALL) { // Try to create a new appcache, the resulting update job will // eventually fail when it gets to disk cache initialization. - backend_->RegisterHost(blink::mojom::AppCacheHostRequest(), 1, - kMockRenderFrameId); + backend_->RegisterHost(blink::mojom::AppCacheHostRequest(), + BindFrontend(), 1, kMockRenderFrameId); AppCacheHost* host1 = backend_->GetHost(1); const GURL kEmptyPageUrl(GetMockUrl("empty.html")); host1->SetFirstPartyUrlForTesting(kEmptyPageUrl); @@ -1706,8 +1655,8 @@ // Try to access the existing cache manifest. // The URLRequestJob will eventually fail when it gets to disk // cache initialization. - backend_->RegisterHost(blink::mojom::AppCacheHostRequest(), 2, - kMockRenderFrameId); + backend_->RegisterHost(blink::mojom::AppCacheHostRequest(), + BindFrontend(), 2, kMockRenderFrameId); AppCacheHost* host2 = backend_->GetHost(2); network::ResourceRequest request; request.url = GetMockUrl("manifest"); @@ -1761,29 +1710,29 @@ // Test case helpers -------------------------------------------------- - AppCacheServiceImpl* service() { - return service_.get(); - } + AppCacheServiceImpl* service() { return service_.get(); } AppCacheStorageImpl* storage() { return static_cast<AppCacheStorageImpl*>(service()->storage()); } - AppCacheDatabase* database() { - return storage()->database_; - } + AppCacheDatabase* database() { return storage()->database_; } - MockStorageDelegate* delegate() { - return delegate_.get(); + MockStorageDelegate* delegate() { return delegate_.get(); } + + blink::mojom::AppCacheFrontendPtr BindFrontend() { + blink::mojom::AppCacheFrontendPtr result; + frontend_bindings_.AddBinding(&frontend_, mojo::MakeRequest(&result)); + return result; } void MakeCacheAndGroup(const GURL& manifest_url, int64_t group_id, int64_t cache_id, bool add_to_database) { - AppCacheEntry default_entry( - AppCacheEntry::EXPLICIT, cache_id + kDefaultEntryIdOffset, - kDefaultEntrySize); + AppCacheEntry default_entry(AppCacheEntry::EXPLICIT, + cache_id + kDefaultEntryIdOffset, + kDefaultEntrySize); group_ = new AppCacheGroup(storage(), manifest_url, group_id); cache_ = new AppCache(storage(), cache_id); cache_->AddEntry(kDefaultEntryUrl, default_entry); @@ -1831,6 +1780,7 @@ base::ScopedTempDir temp_directory_; std::unique_ptr<MockServiceObserver> observer_; MockAppCacheFrontend frontend_; + mojo::BindingSet<blink::mojom::AppCacheFrontend> frontend_bindings_; std::unique_ptr<AppCacheBackendImpl> backend_; std::unique_ptr<AppCacheRequestHandler> handler_; network::TestURLLoaderFactory mock_url_loader_factory_; @@ -1932,8 +1882,7 @@ } TEST_F(AppCacheStorageImplTest, BasicFindMainResponseInDatabase) { - RunTestOnIOThread( - &AppCacheStorageImplTest::BasicFindMainResponseInDatabase); + RunTestOnIOThread(&AppCacheStorageImplTest::BasicFindMainResponseInDatabase); } TEST_F(AppCacheStorageImplTest, BasicFindMainResponseInWorkingSet) { @@ -1962,8 +1911,7 @@ } TEST_F(AppCacheStorageImplTest, FindMainResponseWithMultipleHits) { - RunTestOnIOThread( - &AppCacheStorageImplTest::FindMainResponseWithMultipleHits); + RunTestOnIOThread(&AppCacheStorageImplTest::FindMainResponseWithMultipleHits); } TEST_F(AppCacheStorageImplTest, FindMainResponseExclusionsInDatabase) {
diff --git a/content/browser/appcache/appcache_unittest.cc b/content/browser/appcache/appcache_unittest.cc index c3ed3fc..6e12bd8 100644 --- a/content/browser/appcache/appcache_unittest.cc +++ b/content/browser/appcache/appcache_unittest.cc
@@ -18,48 +18,26 @@ namespace content { -namespace { - -class MockAppCacheFrontend : public blink::mojom::AppCacheFrontend { - public: - void CacheSelected(int32_t host_id, - blink::mojom::AppCacheInfoPtr info) override {} - void EventRaised(const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheEventID event_id) override {} - void ProgressEventRaised(const std::vector<int32_t>& host_ids, - const GURL& url, - int32_t num_total, - int32_t num_complete) override {} - void ErrorEventRaised( - const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheErrorDetailsPtr details) override {} - void LogMessage(int32_t host_id, - blink::mojom::ConsoleMessageLevel log_level, - const std::string& message) override {} - void SetSubresourceFactory( - int32_t host_id, - network::mojom::URLLoaderFactoryPtr url_loader_factory) override {} -}; - -} // namespace - class AppCacheTest : public testing::Test { base::test::ScopedTaskEnvironment scoped_task_environment_; }; TEST_F(AppCacheTest, CleanupUnusedCache) { MockAppCacheService service; - MockAppCacheFrontend frontend; scoped_refptr<AppCache> cache(new AppCache(service.storage(), 111)); cache->set_complete(true); scoped_refptr<AppCacheGroup> group( new AppCacheGroup(service.storage(), GURL("http://blah/manifest"), 111)); group->AddCache(cache.get()); + blink::mojom::AppCacheFrontendPtr frontend1; + mojo::MakeRequest(&frontend1); AppCacheHost host1(/*host_id=*/1, /*process_id=*/1, /*render_frame_id=*/1, - &frontend, &service); + std::move(frontend1), &service); + blink::mojom::AppCacheFrontendPtr frontend2; + mojo::MakeRequest(&frontend2); AppCacheHost host2(/*host_id=*/2, /*process_id=*/2, /*render_frame_id=*/2, - &frontend, &service); + std::move(frontend2), &service); host1.AssociateCompleteCache(cache.get()); host2.AssociateCompleteCache(cache.get());
diff --git a/content/browser/appcache/appcache_update_job.cc b/content/browser/appcache/appcache_update_job.cc index 3eaa0a94..c758ac7 100644 --- a/content/browser/appcache/appcache_update_job.cc +++ b/content/browser/appcache/appcache_update_job.cc
@@ -100,15 +100,9 @@ // so that only one notification is sent for all hosts using the same frontend. class HostNotifier { public: - using AppCacheFrontend = blink::mojom::AppCacheFrontend; - using HostIds = std::vector<int>; - using NotifyHostMap = std::map<AppCacheFrontend*, HostIds>; - // Caller is responsible for ensuring there will be no duplicate hosts. void AddHost(AppCacheHost* host) { - std::pair<NotifyHostMap::iterator, bool> ret = hosts_to_notify_.insert( - NotifyHostMap::value_type(host->frontend(), HostIds())); - ret.first->second.push_back(host->host_id()); + hosts_to_notify_.insert(host->frontend()); } void AddHosts(const std::set<AppCacheHost*>& hosts) { @@ -117,41 +111,32 @@ } void SendNotifications(blink::mojom::AppCacheEventID event_id) { - for (auto& pair : hosts_to_notify_) { - AppCacheFrontend* frontend = pair.first; - frontend->EventRaised(pair.second, event_id); - } + for (auto* frontend : hosts_to_notify_) + frontend->EventRaised(event_id); } void SendProgressNotifications(const GURL& url, int num_total, int num_complete) { - for (const auto& pair : hosts_to_notify_) { - AppCacheFrontend* frontend = pair.first; - frontend->ProgressEventRaised(pair.second, url, num_total, num_complete); - } + for (auto* frontend : hosts_to_notify_) + frontend->ProgressEventRaised(url, num_total, num_complete); } void SendErrorNotifications( const blink::mojom::AppCacheErrorDetails& details) { DCHECK(!details.message.empty()); - for (const auto& pair : hosts_to_notify_) { - AppCacheFrontend* frontend = pair.first; - frontend->ErrorEventRaised(pair.second, details.Clone()); - } + for (auto* frontend : hosts_to_notify_) + frontend->ErrorEventRaised(details.Clone()); } void SendLogMessage(const std::string& message) { - for (const auto& pair : hosts_to_notify_) { - AppCacheFrontend* frontend = pair.first; - for (const auto& id : pair.second) - frontend->LogMessage(id, blink::mojom::ConsoleMessageLevel::kWarning, - message); - } + for (auto* frontend : hosts_to_notify_) + frontend->LogMessage(blink::mojom::ConsoleMessageLevel::kWarning, + message); } private: - NotifyHostMap hosts_to_notify_; + std::set<blink::mojom::AppCacheFrontend*> hosts_to_notify_; }; AppCacheUpdateJob::UrlToFetch::UrlToFetch(const GURL& url, bool checked, @@ -834,8 +819,7 @@ void AppCacheUpdateJob::NotifySingleHost( AppCacheHost* host, blink::mojom::AppCacheEventID event_id) { - std::vector<int> ids(1, host->host_id()); - host->frontend()->EventRaised(ids, event_id); + host->frontend()->EventRaised(event_id); } void AppCacheUpdateJob::NotifyAllAssociatedHosts(
diff --git a/content/browser/appcache/appcache_update_job_unittest.cc b/content/browser/appcache/appcache_update_job_unittest.cc index c56c1f0..b858764 100644 --- a/content/browser/appcache/appcache_update_job_unittest.cc +++ b/content/browser/appcache/appcache_update_job_unittest.cc
@@ -54,12 +54,10 @@ class AppCacheUpdateJobTest; // Values should match values used in appcache_update_job.cc. -const base::TimeDelta kFullUpdateInterval = - base::TimeDelta::FromHours(24); +const base::TimeDelta kFullUpdateInterval = base::TimeDelta::FromHours(24); const base::TimeDelta kMaxEvictableErrorDuration = base::TimeDelta::FromDays(14); -const base::TimeDelta kOneHour = - base::TimeDelta::FromHours(1); +const base::TimeDelta kOneHour = base::TimeDelta::FromHours(1); const char kManifest1Contents[] = "CACHE MANIFEST\n" @@ -87,15 +85,16 @@ } static net::URLRequestJob* JobFactory( - net::URLRequest* request, net::NetworkDelegate* network_delegate) { + net::URLRequest* request, + net::NetworkDelegate* network_delegate) { if (request->url().host() != "mockhost" && request->url().host() != "cross_origin_host") return new net::URLRequestErrorJob(request, network_delegate, -100); std::string headers, body; GetMockResponse(request->url().path(), &headers, &body); - return new net::URLRequestTestJob( - request, network_delegate, headers, body, true); + return new net::URLRequestTestJob(request, network_delegate, headers, body, + true); } static void GetMockResponse(const std::string& path, @@ -136,8 +135,9 @@ (*body) = ""; } else if (path == "/files/empty-file-manifest") { (*headers) = std::string(manifest_headers, base::size(manifest_headers)); - (*body) = "CACHE MANIFEST\n" - "empty1\n"; + (*body) = + "CACHE MANIFEST\n" + "empty1\n"; } else if (path == "/files/empty-manifest") { (*headers) = std::string(manifest_headers, base::size(manifest_headers)); (*body) = "CACHE MANIFEST\n"; @@ -162,44 +162,49 @@ } else if (path == "/files/manifest1-with-notmodified") { (*headers) = std::string(manifest_headers, base::size(manifest_headers)); (*body) = kManifest1Contents; - (*body).append("CACHE:\n" - "notmodified\n"); + (*body).append( + "CACHE:\n" + "notmodified\n"); } else if (path == "/files/manifest-fb-404") { (*headers) = std::string(manifest_headers, base::size(manifest_headers)); - (*body) = "CACHE MANIFEST\n" - "explicit1\n" - "FALLBACK:\n" - "fallback1 fallback1a\n" - "fallback404 fallback-404\n" - "NETWORK:\n" - "online1\n"; + (*body) = + "CACHE MANIFEST\n" + "explicit1\n" + "FALLBACK:\n" + "fallback1 fallback1a\n" + "fallback404 fallback-404\n" + "NETWORK:\n" + "online1\n"; } else if (path == "/files/manifest-merged-types") { (*headers) = std::string(manifest_headers, base::size(manifest_headers)); - (*body) = "CACHE MANIFEST\n" - "explicit1\n" - "# manifest is also an explicit entry\n" - "manifest-merged-types\n" - "FALLBACK:\n" - "# fallback is also explicit entry\n" - "fallback1 explicit1\n" - "NETWORK:\n" - "online1\n"; + (*body) = + "CACHE MANIFEST\n" + "explicit1\n" + "# manifest is also an explicit entry\n" + "manifest-merged-types\n" + "FALLBACK:\n" + "# fallback is also explicit entry\n" + "fallback1 explicit1\n" + "NETWORK:\n" + "online1\n"; } else if (path == "/files/manifest-with-404") { (*headers) = std::string(manifest_headers, base::size(manifest_headers)); - (*body) = "CACHE MANIFEST\n" - "explicit-404\n" - "explicit1\n" - "explicit2\n" - "explicit3\n" - "FALLBACK:\n" - "fallback1 fallback1a\n" - "NETWORK:\n" - "online1\n"; + (*body) = + "CACHE MANIFEST\n" + "explicit-404\n" + "explicit1\n" + "explicit2\n" + "explicit3\n" + "FALLBACK:\n" + "fallback1 fallback1a\n" + "NETWORK:\n" + "online1\n"; } else if (path == "/files/manifest-with-intercept") { (*headers) = std::string(manifest_headers, base::size(manifest_headers)); - (*body) = "CACHE MANIFEST\n" - "CHROMIUM-INTERCEPT:\n" - "intercept1 return intercept1a\n"; + (*body) = + "CACHE MANIFEST\n" + "CHROMIUM-INTERCEPT:\n" + "intercept1 return intercept1a\n"; } else if (path == "/files/notmodified") { (*headers) = std::string(not_modified_headers, base::size(not_modified_headers)); @@ -209,12 +214,14 @@ (*body) = "error"; } else if (path == "/files/valid_cross_origin_https_manifest") { (*headers) = std::string(manifest_headers, base::size(manifest_headers)); - (*body) = "CACHE MANIFEST\n" - "https://cross_origin_host/files/explicit1\n"; + (*body) = + "CACHE MANIFEST\n" + "https://cross_origin_host/files/explicit1\n"; } else if (path == "/files/invalid_cross_origin_https_manifest") { (*headers) = std::string(manifest_headers, base::size(manifest_headers)); - (*body) = "CACHE MANIFEST\n" - "https://cross_origin_host/files/no-store-headers\n"; + (*body) = + "CACHE MANIFEST\n" + "https://cross_origin_host/files/no-store-headers\n"; } else if (path == "/files/no-store-headers") { (*headers) = std::string(no_store_headers, base::size(no_store_headers)); (*body) = "no-store"; @@ -237,9 +244,8 @@ }; inline bool operator==(const AppCacheNamespace& lhs, - const AppCacheNamespace& rhs) { - return lhs.type == rhs.type && - lhs.namespace_url == rhs.namespace_url && + const AppCacheNamespace& rhs) { + return lhs.type == rhs.type && lhs.namespace_url == rhs.namespace_url && lhs.target_url == rhs.target_url; } @@ -254,12 +260,10 @@ blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT), update_(nullptr) {} - void CacheSelected(int32_t host_id, - blink::mojom::AppCacheInfoPtr info) override {} + void CacheSelected(blink::mojom::AppCacheInfoPtr info) override {} - void EventRaised(const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheEventID event_id) override { - raised_events_.push_back(RaisedEvent(host_ids, event_id)); + void EventRaised(blink::mojom::AppCacheEventID event_id) override { + raised_events_.push_back(event_id); // Trigger additional updates if requested. if (event_id == start_update_trigger_ && update_) { @@ -272,19 +276,16 @@ } void ErrorEventRaised( - const std::vector<int32_t>& host_ids, blink::mojom::AppCacheErrorDetailsPtr details) override { error_message_ = details->message; - EventRaised(host_ids, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + EventRaised(blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); } - void ProgressEventRaised(const std::vector<int32_t>& host_ids, - const GURL& url, + void ProgressEventRaised(const GURL& url, int32_t num_total, int32_t num_complete) override { if (!ignore_progress_events_) - EventRaised(host_ids, - blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + EventRaised(blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); if (verify_progress_events_) { EXPECT_GE(num_total, num_complete); @@ -310,19 +311,16 @@ } } - void LogMessage(int32_t host_id, - blink::mojom::ConsoleMessageLevel log_level, + void LogMessage(blink::mojom::ConsoleMessageLevel log_level, const std::string& message) override {} void SetSubresourceFactory( - int32_t host_id, network::mojom::URLLoaderFactoryPtr url_loader_factory) override {} - void AddExpectedEvent(const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheEventID event_id) { + void AddExpectedEvent(blink::mojom::AppCacheEventID event_id) { DCHECK(!ignore_progress_events_ || event_id != blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); - expected_events_.push_back(RaisedEvent(host_ids, event_id)); + expected_events_.push_back(event_id); } void SetIgnoreProgressEvents(bool ignore) { @@ -349,9 +347,7 @@ update_hosts_.push_back(host); } - using HostIds = std::vector<int32_t>; - using RaisedEvent = std::pair<HostIds, blink::mojom::AppCacheEventID>; - using RaisedEvents = std::vector<RaisedEvent>; + using RaisedEvents = std::vector<blink::mojom::AppCacheEventID>; RaisedEvents raised_events_; std::string error_message_; @@ -378,11 +374,9 @@ net::URLRequest* request, net::NetworkDelegate* network_delegate) const override { return new net::URLRequestTestJob( - request, - network_delegate, + request, network_delegate, net::URLRequestTestJob::test_redirect_headers(), - net::URLRequestTestJob::test_data_1(), - true); + net::URLRequestTestJob::test_data_1(), true); } }; @@ -398,8 +392,9 @@ static const GURL kRetryUrl; // Call this at the start of each retry test. - static void Initialize(int num_retry_responses, RetryHeader header, - int expected_requests) { + static void Initialize(int num_retry_responses, + RetryHeader header, + int expected_requests) { num_requests_ = 0; num_retries_ = num_retry_responses; retry_after_ = header; @@ -414,7 +409,8 @@ } static net::URLRequestJob* RetryFactory( - net::URLRequest* request, net::NetworkDelegate* network_delegate) { + net::URLRequest* request, + net::NetworkDelegate* network_delegate) { std::string headers; GetResponseForURL(request->original_url(), &headers, nullptr); return new RetryRequestTestJob(request, network_delegate, headers); @@ -470,7 +466,8 @@ } static std::string data() { - return std::string("CACHE MANIFEST\r" + return std::string( + "CACHE MANIFEST\r" "http://retry\r"); // must be same as kRetryUrl } @@ -532,7 +529,8 @@ } static net::URLRequestJob* IfModifiedSinceFactory( - net::URLRequest* request, net::NetworkDelegate* network_delegate) { + net::URLRequest* request, + net::NetworkDelegate* network_delegate) { ValidateExtraHeaders(request->extra_request_headers()); return MockHttpServer::JobFactory(request, network_delegate); } @@ -580,8 +578,8 @@ net::URLRequestJob* MaybeCreateJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) const override { - return HttpHeadersRequestTestJob::IfModifiedSinceFactory( - request, network_delegate); + return HttpHeadersRequestTestJob::IfModifiedSinceFactory(request, + network_delegate); } }; @@ -649,9 +647,7 @@ IOThread() {} ~IOThread() {} - net::URLRequestContext* request_context() { - return request_context_.get(); - } + net::URLRequestContext* request_context() { return request_context_.get(); } void SetNewJobFactory(net::URLRequestJobFactory* job_factory) { DCHECK(job_factory); @@ -761,7 +757,8 @@ MockFrontend mock_frontend; AppCacheHost host(/*host_id=*/1, /*process_id=*/1, /*render_frame_id=*/1, - &mock_frontend, service_.get()); + nullptr, service_.get()); + host.set_frontend_for_testing(&mock_frontend); update->StartUpdate(&host, GURL()); @@ -773,12 +770,9 @@ // Verify notifications. MockFrontend::RaisedEvents& events = mock_frontend.raised_events_; - size_t expected = 1; - EXPECT_EQ(expected, events.size()); - EXPECT_EQ(expected, events[0].first.size()); - EXPECT_EQ(host.host_id(), events[0].first[0]); + ASSERT_EQ(1u, events.size()); EXPECT_EQ(blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT, - events[0].second); + events[0]); // Abort as we're not testing actual URL fetches in this test. delete update; @@ -801,21 +795,26 @@ MockFrontend mock_frontend1; MockFrontend mock_frontend2; MockFrontend mock_frontend3; + MockFrontend mock_frontend4; AppCacheHost host1(/*host_id=*/1, /*process_id=*/1, /*render_frame_id=*/1, - &mock_frontend1, service_.get()); + nullptr, service_.get()); + host1.set_frontend_for_testing(&mock_frontend1); host1.AssociateCompleteCache(cache1); AppCacheHost host2(/*host_id=*/2, /*process_id=*/2, /*render_frame_id=*/2, - &mock_frontend2, service_.get()); + nullptr, service_.get()); + host2.set_frontend_for_testing(&mock_frontend2); host2.AssociateCompleteCache(cache2); AppCacheHost host3(/*host_id=*/3, /*process_id=*/3, /*render_frame_id=*/3, - &mock_frontend1, service_.get()); + nullptr, service_.get()); + host3.set_frontend_for_testing(&mock_frontend3); host3.AssociateCompleteCache(cache1); AppCacheHost host4(/*host_id=*/4, /*process_id=*/4, /*render_frame_id=*/4, - &mock_frontend3, service_.get()); + nullptr, service_.get()); + host4.set_frontend_for_testing(&mock_frontend4); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); @@ -829,26 +828,22 @@ EXPECT_FALSE(update->doing_full_update_check_); // Verify notifications. - MockFrontend::RaisedEvents& events = mock_frontend1.raised_events_; - size_t expected = 1; - EXPECT_EQ(expected, events.size()); - expected = 2; // 2 hosts using frontend1 - EXPECT_EQ(expected, events[0].first.size()); - MockFrontend::HostIds& host_ids = events[0].first; - EXPECT_TRUE(base::ContainsValue(host_ids, host1.host_id())); - EXPECT_TRUE(base::ContainsValue(host_ids, host3.host_id())); + MockFrontend::RaisedEvents events = mock_frontend1.raised_events_; + ASSERT_EQ(1u, events.size()); EXPECT_EQ(blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT, - events[0].second); + events[0]); events = mock_frontend2.raised_events_; - expected = 1; - EXPECT_EQ(expected, events.size()); - EXPECT_EQ(expected, events[0].first.size()); // 1 host using frontend2 - EXPECT_EQ(host2.host_id(), events[0].first[0]); + ASSERT_EQ(1u, events.size()); EXPECT_EQ(blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT, - events[0].second); + events[0]); events = mock_frontend3.raised_events_; + ASSERT_EQ(1u, events.size()); + EXPECT_EQ(blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT, + events[0]); + + events = mock_frontend4.raised_events_; EXPECT_TRUE(events.empty()); // Abort as we're not testing actual URL fetches in this test. @@ -876,7 +871,6 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = false; frontend->AddExpectedEvent( - MockFrontend::HostIds(1, host->host_id()), blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); WaitForUpdateToFinish(); @@ -901,8 +895,8 @@ host1->AssociateCompleteCache(cache); host2->AssociateCompleteCache(cache); - group_->set_last_full_update_check_time( - base::Time::Now() - kFullUpdateInterval - kOneHour); + group_->set_last_full_update_check_time(base::Time::Now() - + kFullUpdateInterval - kOneHour); update->StartUpdate(nullptr, GURL()); EXPECT_TRUE(update->doing_full_update_check_); @@ -913,16 +907,14 @@ expect_evictable_error_ = true; expect_newest_cache_ = cache; // newest cache unaffected by update expect_full_update_time_equal_to_ = group_->last_full_update_check_time(); - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); WaitForUpdateToFinish(); } @@ -946,7 +938,6 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = false; // redirect is like a failed request frontend->AddExpectedEvent( - MockFrontend::HostIds(1, host->host_id()), blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); WaitForUpdateToFinish(); @@ -980,15 +971,14 @@ expect_old_cache_ = cache; tested_manifest_ = EMPTY_MANIFEST; tested_manifest_path_override_ = "files/missing-mime-manifest"; - MockFrontend::HostIds ids(1, host->host_id()); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); WaitForUpdateToFinish(); } @@ -997,9 +987,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), MockHttpServer::GetMockUrl("files/nosuchfile"), - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/nosuchfile"), + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -1019,16 +1009,14 @@ expect_group_obsolete_ = true; expect_group_has_cache_ = true; expect_newest_cache_ = cache; // newest cache unaffected by update - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_OBSOLETE_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_OBSOLETE_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_OBSOLETE_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_OBSOLETE_EVENT); WaitForUpdateToFinish(); } @@ -1037,9 +1025,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), MockHttpServer::GetMockUrl("files/gone"), - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/gone"), + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -1053,7 +1041,6 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = false; frontend->AddExpectedEvent( - MockFrontend::HostIds(1, host->host_id()), blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); WaitForUpdateToFinish(); @@ -1063,9 +1050,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), MockHttpServer::GetMockUrl("files/notmodified"), - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/notmodified"), + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -1079,7 +1066,6 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = false; // treated like cache failure frontend->AddExpectedEvent( - MockFrontend::HostIds(1, host->host_id()), blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); WaitForUpdateToFinish(); @@ -1089,9 +1075,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), MockHttpServer::GetMockUrl("files/notmodified"), - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/notmodified"), + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -1104,8 +1090,8 @@ host1->AssociateCompleteCache(cache); host2->AssociateCompleteCache(cache); - group_->set_last_full_update_check_time( - base::Time::Now() - kFullUpdateInterval - kOneHour); + group_->set_last_full_update_check_time(base::Time::Now() - + kFullUpdateInterval - kOneHour); group_->set_first_evictable_error_time(base::Time::Now()); update->StartUpdate(nullptr, GURL()); EXPECT_TRUE(update->doing_full_update_check_); @@ -1114,19 +1100,17 @@ do_checks_after_update_finished_ = true; expect_group_obsolete_ = false; expect_group_has_cache_ = true; - expect_newest_cache_ = cache; // newest cache unaffected by update - expect_evictable_error_ = false; // should be reset + expect_newest_cache_ = cache; // newest cache unaffected by update + expect_evictable_error_ = false; // should be reset expect_full_update_time_newer_than_ = group_->last_full_update_check_time(); - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); WaitForUpdateToFinish(); } @@ -1135,9 +1119,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), MockHttpServer::GetMockUrl("files/manifest1"), - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest1"), + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -1159,16 +1143,14 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = true; expect_newest_cache_ = cache; // newest cache unaffected by update - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); // Seed storage with expected manifest data. const std::string seed_data(kManifest1Contents); @@ -1210,11 +1192,10 @@ expect_group_is_being_deleted_ = true; expect_group_has_cache_ = true; expect_newest_cache_ = cache; // newest cache unaffected by update - MockFrontend::HostIds id(1, host->host_id()); frontend->AddExpectedEvent( - id, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend->AddExpectedEvent( - id, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); frontend->expected_error_message_ = "Manifest entry not found in existing cache"; WaitForUpdateToFinish(); @@ -1236,9 +1217,8 @@ GURL manifest_url = MockHttpServer::GetMockUrl("files/manifest1"); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), manifest_url, - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), manifest_url, + service_->storage()->NewGroupId()); ASSERT_TRUE(group_->last_full_update_check_time().is_null()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); @@ -1255,7 +1235,6 @@ expect_full_update_time_newer_than_ = base::Time::Now() - kOneHour; tested_manifest_ = MANIFEST1; frontend->AddExpectedEvent( - MockFrontend::HostIds(1, host->host_id()), blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); WaitForUpdateToFinish(); @@ -1267,9 +1246,8 @@ GURL manifest_url = MockHttpServer::GetMockUrl("files/manifest-with-intercept"); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), manifest_url, - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), manifest_url, + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -1284,7 +1262,6 @@ expect_group_has_cache_ = true; tested_manifest_ = MANIFEST_WITH_INTERCEPT; frontend->AddExpectedEvent( - MockFrontend::HostIds(1, host->host_id()), blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); WaitForUpdateToFinish(); @@ -1294,9 +1271,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), MockHttpServer::GetMockUrl("files/manifest1"), - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest1"), + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -1315,8 +1292,8 @@ host2->AssociateCompleteCache(cache); frontend1->SetVerifyProgressEvents(true); frontend2->SetVerifyProgressEvents(true); - group_->set_last_full_update_check_time( - base::Time::Now() - kFullUpdateInterval - kOneHour); + group_->set_last_full_update_check_time(base::Time::Now() - + kFullUpdateInterval - kOneHour); // Set up checks for when update job finishes. do_checks_after_update_finished_ = true; @@ -1325,32 +1302,30 @@ expect_old_cache_ = cache; tested_manifest_ = MANIFEST1; expect_full_update_time_newer_than_ = group_->last_full_update_check_time(); - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); // Seed storage with expected manifest data different from manifest1. const std::string seed_data("different"); @@ -1369,9 +1344,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), MockHttpServer::GetMockUrl("files/manifest1"), - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest1"), + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -1397,19 +1372,18 @@ MockHttpServer::GetMockUrl("files/explicit1"), response_writer_->response_id())); tested_manifest_ = MANIFEST1; - MockFrontend::HostIds ids(1, host->host_id()); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); // Seed storage with expected http response info for entry. Allow reuse. const char data[] = @@ -1440,9 +1414,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), MockHttpServer::GetMockUrl("files/manifest1"), - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest1"), + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -1465,19 +1439,18 @@ expect_group_has_cache_ = true; expect_old_cache_ = cache; tested_manifest_ = MANIFEST1; - MockFrontend::HostIds ids(1, host->host_id()); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); // Seed storage with expected http response info for entry. Do NOT // allow reuse by setting an expires header in the past. @@ -1509,9 +1482,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), MockHttpServer::GetMockUrl("files/manifest1"), - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest1"), + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -1534,19 +1507,18 @@ expect_group_has_cache_ = true; expect_old_cache_ = cache; tested_manifest_ = MANIFEST1; - MockFrontend::HostIds ids(1, host->host_id()); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); // Seed storage with expected http response info for entry: a vary header. const char data[] = @@ -1606,19 +1578,18 @@ MockHttpServer::GetMockUrl("files/explicit1"), response_writer_->response_id())); tested_manifest_ = MANIFEST1; - MockFrontend::HostIds ids(1, host->host_id()); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend->AddExpectedEvent( - ids, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); // Seed storage with expected http response info for an entry // with a vary header for which we allow reuse. @@ -1651,7 +1622,8 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup(service_->storage(), + group_ = new AppCacheGroup( + service_->storage(), MockHttpServer::GetMockUrl("files/manifest-merged-types"), service_->storage()->NewGroupId()); AppCacheUpdateJob* update = @@ -1679,34 +1651,31 @@ expect_group_has_cache_ = true; expect_old_cache_ = cache; tested_manifest_ = MANIFEST_MERGED_TYPES; - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // explicit1 frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // manifest frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); WaitForUpdateToFinish(); } @@ -1715,9 +1684,10 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup(service_->storage(), - MockHttpServer::GetMockUrl("files/manifest-with-404"), - service_->storage()->NewGroupId()); + group_ = + new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest-with-404"), + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -1731,7 +1701,6 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = false; // 404 explicit url is cache failure frontend->AddExpectedEvent( - MockFrontend::HostIds(1, host->host_id()), blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); WaitForUpdateToFinish(); @@ -1741,9 +1710,10 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup(service_->storage(), - MockHttpServer::GetMockUrl("files/manifest-fb-404"), - service_->storage()->NewGroupId()); + group_ = + new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest-fb-404"), + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -1768,20 +1738,19 @@ expect_group_has_cache_ = true; expect_newest_cache_ = cache; // newest cache unaffectd by failed update expect_eviction_ = true; - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); WaitForUpdateToFinish(); } @@ -1794,9 +1763,8 @@ MakeService(); const GURL kManifestUrl = MockHttpServer::GetMockUrl(tested_manifest_path_override_); - group_ = new AppCacheGroup( - service_->storage(), kManifestUrl, - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), kManifestUrl, + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -1810,18 +1778,15 @@ host2->AssociateCompleteCache(cache); // Give the newest cache some existing entries; one will fail with a 404. - cache->AddEntry( - MockHttpServer::GetMockUrl("files/notfound"), - AppCacheEntry(AppCacheEntry::MASTER, 222)); + cache->AddEntry(MockHttpServer::GetMockUrl("files/notfound"), + AppCacheEntry(AppCacheEntry::MASTER, 222)); cache->AddEntry( MockHttpServer::GetMockUrl("files/explicit2"), AppCacheEntry(AppCacheEntry::MASTER | AppCacheEntry::FOREIGN, 333)); - cache->AddEntry( - MockHttpServer::GetMockUrl("files/servererror"), - AppCacheEntry(AppCacheEntry::MASTER, 444)); - cache->AddEntry( - MockHttpServer::GetMockUrl("files/notmodified"), - AppCacheEntry(AppCacheEntry::EXPLICIT, 555)); + cache->AddEntry(MockHttpServer::GetMockUrl("files/servererror"), + AppCacheEntry(AppCacheEntry::MASTER, 444)); + cache->AddEntry(MockHttpServer::GetMockUrl("files/notmodified"), + AppCacheEntry(AppCacheEntry::EXPLICIT, 555)); // Seed the response_info working set with canned data for // files/servererror and for files/notmodified to test that the @@ -1855,60 +1820,47 @@ MockHttpServer::GetMockUrl("files/servererror"), 444)); // copied expect_response_ids_.insert(std::map<GURL, int64_t>::value_type( MockHttpServer::GetMockUrl("files/notmodified"), 555)); // copied - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // explicit1 frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // fallback1a frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // notfound frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // explicit2 frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // servererror frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // notmodified frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // explicit1 frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // fallback1a frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // notfound frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // explicit2 frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // servererror frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // notmodified frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); WaitForUpdateToFinish(); } @@ -1942,24 +1894,23 @@ expect_group_has_cache_ = true; expect_old_cache_ = cache; tested_manifest_ = EMPTY_MANIFEST; - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); WaitForUpdateToFinish(); } @@ -1968,7 +1919,8 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup(service_->storage(), + group_ = new AppCacheGroup( + service_->storage(), MockHttpServer::GetMockUrl("files/empty-file-manifest"), service_->storage()->NewGroupId()); AppCacheUpdateJob* update = @@ -1988,17 +1940,16 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = true; tested_manifest_ = EMPTY_FILE_MANIFEST; - MockFrontend::HostIds ids1(1, host->host_id()); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); WaitForUpdateToFinish(); } @@ -2011,9 +1962,9 @@ RetryRequestTestJob::Initialize(5, RetryRequestTestJob::RETRY_AFTER_0, 4); MakeService(); - group_ = new AppCacheGroup(service_->storage(), - RetryRequestTestJob::kRetryUrl, - service_->storage()->NewGroupId()); + group_ = + new AppCacheGroup(service_->storage(), RetryRequestTestJob::kRetryUrl, + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2027,7 +1978,6 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = false; frontend->AddExpectedEvent( - MockFrontend::HostIds(1, host->host_id()), blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); WaitForUpdateToFinish(); @@ -2041,9 +1991,9 @@ RetryRequestTestJob::Initialize(5, RetryRequestTestJob::NO_RETRY_AFTER, 1); MakeService(); - group_ = new AppCacheGroup(service_->storage(), - RetryRequestTestJob::kRetryUrl, - service_->storage()->NewGroupId()); + group_ = + new AppCacheGroup(service_->storage(), RetryRequestTestJob::kRetryUrl, + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2057,7 +2007,6 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = false; frontend->AddExpectedEvent( - MockFrontend::HostIds(1, host->host_id()), blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); WaitForUpdateToFinish(); @@ -2068,13 +2017,13 @@ // Set some large number of times to return retry. // Expect 1 request and 0 retry attempts. - RetryRequestTestJob::Initialize( - 5, RetryRequestTestJob::NONZERO_RETRY_AFTER, 1); + RetryRequestTestJob::Initialize(5, RetryRequestTestJob::NONZERO_RETRY_AFTER, + 1); MakeService(); - group_ = new AppCacheGroup(service_->storage(), - RetryRequestTestJob::kRetryUrl, - service_->storage()->NewGroupId()); + group_ = + new AppCacheGroup(service_->storage(), RetryRequestTestJob::kRetryUrl, + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2088,7 +2037,6 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = false; frontend->AddExpectedEvent( - MockFrontend::HostIds(1, host->host_id()), blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); WaitForUpdateToFinish(); @@ -2102,9 +2050,9 @@ RetryRequestTestJob::Initialize(2, RetryRequestTestJob::RETRY_AFTER_0, 5); MakeService(); - group_ = new AppCacheGroup(service_->storage(), - RetryRequestTestJob::kRetryUrl, - service_->storage()->NewGroupId()); + group_ = + new AppCacheGroup(service_->storage(), RetryRequestTestJob::kRetryUrl, + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2118,7 +2066,6 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = true; frontend->AddExpectedEvent( - MockFrontend::HostIds(1, host->host_id()), blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); WaitForUpdateToFinish(); @@ -2148,7 +2095,6 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = true; frontend->AddExpectedEvent( - MockFrontend::HostIds(1, host->host_id()), blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); WaitForUpdateToFinish(); @@ -2162,9 +2108,9 @@ reinterpret_cast<MockAppCacheStorage*>(service_->storage()); storage->SimulateStoreGroupAndNewestCacheFailure(); - group_ = new AppCacheGroup( - service_->storage(), MockHttpServer::GetMockUrl("files/manifest1"), - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest1"), + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2178,7 +2124,6 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = false; // storage failed frontend->AddExpectedEvent( - MockFrontend::HostIds(1, host->host_id()), blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); WaitForUpdateToFinish(); @@ -2192,9 +2137,9 @@ reinterpret_cast<MockAppCacheStorage*>(service_->storage()); storage->SimulateStoreGroupAndNewestCacheFailure(); - group_ = new AppCacheGroup( - service_->storage(), MockHttpServer::GetMockUrl("files/manifest1"), - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest1"), + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2214,28 +2159,27 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = true; expect_newest_cache_ = cache; // unchanged - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); WaitForUpdateToFinish(); } @@ -2262,12 +2206,10 @@ const std::string kRawHeaders(kData, base::size(kData)); MakeAppCacheResponseInfo(kManifestUrl, kManifestResponseId, kRawHeaders); - group_ = new AppCacheGroup( - service_->storage(), kManifestUrl, - service_->storage()->NewGroupId()); - scoped_refptr<AppCache> cache( - MakeCacheForGroup(service_->storage()->NewCacheId(), - kManifestResponseId)); + group_ = new AppCacheGroup(service_->storage(), kManifestUrl, + service_->storage()->NewGroupId()); + scoped_refptr<AppCache> cache(MakeCacheForGroup( + service_->storage()->NewCacheId(), kManifestResponseId)); MockFrontend* frontend = MakeMockFrontend(); AppCacheHost* host = MakeHost(1, frontend); @@ -2282,11 +2224,9 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = true; expect_newest_cache_ = cache.get(); // unchanged - MockFrontend::HostIds ids1(1, host->host_id()); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); - frontend->expected_error_message_ = - "Failed to commit new cache to storage"; + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + frontend->expected_error_message_ = "Failed to commit new cache to storage"; WaitForUpdateToFinish(); } @@ -2299,9 +2239,9 @@ reinterpret_cast<MockAppCacheStorage*>(service_->storage()); storage->SimulateMakeGroupObsoleteFailure(); - group_ = new AppCacheGroup( - service_->storage(), MockHttpServer::GetMockUrl("files/nosuchfile"), - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/nosuchfile"), + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2321,16 +2261,15 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = true; expect_newest_cache_ = cache; // newest cache unaffected by update - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); WaitForUpdateToFinish(); } @@ -2353,11 +2292,10 @@ do_checks_after_update_finished_ = true; expect_group_obsolete_ = false; expect_group_has_cache_ = false; - MockFrontend::HostIds ids1(1, host->host_id()); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); WaitForUpdateToFinish(); } @@ -2367,7 +2305,8 @@ MakeService(); group_ = new AppCacheGroup(service_->storage(), - MockHttpServer::GetMockUrl("files/bad-manifest"), 111); + MockHttpServer::GetMockUrl("files/bad-manifest"), + 111); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2381,11 +2320,10 @@ do_checks_after_update_finished_ = true; expect_group_obsolete_ = false; expect_group_has_cache_ = false; - MockFrontend::HostIds ids1(1, host->host_id()); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); WaitForUpdateToFinish(); } @@ -2394,10 +2332,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), - MockHttpServer::GetMockUrl("files/nosuchfile"), - 111); + group_ = + new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/nosuchfile"), 111); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2412,11 +2349,10 @@ do_checks_after_update_finished_ = true; expect_group_obsolete_ = false; expect_group_has_cache_ = false; - MockFrontend::HostIds ids1(1, host->host_id()); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); WaitForUpdateToFinish(); } @@ -2425,7 +2361,8 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup(service_->storage(), + group_ = new AppCacheGroup( + service_->storage(), MockHttpServer::GetMockUrl("files/manifest-fb-404"), 111); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); @@ -2434,8 +2371,7 @@ MockFrontend* frontend = MakeMockFrontend(); frontend->SetIgnoreProgressEvents(true); AppCacheHost* host = MakeHost(1, frontend); - host->new_master_entry_url_ = - MockHttpServer::GetMockUrl("files/explicit1"); + host->new_master_entry_url_ = MockHttpServer::GetMockUrl("files/explicit1"); update->StartUpdate(host, host->new_master_entry_url_); @@ -2443,13 +2379,12 @@ do_checks_after_update_finished_ = true; expect_group_obsolete_ = false; expect_group_has_cache_ = false; // 404 fallback url is cache failure - MockFrontend::HostIds ids1(1, host->host_id()); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); WaitForUpdateToFinish(); } @@ -2458,10 +2393,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), - MockHttpServer::GetMockUrl("files/manifest1"), - 111); + group_ = + new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest1"), 111); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2484,20 +2418,19 @@ do_checks_after_update_finished_ = true; expect_group_obsolete_ = false; expect_group_has_cache_ = false; // all pending masters failed - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); WaitForUpdateToFinish(); } @@ -2506,10 +2439,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), - MockHttpServer::GetMockUrl("files/manifest1"), - 111); + group_ = + new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest1"), 111); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2539,31 +2471,30 @@ expect_group_has_cache_ = true; expect_old_cache_ = cache; tested_manifest_ = MANIFEST1; - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); - MockFrontend::HostIds ids3(1, host3->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); WaitForUpdateToFinish(); } @@ -2572,10 +2503,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), - MockHttpServer::GetMockUrl("files/manifest1"), - 111); + group_ = + new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest1"), 111); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2601,26 +2531,25 @@ expect_extra_entries_.insert(AppCache::EntryMap::value_type( MockHttpServer::GetMockUrl("files/explicit2"), AppCacheEntry(AppCacheEntry::MASTER))); - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_CACHED_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CACHED_EVENT); WaitForUpdateToFinish(); } @@ -2629,10 +2558,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), - MockHttpServer::GetMockUrl("files/manifest1"), - 111); + group_ = + new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest1"), 111); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2664,37 +2592,36 @@ expect_extra_entries_.insert(AppCache::EntryMap::value_type( MockHttpServer::GetMockUrl("files/explicit2"), AppCacheEntry(AppCacheEntry::MASTER))); - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); - MockFrontend::HostIds ids3(1, host3->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); WaitForUpdateToFinish(); } @@ -2703,8 +2630,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup(service_->storage(), - MockHttpServer::GetMockUrl("files/notmodified"), 111); + group_ = + new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/notmodified"), 111); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2728,7 +2656,8 @@ MockHttpServer::GetMockUrl("files/explicit1"); update->StartUpdate(host2, host2->new_master_entry_url_); - AppCacheHost* host3 = MakeHost(3, frontend2); // same frontend as host2 + MockFrontend* frontend3 = MakeMockFrontend(); + AppCacheHost* host3 = MakeHost(3, frontend3); host3->new_master_entry_url_ = MockHttpServer::GetMockUrl("files/explicit2"); update->StartUpdate(host3, host3->new_master_entry_url_); @@ -2740,19 +2669,18 @@ expect_newest_cache_ = cache; // newest cache still the same cache expect_non_null_update_time_ = true; tested_manifest_ = PENDING_MASTER_NO_UPDATE; - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); - MockFrontend::HostIds ids3(1, host3->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); + frontend2->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); - MockFrontend::HostIds ids2and3; - ids2and3.push_back(host2->host_id()); - ids2and3.push_back(host3->host_id()); - frontend2->AddExpectedEvent( - ids2and3, blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); + + frontend3->AddExpectedEvent( + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + frontend3->AddExpectedEvent( + blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); WaitForUpdateToFinish(); } @@ -2761,9 +2689,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), MockHttpServer::GetMockUrl("files/manifest1"), - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest1"), + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2796,11 +2724,11 @@ frontend1->TriggerAdditionalUpdates( blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT, update); - frontend1->AdditionalUpdateHost(host2); // fetch will fail - frontend1->AdditionalUpdateHost(host3); // same as an explicit entry - frontend1->AdditionalUpdateHost(host4); // same as another master entry + frontend1->AdditionalUpdateHost(host2); // fetch will fail + frontend1->AdditionalUpdateHost(host3); // same as an explicit entry + frontend1->AdditionalUpdateHost(host4); // same as another master entry frontend1->AdditionalUpdateHost(nullptr); // no host - frontend1->AdditionalUpdateHost(host5); // no master entry url + frontend1->AdditionalUpdateHost(host5); // no master entry url // Set up checks for when update job finishes. do_checks_after_update_finished_ = true; @@ -2810,59 +2738,57 @@ expect_extra_entries_.insert(AppCache::EntryMap::value_type( MockHttpServer::GetMockUrl("files/explicit2"), AppCacheEntry(AppCacheEntry::MASTER))); - MockFrontend::HostIds ids1(1, host1->host_id()); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CACHED_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_CACHED_EVENT); + frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); - MockFrontend::HostIds ids3(1, host3->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_CACHED_EVENT); - MockFrontend::HostIds ids4(1, host4->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_CACHED_EVENT); + frontend4->AddExpectedEvent( - ids4, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend4->AddExpectedEvent( - ids4, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend4->AddExpectedEvent( - ids4, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend4->AddExpectedEvent( - ids4, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend4->AddExpectedEvent( - ids4, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend4->AddExpectedEvent( - ids4, blink::mojom::AppCacheEventID::APPCACHE_CACHED_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CACHED_EVENT); // Host 5 is not associated with cache so no progress/cached events. - MockFrontend::HostIds ids5(1, host5->host_id()); frontend5->AddExpectedEvent( - ids5, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend5->AddExpectedEvent( - ids5, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); WaitForUpdateToFinish(); } @@ -2871,9 +2797,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), MockHttpServer::GetMockUrl("files/notmodified"), - service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/notmodified"), + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2918,9 +2844,9 @@ blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT, update); frontend2->AdditionalUpdateHost(host3); frontend2->AdditionalUpdateHost(nullptr); // no host - frontend2->AdditionalUpdateHost(host4); // no master entry url - frontend2->AdditionalUpdateHost(host5); // same as existing cache entry - frontend2->AdditionalUpdateHost(host6); // same as another master entry + frontend2->AdditionalUpdateHost(host4); // no master entry url + frontend2->AdditionalUpdateHost(host5); // same as existing cache entry + frontend2->AdditionalUpdateHost(host6); // same as another master entry // Set up checks for when update job finishes. do_checks_after_update_finished_ = true; @@ -2928,32 +2854,33 @@ expect_group_has_cache_ = true; expect_newest_cache_ = cache; // newest cache unaffected by update tested_manifest_ = PENDING_MASTER_NO_UPDATE; - MockFrontend::HostIds ids1(1, host1->host_id()); // prior associated host + // prior associated host frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); + frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); - MockFrontend::HostIds ids3(1, host3->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_ERROR_EVENT); + frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); - MockFrontend::HostIds ids4(1, host4->host_id()); // unassociated w/cache + blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); + + // unassociated w/cache frontend4->AddExpectedEvent( - ids4, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); - MockFrontend::HostIds ids5(1, host5->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + frontend5->AddExpectedEvent( - ids5, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend5->AddExpectedEvent( - ids5, blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); - MockFrontend::HostIds ids6(1, host6->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); + frontend6->AddExpectedEvent( - ids6, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend6->AddExpectedEvent( - ids6, blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT); WaitForUpdateToFinish(); } @@ -2962,10 +2889,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), - MockHttpServer::GetMockUrl("files/manifest1"), - 111); + group_ = + new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest1"), 111); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -2998,11 +2924,11 @@ frontend1->TriggerAdditionalUpdates( blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT, update); - frontend1->AdditionalUpdateHost(host2); // same as entry in manifest + frontend1->AdditionalUpdateHost(host2); // same as entry in manifest frontend1->AdditionalUpdateHost(nullptr); // no host - frontend1->AdditionalUpdateHost(host3); // new master entry - frontend1->AdditionalUpdateHost(host4); // no master entry url - frontend1->AdditionalUpdateHost(host5); // same as another master entry + frontend1->AdditionalUpdateHost(host3); // new master entry + frontend1->AdditionalUpdateHost(host4); // no master entry url + frontend1->AdditionalUpdateHost(host5); // same as another master entry // Set up checks for when update job finishes. do_checks_after_update_finished_ = true; @@ -3012,57 +2938,58 @@ expect_extra_entries_.insert(AppCache::EntryMap::value_type( MockHttpServer::GetMockUrl("files/explicit2"), AppCacheEntry(AppCacheEntry::MASTER))); - MockFrontend::HostIds ids1(1, host1->host_id()); // prior associated host + // prior associated host frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend1->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); - MockFrontend::HostIds ids2(1, host2->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend2->AddExpectedEvent( - ids2, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); - MockFrontend::HostIds ids3(1, host3->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend3->AddExpectedEvent( - ids3, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); - MockFrontend::HostIds ids4(1, host4->host_id()); // unassociated w/cache + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + + // unassociated w/cache frontend4->AddExpectedEvent( - ids4, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend4->AddExpectedEvent( - ids4, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); - MockFrontend::HostIds ids5(1, host5->host_id()); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + frontend5->AddExpectedEvent( - ids5, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend5->AddExpectedEvent( - ids5, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend5->AddExpectedEvent( - ids5, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend5->AddExpectedEvent( - ids5, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend5->AddExpectedEvent( - ids5, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); WaitForUpdateToFinish(); } @@ -3071,10 +2998,9 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), - MockHttpServer::GetMockUrl("files/manifest1"), - 111); + group_ = + new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest1"), 111); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -3087,8 +3013,7 @@ // Start an update. Should be queued. MockFrontend* frontend = MakeMockFrontend(); AppCacheHost* host = MakeHost(1, frontend); - host->new_master_entry_url_ = - MockHttpServer::GetMockUrl("files/explicit2"); + host->new_master_entry_url_ = MockHttpServer::GetMockUrl("files/explicit2"); update->StartUpdate(host, host->new_master_entry_url_); EXPECT_TRUE(update->pending_master_entries_.empty()); EXPECT_FALSE(group_->queued_updates_.empty()); @@ -3105,19 +3030,18 @@ tested_manifest_ = MANIFEST1; expect_extra_entries_.insert(AppCache::EntryMap::value_type( host->new_master_entry_url_, AppCacheEntry(AppCacheEntry::MASTER))); - MockFrontend::HostIds ids1(1, host->host_id()); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CACHED_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CACHED_EVENT); // Group status will be blink::mojom::AppCacheStatus::APPCACHE_STATUS_IDLE // so cannot call WaitForUpdateToFinish. @@ -3133,8 +3057,8 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), GURL("http://headertest"), 111); + group_ = + new AppCacheGroup(service_->storage(), GURL("http://headertest"), 111); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -3144,7 +3068,8 @@ HttpHeadersRequestTestJob::Initialize(std::string(), std::string()); MockFrontend mock_frontend; AppCacheHost host(/*host_id=*/1, /*process_id=*/1, /*render_frame_id=*/1, - &mock_frontend, service_.get()); + nullptr, service_.get()); + host.set_frontend_for_testing(&mock_frontend); update->StartUpdate(&host, GURL()); // We need to wait for the URL load requests to make it to the @@ -3245,10 +3170,9 @@ std::string()); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), - MockHttpServer::GetMockUrl("files/manifest1"), - 111); + group_ = + new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest1"), 111); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -3269,19 +3193,18 @@ expect_group_has_cache_ = true; expect_old_cache_ = cache; tested_manifest_ = MANIFEST1; - MockFrontend::HostIds ids1(1, host->host_id()); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); // Seed storage with expected manifest response info that will cause // an If-Modified-Since header to be put in the manifest fetch request. @@ -3313,10 +3236,9 @@ HttpHeadersRequestTestJob::Initialize(std::string(), "\"LadeDade\""); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), - MockHttpServer::GetMockUrl("files/manifest1"), - 111); + group_ = + new AppCacheGroup(service_->storage(), + MockHttpServer::GetMockUrl("files/manifest1"), 111); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -3337,19 +3259,18 @@ expect_group_has_cache_ = true; expect_old_cache_ = cache; tested_manifest_ = MANIFEST1; - MockFrontend::HostIds ids1(1, host->host_id()); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final + blink::mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT); // final frontend->AddExpectedEvent( - ids1, blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT); // Seed storage with expected manifest response info that will cause // an If-None-Match header to be put in the manifest fetch request. @@ -3381,8 +3302,8 @@ HttpHeadersRequestTestJob::Initialize(std::string(), "\"LadeDade\""); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), GURL("http://headertest"), 111); + group_ = + new AppCacheGroup(service_->storage(), GURL("http://headertest"), 111); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -3418,12 +3339,12 @@ ASSERT_TRUE(base::MessageLoopCurrentForIO::IsSet()); // Verify that code is correct when building multiple extra headers. - HttpHeadersRequestTestJob::Initialize( - "Sat, 29 Oct 1994 19:43:31 GMT", "\"LadeDade\""); + HttpHeadersRequestTestJob::Initialize("Sat, 29 Oct 1994 19:43:31 GMT", + "\"LadeDade\""); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), GURL("http://headertest"), 111); + group_ = + new AppCacheGroup(service_->storage(), GURL("http://headertest"), 111); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -3463,8 +3384,8 @@ "files/valid_cross_origin_https_manifest"); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), manifest_url, service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), manifest_url, + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -3478,9 +3399,8 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = true; tested_manifest_ = NONE; - MockFrontend::HostIds host_ids(1, host->host_id()); frontend->AddExpectedEvent( - host_ids, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); WaitForUpdateToFinish(); } @@ -3492,8 +3412,8 @@ "files/invalid_cross_origin_https_manifest"); MakeService(); - group_ = new AppCacheGroup( - service_->storage(), manifest_url, service_->storage()->NewGroupId()); + group_ = new AppCacheGroup(service_->storage(), manifest_url, + service_->storage()->NewGroupId()); AppCacheUpdateJob* update = new AppCacheUpdateJob(service_.get(), group_.get()); group_->update_job_ = update; @@ -3507,9 +3427,8 @@ expect_group_obsolete_ = false; expect_group_has_cache_ = false; tested_manifest_ = NONE; - MockFrontend::HostIds host_ids(1, host->host_id()); frontend->AddExpectedEvent( - host_ids, blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); + blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT); WaitForUpdateToFinish(); } @@ -3573,8 +3492,8 @@ group_->set_last_full_update_check_time(cache->update_time()); // Add manifest entry to cache. - cache->AddEntry(manifest_entry_url, - AppCacheEntry(AppCacheEntry::MANIFEST, manifest_response_id)); + cache->AddEntry(manifest_entry_url, AppCacheEntry(AppCacheEntry::MANIFEST, + manifest_response_id)); // Specific tests that expect a newer time should set // expect_full_update_time_newer_than_ which causes this @@ -3590,7 +3509,8 @@ constexpr int kRenderFrameIdForTests = 456; hosts_.push_back(std::make_unique<AppCacheHost>(host_id, kProcessIdForTests, kRenderFrameIdForTests, - frontend, service_.get())); + nullptr, service_.get())); + hosts_.back()->set_frontend_for_testing(frontend); return hosts_.back().get(); } @@ -3694,26 +3614,16 @@ MockFrontend::RaisedEvents& expected_events = frontend->expected_events_; MockFrontend::RaisedEvents& actual_events = frontend->raised_events_; - EXPECT_EQ(expected_events.size(), actual_events.size()); + ASSERT_EQ(expected_events.size(), actual_events.size()); // Check each expected event. - for (size_t j = 0; - j < expected_events.size() && j < actual_events.size(); ++j) { - EXPECT_EQ(expected_events[j].second, actual_events[j].second); - - MockFrontend::HostIds& expected_ids = expected_events[j].first; - MockFrontend::HostIds& actual_ids = actual_events[j].first; - EXPECT_EQ(expected_ids.size(), actual_ids.size()); - - for (size_t k = 0; k < expected_ids.size(); ++k) { - int id = expected_ids[k]; - EXPECT_TRUE(base::ContainsValue(actual_ids, id)); - } + for (size_t j = 0; j < expected_events.size() && j < actual_events.size(); + ++j) { + EXPECT_EQ(expected_events[j], actual_events[j]); } if (!frontend->expected_error_message_.empty()) { - EXPECT_EQ(frontend->expected_error_message_, - frontend->error_message_); + EXPECT_EQ(frontend->expected_error_message_, frontend->error_message_); } } @@ -3754,9 +3664,9 @@ void VerifyManifest1(AppCache* cache) { size_t expected = 3 + expect_extra_entries_.size(); EXPECT_EQ(expected, cache->entries().size()); - const char* kManifestPath = tested_manifest_path_override_ ? - tested_manifest_path_override_ : - "files/manifest1"; + const char* kManifestPath = tested_manifest_path_override_ + ? tested_manifest_path_override_ + : "files/manifest1"; AppCacheEntry* entry = cache->GetEntry(MockHttpServer::GetMockUrl(kManifestPath)); ASSERT_TRUE(entry); @@ -3764,8 +3674,7 @@ entry = cache->GetEntry(MockHttpServer::GetMockUrl("files/explicit1")); ASSERT_TRUE(entry); EXPECT_TRUE(entry->IsExplicit()); - entry = cache->GetEntry( - MockHttpServer::GetMockUrl("files/fallback1a")); + entry = cache->GetEntry(MockHttpServer::GetMockUrl("files/fallback1a")); ASSERT_TRUE(entry); EXPECT_EQ(AppCacheEntry::FALLBACK, entry->types()); @@ -3778,11 +3687,10 @@ expected = 1; ASSERT_EQ(expected, cache->fallback_namespaces_.size()); EXPECT_TRUE(cache->fallback_namespaces_[0] == - AppCacheNamespace( - APPCACHE_FALLBACK_NAMESPACE, - MockHttpServer::GetMockUrl("files/fallback1"), - MockHttpServer::GetMockUrl("files/fallback1a"), - false)); + AppCacheNamespace( + APPCACHE_FALLBACK_NAMESPACE, + MockHttpServer::GetMockUrl("files/fallback1"), + MockHttpServer::GetMockUrl("files/fallback1a"), false)); EXPECT_TRUE(cache->online_whitelist_namespaces_.empty()); EXPECT_TRUE(cache->online_whitelist_all_); @@ -3801,36 +3709,35 @@ entry = cache->GetEntry(MockHttpServer::GetMockUrl("files/explicit1")); ASSERT_TRUE(entry); EXPECT_EQ(AppCacheEntry::EXPLICIT | AppCacheEntry::FALLBACK | - AppCacheEntry::MASTER, entry->types()); + AppCacheEntry::MASTER, + entry->types()); expected = 1; ASSERT_EQ(expected, cache->fallback_namespaces_.size()); EXPECT_TRUE(cache->fallback_namespaces_[0] == - AppCacheNamespace( - APPCACHE_FALLBACK_NAMESPACE, - MockHttpServer::GetMockUrl("files/fallback1"), - MockHttpServer::GetMockUrl("files/explicit1"), - false)); + AppCacheNamespace(APPCACHE_FALLBACK_NAMESPACE, + MockHttpServer::GetMockUrl("files/fallback1"), + MockHttpServer::GetMockUrl("files/explicit1"), + false)); EXPECT_EQ(expected, cache->online_whitelist_namespaces_.size()); EXPECT_TRUE(cache->online_whitelist_namespaces_[0] == - AppCacheNamespace( - APPCACHE_NETWORK_NAMESPACE, - MockHttpServer::GetMockUrl("files/online1"), - GURL(), false)); + AppCacheNamespace(APPCACHE_NETWORK_NAMESPACE, + MockHttpServer::GetMockUrl("files/online1"), + GURL(), false)); EXPECT_FALSE(cache->online_whitelist_all_); EXPECT_TRUE(cache->update_time_ > base::Time()); } void VerifyEmptyManifest(AppCache* cache) { - const char* kManifestPath = tested_manifest_path_override_ ? - tested_manifest_path_override_ : - "files/empty-manifest"; + const char* kManifestPath = tested_manifest_path_override_ + ? tested_manifest_path_override_ + : "files/empty-manifest"; size_t expected = 1; EXPECT_EQ(expected, cache->entries().size()); - AppCacheEntry* entry = cache->GetEntry( - MockHttpServer::GetMockUrl(kManifestPath)); + AppCacheEntry* entry = + cache->GetEntry(MockHttpServer::GetMockUrl(kManifestPath)); ASSERT_TRUE(entry); EXPECT_EQ(AppCacheEntry::MANIFEST, entry->types()); @@ -3848,8 +3755,7 @@ ASSERT_TRUE(entry); EXPECT_EQ(AppCacheEntry::MANIFEST, entry->types()); - entry = cache->GetEntry( - MockHttpServer::GetMockUrl("files/empty1")); + entry = cache->GetEntry(MockHttpServer::GetMockUrl("files/empty1")); ASSERT_TRUE(entry); EXPECT_EQ(AppCacheEntry::EXPLICIT, entry->types()); EXPECT_TRUE(entry->has_response_id()); @@ -3863,19 +3769,17 @@ void VerifyMasterEntryNoUpdate(AppCache* cache) { EXPECT_EQ(size_t(3), cache->entries().size()); - AppCacheEntry* entry = cache->GetEntry( - MockHttpServer::GetMockUrl("files/notmodified")); + AppCacheEntry* entry = + cache->GetEntry(MockHttpServer::GetMockUrl("files/notmodified")); ASSERT_TRUE(entry); EXPECT_EQ(AppCacheEntry::MANIFEST, entry->types()); - entry = cache->GetEntry( - MockHttpServer::GetMockUrl("files/explicit1")); + entry = cache->GetEntry(MockHttpServer::GetMockUrl("files/explicit1")); ASSERT_TRUE(entry); EXPECT_EQ(AppCacheEntry::MASTER, entry->types()); EXPECT_TRUE(entry->has_response_id()); - entry = cache->GetEntry( - MockHttpServer::GetMockUrl("files/explicit2")); + entry = cache->GetEntry(MockHttpServer::GetMockUrl("files/explicit2")); ASSERT_TRUE(entry); EXPECT_EQ(AppCacheEntry::EXPLICIT | AppCacheEntry::MASTER, entry->types()); EXPECT_TRUE(entry->has_response_id()); @@ -3973,16 +3877,13 @@ MockFrontend mock_frontend; AppCacheHost host(/*host_id=*/1, /*process_id=*/1, /*render_frame_id=*/1, - &mock_frontend, &service); + nullptr, &service); + host.set_frontend_for_testing(&mock_frontend); update.StartUpdate(&host, GURL()); MockFrontend::RaisedEvents events = mock_frontend.raised_events_; - size_t expected = 1; - EXPECT_EQ(expected, events.size()); - EXPECT_EQ(expected, events[0].first.size()); - EXPECT_EQ(host.host_id(), events[0].first[0]); - EXPECT_EQ(blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT, - events[0].second); + ASSERT_EQ(1u, events.size()); + EXPECT_EQ(blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT, events[0]); EXPECT_EQ(AppCacheGroup::CHECKING, group->update_status()); } @@ -4003,22 +3904,15 @@ MockFrontend mock_frontend; AppCacheHost host(/*host_id=*/1, /*process_id=*/1, /*render_frame_id=*/1, - &mock_frontend, &service); + nullptr, &service); + host.set_frontend_for_testing(&mock_frontend); update.StartUpdate(&host, GURL()); MockFrontend::RaisedEvents events = mock_frontend.raised_events_; - size_t expected = 2; - EXPECT_EQ(expected, events.size()); - expected = 1; - EXPECT_EQ(expected, events[0].first.size()); - EXPECT_EQ(host.host_id(), events[0].first[0]); - EXPECT_EQ(blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT, - events[0].second); - - EXPECT_EQ(expected, events[1].first.size()); - EXPECT_EQ(host.host_id(), events[1].first[0]); + ASSERT_EQ(2u, events.size()); + EXPECT_EQ(blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT, events[0]); EXPECT_EQ(blink::mojom::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT, - events[1].second); + events[1]); EXPECT_EQ(AppCacheGroup::DOWNLOADING, group->update_status()); }
diff --git a/content/browser/appcache/appcache_url_request_job.cc b/content/browser/appcache/appcache_url_request_job.cc index fff66184..1670307 100644 --- a/content/browser/appcache/appcache_url_request_job.cc +++ b/content/browser/appcache/appcache_url_request_job.cc
@@ -169,9 +169,10 @@ } void AppCacheURLRequestJob::BeginErrorDelivery(const char* message) { - if (host_) - host_->frontend()->LogMessage( - host_->host_id(), blink::mojom::ConsoleMessageLevel::kError, message); + if (host_) { + host_->frontend()->LogMessage(blink::mojom::ConsoleMessageLevel::kError, + message); + } delivery_type_ = DeliveryType::kError; storage_ = nullptr; BeginDelivery();
diff --git a/content/browser/blob_storage/chrome_blob_storage_context.cc b/content/browser/blob_storage/chrome_blob_storage_context.cc index 8c5b2fc..5610c0d 100644 --- a/content/browser/blob_storage/chrome_blob_storage_context.cc +++ b/content/browser/blob_storage/chrome_blob_storage_context.cc
@@ -243,16 +243,7 @@ return blob_ptr; } -ChromeBlobStorageContext::~ChromeBlobStorageContext() {} - -void ChromeBlobStorageContext::DeleteOnCorrectThread() const { - if (BrowserThread::IsThreadInitialized(BrowserThread::IO) && - !BrowserThread::CurrentlyOn(BrowserThread::IO)) { - BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this); - return; - } - delete this; -} +ChromeBlobStorageContext::~ChromeBlobStorageContext() = default; storage::BlobStorageContext* GetBlobStorageContext( ChromeBlobStorageContext* blob_storage_context) {
diff --git a/content/browser/blob_storage/chrome_blob_storage_context.h b/content/browser/blob_storage/chrome_blob_storage_context.h index 26cf1eb..afd21be63 100644 --- a/content/browser/blob_storage/chrome_blob_storage_context.h +++ b/content/browser/blob_storage/chrome_blob_storage_context.h
@@ -15,6 +15,7 @@ #include "base/memory/ref_counted.h" #include "base/sequenced_task_runner_helpers.h" #include "content/common/content_export.h" +#include "content/public/browser/browser_thread.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "storage/browser/blob/blob_data_handle.h" #include "third_party/blink/public/mojom/blob/blob_url_store.mojom.h" @@ -34,7 +35,6 @@ namespace content { class BlobHandle; class BrowserContext; -struct ChromeBlobStorageContextDeleter; class ResourceContext; // A context class that keeps track of BlobStorageController used by the chrome. @@ -46,7 +46,7 @@ // the IO thread (unless specifically called out in doc comments). class CONTENT_EXPORT ChromeBlobStorageContext : public base::RefCountedThreadSafe<ChromeBlobStorageContext, - ChromeBlobStorageContextDeleter> { + BrowserThread::DeleteOnIOThread> { public: ChromeBlobStorageContext(); @@ -95,22 +95,12 @@ virtual ~ChromeBlobStorageContext(); private: + friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>; friend class base::DeleteHelper<ChromeBlobStorageContext>; - friend class base::RefCountedThreadSafe<ChromeBlobStorageContext, - ChromeBlobStorageContextDeleter>; - friend struct ChromeBlobStorageContextDeleter; - - void DeleteOnCorrectThread() const; std::unique_ptr<storage::BlobStorageContext> context_; }; -struct ChromeBlobStorageContextDeleter { - static void Destruct(const ChromeBlobStorageContext* context) { - context->DeleteOnCorrectThread(); - } -}; - // Returns the BlobStorageContext associated with the // ChromeBlobStorageContext instance passed in. storage::BlobStorageContext* GetBlobStorageContext(
diff --git a/content/browser/browser_child_process_host_impl.cc b/content/browser/browser_child_process_host_impl.cc index fdf81747..2bb0d19 100644 --- a/content/browser/browser_child_process_host_impl.cc +++ b/content/browser/browser_child_process_host_impl.cc
@@ -603,7 +603,7 @@ DCHECK(process.IsValid()); if (child_connection_) - child_connection_->SetProcessHandle(process.Handle()); + child_connection_->SetProcess(process.Duplicate()); #if defined(OS_WIN) // Start a WaitableEventWatcher that will invoke OnProcessExitedEarly if the
diff --git a/content/browser/browser_thread_unittest.cc b/content/browser/browser_thread_unittest.cc index c9d13aa3..7b44ad6 100644 --- a/content/browser/browser_thread_unittest.cc +++ b/content/browser/browser_thread_unittest.cc
@@ -28,6 +28,41 @@ namespace content { +namespace { + +class SequenceManagerTaskEnvironment : public base::Thread::TaskEnvironment { + public: + SequenceManagerTaskEnvironment( + std::unique_ptr<base::sequence_manager::SequenceManager> sequence_manager, + scoped_refptr<base::SingleThreadTaskRunner> default_task_runner) + : sequence_manager_(std::move(sequence_manager)), + default_task_runner_(std::move(default_task_runner)) { + sequence_manager_->SetDefaultTaskRunner(default_task_runner_); + } + + ~SequenceManagerTaskEnvironment() override {} + + // Thread::TaskEnvironment: + scoped_refptr<base::SingleThreadTaskRunner> GetDefaultTaskRunner() override { + return default_task_runner_; + } + + void BindToCurrentThread(base::TimerSlack timer_slack) override { + sequence_manager_->BindToMessagePump( + base::MessageLoop::CreateMessagePumpForType( + base::MessageLoop::TYPE_DEFAULT)); + sequence_manager_->SetTimerSlack(timer_slack); + } + + private: + std::unique_ptr<base::sequence_manager::SequenceManager> sequence_manager_; + scoped_refptr<base::SingleThreadTaskRunner> default_task_runner_; + + DISALLOW_COPY_AND_ASSIGN(SequenceManagerTaskEnvironment); +}; + +} // namespace + class BrowserThreadTest : public testing::Test { public: void Release() const { @@ -50,14 +85,15 @@ std::unique_ptr<BrowserUIThreadScheduler> browser_ui_thread_scheduler = BrowserUIThreadScheduler::CreateForTesting( sequence_manager.get(), sequence_manager->GetRealTimeDomain()); - sequence_manager->SetDefaultTaskRunner( - browser_ui_thread_scheduler->GetTaskRunnerForTesting( - BrowserUIThreadScheduler::QueueType::kDefault)); - BrowserTaskExecutor::CreateWithBrowserUIThreadSchedulerForTesting( - std::move(browser_ui_thread_scheduler)); base::Thread::Options ui_options; - ui_options.message_loop_base = sequence_manager.release(); + ui_options.task_environment = new SequenceManagerTaskEnvironment( + std::move(sequence_manager), + browser_ui_thread_scheduler->GetTaskRunnerForTesting( + BrowserUIThreadScheduler::QueueType::kDefault)); + + BrowserTaskExecutor::CreateWithBrowserUIThreadSchedulerForTesting( + std::move(browser_ui_thread_scheduler)); ui_thread_->StartWithOptions(ui_options); io_thread_ = std::make_unique<BrowserProcessSubThread>(BrowserThread::IO);
diff --git a/content/browser/devtools/protocol/network_handler.cc b/content/browser/devtools/protocol/network_handler.cc index 8abb1b1..483ad51 100644 --- a/content/browser/devtools/protocol/network_handler.cc +++ b/content/browser/devtools/protocol/network_handler.cc
@@ -371,11 +371,14 @@ normalized_domain, path, std::move(callback))); } -void CookieSetOnIO(std::unique_ptr<SetCookieCallback> callback, bool success) { +void CookieSetOnIO(std::unique_ptr<SetCookieCallback> callback, + net::CanonicalCookie::CookieInclusionStatus status) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&SetCookieCallback::sendSuccess, - std::move(callback), success)); + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::UI}, + base::BindOnce( + &SetCookieCallback::sendSuccess, std::move(callback), + (status == net::CanonicalCookie::CookieInclusionStatus::INCLUDE))); } void DeleteFilteredCookies(network::mojom::CookieManager* cookie_manager, @@ -445,9 +448,11 @@ base::Time(), secure, http_only, css, net::COOKIE_PRIORITY_DEFAULT); } -void SetCookieOnIO(net::URLRequestContextGetter* context_getter, - std::unique_ptr<net::CanonicalCookie> cookie, - base::OnceCallback<void(bool)> callback) { +void SetCookieOnIO( + net::URLRequestContextGetter* context_getter, + std::unique_ptr<net::CanonicalCookie> cookie, + base::OnceCallback<void(net::CanonicalCookie::CookieInclusionStatus)> + callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService)); net::URLRequestContext* request_context = @@ -474,10 +479,12 @@ base::RepeatingClosure barrier_closure = base::BarrierClosure(cookies.size(), std::move(callback)); for (auto& cookie : cookies) { - SetCookieOnIO(context_getter, std::move(cookie), - base::BindOnce([](base::RepeatingClosure callback, - bool) { callback.Run(); }, - barrier_closure)); + SetCookieOnIO( + context_getter, std::move(cookie), + base::BindOnce( + [](base::RepeatingClosure callback, + net::CanonicalCookie::CookieInclusionStatus) { callback.Run(); }, + barrier_closure)); } }
diff --git a/content/browser/frame_host/ipc_utils.cc b/content/browser/frame_host/ipc_utils.cc index 7fa9e97..53006c9f 100644 --- a/content/browser/frame_host/ipc_utils.cc +++ b/content/browser/frame_host/ipc_utils.cc
@@ -15,6 +15,7 @@ #include "content/public/browser/render_process_host.h" #include "content/public/browser/site_instance.h" #include "content/public/common/child_process_host.h" +#include "content/public/common/url_constants.h" #include "mojo/public/cpp/system/message_pipe.h" namespace content { @@ -82,6 +83,7 @@ if (!VerifyInitiatorOrigin(process_id, params.initiator_origin)) return false; + // Verification succeeded. return true; } @@ -128,6 +130,49 @@ if (!VerifyInitiatorOrigin(process_id, params.initiator_origin)) return false; + // Verification succeeded. + return true; +} + +bool VerifyBeginNavigationCommonParams(SiteInstance* site_instance, + CommonNavigationParams* common_params) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(site_instance); + DCHECK(common_params); + RenderProcessHost* process = site_instance->GetProcess(); + int process_id = process->GetID(); + + // Verify (and possibly rewrite) |url|. + process->FilterURL(false, &common_params->url); + if (common_params->url.SchemeIs(kChromeErrorScheme)) { + mojo::ReportBadMessage("Renderer cannot request error page URLs directly"); + return false; + } + + // Verify |resource_request_body|. + auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); + if (!policy->CanReadRequestBody(site_instance, common_params->post_data)) { + bad_message::ReceivedBadMessage(process, + bad_message::ILLEGAL_UPLOAD_PARAMS); + return false; + } + + // Verify |initiator_origin|. + if (common_params->initiator_origin.has_value() && + !VerifyInitiatorOrigin(process_id, + common_params->initiator_origin.value())) { + return false; + } + + // Verify |base_url_for_data_url|. + if (!common_params->base_url_for_data_url.is_empty()) { + // Kills the process. http://crbug.com/726142 + bad_message::ReceivedBadMessage( + process, bad_message::RFH_BASE_URL_FOR_DATA_URL_SPECIFIED); + return false; + } + + // Verification succeeded. return true; }
diff --git a/content/browser/frame_host/ipc_utils.h b/content/browser/frame_host/ipc_utils.h index 5263264..8f72e42 100644 --- a/content/browser/frame_host/ipc_utils.h +++ b/content/browser/frame_host/ipc_utils.h
@@ -48,6 +48,20 @@ scoped_refptr<network::SharedURLLoaderFactory>* out_blob_url_loader_factory); +// Verifies that CommonNavigationParams are valid and can be accessed by the +// renderer process associated with |site_instance|. +// +// Returns true if the CommonNavigationParams are valid. As a side-effect of +// the verification parts of |common_params| will be rewritten (e.g. some +// URLs will be filtered). +// +// Terminates the renderer the process associated with |site_instance| and +// returns false if the CommonNavigationParams are invalid. +// +// This function has to be called on the UI thread. +bool VerifyBeginNavigationCommonParams(SiteInstance* site_instance, + CommonNavigationParams* common_params); + } // namespace content #endif // CONTENT_BROWSER_FRAME_HOST_IPC_UTILS_H_
diff --git a/content/browser/frame_host/navigation_controller_impl_browsertest.cc b/content/browser/frame_host/navigation_controller_impl_browsertest.cc index ffbd16c..13f3c3f 100644 --- a/content/browser/frame_host/navigation_controller_impl_browsertest.cc +++ b/content/browser/frame_host/navigation_controller_impl_browsertest.cc
@@ -65,7 +65,7 @@ #include "content/shell/browser/shell_download_manager_delegate.h" #include "content/shell/common/shell_switches.h" #include "content/test/content_browser_test_utils_internal.h" -#include "content/test/did_commit_provisional_load_interceptor.h" +#include "content/test/frame_host_interceptor.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/controllable_http_response.h" #include "net/test/embedded_test_server/embedded_test_server.h" @@ -6973,12 +6973,11 @@ // renderer has committed a same-process and cross-origin navigation to the // given |url|, but before the browser side has had a chance to process the // DidCommitProvisionalLoad message. -class HistoryNavigationBeforeCommitInjector - : public DidCommitProvisionalLoadInterceptor { +class HistoryNavigationBeforeCommitInjector : public FrameHostInterceptor { public: HistoryNavigationBeforeCommitInjector(WebContentsImpl* web_contents, const GURL& url) - : DidCommitProvisionalLoadInterceptor(web_contents), + : FrameHostInterceptor(web_contents), did_trigger_history_navigation_(false), url_(url) {} ~HistoryNavigationBeforeCommitInjector() override {} @@ -6988,11 +6987,11 @@ } private: - // DidCommitProvisionalLoadInterceptor: + // FrameHostInterceptor: bool WillDispatchDidCommitProvisionalLoad( RenderFrameHost* render_frame_host, ::FrameHostMsg_DidCommitProvisionalLoad_Params* params, - mojom::DidCommitProvisionalLoadInterfaceParamsPtr& interface_params) + mojom::DidCommitProvisionalLoadInterfaceParamsPtr* interface_params) override { if (!render_frame_host->GetParent() && params->url == url_) { did_trigger_history_navigation_ = true;
diff --git a/content/browser/frame_host/navigation_handle_impl.cc b/content/browser/frame_host/navigation_handle_impl.cc index 88da921..46044aa 100644 --- a/content/browser/frame_host/navigation_handle_impl.cc +++ b/content/browser/frame_host/navigation_handle_impl.cc
@@ -1111,10 +1111,12 @@ RenderProcessHost* renderer_host = GetRenderFrameHost()->GetRenderWidgetHost()->GetProcess(); - render_process_blocked_state_changed_subscription_ = - renderer_host->RegisterBlockStateChangedCallback(base::BindRepeating( - &NavigationHandleImpl::RenderProcessBlockedStateChanged, - base::Unretained(this))); + if (!render_process_blocked_state_changed_subscription_) { + render_process_blocked_state_changed_subscription_ = + renderer_host->RegisterBlockStateChangedCallback(base::BindRepeating( + &NavigationHandleImpl::RenderProcessBlockedStateChanged, + base::Unretained(this))); + } if (!renderer_host->IsBlocked()) commit_timeout_timer_.Start( FROM_HERE, g_commit_timeout,
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index 8d44d70..5b7b02e 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -1349,7 +1349,7 @@ if (!render_frame_created_) return false; - // Crash reports trigerred by IPC messages for this frame should be associated + // Crash reports triggered by IPC messages for this frame should be associated // with its URL. // TODO(lukasza): Also call SetActiveURL for mojo messages dispatched to // either the FrameHost interface or to interfaces bound by this frame. @@ -3808,28 +3808,11 @@ DCHECK(IsPerNavigationMojoInterfaceEnabled() == navigation_client.is_valid()); CommonNavigationParams validated_params = common_params; - GetProcess()->FilterURL(false, &validated_params.url); - if (!validated_params.base_url_for_data_url.is_empty()) { - // Kills the process. http://crbug.com/726142 - bad_message::ReceivedBadMessage( - GetProcess(), bad_message::RFH_BASE_URL_FOR_DATA_URL_SPECIFIED); + if (!VerifyBeginNavigationCommonParams(GetSiteInstance(), &validated_params)) return; - } GetProcess()->FilterURL(true, &begin_params->searchable_form_url); - if (!ChildProcessSecurityPolicyImpl::GetInstance()->CanReadRequestBody( - GetSiteInstance(), validated_params.post_data)) { - bad_message::ReceivedBadMessage(GetProcess(), - bad_message::ILLEGAL_UPLOAD_PARAMS); - return; - } - - if (validated_params.url.SchemeIs(kChromeErrorScheme)) { - mojo::ReportBadMessage("Renderer cannot request error page URLs directly"); - return; - } - // If the request was for a blob URL, but the validated URL is no longer a // blob URL, reset the blob_url_token to prevent hitting the ReportBadMessage // below, and to make sure we don't incorrectly try to use the blob_url_token.
diff --git a/content/browser/frame_host/render_frame_host_impl_browsertest.cc b/content/browser/frame_host/render_frame_host_impl_browsertest.cc index 510aab1..9d223f4e 100644 --- a/content/browser/frame_host/render_frame_host_impl_browsertest.cc +++ b/content/browser/frame_host/render_frame_host_impl_browsertest.cc
@@ -36,7 +36,7 @@ #include "content/public/test/test_utils.h" #include "content/shell/browser/shell.h" #include "content/test/content_browser_test_utils_internal.h" -#include "content/test/did_commit_provisional_load_interceptor.h" +#include "content/test/frame_host_interceptor.h" #include "content/test/frame_host_test_interface.mojom.h" #include "content/test/test_content_browser_client.h" #include "net/dns/mock_host_resolver.h" @@ -1354,11 +1354,10 @@ // Allows injecting a fake, test-provided |interface_provider_request| into // DidCommitProvisionalLoad messages in a given |web_contents| instead of the // real one coming from the renderer process. -class ScopedFakeInterfaceProviderRequestInjector - : public DidCommitProvisionalLoadInterceptor { +class ScopedFakeInterfaceProviderRequestInjector : public FrameHostInterceptor { public: explicit ScopedFakeInterfaceProviderRequestInjector(WebContents* web_contents) - : DidCommitProvisionalLoadInterceptor(web_contents) {} + : FrameHostInterceptor(web_contents) {} ~ScopedFakeInterfaceProviderRequestInjector() override = default; // Sets the fake InterfaceProvider |request| to inject into the next incoming @@ -1379,13 +1378,13 @@ bool WillDispatchDidCommitProvisionalLoad( RenderFrameHost* render_frame_host, ::FrameHostMsg_DidCommitProvisionalLoad_Params* params, - mojom::DidCommitProvisionalLoadInterfaceParamsPtr& interface_params) + mojom::DidCommitProvisionalLoadInterfaceParamsPtr* interface_params) override { url_of_last_commit_ = params->url; - if (interface_params) { + if (*interface_params) { original_request_of_last_commit_ = - std::move(interface_params->interface_provider_request); - interface_params->interface_provider_request = + std::move((*interface_params)->interface_provider_request); + (*interface_params)->interface_provider_request = std::move(next_fake_request_); } return true;
diff --git a/content/browser/frame_host/render_frame_host_manager_browsertest.cc b/content/browser/frame_host/render_frame_host_manager_browsertest.cc index e9768e0..3e08d82 100644 --- a/content/browser/frame_host/render_frame_host_manager_browsertest.cc +++ b/content/browser/frame_host/render_frame_host_manager_browsertest.cc
@@ -20,6 +20,7 @@ #include "base/single_thread_task_runner.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/bind_test_util.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "base/values.h" @@ -54,6 +55,7 @@ #include "content/public/test/navigation_handle_observer.h" #include "content/public/test/test_frame_navigation_observer.h" #include "content/public/test/test_navigation_observer.h" +#include "content/public/test/test_navigation_throttle.h" #include "content/public/test/test_navigation_throttle_inserter.h" #include "content/public/test/test_utils.h" #include "content/public/test/url_loader_interceptor.h" @@ -141,6 +143,30 @@ RenderFrameHost* render_frame_host_; }; +// A NavigationThrottle implementation that blocks all outgoing navigation +// requests for a specific WebContents. It is used to block navigations to +// WebUI URLs in the following test. +class RequestBlockingNavigationThrottle : public NavigationThrottle { + public: + explicit RequestBlockingNavigationThrottle(NavigationHandle* handle) + : NavigationThrottle(handle) {} + + static std::unique_ptr<NavigationThrottle> Create(NavigationHandle* handle) { + return std::make_unique<RequestBlockingNavigationThrottle>(handle); + } + + private: + ThrottleCheckResult WillStartRequest() override { + return NavigationThrottle::BLOCK_REQUEST; + } + + const char* GetNameForLogging() override { + return "RequestBlockingNavigationThrottle"; + } + + DISALLOW_COPY_AND_ASSIGN(RequestBlockingNavigationThrottle); +}; + } // anonymous namespace class RenderFrameHostManagerTest : public ContentBrowserTest { @@ -4449,6 +4475,192 @@ shell()->web_contents()->GetMainFrame()->GetLastCommittedOrigin()); } +// Version of ErrorPageNavigationReload test that targets a subframe (because +// subframes are currently [~2019Q1] not subject to error page isolation). +IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, + ErrorPageNavigationReload_InSubframe_NetworkError) { + StartEmbeddedServer(); + + // Isolating a.com helps more robustly exercise platforms without strict site + // isolation - we want to ensure that enforcing |initiator_origin| in + // BeginNavigation is compatible with process locks, even when only one of the + // frames requires isolation. + IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(), + {"b.com"}); + + // Start on a page with a main frame and a subframe. + GURL page_url(embedded_test_server()->GetURL( + "a.com", "/cross_site_iframe_factory.html?a(b)")); + GURL test_url(embedded_test_server()->GetURL("b.com", "/title1.html")); + EXPECT_TRUE(NavigateToURL(shell(), page_url)); + NavigationControllerImpl& nav_controller = + static_cast<NavigationControllerImpl&>( + shell()->web_contents()->GetController()); + // We start at 3, because IsolateOriginsForTesting is sneeking in extra two + // navigations. + EXPECT_EQ(3, nav_controller.GetEntryCount()); + + // Grab child's site URL. + FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) + ->GetFrameTree() + ->root(); + FrameTreeNode* child = root->child_at(0); + GURL child_site_url = + child->current_frame_host()->GetSiteInstance()->GetSiteURL(); + + // Navigate the subframe to a URL that is cross-site from the main frame. + { + TestNavigationObserver nav_observer(shell()->web_contents()); + ASSERT_TRUE(ExecJs(child, JsReplace("window.location = $1", test_url))); + nav_observer.Wait(); + + EXPECT_TRUE(nav_observer.last_navigation_succeeded()); + EXPECT_EQ(4, nav_controller.GetEntryCount()); + EXPECT_EQ(test_url, child->current_frame_host()->GetLastCommittedURL()); + EXPECT_EQ(url::Origin::Create(test_url), + child->current_frame_host()->GetLastCommittedOrigin()); + EXPECT_EQ(child_site_url, + child->current_frame_host()->GetSiteInstance()->GetSiteURL()); + } + + // Reload the subframe while the network is down. + { + std::unique_ptr<URLLoaderInterceptor> url_interceptor = + SetupRequestFailForURL(test_url); + TestNavigationObserver nav_observer(shell()->web_contents()); + ASSERT_TRUE(ExecJs(child, "window.location.reload()")); + nav_observer.Wait(); + + EXPECT_FALSE(nav_observer.last_navigation_succeeded()); + EXPECT_EQ(4, nav_controller.GetEntryCount()); + EXPECT_EQ(test_url, child->current_frame_host()->GetLastCommittedURL()); + + // Error pages should commit in an opaque origin. + url::Origin origin = child->current_frame_host()->GetLastCommittedOrigin(); + EXPECT_TRUE(origin.opaque()); + EXPECT_EQ(test_url.GetOrigin(), + origin.GetTupleOrPrecursorTupleIfOpaque().GetURL()); + + // Error page isolation should apply only to the main frame - subframes + // should commit in their usual process / SiteInstance. + EXPECT_EQ(child_site_url, + child->current_frame_host()->GetSiteInstance()->GetSiteURL()); + } + + // Reload the subframe after the network is restored. + { + TestNavigationObserver nav_observer(shell()->web_contents()); + // Note that some error pages actually do embed a button that will do an + // equivalent of the renderer-initiated reload that is triggered below. + ASSERT_TRUE(ExecJs(child, "window.location.reload()")); + nav_observer.Wait(); + + EXPECT_TRUE(nav_observer.last_navigation_succeeded()); + EXPECT_EQ(4, nav_controller.GetEntryCount()); + EXPECT_EQ(test_url, child->current_frame_host()->GetLastCommittedURL()); + EXPECT_EQ(url::Origin::Create(test_url), + child->current_frame_host()->GetLastCommittedOrigin()); + EXPECT_EQ(child_site_url, + child->current_frame_host()->GetSiteInstance()->GetSiteURL()); + } +} + +// Version of ErrorPageNavigationReload test that targets a subframe (because +// subframes are currently [~2019Q1] not subject to error page isolation). +IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, + ErrorPageNavigationReload_InSubframe_BlockedByClient) { + StartEmbeddedServer(); + + // Isolating a.com and b.com helps more robustly exercise platforms without + // strict site isolation - we want to ensure that enforcing |initiator_origin| + // in BeginNavigation is compatible with process locks, even when only some of + // the frames requires isolation. + IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(), + {"a.com", "b.com"}); + + // Start on a page with a same-site main frame and a subframe. + GURL page_url(embedded_test_server()->GetURL( + "a.com", "/cross_site_iframe_factory.html?a(b,b)")); + GURL test_url(embedded_test_server()->GetURL("c.com", "/title1.html")); + EXPECT_TRUE(NavigateToURL(shell(), page_url)); + NavigationControllerImpl& nav_controller = + static_cast<NavigationControllerImpl&>( + shell()->web_contents()->GetController()); + // We start at 3, because IsolateOriginsForTesting calls are sneeking in extra + // two navigations. + EXPECT_EQ(3, nav_controller.GetEntryCount()); + + // Grab child's site URL. + FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) + ->GetFrameTree() + ->root(); + FrameTreeNode* child1 = root->child_at(0); + FrameTreeNode* child2 = root->child_at(1); + GURL a_site_url = root->current_frame_host()->GetSiteInstance()->GetSiteURL(); + EXPECT_EQ("a.com", a_site_url.host()); + GURL b_site_url = + child2->current_frame_host()->GetSiteInstance()->GetSiteURL(); + EXPECT_EQ("b.com", b_site_url.host()); + + // Navigate the subframe to a cross-site URL, while blocking the request with + // ERR_BLOCKED_BY_CLIENT. + { + // Name the first child, so it can be found and navigated by the other child + // in the next test step below. + ASSERT_TRUE(ExecJs(child1, "window.name = 'child1';")); + + // Have |child2| initiate navigation of |child1| - the navigation should + // result in ERR_BLOCKED_BY_CLIENT (because of the throttle created below). + content::TestNavigationThrottleInserter throttle_inserter( + shell()->web_contents(), + base::BindRepeating(&RequestBlockingNavigationThrottle::Create)); + const char kScriptTemplate[] = R"( + var child1 = window.open('', 'child1'); + child1.location = $1; + )"; + TestNavigationObserver nav_observer(shell()->web_contents()); + ASSERT_TRUE(ExecJs(child2, JsReplace(kScriptTemplate, test_url))); + nav_observer.Wait(); + EXPECT_FALSE(nav_observer.last_navigation_succeeded()); + EXPECT_EQ(4, nav_controller.GetEntryCount()); + EXPECT_EQ(test_url, child1->current_frame_host()->GetLastCommittedURL()); + + // Error pages should commit in an opaque origin. + url::Origin error_origin = + child1->current_frame_host()->GetLastCommittedOrigin(); + url::Origin initiator_origin = + child2->current_frame_host()->GetLastCommittedOrigin(); + EXPECT_TRUE(error_origin.opaque()); + EXPECT_EQ(initiator_origin.GetURL(), + error_origin.GetTupleOrPrecursorTupleIfOpaque().GetURL()); + + // net::ERR_BLOCKED_BY_CLIENT errors in subframes should commit in their + // initiator's process (not in their parent's process). + EXPECT_EQ(b_site_url, + child1->current_frame_host()->GetSiteInstance()->GetSiteURL()); + } + + // Reload the subframe when no longer blocking the navigation. + { + TestNavigationObserver nav_observer(shell()->web_contents()); + // Note that some error pages actually do embed a button that will do an + // equivalent of the renderer-initiated reload that is triggered below. + ASSERT_TRUE(ExecJs(child1, "window.location.reload()")); + nav_observer.Wait(); + + EXPECT_TRUE(nav_observer.last_navigation_succeeded()); + EXPECT_EQ(4, nav_controller.GetEntryCount()); + EXPECT_EQ(test_url, child1->current_frame_host()->GetLastCommittedURL()); + EXPECT_EQ(url::Origin::Create(test_url), + child1->current_frame_host()->GetLastCommittedOrigin()); + GURL c_site_url = + child1->current_frame_host()->GetSiteInstance()->GetSiteURL(); + EXPECT_EQ("c.com", c_site_url.host()); + EXPECT_NE(a_site_url, c_site_url); + EXPECT_NE(b_site_url, c_site_url); + } +} + // Make sure that reload works properly if it redirects to a different site than // the initial navigation. The initial purpose of this test was to make sure // the corresponding unit test matches the actual product code behavior @@ -4785,30 +4997,6 @@ web_contents->GetSiteInstance()->GetProcess()->GetID())); } -// A NavigationThrottle implementation that blocks all outgoing navigation -// requests for a specific WebContents. It is used to block navigations to -// WebUI URLs in the following test. -class RequestBlockingNavigationThrottle : public NavigationThrottle { - public: - explicit RequestBlockingNavigationThrottle(NavigationHandle* handle) - : NavigationThrottle(handle) {} - - static std::unique_ptr<NavigationThrottle> Create(NavigationHandle* handle) { - return std::make_unique<RequestBlockingNavigationThrottle>(handle); - } - - private: - ThrottleCheckResult WillStartRequest() override { - return NavigationThrottle::BLOCK_REQUEST; - } - - const char* GetNameForLogging() override { - return "RequestBlockingNavigationThrottle"; - } - - DISALLOW_COPY_AND_ASSIGN(RequestBlockingNavigationThrottle); -}; - // Test to verify that navigations to WebUI URL which results in an error // commits properly in the error page process and does not give it WebUI // bindings.
diff --git a/content/browser/frame_host/render_frame_message_filter.cc b/content/browser/frame_host/render_frame_message_filter.cc index 52596270..62f00997 100644 --- a/content/browser/frame_host/render_frame_message_filter.cc +++ b/content/browser/frame_host/render_frame_message_filter.cc
@@ -620,7 +620,7 @@ // |callback| needs to be fired even if network process crashes as it's for // sync IPC. - net::CookieStore::SetCookiesCallback net_callback = + base::OnceCallback<void(bool)> net_callback = mojo::WrapCallbackWithDefaultInvokeIfNotRun( base::BindOnce([](SetCookieCallback callback, bool success) { std::move(callback).Run(); },
diff --git a/content/browser/indexed_db/indexed_db_database.cc b/content/browser/indexed_db/indexed_db_database.cc index 1387bd6c..6b5787a5 100644 --- a/content/browser/indexed_db/indexed_db_database.cc +++ b/content/browser/indexed_db/indexed_db_database.cc
@@ -14,6 +14,7 @@ #include "base/bind.h" #include "base/logging.h" #include "base/macros.h" +#include "base/memory/weak_ptr.h" #include "base/metrics/histogram_macros.h" #include "base/numerics/safe_conversions.h" #include "base/stl_util.h" @@ -32,6 +33,8 @@ #include "content/browser/indexed_db/indexed_db_tracing.h" #include "content/browser/indexed_db/indexed_db_transaction.h" #include "content/browser/indexed_db/indexed_db_value.h" +#include "content/browser/indexed_db/scopes/scope_lock.h" +#include "content/browser/indexed_db/scopes/scopes_lock_manager.h" #include "content/public/common/content_switches.h" #include "ipc/ipc_channel.h" #include "storage/browser/blob/blob_data_handle.h" @@ -124,7 +127,9 @@ public: OpenRequest(scoped_refptr<IndexedDBDatabase> db, std::unique_ptr<IndexedDBPendingConnection> pending_connection) - : ConnectionRequest(db), pending_(std::move(pending_connection)) {} + : ConnectionRequest(db), + pending_(std::move(pending_connection)), + weak_factory_(this) {} void Perform() override { if (db_->metadata_.id == kInvalidId) { @@ -200,7 +205,13 @@ DCHECK_GT(new_version, old_version); if (db_->connections_.empty()) { - StartUpgrade(); + std::vector<ScopesLockManager::ScopeLockRequest> lock_requests = { + {kDatabaseRangeLockLevel, GetDatabaseLockRange(db_->metadata_.id), + ScopesLockManager::LockType::kExclusive}}; + db_->lock_manager_->AcquireLocks( + std::move(lock_requests), + base::BindOnce(&IndexedDBDatabase::OpenRequest::StartUpgrade, + weak_factory_.GetWeakPtr())); return; } @@ -234,13 +245,19 @@ if (!db_->connections_.empty()) return; - StartUpgrade(); + std::vector<ScopesLockManager::ScopeLockRequest> lock_requests = { + {kDatabaseRangeLockLevel, GetDatabaseLockRange(db_->metadata_.id), + ScopesLockManager::LockType::kExclusive}}; + db_->lock_manager_->AcquireLocks( + std::move(lock_requests), + base::BindOnce(&IndexedDBDatabase::OpenRequest::StartUpgrade, + weak_factory_.GetWeakPtr())); } // Initiate the upgrade. The bulk of the work actually happens in // IndexedDBDatabase::VersionChangeOperation in order to kick the // transaction into the correct state. - void StartUpgrade() { + void StartUpgrade(std::vector<ScopeLock> locks) { connection_ = db_->CreateConnection(pending_->database_callbacks, pending_->child_process_id); DCHECK_EQ(db_->connections_.count(connection_.get()), 1UL); @@ -252,11 +269,10 @@ std::set<int64_t>(object_store_ids.begin(), object_store_ids.end()), blink::mojom::IDBTransactionMode::VersionChange, new IndexedDBBackingStore::Transaction(db_->backing_store())); - db_->RegisterAndScheduleTransaction(transaction); - transaction->ScheduleTask( base::BindOnce(&IndexedDBDatabase::VersionChangeOperation, db_, pending_->version, pending_->callbacks)); + transaction->Start(std::move(locks)); } // Called when the upgrade transaction has started executing. @@ -296,6 +312,7 @@ // transferred to the IndexedDBDispatcherHost via OnUpgradeNeeded. std::unique_ptr<IndexedDBConnection> connection_; + base::WeakPtrFactory<OpenRequest> weak_factory_; DISALLOW_COPY_AND_ASSIGN(OpenRequest); }; @@ -304,12 +321,18 @@ public: DeleteRequest(scoped_refptr<IndexedDBDatabase> db, scoped_refptr<IndexedDBCallbacks> callbacks) - : ConnectionRequest(db), callbacks_(callbacks) {} + : ConnectionRequest(db), callbacks_(callbacks), weak_factory_(this) {} void Perform() override { if (db_->connections_.empty()) { // No connections, so delete immediately. - DoDelete(); + std::vector<ScopesLockManager::ScopeLockRequest> lock_requests = { + {kDatabaseRangeLockLevel, GetDatabaseLockRange(db_->metadata_.id), + ScopesLockManager::LockType::kExclusive}}; + db_->lock_manager_->AcquireLocks( + std::move(lock_requests), + base::BindOnce(&IndexedDBDatabase::DeleteRequest::DoDelete, + weak_factory_.GetWeakPtr())); return; } @@ -328,10 +351,17 @@ void OnConnectionClosed(IndexedDBConnection* connection) override { if (!db_->connections_.empty()) return; - DoDelete(); + + std::vector<ScopesLockManager::ScopeLockRequest> lock_requests = { + {kDatabaseRangeLockLevel, GetDatabaseLockRange(db_->metadata_.id), + ScopesLockManager::LockType::kExclusive}}; + db_->lock_manager_->AcquireLocks( + std::move(lock_requests), + base::BindOnce(&IndexedDBDatabase::DeleteRequest::DoDelete, + weak_factory_.GetWeakPtr())); } - void DoDelete() { + void DoDelete(std::vector<ScopeLock> locks) { Status s; if (db_->backing_store_) s = db_->backing_store_->DeleteDatabase(db_->metadata_.name); @@ -374,6 +404,7 @@ private: scoped_refptr<IndexedDBCallbacks> callbacks_; + base::WeakPtrFactory<DeleteRequest> weak_factory_; DISALLOW_COPY_AND_ASSIGN(DeleteRequest); }; @@ -1806,18 +1837,28 @@ return Status::OK(); } -void IndexedDBDatabase::TransactionFinished(IndexedDBTransaction* transaction, - bool committed) { - IDB_TRACE1("IndexedDBTransaction::TransactionFinished", "txn.id", - transaction->id()); +void IndexedDBDatabase::TransactionCreated() { + UMA_HISTOGRAM_COUNTS_1000( + "WebCore.IndexedDB.Database.OutstandingTransactionCount", + transaction_count_); + ++transaction_count_; +} + +void IndexedDBDatabase::TransactionFinished( + blink::mojom::IDBTransactionMode mode, + bool committed) { --transaction_count_; DCHECK_GE(transaction_count_, 0); + // TODO(dmurph): To help remove this integration with IndexedDBDatabase, make + // a 'committed' listener closure on all transactions. Then the request can + // just listen for that. + // This may be an unrelated transaction finishing while waiting for // connections to close, or the actual upgrade transaction from an active // request. Notify the active request if it's the latter. if (active_request_ && - transaction->mode() == blink::mojom::IDBTransactionMode::VersionChange) { + mode == blink::mojom::IDBTransactionMode::VersionChange) { active_request_->UpgradeTransactionFinished(committed); } } @@ -1861,11 +1902,6 @@ IndexedDBTransaction* transaction) { IDB_TRACE1("IndexedDBDatabase::RegisterAndScheduleTransaction", "txn.id", transaction->id()); - - UMA_HISTOGRAM_COUNTS_1000( - "WebCore.IndexedDB.Database.OutstandingTransactionCount", - transaction_count_); - transaction_count_++; std::vector<ScopesLockManager::ScopeLockRequest> lock_requests; lock_requests.reserve(1 + transaction->scope().size()); lock_requests.emplace_back(
diff --git a/content/browser/indexed_db/indexed_db_database.h b/content/browser/indexed_db/indexed_db_database.h index d29251f9..f7f669d 100644 --- a/content/browser/indexed_db/indexed_db_database.h +++ b/content/browser/indexed_db/indexed_db_database.h
@@ -103,8 +103,8 @@ int64_t object_store_id, const base::string16& new_name); - // Returns a pointer to a newly created transaction. The object is owned - // by the connection. + // TODO(dmurph): Remove this method and have transactions be directly + // scheduled using the lock manager. void RegisterAndScheduleTransaction(IndexedDBTransaction* transaction); void Close(IndexedDBConnection* connection, bool forced); void ForceClose(); @@ -136,7 +136,9 @@ return lock_manager_; } - void TransactionFinished(IndexedDBTransaction* transaction, bool committed); + void TransactionCreated(); + void TransactionFinished(blink::mojom::IDBTransactionMode mode, + bool committed); void AbortAllTransactionsForConnections();
diff --git a/content/browser/indexed_db/indexed_db_database_error.cc b/content/browser/indexed_db/indexed_db_database_error.cc index 05c0cb5..af0702e 100644 --- a/content/browser/indexed_db/indexed_db_database_error.cc +++ b/content/browser/indexed_db/indexed_db_database_error.cc
@@ -6,15 +6,15 @@ namespace content { -IndexedDBDatabaseError::IndexedDBDatabaseError(uint16_t code) : code_(code) {} +IndexedDBDatabaseError::IndexedDBDatabaseError(int32_t code) : code_(code) {} IndexedDBDatabaseError::IndexedDBDatabaseError() = default; -IndexedDBDatabaseError::IndexedDBDatabaseError(uint16_t code, +IndexedDBDatabaseError::IndexedDBDatabaseError(int32_t code, const char* message) : code_(code), message_(base::ASCIIToUTF16(message)) {} -IndexedDBDatabaseError::IndexedDBDatabaseError(uint16_t code, +IndexedDBDatabaseError::IndexedDBDatabaseError(int32_t code, const base::string16& message) : code_(code), message_(message) {}
diff --git a/content/browser/indexed_db/indexed_db_database_error.h b/content/browser/indexed_db/indexed_db_database_error.h index 0cb060c..035209b 100644 --- a/content/browser/indexed_db/indexed_db_database_error.h +++ b/content/browser/indexed_db/indexed_db_database_error.h
@@ -14,20 +14,22 @@ namespace content { class CONTENT_EXPORT IndexedDBDatabaseError { + // TODO(dmurph): Move the WebIDBDatabaseException enum into mojo, and make + // the |code| type the mojo enum type. public: IndexedDBDatabaseError(); - explicit IndexedDBDatabaseError(uint16_t code); - IndexedDBDatabaseError(uint16_t code, const char* message); - IndexedDBDatabaseError(uint16_t code, const base::string16& message); + explicit IndexedDBDatabaseError(int32_t code); + IndexedDBDatabaseError(int32_t code, const char* message); + IndexedDBDatabaseError(int32_t code, const base::string16& message); ~IndexedDBDatabaseError(); IndexedDBDatabaseError& operator=(const IndexedDBDatabaseError& rhs); - uint16_t code() const { return code_; } + int32_t code() const { return code_; } const base::string16& message() const { return message_; } private: - uint16_t code_ = 0; + int32_t code_ = 0; base::string16 message_; };
diff --git a/content/browser/indexed_db/indexed_db_transaction.cc b/content/browser/indexed_db/indexed_db_transaction.cc index d418674..3b501662 100644 --- a/content/browser/indexed_db/indexed_db_transaction.cc +++ b/content/browser/indexed_db/indexed_db_transaction.cc
@@ -119,6 +119,8 @@ IDB_ASYNC_TRACE_BEGIN("IndexedDBTransaction::lifetime", this); callbacks_ = connection_->callbacks(); database_ = connection_->database(); + if (database_) + database_->TransactionCreated(); diagnostics_.tasks_scheduled = 0; diagnostics_.tasks_completed = 0; @@ -237,7 +239,7 @@ if (callbacks_.get()) callbacks_->OnAbort(*this, error); - database_->TransactionFinished(this, false); + database_->TransactionFinished(mode_, false); // RemoveTransaction will delete |this|. // Note: During force-close situations, the connection can be destroyed during @@ -460,7 +462,7 @@ if (!pending_observers_.empty() && connection_) connection_->ActivatePendingObservers(std::move(pending_observers_)); - database_->TransactionFinished(this, true); + database_->TransactionFinished(mode_, true); // RemoveTransaction will delete |this|. connection_->RemoveTransaction(id_); return s; @@ -479,7 +481,7 @@ "Internal error committing transaction."); } callbacks_->OnAbort(*this, error); - database_->TransactionFinished(this, false); + database_->TransactionFinished(mode_, false); } return s; }
diff --git a/content/browser/loader/navigation_url_loader_impl.cc b/content/browser/loader/navigation_url_loader_impl.cc index ef91af1..0136987 100644 --- a/content/browser/loader/navigation_url_loader_impl.cc +++ b/content/browser/loader/navigation_url_loader_impl.cc
@@ -231,8 +231,7 @@ request_info->begin_params->headers); std::string accept_value = network::kFrameAcceptHeader; - if (signed_exchange_utils::ShouldAdvertiseAcceptHeader( - url::Origin::Create(request_info->common_params.url))) { + if (signed_exchange_utils::IsSignedExchangeHandlingEnabled()) { DCHECK(!accept_value.empty()); accept_value.append(kAcceptHeaderSignedExchangeSuffix); } @@ -1104,25 +1103,6 @@ url_loader_removed_headers_ = removed_headers; url_loader_modified_headers_ = modified_headers; - if (signed_exchange_utils::NeedToCheckRedirectedURLForAcceptHeader()) { - // Currently we send the SignedExchange accept header only for the limited - // origins when SignedHTTPExchangeOriginTrial feature is enabled without - // SignedHTTPExchange feature. We need to put the SignedExchange accept - // header on when redirecting to the origins in the OriginList of - // SignedHTTPExchangeAcceptHeader field trial, and need to remove it when - // redirecting to out of the OriginList. - std::string accept_value = network::kFrameAcceptHeader; - if (signed_exchange_utils::ShouldAdvertiseAcceptHeader( - url::Origin::Create(resource_request_->url))) { - DCHECK(!accept_value.empty()); - accept_value.append(kAcceptHeaderSignedExchangeSuffix); - } - url_loader_modified_headers_.SetHeader(network::kAcceptHeader, - accept_value); - resource_request_->headers.SetHeader(network::kAcceptHeader, - accept_value); - } - Restart(); }
diff --git a/content/browser/loader/prefetch_url_loader.cc b/content/browser/loader/prefetch_url_loader.cc index 32bfe1c..69d36cf1 100644 --- a/content/browser/loader/prefetch_url_loader.cc +++ b/content/browser/loader/prefetch_url_loader.cc
@@ -50,9 +50,8 @@ std::move(signed_exchange_prefetch_metric_recorder)) { DCHECK(network_loader_factory_); - if (signed_exchange_utils::ShouldAdvertiseAcceptHeader( - url::Origin::Create(resource_request_.url))) { - // Set the SignedExchange accept header only for the limited origins. + if (signed_exchange_utils::IsSignedExchangeHandlingEnabled()) { + // Set the SignedExchange accept header. // (https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#internet-media-type-applicationsigned-exchange). resource_request_.headers.SetHeader( network::kAcceptHeader, kSignedExchangeEnabledAcceptHeaderForPrefetch); @@ -85,25 +84,9 @@ return; } - net::HttpRequestHeaders modified_request_headers_for_accept; - if (signed_exchange_utils::NeedToCheckRedirectedURLForAcceptHeader()) { - // Currently we send the SignedExchange accept header only for the limited - // origins when SignedHTTPExchangeOriginTrial feature is enabled without - // SignedHTTPExchange feature. So need to update the accept header by - // checking the new URL when redirected. - if (signed_exchange_utils::ShouldAdvertiseAcceptHeader( - url::Origin::Create(resource_request_.url))) { - modified_request_headers_for_accept.SetHeader( - network::kAcceptHeader, - kSignedExchangeEnabledAcceptHeaderForPrefetch); - } else { - modified_request_headers_for_accept.SetHeader( - network::kAcceptHeader, network::kDefaultAcceptHeader); - } - } - DCHECK(loader_); - loader_->FollowRedirect(removed_headers, modified_request_headers_for_accept, + loader_->FollowRedirect(removed_headers, + net::HttpRequestHeaders() /* modified_headers */, base::nullopt); }
diff --git a/content/browser/navigation_browsertest.cc b/content/browser/navigation_browsertest.cc index 43fb95b..ae113a5 100644 --- a/content/browser/navigation_browsertest.cc +++ b/content/browser/navigation_browsertest.cc
@@ -50,7 +50,7 @@ #include "content/shell/browser/shell_download_manager_delegate.h" #include "content/shell/browser/shell_network_delegate.h" #include "content/test/content_browser_test_utils_internal.h" -#include "content/test/did_commit_provisional_load_interceptor.h" +#include "content/test/frame_host_interceptor.h" #include "ipc/ipc_security_test_util.h" #include "net/base/filename_util.h" #include "net/base/load_flags.h" @@ -65,11 +65,10 @@ namespace { -class InterceptAndCancelDidCommitProvisionalLoad - : public DidCommitProvisionalLoadInterceptor { +class InterceptAndCancelDidCommitProvisionalLoad : public FrameHostInterceptor { public: explicit InterceptAndCancelDidCommitProvisionalLoad(WebContents* web_contents) - : DidCommitProvisionalLoadInterceptor(web_contents) {} + : FrameHostInterceptor(web_contents) {} ~InterceptAndCancelDidCommitProvisionalLoad() override {} void Wait(size_t number_of_messages) { @@ -103,15 +102,15 @@ bool WillDispatchDidCommitProvisionalLoad( RenderFrameHost* render_frame_host, ::FrameHostMsg_DidCommitProvisionalLoad_Params* params, - mojom::DidCommitProvisionalLoadInterfaceParamsPtr& interface_params) + mojom::DidCommitProvisionalLoadInterfaceParamsPtr* interface_params) override { intercepted_messages_.push_back(*params); intercepted_requests_.push_back( - std::move(interface_params->interface_provider_request)); - intercepted_broker_content_requests_.push_back( - std::move(interface_params->document_interface_broker_content_request)); - intercepted_broker_blink_requests_.push_back( - std::move(interface_params->document_interface_broker_blink_request)); + std::move((*interface_params)->interface_provider_request)); + intercepted_broker_content_requests_.push_back(std::move( + (*interface_params)->document_interface_broker_content_request)); + intercepted_broker_blink_requests_.push_back(std::move( + (*interface_params)->document_interface_broker_blink_request)); if (loop_) loop_->Quit(); // Do not send the message to the RenderFrameHostImpl. @@ -133,7 +132,7 @@ // to check these events happen and happen in the expected right order. class NavigationRecorder : public WebContentsObserver { public: - NavigationRecorder(WebContents* web_contents) + explicit NavigationRecorder(WebContents* web_contents) : WebContentsObserver(web_contents) {} // WebContentsObserver implementation. @@ -1338,7 +1337,7 @@ // returns the appropriate value when the Previews are set. class PreviewsStateContentBrowserClient : public ContentBrowserClient { public: - PreviewsStateContentBrowserClient(const GURL& main_frame_url) + explicit PreviewsStateContentBrowserClient(const GURL& main_frame_url) : main_frame_url_(main_frame_url), main_frame_url_seen_(false), previews_state_(PREVIEWS_OFF),
diff --git a/content/browser/notifications/notification_database_data_conversions.cc b/content/browser/notifications/notification_database_data_conversions.cc index 83b0b0043..d6b1332 100644 --- a/content/browser/notifications/notification_database_data_conversions.cc +++ b/content/browser/notifications/notification_database_data_conversions.cc
@@ -70,15 +70,14 @@ switch (payload.direction()) { case NotificationDatabaseDataProto::NotificationData::LEFT_TO_RIGHT: notification_data->direction = - blink::PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT; + blink::mojom::NotificationDirection::LEFT_TO_RIGHT; break; case NotificationDatabaseDataProto::NotificationData::RIGHT_TO_LEFT: notification_data->direction = - blink::PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT; + blink::mojom::NotificationDirection::RIGHT_TO_LEFT; break; case NotificationDatabaseDataProto::NotificationData::AUTO: - notification_data->direction = - blink::PlatformNotificationData::DIRECTION_AUTO; + notification_data->direction = blink::mojom::NotificationDirection::AUTO; break; } @@ -151,15 +150,15 @@ payload->set_title(base::UTF16ToUTF8(notification_data.title)); switch (notification_data.direction) { - case blink::PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT: + case blink::mojom::NotificationDirection::LEFT_TO_RIGHT: payload->set_direction( NotificationDatabaseDataProto::NotificationData::LEFT_TO_RIGHT); break; - case blink::PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT: + case blink::mojom::NotificationDirection::RIGHT_TO_LEFT: payload->set_direction( NotificationDatabaseDataProto::NotificationData::RIGHT_TO_LEFT); break; - case blink::PlatformNotificationData::DIRECTION_AUTO: + case blink::mojom::NotificationDirection::AUTO: payload->set_direction( NotificationDatabaseDataProto::NotificationData::AUTO); break;
diff --git a/content/browser/notifications/notification_database_data_unittest.cc b/content/browser/notifications/notification_database_data_unittest.cc index db02412..72d7363 100644 --- a/content/browser/notifications/notification_database_data_unittest.cc +++ b/content/browser/notifications/notification_database_data_unittest.cc
@@ -57,7 +57,7 @@ blink::PlatformNotificationData notification_data; notification_data.title = base::ASCIIToUTF16(kNotificationTitle); notification_data.direction = - blink::PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT; + blink::mojom::NotificationDirection::RIGHT_TO_LEFT; notification_data.lang = kNotificationLang; notification_data.body = base::ASCIIToUTF16(kNotificationBody); notification_data.tag = kNotificationTag; @@ -226,10 +226,10 @@ } TEST(NotificationDatabaseDataTest, SerializeAndDeserializeDirections) { - blink::PlatformNotificationData::Direction directions[] = { - blink::PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT, - blink::PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT, - blink::PlatformNotificationData::DIRECTION_AUTO}; + blink::mojom::NotificationDirection directions[] = { + blink::mojom::NotificationDirection::LEFT_TO_RIGHT, + blink::mojom::NotificationDirection::RIGHT_TO_LEFT, + blink::mojom::NotificationDirection::AUTO}; for (size_t i = 0; i < base::size(directions); ++i) { blink::PlatformNotificationData notification_data;
diff --git a/content/browser/notifications/notification_database_unittest.cc b/content/browser/notifications/notification_database_unittest.cc index 7bdbf34..3544a5f 100644 --- a/content/browser/notifications/notification_database_unittest.cc +++ b/content/browser/notifications/notification_database_unittest.cc
@@ -286,7 +286,7 @@ blink::PlatformNotificationData notification_data; notification_data.title = base::UTF8ToUTF16("My Notification"); notification_data.direction = - blink::PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT; + blink::mojom::NotificationDirection::RIGHT_TO_LEFT; notification_data.lang = "nl-NL"; notification_data.body = base::UTF8ToUTF16("Hello, world!"); notification_data.tag = "replace id";
diff --git a/content/browser/renderer_host/input/synthetic_gesture_controller.cc b/content/browser/renderer_host/input/synthetic_gesture_controller.cc index 14d6145c..b6c887fb 100644 --- a/content/browser/renderer_host/input/synthetic_gesture_controller.cc +++ b/content/browser/renderer_host/input/synthetic_gesture_controller.cc
@@ -33,12 +33,28 @@ void SyntheticGestureController::QueueSyntheticGesture( std::unique_ptr<SyntheticGesture> synthetic_gesture, OnGestureCompleteCallback completion_callback) { + QueueSyntheticGesture(std::move(synthetic_gesture), + std::move(completion_callback), false); +} + +void SyntheticGestureController::QueueSyntheticGestureCompleteImmediately( + std::unique_ptr<SyntheticGesture> synthetic_gesture) { + QueueSyntheticGesture(std::move(synthetic_gesture), + base::BindOnce([](SyntheticGesture::Result result) {}), + true); +} + +void SyntheticGestureController::QueueSyntheticGesture( + std::unique_ptr<SyntheticGesture> synthetic_gesture, + OnGestureCompleteCallback completion_callback, + bool complete_immediately) { DCHECK(synthetic_gesture); bool was_empty = pending_gesture_queue_.IsEmpty(); pending_gesture_queue_.Push(std::move(synthetic_gesture), - std::move(completion_callback)); + std::move(completion_callback), + complete_immediately); if (was_empty) StartGesture(*pending_gesture_queue_.FrontGesture()); @@ -73,11 +89,13 @@ pending_gesture_queue_.mark_current_gesture_complete(result); } - if (!delegate_->HasGestureStopped()) + if (!pending_gesture_queue_.CompleteCurrentGestureImmediately() && + !delegate_->HasGestureStopped()) return true; StopGesture(*pending_gesture_queue_.FrontGesture(), - pending_gesture_queue_.current_gesture_result()); + pending_gesture_queue_.current_gesture_result(), + pending_gesture_queue_.CompleteCurrentGestureImmediately()); return !pending_gesture_queue_.IsEmpty(); } @@ -90,9 +108,9 @@ StartTimer(gesture.AllowHighFrequencyDispatch()); } -void SyntheticGestureController::StopGesture( - const SyntheticGesture& gesture, - SyntheticGesture::Result result) { +void SyntheticGestureController::StopGesture(const SyntheticGesture& gesture, + SyntheticGesture::Result result, + bool complete_immediately) { DCHECK_NE(result, SyntheticGesture::GESTURE_RUNNING); TRACE_EVENT_ASYNC_END0("input,benchmark", "SyntheticGestureController::running", @@ -100,7 +118,7 @@ dispatch_timer_.Stop(); - if (result != SyntheticGesture::GESTURE_FINISHED) { + if (result != SyntheticGesture::GESTURE_FINISHED || complete_immediately) { GestureCompleted(result); return; }
diff --git a/content/browser/renderer_host/input/synthetic_gesture_controller.h b/content/browser/renderer_host/input/synthetic_gesture_controller.h index 53d59bad..efa6133 100644 --- a/content/browser/renderer_host/input/synthetic_gesture_controller.h +++ b/content/browser/renderer_host/input/synthetic_gesture_controller.h
@@ -47,35 +47,49 @@ std::unique_ptr<SyntheticGesture> synthetic_gesture, OnGestureCompleteCallback completion_callback); + // Like QueueSyntheticGesture, but the gesture is considered complete as soon + // as the SyntheticGestureController is done dispatching the events. + void QueueSyntheticGestureCompleteImmediately( + std::unique_ptr<SyntheticGesture> synthetic_gesture); + bool DispatchNextEvent(base::TimeTicks = base::TimeTicks::Now()); private: friend class SyntheticGestureControllerTestBase; + void QueueSyntheticGesture( + std::unique_ptr<SyntheticGesture> synthetic_gesture, + OnGestureCompleteCallback completion_callback, + bool complete_immediately); + void StartTimer(bool high_frequency); void StartGesture(const SyntheticGesture& gesture); void StopGesture(const SyntheticGesture& gesture, - SyntheticGesture::Result result); + SyntheticGesture::Result result, + bool complete_immediately); void GestureCompleted(SyntheticGesture::Result result); void ResolveCompletionCallback(); Delegate* const delegate_; std::unique_ptr<SyntheticGestureTarget> gesture_target_; - // A queue of gesture/callback pairs. Implemented as two queues to + // A queue of gesture/callback/bool tuples. Implemented as multiple queues to // simplify the ownership of SyntheticGesture pointers. class GestureAndCallbackQueue { public: GestureAndCallbackQueue(); ~GestureAndCallbackQueue(); void Push(std::unique_ptr<SyntheticGesture> gesture, - OnGestureCompleteCallback callback) { + OnGestureCompleteCallback callback, + bool complete_immediately) { gestures_.push_back(std::move(gesture)); callbacks_.push(std::move(callback)); + complete_immediately_.push(complete_immediately); } void Pop() { gestures_.erase(gestures_.begin()); callbacks_.pop(); + complete_immediately_.pop(); result_of_current_gesture_ = SyntheticGesture::GESTURE_RUNNING; } SyntheticGesture* FrontGesture() { return gestures_.front().get(); } @@ -85,8 +99,12 @@ // remove FrontGesture/FrontCallback. return std::move(callbacks_.front()); } + bool CompleteCurrentGestureImmediately() { + return complete_immediately_.front(); + } bool IsEmpty() const { CHECK(gestures_.empty() == callbacks_.empty()); + CHECK(gestures_.empty() == complete_immediately_.empty()); return gestures_.empty(); } @@ -107,6 +125,7 @@ SyntheticGesture::GESTURE_RUNNING; std::vector<std::unique_ptr<SyntheticGesture>> gestures_; base::queue<OnGestureCompleteCallback> callbacks_; + base::queue<bool> complete_immediately_; DISALLOW_COPY_AND_ASSIGN(GestureAndCallbackQueue); } pending_gesture_queue_;
diff --git a/content/browser/renderer_host/input/touch_action_browsertest.cc b/content/browser/renderer_host/input/touch_action_browsertest.cc index 15fb21b..538e8181 100644 --- a/content/browser/renderer_host/input/touch_action_browsertest.cc +++ b/content/browser/renderer_host/input/touch_action_browsertest.cc
@@ -378,7 +378,7 @@ "actions": [ { "name": "pointerDown", "x": 50, "y": 50 }, { "name": "pointerUp" }, - { "name": "pause", "duration": 0.05 }, + { "name": "pause", "duration": 50 }, { "name": "pointerDown", "x": 50, "y": 50 }, { "name": "pointerMove", "x": 50, "y": 150 }, { "name": "pointerUp" }
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index 7ad5129..581830b 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -216,6 +216,7 @@ #include "third_party/blink/public/common/user_agent/user_agent_metadata.h" #include "third_party/blink/public/public_buildflags.h" #include "third_party/skia/include/core/SkBitmap.h" +#include "ui/accessibility/accessibility_switches.h" #include "ui/base/ui_base_features.h" #include "ui/base/ui_base_switches.h" #include "ui/base/ui_base_switches_util.h" @@ -2988,6 +2989,7 @@ switches::kDomAutomationController, switches::kEnableAccessibilityObjectModel, switches::kEnableAutomation, + switches::kEnableExperimentalAccessibilityLabels, switches::kEnableExperimentalWebPlatformFeatures, switches::kEnableGPUClientLogging, switches::kEnableGpuClientTracing, @@ -4421,8 +4423,8 @@ channel_->Unpause(false /* flush */); if (child_connection_) { - child_connection_->SetProcessHandle( - child_process_launcher_->GetProcess().Handle()); + child_connection_->SetProcess( + child_process_launcher_->GetProcess().Duplicate()); } // Not all platforms launch processes in the same backgrounded state. Make
diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc index 763bfcc8..3115d21 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc
@@ -1616,20 +1616,33 @@ result_tracker_weak_ptr->PrepareForAsync(); } -void RenderWidgetHostImpl::QueueSyntheticGesture( - std::unique_ptr<SyntheticGesture> synthetic_gesture, - base::OnceCallback<void(SyntheticGesture::Result)> on_complete) { +void RenderWidgetHostImpl::CreateSyntheticGestureControllerIfNecessary() { if (!synthetic_gesture_controller_ && view_) { synthetic_gesture_controller_ = std::make_unique<SyntheticGestureController>( this, view_->CreateSyntheticGestureTarget()); } +} + +void RenderWidgetHostImpl::QueueSyntheticGesture( + std::unique_ptr<SyntheticGesture> synthetic_gesture, + base::OnceCallback<void(SyntheticGesture::Result)> on_complete) { + CreateSyntheticGestureControllerIfNecessary(); if (synthetic_gesture_controller_) { synthetic_gesture_controller_->QueueSyntheticGesture( std::move(synthetic_gesture), std::move(on_complete)); } } +void RenderWidgetHostImpl::QueueSyntheticGestureCompleteImmediately( + std::unique_ptr<SyntheticGesture> synthetic_gesture) { + CreateSyntheticGestureControllerIfNecessary(); + if (synthetic_gesture_controller_) { + synthetic_gesture_controller_->QueueSyntheticGestureCompleteImmediately( + std::move(synthetic_gesture)); + } +} + void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) { if (!view_) return; @@ -2999,7 +3012,24 @@ } bool RenderWidgetHostImpl::HasGestureStopped() { - return !input_router_->HasPendingEvents(); + if (delegate_ && delegate_->GetInputEventRouter() && + delegate_->GetInputEventRouter()->HasEventsPendingDispatch()) { + return false; + } + + if (input_router_->HasPendingEvents()) + return false; + + std::unique_ptr<RenderWidgetHostIterator> child_widgets( + GetEmbeddedRenderWidgetHosts()); + while (RenderWidgetHost* child = child_widgets->GetNextHost()) { + auto* child_impl = static_cast<RenderWidgetHostImpl*>(child); + if (!child_impl->HasGestureStopped()) { + return false; + } + } + + return true; } void RenderWidgetHostImpl::SetNeedsBeginFrame(bool needs_begin_frames) {
diff --git a/content/browser/renderer_host/render_widget_host_impl.h b/content/browser/renderer_host/render_widget_host_impl.h index 0029b07..b6a90bdd 100644 --- a/content/browser/renderer_host/render_widget_host_impl.h +++ b/content/browser/renderer_host/render_widget_host_impl.h
@@ -440,6 +440,8 @@ void QueueSyntheticGesture( std::unique_ptr<SyntheticGesture> synthetic_gesture, base::OnceCallback<void(SyntheticGesture::Result)> on_complete); + void QueueSyntheticGestureCompleteImmediately( + std::unique_ptr<SyntheticGesture> synthetic_gesture); void CancelUpdateTextDirection(); @@ -942,6 +944,8 @@ // TouchEmulator. TouchEmulator* GetExistingTouchEmulator(); + void CreateSyntheticGestureControllerIfNecessary(); + // true if a renderer has once been valid. We use this flag to display a sad // tab only when we lose our renderer and not if a paint occurs during // initialization.
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.cc b/content/browser/renderer_host/render_widget_host_input_event_router.cc index 3890382..7596224 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.cc +++ b/content/browser/renderer_host/render_widget_host_input_event_router.cc
@@ -232,6 +232,10 @@ ProcessAckedTouchEvents(); } +bool RenderWidgetHostInputEventRouter::HasEventsPendingDispatch() const { + return event_targeter_->HasEventsPendingDispatch(); +} + size_t RenderWidgetHostInputEventRouter::TouchEventAckQueueLengthForTesting() const { return touch_event_ack_queue_->length_for_testing();
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.h b/content/browser/renderer_host/render_widget_host_input_event_router.h index 86bf64a..ec55d04 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.h +++ b/content/browser/renderer_host/render_widget_host_input_event_router.h
@@ -166,6 +166,8 @@ void ShowContextMenuAtPoint(const gfx::Point& point, const ui::MenuSourceType source_type) override; + bool HasEventsPendingDispatch() const; + size_t TouchEventAckQueueLengthForTesting() const; private:
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc b/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc index 69fdae7..d1727f7 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc
@@ -25,6 +25,7 @@ #include "content/test/test_render_view_host.h" #include "services/viz/public/interfaces/hit_test/input_target_client.mojom.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/base/ui_base_features.h" namespace content { @@ -266,8 +267,11 @@ child.view.get(), parent_view, view_root_.get(), false /* use_zoom_for_device_scale_factor */); - EXPECT_EQ(child.view.get(), - rwhier()->FindViewFromFrameSinkId(child.view->GetFrameSinkId())); + // This check often fails in Mash. https://crbug.com/933876 + if (!features::IsMultiProcessMash()) { + EXPECT_EQ(child.view.get(), rwhier()->FindViewFromFrameSinkId( + child.view->GetFrameSinkId())); + } return child; }
diff --git a/content/browser/renderer_host/render_widget_host_view_browsertest.cc b/content/browser/renderer_host/render_widget_host_view_browsertest.cc index 3c1eec4..5a5806b 100644 --- a/content/browser/renderer_host/render_widget_host_view_browsertest.cc +++ b/content/browser/renderer_host/render_widget_host_view_browsertest.cc
@@ -30,7 +30,7 @@ #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/test_utils.h" #include "content/shell/browser/shell.h" -#include "content/test/did_commit_provisional_load_interceptor.h" +#include "content/test/frame_host_interceptor.h" #include "net/base/filename_util.h" #include "net/dns/mock_host_resolver.h" #include "testing/gtest/include/gtest/gtest.h" @@ -142,21 +142,19 @@ // Helps to ensure that a navigation is committed after a compositor frame was // submitted by the renderer, but before corresponding ACK is sent back. -class CommitBeforeSwapAckSentHelper - : public DidCommitProvisionalLoadInterceptor { +class CommitBeforeSwapAckSentHelper : public FrameHostInterceptor { public: explicit CommitBeforeSwapAckSentHelper( WebContents* web_contents, RenderFrameSubmissionObserver* frame_observer) - : DidCommitProvisionalLoadInterceptor(web_contents), - frame_observer_(frame_observer) {} + : FrameHostInterceptor(web_contents), frame_observer_(frame_observer) {} private: - // DidCommitProvisionalLoadInterceptor: + // FrameHostInterceptor: bool WillDispatchDidCommitProvisionalLoad( RenderFrameHost* render_frame_host, ::FrameHostMsg_DidCommitProvisionalLoad_Params* params, - mojom::DidCommitProvisionalLoadInterfaceParamsPtr& interface_params) + mojom::DidCommitProvisionalLoadInterfaceParamsPtr* interface_params) override { base::MessageLoopCurrent::ScopedNestableTaskAllower allow; frame_observer_->WaitForAnyFrameSubmission();
diff --git a/content/browser/renderer_host/render_widget_targeter.cc b/content/browser/renderer_host/render_widget_targeter.cc index ac6ba400..02a079b 100644 --- a/content/browser/renderer_host/render_widget_targeter.cc +++ b/content/browser/renderer_host/render_widget_targeter.cc
@@ -209,6 +209,10 @@ unresponsive_views_.erase(view); } +bool RenderWidgetTargeter::HasEventsPendingDispatch() const { + return request_in_flight_ || !requests_.empty(); +} + void RenderWidgetTargeter::QueryClientInternal( RenderWidgetHostViewBase* root_view, RenderWidgetHostViewBase* target,
diff --git a/content/browser/renderer_host/render_widget_targeter.h b/content/browser/renderer_host/render_widget_targeter.h index c794db9..d6b9834 100644 --- a/content/browser/renderer_host/render_widget_targeter.h +++ b/content/browser/renderer_host/render_widget_targeter.h
@@ -99,6 +99,8 @@ void ViewWillBeDestroyed(RenderWidgetHostViewBase* view); + bool HasEventsPendingDispatch() const; + void set_async_hit_test_timeout_delay_for_testing( const base::TimeDelta& delay) { async_hit_test_timeout_delay_ = delay;
diff --git a/content/browser/resources/process/BUILD.gn b/content/browser/resources/process/BUILD.gn index 6f964f69..0d1c889 100644 --- a/content/browser/resources/process/BUILD.gn +++ b/content/browser/resources/process/BUILD.gn
@@ -12,7 +12,7 @@ js_library("process_internals") { deps = [ - "//content/browser/process_internals:mojo_bindings_js_externs", + "//content/browser/process_internals:mojo_bindings_js_library_for_compile", "//ui/webui/resources/js:assert", "//ui/webui/resources/js:util", "//ui/webui/resources/js/cr/ui:tree",
diff --git a/content/browser/security_exploit_browsertest.cc b/content/browser/security_exploit_browsertest.cc index 83d0a79..d051fd9 100644 --- a/content/browser/security_exploit_browsertest.cc +++ b/content/browser/security_exploit_browsertest.cc
@@ -7,7 +7,6 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/feature_list.h" -#include "base/guid.h" #include "base/macros.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" @@ -47,7 +46,7 @@ #include "content/public/test/test_utils.h" #include "content/shell/browser/shell.h" #include "content/test/content_browser_test_utils_internal.h" -#include "content/test/did_commit_provisional_load_interceptor.h" +#include "content/test/frame_host_interceptor.h" #include "content/test/mock_widget_impl.h" #include "content/test/test_content_browser_client.h" #include "ipc/ipc_security_test_util.h" @@ -315,15 +314,8 @@ void TestFileChooserWithPath(const base::FilePath& path); void IsolateOrigin(const std::string& hostname) { - ChildProcessSecurityPolicyImpl::GetInstance()->AddIsolatedOrigins( - {url::Origin::Create(embedded_test_server()->GetURL(hostname, "/"))}); - - // Force a BrowsingInstance swap by navigating cross-site (the newly - // isolated origin only affects *future* BrowsingInstances). - std::string cross_site_hostname = base::GenerateGUID() + ".com"; - EXPECT_TRUE(NavigateToURL( - shell(), - embedded_test_server()->GetURL(cross_site_hostname, "/title1.html"))); + IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(), + {hostname}); } }; @@ -652,13 +644,12 @@ // Interceptor that replaces |interface_params| with the specified // value for the first DidCommitProvisionalLoad message it observes in the given // |web_contents| while in scope. -class ScopedInterfaceParamsReplacer - : public DidCommitProvisionalLoadInterceptor { +class ScopedInterfaceParamsReplacer : public FrameHostInterceptor { public: ScopedInterfaceParamsReplacer( WebContents* web_contents, mojom::DidCommitProvisionalLoadInterfaceParamsPtr params_override) - : DidCommitProvisionalLoadInterceptor(web_contents), + : FrameHostInterceptor(web_contents), params_override_(std::move(params_override)) {} ~ScopedInterfaceParamsReplacer() override = default; @@ -666,9 +657,9 @@ bool WillDispatchDidCommitProvisionalLoad( RenderFrameHost* render_frame_host, ::FrameHostMsg_DidCommitProvisionalLoad_Params* params, - mojom::DidCommitProvisionalLoadInterfaceParamsPtr& interface_params) + mojom::DidCommitProvisionalLoadInterfaceParamsPtr* interface_params) override { - interface_params.Swap(¶ms_override_); + interface_params->Swap(¶ms_override_); return true; } @@ -1284,4 +1275,63 @@ EXPECT_EQ(bad_message::INVALID_INITIATOR_ORIGIN, kill_waiter.Wait()); } +class BeginNavigationInitiatorReplacer : public FrameHostInterceptor { + public: + BeginNavigationInitiatorReplacer(WebContents* web_contents, + const url::Origin& initiator_to_inject) + : FrameHostInterceptor(web_contents), + initiator_to_inject_(initiator_to_inject) {} + + bool WillDispatchBeginNavigation( + RenderFrameHost* render_frame_host, + CommonNavigationParams* common_params, + mojom::BeginNavigationParamsPtr* begin_params, + blink::mojom::BlobURLTokenPtr* blob_url_token, + mojom::NavigationClientAssociatedPtrInfo* navigation_client, + blink::mojom::NavigationInitiatorPtr* navigation_initiator) override { + if (is_activated_) { + common_params->initiator_origin = initiator_to_inject_; + is_activated_ = false; + } + + return true; + } + + void Activate() { is_activated_ = true; } + + private: + url::Origin initiator_to_inject_; + bool is_activated_ = false; + + DISALLOW_COPY_AND_ASSIGN(BeginNavigationInitiatorReplacer); +}; + +IN_PROC_BROWSER_TEST_F(SecurityExploitBrowserTest, + InvalidBeginNavigationInitiator) { + // Explicitly isolating a.com helps ensure that this test is applicable on + // platforms without site-per-process. + IsolateOrigin("a.com"); + + // Prepare to intercept BeginNavigation mojo IPC. This has to be done before + // the test creates the RenderFrameHostImpl that is the target of the IPC. + WebContents* web_contents = shell()->web_contents(); + BeginNavigationInitiatorReplacer injector( + web_contents, url::Origin::Create(GURL("http://b.com"))); + + // Navigate to a test page that will be locked to a.com. + GURL main_url(embedded_test_server()->GetURL("a.com", "/title1.html")); + EXPECT_TRUE(NavigateToURL(web_contents, main_url)); + + // Start monitoring for renderer kills. + RenderProcessHost* main_process = web_contents->GetMainFrame()->GetProcess(); + RenderProcessHostKillWaiter kill_waiter(main_process); + + // Have the main frame navigate and lie that the initiator origin is b.com. + injector.Activate(); + EXPECT_TRUE(ExecJs(web_contents, "window.location = '/title2.html';")); + + // Verify that the renderer was terminated. + EXPECT_EQ(bad_message::INVALID_INITIATOR_ORIGIN, kill_waiter.Wait()); +} + } // namespace content
diff --git a/content/browser/site_per_process_browsertest.cc b/content/browser/site_per_process_browsertest.cc index 753ecd5..62f600e7 100644 --- a/content/browser/site_per_process_browsertest.cc +++ b/content/browser/site_per_process_browsertest.cc
@@ -103,7 +103,7 @@ #include "content/shell/browser/shell.h" #include "content/shell/common/shell_switches.h" #include "content/test/content_browser_test_utils_internal.h" -#include "content/test/did_commit_provisional_load_interceptor.h" +#include "content/test/frame_host_interceptor.h" #include "ipc/constants.mojom.h" #include "ipc/ipc_security_test_util.h" #include "media/base/media_switches.h" @@ -529,17 +529,18 @@ // and re-layout in the same way since children might be in a different origin. void LayoutNonRecursiveForTestingViewportIntersection( WebContents* web_contents) { - static const char* script = - "function relayoutNonRecursiveForTestingViewportIntersection() {\ - var width = window.innerWidth;\ - var height = window.innerHeight * 0.75;\ - for (var i = 0; i < window.frames.length; i++) {\ - child = document.getElementById(\"child-\" + i);\ - child.width = width;\ - child.height = height;\ - }\ - }\ - relayoutNonRecursiveForTestingViewportIntersection();"; + static const char* script = R"( + function relayoutNonRecursiveForTestingViewportIntersection() { + var width = window.innerWidth; + var height = window.innerHeight * 0.75; + for (var i = 0; i < window.frames.length; i++) { + child = document.getElementById("child-" + i); + child.width = width; + child.height = height; + } + } + relayoutNonRecursiveForTestingViewportIntersection(); + )"; EXPECT_TRUE(ExecuteScript(web_contents, script)); } @@ -10660,9 +10661,9 @@ ASSERT_EQ(1u, root->child_count()); FrameTreeNode* child_node = root->child_at(0); - // Add a *slow* & passive touch event handler in the child. It needs to be - // passive to ensure TouchStart doesn't get acked until after the touch - // handler completes. + // Add a *slow* & non-passive touch event handler in the child. It needs to + // be non-passive to ensure TouchStart doesn't get acked until after the + // touch handler completes. EXPECT_TRUE(ExecuteScript(child_node, "touch_event_count = 0;\ function touch_handler(ev) {\ @@ -10738,11 +10739,12 @@ std::make_unique<SyntheticTapGesture>(root_tap_params); // Queue both GestureTaps, child first. - root_host->QueueSyntheticGesture( - std::move(child_tap_gesture), - base::BindOnce([](SyntheticGesture::Result result) { - EXPECT_EQ(SyntheticGesture::GESTURE_FINISHED, result); - })); + // Note that we want the SyntheticGestureController to start sending the + // root tap gesture as soon as it's finished sending the events for the + // child tap gesture, otherwise it would wait for the acks from the child + // before starting the root gesture which defeats the purpose of this test. + root_host->QueueSyntheticGestureCompleteImmediately( + std::move(child_tap_gesture)); root_host->QueueSyntheticGesture( std::move(root_tap_gesture), base::BindOnce([](SyntheticGesture::Result result) { @@ -11408,7 +11410,7 @@ // to |deferred_url| after receiving FrameNavigationControl::CommitNavigation; // whereas there is a fast cross-site navigation taking place in the same // frame which starts second but finishes first. -class CommitMessageOrderReverser : public DidCommitProvisionalLoadInterceptor { +class CommitMessageOrderReverser : public FrameHostInterceptor { public: using DidStartDeferringCommitCallback = base::OnceCallback<void(RenderFrameHost*)>; @@ -11417,7 +11419,7 @@ WebContents* web_contents, const GURL& deferred_url, DidStartDeferringCommitCallback deferred_url_triggered_action) - : DidCommitProvisionalLoadInterceptor(web_contents), + : FrameHostInterceptor(web_contents), deferred_url_(deferred_url), deferred_url_triggered_action_( std::move(deferred_url_triggered_action)) {} @@ -11429,7 +11431,7 @@ bool WillDispatchDidCommitProvisionalLoad( RenderFrameHost* render_frame_host, ::FrameHostMsg_DidCommitProvisionalLoad_Params* params, - mojom::DidCommitProvisionalLoadInterfaceParamsPtr& interface_params) + mojom::DidCommitProvisionalLoadInterfaceParamsPtr* interface_params) override { // The DidCommitProvisionalLoad message is dispatched once this method // returns, so to defer committing the the navigation to |deferred_url_|, @@ -12308,10 +12310,10 @@ // Helper class to intercept DidCommitProvisionalLoad messages and inject a // call to close the current tab right before them. -class ClosePageBeforeCommitHelper : public DidCommitProvisionalLoadInterceptor { +class ClosePageBeforeCommitHelper : public FrameHostInterceptor { public: explicit ClosePageBeforeCommitHelper(WebContents* web_contents) - : DidCommitProvisionalLoadInterceptor(web_contents) {} + : FrameHostInterceptor(web_contents) {} void Wait() { run_loop_.reset(new base::RunLoop()); @@ -12320,11 +12322,11 @@ } private: - // DidCommitProvisionalLoadInterceptor: + // FrameHostInterceptor: bool WillDispatchDidCommitProvisionalLoad( RenderFrameHost* render_frame_host, ::FrameHostMsg_DidCommitProvisionalLoad_Params* params, - mojom::DidCommitProvisionalLoadInterfaceParamsPtr& interface_params) + mojom::DidCommitProvisionalLoadInterfaceParamsPtr* interface_params) override { RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( render_frame_host->GetRenderViewHost()); @@ -13602,7 +13604,7 @@ "actions" : [ { "name": "pointerDown", "x": %f, "y": %f}, { "name": "pointerUp"}, - { "name": "pause", "duration": 0.05 }, + { "name": "pause", "duration": 50 }, { "name": "pointerDown", "x": %f, "y": %f}, { "name": "pointerUp"} ] @@ -14293,7 +14295,7 @@ "actions" : [ { "name": "pointerDown", "x": %f, "y": %f}, { "name": "pointerMove", "x": %f, "y": %f}, - { "name": "pause", "duration": 0.3 }, + { "name": "pause", "duration": 300 }, { "name": "pointerUp"} ] }]
diff --git a/content/browser/site_per_process_unload_browsertest.cc b/content/browser/site_per_process_unload_browsertest.cc index a54bdaad..3aade57 100644 --- a/content/browser/site_per_process_unload_browsertest.cc +++ b/content/browser/site_per_process_unload_browsertest.cc
@@ -36,7 +36,6 @@ #include "content/public/test/content_browser_test_utils.h" #include "content/shell/browser/shell.h" #include "content/test/content_browser_test_utils_internal.h" -#include "content/test/did_commit_provisional_load_interceptor.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h"
diff --git a/content/browser/storage_partition_impl_unittest.cc b/content/browser/storage_partition_impl_unittest.cc index ba78ffd..41a5dcf 100644 --- a/content/browser/storage_partition_impl_unittest.cc +++ b/content/browser/storage_partition_impl_unittest.cc
@@ -176,8 +176,8 @@ await_completion_.Notify(); } - void SetCookieCallback(bool result) { - ASSERT_TRUE(result); + void SetCookieCallback(CanonicalCookie::CookieInclusionStatus result) { + ASSERT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, result); await_completion_.Notify(); }
diff --git a/content/browser/tracing/background_tracing_manager_impl.cc b/content/browser/tracing/background_tracing_manager_impl.cc index 65ea05d..dea43cc 100644 --- a/content/browser/tracing/background_tracing_manager_impl.cc +++ b/content/browser/tracing/background_tracing_manager_impl.cc
@@ -730,7 +730,7 @@ "benchmark,toplevel,ipc,base,browser,navigation,omnibox,ui,shutdown," "safe_browsing,Java,EarlyJava,loading,startup,mojom,renderer_host," "disabled-by-default-system_stats,disabled-by-default-cpu_profiler," - "dwrite", + "dwrite,font_loader,font_service", record_mode); // Filter only browser process events. base::trace_event::TraceConfig::ProcessFilterConfig process_config( @@ -741,7 +741,8 @@ case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_RENDERERS: return TraceConfig( "benchmark,toplevel,ipc,base,ui,v8,renderer,blink,blink_gc,mojom," - "latency,latencyInfo,renderer_host,cc,memory,dwrite," + "latency,latencyInfo,renderer_host,cc,memory,dwrite,font_loader," + "font_service," "disabled-by-default-v8.gc," "disabled-by-default-blink_gc," "disabled-by-default-renderer.scheduler,"
diff --git a/content/browser/web_package/origins_list.cc b/content/browser/web_package/origins_list.cc deleted file mode 100644 index 05faed7..0000000 --- a/content/browser/web_package/origins_list.cc +++ /dev/null
@@ -1,82 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/web_package/origins_list.h" - -#include "base/strings/string_split.h" -#include "url/gurl.h" - -namespace content { -namespace signed_exchange_utils { - -constexpr char kSubdomainMatchPrefix[] = "*."; - -OriginsList::OriginsList() = default; - -OriginsList::OriginsList(base::StringPiece str) { - std::vector<base::StringPiece> elements = base::SplitStringPiece( - str, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); - - for (base::StringPiece element : elements) { - bool subdomain_match = false; - if (base::StartsWith(element, kSubdomainMatchPrefix, - base::CompareCase::SENSITIVE)) { - subdomain_match = true; - element.remove_prefix(sizeof(kSubdomainMatchPrefix) - 1); - } - if (base::StartsWith(element, - "https:", base::CompareCase::INSENSITIVE_ASCII)) { - LOG(ERROR) << "OriginsList entry should omit https scheme: \"" << element - << "\""; - continue; - } - - std::string url_str("https://"); - element.AppendToString(&url_str); - GURL url(url_str); - if (!url.is_valid()) { - LOG(ERROR) << "Failed to parse an OriginsList entry to a valid Origin: \"" - << element << "\""; - continue; - } - DCHECK(url.SchemeIs("https")); - - url::Origin origin = url::Origin::Create(url); - if (subdomain_match) { - subdomain_match_origins_.push_back(origin); - } else { - exact_match_origins_.insert(origin); - } - } -} - -OriginsList::OriginsList(OriginsList&&) = default; -OriginsList::~OriginsList() = default; - -bool OriginsList::IsEmpty() const { - return exact_match_origins_.empty() && subdomain_match_origins_.empty(); -} - -bool OriginsList::Match(const url::Origin& origin) const { - // OriginsList only contains HTTPS scheme origins. - if (origin.scheme() != url::kHttpsScheme) { - return false; - } - - if (exact_match_origins_.find(origin) != exact_match_origins_.end()) { - return true; - } - - for (const auto& subdomain_match_origin : subdomain_match_origins_) { - if (origin.DomainIs(subdomain_match_origin.host()) && - origin.port() == subdomain_match_origin.port()) { - return true; - } - } - - return false; -} - -} // namespace signed_exchange_utils -} // namespace content
diff --git a/content/browser/web_package/origins_list.h b/content/browser/web_package/origins_list.h deleted file mode 100644 index 4bd3cff..0000000 --- a/content/browser/web_package/origins_list.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_BROWSER_WEB_PACKAGE_ORIGINS_LIST_H_ -#define CONTENT_BROWSER_WEB_PACKAGE_ORIGINS_LIST_H_ - -#include <vector> - -#include "base/containers/flat_set.h" -#include "base/strings/string_piece.h" -#include "content/common/content_export.h" -#include "url/origin.h" - -namespace content { -namespace signed_exchange_utils { - -// OriginsList can query if a particular origin |Match|. -// OriginsList can only match HTTPS origins. -class CONTENT_EXPORT OriginsList { - public: - OriginsList(); - - // Creates an OriginsList from comma-separated list of hosts. - // - // Entries starting with "*." will match with subdomains. - // - // For example, "example.com,*.google.com" will create an - // OriginsList that match exactly "example.com" but not its - // subdomains, and all subdomains of "google.com". - // - // Note: Entries should NOT start with "https://", but start from hostname. - explicit OriginsList(base::StringPiece str); - - OriginsList(OriginsList&&); - ~OriginsList(); - - // Returns true when |this| has an empty list to match - // (i.e. no origins would match). - bool IsEmpty() const; - - bool Match(const url::Origin& origin) const; - - private: - base::flat_set<url::Origin> exact_match_origins_; - std::vector<url::Origin> subdomain_match_origins_; -}; - -} // namespace signed_exchange_utils -} // namespace content - -#endif // CONTENT_BROWSER_WEB_PACKAGE_ORIGINS_LIST_H_
diff --git a/content/browser/web_package/origins_list_unittest.cc b/content/browser/web_package/origins_list_unittest.cc deleted file mode 100644 index 3338a3b..0000000 --- a/content/browser/web_package/origins_list_unittest.cc +++ /dev/null
@@ -1,77 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/web_package/origins_list.h" - -#include "base/callback.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" -#include "url/origin.h" - -namespace content { -namespace signed_exchange_utils { - -TEST(OriginsList, IsEmpty) { - OriginsList origins_list; - EXPECT_TRUE(origins_list.IsEmpty()); -} - -TEST(OriginsList, ExactMatch) { - OriginsList origins_list( - "example.com,test.example.com,https://invalid.entry,example.net:1234"); - - EXPECT_FALSE(origins_list.IsEmpty()); - - static constexpr const char* kShouldMatchList[] = { - "https://example.com", "https://test.example.com", - "https://example.net:1234", - }; - - for (const char* should_match : kShouldMatchList) { - EXPECT_TRUE(origins_list.Match(url::Origin::Create(GURL(should_match)))) - << "OriginList should match url: " << should_match; - } - - static constexpr const char* kShouldNotMatchList[] = { - "http://example.com", "https://subdomain.example.com", - "https://notexample.com", "https://invalid.entry", - "https://example.net", "https://example.net:5432", - }; - - for (const char* should_not_match : kShouldNotMatchList) { - EXPECT_FALSE( - origins_list.Match(url::Origin::Create(GURL(should_not_match)))) - << "OriginList should not match url: " << should_not_match; - } -} - -TEST(OriginsList, SubdomainMatch) { - OriginsList origins_list("*.example.com,*.example.net:1234"); - - EXPECT_FALSE(origins_list.IsEmpty()); - - static constexpr const char* kShouldMatchList[] = { - "https://example.com", "https://test.example.com", - "https://test.test2.example.com", "https://test.example.net:1234", - }; - - for (const char* should_match : kShouldMatchList) { - EXPECT_TRUE(origins_list.Match(url::Origin::Create(GURL(should_match)))) - << "OriginList should match url: " << should_match; - } - - static constexpr const char* kShouldNotMatchList[] = { - "http://example.com", "https://notexample.com", - "https://test.example.net", "https://test.example.net:5432", - }; - - for (const char* should_not_match : kShouldNotMatchList) { - EXPECT_FALSE( - origins_list.Match(url::Origin::Create(GURL(should_not_match)))) - << "OriginList should not match url: " << should_not_match; - } -} - -} // namespace signed_exchange_utils -} // namespace content
diff --git a/content/browser/web_package/signed_exchange_request_handler_browsertest.cc b/content/browser/web_package/signed_exchange_request_handler_browsertest.cc index a960320f..255e9ae 100644 --- a/content/browser/web_package/signed_exchange_request_handler_browsertest.cc +++ b/content/browser/web_package/signed_exchange_request_handler_browsertest.cc
@@ -31,6 +31,7 @@ #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/content_cert_verifier_browser_test.h" +#include "content/public/test/signed_exchange_browser_test_helper.h" #include "content/public/test/test_navigation_throttle.h" #include "content/public/test/url_loader_interceptor.h" #include "content/shell/browser/shell.h" @@ -56,9 +57,6 @@ namespace { -const uint64_t kSignatureHeaderDate = 1520834000; // 2018-03-12T05:53:20Z -const uint64_t kSignatureHeaderExpires = 1520837600; // 2018-03-12T06:53:20Z - constexpr char kExpectedSXGEnabledAcceptHeaderForPrefetch[] = "application/signed-exchange;v=b3;q=0.9,*/*;q=0.8"; @@ -113,60 +111,26 @@ } void SetUp() override { - SignedExchangeHandler::SetVerificationTimeForTesting( - base::Time::UnixEpoch() + - base::TimeDelta::FromSeconds(kSignatureHeaderDate)); + sxg_test_helper_.SetUp(); feature_list_.InitWithFeatures({features::kSignedHTTPExchange}, {}); CertVerifierBrowserTest::SetUp(); } void TearDownOnMainThread() override { - interceptor_.reset(); - SignedExchangeHandler::SetVerificationTimeForTesting( - base::Optional<base::Time>()); + sxg_test_helper_.TearDownOnMainThread(); } protected: - static scoped_refptr<net::X509Certificate> LoadCertificate( - const std::string& cert_file) { - base::ScopedAllowBlockingForTesting allow_io; - base::FilePath dir_path; - base::PathService::Get(content::DIR_TEST_DATA, &dir_path); - dir_path = dir_path.AppendASCII("sxg"); - - return net::CreateCertificateChainFromFile( - dir_path, cert_file, net::X509Certificate::FORMAT_PEM_CERT_SEQUENCE); - } - void InstallUrlInterceptor(const GURL& url, const std::string& data_path) { - if (base::FeatureList::IsEnabled(network::features::kNetworkService)) { - if (!interceptor_) { - interceptor_ = std::make_unique< - URLLoaderInterceptor>(base::BindRepeating( - &SignedExchangeRequestHandlerBrowserTestBase::OnInterceptCallback, - base::Unretained(this))); - } - interceptor_data_path_map_[url] = data_path; - } else { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&InstallMockInterceptors, url, data_path)); - } + sxg_test_helper_.InstallUrlInterceptor(url, data_path); } void InstallMockCert() { - // Make the MockCertVerifier treat the certificate - // "prime256v1-sha256.public.pem" as valid for "test.example.org". - scoped_refptr<net::X509Certificate> original_cert = - LoadCertificate("prime256v1-sha256.public.pem"); - net::CertVerifyResult dummy_result; - dummy_result.verified_cert = original_cert; - dummy_result.cert_status = net::OK; - dummy_result.ocsp_result.response_status = net::OCSPVerifyResult::PROVIDED; - dummy_result.ocsp_result.revocation_status = - net::OCSPRevocationStatus::GOOD; - mock_cert_verifier()->AddResultForCertAndHost( - original_cert, "test.example.org", dummy_result, net::OK); + sxg_test_helper_.InstallMockCert(mock_cert_verifier()); + } + + void InstallMockCertChainInterceptor() { + sxg_test_helper_.InstallMockCertChainInterceptor(); } void TriggerPrefetch(const GURL& url, bool expect_success) { @@ -182,26 +146,8 @@ const base::HistogramTester histogram_tester_; private: - static void InstallMockInterceptors(const GURL& url, - const std::string& data_path) { - base::FilePath root_path; - CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &root_path)); - net::URLRequestFilter::GetInstance()->AddUrlInterceptor( - url, net::URLRequestMockHTTPJob::CreateInterceptorForSingleFile( - root_path.AppendASCII(data_path))); - } - - bool OnInterceptCallback(URLLoaderInterceptor::RequestParams* params) { - const auto it = interceptor_data_path_map_.find(params->url_request.url); - if (it == interceptor_data_path_map_.end()) - return false; - URLLoaderInterceptor::WriteResponse(it->second, params->client.get()); - return true; - } - base::test::ScopedFeatureList feature_list_; - std::unique_ptr<URLLoaderInterceptor> interceptor_; - std::map<GURL, std::string> interceptor_data_path_map_; + SignedExchangeBrowserTestHelper sxg_test_helper_; DISALLOW_COPY_AND_ASSIGN(SignedExchangeRequestHandlerBrowserTestBase); }; @@ -229,10 +175,8 @@ }; IN_PROC_BROWSER_TEST_P(SignedExchangeRequestHandlerBrowserTest, Simple) { - InstallUrlInterceptor( - GURL("https://cert.example.org/cert.msg"), - "content/test/data/sxg/test.example.org.public.pem.cbor"); InstallMockCert(); + InstallMockCertChainInterceptor(); embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data"); ASSERT_TRUE(embedded_test_server()->Start()); @@ -264,7 +208,7 @@ net::X509Certificate::CalculateFingerprint256( entry->GetSSL().certificate->cert_buffer()); scoped_refptr<net::X509Certificate> original_cert = - LoadCertificate("prime256v1-sha256.public.pem"); + SignedExchangeBrowserTestHelper::LoadCertificate(); const net::SHA256HashValue original_fingerprint = net::X509Certificate::CalculateFingerprint256( original_cert->cert_buffer()); @@ -314,12 +258,10 @@ IN_PROC_BROWSER_TEST_P(SignedExchangeRequestHandlerBrowserTest, InvalidContentType) { - InstallUrlInterceptor( - GURL("https://cert.example.org/cert.msg"), - "content/test/data/sxg/test.example.org.public.pem.cbor"); InstallUrlInterceptor(GURL("https://test.example.org/test/"), "content/test/data/sxg/fallback.html"); InstallMockCert(); + InstallMockCertChainInterceptor(); embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data"); ASSERT_TRUE(embedded_test_server()->Start()); @@ -342,11 +284,10 @@ IN_PROC_BROWSER_TEST_P(SignedExchangeRequestHandlerBrowserTest, Expired) { SignedExchangeHandler::SetVerificationTimeForTesting( base::Time::UnixEpoch() + - base::TimeDelta::FromSeconds(kSignatureHeaderExpires + 1)); + base::TimeDelta::FromSeconds( + SignedExchangeBrowserTestHelper::kSignatureHeaderExpires + 1)); - InstallUrlInterceptor( - GURL("https://cert.example.org/cert.msg"), - "content/test/data/sxg/test.example.org.public.pem.cbor"); + InstallMockCertChainInterceptor(); InstallUrlInterceptor(GURL("https://test.example.org/test/"), "content/test/data/sxg/fallback.html"); InstallMockCert(); @@ -525,9 +466,7 @@ IN_PROC_BROWSER_TEST_F(SignedExchangeRequestHandlerRealCertVerifierBrowserTest, Basic) { - InstallUrlInterceptor( - GURL("https://cert.example.org/cert.msg"), - "content/test/data/sxg/test.example.org.public.pem.cbor"); + InstallMockCertChainInterceptor(); InstallUrlInterceptor(GURL("https://test.example.org/test/"), "content/test/data/sxg/fallback.html"); @@ -596,10 +535,8 @@ // SW-scope: https://test.example.org/test/ // SXG physical URL: http://127.0.0.1:PORT/sxg/test.example.org_test.sxg // SXG logical URL: https://test.example.org/test/ - InstallUrlInterceptor( - GURL("https://cert.example.org/cert.msg"), - "content/test/data/sxg/test.example.org.public.pem.cbor"); InstallMockCert(); + InstallMockCertChainInterceptor(); const GURL install_sw_url = GURL("https://test.example.org/test/publisher-service-worker.html"); @@ -633,10 +570,8 @@ // SW-scope: http://127.0.0.1:PORT/sxg/ // SXG physical URL: http://127.0.0.1:PORT/sxg/test.example.org_test.sxg // SXG logical URL: https://test.example.org/test/ - InstallUrlInterceptor( - GURL("https://cert.example.org/cert.msg"), - "content/test/data/sxg/test.example.org.public.pem.cbor"); InstallMockCert(); + InstallMockCertChainInterceptor(); embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data"); ASSERT_TRUE(embedded_test_server()->Start()); @@ -665,10 +600,8 @@ // SW-scope: https://test.example.org/scope/ // SXG physical URL: https://test.example.org/scope/test.example.org_test.sxg // SXG logical URL: https://test.example.org/test/ - InstallUrlInterceptor( - GURL("https://cert.example.org/cert.msg"), - "content/test/data/sxg/test.example.org.public.pem.cbor"); InstallMockCert(); + InstallMockCertChainInterceptor(); InstallUrlInterceptor(GURL("https://test.example.org/scope/test.sxg"), "content/test/data/sxg/test.example.org_test.sxg"); @@ -703,10 +636,8 @@ RegisterServiceWorkerFromSignedExchange) { // SXG physical URL: http://127.0.0.1:PORT/sxg/test.example.org_test.sxg // SXG logical URL: https://test.example.org/test/ - InstallUrlInterceptor( - GURL("https://cert.example.org/cert.msg"), - "content/test/data/sxg/test.example.org.public.pem.cbor"); InstallMockCert(); + InstallMockCertChainInterceptor(); InstallUrlInterceptor( GURL("https://test.example.org/test/publisher-service-worker.js"), @@ -755,17 +686,11 @@ struct SignedExchangeAcceptHeaderBrowserTestParam { SignedExchangeAcceptHeaderBrowserTestParam( bool sxg_enabled, - bool sxg_origin_trial_enabled, - bool sxg_accept_header_enabled, bool service_worker_servicification_enabled) : sxg_enabled(sxg_enabled), - sxg_origin_trial_enabled(sxg_origin_trial_enabled), - sxg_accept_header_enabled(sxg_accept_header_enabled), service_worker_servicification_enabled( service_worker_servicification_enabled) {} const bool sxg_enabled; - const bool sxg_origin_trial_enabled; - const bool sxg_accept_header_enabled; const bool service_worker_servicification_enabled; }; @@ -776,8 +701,7 @@ public: using self = SignedExchangeAcceptHeaderBrowserTest; SignedExchangeAcceptHeaderBrowserTest() - : enabled_https_server_(net::EmbeddedTestServer::TYPE_HTTPS), - disabled_https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {} + : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {} ~SignedExchangeAcceptHeaderBrowserTest() override = default; protected: @@ -789,11 +713,6 @@ } else { disable_features.push_back(features::kSignedHTTPExchange); } - if (GetParam().sxg_origin_trial_enabled) { - enable_features.push_back(features::kSignedHTTPExchangeOriginTrial); - } else { - disable_features.push_back(features::kSignedHTTPExchangeOriginTrial); - } if (GetParam().service_worker_servicification_enabled) { enable_features.push_back(blink::features::kServiceWorkerServicification); } else { @@ -802,27 +721,13 @@ } feature_list_.InitWithFeatures(enable_features, disable_features); - enabled_https_server_.ServeFilesFromSourceDirectory("content/test/data"); - enabled_https_server_.RegisterRequestHandler( + https_server_.ServeFilesFromSourceDirectory("content/test/data"); + https_server_.RegisterRequestHandler( base::BindRepeating(&self::RedirectResponseHandler)); - enabled_https_server_.RegisterRequestMonitor( + https_server_.RegisterRequestMonitor( base::BindRepeating(&self::MonitorRequest, base::Unretained(this))); - ASSERT_TRUE(enabled_https_server_.Start()); + ASSERT_TRUE(https_server_.Start()); - disabled_https_server_.ServeFilesFromSourceDirectory("content/test/data"); - disabled_https_server_.RegisterRequestHandler( - base::BindRepeating(&self::RedirectResponseHandler)); - disabled_https_server_.RegisterRequestMonitor( - base::BindRepeating(&self::MonitorRequest, base::Unretained(this))); - ASSERT_TRUE(disabled_https_server_.Start()); - - if (GetParam().sxg_accept_header_enabled) { - std::map<std::string, std::string> feature_parameters; - feature_parameters["OriginsList"] = - base::StringPrintf("127.0.0.1:%u", enabled_https_server_.port()); - feature_list_for_accept_header_.InitAndEnableFeatureWithParameters( - features::kSignedHTTPExchangeAcceptHeader, feature_parameters); - } ContentBrowserTest::SetUp(); } @@ -834,25 +739,17 @@ } bool ShouldHaveSXGAcceptHeaderInEnabledOrigin() const { - return GetParam().sxg_enabled || (GetParam().sxg_origin_trial_enabled && - GetParam().sxg_accept_header_enabled); - } - - bool ShouldHaveSXGAcceptHeaderInDisabledOrigin() const { return GetParam().sxg_enabled; } + bool ShouldHaveSXGAcceptHeader() const { return GetParam().sxg_enabled; } + void CheckAcceptHeader(const GURL& url, bool is_navigation) { - const bool is_enabled_origin = - url.IntPort() == enabled_https_server_.port(); - const bool should_have_sxg = - is_enabled_origin ? ShouldHaveSXGAcceptHeaderInEnabledOrigin() - : ShouldHaveSXGAcceptHeaderInDisabledOrigin(); const auto accept_header = GetInterceptedAcceptHeader(url); ASSERT_TRUE(accept_header); EXPECT_EQ( *accept_header, - should_have_sxg + ShouldHaveSXGAcceptHeader() ? (is_navigation ? std::string(network::kFrameAcceptHeader) + std::string(kAcceptHeaderSignedExchangeSuffix) @@ -885,8 +782,7 @@ void ClearInterceptedAcceptHeaders() { url_accept_header_map_.clear(); } - net::EmbeddedTestServer enabled_https_server_; - net::EmbeddedTestServer disabled_https_server_; + net::EmbeddedTestServer https_server_; private: static std::unique_ptr<net::test_server::HttpResponse> @@ -917,121 +813,51 @@ std::map<GURL, std::string> url_accept_header_map_; }; -IN_PROC_BROWSER_TEST_P(SignedExchangeAcceptHeaderBrowserTest, EnabledOrigin) { - const GURL enabled_test_url = enabled_https_server_.GetURL("/sxg/test.html"); +IN_PROC_BROWSER_TEST_P(SignedExchangeAcceptHeaderBrowserTest, Simple) { + const GURL test_url = https_server_.GetURL("/sxg/test.html"); EXPECT_EQ(ShouldHaveSXGAcceptHeaderInEnabledOrigin(), - signed_exchange_utils::ShouldAdvertiseAcceptHeader( - url::Origin::Create(enabled_test_url))); - NavigateAndWaitForTitle(enabled_test_url, enabled_test_url.spec()); - CheckNavigationAcceptHeader({enabled_test_url}); + signed_exchange_utils::IsSignedExchangeHandlingEnabled()); + NavigateAndWaitForTitle(test_url, test_url.spec()); + CheckNavigationAcceptHeader({test_url}); } -IN_PROC_BROWSER_TEST_P(SignedExchangeAcceptHeaderBrowserTest, DisabledOrigin) { - const GURL disabled_test_url = - disabled_https_server_.GetURL("/sxg/test.html"); - EXPECT_EQ(GetParam().sxg_enabled, - signed_exchange_utils::ShouldAdvertiseAcceptHeader( - url::Origin::Create(disabled_test_url))); +IN_PROC_BROWSER_TEST_P(SignedExchangeAcceptHeaderBrowserTest, Redirect) { + const GURL test_url = https_server_.GetURL("/sxg/test.html"); + const GURL redirect_url = https_server_.GetURL("/r?" + test_url.spec()); + const GURL redirect_redirect_url = + https_server_.GetURL("/r?" + redirect_url.spec()); + NavigateAndWaitForTitle(redirect_redirect_url, test_url.spec()); - NavigateAndWaitForTitle(disabled_test_url, disabled_test_url.spec()); - CheckNavigationAcceptHeader({disabled_test_url}); -} - -IN_PROC_BROWSER_TEST_P(SignedExchangeAcceptHeaderBrowserTest, - RedirectEnabledToDisabledToEnabled) { - const GURL enabled_test_url = enabled_https_server_.GetURL("/sxg/test.html"); - const GURL redirect_disabled_to_enabled_url = - disabled_https_server_.GetURL("/r?" + enabled_test_url.spec()); - const GURL redirect_enabled_to_disabled_to_enabled_url = - enabled_https_server_.GetURL("/r?" + - redirect_disabled_to_enabled_url.spec()); - NavigateAndWaitForTitle(redirect_enabled_to_disabled_to_enabled_url, - enabled_test_url.spec()); - - CheckNavigationAcceptHeader({redirect_enabled_to_disabled_to_enabled_url, - redirect_disabled_to_enabled_url, - enabled_test_url}); -} - -IN_PROC_BROWSER_TEST_P(SignedExchangeAcceptHeaderBrowserTest, - RedirectDisabledToEnabledToDisabled) { - const GURL disabled_test_url = - disabled_https_server_.GetURL("/sxg/test.html"); - const GURL redirect_enabled_to_disabled_url = - enabled_https_server_.GetURL("/r?" + disabled_test_url.spec()); - const GURL redirect_disabled_to_enabled_to_disabled_url = - disabled_https_server_.GetURL("/r?" + - redirect_enabled_to_disabled_url.spec()); - NavigateAndWaitForTitle(redirect_disabled_to_enabled_to_disabled_url, - disabled_test_url.spec()); - - CheckNavigationAcceptHeader({redirect_disabled_to_enabled_to_disabled_url, - redirect_enabled_to_disabled_url, - disabled_test_url}); + CheckNavigationAcceptHeader({redirect_redirect_url, redirect_url, test_url}); } IN_PROC_BROWSER_TEST_P(SignedExchangeAcceptHeaderBrowserTest, PrefetchEnabledPageEnabledTarget) { - const GURL enabled_target = enabled_https_server_.GetURL("/sxg/hello.txt"); - const GURL enabled_page_url = enabled_https_server_.GetURL( - std::string("/sxg/prefetch.html#") + enabled_target.spec()); - NavigateAndWaitForTitle(enabled_page_url, "OK"); - CheckPrefetchAcceptHeader({enabled_target}); + const GURL target = https_server_.GetURL("/sxg/hello.txt"); + const GURL page_url = + https_server_.GetURL(std::string("/sxg/prefetch.html#") + target.spec()); + NavigateAndWaitForTitle(page_url, "OK"); + CheckPrefetchAcceptHeader({target}); } IN_PROC_BROWSER_TEST_P(SignedExchangeAcceptHeaderBrowserTest, - PrefetchEnabledPageDisabledTarget) { - const GURL disabled_target = disabled_https_server_.GetURL("/sxg/hello.txt"); - const GURL enabled_page_url = enabled_https_server_.GetURL( - std::string("/sxg/prefetch.html#") + disabled_target.spec()); - NavigateAndWaitForTitle(enabled_page_url, "OK"); - CheckPrefetchAcceptHeader({disabled_target}); -} + PrefetchRedirect) { + const GURL target = https_server_.GetURL("/sxg/hello.txt"); + const GURL redirect_url = https_server_.GetURL("/r?" + target.spec()); + const GURL redirect_redirect_url = + https_server_.GetURL("/r?" + redirect_url.spec()); -IN_PROC_BROWSER_TEST_P(SignedExchangeAcceptHeaderBrowserTest, - PrefetchDisabledPageEnabledTarget) { - const GURL enabled_target = enabled_https_server_.GetURL("/sxg/hello.txt"); - const GURL disabled_page_url = disabled_https_server_.GetURL( - std::string("/sxg/prefetch.html#") + enabled_target.spec()); - NavigateAndWaitForTitle(disabled_page_url, "OK"); - CheckPrefetchAcceptHeader({enabled_target}); -} + const GURL page_url = https_server_.GetURL( + std::string("/sxg/prefetch.html#") + redirect_redirect_url.spec()); -IN_PROC_BROWSER_TEST_P(SignedExchangeAcceptHeaderBrowserTest, - PrefetchDisabledPageDisabledTarget) { - const GURL disabled_target = disabled_https_server_.GetURL("/sxg/hello.txt"); - const GURL disabled_page_url = disabled_https_server_.GetURL( - std::string("/sxg/prefetch.html#") + disabled_target.spec()); - NavigateAndWaitForTitle(disabled_page_url, "OK"); - CheckPrefetchAcceptHeader({disabled_target}); -} + NavigateAndWaitForTitle(page_url, "OK"); -IN_PROC_BROWSER_TEST_P( - SignedExchangeAcceptHeaderBrowserTest, - PrefetchEnabledPageRedirectFromDisabledToEnabledToDisabledTarget) { - const GURL disabled_target = disabled_https_server_.GetURL("/sxg/hello.txt"); - const GURL redirect_enabled_to_disabled_url = - enabled_https_server_.GetURL("/r?" + disabled_target.spec()); - const GURL redirect_disabled_to_enabled_to_disabled_url = - disabled_https_server_.GetURL("/r?" + - redirect_enabled_to_disabled_url.spec()); - - const GURL enabled_page_url = enabled_https_server_.GetURL( - std::string("/sxg/prefetch.html#") + - redirect_disabled_to_enabled_to_disabled_url.spec()); - - NavigateAndWaitForTitle(enabled_page_url, "OK"); - - CheckPrefetchAcceptHeader({redirect_disabled_to_enabled_to_disabled_url, - redirect_enabled_to_disabled_url, - disabled_target}); + CheckPrefetchAcceptHeader({redirect_redirect_url, redirect_url, target}); } IN_PROC_BROWSER_TEST_P(SignedExchangeAcceptHeaderBrowserTest, ServiceWorker) { - NavigateAndWaitForTitle( - enabled_https_server_.GetURL("/sxg/service-worker.html"), "Done"); - NavigateAndWaitForTitle( - disabled_https_server_.GetURL("/sxg/service-worker.html"), "Done"); + NavigateAndWaitForTitle(https_server_.GetURL("/sxg/service-worker.html"), + "Done"); const std::string frame_accept = std::string(network::kFrameAcceptHeader); const std::string frame_accept_with_sxg = @@ -1043,105 +869,53 @@ SCOPED_TRACE(scope); const bool is_generated_scope = scope == std::string("/sxg/sw-scope-generated/"); - const GURL enabled_target_url = - enabled_https_server_.GetURL(scope + "test.html"); - const GURL disabled_target_url = - disabled_https_server_.GetURL(scope + "test.html"); - const GURL redirect_disabled_to_enabled_target_url = - disabled_https_server_.GetURL("/r?" + enabled_target_url.spec()); - const GURL redirect_enabled_to_disabled_to_enabled_target_url = - enabled_https_server_.GetURL( - "/r?" + redirect_disabled_to_enabled_target_url.spec()); - const GURL redirect_enabled_to_disabled_target_url = - enabled_https_server_.GetURL("/r?" + disabled_target_url.spec()); - const GURL redirect_disabled_to_enabled_to_disabled_target_url = - disabled_https_server_.GetURL( - "/r?" + redirect_enabled_to_disabled_target_url.spec()); + const GURL target_url = https_server_.GetURL(scope + "test.html"); + const GURL redirect_target_url = + https_server_.GetURL("/r?" + target_url.spec()); + const GURL redirect_redirect_target_url = + https_server_.GetURL("/r?" + redirect_target_url.spec()); - const std::string expected_enabled_title = - is_generated_scope ? (ShouldHaveSXGAcceptHeaderInEnabledOrigin() - ? frame_accept_with_sxg - : frame_accept) - : "Done"; - const std::string expected_disabled_title = - is_generated_scope ? (ShouldHaveSXGAcceptHeaderInDisabledOrigin() - ? frame_accept_with_sxg - : frame_accept) - : "Done"; - const base::Optional<std::string> expected_enabled_target_accept_header = - is_generated_scope ? base::nullopt - : base::Optional<std::string>( - ShouldHaveSXGAcceptHeaderInEnabledOrigin() - ? frame_accept_with_sxg - : frame_accept); - const base::Optional<std::string> expected_disabled_target_accept_header = - is_generated_scope ? base::nullopt - : base::Optional<std::string>( - ShouldHaveSXGAcceptHeaderInDisabledOrigin() - ? frame_accept_with_sxg - : frame_accept); + const std::string expected_title = + is_generated_scope + ? (ShouldHaveSXGAcceptHeader() ? frame_accept_with_sxg + : frame_accept) + : "Done"; + const base::Optional<std::string> expected_target_accept_header = + is_generated_scope + ? base::nullopt + : base::Optional<std::string>(ShouldHaveSXGAcceptHeader() + ? frame_accept_with_sxg + : frame_accept); - NavigateAndWaitForTitle(enabled_target_url, expected_enabled_title); - EXPECT_EQ(expected_enabled_target_accept_header, - GetInterceptedAcceptHeader(enabled_target_url)); + NavigateAndWaitForTitle(target_url, expected_title); + EXPECT_EQ(expected_target_accept_header, + GetInterceptedAcceptHeader(target_url)); ClearInterceptedAcceptHeaders(); - NavigateAndWaitForTitle(disabled_target_url, expected_disabled_title); - EXPECT_EQ(expected_disabled_target_accept_header, - GetInterceptedAcceptHeader(disabled_target_url)); + NavigateAndWaitForTitle(redirect_target_url, expected_title); + CheckNavigationAcceptHeader({redirect_target_url}); + EXPECT_EQ(expected_target_accept_header, + GetInterceptedAcceptHeader(target_url)); ClearInterceptedAcceptHeaders(); - NavigateAndWaitForTitle(redirect_disabled_to_enabled_target_url, - expected_enabled_title); - CheckNavigationAcceptHeader({redirect_disabled_to_enabled_target_url}); - EXPECT_EQ(expected_enabled_target_accept_header, - GetInterceptedAcceptHeader(enabled_target_url)); - ClearInterceptedAcceptHeaders(); - - NavigateAndWaitForTitle(redirect_enabled_to_disabled_target_url, - expected_disabled_title); - CheckNavigationAcceptHeader({redirect_enabled_to_disabled_target_url}); - EXPECT_EQ(expected_disabled_target_accept_header, - GetInterceptedAcceptHeader(disabled_target_url)); - ClearInterceptedAcceptHeaders(); - - NavigateAndWaitForTitle(redirect_enabled_to_disabled_to_enabled_target_url, - expected_enabled_title); + NavigateAndWaitForTitle(redirect_redirect_target_url, expected_title); CheckNavigationAcceptHeader( - {redirect_enabled_to_disabled_to_enabled_target_url, - redirect_disabled_to_enabled_target_url}); - EXPECT_EQ(expected_enabled_target_accept_header, - GetInterceptedAcceptHeader(enabled_target_url)); + {redirect_redirect_target_url, redirect_target_url}); + EXPECT_EQ(expected_target_accept_header, + GetInterceptedAcceptHeader(target_url)); ClearInterceptedAcceptHeaders(); - - NavigateAndWaitForTitle(redirect_disabled_to_enabled_to_disabled_target_url, - expected_disabled_title); - CheckNavigationAcceptHeader( - {redirect_disabled_to_enabled_to_disabled_target_url, - redirect_enabled_to_disabled_target_url}); - EXPECT_EQ(expected_disabled_target_accept_header, - GetInterceptedAcceptHeader(disabled_target_url)); } } IN_PROC_BROWSER_TEST_P(SignedExchangeAcceptHeaderBrowserTest, ServiceWorkerPrefetch) { NavigateAndWaitForTitle( - enabled_https_server_.GetURL("/sxg/service-worker-prefetch.html"), - "Done"); - NavigateAndWaitForTitle( - disabled_https_server_.GetURL("/sxg/service-worker-prefetch.html"), - "Done"); + https_server_.GetURL("/sxg/service-worker-prefetch.html"), "Done"); const std::string scope = "/sxg/sw-prefetch-scope/"; - const GURL enabled_target_url = - enabled_https_server_.GetURL(scope + "test.html"); - const GURL disabled_target_url = - disabled_https_server_.GetURL(scope + "test.html"); + const GURL target_url = https_server_.GetURL(scope + "test.html"); - const GURL enabled_prefetch_target = - enabled_https_server_.GetURL(std::string("/sxg/hello.txt")); - const GURL disabled_prefetch_target = - disabled_https_server_.GetURL(std::string("/sxg/hello.txt")); + const GURL prefetch_target = + https_server_.GetURL(std::string("/sxg/hello.txt")); const std::string load_prefetch_script = base::StringPrintf( "(function loadPrefetch(urls) {" " for (let url of urls) {" @@ -1163,44 +937,23 @@ " }" " }" " check();" - "})(['%s','%s'])", - enabled_prefetch_target.spec().c_str(), - disabled_prefetch_target.spec().c_str()); + "})(['%s'])", + prefetch_target.spec().c_str()); bool unused = false; - NavigateAndWaitForTitle(enabled_target_url, "Done"); + NavigateAndWaitForTitle(target_url, "Done"); EXPECT_TRUE(ExecuteScriptAndExtractBool(shell()->web_contents(), load_prefetch_script, &unused)); - CheckPrefetchAcceptHeader( - {enabled_prefetch_target, disabled_prefetch_target}); + CheckPrefetchAcceptHeader({prefetch_target}); ClearInterceptedAcceptHeaders(); - - NavigateAndWaitForTitle(disabled_target_url, "Done"); - EXPECT_TRUE(ExecuteScriptAndExtractBool(shell()->web_contents(), - load_prefetch_script, &unused)); - CheckPrefetchAcceptHeader( - {enabled_prefetch_target, disabled_prefetch_target}); } INSTANTIATE_TEST_SUITE_P( SignedExchangeAcceptHeaderBrowserTest, SignedExchangeAcceptHeaderBrowserTest, - testing::Values( - SignedExchangeAcceptHeaderBrowserTestParam(false, false, false, false), - SignedExchangeAcceptHeaderBrowserTestParam(false, false, false, true), - SignedExchangeAcceptHeaderBrowserTestParam(false, false, true, false), - SignedExchangeAcceptHeaderBrowserTestParam(false, false, true, true), - SignedExchangeAcceptHeaderBrowserTestParam(false, true, false, false), - SignedExchangeAcceptHeaderBrowserTestParam(false, true, false, true), - SignedExchangeAcceptHeaderBrowserTestParam(false, true, true, false), - SignedExchangeAcceptHeaderBrowserTestParam(false, true, true, true), - SignedExchangeAcceptHeaderBrowserTestParam(true, false, false, false), - SignedExchangeAcceptHeaderBrowserTestParam(true, false, false, true), - SignedExchangeAcceptHeaderBrowserTestParam(true, false, true, false), - SignedExchangeAcceptHeaderBrowserTestParam(true, false, true, true), - SignedExchangeAcceptHeaderBrowserTestParam(true, true, false, false), - SignedExchangeAcceptHeaderBrowserTestParam(true, true, false, true), - SignedExchangeAcceptHeaderBrowserTestParam(true, true, true, false), - SignedExchangeAcceptHeaderBrowserTestParam(true, true, true, true))); + testing::Values(SignedExchangeAcceptHeaderBrowserTestParam(false, false), + SignedExchangeAcceptHeaderBrowserTestParam(false, true), + SignedExchangeAcceptHeaderBrowserTestParam(true, false), + SignedExchangeAcceptHeaderBrowserTestParam(true, true))); } // namespace content
diff --git a/content/browser/web_package/signed_exchange_signature_verifier.cc b/content/browser/web_package/signed_exchange_signature_verifier.cc index d67d9a3..adb3c3a1 100644 --- a/content/browser/web_package/signed_exchange_signature_verifier.cc +++ b/content/browser/web_package/signed_exchange_signature_verifier.cc
@@ -196,11 +196,8 @@ return base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(t); } -// Implements steps 3-4 of -// https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#signature-validity -SignedExchangeSignatureVerifier::Result VerifyTimestamps( - const SignedExchangeEnvelope& envelope, - const base::Time& verification_time) { +SignedExchangeSignatureVerifier::Result VerifyValidityPeriod( + const SignedExchangeEnvelope& envelope) { base::Time expires_time = TimeFromSignedExchangeUnixTime(envelope.signature().expires); base::Time creation_time = @@ -211,6 +208,18 @@ if ((expires_time - creation_time).InSeconds() > kOneWeek.InSeconds()) { return SignedExchangeSignatureVerifier::Result::kErrValidityPeriodTooLong; } + return SignedExchangeSignatureVerifier::Result::kSuccess; +} + +// Implements "Signature validity" of +// https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#signature-validity +SignedExchangeSignatureVerifier::Result VerifyTimestamps( + const SignedExchangeEnvelope& envelope, + const base::Time& verification_time) { + base::Time expires_time = + TimeFromSignedExchangeUnixTime(envelope.signature().expires); + base::Time creation_time = + TimeFromSignedExchangeUnixTime(envelope.signature().date); // 4. "If the current time is before date or after expires, return // "invalid"." @@ -258,6 +267,17 @@ TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("loading"), "SignedExchangeSignatureVerifier::Verify"); DCHECK(certificate); + const auto validity_period_result = VerifyValidityPeriod(envelope); + if (validity_period_result != Result::kSuccess) { + signed_exchange_utils::ReportErrorAndTraceEvent( + devtools_proxy, + base::StringPrintf( + "Specified validity period too long. creation_time: %" PRIu64 + ", expires_time: %" PRIu64 ", verification_time: %" PRIu64, + envelope.signature().date, envelope.signature().expires, + (verification_time - base::Time::UnixEpoch()).InSeconds())); + return validity_period_result; + } const auto timestamp_result = VerifyTimestamps(envelope, verification_time); if (timestamp_result != Result::kSuccess && !ShouldIgnoreTimestampError(certificate)) {
diff --git a/content/browser/web_package/signed_exchange_utils.cc b/content/browser/web_package/signed_exchange_utils.cc index 2683195..ab37cf6 100644 --- a/content/browser/web_package/signed_exchange_utils.cc +++ b/content/browser/web_package/signed_exchange_utils.cc
@@ -6,14 +6,11 @@ #include "base/command_line.h" #include "base/feature_list.h" -#include "base/metrics/field_trial_params.h" -#include "base/no_destructor.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/time/time.h" #include "base/trace_event/trace_event.h" #include "content/browser/loader/download_utils_impl.h" -#include "content/browser/web_package/origins_list.h" #include "content/browser/web_package/signed_exchange_devtools_proxy.h" #include "content/browser/web_package/signed_exchange_error.h" #include "content/browser/web_package/signed_exchange_request_handler.h" @@ -21,7 +18,6 @@ #include "content/public/common/content_switches.h" #include "net/http/http_util.h" #include "services/network/public/cpp/resource_response.h" -#include "third_party/blink/public/common/origin_trials/trial_token_validator.h" namespace content { namespace signed_exchange_utils { @@ -37,62 +33,12 @@ devtools_proxy->ReportError(error_message, std::move(error_field)); } -namespace { - -OriginsList CreateAdvertiseAcceptHeaderOriginsList() { - std::string param = base::GetFieldTrialParamValueByFeature( - features::kSignedHTTPExchangeAcceptHeader, - features::kSignedHTTPExchangeAcceptHeaderFieldTrialParamName); - if (param.empty()) - DLOG(ERROR) << "The Accept-SXG origins list param is empty."; - - return OriginsList(param); -} - -bool IsSignedHTTPExchangeEnabledByFlags() { +bool IsSignedExchangeHandlingEnabled() { return base::FeatureList::IsEnabled(features::kSignedHTTPExchange) || base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalWebPlatformFeatures); } -} // namespace - -bool NeedToCheckRedirectedURLForAcceptHeader() { - // When SignedHTTPExchange is enabled, the SignedExchange accept header must - // be sent to all origins. So we don't need to check the redirected URL. - return !IsSignedHTTPExchangeEnabledByFlags() && - base::FeatureList::IsEnabled( - features::kSignedHTTPExchangeOriginTrial) && - base::FeatureList::IsEnabled( - features::kSignedHTTPExchangeAcceptHeader); -} - -bool ShouldAdvertiseAcceptHeader(const url::Origin& origin) { - // When SignedHTTPExchange is enabled, we must send the SignedExchange accept - // header to all origins. - if (IsSignedHTTPExchangeEnabledByFlags()) - return true; - // When SignedHTTPExchangeOriginTrial is not enabled or - // SignedHTTPExchangeAcceptHeader is not enabled, we must not send the - // SignedExchange accept header. - if (!base::FeatureList::IsEnabled(features::kSignedHTTPExchangeOriginTrial) || - !base::FeatureList::IsEnabled( - features::kSignedHTTPExchangeAcceptHeader)) { - return false; - } - - // |origins_list| is initialized in a thread-safe manner. - // Querying OriginsList::Match() should be safe since it's read-only access. - static base::NoDestructor<OriginsList> origins_list( - CreateAdvertiseAcceptHeaderOriginsList()); - return origins_list->Match(origin); -} - -bool IsSignedExchangeHandlingEnabled() { - return IsSignedHTTPExchangeEnabledByFlags() || - base::FeatureList::IsEnabled(features::kSignedHTTPExchangeOriginTrial); -} - bool ShouldHandleAsSignedHTTPExchange( const GURL& request_url, const network::ResourceResponseHead& head) { @@ -107,15 +53,7 @@ head.mime_type)) { return false; } - if (IsSignedHTTPExchangeEnabledByFlags()) - return true; - if (!base::FeatureList::IsEnabled(features::kSignedHTTPExchangeOriginTrial)) - return false; - std::unique_ptr<blink::TrialTokenValidator> validator = - std::make_unique<blink::TrialTokenValidator>(); - return validator->RequestEnablesFeature( - request_url, head.headers.get(), - features::kSignedHTTPExchangeOriginTrial.name, base::Time::Now()); + return IsSignedExchangeHandlingEnabled(); } base::Optional<SignedExchangeVersion> GetSignedExchangeVersion(
diff --git a/content/browser/web_package/signed_exchange_utils.h b/content/browser/web_package/signed_exchange_utils.h index 96848246..52d4f04c 100644 --- a/content/browser/web_package/signed_exchange_utils.h +++ b/content/browser/web_package/signed_exchange_utils.h
@@ -8,17 +8,12 @@ #include <string> #include "base/optional.h" -#include "content/browser/web_package/origins_list.h" #include "content/browser/web_package/signed_exchange_consts.h" #include "content/browser/web_package/signed_exchange_error.h" #include "content/browser/web_package/signed_exchange_signature_verifier.h" #include "content/common/content_export.h" #include "url/gurl.h" -namespace url { -class Origin; -} // namespace url - namespace network { struct ResourceResponseHead; } // namespace network @@ -47,23 +42,11 @@ base::Optional<SignedExchangeError::FieldIndexPair> error_field = base::nullopt); -// Returns true when SignedHTTPExchange feature is NOT enabled and -// SignedHTTPExchangeOriginTrial and SignedHTTPExchangeAcceptHeader features are -// enabled. -bool NeedToCheckRedirectedURLForAcceptHeader(); - -// Returns true if Accept headers should be sent with -// "application/signed-exchange". -CONTENT_EXPORT bool ShouldAdvertiseAcceptHeader(const url::Origin& origin); - -// Returns true when SignedHTTPExchange feature or SignedHTTPExchangeOriginTrial -// feature is enabled. -bool IsSignedExchangeHandlingEnabled(); +// Returns true when SignedHTTPExchange feature is enabled. +CONTENT_EXPORT bool IsSignedExchangeHandlingEnabled(); // Returns true when the response should be handled as a signed exchange by -// checking the mime type and the feature flags. When SignedHTTPExchange feature -// is not enabled and SignedHTTPExchangeOriginTrial feature is enabled, this -// method also checks the Origin Trial header. +// checking the mime type and the feature flags. bool ShouldHandleAsSignedHTTPExchange( const GURL& request_url, const network::ResourceResponseHead& head);
diff --git a/content/browser/webauth/webauth_browsertest.cc b/content/browser/webauth/webauth_browsertest.cc index f4718c61..c84d8a1 100644 --- a/content/browser/webauth/webauth_browsertest.cc +++ b/content/browser/webauth/webauth_browsertest.cc
@@ -30,7 +30,7 @@ #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/test_utils.h" #include "content/shell/browser/shell.h" -#include "content/test/did_commit_provisional_load_interceptor.h" +#include "content/test/frame_host_interceptor.h" #include "device/base/features.h" #include "device/fido/fake_fido_discovery.h" #include "device/fido/fido_discovery_factory.h" @@ -159,20 +159,18 @@ // Helper class that executes the given |closure| the very last moment before // the next navigation commits in a given WebContents. -class ClosureExecutorBeforeNavigationCommit - : public DidCommitProvisionalLoadInterceptor { +class ClosureExecutorBeforeNavigationCommit : public FrameHostInterceptor { public: ClosureExecutorBeforeNavigationCommit(WebContents* web_contents, base::OnceClosure closure) - : DidCommitProvisionalLoadInterceptor(web_contents), - closure_(std::move(closure)) {} + : FrameHostInterceptor(web_contents), closure_(std::move(closure)) {} ~ClosureExecutorBeforeNavigationCommit() override = default; protected: bool WillDispatchDidCommitProvisionalLoad( RenderFrameHost* render_frame_host, ::FrameHostMsg_DidCommitProvisionalLoad_Params* params, - mojom::DidCommitProvisionalLoadInterfaceParamsPtr& interface_params) + mojom::DidCommitProvisionalLoadInterfaceParamsPtr* interface_params) override { if (closure_) std::move(closure_).Run();
diff --git a/content/child/DEPS b/content/child/DEPS index 9cb3d30d..8657169 100644 --- a/content/child/DEPS +++ b/content/child/DEPS
@@ -6,7 +6,6 @@ "+components/webcrypto", "+components/services/font/public", - "+content/app/strings/grit", # For generated headers "+content/public/child", "+services/device/public/cpp/device_features.h", "+services/device/public/cpp/power_monitor",
diff --git a/content/child/blink_platform_impl.cc b/content/child/blink_platform_impl.cc index 51639ab8..c44481e 100644 --- a/content/child/blink_platform_impl.cc +++ b/content/child/blink_platform_impl.cc
@@ -163,6 +163,8 @@ return IDS_FORM_INPUT_ALT; case WebLocalizedString::kMissingPluginText: return IDS_PLUGIN_INITIALIZATION_ERROR; + case WebLocalizedString::kAXMediaPlaybackError: + return IDS_MEDIA_PLAYBACK_ERROR; case WebLocalizedString::kMediaRemotingCastText: return IDS_MEDIA_REMOTING_CAST_TEXT; case WebLocalizedString::kMediaRemotingCastToUnknownDeviceText:
diff --git a/content/child/runtime_features.cc b/content/child/runtime_features.cc index 68951f4a..c3ef8dc 100644 --- a/content/child/runtime_features.cc +++ b/content/child/runtime_features.cc
@@ -335,12 +335,6 @@ WebRuntimeFeatures::EnableWebAuth( base::FeatureList::IsEnabled(features::kWebAuth)); - // TODO(yashard): Remove |enable_experimental_web_platform_features| flag - // since the feature should have been enabled when it is set to experimental - WebRuntimeFeatures::EnableWebAuthGetTransports( - base::FeatureList::IsEnabled(features::kWebAuthGetTransports) || - enable_experimental_web_platform_features); - WebRuntimeFeatures::EnableClientPlaceholdersForServerLoFi( base::GetFieldTrialParamValue("PreviewsClientLoFi", "replace_server_placeholders") != "false");
diff --git a/content/common/input/actions_parser.cc b/content/common/input/actions_parser.cc index 27364dcf5..db404a9 100644 --- a/content/common/input/actions_parser.cc +++ b/content/common/input/actions_parser.cc
@@ -110,13 +110,32 @@ for (size_t action_index = 0; action_index < longest_action_sequence_; ++action_index) { SyntheticPointerActionListParams::ParamList param_list; + size_t longest_pause_frame = 0; for (const auto pointer_action_list : pointer_actions_list_) { - if (action_index < pointer_action_list.size()) + if (action_index < pointer_action_list.size()) { param_list.push_back(pointer_action_list[action_index]); + if (pointer_action_list[action_index].pointer_action_type() == + SyntheticPointerActionParams::PointerActionType::IDLE) { + size_t num_pause_frame = static_cast<size_t>(std::ceil( + pointer_action_list[action_index].duration().InMilliseconds() / + viz::BeginFrameArgs::DefaultInterval().InMilliseconds())); + longest_pause_frame = std::max(longest_pause_frame, num_pause_frame); + } + } } gesture_params_.PushPointerActionParamsList(param_list); - } + for (size_t pause_index = 1; pause_index < longest_pause_frame; + ++pause_index) { + SyntheticPointerActionListParams::ParamList pause_param_list; + SyntheticPointerActionParams pause_action_param( + SyntheticPointerActionParams::PointerActionType::IDLE); + for (size_t i = 0; i < param_list.size(); ++i) { + pause_param_list.push_back(pause_action_param); + } + gesture_params_.PushPointerActionParamsList(pause_param_list); + } + } return true; } @@ -135,75 +154,72 @@ } else if (source_type == "") { error_message_ = std::string("action sequence type cannot be empty"); return false; - } else if (source_type != "pointer") { + } else if (source_type == "key") { error_message_ = - std::string("we only support action sequence type of pointer"); + std::string("we do not support action sequence type of key"); return false; } - if (source_type_.empty()) - source_type_ = source_type; + if (source_type == "pointer") { + if (source_type_.empty()) + source_type_ = source_type; - if (source_type_ != source_type) { - error_message_ = std::string( - "currently multiple action sequence type are not supported"); - return false; + if (source_type_ == "pointer" && !pointer.HasKey("parameters")) { + error_message_ = std::string( + "action sequence parameters is missing for pointer type"); + return false; + } + + const base::DictionaryValue* parameters; + std::string pointer_type; + if (!pointer.GetDictionary("parameters", ¶meters)) { + error_message_ = + std::string("action sequence parameters is not a dictionary"); + return false; + } + + if (!parameters->GetString("pointerType", &pointer_type)) { + error_message_ = std::string( + "action sequence pointer type is missing or not a string"); + return false; + } else if (pointer_type != "touch" && pointer_type != "mouse" && + pointer_type != "pen") { + error_message_ = std::string( + "action sequence pointer type is an unsupported input type"); + return false; + } + + if (pointer_type_.empty()) { + pointer_type_ = pointer_type; + } + + if (pointer_type_ != pointer_type) { + error_message_ = std::string( + "currently multiple action sequence pointer type are not " + "supported"); + return false; + } + + if (pointer_type != "touch" && action_index_ > 0) { + error_message_ = std::string( + "for input type of mouse and pen, we only support one device"); + return false; + } + + std::string pointer_name; + if (!pointer.GetString("id", &pointer_name)) { + error_message_ = std::string("pointer name is missing or not a string"); + return false; + } + + if (pointer_name_set_.find(pointer_name) != pointer_name_set_.end()) { + error_message_ = std::string("pointer name already exists"); + return false; + } + + pointer_name_set_.insert(pointer_name); + pointer_id_set_.insert(action_index_); } - - if (source_type_ == "pointer" && !pointer.HasKey("parameters")) { - error_message_ = - std::string("action sequence parameters is missing for pointer type"); - return false; - } - - const base::DictionaryValue* parameters; - std::string pointer_type; - if (!pointer.GetDictionary("parameters", ¶meters)) { - error_message_ = - std::string("action sequence parameters is not a dictionary"); - return false; - } - - if (!parameters->GetString("pointerType", &pointer_type)) { - error_message_ = std::string( - "action sequence pointer type is missing or not a string"); - return false; - } else if (pointer_type != "touch" && pointer_type != "mouse" && - pointer_type != "pen") { - error_message_ = std::string( - "action sequence pointer type is an unsupported input type"); - return false; - } - - if (pointer_type_.empty()) { - pointer_type_ = pointer_type; - } - - if (pointer_type_ != pointer_type) { - error_message_ = std::string( - "currently multiple action sequence pointer type are not supported"); - return false; - } - - if (pointer_type != "touch" && action_index_ > 0) { - error_message_ = std::string( - "for input type of mouse and pen, we only support one device"); - return false; - } - - std::string pointer_name; - if (!pointer.GetString("id", &pointer_name)) { - error_message_ = std::string("pointer name is missing or not a string"); - return false; - } - - if (pointer_name_set_.find(pointer_name) != pointer_name_set_.end()) { - error_message_ = std::string("pointer name already exists"); - return false; - } - - pointer_name_set_.insert(pointer_name); - pointer_id_set_.insert(action_index_); pointer_id = action_index_; } else { std::string pointer_type; @@ -320,6 +336,7 @@ return false; } } + pointer_action_type = ToSyntheticPointerActionType(type); if (pointer_action_type == SyntheticPointerActionParams::PointerActionType::NOT_INITIALIZED) { @@ -375,22 +392,20 @@ key_modifiers |= key_modifier; } - double duration = 0; - int num_idle = 0; + int duration = viz::BeginFrameArgs::DefaultInterval().InMilliseconds(); if (pointer_action_type == SyntheticPointerActionParams::PointerActionType::IDLE) { - num_idle = 1; - if (action.HasKey("duration") && !action.GetDouble("duration", &duration)) { + if (action.HasKey("duration") && + !action.GetInteger("duration", &duration)) { error_message_ = base::StringPrintf( - "actions[%d].actions.x is not a number", action_index_); + "actions[%d].actions.duration is not a number", action_index_); return false; } - } - - // If users pause for given seconds, we convert to the number of idle frames. - if (duration > 0) { - num_idle = static_cast<int>(std::ceil( - duration / viz::BeginFrameArgs::DefaultInterval().InSecondsF())); + if (duration < 0) { + error_message_ = base::StringPrintf( + "actions[%d].actions.duration should not be negative", action_index_); + return false; + } } SyntheticPointerActionParams action_param(pointer_action_type); @@ -412,19 +427,15 @@ action_param.set_button(button); action_param.set_key_modifiers(key_modifiers); break; + case SyntheticPointerActionParams::PointerActionType::IDLE: + action_param.set_duration(base::TimeDelta::FromMilliseconds(duration)); + break; case SyntheticPointerActionParams::PointerActionType::CANCEL: case SyntheticPointerActionParams::PointerActionType::LEAVE: - case SyntheticPointerActionParams::PointerActionType::IDLE: case SyntheticPointerActionParams::PointerActionType::NOT_INITIALIZED: break; } param_list.push_back(action_param); - - // We queue all the IDLE actions in the action parameter list to make sure we - // will pause long enough on the given pointer. - for (int count = 1; count < num_idle; ++count) - param_list.push_back(action_param); - return true; }
diff --git a/content/common/input/actions_parser_unittest.cc b/content/common/input/actions_parser_unittest.cc index 78db89a..a1b135f6 100644 --- a/content/common/input/actions_parser_unittest.cc +++ b/content/common/input/actions_parser_unittest.cc
@@ -69,6 +69,55 @@ EXPECT_EQ(1U, action_list_params.params[0][1].pointer_id()); } +TEST(ActionsParserTest, ParseTouchPointerActionSequenceWithPause) { + std::unique_ptr<base::Value> value = base::JSONReader::ReadDeprecated( + R"( [{"type": "pointer", + "actions": [{"type": "pointerDown", "x": 3, "y": 5}, + {"type": "pointerMove", "x": 30, "y": 30}, + {"type": "pointerUp" }], + "parameters": {"pointerType": "touch"}, + "id": "pointer1"}, + {"type":"none", + "actions":[{"type":"pause"}, + {"type":"pause","duration":50}, + {"type":"pause"}], + "id":"0"}] )"); + + ActionsParser actions_parser(value.get()); + EXPECT_TRUE(actions_parser.ParsePointerActionSequence()); + SyntheticPointerActionListParams action_list_params = + actions_parser.gesture_params(); + EXPECT_EQ(SyntheticGestureParams::TOUCH_INPUT, + action_list_params.gesture_source_type); + EXPECT_EQ(5U, action_list_params.params.size()); + EXPECT_EQ(2U, action_list_params.params[0].size()); + EXPECT_EQ(SyntheticPointerActionParams::PointerActionType::PRESS, + action_list_params.params[0][0].pointer_action_type()); + EXPECT_EQ(gfx::PointF(3, 5), action_list_params.params[0][0].position()); + EXPECT_EQ(0U, action_list_params.params[0][0].pointer_id()); + EXPECT_EQ(SyntheticPointerActionParams::PointerActionType::IDLE, + action_list_params.params[0][1].pointer_action_type()); + EXPECT_EQ(SyntheticPointerActionParams::PointerActionType::MOVE, + action_list_params.params[1][0].pointer_action_type()); + EXPECT_EQ(gfx::PointF(30, 30), action_list_params.params[1][0].position()); + EXPECT_EQ(0U, action_list_params.params[1][0].pointer_id()); + EXPECT_EQ(SyntheticPointerActionParams::PointerActionType::IDLE, + action_list_params.params[1][1].pointer_action_type()); + EXPECT_EQ(SyntheticPointerActionParams::PointerActionType::IDLE, + action_list_params.params[2][0].pointer_action_type()); + EXPECT_EQ(SyntheticPointerActionParams::PointerActionType::IDLE, + action_list_params.params[2][1].pointer_action_type()); + EXPECT_EQ(SyntheticPointerActionParams::PointerActionType::IDLE, + action_list_params.params[3][0].pointer_action_type()); + EXPECT_EQ(SyntheticPointerActionParams::PointerActionType::IDLE, + action_list_params.params[3][1].pointer_action_type()); + EXPECT_EQ(SyntheticPointerActionParams::PointerActionType::RELEASE, + action_list_params.params[4][0].pointer_action_type()); + EXPECT_EQ(0U, action_list_params.params[4][0].pointer_id()); + EXPECT_EQ(SyntheticPointerActionParams::PointerActionType::IDLE, + action_list_params.params[4][1].pointer_action_type()); +} + TEST(ActionsParserTest, ParseTouchPointerActionSequenceIdNotString) { std::unique_ptr<base::Value> value = base::JSONReader::ReadDeprecated( R"( [{"type": "pointer", @@ -179,7 +228,7 @@ ActionsParser actions_parser(value.get()); EXPECT_FALSE(actions_parser.ParsePointerActionSequence()); - EXPECT_EQ("we only support action sequence type of pointer", + EXPECT_EQ("we do not support action sequence type of key", actions_parser.error_message()); }
diff --git a/content/common/input/synthetic_pointer_action_params.h b/content/common/input/synthetic_pointer_action_params.h index 2e334c5..fd7ebac7 100644 --- a/content/common/input/synthetic_pointer_action_params.h +++ b/content/common/input/synthetic_pointer_action_params.h
@@ -102,6 +102,11 @@ void set_timestamp(base::TimeTicks timestamp) { timestamp_ = timestamp; } + void set_duration(base::TimeDelta duration) { + DCHECK_EQ(PointerActionType::IDLE, pointer_action_type_); + duration_ = duration; + } + PointerActionType pointer_action_type() const { return pointer_action_type_; } uint32_t pointer_id() const { return pointer_id_; } @@ -150,6 +155,11 @@ base::TimeTicks timestamp() const { return timestamp_; } + base::TimeDelta duration() const { + DCHECK_EQ(PointerActionType::IDLE, pointer_action_type_); + return duration_; + } + static unsigned GetWebMouseEventModifier( SyntheticPointerActionParams::Button button); static blink::WebMouseEvent::Button GetWebMouseEventButton( @@ -176,6 +186,8 @@ float rotation_angle_ = 0.f; float force_ = 1.f; base::TimeTicks timestamp_; + // The duration of the pause action is in milliseconds. + base::TimeDelta duration_; }; } // namespace content
diff --git a/content/common/input_messages.h b/content/common/input_messages.h index 3400743..ca702e2b 100644 --- a/content/common/input_messages.h +++ b/content/common/input_messages.h
@@ -150,6 +150,7 @@ IPC_STRUCT_TRAITS_MEMBER(rotation_angle_) IPC_STRUCT_TRAITS_MEMBER(force_) IPC_STRUCT_TRAITS_MEMBER(timestamp_) + IPC_STRUCT_TRAITS_MEMBER(duration_) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(content::SyntheticPointerActionListParams)
diff --git a/content/common/service_manager/child_connection.cc b/content/common/service_manager/child_connection.cc index a71623c4..417cba24 100644 --- a/content/common/service_manager/child_connection.cc +++ b/content/common/service_manager/child_connection.cc
@@ -9,6 +9,7 @@ #include "base/bind.h" #include "base/macros.h" +#include "base/process/process.h" #include "base/rand_util.h" #include "base/strings/string_number_conversions.h" #include "content/common/child.mojom.h" @@ -64,11 +65,11 @@ } } - void SetProcessHandle(base::ProcessHandle handle) { + void SetProcess(base::Process process) { DCHECK(io_task_runner_); io_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&IOThreadContext::SetProcessHandleOnIOThread, - this, handle)); + FROM_HERE, base::BindOnce(&IOThreadContext::SetProcessOnIOThread, this, + std::move(process))); } private: @@ -96,10 +97,11 @@ pid_receiver_.reset(); } - void SetProcessHandleOnIOThread(base::ProcessHandle handle) { + void SetProcessOnIOThread(base::Process process) { DCHECK(pid_receiver_.is_bound()); - pid_receiver_->SetPID(base::GetProcId(handle)); + pid_receiver_->SetPID(process.Pid()); pid_receiver_.reset(); + process_ = std::move(process); } scoped_refptr<base::SequencedTaskRunner> io_task_runner_; @@ -109,6 +111,9 @@ // ServiceManagerConnection in the child monitors the lifetime of this pipe. mojom::ChildPtr child_; service_manager::mojom::PIDReceiverPtr pid_receiver_; + // Hold onto the process, and thus its process handle, so that the pid will + // remain valid. + base::Process process_; DISALLOW_COPY_AND_ASSIGN(IOThreadContext); }; @@ -137,9 +142,8 @@ context_->BindInterface(interface_name, std::move(interface_pipe)); } -void ChildConnection::SetProcessHandle(base::ProcessHandle handle) { - process_handle_ = handle; - context_->SetProcessHandle(handle); +void ChildConnection::SetProcess(base::Process process) { + context_->SetProcess(std::move(process)); } } // namespace content
diff --git a/content/common/service_manager/child_connection.h b/content/common/service_manager/child_connection.h index 96aca64..ab798f5 100644 --- a/content/common/service_manager/child_connection.h +++ b/content/common/service_manager/child_connection.h
@@ -11,7 +11,7 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" -#include "base/process/process_handle.h" +#include "base/process/process.h" #include "base/sequenced_task_runner.h" #include "content/common/content_export.h" #include "mojo/public/cpp/system/invitation.h" @@ -54,10 +54,10 @@ // initialize its end of the Service Manager connection pipe. std::string service_token() const { return service_token_; } - // Sets the child connection's process handle. This should be called as soon + // Sets the child connection's process. This should be called as soon // as the process has been launched, and the connection will not be fully // functional until this is called. - void SetProcessHandle(base::ProcessHandle handle); + void SetProcess(base::Process process); private: class IOThreadContext; @@ -65,7 +65,6 @@ scoped_refptr<IOThreadContext> context_; service_manager::Identity child_identity_; std::string service_token_; - base::ProcessHandle process_handle_ = base::kNullProcessHandle; base::WeakPtrFactory<ChildConnection> weak_factory_;
diff --git a/content/public/android/java/src/org/chromium/content/browser/accessibility/KitKatWebContentsAccessibility.java b/content/public/android/java/src/org/chromium/content/browser/accessibility/KitKatWebContentsAccessibility.java index 6a8409f..be9e010d 100644 --- a/content/public/android/java/src/org/chromium/content/browser/accessibility/KitKatWebContentsAccessibility.java +++ b/content/public/android/java/src/org/chromium/content/browser/accessibility/KitKatWebContentsAccessibility.java
@@ -34,7 +34,8 @@ @Override protected void setAccessibilityNodeInfoKitKatAttributes(AccessibilityNodeInfo node, boolean isRoot, boolean isEditableText, String role, String roleDescription, - String hint, int selectionStartIndex, int selectionEndIndex, boolean hasImage) { + String hint, int selectionStartIndex, int selectionEndIndex, boolean hasImage, + boolean contentInvalid) { Bundle bundle = node.getExtras(); bundle.putCharSequence("AccessibilityNodeInfo.chromeRole", role); bundle.putCharSequence("AccessibilityNodeInfo.roleDescription", roleDescription); @@ -48,6 +49,8 @@ node.setEditable(true); node.setTextSelection(selectionStartIndex, selectionEndIndex); } + + node.setContentInvalid(contentInvalid); } @Override
diff --git a/content/public/android/java/src/org/chromium/content/browser/accessibility/LollipopWebContentsAccessibility.java b/content/public/android/java/src/org/chromium/content/browser/accessibility/LollipopWebContentsAccessibility.java index 06a330d..b369a08 100644 --- a/content/public/android/java/src/org/chromium/content/browser/accessibility/LollipopWebContentsAccessibility.java +++ b/content/public/android/java/src/org/chromium/content/browser/accessibility/LollipopWebContentsAccessibility.java
@@ -56,13 +56,14 @@ @Override protected void setAccessibilityNodeInfoLollipopAttributes(AccessibilityNodeInfo node, boolean canOpenPopup, boolean contentInvalid, boolean dismissable, boolean multiLine, - int inputType, int liveRegion) { + int inputType, int liveRegion, String errorMessage) { node.setCanOpenPopup(canOpenPopup); node.setContentInvalid(contentInvalid); node.setDismissable(contentInvalid); node.setMultiLine(multiLine); node.setInputType(inputType); node.setLiveRegion(liveRegion); + node.setError(errorMessage); } @Override
diff --git a/content/public/android/java/src/org/chromium/content/browser/accessibility/OWebContentsAccessibility.java b/content/public/android/java/src/org/chromium/content/browser/accessibility/OWebContentsAccessibility.java index d2419e7..24be5d8 100644 --- a/content/public/android/java/src/org/chromium/content/browser/accessibility/OWebContentsAccessibility.java +++ b/content/public/android/java/src/org/chromium/content/browser/accessibility/OWebContentsAccessibility.java
@@ -41,9 +41,11 @@ @Override protected void setAccessibilityNodeInfoKitKatAttributes(AccessibilityNodeInfo node, boolean isRoot, boolean isEditableText, String role, String roleDescription, - String hint, int selectionStartIndex, int selectionEndIndex, boolean hasImage) { + String hint, int selectionStartIndex, int selectionEndIndex, boolean hasImage, + boolean contentInvalid) { super.setAccessibilityNodeInfoKitKatAttributes(node, isRoot, isEditableText, role, - roleDescription, hint, selectionStartIndex, selectionEndIndex, hasImage); + roleDescription, hint, selectionStartIndex, selectionEndIndex, hasImage, + contentInvalid); node.setHintText(hint); }
diff --git a/content/public/android/java/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityImpl.java b/content/public/android/java/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityImpl.java index cd9a2e2..c9843c5f 100644 --- a/content/public/android/java/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityImpl.java
@@ -1210,14 +1210,15 @@ @CalledByNative protected void setAccessibilityNodeInfoKitKatAttributes(AccessibilityNodeInfo node, boolean isRoot, boolean isEditableText, String role, String roleDescription, - String hint, int selectionStartIndex, int selectionEndIndex, boolean hasImage) { + String hint, int selectionStartIndex, int selectionEndIndex, boolean hasImage, + boolean contentInvalid) { // Requires KitKat or higher. } @CalledByNative protected void setAccessibilityNodeInfoLollipopAttributes(AccessibilityNodeInfo node, boolean canOpenPopup, boolean contentInvalid, boolean dismissable, boolean multiLine, - int inputType, int liveRegion) { + int inputType, int liveRegion, String errorMessage) { // Requires Lollipop or higher. }
diff --git a/content/public/android/javatests/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityTest.java b/content/public/android/javatests/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityTest.java index d5a4c32..ab68327c 100644 --- a/content/public/android/javatests/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityTest.java +++ b/content/public/android/javatests/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityTest.java
@@ -385,7 +385,6 @@ Assert.fail("ACTION_SET_TEXT not found"); } - /** * ContentEditable elements should get a class name of EditText. **/ @@ -406,4 +405,95 @@ Assert.assertEquals(editableNode.isEditable(), true); Assert.assertEquals(editableNode.getText().toString(), "Edit This"); } + + /** + * Tests presence of ContentInvalid attribute and correctness of + * error message given aria-invalid = true + **/ + @Test + @MediumTest + @MinAndroidSdkLevel(Build.VERSION_CODES.LOLLIPOP) + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + public void testEditTextFieldAriaInvalidTrueErrorMessage() throws Throwable { + final String data = "<form>\n" + + " First name:<br>\n" + + " <input id='fn' type='text' aria-invalid='true'><br>\n" + + "<input type='submit'><br>" + + "</form>"; + mActivityTestRule.launchContentShellWithUrl(UrlUtils.encodeHtmlDataUri(data)); + mActivityTestRule.waitForActiveShellToBeDoneLoading(); + AccessibilityNodeProvider provider = enableAccessibilityAndWaitForNodeProvider(); + int textNodeVirtualViewId = waitForNodeWithClassName(provider, "android.widget.EditText"); + AccessibilityNodeInfo textNode = + provider.createAccessibilityNodeInfo(textNodeVirtualViewId); + Assert.assertNotEquals(textNode, null); + Assert.assertEquals(textNode.isContentInvalid(), true); + Assert.assertEquals(textNode.getError(), "Invalid entry"); + } + + /** + * Tests presence of ContentInvalid attribute and correctness of + * error message given aria-invalid = spelling + **/ + @Test + @MediumTest + @MinAndroidSdkLevel(Build.VERSION_CODES.LOLLIPOP) + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + public void testEditTextFieldAriaInvalidSpellingErrorMessage() throws Throwable { + final String data = "<input type='text' aria-invalid='spelling'><br>\n"; + + mActivityTestRule.launchContentShellWithUrl(UrlUtils.encodeHtmlDataUri(data)); + mActivityTestRule.waitForActiveShellToBeDoneLoading(); + AccessibilityNodeProvider provider = enableAccessibilityAndWaitForNodeProvider(); + int textNodeVirtualViewId = waitForNodeWithClassName(provider, "android.widget.EditText"); + AccessibilityNodeInfo textNode = + provider.createAccessibilityNodeInfo(textNodeVirtualViewId); + Assert.assertNotEquals(textNode, null); + Assert.assertEquals(textNode.isContentInvalid(), true); + Assert.assertEquals(textNode.getError(), "Invalid spelling"); + } + + /** + * Tests presence of ContentInvalid attribute and correctness of + * error message given aria-invalid = grammar + **/ + @Test + @MediumTest + @MinAndroidSdkLevel(Build.VERSION_CODES.LOLLIPOP) + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + public void testEditTextFieldAriaInvalidGrammarErrorMessage() throws Throwable { + final String data = "<input type='text' aria-invalid='grammar'><br>\n"; + + mActivityTestRule.launchContentShellWithUrl(UrlUtils.encodeHtmlDataUri(data)); + mActivityTestRule.waitForActiveShellToBeDoneLoading(); + AccessibilityNodeProvider provider = enableAccessibilityAndWaitForNodeProvider(); + int textNodeVirtualViewId = waitForNodeWithClassName(provider, "android.widget.EditText"); + AccessibilityNodeInfo textNode = + provider.createAccessibilityNodeInfo(textNodeVirtualViewId); + Assert.assertNotEquals(textNode, null); + Assert.assertEquals(textNode.isContentInvalid(), true); + Assert.assertEquals(textNode.getError(), "Invalid grammar"); + } + + /** + * Tests ContentInvalid is false and empty error message for well-formed input + **/ + @Test + @MediumTest + @MinAndroidSdkLevel(Build.VERSION_CODES.LOLLIPOP) + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + + public void testEditTextFieldValidNoErrorMessage() throws Throwable { + final String data = "<input type='text'><br>\n"; + mActivityTestRule.launchContentShellWithUrl(UrlUtils.encodeHtmlDataUri(data)); + mActivityTestRule.waitForActiveShellToBeDoneLoading(); + AccessibilityNodeProvider provider = enableAccessibilityAndWaitForNodeProvider(); + int textNodeVirtualViewId = waitForNodeWithClassName(provider, "android.widget.EditText"); + + AccessibilityNodeInfo textNode = + provider.createAccessibilityNodeInfo(textNodeVirtualViewId); + Assert.assertNotEquals(textNode, null); + Assert.assertEquals(textNode.isContentInvalid(), false); + Assert.assertEquals(textNode.getError(), ""); + } }
diff --git a/content/public/app/content_renderer_manifest.cc b/content/public/app/content_renderer_manifest.cc index c70ecbb..22d3f7d 100644 --- a/content/public/app/content_renderer_manifest.cc +++ b/content/public/app/content_renderer_manifest.cc
@@ -23,7 +23,6 @@ .ExposeCapability( "browser", std::set<const char*>{ - "blink.mojom.AppCacheFrontend", "blink.mojom.CodeCacheHost", "blink.mojom.CrashMemoryMetricsReporter", "blink.mojom.LeakDetector",
diff --git a/content/public/browser/browser_or_resource_context.h b/content/public/browser/browser_or_resource_context.h index cacd119..48a2f56 100644 --- a/content/public/browser/browser_or_resource_context.h +++ b/content/public/browser/browser_or_resource_context.h
@@ -5,6 +5,7 @@ #ifndef CONTENT_PUBLIC_BROWSER_BROWSER_OR_RESOURCE_CONTEXT_H_ #define CONTENT_PUBLIC_BROWSER_BROWSER_OR_RESOURCE_CONTEXT_H_ +#include <cstddef> #include <type_traits> #include "base/logging.h" @@ -43,7 +44,7 @@ union_.resource_context_ = resource_context; flavour_ = kResourceContextFlavour; } - BrowserOrResourceContext(nullptr_t) = delete; + BrowserOrResourceContext(std::nullptr_t) = delete; // BrowserOrResourceContext has a trivial, default destructor. ~BrowserOrResourceContext() = default;
diff --git a/content/public/common/content_client.cc b/content/public/common/content_client.cc index bfbdd7b..9ab2f239 100644 --- a/content/public/common/content_client.cc +++ b/content/public/common/content_client.cc
@@ -75,6 +75,12 @@ return base::string16(); } +base::string16 ContentClient::GetLocalizedString( + int message_id, + const base::string16& replacement) const { + return base::string16(); +} + base::StringPiece ContentClient::GetDataResource( int resource_id, ui::ScaleFactor scale_factor) const {
diff --git a/content/public/common/content_client.h b/content/public/common/content_client.h index f7a451c..bfe6deb 100644 --- a/content/public/common/content_client.h +++ b/content/public/common/content_client.h
@@ -156,6 +156,12 @@ // Returns a string resource given its id. virtual base::string16 GetLocalizedString(int message_id) const; + // Returns a string resource given its id and replace $1 with the given + // replacement. + virtual base::string16 GetLocalizedString( + int message_id, + const base::string16& replacement) const; + // Return the contents of a resource in a StringPiece given the resource id. virtual base::StringPiece GetDataResource( int resource_id,
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index 9a9d4fa..97cdde03 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -443,17 +443,6 @@ const base::Feature kSignedHTTPExchange{"SignedHTTPExchange", base::FEATURE_ENABLED_BY_DEFAULT}; -// Send "Accept: application/signed-exchange" header to origins who opt-in. -const base::Feature kSignedHTTPExchangeAcceptHeader{ - "SignedHTTPExchangeAcceptHeader", base::FEATURE_DISABLED_BY_DEFAULT}; -// Field trial parameter containing the list of origins that opted-in to receive -// "Accept: application/signed-exchange" header. -const char kSignedHTTPExchangeAcceptHeaderFieldTrialParamName[] = "OriginsList"; - -// Origin Trial of Origin-Signed HTTP Exchanges (for WebPackage Loading) -const base::Feature kSignedHTTPExchangeOriginTrial{ - "SignedHTTPExchangeOriginTrial", base::FEATURE_ENABLED_BY_DEFAULT}; - // Controls whether SpareRenderProcessHostManager tries to always have a warm // spare renderer process around for the most recently requested BrowserContext. // This feature is only consulted in site-per-process mode. @@ -575,11 +564,6 @@ #endif }; -// Controls whether AuthenticatorAttestationResponse contains a getTransports -// member to return the set of transports supported by an authenticator. -const base::Feature kWebAuthGetTransports{"WebAuthenticationGetTransports", - base::FEATURE_DISABLED_BY_DEFAULT}; - // If WebGL Image Chromium is allowed, this feature controls whether it is // enabled. const base::Feature kWebGLImageChromium{"WebGLImageChromium",
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index 731ccfe..c017443 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -104,10 +104,6 @@ CONTENT_EXPORT extern const base::Feature kSignedExchangeReportingForDistributors; CONTENT_EXPORT extern const base::Feature kSignedHTTPExchange; -CONTENT_EXPORT extern const base::Feature kSignedHTTPExchangeAcceptHeader; -CONTENT_EXPORT extern const char - kSignedHTTPExchangeAcceptHeaderFieldTrialParamName[]; -CONTENT_EXPORT extern const base::Feature kSignedHTTPExchangeOriginTrial; CONTENT_EXPORT extern const base::Feature kSkipBrowserTouchFilter; CONTENT_EXPORT extern const char kSkipBrowserTouchFilterTypeParamName[]; CONTENT_EXPORT extern const char @@ -130,7 +126,6 @@ CONTENT_EXPORT extern const base::Feature kWebAuth; CONTENT_EXPORT extern const base::Feature kWebAuthBle; CONTENT_EXPORT extern const base::Feature kWebAuthCable; -CONTENT_EXPORT extern const base::Feature kWebAuthGetTransports; CONTENT_EXPORT extern const base::Feature kWebContentsOcclusion; CONTENT_EXPORT extern const base::Feature kWebGLImageChromium; CONTENT_EXPORT extern const base::Feature kWebPayments;
diff --git a/content/public/renderer/render_frame_observer.h b/content/public/renderer/render_frame_observer.h index 8136604..c246c0e 100644 --- a/content/public/renderer/render_frame_observer.h +++ b/content/public/renderer/render_frame_observer.h
@@ -9,6 +9,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" +#include "base/optional.h" #include "base/strings/string16.h" #include "content/common/content_export.h" #include "content/public/common/resource_type.h" @@ -21,6 +22,7 @@ #include "third_party/blink/public/platform/web_loading_behavior_flag.h" #include "third_party/blink/public/platform/web_vector.h" #include "third_party/blink/public/web/web_meaningful_layout.h" +#include "third_party/blink/public/web/web_navigation_type.h" #include "ui/base/page_transition_types.h" #include "v8/include/v8.h" @@ -69,17 +71,43 @@ // Called when associated widget is about to close. virtual void WidgetWillClose() {} + // Navigation callbacks. + // + // Each navigation starts with a DidStartNavigation call. Then it may be + // followed by a ReadyToCommitNavigation (if the navigation has succeeded), + // and should always end with a DidFinishNavigation. + // + // Unfortunately, this is currently a mess. For example, some started + // navigations which did not commit won't receive any further notifications. + // DidCommitProvisionalLoad will be called for same-document navigations, + // without any other notifications. DidFailProvisionalLoad will be called + // when committing error pages, in addition to all the methods (start, ready, + // commit) for the error page load itself. + + // Called when the RenderFrame has started a navigation. + // |url| is a url being navigated to. Note that final url might be different + // due to redirects. + // |navigation_type| is only present for renderer-initiated navigations, e.g. + // JavaScript call, link click, form submit. User-initiated navigations from + // the browser process (e.g. by typing a url) won't have a navigation type. + virtual void DidStartNavigation( + const GURL& url, + base::Optional<blink::WebNavigationType> navigation_type) {} + + // Called when a navigation is about to be committed and |document_loader| + // will start loading a new document in the RenderFrame. + virtual void ReadyToCommitNavigation( + blink::WebDocumentLoader* document_loader) {} + // These match the Blink API notifications virtual void DidCreateNewDocument() {} virtual void DidCreateDocumentElement() {} // Called when a provisional load is about to commit in a frame. This is // dispatched just before the Javascript unload event. virtual void WillCommitProvisionalLoad() {} + // TODO(dgozman): replace next two methods with DidFinishNavigation. virtual void DidCommitProvisionalLoad(bool is_same_document_navigation, ui::PageTransition transition) {} - virtual void DidStartProvisionalLoad( - blink::WebDocumentLoader* document_loader, - bool is_content_initiated) {} virtual void DidFailProvisionalLoad(const blink::WebURLError& error) {} virtual void DidFinishLoad() {} virtual void DidFinishDocumentLoad() {}
diff --git a/content/public/test/browser_test_utils.cc b/content/public/test/browser_test_utils.cc index b138d77..c2402c94 100644 --- a/content/public/test/browser_test_utils.cc +++ b/content/public/test/browser_test_utils.cc
@@ -88,7 +88,7 @@ #include "content/public/test/test_navigation_observer.h" #include "content/public/test/test_utils.h" #include "content/test/accessibility_browser_test_utils.h" -#include "content/test/did_commit_provisional_load_interceptor.h" +#include "content/test/frame_host_interceptor.h" #include "ipc/ipc_security_test_util.h" #include "net/base/filename_util.h" #include "net/base/io_buffer.h" @@ -538,13 +538,13 @@ // Interceptor that replaces params.url with |new_url| and params.origin with // |new_origin| for any commits to |target_url|. -class CommitOriginInterceptor : public DidCommitProvisionalLoadInterceptor { +class CommitOriginInterceptor : public FrameHostInterceptor { public: CommitOriginInterceptor(WebContents* web_contents, const GURL& target_url, const GURL& new_url, const url::Origin& new_origin) - : DidCommitProvisionalLoadInterceptor(web_contents), + : FrameHostInterceptor(web_contents), target_url_(target_url), new_url_(new_url), new_origin_(new_origin) {} @@ -557,7 +557,7 @@ bool WillDispatchDidCommitProvisionalLoad( RenderFrameHost* render_frame_host, ::FrameHostMsg_DidCommitProvisionalLoad_Params* params, - mojom::DidCommitProvisionalLoadInterfaceParamsPtr& interface_params) + mojom::DidCommitProvisionalLoadInterfaceParamsPtr* interface_params) override { if (params->url == target_url_) { params->url = new_url_;
diff --git a/content/public/test/content_browser_test_utils.cc b/content/public/test/content_browser_test_utils.cc index e2e338c3..b21dbd8f 100644 --- a/content/public/test/content_browser_test_utils.cc +++ b/content/public/test/content_browser_test_utils.cc
@@ -4,17 +4,21 @@ #include "content/public/test/content_browser_test_utils.h" +#include <string> #include <utility> #include "base/bind.h" #include "base/files/file_path.h" +#include "base/guid.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/task/post_task.h" #include "base/threading/thread_restrictions.h" #include "content/browser/browser_main_loop.h" +#include "content/browser/child_process_security_policy_impl.h" #include "content/browser/renderer_host/media/media_stream_manager.h" #include "content/browser/renderer_host/media/video_capture_manager.h" +#include "content/browser/site_instance_impl.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_controller.h" @@ -30,6 +34,7 @@ #include "content/shell/browser/shell.h" #include "content/shell/browser/shell_javascript_dialog_manager.h" #include "net/base/filename_util.h" +#include "net/test/embedded_test_server/embedded_test_server.h" namespace content { @@ -177,4 +182,45 @@ runner_->QuitClosure().Run(); } +void IsolateOriginsForTesting( + net::test_server::EmbeddedTestServer* embedded_test_server, + WebContents* web_contents, + std::vector<std::string> hostnames_to_isolate) { + std::vector<url::Origin> origins_to_isolate; + for (const std::string& hostname : hostnames_to_isolate) { + origins_to_isolate.push_back( + url::Origin::Create(GURL(std::string("http://") + hostname + "/"))); + } + + auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); + policy->AddIsolatedOrigins(origins_to_isolate); + + // Force a BrowsingInstance swap by navigating cross-site (the newly + // isolated origin only affects *future* BrowsingInstances). + scoped_refptr<SiteInstanceImpl> old_site_instance; + scoped_refptr<SiteInstanceImpl> new_site_instance; + do { + old_site_instance = static_cast<SiteInstanceImpl*>( + web_contents->GetMainFrame()->GetSiteInstance()); + std::string cross_site_hostname = base::GenerateGUID() + ".com"; + EXPECT_TRUE(NavigateToURL( + web_contents, + embedded_test_server->GetURL(cross_site_hostname, "/title1.html"))); + new_site_instance = static_cast<SiteInstanceImpl*>( + web_contents->GetMainFrame()->GetSiteInstance()); + + // The navigation might need to be repeated until we actually swap the + // SiteInstance (no swap might happen when navigating away from the initial, + // empty frame). + } while (new_site_instance.get() == old_site_instance.get()); + EXPECT_FALSE( + new_site_instance->IsRelatedSiteInstance(old_site_instance.get())); + for (const url::Origin& origin : origins_to_isolate) { + EXPECT_FALSE(policy->IsIsolatedOrigin( + old_site_instance->GetIsolationContext(), origin)); + EXPECT_TRUE(policy->IsIsolatedOrigin( + new_site_instance->GetIsolationContext(), origin)); + } +} + } // namespace content
diff --git a/content/public/test/content_browser_test_utils.h b/content/public/test/content_browser_test_utils.h index 451cc76..d0a77d4 100644 --- a/content/public/test/content_browser_test_utils.h +++ b/content/public/test/content_browser_test_utils.h
@@ -6,6 +6,7 @@ #define CONTENT_PUBLIC_TEST_CONTENT_BROWSER_TEST_UTILS_H_ #include <map> +#include <string> #include "base/callback.h" #include "base/macros.h" @@ -19,14 +20,20 @@ namespace mac { class ScopedObjCClassSwizzler; -} -} +} // namespace mac +} // namespace base namespace gfx { class Point; class Range; class Rect; -} +} // namespace gfx + +namespace net { +namespace test_server { +class EmbeddedTestServer; +} // namespace test_server +} // namespace net // A collections of functions designed for use with content_shell based browser // tests. @@ -206,6 +213,18 @@ #endif +// Adds http://<hostname_to_isolate>/ to the list of origins that require +// isolation (for each of the hostnames in the |hostnames_to_isolate| vector). +// +// To ensure that the isolation applies to subsequent navigations in +// |web_contents|, this function forces a BrowsingInstance swap by performing +// one or two browser-initiated navigations in |web_contents| to another, +// random, guid-based hostname. +void IsolateOriginsForTesting( + net::test_server::EmbeddedTestServer* embedded_test_server, + WebContents* web_contents, + std::vector<std::string> hostnames_to_isolate); + } // namespace content #endif // CONTENT_PUBLIC_TEST_CONTENT_BROWSER_TEST_UTILS_H_
diff --git a/content/public/test/signed_exchange_browser_test_helper.cc b/content/public/test/signed_exchange_browser_test_helper.cc new file mode 100644 index 0000000..4cd4619 --- /dev/null +++ b/content/public/test/signed_exchange_browser_test_helper.cc
@@ -0,0 +1,120 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/public/test/signed_exchange_browser_test_helper.h" + +#include <memory> + +#include "base/files/file_path.h" +#include "base/path_service.h" +#include "base/strings/utf_string_conversions.h" +#include "base/task/post_task.h" +#include "base/threading/thread_restrictions.h" +#include "content/browser/web_package/signed_exchange_handler.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/common/content_features.h" +#include "content/public/common/content_paths.h" +#include "content/public/test/browser_test_utils.h" +#include "net/cert/cert_verify_result.h" +#include "net/cert/mock_cert_verifier.h" +#include "net/dns/mock_host_resolver.h" +#include "net/test/cert_test_util.h" +#include "net/test/url_request/url_request_mock_http_job.h" +#include "net/url_request/url_request_filter.h" +#include "services/network/public/cpp/features.h" + +namespace content { + +constexpr uint64_t SignedExchangeBrowserTestHelper::kSignatureHeaderDate = + 1520834000; // 2018-03-12T05:53:20Z +constexpr uint64_t SignedExchangeBrowserTestHelper::kSignatureHeaderExpires = + 1520837600; // 2018-03-12T06:53:20Z + +SignedExchangeBrowserTestHelper::SignedExchangeBrowserTestHelper() = default; + +SignedExchangeBrowserTestHelper::~SignedExchangeBrowserTestHelper() = default; + +void SignedExchangeBrowserTestHelper::SetUp() { + SignedExchangeHandler::SetVerificationTimeForTesting( + base::Time::UnixEpoch() + + base::TimeDelta::FromSeconds(kSignatureHeaderDate)); +} + +void SignedExchangeBrowserTestHelper::TearDownOnMainThread() { + interceptor_.reset(); + SignedExchangeHandler::SetVerificationTimeForTesting( + base::Optional<base::Time>()); +} + +scoped_refptr<net::X509Certificate> +SignedExchangeBrowserTestHelper::LoadCertificate() { + constexpr char kCertFileName[] = "prime256v1-sha256.public.pem"; + + base::ScopedAllowBlockingForTesting allow_io; + base::FilePath dir_path; + base::PathService::Get(content::DIR_TEST_DATA, &dir_path); + dir_path = dir_path.Append(FILE_PATH_LITERAL("sxg")); + + return net::CreateCertificateChainFromFile( + dir_path, kCertFileName, net::X509Certificate::FORMAT_PEM_CERT_SEQUENCE); +} + +void SignedExchangeBrowserTestHelper::InstallUrlInterceptor( + const GURL& url, + const std::string& data_path) { + if (base::FeatureList::IsEnabled(network::features::kNetworkService)) { + if (!interceptor_) { + interceptor_ = std::make_unique<URLLoaderInterceptor>(base::BindRepeating( + &SignedExchangeBrowserTestHelper::OnInterceptCallback, + base::Unretained(this))); + } + interceptor_data_path_map_[url] = data_path; + } else { + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&InstallMockInterceptors, url, data_path)); + } +} + +void SignedExchangeBrowserTestHelper::InstallMockCert( + content::ContentMockCertVerifier::CertVerifier* cert_verifier) { + // Make the MockCertVerifier treat the certificate + // "prime256v1-sha256.public.pem" as valid for "test.example.org". + scoped_refptr<net::X509Certificate> original_cert = LoadCertificate(); + net::CertVerifyResult dummy_result; + dummy_result.verified_cert = original_cert; + dummy_result.cert_status = net::OK; + dummy_result.ocsp_result.response_status = net::OCSPVerifyResult::PROVIDED; + dummy_result.ocsp_result.revocation_status = net::OCSPRevocationStatus::GOOD; + cert_verifier->AddResultForCertAndHost(original_cert, "test.example.org", + dummy_result, net::OK); +} + +void SignedExchangeBrowserTestHelper::InstallMockCertChainInterceptor() { + InstallUrlInterceptor( + GURL("https://cert.example.org/cert.msg"), + "content/test/data/sxg/test.example.org.public.pem.cbor"); +} + +void SignedExchangeBrowserTestHelper::InstallMockInterceptors( + const GURL& url, + const std::string& data_path) { + base::FilePath root_path; + CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &root_path)); + net::URLRequestFilter::GetInstance()->AddUrlInterceptor( + url, net::URLRequestMockHTTPJob::CreateInterceptorForSingleFile( + root_path.AppendASCII(data_path))); +} + +bool SignedExchangeBrowserTestHelper::OnInterceptCallback( + URLLoaderInterceptor::RequestParams* params) { + const auto it = interceptor_data_path_map_.find(params->url_request.url); + if (it == interceptor_data_path_map_.end()) + return false; + URLLoaderInterceptor::WriteResponse(it->second, params->client.get()); + return true; +} + +} // namespace content
diff --git a/content/public/test/signed_exchange_browser_test_helper.h b/content/public/test/signed_exchange_browser_test_helper.h new file mode 100644 index 0000000..37cc0e5f --- /dev/null +++ b/content/public/test/signed_exchange_browser_test_helper.h
@@ -0,0 +1,88 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_PUBLIC_TEST_SIGNED_EXCHANGE_BROWSER_TEST_HELPER_H_ +#define CONTENT_PUBLIC_TEST_SIGNED_EXCHANGE_BROWSER_TEST_HELPER_H_ + +#include <map> +#include <memory> +#include <string> + +#include "base/test/metrics/histogram_tester.h" +#include "base/test/scoped_feature_list.h" +#include "content/public/test/content_mock_cert_verifier.h" +#include "content/public/test/url_loader_interceptor.h" +#include "net/cert/x509_certificate.h" +#include "url/gurl.h" + +namespace content { + +// SignedExchangeBrowserTestHelper helps writing browser tests for +// signed exchanges by: +// - Override signed exchange verification time epoch +// to that of the test SXGs in content/test/data/sxg. +// See kSignatureHeaderDate and kSignatureHeaderExpires for more details. +// - Setup URLLoaderInterceptor, which serves injected content via +// InstallUrlInterceptor. +// +// Typical usage would look like following: +// +// Installs a test mock certificate to the |mock_cert_verifier| +// to work with the test certificate used by the helper: +// SignedExchangeBrowserTestHlper helper; +// helper.InstallMockCert(mock_cert_verifier()); +// +// Then installs a HTTP request interceptor for the cert chain +// for the same test mock certificate so that it can be fetched at +// the cert URL embedded in the test SXGs in content/test/data/sxg. +// helper.InstallMockCertChainInterceptor() +// +// Sets up HTTP request interceptors for the testing (e.g. SXGs, +// service worker resources). +// helper.InstallUrlInterceptor( +// GURL("https://test.example.org/scope/test.sxg"), +// "content/test/data/sxg/test.example.org_test.sxg"); +class SignedExchangeBrowserTestHelper { + public: + SignedExchangeBrowserTestHelper(); + ~SignedExchangeBrowserTestHelper(); + + void SetUp(); + void TearDownOnMainThread(); + + // Load the same certificate file as the one that is used by the helper. + // This can be used to verify if the same cert is correctly set up or to + // compute its fingerprint. + static scoped_refptr<net::X509Certificate> LoadCertificate(); + + // Make the |cert_verifier| trust the test certificate for "test.example.org". + void InstallMockCert( + content::ContentMockCertVerifier::CertVerifier* cert_verifier); + + void InstallUrlInterceptor(const GURL& url, const std::string& data_path); + + // Make the URL loader interceptor serve the test certchain cbor for + // "test.example.org" at "https://cert.example.org/cert.msg". + void InstallMockCertChainInterceptor(); + + // 'Date' and 'Expire' timestamp of the SXGs in content/test/data/sxg in Unix + // time. + static const uint64_t kSignatureHeaderDate; + static const uint64_t kSignatureHeaderExpires; + + private: + static void InstallMockInterceptors(const GURL& url, + const std::string& data_path); + + bool OnInterceptCallback(URLLoaderInterceptor::RequestParams* params); + + std::unique_ptr<URLLoaderInterceptor> interceptor_; + std::map<GURL, std::string> interceptor_data_path_map_; + + DISALLOW_COPY_AND_ASSIGN(SignedExchangeBrowserTestHelper); +}; + +} // namespace content + +#endif // CONTENT_PUBLIC_TEST_SIGNED_EXCHANGE_BROWSER_TEST_HELPER_H_
diff --git a/content/public/test/test_browser_thread_bundle.cc b/content/public/test/test_browser_thread_bundle.cc index fe26c0b..b42e48d 100644 --- a/content/public/test/test_browser_thread_bundle.cc +++ b/content/public/test/test_browser_thread_bundle.cc
@@ -54,7 +54,7 @@ // blocked upon it could make a test flaky whereas by flushing we guarantee // it will blow up). RunAllTasksUntilIdle(); - CHECK(!MainThreadHasPendingTask()); + CHECK(MainThreadIsIdle()); } BrowserTaskExecutor::ResetForTesting();
diff --git a/content/public/test/test_launcher.cc b/content/public/test/test_launcher.cc index 08a36b5f..d4bc196 100644 --- a/content/public/test/test_launcher.cc +++ b/content/public/test/test_launcher.cc
@@ -136,6 +136,8 @@ // base::TestLauncherDelegate: bool GetTests(std::vector<base::TestIdentifier>* output) override; + bool WillRunTest(const std::string& test_case_name, + const std::string& test_name) override; bool ShouldRunTest(const std::string& test_case_name, const std::string& test_name) override; size_t RunTests(base::TestLauncher* test_launcher, @@ -261,9 +263,8 @@ base::CompareCase::SENSITIVE); } -bool WrapperTestLauncherDelegate::ShouldRunTest( - const std::string& test_case_name, - const std::string& test_name) { +bool WrapperTestLauncherDelegate::WillRunTest(const std::string& test_case_name, + const std::string& test_name) { all_test_names_.insert(test_case_name + "." + test_name); if (base::StartsWith(test_name, kManualTestPrefix, @@ -272,6 +273,15 @@ return false; } + return true; +} + +bool WrapperTestLauncherDelegate::ShouldRunTest( + const std::string& test_case_name, + const std::string& test_name) { + if (!WillRunTest(test_case_name, test_name)) + return false; + if (IsPreTestName(test_name)) { // We will actually run PRE_ tests, but to ensure they run on the same shard // as dependent tests, handle all these details internally.
diff --git a/content/renderer/BUILD.gn b/content/renderer/BUILD.gn index 47714c8..e214e00 100644 --- a/content/renderer/BUILD.gn +++ b/content/renderer/BUILD.gn
@@ -48,8 +48,6 @@ "android/synchronous_compositor_registry.h", "android/synchronous_layer_tree_frame_sink.cc", "android/synchronous_layer_tree_frame_sink.h", - "appcache/appcache_frontend_impl.cc", - "appcache/appcache_frontend_impl.h", "appcache/web_application_cache_host_impl.cc", "appcache/web_application_cache_host_impl.h", "blob_storage/webblobregistry_impl.cc", @@ -614,6 +612,7 @@ "//components/viz/common", "//components/viz/service", "//content:resources", + "//content/app/strings:strings_grit", "//content/child", "//content/common", "//content/common:buildflags",
diff --git a/content/renderer/accessibility/ax_image_annotator.cc b/content/renderer/accessibility/ax_image_annotator.cc index e8805b0..8bb9729 100644 --- a/content/renderer/accessibility/ax_image_annotator.cc +++ b/content/renderer/accessibility/ax_image_annotator.cc
@@ -6,6 +6,10 @@ #include "base/base64.h" #include "base/stl_util.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/utf_string_conversions.h" +#include "content/app/strings/grit/content_strings.h" +#include "content/public/common/content_client.h" #include "content/renderer/render_frame_impl.h" #include "crypto/sha2.h" #include "third_party/blink/public/web/web_ax_object.h" @@ -177,9 +181,16 @@ DLOG(WARNING) << "Unrecognized image annotation result."; return; } - // TODO(nektar): Add message to explain that the annotation is a best guess, - // e.g. "appears to be". - image_annotations_.at(image.AxID()).set_annotation(result->get_ocr_text()); + + if (result->get_ocr_text().empty()) + return; + + auto contextualized_string = GetContentClient()->GetLocalizedString( + IDS_AX_IMAGE_ANNOTATION_OCR_CONTEXT, + base::UTF8ToUTF16(result->get_ocr_text())); + + image_annotations_.at(image.AxID()) + .set_annotation(base::UTF16ToUTF8(contextualized_string)); render_accessibility_->MarkWebAXObjectDirty(image, false /* subtree */); }
diff --git a/content/renderer/accessibility/blink_ax_tree_source.cc b/content/renderer/accessibility/blink_ax_tree_source.cc index 372534c..a4d52db 100644 --- a/content/renderer/accessibility/blink_ax_tree_source.cc +++ b/content/renderer/accessibility/blink_ax_tree_source.cc
@@ -8,6 +8,7 @@ #include <set> +#include "base/command_line.h" #include "base/memory/ptr_util.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" @@ -38,6 +39,7 @@ #include "third_party/blink/public/web/web_plugin.h" #include "third_party/blink/public/web/web_plugin_container.h" #include "third_party/blink/public/web/web_view.h" +#include "ui/accessibility/accessibility_switches.h" #include "ui/accessibility/ax_enum_util.h" #include "ui/accessibility/ax_role_properties.h" #include "ui/gfx/geometry/vector2d_f.h" @@ -480,32 +482,32 @@ AXContentNodeDataSparseAttributeAdapter sparse_attribute_adapter(dst); src.GetSparseAXAttributes(sparse_attribute_adapter); - ax::mojom::NameFrom nameFrom; - blink::WebVector<WebAXObject> nameObjects; - blink::WebString web_name = src.GetName(nameFrom, nameObjects); + ax::mojom::NameFrom name_from; + blink::WebVector<WebAXObject> name_objects; + blink::WebString web_name = src.GetName(name_from, name_objects); if ((!web_name.IsEmpty() && !web_name.IsNull()) || - nameFrom == ax::mojom::NameFrom::kAttributeExplicitlyEmpty) { + name_from == ax::mojom::NameFrom::kAttributeExplicitlyEmpty) { int max_length = dst->role == ax::mojom::Role::kStaticText ? kMaxStaticTextLength : kMaxStringAttributeLength; TruncateAndAddStringAttribute(dst, ax::mojom::StringAttribute::kName, web_name.Utf8(), max_length); - dst->SetNameFrom(nameFrom); + dst->SetNameFrom(name_from); AddIntListAttributeFromWebObjects( - ax::mojom::IntListAttribute::kLabelledbyIds, nameObjects, dst); + ax::mojom::IntListAttribute::kLabelledbyIds, name_objects, dst); } - ax::mojom::DescriptionFrom descriptionFrom; - blink::WebVector<WebAXObject> descriptionObjects; + ax::mojom::DescriptionFrom description_from; + blink::WebVector<WebAXObject> description_objects; blink::WebString web_description = - src.Description(nameFrom, descriptionFrom, descriptionObjects); + src.Description(name_from, description_from, description_objects); if (!web_description.IsEmpty()) { TruncateAndAddStringAttribute(dst, ax::mojom::StringAttribute::kDescription, web_description.Utf8()); dst->AddIntAttribute(ax::mojom::IntAttribute::kDescriptionFrom, - static_cast<int32_t>(descriptionFrom)); + static_cast<int32_t>(description_from)); AddIntListAttributeFromWebObjects( - ax::mojom::IntListAttribute::kDescribedbyIds, descriptionObjects, dst); + ax::mojom::IntListAttribute::kDescribedbyIds, description_objects, dst); } if (src.ValueDescription().length()) { @@ -537,7 +539,7 @@ // mode is set to screen reader mode, otherwise only the more basic // attributes are populated. if (accessibility_mode_.has_mode(ui::AXMode::kScreenReader)) { - blink::WebString web_placeholder = src.Placeholder(nameFrom); + blink::WebString web_placeholder = src.Placeholder(name_from); if (!web_placeholder.IsEmpty()) TruncateAndAddStringAttribute(dst, ax::mojom::StringAttribute::kPlaceholder, @@ -878,17 +880,9 @@ dst->AddIntAttribute(ax::mojom::IntAttribute::kSortDirection, static_cast<int32_t>(src.SortDirection())); } - } - if (accessibility_mode_.has_mode(ui::AXMode::kLabelImages) && - dst->role == ax::mojom::Role::kImage) { - DCHECK(image_annotator_); - if (image_annotator_->HasAnnotationInCache(src)) { - dst->AddStringAttribute(ax::mojom::StringAttribute::kImageAnnotation, - image_annotator_->GetImageAnnotation(src)); - } else if (!image_annotator_->HasImageInCache(src)) { - image_annotator_->OnImageAdded(src); - } + if (dst->role == ax::mojom::Role::kImage) + AddImageAnnotations(src, dst); } // The majority of the rest of this code computes attributes needed for @@ -1044,4 +1038,42 @@ } } +void BlinkAXTreeSource::AddImageAnnotations(blink::WebAXObject src, + AXContentNodeData* dst) const { + if (!base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kEnableExperimentalAccessibilityLabels)) + return; + + // Reject images that are explicitly empty, or that have a name already. + // + // In the future, we may annotate some images that have a name + // if we think we can add additional useful information. + if (dst->GetNameFrom() == ax::mojom::NameFrom::kAttributeExplicitlyEmpty || + dst->HasStringAttribute(ax::mojom::StringAttribute::kName)) { + dst->SetImageAnnotationStatus( + ax::mojom::ImageAnnotationStatus::kIneligibleForAnnotation); + return; + } + + if (!image_annotator_) { + dst->SetImageAnnotationStatus( + ax::mojom::ImageAnnotationStatus::kEligibleForAnnotation); + return; + } + + if (image_annotator_->HasAnnotationInCache(src)) { + dst->AddStringAttribute(ax::mojom::StringAttribute::kImageAnnotation, + image_annotator_->GetImageAnnotation(src)); + dst->SetImageAnnotationStatus( + ax::mojom::ImageAnnotationStatus::kAnnotationSucceeded); + } else if (image_annotator_->HasImageInCache(src)) { + dst->SetImageAnnotationStatus( + ax::mojom::ImageAnnotationStatus::kAnnotationPending); + } else if (!image_annotator_->HasImageInCache(src)) { + image_annotator_->OnImageAdded(src); + dst->SetImageAnnotationStatus( + ax::mojom::ImageAnnotationStatus::kAnnotationPending); + } +} + } // namespace content
diff --git a/content/renderer/accessibility/blink_ax_tree_source.h b/content/renderer/accessibility/blink_ax_tree_source.h index 7f9c6788..8f635658 100644 --- a/content/renderer/accessibility/blink_ax_tree_source.h +++ b/content/renderer/accessibility/blink_ax_tree_source.h
@@ -129,6 +129,9 @@ const std::string& value, uint32_t max_len = kMaxStringAttributeLength) const; + void AddImageAnnotations(blink::WebAXObject node, + AXContentNodeData* out_data) const; + RenderFrameImpl* render_frame_; ui::AXMode accessibility_mode_;
diff --git a/content/renderer/appcache/appcache_frontend_impl.cc b/content/renderer/appcache/appcache_frontend_impl.cc deleted file mode 100644 index 49135bb..0000000 --- a/content/renderer/appcache/appcache_frontend_impl.cc +++ /dev/null
@@ -1,101 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/appcache/appcache_frontend_impl.h" - -#include "content/public/common/service_names.mojom.h" -#include "content/public/renderer/render_thread.h" -#include "content/renderer/appcache/web_application_cache_host_impl.h" -#include "mojo/public/cpp/bindings/interface_request.h" -#include "services/service_manager/public/cpp/connector.h" -#include "third_party/blink/public/mojom/appcache/appcache.mojom.h" -#include "third_party/blink/public/mojom/appcache/appcache_info.mojom.h" -#include "third_party/blink/public/mojom/devtools/console_message.mojom.h" - -using blink::WebApplicationCacheHost; - -namespace content { - -// Inline helper to keep the lines shorter and unwrapped. -inline WebApplicationCacheHostImpl* GetHost(int id) { - return WebApplicationCacheHostImpl::FromId(id); -} - -AppCacheFrontendImpl::AppCacheFrontendImpl() : binding_(this) {} -AppCacheFrontendImpl::~AppCacheFrontendImpl() = default; - -void AppCacheFrontendImpl::Bind(blink::mojom::AppCacheFrontendRequest request) { - binding_.Bind(std::move(request)); -} - -blink::mojom::AppCacheBackend* AppCacheFrontendImpl::backend_proxy() { - if (!backend_ptr_) { - RenderThread::Get()->GetConnector()->BindInterface( - mojom::kBrowserServiceName, mojo::MakeRequest(&backend_ptr_)); - } - return backend_ptr_.get(); -} - -void AppCacheFrontendImpl::CacheSelected(int32_t host_id, - blink::mojom::AppCacheInfoPtr info) { - WebApplicationCacheHostImpl* host = GetHost(host_id); - if (host) - host->OnCacheSelected(*info); -} - -void AppCacheFrontendImpl::EventRaised(const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheEventID event_id) { - DCHECK_NE(event_id, - blink::mojom::AppCacheEventID:: - APPCACHE_PROGRESS_EVENT); // See OnProgressEventRaised. - DCHECK_NE(event_id, - blink::mojom::AppCacheEventID:: - APPCACHE_ERROR_EVENT); // See OnErrorEventRaised. - for (auto i = host_ids.begin(); i != host_ids.end(); ++i) { - WebApplicationCacheHostImpl* host = GetHost(*i); - if (host) - host->OnEventRaised(event_id); - } -} - -void AppCacheFrontendImpl::ProgressEventRaised( - const std::vector<int32_t>& host_ids, - const GURL& url, - int32_t num_total, - int32_t num_complete) { - for (auto i = host_ids.begin(); i != host_ids.end(); ++i) { - WebApplicationCacheHostImpl* host = GetHost(*i); - if (host) - host->OnProgressEventRaised(url, num_total, num_complete); - } -} - -void AppCacheFrontendImpl::ErrorEventRaised( - const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheErrorDetailsPtr details) { - for (auto i = host_ids.begin(); i != host_ids.end(); ++i) { - WebApplicationCacheHostImpl* host = GetHost(*i); - if (host) - host->OnErrorEventRaised(*details); - } -} - -void AppCacheFrontendImpl::LogMessage( - int32_t host_id, - blink::mojom::ConsoleMessageLevel log_level, - const std::string& message) { - WebApplicationCacheHostImpl* host = GetHost(host_id); - if (host) - host->OnLogMessage(log_level, message); -} - -void AppCacheFrontendImpl::SetSubresourceFactory( - int32_t host_id, - network::mojom::URLLoaderFactoryPtr url_loader_factory) { - WebApplicationCacheHostImpl* host = GetHost(host_id); - if (host) - host->SetSubresourceFactory(std::move(url_loader_factory)); -} - -} // namespace content
diff --git a/content/renderer/appcache/appcache_frontend_impl.h b/content/renderer/appcache/appcache_frontend_impl.h deleted file mode 100644 index 3bde802..0000000 --- a/content/renderer/appcache/appcache_frontend_impl.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_APPCACHE_APPCACHE_FRONTEND_IMPL_H_ -#define CONTENT_RENDERER_APPCACHE_APPCACHE_FRONTEND_IMPL_H_ - -#include <cstdint> -#include <string> -#include <vector> - -#include "mojo/public/cpp/bindings/binding.h" -#include "third_party/blink/public/mojom/appcache/appcache.mojom.h" -#include "third_party/blink/public/mojom/appcache/appcache_info.mojom.h" -#include "third_party/blink/public/mojom/devtools/console_message.mojom.h" - -namespace content { - -// Dispatches appcache related messages sent to a child process from the main -// browser process. There is one instance per child process. -class AppCacheFrontendImpl : public blink::mojom::AppCacheFrontend { - public: - AppCacheFrontendImpl(); - ~AppCacheFrontendImpl() override; - - void Bind(blink::mojom::AppCacheFrontendRequest request); - - blink::mojom::AppCacheBackend* backend_proxy(); - - private: - // blink::mojom::AppCacheFrontend - void CacheSelected(int32_t host_id, - blink::mojom::AppCacheInfoPtr info) override; - void EventRaised(const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheEventID event_id) override; - void ProgressEventRaised(const std::vector<int32_t>& host_ids, - const GURL& url, - int32_t num_total, - int32_t num_complete) override; - void ErrorEventRaised(const std::vector<int32_t>& host_ids, - blink::mojom::AppCacheErrorDetailsPtr details) override; - void LogMessage(int32_t host_id, - blink::mojom::ConsoleMessageLevel log_level, - const std::string& message) override; - void SetSubresourceFactory( - int32_t host_id, - network::mojom::URLLoaderFactoryPtr url_loader_factory) override; - - blink::mojom::AppCacheBackendPtr backend_ptr_; - mojo::Binding<blink::mojom::AppCacheFrontend> binding_; -}; - -} // namespace content - -#endif // CONTENT_RENDERER_APPCACHE_APPCACHE_FRONTEND_IMPL_H_
diff --git a/content/renderer/appcache/web_application_cache_host_impl.cc b/content/renderer/appcache/web_application_cache_host_impl.cc index 3d5daed1e..a1bd57e 100644 --- a/content/renderer/appcache/web_application_cache_host_impl.cc +++ b/content/renderer/appcache/web_application_cache_host_impl.cc
@@ -12,6 +12,10 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "content/common/appcache_interfaces.h" +#include "content/public/common/service_names.mojom.h" +#include "content/public/renderer/render_thread.h" +#include "mojo/public/cpp/bindings/interface_request.h" +#include "services/service_manager/public/cpp/connector.h" #include "third_party/blink/public/mojom/appcache/appcache.mojom.h" #include "third_party/blink/public/mojom/appcache/appcache_info.mojom.h" #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" @@ -60,17 +64,16 @@ WebApplicationCacheHostImpl::WebApplicationCacheHostImpl( WebApplicationCacheHostClient* client, - blink::mojom::AppCacheBackend* backend, int appcache_host_id, int render_frame_id) - : client_(client), - backend_(backend), + : binding_(this), + client_(client), status_(blink::mojom::AppCacheStatus::APPCACHE_STATUS_UNCACHED), is_scheme_supported_(false), is_get_method_(false), is_new_master_entry_(MAYBE_NEW_ENTRY), was_select_cache_called_(false) { - DCHECK(client && backend); + DCHECK(client); // PlzNavigate: The browser passes the ID to be used. if (appcache_host_id != blink::mojom::kAppCacheNoHostId) { all_hosts()->AddWithID(this, appcache_host_id); @@ -80,21 +83,32 @@ } DCHECK(host_id_ != blink::mojom::kAppCacheNoHostId); - backend_->RegisterHost(mojo::MakeRequest(&backend_host_), host_id_, - render_frame_id); + static const base::NoDestructor<blink::mojom::AppCacheBackendPtr> backend_ptr( + [] { + blink::mojom::AppCacheBackendPtr result; + RenderThread::Get()->GetConnector()->BindInterface( + mojom::kBrowserServiceName, mojo::MakeRequest(&result)); + return result; + }()); + backend_ = backend_ptr->get(); + + blink::mojom::AppCacheFrontendPtr frontend_ptr; + binding_.Bind(mojo::MakeRequest(&frontend_ptr)); + backend_->RegisterHost(mojo::MakeRequest(&backend_host_), + std::move(frontend_ptr), host_id_, render_frame_id); } WebApplicationCacheHostImpl::~WebApplicationCacheHostImpl() { all_hosts()->Remove(host_id_); } -void WebApplicationCacheHostImpl::OnCacheSelected( - const blink::mojom::AppCacheInfo& info) { - cache_info_ = info; +void WebApplicationCacheHostImpl::CacheSelected( + blink::mojom::AppCacheInfoPtr info) { + cache_info_ = *info; client_->DidChangeCacheAssociation(); } -void WebApplicationCacheHostImpl::OnEventRaised( +void WebApplicationCacheHostImpl::EventRaised( blink::mojom::AppCacheEventID event_id) { DCHECK_NE(event_id, blink::mojom::AppCacheEventID:: @@ -108,7 +122,7 @@ const char kFormatString[] = "Application Cache %s event"; std::string message = base::StringPrintf( kFormatString, kEventNames[static_cast<int>(event_id)]); - OnLogMessage(blink::mojom::ConsoleMessageLevel::kInfo, message); + LogMessage(blink::mojom::ConsoleMessageLevel::kInfo, message); switch (event_id) { case blink::mojom::AppCacheEventID::APPCACHE_CHECKING_EVENT: @@ -135,40 +149,41 @@ client_->NotifyEventListener(event_id); } -void WebApplicationCacheHostImpl::OnProgressEventRaised( - const GURL& url, int num_total, int num_complete) { +void WebApplicationCacheHostImpl::ProgressEventRaised(const GURL& url, + int num_total, + int num_complete) { // Emit logging output prior to calling out to script as we can get // deleted within the script event handler. const char kFormatString[] = "Application Cache Progress event (%d of %d) %s"; std::string message = base::StringPrintf(kFormatString, num_complete, num_total, url.spec().c_str()); - OnLogMessage(blink::mojom::ConsoleMessageLevel::kInfo, message); + LogMessage(blink::mojom::ConsoleMessageLevel::kInfo, message); status_ = blink::mojom::AppCacheStatus::APPCACHE_STATUS_DOWNLOADING; client_->NotifyProgressEventListener(url, num_total, num_complete); } -void WebApplicationCacheHostImpl::OnErrorEventRaised( - const blink::mojom::AppCacheErrorDetails& details) { +void WebApplicationCacheHostImpl::ErrorEventRaised( + blink::mojom::AppCacheErrorDetailsPtr details) { // Emit logging output prior to calling out to script as we can get // deleted within the script event handler. const char kFormatString[] = "Application Cache Error event: %s"; std::string full_message = - base::StringPrintf(kFormatString, details.message.c_str()); - OnLogMessage(blink::mojom::ConsoleMessageLevel::kError, full_message); + base::StringPrintf(kFormatString, details->message.c_str()); + LogMessage(blink::mojom::ConsoleMessageLevel::kError, full_message); status_ = cache_info_.is_complete ? blink::mojom::AppCacheStatus::APPCACHE_STATUS_IDLE : blink::mojom::AppCacheStatus::APPCACHE_STATUS_UNCACHED; - if (details.is_cross_origin) { + if (details->is_cross_origin) { // Don't leak detailed information to script for cross-origin resources. DCHECK_EQ(blink::mojom::AppCacheErrorReason::APPCACHE_RESOURCE_ERROR, - details.reason); - client_->NotifyErrorEventListener(details.reason, details.url, 0, + details->reason); + client_->NotifyErrorEventListener(details->reason, details->url, 0, WebString()); } else { - client_->NotifyErrorEventListener(details.reason, details.url, - details.status, - WebString::FromUTF8(details.message)); + client_->NotifyErrorEventListener(details->reason, details->url, + details->status, + WebString::FromUTF8(details->message)); } }
diff --git a/content/renderer/appcache/web_application_cache_host_impl.h b/content/renderer/appcache/web_application_cache_host_impl.h index c932c20..14b0e19 100644 --- a/content/renderer/appcache/web_application_cache_host_impl.h +++ b/content/renderer/appcache/web_application_cache_host_impl.h
@@ -7,7 +7,7 @@ #include <string> -#include "mojo/public/cpp/system/message_pipe.h" +#include "mojo/public/cpp/bindings/binding.h" #include "third_party/blink/public/mojom/appcache/appcache.mojom.h" #include "third_party/blink/public/mojom/appcache/appcache_info.mojom.h" #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" @@ -19,13 +19,13 @@ namespace content { -class WebApplicationCacheHostImpl : public blink::WebApplicationCacheHost { +class WebApplicationCacheHostImpl : public blink::WebApplicationCacheHost, + public blink::mojom::AppCacheFrontend { public: // Returns the host having given id or NULL if there is no such host. static WebApplicationCacheHostImpl* FromId(int id); WebApplicationCacheHostImpl(blink::WebApplicationCacheHostClient* client, - blink::mojom::AppCacheBackend* backend, int appcache_host_id, int render_frame_id); ~WebApplicationCacheHostImpl() override; @@ -34,12 +34,13 @@ blink::mojom::AppCacheBackend* backend() const { return backend_; } blink::WebApplicationCacheHostClient* client() const { return client_; } - virtual void OnCacheSelected(const blink::mojom::AppCacheInfo& info); - void OnEventRaised(blink::mojom::AppCacheEventID); - void OnProgressEventRaised(const GURL& url, int num_total, int num_complete); - void OnErrorEventRaised(const blink::mojom::AppCacheErrorDetails& details); - virtual void OnLogMessage(blink::mojom::ConsoleMessageLevel log_level, - const std::string& message) {} + // blink::mojom::AppCacheFrontend + void CacheSelected(blink::mojom::AppCacheInfoPtr info) override; + void EventRaised(blink::mojom::AppCacheEventID event_id) override; + void ProgressEventRaised(const GURL& url, + int32_t num_total, + int32_t num_complete) override; + void ErrorEventRaised(blink::mojom::AppCacheErrorDetailsPtr details) override; // blink::WebApplicationCacheHost: void WillStartMainResourceRequest( @@ -58,13 +59,10 @@ void SelectCacheForSharedWorker(long long app_cache_id); - // Set the URLLoaderFactory instance to be used for subresource requests. - virtual void SetSubresourceFactory( - network::mojom::URLLoaderFactoryPtr url_loader_factory) {} - private: enum IsNewMasterEntry { MAYBE_NEW_ENTRY, NEW_ENTRY, OLD_ENTRY }; + mojo::Binding<blink::mojom::AppCacheFrontend> binding_; blink::WebApplicationCacheHostClient* client_; blink::mojom::AppCacheBackend* backend_; blink::mojom::AppCacheHostPtr backend_host_;
diff --git a/content/renderer/media/webrtc/rtc_data_channel_handler.cc b/content/renderer/media/webrtc/rtc_data_channel_handler.cc index 6146726..7970d585 100644 --- a/content/renderer/media/webrtc/rtc_data_channel_handler.cc +++ b/content/renderer/media/webrtc/rtc_data_channel_handler.cc
@@ -192,12 +192,12 @@ return channel()->ordered(); } -unsigned short RtcDataChannelHandler::MaxRetransmitTime() const { +uint16_t RtcDataChannelHandler::MaxRetransmitTime() const { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); return channel()->maxRetransmitTime(); } -unsigned short RtcDataChannelHandler::MaxRetransmits() const { +uint16_t RtcDataChannelHandler::MaxRetransmits() const { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); return channel()->maxRetransmits(); } @@ -212,7 +212,7 @@ return channel()->negotiated(); } -unsigned short RtcDataChannelHandler::Id() const { +uint16_t RtcDataChannelHandler::Id() const { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); return channel()->id(); }
diff --git a/content/renderer/media/webrtc/rtc_data_channel_handler.h b/content/renderer/media/webrtc/rtc_data_channel_handler.h index 949bc486..6d1186a 100644 --- a/content/renderer/media/webrtc/rtc_data_channel_handler.h +++ b/content/renderer/media/webrtc/rtc_data_channel_handler.h
@@ -48,11 +48,11 @@ blink::WebString Label() override; bool IsReliable() override; bool Ordered() const override; - unsigned short MaxRetransmitTime() const override; - unsigned short MaxRetransmits() const override; + uint16_t MaxRetransmitTime() const override; + uint16_t MaxRetransmits() const override; blink::WebString Protocol() const override; bool Negotiated() const override; - unsigned short Id() const override; + uint16_t Id() const override; blink::WebRTCDataChannelHandlerClient::ReadyState GetState() const override; unsigned long BufferedAmount() override; bool SendStringData(const blink::WebString& data) override;
diff --git a/content/renderer/media/webrtc/rtc_stats_unittest.cc b/content/renderer/media/webrtc/rtc_stats_unittest.cc index 1e1d39c..e33ef87 100644 --- a/content/renderer/media/webrtc/rtc_stats_unittest.cc +++ b/content/renderer/media/webrtc/rtc_stats_unittest.cc
@@ -68,7 +68,7 @@ webrtc::RTCStats, "teststats", &standardized, - &non_standardized); + &non_standardized) TestStats::TestStats(const std::string& id, int64_t timestamp_us) : RTCStats(id, timestamp_us),
diff --git a/content/renderer/navigation_client.cc b/content/renderer/navigation_client.cc index c17226b2..56f13dd 100644 --- a/content/renderer/navigation_client.cc +++ b/content/renderer/navigation_client.cc
@@ -62,6 +62,11 @@ SetDisconnectionHandler(); } +void NavigationClient::MarkWasInitiatedInThisFrame() { + DCHECK(!was_initiated_in_this_frame_); + was_initiated_in_this_frame_ = true; +} + void NavigationClient::SetDisconnectionHandler() { navigation_client_binding_.set_connection_error_handler(base::BindOnce( &NavigationClient::OnDroppedNavigation, base::Unretained(this)));
diff --git a/content/renderer/navigation_client.h b/content/renderer/navigation_client.h index 753b655e..96eb654 100644 --- a/content/renderer/navigation_client.h +++ b/content/renderer/navigation_client.h
@@ -42,6 +42,12 @@ void Bind(mojom::NavigationClientAssociatedRequest request); + // See NavigationState::was_initiated_in_this_frame for details. + void MarkWasInitiatedInThisFrame(); + bool was_initiated_in_this_frame() const { + return was_initiated_in_this_frame_; + } + private: // OnDroppedNavigation is bound from BeginNavigation till CommitNavigation. // During this period, it is called when the interface pipe is closed from the @@ -52,6 +58,7 @@ mojo::AssociatedBinding<mojom::NavigationClient> navigation_client_binding_; RenderFrameImpl* render_frame_; + bool was_initiated_in_this_frame_ = false; }; } // namespace content
diff --git a/content/renderer/navigation_state.cc b/content/renderer/navigation_state.cc index 7a1e0092..bdf0236 100644 --- a/content/renderer/navigation_state.cc +++ b/content/renderer/navigation_state.cc
@@ -4,6 +4,7 @@ #include "content/renderer/navigation_state.h" +#include <memory> #include <utility> #include "content/common/frame_messages.h" @@ -26,11 +27,12 @@ mojom::FrameNavigationControl::CommitNavigationCallback callback, mojom::NavigationClient::CommitNavigationCallback per_navigation_mojo_interface_callback, - std::unique_ptr<NavigationClient> navigation_client) { + std::unique_ptr<NavigationClient> navigation_client, + bool was_initiated_in_this_frame) { return base::WrapUnique(new NavigationState( common_params, commit_params, time_commit_requested, false, std::move(callback), std::move(per_navigation_mojo_interface_callback), - std::move(navigation_client))); + std::move(navigation_client), was_initiated_in_this_frame)); } // static @@ -38,7 +40,8 @@ return base::WrapUnique(new NavigationState( CommonNavigationParams(), CommitNavigationParams(), base::TimeTicks(), true, content::mojom::FrameNavigationControl::CommitNavigationCallback(), - content::mojom::NavigationClient::CommitNavigationCallback(), nullptr)); + content::mojom::NavigationClient::CommitNavigationCallback(), nullptr, + true)); } // static @@ -80,9 +83,11 @@ mojom::FrameNavigationControl::CommitNavigationCallback callback, mojom::NavigationClient::CommitNavigationCallback per_navigation_mojo_interface_commit_callback, - std::unique_ptr<NavigationClient> navigation_client) + std::unique_ptr<NavigationClient> navigation_client, + bool was_initiated_in_this_frame) : request_committed_(false), was_within_same_document_(false), + was_initiated_in_this_frame_(was_initiated_in_this_frame), is_content_initiated_(is_content_initiated), common_params_(common_params), commit_params_(commit_params),
diff --git a/content/renderer/navigation_state.h b/content/renderer/navigation_state.h index 418fc316..f8e465d 100644 --- a/content/renderer/navigation_state.h +++ b/content/renderer/navigation_state.h
@@ -36,7 +36,8 @@ mojom::FrameNavigationControl::CommitNavigationCallback callback, mojom::NavigationClient::CommitNavigationCallback per_navigation_mojo_interface_callback, - std::unique_ptr<NavigationClient> navigation_client); + std::unique_ptr<NavigationClient> navigation_client, + bool was_initiated_in_this_frame); static std::unique_ptr<NavigationState> CreateContentInitiated(); @@ -60,6 +61,10 @@ was_within_same_document_ = value; } + bool was_initiated_in_this_frame() const { + return was_initiated_in_this_frame_; + } + void set_transition_type(ui::PageTransition transition) { common_params_.transition = transition; } @@ -93,11 +98,20 @@ content::mojom::FrameNavigationControl::CommitNavigationCallback callback, content::mojom::NavigationClient::CommitNavigationCallback per_navigation_mojo_interface_callback, - std::unique_ptr<NavigationClient> navigation_client); + std::unique_ptr<NavigationClient> navigation_client, + bool was_initiated_in_this_frame); bool request_committed_; bool was_within_same_document_; + // Indicates whether the navigation was initiated by the same RenderFrame + // it is about to commit in. An example would be a link click. + // A counter-example would be user typing in the url bar (browser-initiated + // navigation), or a link click leading to a process swap (different + // RenderFrame instance). + // Used to ensure consistent observer notifications about a navigation. + bool was_initiated_in_this_frame_; + // True if this navigation was not initiated via WebFrame::LoadRequest. const bool is_content_initiated_;
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index d357cd6..cb07c32 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -91,7 +91,6 @@ #include "content/public/renderer/renderer_ppapi_host.h" #include "content/renderer/accessibility/aom_content_ax_tree.h" #include "content/renderer/accessibility/render_accessibility_impl.h" -#include "content/renderer/appcache/appcache_frontend_impl.h" #include "content/renderer/browser_plugin/browser_plugin.h" #include "content/renderer/browser_plugin/browser_plugin_manager.h" #include "content/renderer/compositor/layer_tree_view.h" @@ -816,7 +815,8 @@ per_navigation_mojo_interface_commit_callback, const network::ResourceResponseHead* head, std::unique_ptr<NavigationClient> navigation_client, - int request_id) { + int request_id, + bool was_initiated_in_this_frame) { std::unique_ptr<DocumentState> document_state(new DocumentState()); InternalDocumentStateData* internal_data = InternalDocumentStateData::FromDocumentState(document_state.get()); @@ -877,7 +877,7 @@ common_params, commit_params, time_commit_requested, std::move(commit_callback), std::move(per_navigation_mojo_interface_commit_callback), - std::move(navigation_client))); + std::move(navigation_client), was_initiated_in_this_frame)); return document_state; } @@ -2871,12 +2871,16 @@ if (inherit_document_state) { NavigationState* navigation_state = NavigationState::FromDocumentLoader(document_loader); + // The error page load (not to confuse with a failed load of original page) + // was not initiated through BeginNavigation, therefore + // |was_initiated_in_this_frame| is false. document_state = BuildDocumentStateFromParams( navigation_state->common_params(), navigation_state->commit_params(), base::TimeTicks(), // Not used for failed navigation. mojom::FrameNavigationControl::CommitNavigationCallback(), mojom::NavigationClient::CommitNavigationCallback(), nullptr, nullptr, - ResourceDispatcher::MakeRequestID()); + ResourceDispatcher::MakeRequestID(), + false /* was_initiated_in_this_frame */); FillMiscNavigationParams(navigation_state->common_params(), navigation_state->commit_params(), navigation_params.get()); @@ -3036,6 +3040,12 @@ return document_interface_broker_.get(); } +void RenderFrameImpl::SetDocumentInterfaceBrokerForTesting( + blink::mojom::DocumentInterfaceBrokerPtr test_broker) { + document_interface_broker_.FlushForTesting(); + document_interface_broker_ = std::move(test_broker); +} + blink::AssociatedInterfaceRegistry* RenderFrameImpl::GetAssociatedInterfaceRegistry() { return &associated_interfaces_; @@ -3314,6 +3324,18 @@ return; } + bool was_initiated_in_this_frame = false; + if (IsPerNavigationMojoInterfaceEnabled()) { + was_initiated_in_this_frame = + navigation_client_impl_ && + navigation_client_impl_->was_initiated_in_this_frame(); + } else { + was_initiated_in_this_frame = + browser_side_navigation_pending_ && + browser_side_navigation_pending_url_ == commit_params.original_url && + commit_params.nav_entry_id == 0; + } + // Sanity check that the browser always sends us new loader factories on // cross-document navigations with the Network Service enabled. DCHECK(common_params.url.SchemeIs(url::kJavaScriptScheme) || @@ -3331,7 +3353,8 @@ std::unique_ptr<DocumentState> document_state = BuildDocumentStateFromParams( common_params, commit_params, base::TimeTicks::Now(), std::move(callback), std::move(per_navigation_mojo_interface_callback), response_head, - std::move(navigation_client_impl_), request_id); + std::move(navigation_client_impl_), request_id, + was_initiated_in_this_frame); // Check if the navigation being committed originated as a client redirect. bool is_client_redirect = @@ -3681,10 +3704,14 @@ "UTF-8", error_html); navigation_params->unreachable_url = error.url(); + // The error page load (not to confuse with a failed load of original page) + // was not initiated through BeginNavigation, therefore + // |was_initiated_in_this_frame| is false. std::unique_ptr<DocumentState> document_state = BuildDocumentStateFromParams( common_params, commit_params, base::TimeTicks(), std::move(callback), std::move(per_navigation_mojo_interface_callback), nullptr, - std::move(navigation_client_impl_), ResourceDispatcher::MakeRequestID()); + std::move(navigation_client_impl_), ResourceDispatcher::MakeRequestID(), + false /* was_initiated_in_this_frame */); // The load of the error page can result in this frame being removed. // Use a WeakPtr as an easy way to detect whether this has occured. If so, @@ -3743,11 +3770,14 @@ InternalDocumentStateData::FromDocumentState(document_state.get()); internal_data->CopyFrom( InternalDocumentStateData::FromDocumentState(original_document_state)); + // This is a browser-initiated same-document navigation (as opposed to a + // fragment link click), therefore |was_initiated_in_this_frame| is false. internal_data->set_navigation_state(NavigationState::CreateBrowserInitiated( common_params, commit_params, base::TimeTicks(), // Not used for same-document navigation. mojom::FrameNavigationControl::CommitNavigationCallback(), - mojom::NavigationClient::CommitNavigationCallback(), nullptr)); + mojom::NavigationClient::CommitNavigationCallback(), nullptr, + false /* was_initiated_in_this_frame */)); // Load the request. commit_status = frame_->CommitSameDocumentNavigation( @@ -3913,7 +3943,6 @@ return std::make_unique<RendererWebApplicationCacheHostImpl>( RenderViewImpl::FromWebView(frame_->View()), client, - RenderThreadImpl::current()->appcache_frontend_impl()->backend_proxy(), navigation_state->commit_params().appcache_host_id, routing_id_); } @@ -4440,10 +4469,18 @@ NavigationState* navigation_state = NavigationState::FromDocumentLoader(document_loader); - for (auto& observer : observers_) { - observer.DidStartProvisionalLoad(document_loader, - navigation_state->IsContentInitiated()); + // TODO(dgozman): call DidStartNavigation in various places where we call + // CommitNavigation() on the frame. This will happen naturally once we remove + // WebLocalFrameClient::DidStartProvisionalLoad. + if (!navigation_state->was_initiated_in_this_frame()) { + // Navigation initiated in this frame has been already reported in + // BeginNavigation. + for (auto& observer : observers_) + observer.DidStartNavigation(document_loader->GetUrl(), base::nullopt); } + + for (auto& observer : observers_) + observer.ReadyToCommitNavigation(document_loader); } void RenderFrameImpl::DidCommitProvisionalLoad( @@ -6283,6 +6320,9 @@ sync_navigation_callback_.Cancel(); mhtml_body_loader_client_.reset(); + for (auto& observer : observers_) + observer.DidStartNavigation(url, info->navigation_type); + // When an MHTML Archive is present, it should be used to serve iframe // content instead of doing a network request. bool use_archive = (info->archive_status == @@ -6836,10 +6876,6 @@ if (!CreatePlaceholderDocumentLoader(*info)) return; - WebDocumentLoader* document_loader = frame_->GetProvisionalDocumentLoader(); - NavigationState* navigation_state = - NavigationState::FromDocumentLoader(document_loader); - browser_side_navigation_pending_ = true; browser_side_navigation_pending_url_ = info->url_request.Url(); @@ -6927,8 +6963,10 @@ : base::nullopt); mojom::NavigationClientAssociatedPtrInfo navigation_client_info; - if (IsPerNavigationMojoInterfaceEnabled()) + if (IsPerNavigationMojoInterfaceEnabled()) { BindNavigationClient(mojo::MakeRequest(&navigation_client_info)); + navigation_client_impl_->MarkWasInitiatedInThisFrame(); + } blink::mojom::NavigationInitiatorPtr initiator_ptr( blink::mojom::NavigationInitiatorPtrInfo( @@ -6945,12 +6983,6 @@ load_flags, prevent_sandboxed_download), std::move(begin_navigation_params), std::move(blob_url_token), std::move(navigation_client_info), std::move(initiator_ptr)); - - DCHECK(navigation_state->IsContentInitiated()); - for (auto& observer : observers_) { - observer.DidStartProvisionalLoad(document_loader, - true /* is_content_initiated */); - } } void RenderFrameImpl::DecodeDataURL(const CommonNavigationParams& common_params,
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index 1ae3a32..1239e8b 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -939,6 +939,10 @@ void DidCancelResponse(int request_id); void DidReceiveTransferSizeUpdate(int request_id, int received_data_length); + // Used in tests to override DocumentInterfaceBroker's methods + void SetDocumentInterfaceBrokerForTesting( + blink::mojom::DocumentInterfaceBrokerPtr test_broker); + protected: explicit RenderFrameImpl(CreateParams params);
diff --git a/content/renderer/render_frame_impl_browsertest.cc b/content/renderer/render_frame_impl_browsertest.cc index 84b4e01..eac47c00 100644 --- a/content/renderer/render_frame_impl_browsertest.cc +++ b/content/renderer/render_frame_impl_browsertest.cc
@@ -35,6 +35,7 @@ #include "content/renderer/render_view_impl.h" #include "content/test/fake_compositor_dependencies.h" #include "content/test/frame_host_test_interface.mojom.h" +#include "content/test/test_document_interface_broker.h" #include "content/test/test_render_frame.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "services/service_manager/public/mojom/interface_provider.mojom.h" @@ -67,6 +68,8 @@ const char kAutoplayTestOrigin[] = "https://www.google.com"; +constexpr char kGetNameTestResponse[] = "TestName"; + } // namespace // RenderFrameImplTest creates a RenderFrameImpl that is a child of the @@ -701,6 +704,87 @@ } } +// Used to annotate the source of an interface request. +struct SourceAnnotation { + // The URL of the active document in the frame, at the time the interface was + // requested by the RenderFrame. + GURL document_url; + + // The RenderFrameObserver event in response to which the interface is + // requested by the RenderFrame. + std::string render_frame_event; + + bool operator==(const SourceAnnotation& rhs) const { + return document_url == rhs.document_url && + render_frame_event == rhs.render_frame_event; + } +}; + +// TODO(crbug.com/718652): this is a blink version of the FrameHostTestInterface +// implementation. The non-blink one will be removed when all clients are +// converted to use DocumentInterfaceBroker. +class BlinkFrameHostTestInterfaceImpl + : public blink::mojom::FrameHostTestInterface { + public: + BlinkFrameHostTestInterfaceImpl() : binding_(this) {} + ~BlinkFrameHostTestInterfaceImpl() override {} + + void BindAndFlush(blink::mojom::FrameHostTestInterfaceRequest request) { + binding_.Bind(std::move(request)); + binding_.WaitForIncomingMethodCall(); + } + + const base::Optional<SourceAnnotation>& ping_source() const { + return ping_source_; + } + + protected: + // blink::mojom::FrameHostTestInterface + void Ping(const GURL& url, const std::string& event) override { + ping_source_ = SourceAnnotation{url, event}; + } + void GetName(GetNameCallback callback) override { + std::move(callback).Run(kGetNameTestResponse); + } + + private: + mojo::Binding<blink::mojom::FrameHostTestInterface> binding_; + base::Optional<SourceAnnotation> ping_source_; + + DISALLOW_COPY_AND_ASSIGN(BlinkFrameHostTestInterfaceImpl); +}; + +class FrameHostTestDocumentInterfaceBroker + : public TestDocumentInterfaceBroker { + public: + FrameHostTestDocumentInterfaceBroker( + blink::mojom::DocumentInterfaceBroker* document_interface_broker, + blink::mojom::DocumentInterfaceBrokerRequest request) + : TestDocumentInterfaceBroker(document_interface_broker, + std::move(request)) {} + + void GetFrameHostTestInterface( + blink::mojom::FrameHostTestInterfaceRequest request) override { + BlinkFrameHostTestInterfaceImpl impl; + impl.BindAndFlush(std::move(request)); + } +}; + +TEST_F(RenderFrameImplTest, TestDocumentInterfaceBrokerOverride) { + blink::mojom::DocumentInterfaceBrokerPtr doc; + FrameHostTestDocumentInterfaceBroker frame_interface_broker( + frame()->GetDocumentInterfaceBroker(), mojo::MakeRequest(&doc)); + frame()->SetDocumentInterfaceBrokerForTesting(std::move(doc)); + + blink::mojom::FrameHostTestInterfacePtr frame_test; + frame()->GetDocumentInterfaceBroker()->GetFrameHostTestInterface( + mojo::MakeRequest(&frame_test)); + frame_test->GetName(base::BindOnce([](const std::string& result) { + EXPECT_EQ(result, kGetNameTestResponse); + })); + frame_interface_broker.Flush(); +} + // RenderFrameRemoteInterfacesTest ------------------------------------ namespace { @@ -788,26 +872,6 @@ DISALLOW_COPY_AND_ASSIGN(TestSimpleDocumentInterfaceBrokerImpl); }; -// Used to annotate the source of an interface request. -struct SourceAnnotation { - // The URL of the active document in the frame, at the time the interface was - // requested by the RenderFrame. - GURL document_url; - - // The RenderFrameObserver event in response to which the interface is - // requested by the RenderFrame. - std::string render_frame_event; - - bool operator==(const SourceAnnotation& rhs) const { - return document_url == rhs.document_url && - render_frame_event == rhs.render_frame_event; - } -}; - -std::ostream& operator<<(std::ostream& os, const SourceAnnotation& a) { - return os << "[" << a.document_url << ", " << a.render_frame_event << "]"; -} - class FrameHostTestInterfaceImpl : public mojom::FrameHostTestInterface { public: FrameHostTestInterfaceImpl() : binding_(this) {} @@ -834,38 +898,6 @@ DISALLOW_COPY_AND_ASSIGN(FrameHostTestInterfaceImpl); }; -// TODO(crbug.com/718652): this is a blink version of the FrameHostTestInterface -// implementation. The non-blink one will be removed when all clients are -// converted to use DocumentInterfaceBroker. -class BlinkFrameHostTestInterfaceImpl - : public blink::mojom::FrameHostTestInterface { - public: - BlinkFrameHostTestInterfaceImpl() : binding_(this) {} - ~BlinkFrameHostTestInterfaceImpl() override {} - - void BindAndFlush(blink::mojom::FrameHostTestInterfaceRequest request) { - binding_.Bind(std::move(request)); - binding_.WaitForIncomingMethodCall(); - } - - const base::Optional<SourceAnnotation>& ping_source() const { - return ping_source_; - } - - protected: - // blink::mojom::FrameHostTestInterface - void Ping(const GURL& url, const std::string& event) override { - ping_source_ = SourceAnnotation{url, event}; - } - void GetName(GetNameCallback callback) override {} - - private: - mojo::Binding<blink::mojom::FrameHostTestInterface> binding_; - base::Optional<SourceAnnotation> ping_source_; - - DISALLOW_COPY_AND_ASSIGN(BlinkFrameHostTestInterfaceImpl); -}; - // RenderFrameObserver that issues FrameHostTestInterface interface requests // through the RenderFrame's |remote_interfaces_| in response to observing // important milestones in a frame's lifecycle. @@ -911,11 +943,6 @@ RequestTestInterfaceOnFrameEvent(kFrameEventWillCommitProvisionalLoad); } - void DidStartProvisionalLoad(blink::WebDocumentLoader* document_loader, - bool is_content_initiated) override {} - - void DidFailProvisionalLoad(const blink::WebURLError& error) override {} - void DidCommitProvisionalLoad(bool is_same_document_navigation, ui::PageTransition transition) override { RequestTestInterfaceOnFrameEvent(is_same_document_navigation
diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc index 6af4f7b..ff57196 100644 --- a/content/renderer/render_thread_impl.cc +++ b/content/renderer/render_thread_impl.cc
@@ -80,7 +80,6 @@ #include "content/public/renderer/content_renderer_client.h" #include "content/public/renderer/render_thread_observer.h" #include "content/public/renderer/render_view_visitor.h" -#include "content/renderer/appcache/appcache_frontend_impl.h" #include "content/renderer/browser_plugin/browser_plugin_manager.h" #include "content/renderer/categorized_worker_pool.h" #include "content/renderer/dom_storage/dom_storage_dispatcher.h" @@ -760,11 +759,6 @@ widget_count_ = 0; hidden_widget_count_ = 0; - appcache_frontend_impl_ = std::make_unique<AppCacheFrontendImpl>(); - registry->AddInterface( - base::BindRepeating(&AppCacheFrontendImpl::Bind, - base::Unretained(appcache_frontend_impl())), - GetWebMainThreadScheduler()->IPCTaskRunner()); dom_storage_dispatcher_.reset(new DomStorageDispatcher()); vc_manager_.reset(new VideoCaptureImplManager());
diff --git a/content/renderer/render_thread_impl.h b/content/renderer/render_thread_impl.h index 6798247..b3f3ffbc 100644 --- a/content/renderer/render_thread_impl.h +++ b/content/renderer/render_thread_impl.h
@@ -118,7 +118,6 @@ namespace content { -class AppCacheFrontendImpl; class AecDumpMessageFilter; class AudioRendererMixerManager; class BrowserPluginManager; @@ -317,10 +316,6 @@ return compositor_task_runner_; } - AppCacheFrontendImpl* appcache_frontend_impl() const { - return appcache_frontend_impl_.get(); - } - DomStorageDispatcher* dom_storage_dispatcher() const { return dom_storage_dispatcher_.get(); } @@ -593,7 +588,6 @@ discardable_shared_memory_manager_; // These objects live solely on the render thread. - std::unique_ptr<AppCacheFrontendImpl> appcache_frontend_impl_; std::unique_ptr<DomStorageDispatcher> dom_storage_dispatcher_; std::unique_ptr<blink::scheduler::WebThreadScheduler> main_thread_scheduler_; std::unique_ptr<RendererBlinkPlatformImpl> blink_platform_impl_;
diff --git a/content/renderer/renderer_webapplicationcachehost_impl.cc b/content/renderer/renderer_webapplicationcachehost_impl.cc index 4f16f6eac..f29302e6 100644 --- a/content/renderer/renderer_webapplicationcachehost_impl.cc +++ b/content/renderer/renderer_webapplicationcachehost_impl.cc
@@ -23,17 +23,15 @@ RendererWebApplicationCacheHostImpl::RendererWebApplicationCacheHostImpl( RenderViewImpl* render_view, WebApplicationCacheHostClient* client, - blink::mojom::AppCacheBackend* backend, int appcache_host_id, int frame_routing_id) : WebApplicationCacheHostImpl(client, - backend, appcache_host_id, frame_routing_id), routing_id_(render_view->GetRoutingID()), frame_routing_id_(frame_routing_id) {} -void RendererWebApplicationCacheHostImpl::OnLogMessage( +void RendererWebApplicationCacheHostImpl::LogMessage( blink::mojom::ConsoleMessageLevel log_level, const std::string& message) { if (RenderThreadImpl::current()->web_test_mode())
diff --git a/content/renderer/renderer_webapplicationcachehost_impl.h b/content/renderer/renderer_webapplicationcachehost_impl.h index 62516ab..8226df44 100644 --- a/content/renderer/renderer_webapplicationcachehost_impl.h +++ b/content/renderer/renderer_webapplicationcachehost_impl.h
@@ -19,13 +19,12 @@ RendererWebApplicationCacheHostImpl( RenderViewImpl* render_view, blink::WebApplicationCacheHostClient* client, - blink::mojom::AppCacheBackend* backend, int appcache_host_id, int frame_routing_id); - // WebApplicationCacheHostImpl: - void OnLogMessage(blink::mojom::ConsoleMessageLevel log_level, - const std::string& message) override; + // blink::mojom::AppCacheHostFrontend: + void LogMessage(blink::mojom::ConsoleMessageLevel log_level, + const std::string& message) override; void SetSubresourceFactory( network::mojom::URLLoaderFactoryPtr url_loader_factory) override;
diff --git a/content/renderer/service_worker/service_worker_context_client.cc b/content/renderer/service_worker/service_worker_context_client.cc index 46dc112..f0a7f5e 100644 --- a/content/renderer/service_worker/service_worker_context_client.cc +++ b/content/renderer/service_worker/service_worker_context_client.cc
@@ -13,7 +13,6 @@ #include "base/bind_helpers.h" #include "base/debug/alias.h" #include "base/feature_list.h" -#include "base/location.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/single_thread_task_runner.h" @@ -175,7 +174,6 @@ bool RunEventCallback(MapType* map, ServiceWorkerTimeoutTimer* timer, int event_id, - const base::Location& from_here, Args... args) { auto iter = map->find(event_id); // The event may have been aborted. @@ -183,7 +181,7 @@ return false; std::move(iter->second).Run(args...); map->erase(iter); - timer->EndEvent(event_id, from_here); + timer->EndEvent(event_id); return true; } @@ -581,8 +579,7 @@ TRACE_EVENT_FLAG_FLOW_IN, "status", ServiceWorkerUtils::MojoEnumToString(status)); RunEventCallback(&context_->activate_event_callbacks, - context_->timeout_timer.get(), request_id, FROM_HERE, - status); + context_->timeout_timer.get(), request_id, status); } void ServiceWorkerContextClient::DidHandleBackgroundFetchAbortEvent( @@ -597,8 +594,7 @@ TRACE_EVENT_FLAG_FLOW_IN, "status", ServiceWorkerUtils::MojoEnumToString(status)); RunEventCallback(&context_->background_fetch_abort_event_callbacks, - context_->timeout_timer.get(), request_id, FROM_HERE, - status); + context_->timeout_timer.get(), request_id, status); } void ServiceWorkerContextClient::DidHandleBackgroundFetchClickEvent( @@ -613,8 +609,7 @@ TRACE_EVENT_FLAG_FLOW_IN, "status", ServiceWorkerUtils::MojoEnumToString(status)); RunEventCallback(&context_->background_fetch_click_event_callbacks, - context_->timeout_timer.get(), request_id, FROM_HERE, - status); + context_->timeout_timer.get(), request_id, status); } void ServiceWorkerContextClient::DidHandleBackgroundFetchFailEvent( @@ -629,8 +624,7 @@ TRACE_EVENT_FLAG_FLOW_IN, "status", ServiceWorkerUtils::MojoEnumToString(status)); RunEventCallback(&context_->background_fetch_fail_event_callbacks, - context_->timeout_timer.get(), request_id, FROM_HERE, - status); + context_->timeout_timer.get(), request_id, status); } void ServiceWorkerContextClient::DidHandleBackgroundFetchSuccessEvent( @@ -645,8 +639,7 @@ TRACE_EVENT_FLAG_FLOW_IN, "status", ServiceWorkerUtils::MojoEnumToString(status)); RunEventCallback(&context_->background_fetched_event_callbacks, - context_->timeout_timer.get(), request_id, FROM_HERE, - status); + context_->timeout_timer.get(), request_id, status); } void ServiceWorkerContextClient::DidHandleCookieChangeEvent( @@ -660,8 +653,7 @@ TRACE_EVENT_FLAG_FLOW_IN, "status", ServiceWorkerUtils::MojoEnumToString(status)); RunEventCallback(&context_->cookie_change_event_callbacks, - context_->timeout_timer.get(), request_id, FROM_HERE, - status); + context_->timeout_timer.get(), request_id, status); } void ServiceWorkerContextClient::DidHandleExtendableMessageEvent( @@ -676,8 +668,7 @@ TRACE_EVENT_FLAG_FLOW_IN, "status", ServiceWorkerUtils::MojoEnumToString(status)); RunEventCallback(&context_->message_event_callbacks, - context_->timeout_timer.get(), request_id, FROM_HERE, - status); + context_->timeout_timer.get(), request_id, status); } void ServiceWorkerContextClient::DidHandleInstallEvent( @@ -691,7 +682,7 @@ TRACE_EVENT_FLAG_FLOW_IN, "status", ServiceWorkerUtils::MojoEnumToString(status)); RunEventCallback(&context_->install_event_callbacks, - context_->timeout_timer.get(), event_id, FROM_HERE, status, + context_->timeout_timer.get(), event_id, status, proxy_->HasFetchEventHandler()); } @@ -795,8 +786,7 @@ TRACE_EVENT_FLAG_FLOW_IN, "status", ServiceWorkerUtils::MojoEnumToString(status)); if (!RunEventCallback(&context_->fetch_event_callbacks, - context_->timeout_timer.get(), event_id, FROM_HERE, - status)) { + context_->timeout_timer.get(), event_id, status)) { // The event may have been aborted. Its response callback also needs to be // deleted. context_->fetch_response_callbacks.erase(event_id); @@ -819,8 +809,7 @@ TRACE_EVENT_FLAG_FLOW_IN, "status", ServiceWorkerUtils::MojoEnumToString(status)); RunEventCallback(&context_->notification_click_event_callbacks, - context_->timeout_timer.get(), request_id, FROM_HERE, - status); + context_->timeout_timer.get(), request_id, status); } void ServiceWorkerContextClient::DidHandleNotificationCloseEvent( @@ -835,8 +824,7 @@ TRACE_EVENT_FLAG_FLOW_IN, "status", ServiceWorkerUtils::MojoEnumToString(status)); RunEventCallback(&context_->notification_close_event_callbacks, - context_->timeout_timer.get(), request_id, FROM_HERE, - status); + context_->timeout_timer.get(), request_id, status); } void ServiceWorkerContextClient::DidHandlePushEvent( @@ -850,8 +838,7 @@ TRACE_EVENT_FLAG_FLOW_IN, "status", ServiceWorkerUtils::MojoEnumToString(status)); RunEventCallback(&context_->push_event_callbacks, - context_->timeout_timer.get(), request_id, FROM_HERE, - status); + context_->timeout_timer.get(), request_id, status); } void ServiceWorkerContextClient::DidHandleSyncEvent( @@ -865,8 +852,7 @@ TRACE_EVENT_FLAG_FLOW_IN, "status", ServiceWorkerUtils::MojoEnumToString(status)); RunEventCallback(&context_->sync_event_callbacks, - context_->timeout_timer.get(), request_id, FROM_HERE, - status); + context_->timeout_timer.get(), request_id, status); } void ServiceWorkerContextClient::RespondToAbortPaymentEvent( @@ -896,8 +882,7 @@ TRACE_EVENT_FLAG_FLOW_IN, "status", ServiceWorkerUtils::MojoEnumToString(status)); if (RunEventCallback(&context_->abort_payment_event_callbacks, - context_->timeout_timer.get(), event_id, FROM_HERE, - status)) { + context_->timeout_timer.get(), event_id, status)) { context_->abort_payment_result_callbacks.erase(event_id); } } @@ -932,8 +917,7 @@ TRACE_EVENT_FLAG_FLOW_IN, "status", ServiceWorkerUtils::MojoEnumToString(status)); if (RunEventCallback(&context_->can_make_payment_event_callbacks, - context_->timeout_timer.get(), event_id, FROM_HERE, - status)) { + context_->timeout_timer.get(), event_id, status)) { context_->can_make_payment_result_callbacks.erase(event_id); } } @@ -973,7 +957,7 @@ ServiceWorkerUtils::MojoEnumToString(status)); if (RunEventCallback(&context_->payment_request_event_callbacks, context_->timeout_timer.get(), payment_request_id, - FROM_HERE, status)) { + status)) { context_->payment_response_callbacks.erase(payment_request_id); } } @@ -1037,7 +1021,12 @@ CHECK(worker_task_runner_->RunsTasksInCurrentSequence()); CHECK(context_); CHECK(context_->timeout_timer); - context_->timeout_timer->EndEvent(task_id, FROM_HERE); + // Check if the task is still alive, since the timeout timer might have + // already timed it out (which calls the abort callback passed to StartEvent() + // but that does nothing, since we just check HasEvent() here instead of + // maintaining our own set of started events). + if (context_->timeout_timer->HasEvent(task_id)) + context_->timeout_timer->EndEvent(task_id); } void ServiceWorkerContextClient::DispatchOrQueueFetchEvent( @@ -1651,7 +1640,7 @@ // Dispatch a dummy event to run all of queued tasks. This updates the // idle timer too. const int event_id = context_->timeout_timer->StartEvent(base::DoNothing()); - context_->timeout_timer->EndEvent(event_id, FROM_HERE); + context_->timeout_timer->EndEvent(event_id); } bool ServiceWorkerContextClient::RequestedTermination() const { @@ -1678,6 +1667,13 @@ context_->timeout_timer = std::move(timeout_timer); } +ServiceWorkerTimeoutTimer* +ServiceWorkerContextClient::GetTimeoutTimerForTesting() { + CHECK(worker_task_runner_->RunsTasksInCurrentSequence()); + CHECK(context_); + return context_->timeout_timer.get(); +} + void ServiceWorkerContextClient::RecordDebugLog(const char* message) { const size_t kMaxDebugLogSize = 512; base::AutoLock lock(debug_log_lock_);
diff --git a/content/renderer/service_worker/service_worker_context_client.h b/content/renderer/service_worker/service_worker_context_client.h index 61ba66c..426d03ed 100644 --- a/content/renderer/service_worker/service_worker_context_client.h +++ b/content/renderer/service_worker/service_worker_context_client.h
@@ -365,6 +365,7 @@ void SetTimeoutTimerForTesting( std::unique_ptr<ServiceWorkerTimeoutTimer> timeout_timer); + ServiceWorkerTimeoutTimer* GetTimeoutTimerForTesting(); // TODO(crbug.com/907311): Remove after we identified the cause of crash. void RecordDebugLog(const char* message);
diff --git a/content/renderer/service_worker/service_worker_context_client_unittest.cc b/content/renderer/service_worker/service_worker_context_client_unittest.cc index e99cbdc2..43a1e73 100644 --- a/content/renderer/service_worker/service_worker_context_client_unittest.cc +++ b/content/renderer/service_worker/service_worker_context_client_unittest.cc
@@ -372,6 +372,11 @@ return context_client; } + ServiceWorkerTimeoutTimer* GetTimeoutTimer( + ServiceWorkerContextClient* context_client) { + return context_client->GetTimeoutTimerForTesting(); + } + scoped_refptr<base::TestMockTimeTaskRunner> task_runner() const { return task_runner_; } @@ -615,4 +620,26 @@ EXPECT_TRUE(context_client->RequestedTermination()); } +// Tests timing out a task created by WillStartTask(). +TEST_F(ServiceWorkerContextClientTest, AbortedTaskInServiceWorker) { + EnableServicification(); + ContextClientPipes pipes; + MockWebServiceWorkerContextProxy mock_proxy; + ServiceWorkerContextClient* context_client = + CreateIdleContextClient(&pipes, &mock_proxy); + + // Make a task that times out. + int task_id = context_client->WillStartTask(); + task_runner()->FastForwardBy(ServiceWorkerTimeoutTimer::kEventTimeout + + ServiceWorkerTimeoutTimer::kUpdateInterval + + base::TimeDelta::FromSeconds(1)); + + // The event should have been aborted. + ServiceWorkerTimeoutTimer* timeout_timer = GetTimeoutTimer(context_client); + EXPECT_FALSE(timeout_timer->HasEvent(task_id)); + + // Calling DidEndTask() shouldn't crash. + context_client->DidEndTask(task_id); +} + } // namespace content
diff --git a/content/renderer/service_worker/service_worker_timeout_timer.cc b/content/renderer/service_worker/service_worker_timeout_timer.cc index c539444..33a8833 100644 --- a/content/renderer/service_worker/service_worker_timeout_timer.cc +++ b/content/renderer/service_worker/service_worker_timeout_timer.cc
@@ -6,7 +6,6 @@ #include "base/atomic_sequence_num.h" #include "base/bind.h" -#include "base/debug/alias.h" #include "base/stl_util.h" #include "base/time/default_tick_clock.h" #include "base/time/time.h" @@ -117,24 +116,10 @@ return event_id; } -// TODO(falken): Debugging for https://crbug.com/933273. -void ServiceWorkerTimeoutTimer::CrashBecauseNoEvent( - int event_id, - const base::Location& from_here) { - DEBUG_ALIAS_FOR_CSTR(from_here_copy, from_here.ToString().c_str(), 256); - bool in_dtor = in_dtor_; - base::debug::Alias(&in_dtor); - CHECK(false); -} +void ServiceWorkerTimeoutTimer::EndEvent(int event_id) { + CHECK(HasEvent(event_id)); -void ServiceWorkerTimeoutTimer::EndEvent(int event_id, - const base::Location& from_here) { auto iter = id_event_map_.find(event_id); - if (iter == id_event_map_.end()) { - CrashBecauseNoEvent(event_id, from_here); - return; - } - CHECK(iter != id_event_map_.end()); inflight_events_.erase(iter->second); id_event_map_.erase(iter); @@ -142,6 +127,10 @@ OnNoInflightEvent(); } +bool ServiceWorkerTimeoutTimer::HasEvent(int event_id) const { + return id_event_map_.find(event_id) != id_event_map_.end(); +} + std::unique_ptr<ServiceWorkerTimeoutTimer::StayAwakeToken> ServiceWorkerTimeoutTimer::CreateStayAwakeToken() { if (!blink::ServiceWorkerUtils::IsServicificationEnabled())
diff --git a/content/renderer/service_worker/service_worker_timeout_timer.h b/content/renderer/service_worker/service_worker_timeout_timer.h index f828109d3..86e1072e 100644 --- a/content/renderer/service_worker/service_worker_timeout_timer.h +++ b/content/renderer/service_worker/service_worker_timeout_timer.h
@@ -10,7 +10,6 @@ #include "base/callback.h" #include "base/containers/queue.h" -#include "base/location.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "base/timer/timer.h" @@ -78,8 +77,11 @@ int StartEventWithCustomTimeout( base::OnceCallback<void(int /* event_id */)> abort_callback, base::TimeDelta timeout); - void CrashBecauseNoEvent(int event_id, const base::Location& from_here); - void EndEvent(int event_id, const base::Location& from_here); + + void EndEvent(int event_id); + + // Returns true if |event_id| was started and hasn't ended. + bool HasEvent(int event_id) const; // Creates a StayAwakeToken to ensure that the idle timer won't be triggered // while any of these are alive.
diff --git a/content/renderer/service_worker/service_worker_timeout_timer_unittest.cc b/content/renderer/service_worker/service_worker_timeout_timer_unittest.cc index 883381e..86c69341 100644 --- a/content/renderer/service_worker/service_worker_timeout_timer_unittest.cc +++ b/content/renderer/service_worker/service_worker_timeout_timer_unittest.cc
@@ -66,7 +66,7 @@ out_tags->emplace_back(std::move(tag)); - timer->EndEvent(event_id, FROM_HERE); + timer->EndEvent(event_id); EXPECT_FALSE(event.has_aborted()); }, timer, std::move(tag), out_tags); @@ -131,12 +131,12 @@ // Nothing happens since there are two inflight events. EXPECT_FALSE(is_idle); - timer.EndEvent(event_id_2, FROM_HERE); + timer.EndEvent(event_id_2); task_runner()->FastForwardBy(kIdleInterval); // Nothing happens since there is an inflight event. EXPECT_FALSE(is_idle); - timer.EndEvent(event_id_1, FROM_HERE); + timer.EndEvent(event_id_1); task_runner()->FastForwardBy(kIdleInterval); // |idle_callback| should be fired. EXPECT_TRUE(is_idle); @@ -148,7 +148,7 @@ EXPECT_FALSE(is_idle); std::unique_ptr<StayAwakeToken> token = timer.CreateStayAwakeToken(); - timer.EndEvent(event_id_3, FROM_HERE); + timer.EndEvent(event_id_3); task_runner()->FastForwardBy(kIdleInterval); // Nothing happens since there is a living StayAwakeToken. EXPECT_FALSE(is_idle); @@ -196,7 +196,7 @@ EXPECT_FALSE(event1.has_aborted()); EXPECT_FALSE(event2.has_aborted()); - timer.EndEvent(event1.event_id(), FROM_HERE); + timer.EndEvent(event1.event_id()); task_runner()->FastForwardBy(ServiceWorkerTimeoutTimer::kEventTimeout + base::TimeDelta::FromSeconds(1)); @@ -348,7 +348,7 @@ // Nothing happens since there is an inflight event. EXPECT_FALSE(is_idle); - timer.EndEvent(event_id, FROM_HERE); + timer.EndEvent(event_id); // EndEvent() immediately triggers the idle callback. EXPECT_TRUE(is_idle); } @@ -364,11 +364,11 @@ // Nothing happens since there are two inflight events. EXPECT_FALSE(is_idle); - timer.EndEvent(event_id_1, FROM_HERE); + timer.EndEvent(event_id_1); // Nothing happens since there is an inflight event. EXPECT_FALSE(is_idle); - timer.EndEvent(event_id_2, FROM_HERE); + timer.EndEvent(event_id_2); // EndEvent() immediately triggers the idle callback when no inflight events // exist. EXPECT_TRUE(is_idle);
diff --git a/content/renderer/worker/embedded_shared_worker_stub.cc b/content/renderer/worker/embedded_shared_worker_stub.cc index 8a48336b..dd4159d 100644 --- a/content/renderer/worker/embedded_shared_worker_stub.cc +++ b/content/renderer/worker/embedded_shared_worker_stub.cc
@@ -15,7 +15,6 @@ #include "content/public/common/content_switches.h" #include "content/public/common/network_service_util.h" #include "content/public/common/origin_util.h" -#include "content/renderer/appcache/appcache_frontend_impl.h" #include "content/renderer/appcache/web_application_cache_host_impl.h" #include "content/renderer/loader/child_url_loader_factory_bundle.h" #include "content/renderer/loader/navigation_response_override_parameters.h" @@ -57,9 +56,6 @@ blink::WebApplicationCacheHostClient* client, int appcache_host_id) : WebApplicationCacheHostImpl(client, - RenderThreadImpl::current() - ->appcache_frontend_impl() - ->backend_proxy(), appcache_host_id, MSG_ROUTING_NONE) {} @@ -80,6 +76,12 @@ bool SelectCacheWithManifest(const blink::WebURL& manifestURL) override { return true; } + + // blink::mojom::AppCacheFrontend: + void LogMessage(blink::mojom::ConsoleMessageLevel log_level, + const std::string& message) override {} + void SetSubresourceFactory( + network::mojom::URLLoaderFactoryPtr url_loader_factory) override {} }; } // namespace
diff --git a/content/shell/DEPS b/content/shell/DEPS index 11a76bfc..6cf0717 100644 --- a/content/shell/DEPS +++ b/content/shell/DEPS
@@ -9,7 +9,6 @@ # The content_shell is the canonical sample embedder, so it only uses # content's public API. - "+content/app/strings/grit", # For generated headers "+content/public", "+services/network/ignore_errors_cert_verifier.h",
diff --git a/content/shell/test_runner/web_frame_test_proxy.cc b/content/shell/test_runner/web_frame_test_proxy.cc index e46390c..948be5df 100644 --- a/content/shell/test_runner/web_frame_test_proxy.cc +++ b/content/shell/test_runner/web_frame_test_proxy.cc
@@ -43,17 +43,27 @@ // content::RenderFrameObserver overrides. void OnDestruct() override { delete this; } - void DidStartProvisionalLoad(blink::WebDocumentLoader* document_loader, - bool is_content_initiated) override { + void DidStartNavigation( + const GURL& url, + base::Optional<blink::WebNavigationType> navigation_type) override { if (test_runner()->shouldDumpFrameLoadCallbacks()) { WebFrameTestClient::PrintFrameDescription(delegate(), render_frame()->GetWebFrame()); - delegate()->PrintMessage(" - didStartProvisionalLoadForFrame\n"); + delegate()->PrintMessage(" - DidStartNavigation\n"); } if (test_runner()->shouldDumpUserGestureInFrameLoadCallbacks()) { PrintFrameUserGestureStatus(delegate(), render_frame()->GetWebFrame(), - " - in didStartProvisionalLoadForFrame\n"); + " - in DidStartNavigation\n"); + } + } + + void ReadyToCommitNavigation( + blink::WebDocumentLoader* document_loader) override { + if (test_runner()->shouldDumpFrameLoadCallbacks()) { + WebFrameTestClient::PrintFrameDescription(delegate(), + render_frame()->GetWebFrame()); + delegate()->PrintMessage(" - ReadyToCommitNavigation\n"); } }
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index e69f581..c70425c 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -34,6 +34,8 @@ "../browser/accessibility/accessibility_event_recorder.cc", "../browser/accessibility/accessibility_event_recorder.h", "../browser/accessibility/accessibility_event_recorder_mac.mm", + "../browser/accessibility/accessibility_event_recorder_uia_win.cc", + "../browser/accessibility/accessibility_event_recorder_uia_win.h", "../browser/accessibility/accessibility_event_recorder_win.cc", "../browser/background_fetch/background_fetch_embedded_worker_test_helper.cc", "../browser/background_fetch/background_fetch_embedded_worker_test_helper.h", @@ -131,6 +133,8 @@ "../public/test/scoped_overscroll_modes.h", "../public/test/service_worker_test_helpers.cc", "../public/test/service_worker_test_helpers.h", + "../public/test/signed_exchange_browser_test_helper.cc", + "../public/test/signed_exchange_browser_test_helper.h", "../public/test/simple_url_loader_test_helper.cc", "../public/test/simple_url_loader_test_helper.h", "../public/test/slow_download_http_response.cc", @@ -216,8 +220,6 @@ "content_browser_sanity_checker.h", "content_test_suite.cc", "content_test_suite.h", - "did_commit_provisional_load_interceptor.cc", - "did_commit_provisional_load_interceptor.h", "dwrite_font_fake_sender_win.cc", "dwrite_font_fake_sender_win.h", "fake_compositor_dependencies.cc", @@ -228,6 +230,8 @@ "fake_plugin_service.h", "fake_renderer_compositor_frame_sink.cc", "fake_renderer_compositor_frame_sink.h", + "frame_host_interceptor.cc", + "frame_host_interceptor.h", "gmock_util.h", "gpu_browsertest_helpers.cc", "gpu_browsertest_helpers.h", @@ -277,6 +281,8 @@ "test_content_browser_client.h", "test_content_client.cc", "test_content_client.h", + "test_document_interface_broker.cc", + "test_document_interface_broker.h", "test_mojo_proxy_resolver_factory.cc", "test_mojo_proxy_resolver_factory.h", "test_navigation_url_loader.cc", @@ -565,6 +571,7 @@ "//gin", "//media", "//net", + "//net:test_support", "//skia", "//testing/gtest", "//ui/accessibility:ax_enums_mojo", @@ -1676,7 +1683,6 @@ "../browser/web_contents/web_drag_dest_mac_unittest.mm", "../browser/web_contents/web_drag_source_mac_unittest.mm", "../browser/web_package/http_structured_header_unittest.cc", - "../browser/web_package/origins_list_unittest.cc", "../browser/web_package/signed_exchange_cert_fetcher_unittest.cc", "../browser/web_package/signed_exchange_certificate_chain_unittest.cc", "../browser/web_package/signed_exchange_envelope_unittest.cc",
diff --git a/content/test/data/accessibility/aria/aria-activedescendant-expected-mac.txt b/content/test/data/accessibility/aria/aria-activedescendant-expected-mac.txt index 7f1ebc5..9d3b8b0 100644 --- a/content/test/data/accessibility/aria/aria-activedescendant-expected-mac.txt +++ b/content/test/data/accessibility/aria/aria-activedescendant-expected-mac.txt
@@ -1,5 +1,5 @@ AXWebArea AXFocused='0' -++AXMenu AXDescription='parent node' AXFocusableAncestor='AXMenu parent node' AXFocused='0' -++++AXMenuItem AXTitle='Inactive descendant' AXFocusableAncestor='AXMenuItem Inactive descendant' AXFocused='0' -++++AXMenuItem AXTitle='Active descendant' AXValue='0' AXFocusableAncestor='AXMenuItem Active descendant' AXFocused='1' -++++AXMenuItem AXTitle='Inactive descendant #2' AXValue='0' AXFocusableAncestor='AXMenuItem Inactive descendant #2' AXFocused='0' +++AXMenu AXDescription='parent node' AXFocused='0' +++++AXMenuItem AXTitle='Inactive descendant' AXFocused='0' +++++AXMenuItem AXTitle='Active descendant' AXValue='0' AXFocused='1' +++++AXMenuItem AXTitle='Inactive descendant #2' AXValue='0' AXFocused='0' \ No newline at end of file
diff --git a/content/test/data/accessibility/aria/aria-combobox.html b/content/test/data/accessibility/aria/aria-combobox.html index 887d128..21a66ad2 100644 --- a/content/test/data/accessibility/aria/aria-combobox.html +++ b/content/test/data/accessibility/aria/aria-combobox.html
@@ -2,6 +2,7 @@ <!-- @MAC-ALLOW:AXFocused='1' @MAC-ALLOW:AXLinkedUIElements* +@MAC-DENY:AXLinkedUIElements=[] @MAC-ALLOW:AXTitleUIElement* @WIN-DENY:description* @WIN-ALLOW:FOCUS*
diff --git a/content/test/data/accessibility/aria/aria-controls.html b/content/test/data/accessibility/aria/aria-controls.html index fb3ac33..d8bf3b47 100644 --- a/content/test/data/accessibility/aria/aria-controls.html +++ b/content/test/data/accessibility/aria/aria-controls.html
@@ -2,6 +2,7 @@ @MAC-ALLOW:AXDescription='File' @MAC-DENY:AXValue* @MAC-ALLOW:AXLinkedUIElements* +@MAC-DENY:AXLinkedUIElements=[] --> <!DOCTYPE html> <html>
diff --git a/content/test/data/accessibility/aria/aria-editable-expected-mac.txt b/content/test/data/accessibility/aria/aria-editable-expected-mac.txt index 48863fd..ee456c1 100644 --- a/content/test/data/accessibility/aria/aria-editable-expected-mac.txt +++ b/content/test/data/accessibility/aria/aria-editable-expected-mac.txt
@@ -2,7 +2,7 @@ ++AXTextArea AXValue='Editable text/Non-editable text' AXEditableAncestor='AXTextArea Editable text/Non-editable text' AXHighestEditableAncestor='AXTextArea Editable text/Non-editable text' ++++AXGroup AXEditableAncestor='AXTextArea Editable text/Non-editable text' AXHighestEditableAncestor='AXTextArea Editable text/Non-editable text' ++++++AXStaticText AXValue='Editable text/' AXEditableAncestor='AXTextArea Editable text/Non-editable text' AXHighestEditableAncestor='AXTextArea Editable text/Non-editable text' -++++AXGroup AXEditableAncestor='AXTextArea Editable text/Non-editable text' AXHighestEditableAncestor='AXTextArea Editable text/Non-editable text' -++++++AXStaticText AXValue='Non-editable text' AXEditableAncestor='AXTextArea Editable text/Non-editable text' AXHighestEditableAncestor='AXTextArea Editable text/Non-editable text' +++++AXGroup +++++++AXStaticText AXValue='Non-editable text' ++AXGroup -++++AXStaticText AXValue='Fake-editable' +++++AXStaticText AXValue='Fake-editable' \ No newline at end of file
diff --git a/content/test/data/accessibility/aria/aria-flowto.html b/content/test/data/accessibility/aria/aria-flowto.html index 53ab196..4d9480a 100644 --- a/content/test/data/accessibility/aria/aria-flowto.html +++ b/content/test/data/accessibility/aria/aria-flowto.html
@@ -1,5 +1,6 @@ <!-- @MAC-ALLOW:AXLinkedUIElements* +@MAC-DENY:AXLinkedUIElements=[] @MAC-ALLOW:AXRoleDescription* --> <html>
diff --git a/content/test/data/accessibility/aria/aria-invalid-expected-mac.txt b/content/test/data/accessibility/aria/aria-invalid-expected-mac.txt index f396346..5010121 100644 --- a/content/test/data/accessibility/aria/aria-invalid-expected-mac.txt +++ b/content/test/data/accessibility/aria/aria-invalid-expected-mac.txt
@@ -1,23 +1,23 @@ AXWebArea AXInvalid='false' ++AXGroup AXInvalid='true' -++++AXStaticText AXValue='invalid=true' AXInvalid='false' +++++AXStaticText AXValue='invalid=true' ++AXTextArea AXValue='An eror via invalid=spelling' AXInvalid='false' -++++AXStaticText AXValue='An ' AXInvalid='false' +++++AXStaticText AXValue='An ' ++++AXGroup AXInvalid='spelling' -++++++AXStaticText AXValue='eror' AXInvalid='false' -++++AXStaticText AXValue=' via invalid=spelling' AXInvalid='false' +++++++AXStaticText AXValue='eror' +++++AXStaticText AXValue=' via invalid=spelling' ++AXTextArea AXValue='An errors via invalid=grammar' AXInvalid='false' -++++AXStaticText AXValue='An ' AXInvalid='false' +++++AXStaticText AXValue='An ' ++++AXGroup AXInvalid='grammar' -++++++AXStaticText AXValue='errors' AXInvalid='false' -++++AXStaticText AXValue=' via invalid=grammar' AXInvalid='false' +++++++AXStaticText AXValue='errors' +++++AXStaticText AXValue=' via invalid=grammar' ++AXGroup AXInvalid='false' -++++AXStaticText AXValue='invalid=false' AXInvalid='false' -++AXGroup AXInvalid='false' -++++AXStaticText AXValue='invalid=<empty>' AXInvalid='false' -++AXGroup AXInvalid='false' -++++AXStaticText AXValue='invalid=<default>' AXInvalid='false' +++++AXStaticText AXValue='invalid=false' +++AXGroup +++++AXStaticText AXValue='invalid=<empty>' +++AXGroup +++++AXStaticText AXValue='invalid=<default>' ++AXGroup AXInvalid='unknown' -++++AXStaticText AXValue='invalid=unknown' AXInvalid='false' -++AXGroup AXInvalid='false' +++++AXStaticText AXValue='invalid=unknown' +++AXGroup ++++AXTextField AXValue='1234' AXInvalid='true' \ No newline at end of file
diff --git a/content/test/data/accessibility/aria/aria-listbox-aria-selected-expected-mac.txt b/content/test/data/accessibility/aria/aria-listbox-aria-selected-expected-mac.txt index 60ab7ce..977f199 100644 --- a/content/test/data/accessibility/aria/aria-listbox-aria-selected-expected-mac.txt +++ b/content/test/data/accessibility/aria/aria-listbox-aria-selected-expected-mac.txt
@@ -1,7 +1,7 @@ -AXWebArea -++AXList AXFocusableAncestor='AXWebArea' AXOrientation='AXVerticalOrientation' AXSelectedChildren=["AXStaticText Item 4","AXStaticText Item 5"] AXVisibleChildren=["AXStaticText Item 1","AXStaticText Item 2","AXStaticText Item 3","AXStaticText Item 4","AXStaticText Item 5"] -++++AXStaticText AXValue='Item 1' AXFocusableAncestor='AXStaticText Item 1' AXSelected='0' -++++AXStaticText AXValue='Item 2' AXFocusableAncestor='AXStaticText Item 2' AXSelected='0' -++++AXStaticText AXValue='Item 3' AXFocusableAncestor='AXStaticText Item 3' AXSelected='0' -++++AXStaticText AXValue='Item 4' AXFocusableAncestor='AXStaticText Item 4' AXSelected='1' -++++AXStaticText AXValue='Item 5' AXFocusableAncestor='AXStaticText Item 5' AXSelected='1' +AXWebArea AXSelected='0' +++AXList AXOrientation='AXVerticalOrientation' AXSelected='0' AXSelectedChildren=["AXStaticText Item 4","AXStaticText Item 5"] AXVisibleChildren=["AXStaticText Item 1","AXStaticText Item 2","AXStaticText Item 3","AXStaticText Item 4","AXStaticText Item 5"] +++++AXStaticText AXValue='Item 1' AXSelected='0' +++++AXStaticText AXValue='Item 2' AXSelected='0' +++++AXStaticText AXValue='Item 3' AXSelected='0' +++++AXStaticText AXValue='Item 4' AXSelected='1' +++++AXStaticText AXValue='Item 5' AXSelected='1' \ No newline at end of file
diff --git a/content/test/data/accessibility/aria/aria-menu.html b/content/test/data/accessibility/aria/aria-menu.html index 2211f94..86672d6 100644 --- a/content/test/data/accessibility/aria/aria-menu.html +++ b/content/test/data/accessibility/aria/aria-menu.html
@@ -2,6 +2,7 @@ @MAC-ALLOW:AXDescription='File' @MAC-DENY:AXValue* @MAC-ALLOW:AXLinkedUIElements* +@MAC-DENY:AXLinkedUIElements=[] @WIN-DENY:description='' --> <html>
diff --git a/content/test/data/accessibility/aria/aria-menubar.html b/content/test/data/accessibility/aria/aria-menubar.html index 0302f822..75ff785 100644 --- a/content/test/data/accessibility/aria/aria-menubar.html +++ b/content/test/data/accessibility/aria/aria-menubar.html
@@ -1,6 +1,7 @@ <!-- @MAC-DENY:AXValue* @MAC-ALLOW:AXLinkedUIElements* +@MAC-DENY:AXLinkedUIElements=[] @WIN-DENY:description='' --> <html>
diff --git a/content/test/data/accessibility/aria/aria-radiogroup.html b/content/test/data/accessibility/aria/aria-radiogroup.html index 7725043..e38430e 100644 --- a/content/test/data/accessibility/aria/aria-radiogroup.html +++ b/content/test/data/accessibility/aria/aria-radiogroup.html
@@ -1,6 +1,7 @@ <!-- @BLINK-ALLOW:radioGroupIds=* @MAC-ALLOW:AXLinkedUIElements* +@MAC-DENY:AXLinkedUIElements=[] @MAC-ALLOW:AXRole* @WIN-ALLOW:xml-roles:* @WIN-ALLOW:checkable*
diff --git a/content/test/data/accessibility/aria/aria-required-expected-mac.txt b/content/test/data/accessibility/aria/aria-required-expected-mac.txt index 72c10f36..79dad931 100644 --- a/content/test/data/accessibility/aria/aria-required-expected-mac.txt +++ b/content/test/data/accessibility/aria/aria-required-expected-mac.txt
@@ -1,4 +1,4 @@ -AXWebArea -++AXRadioGroup AXRequired='1' +AXWebArea AXRequired='0' +++AXRadioGroup ++++AXRadioButton AXValue='0' -++++AXRadioButton AXValue='0' +++++AXRadioButton AXValue='0' \ No newline at end of file
diff --git a/content/test/data/accessibility/aria/aria-selected-expected-mac.txt b/content/test/data/accessibility/aria/aria-selected-expected-mac.txt index ad4614a..950b3cab 100644 --- a/content/test/data/accessibility/aria/aria-selected-expected-mac.txt +++ b/content/test/data/accessibility/aria/aria-selected-expected-mac.txt
@@ -1,4 +1,4 @@ -AXWebArea -++AXList AXSelectedChildren=["AXStaticText 1"] +AXWebArea AXSelected='0' +++AXList AXSelected='0' AXSelectedChildren=["AXStaticText 1"] ++++AXStaticText AXValue='1' AXSelected='1' -++++AXStaticText AXValue='2' AXSelected='0' +++++AXStaticText AXValue='2' AXSelected='0' \ No newline at end of file
diff --git a/content/test/data/accessibility/aria/aria1.1-combobox.html b/content/test/data/accessibility/aria/aria1.1-combobox.html index 4fbd0f0..e48faac 100644 --- a/content/test/data/accessibility/aria/aria1.1-combobox.html +++ b/content/test/data/accessibility/aria/aria1.1-combobox.html
@@ -2,6 +2,7 @@ <!-- @MAC-ALLOW:AXFocused='1' @MAC-ALLOW:AXLinkedUIElements* +@MAC-DENY:AXLinkedUIElements=[] @MAC-ALLOW:AXTitleUIElement* @WIN-DENY:description* @WIN-ALLOW:FOCUS*
diff --git a/content/test/data/accessibility/aria/input-text-aria-placeholder-expected-mac.txt b/content/test/data/accessibility/aria/input-text-aria-placeholder-expected-mac.txt index c8322ad..da6d502 100644 --- a/content/test/data/accessibility/aria/input-text-aria-placeholder-expected-mac.txt +++ b/content/test/data/accessibility/aria/input-text-aria-placeholder-expected-mac.txt
@@ -1,9 +1,9 @@ AXWebArea AXRoleDescription='HTML content' -++AXTextField AXRoleDescription='text field' AXDescription='aria-placeholder1' -++AXTextField AXRoleDescription='text field' AXDescription='placeholder2' +++AXTextField AXRoleDescription='text field' AXDescription='aria-placeholder1' AXPlaceholderValue='aria-placeholder1' +++AXTextField AXRoleDescription='text field' AXDescription='placeholder2' AXPlaceholderValue='placeholder2' ++AXTextField AXRoleDescription='text field' AXDescription='aria-label3' AXPlaceholderValue='placeholder3' ++AXTextField AXRoleDescription='text field' AXDescription='aria-label4' AXPlaceholderValue='aria-placeholder4' ++AXTextField AXRoleDescription='text field' AXDescription='aria-label5' AXHelp='aria-description5' AXPlaceholderValue='placeholder5' ++AXGroup AXRoleDescription='group' ++++AXStaticText AXRoleDescription='text' AXValue='aria-description5' -++AXTextField AXRoleDescription='text field' AXDescription='aria-placeholder6' AXHelp='title6' \ No newline at end of file +++AXTextField AXRoleDescription='text field' AXDescription='aria-placeholder6' AXHelp='title6' AXPlaceholderValue='aria-placeholder6' \ No newline at end of file
diff --git a/content/test/data/accessibility/event/aria-combo-box-collapse-expected-win-uia.txt b/content/test/data/accessibility/event/aria-combo-box-collapse-expected-win-uia.txt new file mode 100644 index 0000000..7500f78 --- /dev/null +++ b/content/test/data/accessibility/event/aria-combo-box-collapse-expected-win-uia.txt
@@ -0,0 +1 @@ +UIA_AutomationFocusChangedEventId on role=combobox
diff --git a/content/test/data/accessibility/event/aria-combo-box-delay-add-list-expected-win-uia.txt b/content/test/data/accessibility/event/aria-combo-box-delay-add-list-expected-win-uia.txt new file mode 100644 index 0000000..a67bf9cc3 --- /dev/null +++ b/content/test/data/accessibility/event/aria-combo-box-delay-add-list-expected-win-uia.txt
@@ -0,0 +1 @@ +UIA_AutomationFocusChangedEventId on role=option, name=Apple
diff --git a/content/test/data/accessibility/event/aria-combo-box-expand-expected-win-uia.txt b/content/test/data/accessibility/event/aria-combo-box-expand-expected-win-uia.txt new file mode 100644 index 0000000..a67bf9cc3 --- /dev/null +++ b/content/test/data/accessibility/event/aria-combo-box-expand-expected-win-uia.txt
@@ -0,0 +1 @@ +UIA_AutomationFocusChangedEventId on role=option, name=Apple
diff --git a/content/test/data/accessibility/event/aria-combo-box-focus-expected-win-uia.txt b/content/test/data/accessibility/event/aria-combo-box-focus-expected-win-uia.txt new file mode 100644 index 0000000..a67bf9cc3 --- /dev/null +++ b/content/test/data/accessibility/event/aria-combo-box-focus-expected-win-uia.txt
@@ -0,0 +1 @@ +UIA_AutomationFocusChangedEventId on role=option, name=Apple
diff --git a/content/test/data/accessibility/event/aria-combo-box-next-expected-win-uia.txt b/content/test/data/accessibility/event/aria-combo-box-next-expected-win-uia.txt new file mode 100644 index 0000000..843f1631 --- /dev/null +++ b/content/test/data/accessibility/event/aria-combo-box-next-expected-win-uia.txt
@@ -0,0 +1 @@ +UIA_AutomationFocusChangedEventId on role=option, name=Banana
diff --git a/content/test/data/accessibility/event/listbox-focus-expected-win-uia.txt b/content/test/data/accessibility/event/listbox-focus-expected-win-uia.txt new file mode 100644 index 0000000..3789cbf --- /dev/null +++ b/content/test/data/accessibility/event/listbox-focus-expected-win-uia.txt
@@ -0,0 +1 @@ +UIA_AutomationFocusChangedEventId on role=listbox
diff --git a/content/test/data/accessibility/event/listbox-next-expected-win-uia.txt b/content/test/data/accessibility/event/listbox-next-expected-win-uia.txt new file mode 100644 index 0000000..6d7e8a2 --- /dev/null +++ b/content/test/data/accessibility/event/listbox-next-expected-win-uia.txt
@@ -0,0 +1 @@ +UIA_AutomationFocusChangedEventId on role=option, name=Orange
diff --git a/content/test/data/accessibility/event/menulist-focus-expected-win-uia.txt b/content/test/data/accessibility/event/menulist-focus-expected-win-uia.txt new file mode 100644 index 0000000..7500f78 --- /dev/null +++ b/content/test/data/accessibility/event/menulist-focus-expected-win-uia.txt
@@ -0,0 +1 @@ +UIA_AutomationFocusChangedEventId on role=combobox
diff --git a/content/test/data/accessibility/event/report-validity-invalid-field-expected-win-uia.txt b/content/test/data/accessibility/event/report-validity-invalid-field-expected-win-uia.txt new file mode 100644 index 0000000..f8d851a --- /dev/null +++ b/content/test/data/accessibility/event/report-validity-invalid-field-expected-win-uia.txt
@@ -0,0 +1 @@ +UIA_AutomationFocusChangedEventId on role=textbox, name=Pet name:
diff --git a/content/test/data/accessibility/event/report-validity-invalid-field.html b/content/test/data/accessibility/event/report-validity-invalid-field.html index 5d3e7050..9d0aeec 100644 --- a/content/test/data/accessibility/event/report-validity-invalid-field.html +++ b/content/test/data/accessibility/event/report-validity-invalid-field.html
@@ -3,6 +3,7 @@ @WIN-ALLOW:EVENT_OBJECT_FOCUS* @WIN-ALLOW:EVENT_SYSTEM_ALERT* @WIN-ALLOW:EVENT_OBJECT_LIVE* +@WIN-ALLOW:UIA_AutomationFocusChangedEventId* @MAC-DENY:* @MAC-ALLOW:AXFocusedUIElementChanged* @MAC-ALLOW:AXFocusedUIElementChanged*
diff --git a/content/test/data/accessibility/event/tbody-focus-expected-win-uia.txt b/content/test/data/accessibility/event/tbody-focus-expected-win-uia.txt new file mode 100644 index 0000000..aa3ec43 --- /dev/null +++ b/content/test/data/accessibility/event/tbody-focus-expected-win-uia.txt
@@ -0,0 +1 @@ +UIA_AutomationFocusChangedEventId on role=group, name=tbody
diff --git a/content/test/data/accessibility/event/tfoot-focus-expected-win-uia.txt b/content/test/data/accessibility/event/tfoot-focus-expected-win-uia.txt new file mode 100644 index 0000000..2fd788dc --- /dev/null +++ b/content/test/data/accessibility/event/tfoot-focus-expected-win-uia.txt
@@ -0,0 +1 @@ +UIA_AutomationFocusChangedEventId on role=group, name=tfoot
diff --git a/content/test/data/accessibility/event/thead-focus-expected-win-uia.txt b/content/test/data/accessibility/event/thead-focus-expected-win-uia.txt new file mode 100644 index 0000000..b9af00e --- /dev/null +++ b/content/test/data/accessibility/event/thead-focus-expected-win-uia.txt
@@ -0,0 +1 @@ +UIA_AutomationFocusChangedEventId on role=group, name=thead
diff --git a/content/test/data/accessibility/html/blockquote-levels-expected-mac.txt b/content/test/data/accessibility/html/blockquote-levels-expected-mac.txt new file mode 100644 index 0000000..e1260af --- /dev/null +++ b/content/test/data/accessibility/html/blockquote-levels-expected-mac.txt
@@ -0,0 +1,7 @@ +AXWebArea AXBlockQuoteLevel='0' +++AXGroup AXBlockQuoteLevel='1' +++++AXStaticText AXValue='Top level' AXBlockQuoteLevel='1' +++++AXGroup AXBlockQuoteLevel='2' +++++++AXStaticText AXValue='Sub' AXBlockQuoteLevel='2' +++++++AXGroup AXBlockQuoteLevel='3' +++++++++AXStaticText AXValue='Sub-sub' AXBlockQuoteLevel='3'
diff --git a/content/test/data/accessibility/html/blockquote-levels.html b/content/test/data/accessibility/html/blockquote-levels.html new file mode 100644 index 0000000..a7e7f394 --- /dev/null +++ b/content/test/data/accessibility/html/blockquote-levels.html
@@ -0,0 +1,19 @@ +<!-- +@MAC-ALLOW:AXBlockQuoteLevel* +--> +<!DOCTYPE html> +<html> +<body> +<div> + <blockquote> + Top level + <blockquote> + Sub + <blockquote> + Sub-sub + </blockquote> + </blockquote> + </blockquote> +</div> +</body> +</html>
diff --git a/content/test/data/accessibility/html/in-page-links.html b/content/test/data/accessibility/html/in-page-links.html index 6726b588..6e177440 100644 --- a/content/test/data/accessibility/html/in-page-links.html +++ b/content/test/data/accessibility/html/in-page-links.html
@@ -2,6 +2,7 @@ <!-- @BLINK-ALLOW:inPageLinkTargetId=* @MAC-ALLOW:AXLinkedUIElements* +@MAC-DENY:AXLinkedUIElements=[] @WIN-ALLOW:LINKED -->
diff --git a/content/test/data/accessibility/html/input-radio-expected-mac.txt b/content/test/data/accessibility/html/input-radio-expected-mac.txt index 53cd5c9..b23653f 100644 --- a/content/test/data/accessibility/html/input-radio-expected-mac.txt +++ b/content/test/data/accessibility/html/input-radio-expected-mac.txt
@@ -10,4 +10,4 @@ ++++AXRadioButton AXTitle='Radio4' AXValue='1' AXLinkedUIElements=["AXRadioButton Radio3","AXRadioButton Radio4"] ++AXGroup ++++AXRadioButton AXTitle='Radio5' AXValue='0' AXLinkedUIElements=["AXRadioButton Radio5"] -++++AXRadioButton AXTitle='Radio6' AXValue='1' AXLinkedUIElements=["AXRadioButton Radio6"] \ No newline at end of file +++++AXRadioButton AXTitle='Radio6' AXValue='1' AXLinkedUIElements=["AXRadioButton Radio6"]
diff --git a/content/test/data/accessibility/html/input-radio.html b/content/test/data/accessibility/html/input-radio.html index 248ce2e..bdf786a 100644 --- a/content/test/data/accessibility/html/input-radio.html +++ b/content/test/data/accessibility/html/input-radio.html
@@ -1,6 +1,7 @@ <!-- @BLINK-ALLOW:radioGroupIds=* @MAC-ALLOW:AXLinkedUIElements* +@MAC-DENY:AXLinkedUIElements=[] @WIN-ALLOW:MIXED* @WIN-ALLOW:CHECKED* @WIN-ALLOW:checkable:*
diff --git a/content/test/data/accessibility/html/input-text-expected-mac.txt b/content/test/data/accessibility/html/input-text-expected-mac.txt index b3970e9..38202e53 100644 --- a/content/test/data/accessibility/html/input-text-expected-mac.txt +++ b/content/test/data/accessibility/html/input-text-expected-mac.txt
@@ -1,3 +1,3 @@ AXWebArea AXRoleDescription='HTML content' ++AXGroup AXRoleDescription='group' -++++AXTextField AXRoleDescription='text field' AXDescription='Name' AXEditableAncestor='AXTextField Name' AXHighestEditableAncestor='AXTextField Name' +++++AXTextField AXRoleDescription='text field' AXDescription='Name' AXEditableAncestor='AXTextField Name' AXHighestEditableAncestor='AXTextField Name' AXPlaceholderValue='Name' \ No newline at end of file
diff --git a/content/test/data/accessibility/html/input-text-read-only-expected-mac.txt b/content/test/data/accessibility/html/input-text-read-only-expected-mac.txt index 893526f3..ceaf746f 100644 --- a/content/test/data/accessibility/html/input-text-read-only-expected-mac.txt +++ b/content/test/data/accessibility/html/input-text-read-only-expected-mac.txt
@@ -1,3 +1,3 @@ AXWebArea AXRoleDescription='HTML content' ++AXGroup AXRoleDescription='group' -++++AXTextField AXRoleDescription='text field' AXDescription='Name' +++++AXTextField AXRoleDescription='text field' AXDescription='Name' AXPlaceholderValue='Name' \ No newline at end of file
diff --git a/content/test/data/accessibility/html/no-source-video-expected-android.txt b/content/test/data/accessibility/html/no-source-video-expected-android.txt new file mode 100644 index 0000000..b7f7e2b --- /dev/null +++ b/content/test/data/accessibility/html/no-source-video-expected-android.txt
@@ -0,0 +1,15 @@ +android.webkit.WebView focusable focused scrollable +++android.view.View +++++android.view.View role_description='video' disabled focusable name='Unable to play media.' +++++++android.view.View +++++++++android.view.View +++++++++android.view.View +++++++++++android.widget.Button role_description='button' clickable focusable name='play' +++++++++++android.view.View +++++++++++++android.view.View name='elapsed time: 0:00' +++++++++++++android.view.View +++++++++++++++android.view.View +++++++++++++++android.widget.Button role_description='button' disabled name='mute' +++++++++++++android.widget.Button role_description='button' disabled name='enter full screen' +++++++++++++android.widget.Button role_description='button' disabled name='show more media controls' hint='more options' +++++++++++android.widget.SeekBar role_description='slider' disabled range name='0:00' hint='video time scrubber' item_count=100 \ No newline at end of file
diff --git a/content/test/data/accessibility/html/no-source-video-expected-auralinux.txt b/content/test/data/accessibility/html/no-source-video-expected-auralinux.txt new file mode 100644 index 0000000..9b3716d --- /dev/null +++ b/content/test/data/accessibility/html/no-source-video-expected-auralinux.txt
@@ -0,0 +1,9 @@ +[document web] +++[section] +++++[video] name='Unable to play media.' +++++++[section] +++++++++[section] +++++++++[section] +++++++++++[section] +++++++++++++[push button] name='show more media controls' description='more options' +++++++++++[slider] description='video time scrubber' horizontal \ No newline at end of file
diff --git a/content/test/data/accessibility/html/no-source-video-expected-blink.txt b/content/test/data/accessibility/html/no-source-video-expected-blink.txt new file mode 100644 index 0000000..14094441 --- /dev/null +++ b/content/test/data/accessibility/html/no-source-video-expected-blink.txt
@@ -0,0 +1,18 @@ +rootWebArea +++genericContainer +++++video name='Unable to play media.' restriction=disabled +++++++genericContainer +++++++++genericContainer +++++++++genericContainer +++++++++++genericContainer +++++++++++++button name='play' restriction=disabled +++++++++++++genericContainer name='elapsed time: 0:00' +++++++++++++++staticText name='0:00' +++++++++++++++++inlineTextBox name='0:00' +++++++++++++genericContainer +++++++++++++++genericContainer +++++++++++++++button name='mute' restriction=disabled +++++++++++++button name='enter full screen' restriction=disabled +++++++++++++button description='more options' name='show more media controls' descriptionFrom=attribute restriction=disabled +++++++++++slider horizontal description='video time scrubber' value='0:00' descriptionFrom=uninitialized restriction=disabled valueForRange=0.00 minValueForRange=0.00 maxValueForRange=0.00 +++++++++++++sliderThumb \ No newline at end of file
diff --git a/content/test/data/accessibility/html/no-source-video-expected-mac.txt b/content/test/data/accessibility/html/no-source-video-expected-mac.txt new file mode 100644 index 0000000..7c091e7 --- /dev/null +++ b/content/test/data/accessibility/html/no-source-video-expected-mac.txt
@@ -0,0 +1,9 @@ +AXWebArea +++AXGroup +++++AXGroup AXDescription='Unable to play media.' +++++++AXGroup +++++++++AXGroup +++++++++AXGroup +++++++++++AXGroup +++++++++++++AXButton AXDescription='show more media controls' AXHelp='more options' +++++++++++AXSlider AXValue='0' AXHelp='video time scrubber' \ No newline at end of file
diff --git a/content/test/data/accessibility/html/no-source-video-expected-win.txt b/content/test/data/accessibility/html/no-source-video-expected-win.txt new file mode 100644 index 0000000..f9dbafc --- /dev/null +++ b/content/test/data/accessibility/html/no-source-video-expected-win.txt
@@ -0,0 +1,16 @@ +ROLE_SYSTEM_DOCUMENT READONLY FOCUSABLE +++IA2_ROLE_SECTION +++++ROLE_SYSTEM_GROUPING name='Unable to play media.' UNAVAILABLE FOCUSABLE +++++++IA2_ROLE_SECTION +++++++++IA2_ROLE_SECTION +++++++++IA2_ROLE_SECTION +++++++++++IA2_ROLE_SECTION +++++++++++++ROLE_SYSTEM_PUSHBUTTON name='play' UNAVAILABLE +++++++++++++IA2_ROLE_SECTION name='elapsed time: 0:00' +++++++++++++++ROLE_SYSTEM_STATICTEXT name='0:00' +++++++++++++IA2_ROLE_SECTION +++++++++++++++IA2_ROLE_SECTION +++++++++++++++ROLE_SYSTEM_PUSHBUTTON name='mute' UNAVAILABLE +++++++++++++ROLE_SYSTEM_PUSHBUTTON name='enter full screen' UNAVAILABLE +++++++++++++ROLE_SYSTEM_PUSHBUTTON name='show more media controls' UNAVAILABLE description='more options' +++++++++++ROLE_SYSTEM_SLIDER value='0:00' UNAVAILABLE IA2_STATE_HORIZONTAL description='video time scrubber' \ No newline at end of file
diff --git a/content/test/data/accessibility/html/no-source-video.html b/content/test/data/accessibility/html/no-source-video.html new file mode 100644 index 0000000..08833bb --- /dev/null +++ b/content/test/data/accessibility/html/no-source-video.html
@@ -0,0 +1,9 @@ +<!-- +@WIN-ALLOW:description* +--> +<!DOCTYPE html> +<html> +<body> +<video controls></video> +</body> +</html>
diff --git a/content/test/data/gpu/power_video_bear_1280x720_mp4.html b/content/test/data/gpu/power_video_bear_1280x720_mp4.html index 1ca9ea9..e14a591 100644 --- a/content/test/data/gpu/power_video_bear_1280x720_mp4.html +++ b/content/test/data/gpu/power_video_bear_1280x720_mp4.html
@@ -11,10 +11,8 @@ position: relative; } </style> -<script src="power_video_test.js"></script> </head> -<body onload="main()"> -<button id="fullscreen" onclick="goFullscreen()">Fullscreen</button> +<body> <div id="container" class="relativepos"> <video class="nomargin" id="video" width="1280" height="720" > <source src="/media/test/data/bear-1280x720.mp4" type="video/mp4">
diff --git a/content/test/data/gpu/power_video_test.js b/content/test/data/gpu/power_video_test.js deleted file mode 100644 index 254a578..0000000 --- a/content/test/data/gpu/power_video_test.js +++ /dev/null
@@ -1,83 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var video = null; -var box = null; -var video_in_fullscreen = false; - -function main() { - video = document.getElementById("video"); - video.loop = true; - video.muted = true; - video.addEventListener('timeupdate', waitForVideoToPlay); - video.play(); -} - -function waitForVideoToPlay() { - if (video.currentTime > 0) { - video.removeEventListener('timeupdate', waitForVideoToPlay); - domAutomationController.send("SUCCESS"); - } -} - -function goFullscreen() { - // Call requestFullscreen() on video's parent element, so we could add - // colored box on top of the video. - var container = video.parentNode; - video.style.width="100%"; - video.style.height="100%"; - if (container.requestFullscreen) { - container.requestFullscreen(); - container.addEventListener("fullscreenchange", function() { - video_in_fullscreen = true; - }); - } else if (container.webkitRequestFullscreen) { - container.webkitRequestFullscreen(); - container.addEventListener("webkitfullscreenchange", function() { - video_in_fullscreen = true; - }); - } -} - -function isVideoInFullscreen() { - return video_in_fullscreen; -} - -function goUnderlay() { - if (!box) { - // Draw a solid color box in the top left corner of the video, so the - // video becomes an underlay. - box = document.createElement("div"); - box.style.backgroundColor = "red"; - box.style.width = "100px"; - box.style.height = "50px"; - box.style.position = "absolute"; - box.style.zIndex = "2147483647"; // max zIndex value - var vid_rect = video.getBoundingClientRect(); - var parent_rect = video.parentNode.getBoundingClientRect(); - var top = vid_rect.top - parent_rect.top + 10; - var left = vid_rect.left - parent_rect.left + 10; - box.style.top = top.toString() + "px"; - box.style.left = left.toString() + "px"; - box.style.visibility = "visible"; - video.parentNode.appendChild(box); - } - // Change box color between red/blue every second. This is to emulate UI - // or ads change (once per second) on top of a video. - setTimeout(setBoxColorToBlue, 1000); -} - -function setBoxColorToBlue() { - if (!box) - return; - box.style.backgroundColor = "blue"; - setTimeout(setBoxColorToRed, 1000); -} - -function setBoxColorToRed() { - if (!box) - return; - box.style.backgroundColor = "red"; - setTimeout(setBoxColorToBlue, 1000); -}
diff --git a/content/test/did_commit_provisional_load_interceptor.cc b/content/test/did_commit_provisional_load_interceptor.cc deleted file mode 100644 index cb651e8b..0000000 --- a/content/test/did_commit_provisional_load_interceptor.cc +++ /dev/null
@@ -1,86 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/test/did_commit_provisional_load_interceptor.h" - -#include "content/browser/frame_host/render_frame_host_impl.h" -#include "content/common/frame.mojom-test-utils.h" -#include "content/common/frame_messages.h" -#include "content/public/browser/render_frame_host.h" -#include "content/public/browser/web_contents.h" - -namespace content { - -// Responsible for intercepting DidCommitProvisionalLoad's being disptached to -// a given RenderFrameHostImpl. -class DidCommitProvisionalLoadInterceptor::FrameAgent - : public mojom::FrameHostInterceptorForTesting { - public: - FrameAgent(DidCommitProvisionalLoadInterceptor* interceptor, - RenderFrameHost* rfh) - : interceptor_(interceptor), - rfhi_(static_cast<RenderFrameHostImpl*>(rfh)), - impl_(binding().SwapImplForTesting(this)) {} - - ~FrameAgent() override { - auto* old_impl = binding().SwapImplForTesting(impl_); - // TODO(https://crbug.com/729021): Investigate the scenario where - // |old_impl| can be nullptr if the renderer process is killed. - DCHECK_EQ(this, old_impl); - } - - protected: - mojo::AssociatedBinding<mojom::FrameHost>& binding() { - return rfhi_->frame_host_binding_for_testing(); - } - - // mojom::FrameHostInterceptorForTesting: - FrameHost* GetForwardingInterface() override { return impl_; } - void DidCommitProvisionalLoad( - std::unique_ptr<::FrameHostMsg_DidCommitProvisionalLoad_Params> params, - mojom::DidCommitProvisionalLoadInterfaceParamsPtr interface_params) - override { - if (interceptor_->WillDispatchDidCommitProvisionalLoad(rfhi_, params.get(), - interface_params)) { - GetForwardingInterface()->DidCommitProvisionalLoad( - std::move(params), std::move(interface_params)); - } - } - - private: - DidCommitProvisionalLoadInterceptor* interceptor_; - - RenderFrameHostImpl* rfhi_; - mojom::FrameHost* impl_; - - DISALLOW_COPY_AND_ASSIGN(FrameAgent); -}; - -DidCommitProvisionalLoadInterceptor::DidCommitProvisionalLoadInterceptor( - WebContents* web_contents) - : WebContentsObserver(web_contents) { - for (auto* rfh : web_contents->GetAllFrames()) { - if (rfh->IsRenderFrameLive()) - RenderFrameCreated(rfh); - } -} - -DidCommitProvisionalLoadInterceptor::~DidCommitProvisionalLoadInterceptor() = - default; - -void DidCommitProvisionalLoadInterceptor::RenderFrameCreated( - RenderFrameHost* render_frame_host) { - bool did_insert; - std::tie(std::ignore, did_insert) = frame_agents_.emplace( - render_frame_host, std::make_unique<FrameAgent>(this, render_frame_host)); - DCHECK(did_insert); -} - -void DidCommitProvisionalLoadInterceptor::RenderFrameDeleted( - RenderFrameHost* render_frame_host) { - bool did_remove = !!frame_agents_.erase(render_frame_host); - DCHECK(did_remove); -} - -} // namespace content
diff --git a/content/test/did_commit_provisional_load_interceptor.h b/content/test/did_commit_provisional_load_interceptor.h deleted file mode 100644 index 7178e42..0000000 --- a/content/test/did_commit_provisional_load_interceptor.h +++ /dev/null
@@ -1,53 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_TEST_DID_COMMIT_PROVISIONAL_LOAD_INTERCEPTOR_H_ -#define CONTENT_TEST_DID_COMMIT_PROVISIONAL_LOAD_INTERCEPTOR_H_ - -#include <map> -#include <memory> - -#include "base/macros.h" -#include "content/common/frame.mojom.h" -#include "content/public/browser/web_contents_observer.h" - -namespace content { - -class RenderFrameHost; - -// Allows intercepting calls to RFHI::DidCommitProvisionalLoad just before they -// are dispatched to the implementation. This enables unit/browser tests to -// scrutinize/alter the parameters, or simulate race conditions by triggering -// other calls just before dispatching DidCommitProvisionalLoad. -class DidCommitProvisionalLoadInterceptor : public WebContentsObserver { - public: - // Constructs an instance that will intercept DidCommitProvisionalLoad calls - // in any frame of the |web_contents| while the instance is in scope. - explicit DidCommitProvisionalLoadInterceptor(WebContents* web_contents); - ~DidCommitProvisionalLoadInterceptor() override; - - // Called just before DidCommitProvisionalLoad with |params| and - // |interface_provider_request| would be dispatched to |render_frame_host|. - // Return false to cancel the dispatching of this message to - // |render_frame_host|. - virtual bool WillDispatchDidCommitProvisionalLoad( - RenderFrameHost* render_frame_host, - ::FrameHostMsg_DidCommitProvisionalLoad_Params* params, - mojom::DidCommitProvisionalLoadInterfaceParamsPtr& interface_params) = 0; - - private: - class FrameAgent; - - // WebContentsObserver: - void RenderFrameCreated(RenderFrameHost* render_frame_host) override; - void RenderFrameDeleted(RenderFrameHost* render_frame_host) override; - - std::map<RenderFrameHost*, std::unique_ptr<FrameAgent>> frame_agents_; - - DISALLOW_COPY_AND_ASSIGN(DidCommitProvisionalLoadInterceptor); -}; - -} // namespace content - -#endif // CONTENT_TEST_DID_COMMIT_PROVISIONAL_LOAD_INTERCEPTOR_H_
diff --git a/content/test/frame_host_interceptor.cc b/content/test/frame_host_interceptor.cc new file mode 100644 index 0000000..d8a4fd0 --- /dev/null +++ b/content/test/frame_host_interceptor.cc
@@ -0,0 +1,120 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/test/frame_host_interceptor.h" + +#include <utility> + +#include "content/browser/frame_host/render_frame_host_impl.h" +#include "content/common/frame.mojom-test-utils.h" +#include "content/common/frame_messages.h" +#include "content/public/browser/render_frame_host.h" +#include "content/public/browser/web_contents.h" + +namespace content { + +// Responsible for intercepting DidCommitProvisionalLoad's being disptached to +// a given RenderFrameHostImpl. +class FrameHostInterceptor::FrameAgent + : public mojom::FrameHostInterceptorForTesting { + public: + FrameAgent(FrameHostInterceptor* interceptor, RenderFrameHost* rfh) + : interceptor_(interceptor), + rfhi_(static_cast<RenderFrameHostImpl*>(rfh)), + impl_(binding().SwapImplForTesting(this)) {} + + ~FrameAgent() override { + auto* old_impl = binding().SwapImplForTesting(impl_); + // TODO(https://crbug.com/729021): Investigate the scenario where + // |old_impl| can be nullptr if the renderer process is killed. + DCHECK_EQ(this, old_impl); + } + + protected: + mojo::AssociatedBinding<mojom::FrameHost>& binding() { + return rfhi_->frame_host_binding_for_testing(); + } + + // mojom::FrameHostInterceptorForTesting: + FrameHost* GetForwardingInterface() override { return impl_; } + + void DidCommitProvisionalLoad( + std::unique_ptr<::FrameHostMsg_DidCommitProvisionalLoad_Params> params, + mojom::DidCommitProvisionalLoadInterfaceParamsPtr interface_params) + override { + if (interceptor_->WillDispatchDidCommitProvisionalLoad(rfhi_, params.get(), + &interface_params)) { + GetForwardingInterface()->DidCommitProvisionalLoad( + std::move(params), std::move(interface_params)); + } + } + + void BeginNavigation( + const CommonNavigationParams& common_params, + mojom::BeginNavigationParamsPtr begin_params, + blink::mojom::BlobURLTokenPtr blob_url_token, + mojom::NavigationClientAssociatedPtrInfo navigation_client, + blink::mojom::NavigationInitiatorPtr navigation_initiator) override { + CommonNavigationParams overrideable_common_params = common_params; + if (interceptor_->WillDispatchBeginNavigation( + rfhi_, &overrideable_common_params, &begin_params, &blob_url_token, + &navigation_client, &navigation_initiator)) { + GetForwardingInterface()->BeginNavigation( + overrideable_common_params, std::move(begin_params), + std::move(blob_url_token), std::move(navigation_client), + std::move(navigation_initiator)); + } + } + + private: + FrameHostInterceptor* interceptor_; + + RenderFrameHostImpl* rfhi_; + mojom::FrameHost* impl_; + + DISALLOW_COPY_AND_ASSIGN(FrameAgent); +}; + +FrameHostInterceptor::FrameHostInterceptor(WebContents* web_contents) + : WebContentsObserver(web_contents) { + for (auto* rfh : web_contents->GetAllFrames()) { + if (rfh->IsRenderFrameLive()) + RenderFrameCreated(rfh); + } +} + +FrameHostInterceptor::~FrameHostInterceptor() = default; + +bool FrameHostInterceptor::WillDispatchDidCommitProvisionalLoad( + RenderFrameHost* render_frame_host, + ::FrameHostMsg_DidCommitProvisionalLoad_Params* params, + mojom::DidCommitProvisionalLoadInterfaceParamsPtr* interface_params) { + return true; +} + +bool FrameHostInterceptor::WillDispatchBeginNavigation( + RenderFrameHost* render_frame_host, + CommonNavigationParams* common_params, + mojom::BeginNavigationParamsPtr* begin_params, + blink::mojom::BlobURLTokenPtr* blob_url_token, + mojom::NavigationClientAssociatedPtrInfo* navigation_client, + blink::mojom::NavigationInitiatorPtr* navigation_initiator) { + return true; +} + +void FrameHostInterceptor::RenderFrameCreated( + RenderFrameHost* render_frame_host) { + bool did_insert; + std::tie(std::ignore, did_insert) = frame_agents_.emplace( + render_frame_host, std::make_unique<FrameAgent>(this, render_frame_host)); + DCHECK(did_insert); +} + +void FrameHostInterceptor::RenderFrameDeleted( + RenderFrameHost* render_frame_host) { + bool did_remove = !!frame_agents_.erase(render_frame_host); + DCHECK(did_remove); +} + +} // namespace content
diff --git a/content/test/frame_host_interceptor.h b/content/test/frame_host_interceptor.h new file mode 100644 index 0000000..51b9fe0c --- /dev/null +++ b/content/test/frame_host_interceptor.h
@@ -0,0 +1,78 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_TEST_FRAME_HOST_INTERCEPTOR_H_ +#define CONTENT_TEST_FRAME_HOST_INTERCEPTOR_H_ + +#include <map> +#include <memory> + +#include "base/macros.h" +#include "content/common/frame.mojom.h" +#include "content/public/browser/web_contents_observer.h" + +namespace content { + +class RenderFrameHost; + +// Allows intercepting calls to mojom::FrameHost (e.g. DidCommitProvisionalLoad +// or BeginNavigation) just before they are dispatched to the implementation. +// This enables unit/browser tests to scrutinize/alter the parameters, or +// simulate race conditions by triggering other calls just before dispatching +// the original call. +class FrameHostInterceptor : public WebContentsObserver { + public: + // Constructs an instance that will intercept FrameHost calls in any frame of + // the |web_contents| while the instance is in scope. + explicit FrameHostInterceptor(WebContents* web_contents); + ~FrameHostInterceptor() override; + + // Called just before DidCommitProvisionalLoad with |params| and + // |interface_params| would be dispatched to |render_frame_host|. + // + // Return false to cancel the dispatching of this message. + // + // Return true (and/or modify |params| and |interface_params| as needed) to + // dispatch this message to the original implementation. + // + // By default this method returns true (e.g. doesn't do anything to the + // original messages and just forwards them to the original implementation). + virtual bool WillDispatchDidCommitProvisionalLoad( + RenderFrameHost* render_frame_host, + ::FrameHostMsg_DidCommitProvisionalLoad_Params* params, + mojom::DidCommitProvisionalLoadInterfaceParamsPtr* interface_params); + + // Called just before BeginNavigation IPC would be dispatched to + // |render_frame_host|. + // + // Return false to cancel the dispatching of this message. + // + // Return true (and/or modify args as needed) to dispatch this message to the + // original implementation. + // + // By default this method returns true (e.g. doesn't do anything to the + // original messages and just forwards them to the original implementation). + virtual bool WillDispatchBeginNavigation( + RenderFrameHost* render_frame_host, + CommonNavigationParams* common_params, + mojom::BeginNavigationParamsPtr* begin_params, + blink::mojom::BlobURLTokenPtr* blob_url_token, + mojom::NavigationClientAssociatedPtrInfo* navigation_client, + blink::mojom::NavigationInitiatorPtr* navigation_initiator); + + private: + class FrameAgent; + + // WebContentsObserver: + void RenderFrameCreated(RenderFrameHost* render_frame_host) override; + void RenderFrameDeleted(RenderFrameHost* render_frame_host) override; + + std::map<RenderFrameHost*, std::unique_ptr<FrameAgent>> frame_agents_; + + DISALLOW_COPY_AND_ASSIGN(FrameHostInterceptor); +}; + +} // namespace content + +#endif // CONTENT_TEST_FRAME_HOST_INTERCEPTOR_H_
diff --git a/content/test/gpu/gpu_tests/power_measurement_integration_test.py b/content/test/gpu/gpu_tests/power_measurement_integration_test.py index ebcdbfa82..2a4261b6 100644 --- a/content/test/gpu/gpu_tests/power_measurement_integration_test.py +++ b/content/test/gpu/gpu_tests/power_measurement_integration_test.py
@@ -21,6 +21,7 @@ * https://www.youtube.com * https://www.vimeo.com * https://www.pond5.com + * http://crosvideo.appspot.com """ from gpu_tests import gpu_integration_test @@ -51,42 +52,19 @@ os.path.join( path_util.GetChromiumSrcDir(), 'media', 'test', 'data')] -_BASIC_TEST_HARNESS_SCRIPT = r""" - var domAutomationController = {}; +_VIDEO_TEST_SCRIPT = r""" + var _video_in_fullscreen = false; + var _colored_box = null; + var _video_element = null; - domAutomationController._proceed = false; - - domAutomationController._readyForActions = false; - domAutomationController._succeeded = false; - domAutomationController._finished = false; - - domAutomationController.send = function(msg) { - domAutomationController._proceed = true; - let lmsg = msg.toLowerCase(); - if (lmsg == "ready") { - domAutomationController._readyForActions = true; - } else { - domAutomationController._finished = true; - if (lmsg == "success") { - domAutomationController._succeeded = true; - } else { - domAutomationController._succeeded = false; - } - } - } - - window.domAutomationController = domAutomationController; -""" - -_FULLSCREEN_SCRIPT = r""" - function locateElement(tag) { - // return the element with largest width. - var elements = document.getElementsByTagName(tag); + function _locateVideoElement() { + // return the video element with largest width. + var elements = document.getElementsByTagName("video"); if (elements.length == 0) return null; var rt = elements[0]; var max = elements[0].width; - for (var ii = 0; ii < elements.length; ++ii) { + for (var ii = 1; ii < elements.length; ++ii) { if (elements[ii].width > max) { rt = elements[ii]; max = elements[ii].width; @@ -95,47 +73,71 @@ return rt; } - /** - * Set up the video element for testing. - * @param {boolean} force_underlay - Whether to add a layer on top so - * the video layer becomes an underlay. - * @returns {boolean} true if video has started playing. - */ - function setupVideoElement(force_underlay) { - var video = locateElement("video"); - if (video) { - video.muted = true; - video.loop = true; - video.autoplay = true; - if (force_underlay) { - var layer = document.createElement("div"); - layer.style.border = "thick solid rgb(0,0,255)"; - layer.style.backgroundColor = "red"; - layer.style.width = "100px"; - layer.style.height = "50px"; - layer.style.position = "absolute"; - layer.style.zIndex = "1000"; - var vid_rect = video.getBoundingClientRect(); - var parent_rect = video.parentNode.getBoundingClientRect(); - var top = vid_rect.top - parent_rect.top; - var left = vid_rect.left - parent_rect.left; - layer.style.top = top.toString() + "px"; - layer.style.left = left.toString() + "px"; - // The following might mess with the layout of some sites. - video.parentNode.style.position = "relative"; - video.parentNode.appendChild(layer); - } - return video.currentTime > 0; + function _setupVideoElement() { + if (_video_element) { + // already set up + return; } - return false; + _video_element = _locateVideoElement(); + if (!_video_element) + return; + _video_element.muted = true; + _video_element.loop = true; + _video_element.autoplay = true; } - function locateButton(texts) { + function waitForVideoToPlay() { + _setupVideoElement(); + if (!_video_element) + return false; + return _video_element.currentTime > 0; + } + + function startUnderlayMode() { + _setupVideoElement(); + if (!_video_element) + return; + if (!_colored_box) { + _colored_box = document.createElement("div"); + _colored_box.style.backgroundColor = "red"; + _colored_box.style.width = "100px"; + _colored_box.style.height = "50px"; + _colored_box.style.position = "absolute"; + _colored_box.style.zIndex = "2147483647"; // max zIndex value + var vid_rect = _video_element.getBoundingClientRect(); + var parent_rect = _video_element.parentNode.getBoundingClientRect(); + var top = vid_rect.top - parent_rect.top + 10; + var left = vid_rect.left - parent_rect.left + 10; + _colored_box.style.top = top.toString() + "px"; + _colored_box.style.left = left.toString() + "px"; + _colored_box.style.visibility = "visible"; + _video_element.parentNode.appendChild(_colored_box); + } + // Change box color between red/blue every second. This is to emulate UI + // or ads change (once per second) on top of a video. + setTimeout(_setBoxColorToBlue, 1000); + } + + function _setBoxColorToBlue() { + if (!_colored_box) + return; + _colored_box.style.backgroundColor = "blue"; + setTimeout(_setBoxColorToRed, 1000); + } + + function _setBoxColorToRed() { + if (!_colored_box) + return; + _colored_box.style.backgroundColor = "red"; + setTimeout(_setBoxColorToBlue, 1000); + } + + function _locateButton(queries) { var buttons = document.getElementsByTagName("button"); for (var ii = 0; ii < buttons.length; ++ii) { var label = buttons[ii].textContent.toLowerCase(); - for (var jj = 0; jj < texts.length; ++jj) { - if (label.indexOf(texts[jj]) != -1) { + for (var jj = 0; jj < queries.length; ++jj) { + if (label.indexOf(queries[jj]) != -1) { return buttons[ii]; } } @@ -143,8 +145,8 @@ buttons[ii].getAttribute("data-tooltip-content"); if (label) { label = label.toLowerCase(); - for (var jj = 0; jj < texts.length; ++jj) { - if (label.indexOf(texts[jj]) != -1) + for (var jj = 0; jj < queries.length; ++jj) { + if (label.indexOf(queries[jj]) != -1) return buttons[ii]; } } @@ -152,8 +154,53 @@ return null; } - function locateFullscreenButton() { - return locateButton(["full screen", "fullscreen"]); + function _locateFullscreenButton() { + return _locateButton(["full screen", "fullscreen"]); + } + + function _addFullscreenChangeListener(node) { + if (!node) + return; + node.addEventListener("fullscreenchange", function() { + _video_in_fullscreen = true; + }); + node.addEventListener("webkitfullscreenchange", function() { + _video_in_fullscreen = true; + }); + } + + function isVideoInFullscreen() { + return _video_in_fullscreen; + } + + function startFullscreenMode() { + // Try to locate a fullscreen button on the page and click it. + _setupVideoElement(); + if (!_video_element) + return; + var button = _locateFullscreenButton(); + if (button) { + // We don't know which layer goes fullscreen, so we add callback to all + // layers along the path from the video element to html body. + var cur = _video_element; + while (cur) { + _addFullscreenChangeListener(cur); + cur = cur.parentNode; + } + button.click(); + } else { + // If we fail to locate a fullscreen button, call requestFullscreen() + // directly on the video element's parent node. + _video_element.style.width = "100%"; + _video_element.style.height = "100%"; + var container = _video_element.parentNode; + _addFullscreenChangeListener(container); + if (container.requestFullscreen) { + container.requestFullscreen(); + } else if (container.webkitRequestFullscreen) { + container.webkitRequestFullscreen(); + } + } } """ @@ -294,6 +341,21 @@ # chromeperf.appspot.com. logging.info("Results: %s", str(results)) + def _SetupVideo(self, fullscreen, underlay): + self.tab.action_runner.WaitForJavaScriptCondition( + 'waitForVideoToPlay()', timeout=30) + if fullscreen: + self.tab.action_runner.ExecuteJavaScript( + 'startFullscreenMode();', user_gesture=True) + try: + self.tab.action_runner.WaitForJavaScriptCondition( + 'isVideoInFullscreen()', timeout=5) + except py_utils.TimeoutException: + self.fail('requestFullscreen() fails to work, possibly because ' + '|user_gesture| is not set.') + if underlay: + self.tab.action_runner.ExecuteJavaScript('startUnderlayMode();') + ######################################### # Actual test functions @@ -317,20 +379,8 @@ url = self.UrlOfStaticFilePath(test_path) self.tab.Navigate( - url, script_to_evaluate_on_commit=_BASIC_TEST_HARNESS_SCRIPT) - self.tab.action_runner.WaitForJavaScriptCondition( - 'domAutomationController._finished', timeout=30) - if fullscreen: - self.tab.action_runner.ClickElement(element_function=( - 'document.getElementById("fullscreen")')) - try: - self.tab.action_runner.WaitForJavaScriptCondition( - 'isVideoInFullscreen()', timeout=5) - except py_utils.TimeoutException: - self.fail('requestFullscreen() fails to work, possibly because ' - '|user_gesture| is not set on ClickElement.') - if underlay: - self.tab.action_runner.ExecuteJavaScript('goUnderlay();') + url, script_to_evaluate_on_commit=_VIDEO_TEST_SCRIPT) + self._SetupVideo(fullscreen=fullscreen, underlay=underlay) PowerMeasurementIntegrationTest._MeasurePowerWithIPG(bypass_ipg) @@ -352,22 +402,9 @@ for iteration in range(repeat): if repeat > 1: logging.info("Iteration %d", iteration) - if test_path: - self.tab.action_runner.Navigate(test_path, _FULLSCREEN_SCRIPT) - self.tab.WaitForDocumentReadyStateToBeComplete() - code = "setupVideoElement(%s)" % ("true" if underlay else "false") - if not self.tab.action_runner.EvaluateJavaScript(code): - # autoplay doesn't work for vimeo. - # action_runner.PlayMedia doesn't work for vimeo. - self.tab.action_runner.ClickElement(element_function=( - 'locateElement("video")')) - - if fullscreen: - if self.tab.action_runner.EvaluateJavaScript( - 'locateFullscreenButton() == null'): - self.fail("Fullscreen button not located, --fullscreen won't work") - self.tab.action_runner.ClickElement(element_function=( - 'locateFullscreenButton()')) + self.tab.action_runner.Navigate(test_path, _VIDEO_TEST_SCRIPT) + self.tab.WaitForDocumentReadyStateToBeComplete() + self._SetupVideo(fullscreen=fullscreen, underlay=underlay) if bypass_ipg: logging.info("Bypassing Intel Power Gadget")
diff --git a/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py b/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py index f69ce6e..8634fb3 100644 --- a/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py +++ b/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py
@@ -677,6 +677,10 @@ self.Fail('conformance2/glsl3/tricky-loop-conditions.html', ['mac', ('nvidia', 0xfe9)], bug=929398) + self.Flaky('conformance2/textures/canvas_sub_rectangle/' + + 'tex-3d-r11f_g11f_b10f-rgb-unsigned_int_10f_11f_11f_rev.html', + ['mac', ('nvidia', 0xfe9)], bug=934556) + # When these fail on this configuration, they fail multiple times in a row. self.Fail('deqp/functional/gles3/shaderoperator/*', ['mac', 'nvidia'], bug=756537)
diff --git a/content/test/proxy_service_mojo_unittest.cc b/content/test/proxy_service_mojo_unittest.cc index 65a884ff..7951071 100644 --- a/content/test/proxy_service_mojo_unittest.cc +++ b/content/test/proxy_service_mojo_unittest.cc
@@ -111,20 +111,6 @@ EXPECT_EQ(3, line_number); } -class LoggingMockHostResolver : public net::MockHostResolver { - public: - int Resolve(const RequestInfo& info, - net::RequestPriority priority, - net::AddressList* addresses, - net::CompletionOnceCallback callback, - std::unique_ptr<Request>* out_req, - const net::NetLogWithSource& net_log) override { - net_log.AddEvent(net::NetLogEventType::HOST_RESOLVER_IMPL_JOB); - return net::MockHostResolver::Resolve( - info, priority, addresses, std::move(callback), out_req, net_log); - } -}; - } // namespace class ProxyServiceMojoTest : public testing::Test { @@ -148,7 +134,7 @@ base::test::ScopedTaskEnvironment task_environment_; content::TestMojoProxyResolverFactory test_mojo_proxy_resolver_factory_; TestNetworkDelegate network_delegate_; - LoggingMockHostResolver mock_host_resolver_; + net::MockHostResolver mock_host_resolver_; // Owned by |proxy_resolution_service_|. net::MockPacFileFetcher* fetcher_; net::TestNetLog net_log_; @@ -179,12 +165,11 @@ TEST_F(ProxyServiceMojoTest, DnsResolution) { net::ProxyInfo info; net::TestCompletionCallback callback; - net::BoundTestNetLog test_net_log; std::unique_ptr<net::ProxyResolutionService::Request> request; EXPECT_EQ(net::ERR_IO_PENDING, proxy_resolution_service_->ResolveProxy( GURL("http://foo"), std::string(), &info, callback.callback(), - &request, test_net_log.bound())); + &request, net::NetLogWithSource())); // PAC file fetcher should have a fetch triggered by the first // |ResolveProxy()| request. @@ -197,16 +182,6 @@ EXPECT_EQ("QUIC bar:4321", info.ToPacString()); EXPECT_EQ(1u, mock_host_resolver_.num_resolve()); proxy_resolution_service_.reset(); - - net::TestNetLogEntry::List entries; - test_net_log.GetEntries(&entries); - // There should be one entry with type TYPE_HOST_RESOLVER_IMPL_JOB. - EXPECT_EQ(1, - std::count_if(entries.begin(), entries.end(), - [](const net::TestNetLogEntry& entry) { - return entry.type == - net::NetLogEventType::HOST_RESOLVER_IMPL_JOB; - })); } TEST_F(ProxyServiceMojoTest, Error) {
diff --git a/content/test/test_document_interface_broker.cc b/content/test/test_document_interface_broker.cc new file mode 100644 index 0000000..7b7b009 --- /dev/null +++ b/content/test/test_document_interface_broker.cc
@@ -0,0 +1,26 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/test/test_document_interface_broker.h" + +namespace content { + +TestDocumentInterfaceBroker::TestDocumentInterfaceBroker( + blink::mojom::DocumentInterfaceBroker* document_interface_broker, + blink::mojom::DocumentInterfaceBrokerRequest request) + : real_broker_(document_interface_broker), + binding_(this, std::move(request)) {} + +TestDocumentInterfaceBroker::~TestDocumentInterfaceBroker() {} + +blink::mojom::DocumentInterfaceBroker* +TestDocumentInterfaceBroker::GetForwardingInterface() { + return real_broker_; +} + +void TestDocumentInterfaceBroker::Flush() { + binding_.FlushForTesting(); +} + +} // namespace content \ No newline at end of file
diff --git a/content/test/test_document_interface_broker.h b/content/test/test_document_interface_broker.h new file mode 100644 index 0000000..9b46789 --- /dev/null +++ b/content/test/test_document_interface_broker.h
@@ -0,0 +1,35 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_TEST_TEST_DOCUMENT_INTERFACE_BROKER_H_ +#define CONTENT_TEST_TEST_DOCUMENT_INTERFACE_BROKER_H_ + +#include <utility> + +#include "mojo/public/cpp/bindings/binding.h" +#include "third_party/blink/public/mojom/frame/document_interface_broker.mojom-test-utils.h" + +namespace content { +// This class can be subclassed to override specific methods of RenderFrame's +// DocumentInterfaceBroker in tests. The rest of the calls will be forwarded to +// the implementation passed to the constructor (typically returned by +// RenderFrame::GetDocumentInterfaceBroker()). +class TestDocumentInterfaceBroker + : public blink::mojom::DocumentInterfaceBrokerInterceptorForTesting { + public: + TestDocumentInterfaceBroker( + blink::mojom::DocumentInterfaceBroker* document_interface_broker, + blink::mojom::DocumentInterfaceBrokerRequest request); + ~TestDocumentInterfaceBroker() override; + blink::mojom::DocumentInterfaceBroker* GetForwardingInterface() override; + void Flush(); + + private: + blink::mojom::DocumentInterfaceBroker* real_broker_; + mojo::Binding<DocumentInterfaceBroker> binding_; +}; + +} // namespace content + +#endif // CONTENT_TEST_TEST_DOCUMENT_INTERFACE_BROKER_H_ \ No newline at end of file
diff --git a/device/gamepad/abstract_haptic_gamepad_unittest.cc b/device/gamepad/abstract_haptic_gamepad_unittest.cc index 5f03a24..129c814a 100644 --- a/device/gamepad/abstract_haptic_gamepad_unittest.cc +++ b/device/gamepad/abstract_haptic_gamepad_unittest.cc
@@ -122,7 +122,7 @@ EXPECT_EQ(1, gamepad_->set_vibration_count_); EXPECT_EQ(0, gamepad_->set_zero_vibration_count_); EXPECT_EQ(0, first_callback_count_); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_TRUE(scoped_task_environment_.NextTaskIsDelayed()); // Finish the effect. scoped_task_environment_.FastForwardBy(kPendingTaskDuration); @@ -134,7 +134,7 @@ EXPECT_EQ(1, first_callback_count_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete, first_callback_result_); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); } TEST_F(AbstractHapticGamepadTest, ResetVibrationTest) { @@ -153,7 +153,7 @@ EXPECT_EQ(1, first_callback_count_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete, first_callback_result_); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); } TEST_F(AbstractHapticGamepadTest, UnsupportedEffectTypeTest) { @@ -178,7 +178,7 @@ EXPECT_EQ(1, first_callback_count_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultNotSupported, first_callback_result_); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); } TEST_F(AbstractHapticGamepadTest, StartDelayTest) { @@ -199,7 +199,7 @@ EXPECT_EQ(0, gamepad_->set_vibration_count_); EXPECT_EQ(1, gamepad_->set_zero_vibration_count_); EXPECT_EQ(0, first_callback_count_); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_TRUE(scoped_task_environment_.NextTaskIsDelayed()); // Start vibration. scoped_task_environment_.FastForwardBy(kPendingTaskDuration); @@ -207,7 +207,7 @@ EXPECT_EQ(1, gamepad_->set_vibration_count_); EXPECT_EQ(1, gamepad_->set_zero_vibration_count_); EXPECT_EQ(0, first_callback_count_); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_TRUE(scoped_task_environment_.NextTaskIsDelayed()); // Finish the effect. scoped_task_environment_.FastForwardBy(kPendingTaskDuration); @@ -217,7 +217,7 @@ EXPECT_EQ(1, first_callback_count_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete, first_callback_result_); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); } TEST_F(AbstractHapticGamepadTest, ZeroStartDelayPreemptionTest) { @@ -252,7 +252,7 @@ EXPECT_EQ(0, second_callback_count_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultPreempted, first_callback_result_); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_TRUE(scoped_task_environment_.NextTaskIsDelayed()); // Finish the effect. scoped_task_environment_.FastForwardBy(kPendingTaskDuration); @@ -264,7 +264,7 @@ EXPECT_EQ(1, second_callback_count_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete, second_callback_result_); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); } TEST_F(AbstractHapticGamepadTest, NonZeroStartDelayPreemptionTest) { @@ -300,7 +300,7 @@ EXPECT_EQ(0, second_callback_count_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultPreempted, first_callback_result_); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_TRUE(scoped_task_environment_.NextTaskIsDelayed()); // Start vibration. scoped_task_environment_.FastForwardBy(kPendingTaskDuration); @@ -309,7 +309,7 @@ EXPECT_EQ(1, gamepad_->set_zero_vibration_count_); EXPECT_EQ(1, first_callback_count_); EXPECT_EQ(0, second_callback_count_); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_TRUE(scoped_task_environment_.NextTaskIsDelayed()); // Finish the effect. scoped_task_environment_.FastForwardBy(kPendingTaskDuration); @@ -322,7 +322,7 @@ first_callback_result_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete, second_callback_result_); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); } TEST_F(AbstractHapticGamepadTest, ResetVibrationPreemptionTest) { @@ -353,7 +353,7 @@ first_callback_result_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete, second_callback_result_); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); } } // namespace
diff --git a/device/gamepad/hid_haptic_gamepad_base_unittest.cc b/device/gamepad/hid_haptic_gamepad_base_unittest.cc index 923d011..899852c 100644 --- a/device/gamepad/hid_haptic_gamepad_base_unittest.cc +++ b/device/gamepad/hid_haptic_gamepad_base_unittest.cc
@@ -146,7 +146,7 @@ EXPECT_THAT(gamepad_->output_reports_, testing::ElementsAre(start_vibration_output_report_)); EXPECT_EQ(0, first_callback_count_); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_GT(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); // Finish the effect. scoped_task_environment_.FastForwardBy(kPendingTaskDuration); @@ -156,7 +156,7 @@ EXPECT_EQ(1, first_callback_count_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete, first_callback_result_); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); } TEST_F(HidHapticGamepadBaseTest, ResetVibrationTest) { @@ -174,7 +174,7 @@ EXPECT_EQ(1, first_callback_count_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete, first_callback_result_); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); } TEST_F(HidHapticGamepadBaseTest, ZeroVibrationTest) { @@ -191,7 +191,7 @@ EXPECT_THAT(gamepad_->output_reports_, testing::ElementsAre(stop_vibration_output_report_)); EXPECT_EQ(0, first_callback_count_); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_GT(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); // Finish the effect. scoped_task_environment_.FastForwardBy(kPendingTaskDuration); @@ -201,7 +201,7 @@ EXPECT_EQ(1, first_callback_count_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete, first_callback_result_); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); } TEST_F(HidHapticGamepadBaseTest, StartDelayTest) { @@ -219,7 +219,7 @@ EXPECT_THAT(gamepad_->output_reports_, testing::ElementsAre(stop_vibration_output_report_)); EXPECT_EQ(0, first_callback_count_); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_GT(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); // Start vibration. scoped_task_environment_.FastForwardBy(kPendingTaskDuration); @@ -228,7 +228,7 @@ testing::ElementsAre(stop_vibration_output_report_, start_vibration_output_report_)); EXPECT_EQ(0, first_callback_count_); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_GT(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); // Finish the effect. scoped_task_environment_.FastForwardBy(kPendingTaskDuration); @@ -239,7 +239,7 @@ EXPECT_EQ(1, first_callback_count_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete, first_callback_result_); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); } TEST_F(HidHapticGamepadBaseTest, ZeroStartDelayPreemptionTest) { @@ -269,7 +269,7 @@ EXPECT_EQ(0, second_callback_count_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultPreempted, first_callback_result_); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_GT(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); // Finish the effect. scoped_task_environment_.FastForwardBy(kPendingTaskDuration); @@ -280,7 +280,7 @@ EXPECT_EQ(1, second_callback_count_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete, second_callback_result_); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); } TEST_F(HidHapticGamepadBaseTest, NonZeroStartDelayPreemptionTest) { @@ -312,7 +312,7 @@ EXPECT_EQ(0, second_callback_count_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultPreempted, first_callback_result_); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_GT(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); // Start vibration. scoped_task_environment_.FastForwardBy(kPendingTaskDuration); @@ -322,7 +322,7 @@ start_vibration_output_report_)); EXPECT_EQ(1, first_callback_count_); EXPECT_EQ(0, second_callback_count_); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_GT(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); // Finish the effect. scoped_task_environment_.FastForwardBy(kPendingTaskDuration); @@ -334,7 +334,7 @@ EXPECT_EQ(1, second_callback_count_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete, second_callback_result_); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); } TEST_F(HidHapticGamepadBaseTest, ResetVibrationPreemptionTest) { @@ -363,7 +363,7 @@ first_callback_result_); EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete, second_callback_result_); - EXPECT_FALSE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_EQ(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); } } // namespace
diff --git a/docs/speed/perf_lab_platforms.md b/docs/speed/perf_lab_platforms.md index 68d437b..8e0e4a81 100644 --- a/docs/speed/perf_lab_platforms.md +++ b/docs/speed/perf_lab_platforms.md
@@ -7,6 +7,7 @@ ## Android * [android-go-perf](https://ci.chromium.org/buildbot/chromium.perf/android-go-perf/): Android O. + * [android-go_webview-perf](https://ci.chromium.org/buildbot/chromium.perf/android-go_webview-perf/): Android OPM1.171019.021. * [Android Nexus5 Perf](https://ci.chromium.org/buildbot/chromium.perf/Android%20Nexus5%20Perf/): Android KOT49H. * [android-nexus5x-perf](https://ci.chromium.org/buildbot/chromium.perf/android-nexus5x-perf/): Android MMB29Q. * [Android Nexus5X WebView Perf](https://ci.chromium.org/buildbot/chromium.perf/Android%20Nexus5X%20WebView%20Perf/): Android AOSP MOB30K.
diff --git a/extensions/browser/guest_view/mime_handler_view/mime_handler_view_browsertest.cc b/extensions/browser/guest_view/mime_handler_view/mime_handler_view_browsertest.cc index fb3ea07..9609791 100644 --- a/extensions/browser/guest_view/mime_handler_view/mime_handler_view_browsertest.cc +++ b/extensions/browser/guest_view/mime_handler_view/mime_handler_view_browsertest.cc
@@ -367,10 +367,6 @@ } IN_PROC_BROWSER_TEST_F(MimeHandlerViewTest, Iframe) { - // TODO(https://crbug.com/923051): Flaky in single process mash. - if (features::IsSingleProcessMash()) - return; - RunTest("test_iframe.html"); }
diff --git a/extensions/renderer/extension_frame_helper.cc b/extensions/renderer/extension_frame_helper.cc index 3a4b6ecd..dbd9ecb 100644 --- a/extensions/renderer/extension_frame_helper.cc +++ b/extensions/renderer/extension_frame_helper.cc
@@ -317,9 +317,8 @@ document_idle_callbacks_.push_back(callback); } -void ExtensionFrameHelper::DidStartProvisionalLoad( - blink::WebDocumentLoader* document_loader, - bool is_content_initiated) { +void ExtensionFrameHelper::ReadyToCommitNavigation( + blink::WebDocumentLoader* document_loader) { // New window created by chrome.app.window.create() must not start parsing the // document immediately. The chrome.app.window.create() callback (if any) // needs to be called prior to the new window's 'load' event. The parser will
diff --git a/extensions/renderer/extension_frame_helper.h b/extensions/renderer/extension_frame_helper.h index 5b804c3..d32c788 100644 --- a/extensions/renderer/extension_frame_helper.h +++ b/extensions/renderer/extension_frame_helper.h
@@ -123,8 +123,8 @@ // RenderFrameObserver implementation. void DidCreateDocumentElement() override; void DidCreateNewDocument() override; - void DidStartProvisionalLoad(blink::WebDocumentLoader* document_loader, - bool is_content_initiated) override; + void ReadyToCommitNavigation( + blink::WebDocumentLoader* document_loader) override; void DidCreateScriptContext(v8::Local<v8::Context>, int world_id) override; void WillReleaseScriptContext(v8::Local<v8::Context>, int world_id) override;
diff --git a/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container_base.h b/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container_base.h index f7e7d1a..ff386396 100644 --- a/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container_base.h +++ b/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container_base.h
@@ -71,6 +71,8 @@ void DidFinishLoading() override; protected: + MimeHandlerViewContainerBase(); + virtual void CreateMimeHandlerViewGuestIfNecessary(); virtual void OnRetryCreatingMimeHandlerViewGuest(int32_t element_instance_id); virtual void OnDestroyFrameContainer(int32_t element_instance_id);
diff --git a/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container_manager.cc b/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container_manager.cc index 5c24380..d4a52b4 100644 --- a/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container_manager.cc +++ b/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container_manager.cc
@@ -30,7 +30,8 @@ } MimeHandlerViewContainerManager::MimeHandlerViewContainerManager( - int32_t routing_id) {} + int32_t routing_id) + : render_frame_routing_id_(routing_id) {} MimeHandlerViewContainerManager::~MimeHandlerViewContainerManager() {} @@ -39,6 +40,16 @@ const std::string& mime_type, const std::string& view_id) { // TODO(ekaramad): Implement (https://crbug.com/659750). + auto* render_frame = + content::RenderFrame::FromRoutingID(render_frame_routing_id_); + if (!render_frame) + return; + DCHECK(MimeHandlerViewFrameContainer::IsSupportedMimeType(mime_type)); + auto* child = render_frame->GetWebFrame()->FirstChild(); + if (!child || child->IsWebRemoteFrame()) + return; + MimeHandlerViewFrameContainer::CreateWithFrame( + child->ToWebLocalFrame(), resource_url, mime_type, view_id); } } // namespace extensions
diff --git a/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container_manager.h b/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container_manager.h index 0033ccbb..3f3269c 100644 --- a/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container_manager.h +++ b/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container_manager.h
@@ -30,9 +30,7 @@ const std::string& view_id) override; private: - GURL resource_url_; - std::string mime_type_; - std::string view_id_; + const int32_t render_frame_routing_id_; DISALLOW_COPY_AND_ASSIGN(MimeHandlerViewContainerManager); };
diff --git a/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_frame_container.cc b/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_frame_container.cc index aafb1df..e5a5b56 100644 --- a/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_frame_container.cc +++ b/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_frame_container.cc
@@ -11,6 +11,7 @@ #include "content/public/common/webplugininfo.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_frame_observer.h" +#include "content/public/renderer/render_thread.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_frame.h" #include "third_party/blink/public/web/web_local_frame.h" @@ -19,15 +20,6 @@ namespace extensions { -namespace { - -bool IsSupportedMimeType(const std::string& mime_type) { - return mime_type == "text/pdf" || mime_type == "application/pdf" || - mime_type == "text/csv"; -} - -} // namespace - class MimeHandlerViewFrameContainer::RenderFrameLifetimeObserver : public content::RenderFrameObserver { public: @@ -54,6 +46,13 @@ container_->OnDestroyFrameContainer(container_->element_instance_id_); } +// static. +bool MimeHandlerViewFrameContainer::IsSupportedMimeType( + const std::string& mime_type) { + return mime_type == "text/pdf" || mime_type == "application/pdf" || + mime_type == "text/csv"; +} + // static bool MimeHandlerViewFrameContainer::Create( const blink::WebElement& plugin_element, @@ -77,6 +76,16 @@ element_instance_id); } +// static +void MimeHandlerViewFrameContainer::CreateWithFrame( + blink::WebLocalFrame* web_frame, + const GURL& resource_url, + const std::string& mime_type, + const std::string& view_id) { + new MimeHandlerViewFrameContainer(web_frame, resource_url, mime_type, + view_id); +} + MimeHandlerViewFrameContainer::MimeHandlerViewFrameContainer( const blink::WebElement& plugin_element, const GURL& resource_url, @@ -92,23 +101,27 @@ element_instance_id_(element_instance_id), render_frame_lifetime_observer_( new RenderFrameLifetimeObserver(GetEmbedderRenderFrame(), this)) { - is_embedded_ = IsEmbedded(); - if (is_embedded_) { - SendResourceRequest(); - } else { - // TODO(ekaramad): Currently the full page version gets the same treatment - // as the embedded version of MimeHandlerViewFrameContainer; they both send - // a request for the resource. The full page version however should not as - // there is already an intercepted stream for the navigation. Change the - // logic here to a) IsEmbedded() return false for full page, b) the current - // intercepted stream is used and no new URLRequest is sent for the - // resource, and c) ensure creation of MimeHandlerViewFrameContainer does - // not lead to its destruction right away or the Create() method above would - // incorrectly return |true|. Note that currently calling - // CreateMimeHandlerViewGuestIfNecessary() could lead to the destruction of - // |this| when |plugin_element| does not have a content frame. - NOTREACHED(); - } + is_embedded_ = true; + SendResourceRequest(); +} + +MimeHandlerViewFrameContainer::MimeHandlerViewFrameContainer( + blink::WebLocalFrame* web_local_frame, + const GURL& resource_url, + const std::string& mime_type, + const std::string& view_id) + : MimeHandlerViewContainerBase( + content::RenderFrame::FromWebFrame( + web_local_frame->Parent()->ToWebLocalFrame()), + content::WebPluginInfo(), + mime_type, + resource_url), + element_instance_id_(content::RenderThread::Get()->GenerateRoutingID()) { + is_embedded_ = false; + view_id_ = view_id; + plugin_frame_routing_id_ = + content::RenderFrame::FromWebFrame(web_local_frame)->GetRoutingID(); + MimeHandlerViewContainerBase::CreateMimeHandlerViewGuestIfNecessary(); } MimeHandlerViewFrameContainer::~MimeHandlerViewFrameContainer() {} @@ -149,7 +162,10 @@ } blink::WebFrame* MimeHandlerViewFrameContainer::GetContentFrame() const { - return blink::WebFrame::FromFrameOwnerElement(plugin_element_); + if (is_embedded_) + return blink::WebFrame::FromFrameOwnerElement(plugin_element_); + + return GetEmbedderRenderFrame()->GetWebFrame()->FirstChild(); } // mime_handler::BeforeUnloadControl implementation. @@ -159,13 +175,4 @@ // TODO(ekaramad): Implement. } -bool MimeHandlerViewFrameContainer::IsEmbedded() const { - // TODO(ekaramad): This is currently sending a request regardless of whether - // or not this embed is due to frame navigation to resource. For such cases, - // the renderer has already started a resource request and we should not send - // twice. Find a way to get the intercepted stream and avoid sending an extra - // request here. - return true; -} - } // namespace extensions
diff --git a/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_frame_container.h b/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_frame_container.h index 32e52ae1..4f1c8b7f 100644 --- a/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_frame_container.h +++ b/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_frame_container.h
@@ -13,6 +13,7 @@ namespace blink { class WebElement; class WebFrame; +class WebLocalFrame; } // namespace blink namespace content { @@ -26,6 +27,7 @@ // for an embedded MimeHandlerView extension in a cross-origin frame. class MimeHandlerViewFrameContainer : public MimeHandlerViewContainerBase { public: + static bool IsSupportedMimeType(const std::string& mime_type); static bool Create(const blink::WebElement& plugin_element, const GURL& resource_url, const std::string& mime_type, @@ -35,12 +37,24 @@ private: class RenderFrameLifetimeObserver; friend class RenderFrameLifetimeObserver; + friend class MimeHandlerViewContainerManager; + + static void CreateWithFrame(blink::WebLocalFrame* web_frame, + const GURL& resource_url, + const std::string& mime_type, + const std::string& view_id); + + MimeHandlerViewFrameContainer(blink::WebLocalFrame* web_frame, + const GURL& resource_url, + const std::string& mime_type, + const std::string& view_id); MimeHandlerViewFrameContainer(const blink::WebElement& plugin_element, const GURL& resource_url, const std::string& mime_type, const content::WebPluginInfo& plugin_info, int32_t element_instance_id); + ~MimeHandlerViewFrameContainer() override; // MimeHandlerViewContainerBase overrides. @@ -58,13 +72,6 @@ bool show_dialog, SetShowBeforeUnloadDialogCallback callback) override; - // Returns true if the container is considered as "embedded". A non-embedded - // MimeHandlerViewFrameContainer is the one which is created as a result of - // navigating a frame (either <iframe> or top-level) to a corresponding - // MimeHandlerView mimetype. For such containers there is no need to request - // the resource immediately. - bool IsEmbedded() const; - void OnMessageReceived(const IPC::Message& message); blink::WebElement plugin_element_;
diff --git a/fuchsia/engine/BUILD.gn b/fuchsia/engine/BUILD.gn index f3296743..1ebec46 100644 --- a/fuchsia/engine/BUILD.gn +++ b/fuchsia/engine/BUILD.gn
@@ -123,22 +123,22 @@ "browser/frame_impl.h", "browser/message_port_impl.cc", "browser/message_port_impl.h", + "browser/web_engine_browser_context.cc", + "browser/web_engine_browser_context.h", + "browser/web_engine_browser_main.cc", + "browser/web_engine_browser_main.h", + "browser/web_engine_browser_main_parts.cc", + "browser/web_engine_browser_main_parts.h", + "browser/web_engine_content_browser_client.cc", + "browser/web_engine_content_browser_client.h", "browser/web_engine_devtools_manager_delegate.cc", "browser/web_engine_devtools_manager_delegate.h", - "browser/webrunner_browser_context.cc", - "browser/webrunner_browser_context.h", - "browser/webrunner_browser_main.cc", - "browser/webrunner_browser_main.h", - "browser/webrunner_browser_main_parts.cc", - "browser/webrunner_browser_main_parts.h", - "browser/webrunner_content_browser_client.cc", - "browser/webrunner_content_browser_client.h", - "browser/webrunner_net_log.cc", - "browser/webrunner_net_log.h", - "browser/webrunner_screen.cc", - "browser/webrunner_screen.h", - "browser/webrunner_url_request_context_getter.cc", - "browser/webrunner_url_request_context_getter.h", + "browser/web_engine_net_log.cc", + "browser/web_engine_net_log.h", + "browser/web_engine_screen.cc", + "browser/web_engine_screen.h", + "browser/web_engine_url_request_context_getter.cc", + "browser/web_engine_url_request_context_getter.h", "common.cc", "common.h", "context_provider_impl.cc", @@ -147,13 +147,13 @@ "context_provider_main.h", "renderer/on_load_script_injector.cc", "renderer/on_load_script_injector.h", - "renderer/webrunner_content_renderer_client.cc", - "renderer/webrunner_content_renderer_client.h", + "renderer/web_engine_content_renderer_client.cc", + "renderer/web_engine_content_renderer_client.h", + "web_engine_content_client.cc", + "web_engine_content_client.h", "web_engine_export.h", - "webrunner_content_client.cc", - "webrunner_content_client.h", - "webrunner_main_delegate.cc", - "webrunner_main_delegate.h", + "web_engine_main_delegate.cc", + "web_engine_main_delegate.h", ] visibility = [ ":*" ] } @@ -166,7 +166,7 @@ "//services/service_manager/embedder:embedder_switches", ] sources = [ - "webrunner_main.cc", + "web_engine_main.cc", ] visibility = [ ":*" ] } @@ -190,9 +190,9 @@ source_set("browsertest_core") { testonly = true sources = [ - "test/webrunner_browser_test.cc", - "test/webrunner_browser_test.h", - "test/webrunner_test_launcher.cc", + "test/web_engine_browser_test.cc", + "test/web_engine_browser_test.h", + "test/web_engine_test_launcher.cc", ] deps = [ ":web_engine_core",
diff --git a/fuchsia/engine/browser/context_impl.cc b/fuchsia/engine/browser/context_impl.cc index 2d9c52d3..749177d 100644 --- a/fuchsia/engine/browser/context_impl.cc +++ b/fuchsia/engine/browser/context_impl.cc
@@ -19,8 +19,9 @@ void ContextImpl::CreateFrame( fidl::InterfaceRequest<chromium::web::Frame> frame_request) { - auto web_contents = content::WebContents::Create( - content::WebContents::CreateParams(browser_context_, nullptr)); + content::WebContents::CreateParams create_params(browser_context_, nullptr); + create_params.initially_hidden = true; + auto web_contents = content::WebContents::Create(create_params); frames_.insert(std::make_unique<FrameImpl>(std::move(web_contents), this, std::move(frame_request))); }
diff --git a/fuchsia/engine/browser/context_impl_browsertest.cc b/fuchsia/engine/browser/context_impl_browsertest.cc index 45ba94bfc..c708313 100644 --- a/fuchsia/engine/browser/context_impl_browsertest.cc +++ b/fuchsia/engine/browser/context_impl_browsertest.cc
@@ -14,7 +14,7 @@ #include "content/public/browser/storage_partition.h" #include "fuchsia/engine/common.h" #include "fuchsia/engine/test/test_common.h" -#include "fuchsia/engine/test/webrunner_browser_test.h" +#include "fuchsia/engine/test/web_engine_browser_test.h" #include "net/cookies/cookie_store.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" @@ -32,7 +32,7 @@ // Defines a suite of tests that exercise browser-level configuration and // functionality. -class ContextImplTest : public cr_fuchsia::test::WebRunnerBrowserTest { +class ContextImplTest : public cr_fuchsia::test::WebEngineBrowserTest { public: ContextImplTest() = default; ~ContextImplTest() = default; @@ -40,7 +40,7 @@ protected: // Creates a Frame with |navigation_observer_| attached. chromium::web::FramePtr CreateFrame() { - return WebRunnerBrowserTest::CreateFrame(&navigation_observer_); + return WebEngineBrowserTest::CreateFrame(&navigation_observer_); } // Synchronously gets a list of cookies for this BrowserContext.
diff --git a/fuchsia/engine/browser/frame_impl_browsertest.cc b/fuchsia/engine/browser/frame_impl_browsertest.cc index 1c98c815..7d4de43 100644 --- a/fuchsia/engine/browser/frame_impl_browsertest.cc +++ b/fuchsia/engine/browser/frame_impl_browsertest.cc
@@ -18,7 +18,7 @@ #include "fuchsia/engine/browser/frame_impl.h" #include "fuchsia/engine/common.h" #include "fuchsia/engine/test/test_common.h" -#include "fuchsia/engine/test/webrunner_browser_test.h" +#include "fuchsia/engine/test/web_engine_browser_test.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/url_request/url_request_context.h" @@ -51,7 +51,7 @@ // Defines a suite of tests that exercise Frame-level functionality, such as // navigation commands and page events. -class FrameImplTest : public cr_fuchsia::test::WebRunnerBrowserTest { +class FrameImplTest : public cr_fuchsia::test::WebEngineBrowserTest { public: FrameImplTest() : run_timeout_(TestTimeouts::action_timeout(), @@ -67,7 +67,7 @@ protected: // Creates a Frame with |navigation_observer_| attached. chromium::web::FramePtr CreateFrame() { - return WebRunnerBrowserTest::CreateFrame(&navigation_observer_); + return WebEngineBrowserTest::CreateFrame(&navigation_observer_); } // Navigates a |controller| to |url|, blocking until navigation is complete.
diff --git a/fuchsia/engine/browser/webrunner_browser_context.cc b/fuchsia/engine/browser/web_engine_browser_context.cc similarity index 68% rename from fuchsia/engine/browser/webrunner_browser_context.cc rename to fuchsia/engine/browser/web_engine_browser_context.cc index 3fae9fd..9e23a43 100644 --- a/fuchsia/engine/browser/webrunner_browser_context.cc +++ b/fuchsia/engine/browser/web_engine_browser_context.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "fuchsia/engine/browser/webrunner_browser_context.h" +#include "fuchsia/engine/browser/web_engine_browser_context.h" #include <memory> #include <utility> @@ -16,13 +16,13 @@ #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/resource_context.h" -#include "fuchsia/engine/browser/webrunner_net_log.h" -#include "fuchsia/engine/browser/webrunner_url_request_context_getter.h" +#include "fuchsia/engine/browser/web_engine_net_log.h" +#include "fuchsia/engine/browser/web_engine_url_request_context_getter.h" #include "fuchsia/engine/common.h" #include "net/url_request/url_request_context.h" #include "services/network/public/cpp/network_switches.h" -class WebRunnerBrowserContext::ResourceContext +class WebEngineBrowserContext::ResourceContext : public content::ResourceContext { public: ResourceContext() = default; @@ -32,21 +32,21 @@ DISALLOW_COPY_AND_ASSIGN(ResourceContext); }; -std::unique_ptr<WebRunnerNetLog> CreateNetLog() { - std::unique_ptr<WebRunnerNetLog> result; +std::unique_ptr<WebEngineNetLog> CreateNetLog() { + std::unique_ptr<WebEngineNetLog> result; const base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(network::switches::kLogNetLog)) { base::FilePath log_path = command_line->GetSwitchValuePath(network::switches::kLogNetLog); - result = std::make_unique<WebRunnerNetLog>(log_path); + result = std::make_unique<WebEngineNetLog>(log_path); } return result; } -WebRunnerBrowserContext::WebRunnerBrowserContext(bool force_incognito) +WebEngineBrowserContext::WebEngineBrowserContext(bool force_incognito) : net_log_(CreateNetLog()), resource_context_(new ResourceContext()) { if (!force_incognito) { base::PathService::Get(base::DIR_APP_DATA, &data_dir_path_); @@ -59,7 +59,7 @@ BrowserContext::Initialize(this, data_dir_path_); } -WebRunnerBrowserContext::~WebRunnerBrowserContext() { +WebEngineBrowserContext::~WebEngineBrowserContext() { NotifyWillBeDestroyed(this); if (resource_context_) { @@ -71,78 +71,78 @@ } std::unique_ptr<content::ZoomLevelDelegate> -WebRunnerBrowserContext::CreateZoomLevelDelegate( +WebEngineBrowserContext::CreateZoomLevelDelegate( const base::FilePath& partition_path) { return nullptr; } -base::FilePath WebRunnerBrowserContext::GetPath() const { +base::FilePath WebEngineBrowserContext::GetPath() const { return data_dir_path_; } -bool WebRunnerBrowserContext::IsOffTheRecord() const { +bool WebEngineBrowserContext::IsOffTheRecord() const { return data_dir_path_.empty(); } -content::ResourceContext* WebRunnerBrowserContext::GetResourceContext() { +content::ResourceContext* WebEngineBrowserContext::GetResourceContext() { return resource_context_.get(); } content::DownloadManagerDelegate* -WebRunnerBrowserContext::GetDownloadManagerDelegate() { +WebEngineBrowserContext::GetDownloadManagerDelegate() { NOTIMPLEMENTED(); return nullptr; } -content::BrowserPluginGuestManager* WebRunnerBrowserContext::GetGuestManager() { +content::BrowserPluginGuestManager* WebEngineBrowserContext::GetGuestManager() { return nullptr; } storage::SpecialStoragePolicy* -WebRunnerBrowserContext::GetSpecialStoragePolicy() { +WebEngineBrowserContext::GetSpecialStoragePolicy() { return nullptr; } content::PushMessagingService* -WebRunnerBrowserContext::GetPushMessagingService() { +WebEngineBrowserContext::GetPushMessagingService() { return nullptr; } content::SSLHostStateDelegate* -WebRunnerBrowserContext::GetSSLHostStateDelegate() { +WebEngineBrowserContext::GetSSLHostStateDelegate() { return nullptr; } content::PermissionControllerDelegate* -WebRunnerBrowserContext::GetPermissionControllerDelegate() { +WebEngineBrowserContext::GetPermissionControllerDelegate() { return nullptr; } content::ClientHintsControllerDelegate* -WebRunnerBrowserContext::GetClientHintsControllerDelegate() { +WebEngineBrowserContext::GetClientHintsControllerDelegate() { return nullptr; } content::BackgroundFetchDelegate* -WebRunnerBrowserContext::GetBackgroundFetchDelegate() { +WebEngineBrowserContext::GetBackgroundFetchDelegate() { return nullptr; } content::BackgroundSyncController* -WebRunnerBrowserContext::GetBackgroundSyncController() { +WebEngineBrowserContext::GetBackgroundSyncController() { return nullptr; } content::BrowsingDataRemoverDelegate* -WebRunnerBrowserContext::GetBrowsingDataRemoverDelegate() { +WebEngineBrowserContext::GetBrowsingDataRemoverDelegate() { return nullptr; } -net::URLRequestContextGetter* WebRunnerBrowserContext::CreateRequestContext( +net::URLRequestContextGetter* WebEngineBrowserContext::CreateRequestContext( content::ProtocolHandlerMap* protocol_handlers, content::URLRequestInterceptorScopedVector request_interceptors) { DCHECK(!url_request_getter_); - url_request_getter_ = new WebRunnerURLRequestContextGetter( + url_request_getter_ = new WebEngineURLRequestContextGetter( base::CreateSingleThreadTaskRunnerWithTraits( {content::BrowserThread::IO}), net_log_.get(), std::move(*protocol_handlers), @@ -151,7 +151,7 @@ } net::URLRequestContextGetter* -WebRunnerBrowserContext::CreateRequestContextForStoragePartition( +WebEngineBrowserContext::CreateRequestContextForStoragePartition( const base::FilePath& partition_path, bool in_memory, content::ProtocolHandlerMap* protocol_handlers, @@ -160,13 +160,13 @@ } net::URLRequestContextGetter* -WebRunnerBrowserContext::CreateMediaRequestContext() { +WebEngineBrowserContext::CreateMediaRequestContext() { DCHECK(url_request_getter_.get()); return url_request_getter_.get(); } net::URLRequestContextGetter* -WebRunnerBrowserContext::CreateMediaRequestContextForStoragePartition( +WebEngineBrowserContext::CreateMediaRequestContextForStoragePartition( const base::FilePath& partition_path, bool in_memory) { return nullptr;
diff --git a/fuchsia/engine/browser/webrunner_browser_context.h b/fuchsia/engine/browser/web_engine_browser_context.h similarity index 80% rename from fuchsia/engine/browser/webrunner_browser_context.h rename to fuchsia/engine/browser/web_engine_browser_context.h index e865dd93..00904b5 100644 --- a/fuchsia/engine/browser/webrunner_browser_context.h +++ b/fuchsia/engine/browser/web_engine_browser_context.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FUCHSIA_ENGINE_BROWSER_WEBRUNNER_BROWSER_CONTEXT_H_ -#define FUCHSIA_ENGINE_BROWSER_WEBRUNNER_BROWSER_CONTEXT_H_ +#ifndef FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_BROWSER_CONTEXT_H_ +#define FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_BROWSER_CONTEXT_H_ #include <memory> @@ -11,15 +11,15 @@ #include "base/macros.h" #include "content/public/browser/browser_context.h" -class WebRunnerNetLog; -class WebRunnerURLRequestContextGetter; +class WebEngineNetLog; +class WebEngineURLRequestContextGetter; -class WebRunnerBrowserContext : public content::BrowserContext { +class WebEngineBrowserContext : public content::BrowserContext { public: // |force_incognito|: If set, then this BrowserContext will run in incognito // mode even if /data is available. - explicit WebRunnerBrowserContext(bool force_incognito); - ~WebRunnerBrowserContext() override; + explicit WebEngineBrowserContext(bool force_incognito); + ~WebEngineBrowserContext() override; // BrowserContext implementation. std::unique_ptr<content::ZoomLevelDelegate> CreateZoomLevelDelegate( @@ -59,11 +59,11 @@ base::FilePath data_dir_path_; - std::unique_ptr<WebRunnerNetLog> net_log_; - scoped_refptr<WebRunnerURLRequestContextGetter> url_request_getter_; + std::unique_ptr<WebEngineNetLog> net_log_; + scoped_refptr<WebEngineURLRequestContextGetter> url_request_getter_; std::unique_ptr<ResourceContext> resource_context_; - DISALLOW_COPY_AND_ASSIGN(WebRunnerBrowserContext); + DISALLOW_COPY_AND_ASSIGN(WebEngineBrowserContext); }; -#endif // FUCHSIA_ENGINE_BROWSER_WEBRUNNER_BROWSER_CONTEXT_H_ +#endif // FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_BROWSER_CONTEXT_H_
diff --git a/fuchsia/engine/browser/webrunner_browser_main.cc b/fuchsia/engine/browser/web_engine_browser_main.cc similarity index 82% rename from fuchsia/engine/browser/webrunner_browser_main.cc rename to fuchsia/engine/browser/web_engine_browser_main.cc index ed2cd63b..175c9b0 100644 --- a/fuchsia/engine/browser/webrunner_browser_main.cc +++ b/fuchsia/engine/browser/web_engine_browser_main.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "fuchsia/engine/browser/webrunner_browser_main.h" +#include "fuchsia/engine/browser/web_engine_browser_main.h" #include <memory> @@ -10,7 +10,7 @@ #include "build/build_config.h" #include "content/public/browser/browser_main_runner.h" -int WebRunnerBrowserMain(const content::MainFunctionParams& parameters) { +int WebEngineBrowserMain(const content::MainFunctionParams& parameters) { std::unique_ptr<content::BrowserMainRunner> main_runner = content::BrowserMainRunner::Create(); int exit_code = main_runner->Initialize(parameters);
diff --git a/fuchsia/engine/browser/web_engine_browser_main.h b/fuchsia/engine/browser/web_engine_browser_main.h new file mode 100644 index 0000000..f70d9c38 --- /dev/null +++ b/fuchsia/engine/browser/web_engine_browser_main.h
@@ -0,0 +1,16 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_BROWSER_MAIN_H_ +#define FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_BROWSER_MAIN_H_ + +#include <memory> + +namespace content { +struct MainFunctionParams; +} // namespace content + +int WebEngineBrowserMain(const content::MainFunctionParams& parameters); + +#endif // FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_BROWSER_MAIN_H_
diff --git a/fuchsia/engine/browser/webrunner_browser_main_parts.cc b/fuchsia/engine/browser/web_engine_browser_main_parts.cc similarity index 80% rename from fuchsia/engine/browser/webrunner_browser_main_parts.cc rename to fuchsia/engine/browser/web_engine_browser_main_parts.cc index f77d44e..ad40fc259 100644 --- a/fuchsia/engine/browser/webrunner_browser_main_parts.cc +++ b/fuchsia/engine/browser/web_engine_browser_main_parts.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "fuchsia/engine/browser/webrunner_browser_main_parts.h" +#include "fuchsia/engine/browser/web_engine_browser_main_parts.h" #include <utility> @@ -12,21 +12,21 @@ #include "base/logging.h" #include "content/public/browser/render_frame_host.h" #include "fuchsia/engine/browser/context_impl.h" -#include "fuchsia/engine/browser/webrunner_browser_context.h" -#include "fuchsia/engine/browser/webrunner_screen.h" +#include "fuchsia/engine/browser/web_engine_browser_context.h" +#include "fuchsia/engine/browser/web_engine_screen.h" #include "fuchsia/engine/common.h" #include "ui/aura/screen_ozone.h" #include "ui/ozone/public/ozone_platform.h" -WebRunnerBrowserMainParts::WebRunnerBrowserMainParts( +WebEngineBrowserMainParts::WebEngineBrowserMainParts( zx::channel context_channel) : context_channel_(std::move(context_channel)) {} -WebRunnerBrowserMainParts::~WebRunnerBrowserMainParts() { +WebEngineBrowserMainParts::~WebEngineBrowserMainParts() { display::Screen::SetScreenInstance(nullptr); } -void WebRunnerBrowserMainParts::PreMainMessageLoopRun() { +void WebEngineBrowserMainParts::PreMainMessageLoopRun() { DCHECK(!screen_); auto platform_screen = ui::OzonePlatform::GetInstance()->CreateScreen(); @@ -35,13 +35,13 @@ } else { // Use dummy display::Screen for Ozone platforms that don't provide // PlatformScreen. - screen_ = std::make_unique<WebRunnerScreen>(); + screen_ = std::make_unique<WebEngineScreen>(); } display::Screen::SetScreenInstance(screen_.get()); DCHECK(!browser_context_); - browser_context_ = std::make_unique<WebRunnerBrowserContext>( + browser_context_ = std::make_unique<WebEngineBrowserContext>( base::CommandLine::ForCurrentProcess()->HasSwitch(kIncognitoSwitch)); context_service_ = std::make_unique<ContextImpl>(browser_context_.get()); @@ -64,12 +64,12 @@ content::RenderFrameHost::AllowInjectingJavaScript(); } -void WebRunnerBrowserMainParts::PreDefaultMainMessageLoopRun( +void WebEngineBrowserMainParts::PreDefaultMainMessageLoopRun( base::OnceClosure quit_closure) { quit_closure_ = std::move(quit_closure); } -void WebRunnerBrowserMainParts::PostMainMessageLoopRun() { +void WebEngineBrowserMainParts::PostMainMessageLoopRun() { // The service and its binding should have already been released by the error // handler. DCHECK(!context_service_);
diff --git a/fuchsia/engine/browser/webrunner_browser_main_parts.h b/fuchsia/engine/browser/web_engine_browser_main_parts.h similarity index 67% rename from fuchsia/engine/browser/webrunner_browser_main_parts.h rename to fuchsia/engine/browser/web_engine_browser_main_parts.h index dec6f065..3418b262 100644 --- a/fuchsia/engine/browser/webrunner_browser_main_parts.h +++ b/fuchsia/engine/browser/web_engine_browser_main_parts.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FUCHSIA_ENGINE_BROWSER_WEBRUNNER_BROWSER_MAIN_PARTS_H_ -#define FUCHSIA_ENGINE_BROWSER_WEBRUNNER_BROWSER_MAIN_PARTS_H_ +#ifndef FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_BROWSER_MAIN_PARTS_H_ +#define FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_BROWSER_MAIN_PARTS_H_ #include <lib/fidl/cpp/binding.h> #include <memory> @@ -12,17 +12,17 @@ #include "base/optional.h" #include "content/public/browser/browser_main_parts.h" #include "fuchsia/engine/browser/context_impl.h" -#include "fuchsia/engine/browser/webrunner_browser_context.h" +#include "fuchsia/engine/browser/web_engine_browser_context.h" #include "fuchsia/fidl/chromium/web/cpp/fidl.h" namespace display { class Screen; } -class WebRunnerBrowserMainParts : public content::BrowserMainParts { +class WebEngineBrowserMainParts : public content::BrowserMainParts { public: - explicit WebRunnerBrowserMainParts(zx::channel context_channel); - ~WebRunnerBrowserMainParts() override; + explicit WebEngineBrowserMainParts(zx::channel context_channel); + ~WebEngineBrowserMainParts() override; ContextImpl* context() const { return context_service_.get(); } content::BrowserContext* browser_context() const { @@ -38,13 +38,13 @@ zx::channel context_channel_; std::unique_ptr<display::Screen> screen_; - std::unique_ptr<WebRunnerBrowserContext> browser_context_; + std::unique_ptr<WebEngineBrowserContext> browser_context_; std::unique_ptr<ContextImpl> context_service_; std::unique_ptr<fidl::Binding<chromium::web::Context>> context_binding_; base::OnceClosure quit_closure_; - DISALLOW_COPY_AND_ASSIGN(WebRunnerBrowserMainParts); + DISALLOW_COPY_AND_ASSIGN(WebEngineBrowserMainParts); }; -#endif // FUCHSIA_ENGINE_BROWSER_WEBRUNNER_BROWSER_MAIN_PARTS_H_ +#endif // FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_BROWSER_MAIN_PARTS_H_
diff --git a/fuchsia/engine/browser/webrunner_content_browser_client.cc b/fuchsia/engine/browser/web_engine_content_browser_client.cc similarity index 60% rename from fuchsia/engine/browser/webrunner_content_browser_client.cc rename to fuchsia/engine/browser/web_engine_content_browser_client.cc index b799f4a..0744f3f 100644 --- a/fuchsia/engine/browser/webrunner_content_browser_client.cc +++ b/fuchsia/engine/browser/web_engine_content_browser_client.cc
@@ -2,42 +2,42 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "fuchsia/engine/browser/webrunner_content_browser_client.h" +#include "fuchsia/engine/browser/web_engine_content_browser_client.h" #include <utility> #include "components/version_info/version_info.h" #include "content/public/common/user_agent.h" +#include "fuchsia/engine/browser/web_engine_browser_context.h" +#include "fuchsia/engine/browser/web_engine_browser_main_parts.h" #include "fuchsia/engine/browser/web_engine_devtools_manager_delegate.h" -#include "fuchsia/engine/browser/webrunner_browser_context.h" -#include "fuchsia/engine/browser/webrunner_browser_main_parts.h" -WebRunnerContentBrowserClient::WebRunnerContentBrowserClient( +WebEngineContentBrowserClient::WebEngineContentBrowserClient( zx::channel context_channel) : context_channel_(std::move(context_channel)) {} -WebRunnerContentBrowserClient::~WebRunnerContentBrowserClient() = default; +WebEngineContentBrowserClient::~WebEngineContentBrowserClient() = default; content::BrowserMainParts* -WebRunnerContentBrowserClient::CreateBrowserMainParts( +WebEngineContentBrowserClient::CreateBrowserMainParts( const content::MainFunctionParams& parameters) { DCHECK(context_channel_); - main_parts_ = new WebRunnerBrowserMainParts(std::move(context_channel_)); + main_parts_ = new WebEngineBrowserMainParts(std::move(context_channel_)); return main_parts_; } content::DevToolsManagerDelegate* -WebRunnerContentBrowserClient::GetDevToolsManagerDelegate() { +WebEngineContentBrowserClient::GetDevToolsManagerDelegate() { DCHECK(main_parts_); DCHECK(main_parts_->browser_context()); return new WebEngineDevToolsManagerDelegate(main_parts_->browser_context()); } -std::string WebRunnerContentBrowserClient::GetProduct() const { +std::string WebEngineContentBrowserClient::GetProduct() const { return version_info::GetProductNameAndVersionForUserAgent(); } -std::string WebRunnerContentBrowserClient::GetUserAgent() const { +std::string WebEngineContentBrowserClient::GetUserAgent() const { return content::BuildUserAgentFromProduct( version_info::GetProductNameAndVersionForUserAgent()); }
diff --git a/fuchsia/engine/browser/web_engine_content_browser_client.h b/fuchsia/engine/browser/web_engine_content_browser_client.h new file mode 100644 index 0000000..3761923 --- /dev/null +++ b/fuchsia/engine/browser/web_engine_content_browser_client.h
@@ -0,0 +1,36 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_CONTENT_BROWSER_CLIENT_H_ +#define FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_CONTENT_BROWSER_CLIENT_H_ + +#include <lib/zx/channel.h> + +#include "base/macros.h" +#include "content/public/browser/content_browser_client.h" + +class WebEngineBrowserMainParts; + +class WebEngineContentBrowserClient : public content::ContentBrowserClient { + public: + explicit WebEngineContentBrowserClient(zx::channel context_channel); + ~WebEngineContentBrowserClient() override; + + WebEngineBrowserMainParts* main_parts_for_test() const { return main_parts_; } + + // ContentBrowserClient overrides. + content::BrowserMainParts* CreateBrowserMainParts( + const content::MainFunctionParams& parameters) override; + content::DevToolsManagerDelegate* GetDevToolsManagerDelegate() override; + std::string GetProduct() const override; + std::string GetUserAgent() const override; + + private: + zx::channel context_channel_; + WebEngineBrowserMainParts* main_parts_; + + DISALLOW_COPY_AND_ASSIGN(WebEngineContentBrowserClient); +}; + +#endif // FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_CONTENT_BROWSER_CLIENT_H_
diff --git a/fuchsia/engine/browser/webrunner_net_log.cc b/fuchsia/engine/browser/web_engine_net_log.cc similarity index 81% rename from fuchsia/engine/browser/webrunner_net_log.cc rename to fuchsia/engine/browser/web_engine_net_log.cc index de9c5ff..0926635 100644 --- a/fuchsia/engine/browser/webrunner_net_log.cc +++ b/fuchsia/engine/browser/web_engine_net_log.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "fuchsia/engine/browser/webrunner_net_log.h" +#include "fuchsia/engine/browser/web_engine_net_log.h" #include <string> #include <utility> @@ -17,7 +17,7 @@ namespace { -std::unique_ptr<base::DictionaryValue> GetWebRunnerConstants() { +std::unique_ptr<base::DictionaryValue> GetWebEngineConstants() { std::unique_ptr<base::DictionaryValue> constants_dict = net::GetNetConstants(); @@ -35,16 +35,16 @@ } // namespace -WebRunnerNetLog::WebRunnerNetLog(const base::FilePath& log_path) { +WebEngineNetLog::WebEngineNetLog(const base::FilePath& log_path) { if (!log_path.empty()) { net::NetLogCaptureMode capture_mode = net::NetLogCaptureMode::Default(); file_net_log_observer_ = net::FileNetLogObserver::CreateUnbounded( - log_path, GetWebRunnerConstants()); + log_path, GetWebEngineConstants()); file_net_log_observer_->StartObserving(this, capture_mode); } } -WebRunnerNetLog::~WebRunnerNetLog() { +WebEngineNetLog::~WebEngineNetLog() { if (file_net_log_observer_) file_net_log_observer_->StopObserving(nullptr, base::OnceClosure()); }
diff --git a/fuchsia/engine/browser/web_engine_net_log.h b/fuchsia/engine/browser/web_engine_net_log.h new file mode 100644 index 0000000..a052f15 --- /dev/null +++ b/fuchsia/engine/browser/web_engine_net_log.h
@@ -0,0 +1,32 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_NET_LOG_H_ +#define FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_NET_LOG_H_ + +#include <memory> + +#include "base/macros.h" +#include "net/log/net_log.h" + +namespace base { +class FilePath; +} // namespace base + +namespace net { +class FileNetLogObserver; +} // namespace net + +class WebEngineNetLog : public net::NetLog { + public: + explicit WebEngineNetLog(const base::FilePath& log_path); + ~WebEngineNetLog() override; + + private: + std::unique_ptr<net::FileNetLogObserver> file_net_log_observer_; + + DISALLOW_COPY_AND_ASSIGN(WebEngineNetLog); +}; + +#endif // FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_NET_LOG_H_
diff --git a/fuchsia/engine/browser/webrunner_screen.cc b/fuchsia/engine/browser/web_engine_screen.cc similarity index 71% rename from fuchsia/engine/browser/webrunner_screen.cc rename to fuchsia/engine/browser/web_engine_screen.cc index 98ff226..21be4b84 100644 --- a/fuchsia/engine/browser/webrunner_screen.cc +++ b/fuchsia/engine/browser/web_engine_screen.cc
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "fuchsia/engine/browser/webrunner_screen.h" +#include "fuchsia/engine/browser/web_engine_screen.h" #include "ui/display/display.h" -WebRunnerScreen::WebRunnerScreen() { +WebEngineScreen::WebEngineScreen() { const int64_t kDefaultDisplayId = 1; display::Display display(kDefaultDisplayId); ProcessDisplayChanged(display, /*is_primary=*/true); } -WebRunnerScreen::~WebRunnerScreen() = default; +WebEngineScreen::~WebEngineScreen() = default;
diff --git a/fuchsia/engine/browser/web_engine_screen.h b/fuchsia/engine/browser/web_engine_screen.h new file mode 100644 index 0000000..ac6289b --- /dev/null +++ b/fuchsia/engine/browser/web_engine_screen.h
@@ -0,0 +1,22 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_SCREEN_H_ +#define FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_SCREEN_H_ + +#include "base/macros.h" + +#include "ui/display/screen_base.h" + +// display::Screen implementation for WebEngine on Fuchsia. +class DISPLAY_EXPORT WebEngineScreen : public display::ScreenBase { + public: + WebEngineScreen(); + ~WebEngineScreen() override; + + private: + DISALLOW_COPY_AND_ASSIGN(WebEngineScreen); +}; + +#endif // FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_SCREEN_H_
diff --git a/fuchsia/engine/browser/webrunner_url_request_context_getter.cc b/fuchsia/engine/browser/web_engine_url_request_context_getter.cc similarity index 88% rename from fuchsia/engine/browser/webrunner_url_request_context_getter.cc rename to fuchsia/engine/browser/web_engine_url_request_context_getter.cc index 6347a5e..48a128b 100644 --- a/fuchsia/engine/browser/webrunner_url_request_context_getter.cc +++ b/fuchsia/engine/browser/web_engine_url_request_context_getter.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "fuchsia/engine/browser/webrunner_url_request_context_getter.h" +#include "fuchsia/engine/browser/web_engine_url_request_context_getter.h" #include <utility> @@ -14,7 +14,7 @@ #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_builder.h" -WebRunnerURLRequestContextGetter::WebRunnerURLRequestContextGetter( +WebEngineURLRequestContextGetter::WebEngineURLRequestContextGetter( scoped_refptr<base::SingleThreadTaskRunner> network_task_runner, net::NetLog* net_log, content::ProtocolHandlerMap protocol_handlers, @@ -26,10 +26,10 @@ request_interceptors_(std::move(request_interceptors)), data_dir_path_(data_dir_path) {} -WebRunnerURLRequestContextGetter::~WebRunnerURLRequestContextGetter() = default; +WebEngineURLRequestContextGetter::~WebEngineURLRequestContextGetter() = default; net::URLRequestContext* -WebRunnerURLRequestContextGetter::GetURLRequestContext() { +WebEngineURLRequestContextGetter::GetURLRequestContext() { if (!url_request_context_) { net::URLRequestContextBuilder builder; builder.set_net_log(net_log_); @@ -68,6 +68,6 @@ } scoped_refptr<base::SingleThreadTaskRunner> -WebRunnerURLRequestContextGetter::GetNetworkTaskRunner() const { +WebEngineURLRequestContextGetter::GetNetworkTaskRunner() const { return network_task_runner_; }
diff --git a/fuchsia/engine/browser/webrunner_url_request_context_getter.h b/fuchsia/engine/browser/web_engine_url_request_context_getter.h similarity index 75% rename from fuchsia/engine/browser/webrunner_url_request_context_getter.h rename to fuchsia/engine/browser/web_engine_url_request_context_getter.h index 0969560..9d501cdc 100644 --- a/fuchsia/engine/browser/webrunner_url_request_context_getter.h +++ b/fuchsia/engine/browser/web_engine_url_request_context_getter.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FUCHSIA_ENGINE_BROWSER_WEBRUNNER_URL_REQUEST_CONTEXT_GETTER_H_ -#define FUCHSIA_ENGINE_BROWSER_WEBRUNNER_URL_REQUEST_CONTEXT_GETTER_H_ +#ifndef FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_URL_REQUEST_CONTEXT_GETTER_H_ +#define FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_URL_REQUEST_CONTEXT_GETTER_H_ #include <memory> @@ -20,9 +20,9 @@ class ProxyConfigService; } // namespace net -class WebRunnerURLRequestContextGetter : public net::URLRequestContextGetter { +class WebEngineURLRequestContextGetter : public net::URLRequestContextGetter { public: - WebRunnerURLRequestContextGetter( + WebEngineURLRequestContextGetter( scoped_refptr<base::SingleThreadTaskRunner> network_task_runner, net::NetLog* net_log, content::ProtocolHandlerMap protocol_handlers, @@ -35,7 +35,7 @@ const override; protected: - ~WebRunnerURLRequestContextGetter() override; + ~WebEngineURLRequestContextGetter() override; private: scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_; @@ -47,7 +47,7 @@ content::URLRequestInterceptorScopedVector request_interceptors_; base::FilePath data_dir_path_; - DISALLOW_COPY_AND_ASSIGN(WebRunnerURLRequestContextGetter); + DISALLOW_COPY_AND_ASSIGN(WebEngineURLRequestContextGetter); }; -#endif // FUCHSIA_ENGINE_BROWSER_WEBRUNNER_URL_REQUEST_CONTEXT_GETTER_H_ +#endif // FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_URL_REQUEST_CONTEXT_GETTER_H_
diff --git a/fuchsia/engine/browser/webrunner_browser_main.h b/fuchsia/engine/browser/webrunner_browser_main.h deleted file mode 100644 index fa8db4f..0000000 --- a/fuchsia/engine/browser/webrunner_browser_main.h +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef FUCHSIA_ENGINE_BROWSER_WEBRUNNER_BROWSER_MAIN_H_ -#define FUCHSIA_ENGINE_BROWSER_WEBRUNNER_BROWSER_MAIN_H_ - -#include <memory> - -namespace content { -struct MainFunctionParams; -} // namespace content - -int WebRunnerBrowserMain(const content::MainFunctionParams& parameters); - -#endif // FUCHSIA_ENGINE_BROWSER_WEBRUNNER_BROWSER_MAIN_H_
diff --git a/fuchsia/engine/browser/webrunner_content_browser_client.h b/fuchsia/engine/browser/webrunner_content_browser_client.h deleted file mode 100644 index 5a778d7..0000000 --- a/fuchsia/engine/browser/webrunner_content_browser_client.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef FUCHSIA_ENGINE_BROWSER_WEBRUNNER_CONTENT_BROWSER_CLIENT_H_ -#define FUCHSIA_ENGINE_BROWSER_WEBRUNNER_CONTENT_BROWSER_CLIENT_H_ - -#include <lib/zx/channel.h> - -#include "base/macros.h" -#include "content/public/browser/content_browser_client.h" - -class WebRunnerBrowserMainParts; - -class WebRunnerContentBrowserClient : public content::ContentBrowserClient { - public: - explicit WebRunnerContentBrowserClient(zx::channel context_channel); - ~WebRunnerContentBrowserClient() override; - - WebRunnerBrowserMainParts* main_parts_for_test() const { return main_parts_; } - - // ContentBrowserClient overrides. - content::BrowserMainParts* CreateBrowserMainParts( - const content::MainFunctionParams& parameters) override; - content::DevToolsManagerDelegate* GetDevToolsManagerDelegate() override; - std::string GetProduct() const override; - std::string GetUserAgent() const override; - - private: - zx::channel context_channel_; - WebRunnerBrowserMainParts* main_parts_; - - DISALLOW_COPY_AND_ASSIGN(WebRunnerContentBrowserClient); -}; - -#endif // FUCHSIA_ENGINE_BROWSER_WEBRUNNER_CONTENT_BROWSER_CLIENT_H_
diff --git a/fuchsia/engine/browser/webrunner_net_log.h b/fuchsia/engine/browser/webrunner_net_log.h deleted file mode 100644 index 997af52..0000000 --- a/fuchsia/engine/browser/webrunner_net_log.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef FUCHSIA_ENGINE_BROWSER_WEBRUNNER_NET_LOG_H_ -#define FUCHSIA_ENGINE_BROWSER_WEBRUNNER_NET_LOG_H_ - -#include <memory> - -#include "base/macros.h" -#include "net/log/net_log.h" - -namespace base { -class FilePath; -} // namespace base - -namespace net { -class FileNetLogObserver; -} // namespace net - -class WebRunnerNetLog : public net::NetLog { - public: - explicit WebRunnerNetLog(const base::FilePath& log_path); - ~WebRunnerNetLog() override; - - private: - std::unique_ptr<net::FileNetLogObserver> file_net_log_observer_; - - DISALLOW_COPY_AND_ASSIGN(WebRunnerNetLog); -}; - -#endif // FUCHSIA_ENGINE_BROWSER_WEBRUNNER_NET_LOG_H_
diff --git a/fuchsia/engine/browser/webrunner_screen.h b/fuchsia/engine/browser/webrunner_screen.h deleted file mode 100644 index baa27d7..0000000 --- a/fuchsia/engine/browser/webrunner_screen.h +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef FUCHSIA_ENGINE_BROWSER_WEBRUNNER_SCREEN_H_ -#define FUCHSIA_ENGINE_BROWSER_WEBRUNNER_SCREEN_H_ - -#include "base/macros.h" - -#include "ui/display/screen_base.h" - -// display::Screen implementation for WebRunner on Fuchsia. -class DISPLAY_EXPORT WebRunnerScreen : public display::ScreenBase { - public: - WebRunnerScreen(); - ~WebRunnerScreen() override; - - private: - DISALLOW_COPY_AND_ASSIGN(WebRunnerScreen); -}; - -#endif // FUCHSIA_ENGINE_BROWSER_WEBRUNNER_SCREEN_H_
diff --git a/fuchsia/engine/renderer/webrunner_content_renderer_client.cc b/fuchsia/engine/renderer/web_engine_content_renderer_client.cc similarity index 67% rename from fuchsia/engine/renderer/webrunner_content_renderer_client.cc rename to fuchsia/engine/renderer/web_engine_content_renderer_client.cc index 36ae235..ebe11bf 100644 --- a/fuchsia/engine/renderer/webrunner_content_renderer_client.cc +++ b/fuchsia/engine/renderer/web_engine_content_renderer_client.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "fuchsia/engine/renderer/webrunner_content_renderer_client.h" +#include "fuchsia/engine/renderer/web_engine_content_renderer_client.h" #include "base/macros.h" #include "content/public/renderer/render_frame.h" @@ -10,13 +10,13 @@ #include "services/service_manager/public/cpp/binder_registry.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" -WebRunnerContentRendererClient::WebRunnerContentRendererClient() = default; +WebEngineContentRendererClient::WebEngineContentRendererClient() = default; -WebRunnerContentRendererClient::~WebRunnerContentRendererClient() = default; +WebEngineContentRendererClient::~WebEngineContentRendererClient() = default; -void WebRunnerContentRendererClient::RenderFrameCreated( +void WebEngineContentRendererClient::RenderFrameCreated( content::RenderFrame* render_frame) { - // Add WebRunner services to the new RenderFrame. + // Add WebEngine services to the new RenderFrame. // The objects' lifetimes are bound to the RenderFrame's lifetime. new OnLoadScriptInjector(render_frame); }
diff --git a/fuchsia/engine/renderer/web_engine_content_renderer_client.h b/fuchsia/engine/renderer/web_engine_content_renderer_client.h new file mode 100644 index 0000000..40bad6d --- /dev/null +++ b/fuchsia/engine/renderer/web_engine_content_renderer_client.h
@@ -0,0 +1,23 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FUCHSIA_ENGINE_RENDERER_WEB_ENGINE_CONTENT_RENDERER_CLIENT_H_ +#define FUCHSIA_ENGINE_RENDERER_WEB_ENGINE_CONTENT_RENDERER_CLIENT_H_ + +#include "base/macros.h" +#include "content/public/renderer/content_renderer_client.h" + +class WebEngineContentRendererClient : public content::ContentRendererClient { + public: + WebEngineContentRendererClient(); + ~WebEngineContentRendererClient() override; + + // content::ContentRendererClient overrides. + void RenderFrameCreated(content::RenderFrame* render_frame) override; + + private: + DISALLOW_COPY_AND_ASSIGN(WebEngineContentRendererClient); +}; + +#endif // FUCHSIA_ENGINE_RENDERER_WEB_ENGINE_CONTENT_RENDERER_CLIENT_H_
diff --git a/fuchsia/engine/renderer/webrunner_content_renderer_client.h b/fuchsia/engine/renderer/webrunner_content_renderer_client.h deleted file mode 100644 index 89ce455..0000000 --- a/fuchsia/engine/renderer/webrunner_content_renderer_client.h +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef FUCHSIA_ENGINE_RENDERER_WEBRUNNER_CONTENT_RENDERER_CLIENT_H_ -#define FUCHSIA_ENGINE_RENDERER_WEBRUNNER_CONTENT_RENDERER_CLIENT_H_ - -#include "base/macros.h" -#include "content/public/renderer/content_renderer_client.h" - -class WebRunnerContentRendererClient : public content::ContentRendererClient { - public: - WebRunnerContentRendererClient(); - ~WebRunnerContentRendererClient() override; - - // content::ContentRendererClient overrides. - void RenderFrameCreated(content::RenderFrame* render_frame) override; - - private: - DISALLOW_COPY_AND_ASSIGN(WebRunnerContentRendererClient); -}; - -#endif // FUCHSIA_ENGINE_RENDERER_WEBRUNNER_CONTENT_RENDERER_CLIENT_H_
diff --git a/fuchsia/engine/test/webrunner_browser_test.cc b/fuchsia/engine/test/web_engine_browser_test.cc similarity index 66% rename from fuchsia/engine/test/webrunner_browser_test.cc rename to fuchsia/engine/test/web_engine_browser_test.cc index bce5a62..f3b54898 100644 --- a/fuchsia/engine/test/webrunner_browser_test.cc +++ b/fuchsia/engine/test/web_engine_browser_test.cc
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "fuchsia/engine/test/webrunner_browser_test.h" +#include "fuchsia/engine/test/web_engine_browser_test.h" #include "base/fuchsia/fuchsia_logging.h" -#include "fuchsia/engine/browser/webrunner_browser_context.h" -#include "fuchsia/engine/browser/webrunner_browser_main_parts.h" -#include "fuchsia/engine/browser/webrunner_content_browser_client.h" -#include "fuchsia/engine/webrunner_main_delegate.h" +#include "fuchsia/engine/browser/web_engine_browser_context.h" +#include "fuchsia/engine/browser/web_engine_browser_main_parts.h" +#include "fuchsia/engine/browser/web_engine_content_browser_client.h" +#include "fuchsia/engine/web_engine_main_delegate.h" #include "net/test/embedded_test_server/default_handlers.h" namespace cr_fuchsia { @@ -18,11 +18,11 @@ zx_handle_t g_context_channel = ZX_HANDLE_INVALID; } // namespace -WebRunnerBrowserTest::WebRunnerBrowserTest() = default; +WebEngineBrowserTest::WebEngineBrowserTest() = default; -WebRunnerBrowserTest::~WebRunnerBrowserTest() = default; +WebEngineBrowserTest::~WebEngineBrowserTest() = default; -void WebRunnerBrowserTest::PreRunTestOnMainThread() { +void WebEngineBrowserTest::PreRunTestOnMainThread() { zx_status_t result = context_.Bind(zx::channel(g_context_channel)); ZX_DCHECK(result == ZX_OK, result) << "Context::Bind"; g_context_channel = ZX_HANDLE_INVALID; @@ -33,16 +33,16 @@ } } -void WebRunnerBrowserTest::PostRunTestOnMainThread() { +void WebEngineBrowserTest::PostRunTestOnMainThread() { // Unbind the Context while the message loops are still alive. context_.Unbind(); } -void WebRunnerBrowserTest::TearDownOnMainThread() { +void WebEngineBrowserTest::TearDownOnMainThread() { navigation_observer_bindings_.CloseAll(); } -chromium::web::FramePtr WebRunnerBrowserTest::CreateFrame( +chromium::web::FramePtr WebEngineBrowserTest::CreateFrame( chromium::web::NavigationEventObserver* observer) { chromium::web::FramePtr frame; context_->CreateFrame(frame.NewRequest()); @@ -62,13 +62,13 @@ } // static -void WebRunnerBrowserTest::SetContextClientChannel(zx::channel channel) { +void WebEngineBrowserTest::SetContextClientChannel(zx::channel channel) { DCHECK(channel); g_context_channel = channel.release(); } -ContextImpl* WebRunnerBrowserTest::context_impl() const { - return WebRunnerMainDelegate::GetInstanceForTest() +ContextImpl* WebEngineBrowserTest::context_impl() const { + return WebEngineMainDelegate::GetInstanceForTest() ->browser_client() ->main_parts_for_test() ->context();
diff --git a/fuchsia/engine/test/webrunner_browser_test.h b/fuchsia/engine/test/web_engine_browser_test.h similarity index 79% rename from fuchsia/engine/test/webrunner_browser_test.h rename to fuchsia/engine/test/web_engine_browser_test.h index d58e42a7..ad20a16 100644 --- a/fuchsia/engine/test/webrunner_browser_test.h +++ b/fuchsia/engine/test/web_engine_browser_test.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FUCHSIA_ENGINE_TEST_WEBRUNNER_BROWSER_TEST_H_ -#define FUCHSIA_ENGINE_TEST_WEBRUNNER_BROWSER_TEST_H_ +#ifndef FUCHSIA_ENGINE_TEST_WEB_ENGINE_BROWSER_TEST_H_ +#define FUCHSIA_ENGINE_TEST_WEB_ENGINE_BROWSER_TEST_H_ #include <lib/fidl/cpp/binding_set.h> #include <memory> @@ -18,15 +18,15 @@ namespace cr_fuchsia { namespace test { -// Base test class used for testing the WebRunner Context FIDL service in +// Base test class used for testing the WebEngine Context FIDL service in // integration. -class WebRunnerBrowserTest : public content::BrowserTestBase { +class WebEngineBrowserTest : public content::BrowserTestBase { public: - WebRunnerBrowserTest(); - ~WebRunnerBrowserTest() override; + WebEngineBrowserTest(); + ~WebEngineBrowserTest() override; // Sets the Context client channel which will be bound to a Context FIDL - // object by WebRunnerBrowserTest. + // object by WebEngineBrowserTest. static void SetContextClientChannel(zx::channel channel); // Creates a Frame for this Context. @@ -60,10 +60,10 @@ fidl::BindingSet<chromium::web::NavigationEventObserver> navigation_observer_bindings_; - DISALLOW_COPY_AND_ASSIGN(WebRunnerBrowserTest); + DISALLOW_COPY_AND_ASSIGN(WebEngineBrowserTest); }; } // namespace test } // namespace cr_fuchsia -#endif // FUCHSIA_ENGINE_TEST_WEBRUNNER_BROWSER_TEST_H_ +#endif // FUCHSIA_ENGINE_TEST_WEB_ENGINE_BROWSER_TEST_H_
diff --git a/fuchsia/engine/test/webrunner_test_launcher.cc b/fuchsia/engine/test/web_engine_test_launcher.cc similarity index 79% rename from fuchsia/engine/test/webrunner_test_launcher.cc rename to fuchsia/engine/test/web_engine_test_launcher.cc index bc72cdc..6d5711cd 100644 --- a/fuchsia/engine/test/webrunner_test_launcher.cc +++ b/fuchsia/engine/test/web_engine_test_launcher.cc
@@ -10,8 +10,8 @@ #include "content/public/common/content_switches.h" #include "content/public/test/test_launcher.h" #include "fuchsia/engine/common.h" -#include "fuchsia/engine/test/webrunner_browser_test.h" -#include "fuchsia/engine/webrunner_main_delegate.h" +#include "fuchsia/engine/test/web_engine_browser_test.h" +#include "fuchsia/engine/web_engine_main_delegate.h" #include "fuchsia/fidl/chromium/web/cpp/fidl.h" #include "ui/ozone/public/ozone_switches.h" @@ -20,10 +20,10 @@ namespace { -class WebRunnerTestLauncherDelegate : public content::TestLauncherDelegate { +class WebEngineTestLauncherDelegate : public content::TestLauncherDelegate { public: - WebRunnerTestLauncherDelegate() = default; - ~WebRunnerTestLauncherDelegate() override = default; + WebEngineTestLauncherDelegate() = default; + ~WebEngineTestLauncherDelegate() override = default; // content::TestLauncherDelegate implementation: int RunTestSuite(int argc, char** argv) override { @@ -47,15 +47,15 @@ zx_status_t result = zx::channel::create(0, &client_channel, &server_channel); ZX_CHECK(result == ZX_OK, result) << "zx::channel::create"; - WebRunnerBrowserTest::SetContextClientChannel(std::move(client_channel)); + WebEngineBrowserTest::SetContextClientChannel(std::move(client_channel)); - return new WebRunnerMainDelegate(std::move(server_channel)); + return new WebEngineMainDelegate(std::move(server_channel)); } private: chromium::web::ContextPtr context_; - DISALLOW_COPY_AND_ASSIGN(WebRunnerTestLauncherDelegate); + DISALLOW_COPY_AND_ASSIGN(WebEngineTestLauncherDelegate); }; } // namespace @@ -73,6 +73,6 @@ if (parallel_jobs > 1U) { parallel_jobs /= 2U; } - cr_fuchsia::test::WebRunnerTestLauncherDelegate launcher_delegate; + cr_fuchsia::test::WebEngineTestLauncherDelegate launcher_delegate; return LaunchTests(&launcher_delegate, parallel_jobs, argc, argv); }
diff --git a/fuchsia/engine/webrunner_content_client.cc b/fuchsia/engine/web_engine_content_client.cc similarity index 62% rename from fuchsia/engine/webrunner_content_client.cc rename to fuchsia/engine/web_engine_content_client.cc index 6d2d961d..b929d730 100644 --- a/fuchsia/engine/webrunner_content_client.cc +++ b/fuchsia/engine/web_engine_content_client.cc
@@ -2,37 +2,37 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "fuchsia/engine/webrunner_content_client.h" +#include "fuchsia/engine/web_engine_content_client.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" -WebRunnerContentClient::WebRunnerContentClient() = default; -WebRunnerContentClient::~WebRunnerContentClient() = default; +WebEngineContentClient::WebEngineContentClient() = default; +WebEngineContentClient::~WebEngineContentClient() = default; -base::string16 WebRunnerContentClient::GetLocalizedString( +base::string16 WebEngineContentClient::GetLocalizedString( int message_id) const { return l10n_util::GetStringUTF16(message_id); } -base::StringPiece WebRunnerContentClient::GetDataResource( +base::StringPiece WebEngineContentClient::GetDataResource( int resource_id, ui::ScaleFactor scale_factor) const { return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale( resource_id, scale_factor); } -base::RefCountedMemory* WebRunnerContentClient::GetDataResourceBytes( +base::RefCountedMemory* WebEngineContentClient::GetDataResourceBytes( int resource_id) const { return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes( resource_id); } -gfx::Image& WebRunnerContentClient::GetNativeImageNamed(int resource_id) const { +gfx::Image& WebEngineContentClient::GetNativeImageNamed(int resource_id) const { return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed( resource_id); } -blink::OriginTrialPolicy* WebRunnerContentClient::GetOriginTrialPolicy() { +blink::OriginTrialPolicy* WebEngineContentClient::GetOriginTrialPolicy() { NOTIMPLEMENTED_LOG_ONCE(); return nullptr; }
diff --git a/fuchsia/engine/webrunner_content_client.h b/fuchsia/engine/web_engine_content_client.h similarity index 67% rename from fuchsia/engine/webrunner_content_client.h rename to fuchsia/engine/web_engine_content_client.h index 780c226..58fef83 100644 --- a/fuchsia/engine/webrunner_content_client.h +++ b/fuchsia/engine/web_engine_content_client.h
@@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FUCHSIA_ENGINE_WEBRUNNER_CONTENT_CLIENT_H_ -#define FUCHSIA_ENGINE_WEBRUNNER_CONTENT_CLIENT_H_ +#ifndef FUCHSIA_ENGINE_WEB_ENGINE_CONTENT_CLIENT_H_ +#define FUCHSIA_ENGINE_WEB_ENGINE_CONTENT_CLIENT_H_ #include "base/macros.h" #include "content/public/common/content_client.h" -class WebRunnerContentClient : public content::ContentClient { +class WebEngineContentClient : public content::ContentClient { public: - WebRunnerContentClient(); - ~WebRunnerContentClient() override; + WebEngineContentClient(); + ~WebEngineContentClient() override; // content::ContentClient implementation. base::string16 GetLocalizedString(int message_id) const override; @@ -23,7 +23,7 @@ blink::OriginTrialPolicy* GetOriginTrialPolicy() override; private: - DISALLOW_COPY_AND_ASSIGN(WebRunnerContentClient); + DISALLOW_COPY_AND_ASSIGN(WebEngineContentClient); }; -#endif // FUCHSIA_ENGINE_WEBRUNNER_CONTENT_CLIENT_H_ +#endif // FUCHSIA_ENGINE_WEB_ENGINE_CONTENT_CLIENT_H_
diff --git a/fuchsia/engine/webrunner_main.cc b/fuchsia/engine/web_engine_main.cc similarity index 92% rename from fuchsia/engine/webrunner_main.cc rename to fuchsia/engine/web_engine_main.cc index c439750..8849927 100644 --- a/fuchsia/engine/webrunner_main.cc +++ b/fuchsia/engine/web_engine_main.cc
@@ -8,7 +8,7 @@ #include "content/public/app/content_main.h" #include "fuchsia/engine/common.h" #include "fuchsia/engine/context_provider_main.h" -#include "fuchsia/engine/webrunner_main_delegate.h" +#include "fuchsia/engine/web_engine_main_delegate.h" #include "services/service_manager/embedder/switches.h" int main(int argc, const char** argv) { @@ -32,7 +32,7 @@ return ContextProviderMain(); } - WebRunnerMainDelegate delegate(std::move(context_channel)); + WebEngineMainDelegate delegate(std::move(context_channel)); content::ContentMainParams params(&delegate); // Repeated base::CommandLine::Init() is ignored, so it's safe to pass null
diff --git a/fuchsia/engine/webrunner_main_delegate.cc b/fuchsia/engine/web_engine_main_delegate.cc similarity index 65% rename from fuchsia/engine/webrunner_main_delegate.cc rename to fuchsia/engine/web_engine_main_delegate.cc index ed0664a9..a9044e3b1 100644 --- a/fuchsia/engine/webrunner_main_delegate.cc +++ b/fuchsia/engine/web_engine_main_delegate.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "fuchsia/engine/webrunner_main_delegate.h" +#include "fuchsia/engine/web_engine_main_delegate.h" #include <utility> @@ -10,16 +10,16 @@ #include "base/command_line.h" #include "base/path_service.h" #include "content/public/common/content_switches.h" -#include "fuchsia/engine/browser/webrunner_browser_main.h" -#include "fuchsia/engine/browser/webrunner_content_browser_client.h" +#include "fuchsia/engine/browser/web_engine_browser_main.h" +#include "fuchsia/engine/browser/web_engine_content_browser_client.h" #include "fuchsia/engine/common.h" -#include "fuchsia/engine/renderer/webrunner_content_renderer_client.h" -#include "fuchsia/engine/webrunner_content_client.h" +#include "fuchsia/engine/renderer/web_engine_content_renderer_client.h" +#include "fuchsia/engine/web_engine_content_client.h" #include "ui/base/resource/resource_bundle.h" namespace { -WebRunnerMainDelegate* g_current_webrunner_main_delegate = nullptr; +WebEngineMainDelegate* g_current_web_engine_main_delegate = nullptr; void InitLoggingFromCommandLine(const base::CommandLine& command_line) { base::FilePath log_filename; @@ -51,48 +51,48 @@ } // namespace // static -WebRunnerMainDelegate* WebRunnerMainDelegate::GetInstanceForTest() { - return g_current_webrunner_main_delegate; +WebEngineMainDelegate* WebEngineMainDelegate::GetInstanceForTest() { + return g_current_web_engine_main_delegate; } -WebRunnerMainDelegate::WebRunnerMainDelegate(zx::channel context_channel) +WebEngineMainDelegate::WebEngineMainDelegate(zx::channel context_channel) : context_channel_(std::move(context_channel)) { - g_current_webrunner_main_delegate = this; + g_current_web_engine_main_delegate = this; } -WebRunnerMainDelegate::~WebRunnerMainDelegate() = default; +WebEngineMainDelegate::~WebEngineMainDelegate() = default; -bool WebRunnerMainDelegate::BasicStartupComplete(int* exit_code) { +bool WebEngineMainDelegate::BasicStartupComplete(int* exit_code) { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); InitLoggingFromCommandLine(*command_line); - content_client_ = std::make_unique<WebRunnerContentClient>(); + content_client_ = std::make_unique<WebEngineContentClient>(); SetContentClient(content_client_.get()); return false; } -void WebRunnerMainDelegate::PreSandboxStartup() { +void WebEngineMainDelegate::PreSandboxStartup() { InitializeResourceBundle(); } -int WebRunnerMainDelegate::RunProcess( +int WebEngineMainDelegate::RunProcess( const std::string& process_type, const content::MainFunctionParams& main_function_params) { if (!process_type.empty()) return -1; - return WebRunnerBrowserMain(main_function_params); + return WebEngineBrowserMain(main_function_params); } content::ContentBrowserClient* -WebRunnerMainDelegate::CreateContentBrowserClient() { +WebEngineMainDelegate::CreateContentBrowserClient() { DCHECK(!browser_client_); - browser_client_ = std::make_unique<WebRunnerContentBrowserClient>( + browser_client_ = std::make_unique<WebEngineContentBrowserClient>( std::move(context_channel_)); return browser_client_.get(); } content::ContentRendererClient* -WebRunnerMainDelegate::CreateContentRendererClient() { - renderer_client_ = std::make_unique<WebRunnerContentRendererClient>(); +WebEngineMainDelegate::CreateContentRendererClient() { + renderer_client_ = std::make_unique<WebEngineContentRendererClient>(); return renderer_client_.get(); }
diff --git a/fuchsia/engine/webrunner_main_delegate.h b/fuchsia/engine/web_engine_main_delegate.h similarity index 61% rename from fuchsia/engine/webrunner_main_delegate.h rename to fuchsia/engine/web_engine_main_delegate.h index e336901c..e99b787 100644 --- a/fuchsia/engine/webrunner_main_delegate.h +++ b/fuchsia/engine/web_engine_main_delegate.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FUCHSIA_ENGINE_WEBRUNNER_MAIN_DELEGATE_H_ -#define FUCHSIA_ENGINE_WEBRUNNER_MAIN_DELEGATE_H_ +#ifndef FUCHSIA_ENGINE_WEB_ENGINE_MAIN_DELEGATE_H_ +#define FUCHSIA_ENGINE_WEB_ENGINE_MAIN_DELEGATE_H_ #include <lib/zx/channel.h> #include <memory> @@ -17,18 +17,18 @@ class ContentClient; } // namespace content -class WebRunnerContentBrowserClient; -class WebRunnerContentRendererClient; +class WebEngineContentBrowserClient; +class WebEngineContentRendererClient; -class WEB_ENGINE_EXPORT WebRunnerMainDelegate +class WEB_ENGINE_EXPORT WebEngineMainDelegate : public content::ContentMainDelegate { public: - explicit WebRunnerMainDelegate(zx::channel context_channel); - ~WebRunnerMainDelegate() override; + explicit WebEngineMainDelegate(zx::channel context_channel); + ~WebEngineMainDelegate() override; - static WebRunnerMainDelegate* GetInstanceForTest(); + static WebEngineMainDelegate* GetInstanceForTest(); - WebRunnerContentBrowserClient* browser_client() { + WebEngineContentBrowserClient* browser_client() { return browser_client_.get(); } @@ -43,12 +43,12 @@ private: std::unique_ptr<content::ContentClient> content_client_; - std::unique_ptr<WebRunnerContentBrowserClient> browser_client_; - std::unique_ptr<WebRunnerContentRendererClient> renderer_client_; + std::unique_ptr<WebEngineContentBrowserClient> browser_client_; + std::unique_ptr<WebEngineContentRendererClient> renderer_client_; zx::channel context_channel_; - DISALLOW_COPY_AND_ASSIGN(WebRunnerMainDelegate); + DISALLOW_COPY_AND_ASSIGN(WebEngineMainDelegate); }; -#endif // FUCHSIA_ENGINE_WEBRUNNER_MAIN_DELEGATE_H_ +#endif // FUCHSIA_ENGINE_WEB_ENGINE_MAIN_DELEGATE_H_
diff --git a/fuchsia/runners/cast/cast_channel_bindings_browsertest.cc b/fuchsia/runners/cast/cast_channel_bindings_browsertest.cc index e4ee3e9..2b170288 100644 --- a/fuchsia/runners/cast/cast_channel_bindings_browsertest.cc +++ b/fuchsia/runners/cast/cast_channel_bindings_browsertest.cc
@@ -16,7 +16,7 @@ #include "fuchsia/base/mem_buffer_util.h" #include "fuchsia/base/result_receiver.h" #include "fuchsia/engine/test/test_common.h" -#include "fuchsia/engine/test/webrunner_browser_test.h" +#include "fuchsia/engine/test/web_engine_browser_test.h" #include "fuchsia/runners/cast/cast_channel_bindings.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/url_constants.h" @@ -27,7 +27,7 @@ // referenced frequently in this file. using NavigationDetails = chromium::web::NavigationEvent; -class CastChannelBindingsTest : public cr_fuchsia::test::WebRunnerBrowserTest, +class CastChannelBindingsTest : public cr_fuchsia::test::WebEngineBrowserTest, public chromium::web::NavigationEventObserver, public chromium::cast::CastChannel { public: @@ -42,9 +42,9 @@ protected: void SetUpOnMainThread() override { - cr_fuchsia::test::WebRunnerBrowserTest::SetUpOnMainThread(); + cr_fuchsia::test::WebEngineBrowserTest::SetUpOnMainThread(); base::ScopedAllowBlockingForTesting allow_blocking; - frame_ = WebRunnerBrowserTest::CreateFrame(this); + frame_ = WebEngineBrowserTest::CreateFrame(this); connector_ = std::make_unique<NamedMessagePortConnector>(); }
diff --git a/fuchsia/runners/cast/named_message_port_connector_browsertest.cc b/fuchsia/runners/cast/named_message_port_connector_browsertest.cc index 9346b7b..eb48724 100644 --- a/fuchsia/runners/cast/named_message_port_connector_browsertest.cc +++ b/fuchsia/runners/cast/named_message_port_connector_browsertest.cc
@@ -15,7 +15,7 @@ #include "fuchsia/base/mem_buffer_util.h" #include "fuchsia/base/result_receiver.h" #include "fuchsia/engine/test/test_common.h" -#include "fuchsia/engine/test/webrunner_browser_test.h" +#include "fuchsia/engine/test/web_engine_browser_test.h" #include "fuchsia/runners/cast/named_message_port_connector.h" #include "testing/gmock/include/gmock/gmock-matchers.h" #include "testing/gmock/include/gmock/gmock.h" @@ -27,7 +27,7 @@ using NavigationDetails = chromium::web::NavigationEvent; class NamedMessagePortConnectorTest - : public cr_fuchsia::test::WebRunnerBrowserTest, + : public cr_fuchsia::test::WebEngineBrowserTest, public chromium::web::NavigationEventObserver { public: NamedMessagePortConnectorTest() @@ -40,8 +40,8 @@ protected: void SetUpOnMainThread() override { - cr_fuchsia::test::WebRunnerBrowserTest::SetUpOnMainThread(); - frame_ = WebRunnerBrowserTest::CreateFrame(this); + cr_fuchsia::test::WebEngineBrowserTest::SetUpOnMainThread(); + frame_ = WebEngineBrowserTest::CreateFrame(this); } void OnNavigationStateChanged(
diff --git a/google_apis/gaia/fake_oauth2_token_service_delegate.cc b/google_apis/gaia/fake_oauth2_token_service_delegate.cc index 58b8121..efc528f 100644 --- a/google_apis/gaia/fake_oauth2_token_service_delegate.cc +++ b/google_apis/gaia/fake_oauth2_token_service_delegate.cc
@@ -5,6 +5,25 @@ #include "google_apis/gaia/fake_oauth2_token_service_delegate.h" #include "google_apis/gaia/oauth2_access_token_fetcher_impl.h" +namespace { +// Values used from |MutableProfileOAuth2TokenServiceDelegate|. +const net::BackoffEntry::Policy kBackoffPolicy = { + 0 /* int num_errors_to_ignore */, + + 1000 /* int initial_delay_ms */, + + 2.0 /* double multiply_factor */, + + 0.2 /* double jitter_factor */, + + 15 * 60 * 1000 /* int64_t maximum_backoff_ms */, + + -1 /* int64_t entry_lifetime_ms */, + + false /* bool always_use_initial_delay */, +}; +} // namespace + FakeOAuth2TokenServiceDelegate::AccountInfo::AccountInfo( const std::string& refresh_token) : refresh_token(refresh_token), @@ -13,7 +32,8 @@ FakeOAuth2TokenServiceDelegate::FakeOAuth2TokenServiceDelegate() : shared_factory_( base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( - &test_url_loader_factory_)) {} + &test_url_loader_factory_)), + backoff_entry_(&kBackoffPolicy) {} FakeOAuth2TokenServiceDelegate::~FakeOAuth2TokenServiceDelegate() { } @@ -49,6 +69,10 @@ return std::string(); } +const net::BackoffEntry* FakeOAuth2TokenServiceDelegate::BackoffEntry() const { + return &backoff_entry_; +} + std::vector<std::string> FakeOAuth2TokenServiceDelegate::GetAccounts() { std::vector<std::string> account_ids; for (const auto& token : refresh_tokens_) @@ -124,6 +148,7 @@ void FakeOAuth2TokenServiceDelegate::UpdateAuthError( const std::string& account_id, const GoogleServiceAuthError& error) { + backoff_entry_.InformOfRequest(!error.IsTransientError()); // Drop transient errors to match OAuth2TokenService's stated contract for // GetAuthError() and to allow clients to test proper behavior in the case of // transient errors.
diff --git a/google_apis/gaia/fake_oauth2_token_service_delegate.h b/google_apis/gaia/fake_oauth2_token_service_delegate.h index ef689a7..8fff5cc3 100644 --- a/google_apis/gaia/fake_oauth2_token_service_delegate.h +++ b/google_apis/gaia/fake_oauth2_token_service_delegate.h
@@ -59,6 +59,8 @@ fix_request_if_possible_ = value; } + const net::BackoffEntry* BackoffEntry() const override; + private: struct AccountInfo { AccountInfo(const std::string& refresh_token); @@ -77,6 +79,8 @@ scoped_refptr<network::SharedURLLoaderFactory> shared_factory_; bool fix_request_if_possible_ = false; + net::BackoffEntry backoff_entry_; + DISALLOW_COPY_AND_ASSIGN(FakeOAuth2TokenServiceDelegate); }; #endif
diff --git a/gpu/command_buffer/service/raster_decoder.cc b/gpu/command_buffer/service/raster_decoder.cc index 65a6a9a0ce..ab79b722 100644 --- a/gpu/command_buffer/service/raster_decoder.cc +++ b/gpu/command_buffer/service/raster_decoder.cc
@@ -97,6 +97,21 @@ base::AtomicSequenceNumber g_raster_decoder_id; +class ScopedProgressReporter { + public: + ScopedProgressReporter(gl::ProgressReporter* reporter) : reporter_(reporter) { + if (reporter_) + reporter_->ReportProgress(); + } + ~ScopedProgressReporter() { + if (reporter_) + reporter_->ReportProgress(); + } + + private: + gl::ProgressReporter* reporter_; +}; + // This class prevents any GL errors that occur when it is in scope from // being reported to the client. class ScopedGLErrorSuppressor { @@ -2158,6 +2173,8 @@ options.crash_dump_on_failure = true; size_t paint_buffer_size = raster_shm_size; + ScopedProgressReporter report_progress( + shared_context_state_->progress_reporter()); while (paint_buffer_size > 0) { size_t skip = 0; cc::PaintOp* deserialized_op = cc::PaintOp::Deserialize( @@ -2194,7 +2211,16 @@ recorder_ = nullptr; sk_surface_->draw(ddl.get()); } - sk_surface_->prepareForExternalIO(); + + { + // This is a slow operation since skia will execute the GPU work for the + // complete tile. Make sure the progress reporter is notified to avoid + // hangs. + ScopedProgressReporter report_progress( + shared_context_state_->progress_reporter()); + sk_surface_->prepareForExternalIO(); + } + if (!shared_image_) { // Test only path for SetUpForRasterCHROMIUMForTest. sk_surface_.reset();
diff --git a/gpu/command_buffer/service/shared_context_state.cc b/gpu/command_buffer/service/shared_context_state.cc index 3304a16..6f3c86e 100644 --- a/gpu/command_buffer/service/shared_context_state.cc +++ b/gpu/command_buffer/service/shared_context_state.cc
@@ -74,6 +74,8 @@ GrContextOptions::PersistentCache* cache, GpuProcessActivityFlags* activity_flags, gl::ProgressReporter* progress_reporter) { + progress_reporter_ = progress_reporter; + if (!use_vulkan_gr_context_) { DCHECK(context_->IsCurrent(nullptr)); sk_sp<GrGLInterface> interface(gl::init::CreateGrGLInterface(
diff --git a/gpu/command_buffer/service/shared_context_state.h b/gpu/command_buffer/service/shared_context_state.h index 51a28b2..7883ac2 100644 --- a/gpu/command_buffer/service/shared_context_state.h +++ b/gpu/command_buffer/service/shared_context_state.h
@@ -79,6 +79,7 @@ viz::VulkanContextProvider* vk_context_provider() { return vk_context_provider_; } + gl::ProgressReporter* progress_reporter() const { return progress_reporter_; } GrContext* gr_context() { return gr_context_; } gles2::FeatureInfo* feature_info() { return feature_info_.get(); } gles2::ContextState* context_state() const { return context_state_.get(); } @@ -143,6 +144,7 @@ // raster decoders and display compositor share this context_state_. std::unique_ptr<gles2::ContextState> context_state_; + gl::ProgressReporter* progress_reporter_ = nullptr; sk_sp<GrContext> owned_gr_context_; std::unique_ptr<ServiceTransferCache> transfer_cache_; size_t glyph_cache_max_texture_bytes_ = 0u;
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_gl_texture_unittest.cc b/gpu/command_buffer/service/shared_image_backing_factory_gl_texture_unittest.cc index 8f4a4be..fa5ae7a 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_gl_texture_unittest.cc +++ b/gpu/command_buffer/service/shared_image_backing_factory_gl_texture_unittest.cc
@@ -288,7 +288,8 @@ shared_image.reset(); EXPECT_FALSE(mailbox_manager_.ConsumeTexture(mailbox)); - if (!use_passthrough()) { + if (!use_passthrough() && + context_state_->feature_info()->feature_flags().ext_texture_rg) { // Create a R-8 image texture, and check that the internal_format is that of // the image (GL_RGBA for TextureImageFactory). This only matters for the // validating decoder.
diff --git a/gpu/ipc/service/direct_composition_child_surface_win.cc b/gpu/ipc/service/direct_composition_child_surface_win.cc index 3088286..e59a2b83 100644 --- a/gpu/ipc/service/direct_composition_child_surface_win.cc +++ b/gpu/ipc/service/direct_composition_child_surface_win.cc
@@ -262,19 +262,19 @@ bool DirectCompositionChildSurfaceWin::SetDrawRectangle( const gfx::Rect& rectangle) { if (!gfx::Rect(size_).Contains(rectangle)) { - VLOG(1) << "Draw rectangle must be contained within size of surface"; + DLOG(ERROR) << "Draw rectangle must be contained within size of surface"; return false; } if (draw_texture_) { - VLOG(1) << "SetDrawRectangle must be called only once per swap buffers"; + DLOG(ERROR) << "SetDrawRectangle must be called only once per swap buffers"; return false; } DCHECK(!real_surface_); DCHECK(!g_current_surface); if (gfx::Rect(size_) != rectangle && !swap_chain_ && !dcomp_surface_) { - VLOG(1) << "First draw to surface must draw to everything"; + DLOG(ERROR) << "First draw to surface must draw to everything"; return false; } @@ -294,7 +294,7 @@ size_.width(), size_.height(), output_format, DXGI_ALPHA_MODE_PREMULTIPLIED, dcomp_surface_.GetAddressOf()); if (FAILED(hr)) { - VLOG(1) << "CreateSurface failed with error " << std::hex << hr; + DLOG(ERROR) << "CreateSurface failed with error " << std::hex << hr; return false; } } else if (!enable_dc_layers_ && !swap_chain_) { @@ -331,8 +331,8 @@ d3d11_device_.Get(), &desc, nullptr, swap_chain_.GetAddressOf()); first_swap_ = true; if (FAILED(hr)) { - VLOG(1) << "CreateSwapChainForComposition failed with error " << std::hex - << hr; + DLOG(ERROR) << "CreateSwapChainForComposition failed with error " + << std::hex << hr; return false; } } @@ -346,7 +346,7 @@ HRESULT hr = dcomp_surface_->BeginDraw( &rect, IID_PPV_ARGS(draw_texture_.GetAddressOf()), &update_offset); if (FAILED(hr)) { - VLOG(1) << "BeginDraw failed with error " << std::hex << hr; + DLOG(ERROR) << "BeginDraw failed with error " << std::hex << hr; return false; } draw_offset_ = gfx::Point(update_offset) - rectangle.origin(); @@ -373,8 +373,8 @@ eglCreatePbufferFromClientBuffer(GetDisplay(), EGL_D3D_TEXTURE_ANGLE, buffer, GetConfig(), pbuffer_attribs); if (!real_surface_) { - VLOG(1) << "eglCreatePbufferFromClientBuffer failed with error " - << ui::GetLastEGLErrorString(); + DLOG(ERROR) << "eglCreatePbufferFromClientBuffer failed with error " + << ui::GetLastEGLErrorString(); return false; }
diff --git a/gpu/ipc/service/gpu_memory_buffer_factory_native_pixmap.cc b/gpu/ipc/service/gpu_memory_buffer_factory_native_pixmap.cc index 658441f..031ac812 100644 --- a/gpu/ipc/service/gpu_memory_buffer_factory_native_pixmap.cc +++ b/gpu/ipc/service/gpu_memory_buffer_factory_native_pixmap.cc
@@ -125,7 +125,7 @@ } auto image = base::MakeRefCounted<gl::GLImageNativePixmap>(size, format); - if (!image->Initialize(pixmap.get())) { + if (!image->Initialize(std::move(pixmap))) { LOG(ERROR) << "Failed to create GLImage " << size.ToString() << ", " << gfx::BufferFormatToString(format); return nullptr; @@ -162,7 +162,7 @@ return nullptr; } auto image = base::MakeRefCounted<gl::GLImageNativePixmap>(size, format); - if (!image->Initialize(pixmap.get())) { + if (!image->Initialize(std::move(pixmap))) { LOG(ERROR) << "Failed to create GLImage " << size.ToString() << ", " << gfx::BufferFormatToString(format); return nullptr;
diff --git a/gpu/ipc/service/shared_image_stub.cc b/gpu/ipc/service/shared_image_stub.cc index 6ee676a..70a83f3 100644 --- a/gpu/ipc/service/shared_image_stub.cc +++ b/gpu/ipc/service/shared_image_stub.cc
@@ -151,7 +151,7 @@ void SharedImageStub::OnCreateGMBSharedImage( GpuChannelMsg_CreateGMBSharedImage_Params params) { - TRACE_EVENT2("gpu", "SharedImageStub::OnCreateSharedImage", "width", + TRACE_EVENT2("gpu", "SharedImageStub::OnCreateGMBSharedImage", "width", params.size.width(), "height", params.size.height()); if (!params.mailbox.IsSharedImage()) { LOG(ERROR) << "SharedImageStub: Trying to create a SharedImage with a " @@ -186,7 +186,7 @@ void SharedImageStub::OnUpdateSharedImage(const Mailbox& mailbox, uint32_t release_id) { - TRACE_EVENT0("gpu", "SharedImageStub::OnDestroySharedImage"); + TRACE_EVENT0("gpu", "SharedImageStub::OnUpdateSharedImage"); if (!mailbox.IsSharedImage()) { LOG(ERROR) << "SharedImageStub: Trying to access a SharedImage with a " "non-SharedImage mailbox.";
diff --git a/headless/test/data/protocol/emulation/virtual-time-fetch-stream.js b/headless/test/data/protocol/emulation/virtual-time-fetch-stream.js index 1fa2f9a..b60f46e 100644 --- a/headless/test/data/protocol/emulation/virtual-time-fetch-stream.js +++ b/headless/test/data/protocol/emulation/virtual-time-fetch-stream.js
@@ -30,5 +30,5 @@ policy: 'pauseIfNetworkFetchesPending', budget: 5000, waitForNavigation: true}); await dp.Page.navigate({url: 'http://test.com/index.html'}); - await session.evaluateAsync(`fetch('/fetch')`); + await session.evaluateAsync(`fetch('/fetch').then(res => res.text())`); })
diff --git a/ios/BUILD.gn b/ios/BUILD.gn index da00ac7..57fb3a3 100644 --- a/ios/BUILD.gn +++ b/ios/BUILD.gn
@@ -4,6 +4,7 @@ assert(!is_component_build, "component build is unsupported on iOS") +import("//build/config/gclient_args.gni") import("//build/config/ios/ios_sdk.gni") import("//ios/features.gni") @@ -62,5 +63,9 @@ "//ios/web_view:all_tests", "//ios/web_view/shell/test:all_tests", ] + + if (checkout_ios_webkit) { + deps += [ "//ios/third_party/webkit" ] + } } }
diff --git a/ios/chrome/app/main_controller.mm b/ios/chrome/app/main_controller.mm index cacc0c0..dcedd75 100644 --- a/ios/chrome/app/main_controller.mm +++ b/ios/chrome/app/main_controller.mm
@@ -1845,6 +1845,14 @@ ->LoadUrlInCurrentTab(ChromeLoadParams(params)); } +// Loads the image from startup parameters as search-by-image in the current +// BVC. +- (void)loadStartupImageQueryInCurrentBVC { + NSData* query = self.startupParameters.imageSearchData; + + [self.currentBVC.dispatcher searchByImage:[UIImage imageWithData:query]]; +} + #pragma mark - Preferences Management - (void)onPreferenceChanged:(const std::string&)preferenceName { @@ -2338,6 +2346,10 @@ return ^{ [self loadStartupQueryInCurrentBVC]; }; + case SEARCH_IMAGE: + return ^{ + [self loadStartupImageQueryInCurrentBVC]; + }; default: return nil; }
diff --git a/ios/chrome/app/startup/chrome_app_startup_parameters.h b/ios/chrome/app/startup/chrome_app_startup_parameters.h index e066086..e8f7768 100644 --- a/ios/chrome/app/startup/chrome_app_startup_parameters.h +++ b/ios/chrome/app/startup/chrome_app_startup_parameters.h
@@ -101,6 +101,7 @@ + (instancetype)newAppStartupParametersForCommand:(NSString*)command withExternalText:(NSString*)externalText + withExternalData:(NSData*)externalData withIndex:(NSNumber*)index withURL:(NSURL*)url fromSourceApplication:(NSString*)appId
diff --git a/ios/chrome/app/startup/chrome_app_startup_parameters.mm b/ios/chrome/app/startup/chrome_app_startup_parameters.mm index 9c131af7..5f9cc78 100644 --- a/ios/chrome/app/startup/chrome_app_startup_parameters.mm +++ b/ios/chrome/app/startup/chrome_app_startup_parameters.mm
@@ -54,6 +54,8 @@ ACTION_NEW_VOICE_SEARCH, ACTION_NEW_QR_CODE_SEARCH, ACTION_OPEN_URL, + ACTION_SEARCH_TEXT, + ACTION_SEARCH_IMAGE, SEARCH_EXTENSION_ACTION_COUNT, }; @@ -209,6 +211,11 @@ NSString* externalText = base::mac::ObjCCast<NSString>( [commandDictionary objectForKey:commandTextPreference]); + NSString* commandDataPreference = + base::SysUTF8ToNSString(app_group::kChromeAppGroupCommandDataPreference); + NSData* externalData = base::mac::ObjCCast<NSData>( + [commandDictionary objectForKey:commandDataPreference]); + NSString* commandIndexPreference = base::SysUTF8ToNSString(app_group::kChromeAppGroupCommandIndexPreference); NSNumber* index = base::mac::ObjCCast<NSNumber>( @@ -227,6 +234,7 @@ return [ChromeAppStartupParameters newAppStartupParametersForCommand:command withExternalText:externalText + withExternalData:externalData withIndex:index withURL:url fromSourceApplication:appId @@ -235,6 +243,7 @@ + (instancetype)newAppStartupParametersForCommand:(NSString*)command withExternalText:(NSString*)externalText + withExternalData:(NSData*)externalData withIndex:(NSNumber*)index withURL:(NSURL*)url fromSourceApplication:(NSString*)appId @@ -307,7 +316,26 @@ params.textQuery = externalText; params.postOpeningAction = SEARCH_TEXT; - action = ACTION_NEW_SEARCH; + action = ACTION_SEARCH_TEXT; + } + + if ([command + isEqualToString:base::SysUTF8ToNSString( + app_group::kChromeAppGroupSearchImageCommand)]) { + if (!externalData) { + return nil; + } + + params = [[ChromeAppStartupParameters alloc] + initWithExternalURL:GURL(kChromeUINewTabURL) + declaredSourceApp:appId + secureSourceApp:secureSourceApp + completeURL:url]; + + params.imageSearchData = externalData; + params.postOpeningAction = SEARCH_IMAGE; + + action = ACTION_SEARCH_IMAGE; } if ([command
diff --git a/ios/chrome/app/startup/chrome_app_startup_parameters_unittest.mm b/ios/chrome/app/startup/chrome_app_startup_parameters_unittest.mm index a034336..eb1a586a 100644 --- a/ios/chrome/app/startup/chrome_app_startup_parameters_unittest.mm +++ b/ios/chrome/app/startup/chrome_app_startup_parameters_unittest.mm
@@ -154,6 +154,7 @@ ChromeAppStartupParameters* params = [ChromeAppStartupParameters newAppStartupParametersForCommand:@"voicesearch" withExternalText:nil + withExternalData:nil withIndex:0 withURL:nil fromSourceApplication:nil @@ -170,6 +171,7 @@ ChromeAppStartupParameters* params = [ChromeAppStartupParameters newAppStartupParametersForCommand:@"qrscanner" withExternalText:nil + withExternalData:nil withIndex:0 withURL:nil fromSourceApplication:nil @@ -186,6 +188,7 @@ ChromeAppStartupParameters* params = [ChromeAppStartupParameters newAppStartupParametersForCommand:@"focusomnibox" withExternalText:nil + withExternalData:nil withIndex:0 withURL:nil fromSourceApplication:nil @@ -202,6 +205,7 @@ ChromeAppStartupParameters* params = [ChromeAppStartupParameters newAppStartupParametersForCommand:@"newtab" withExternalText:nil + withExternalData:nil withIndex:0 withURL:nil fromSourceApplication:nil @@ -217,7 +221,7 @@ ChromeAppStartupParameters* params = [ChromeAppStartupParameters newAppStartupParametersForCommand:@"openurl" withExternalText:@"http://foo/bar" - + withExternalData:nil withIndex:0 withURL:nil fromSourceApplication:nil @@ -230,6 +234,7 @@ ChromeAppStartupParameters* params = [ChromeAppStartupParameters newAppStartupParametersForCommand:@"garbage" withExternalText:nil + withExternalData:nil withIndex:0 withURL:nil fromSourceApplication:nil
diff --git a/ios/chrome/app/strings/ios_strings.grd b/ios/chrome/app/strings/ios_strings.grd index 02c2915..6949cac 100644 --- a/ios/chrome/app/strings/ios_strings.grd +++ b/ios/chrome/app/strings/ios_strings.grd
@@ -196,7 +196,7 @@ Google may use your history to personalize Search, ads, and other Google services. </message> <message name="IDS_IOS_ACCOUNT_UNIFIED_CONSENT_SETTINGS" desc="Explination text on the sync consent dialog to explain the user they can customize sync settings. [iOS only]"> - You can <ph name="BEGIN_LINK">BEGIN_LINK</ph>customize these settings<ph name="END_LINK">END_LINK</ph> anytime + You can always <ph name="BEGIN_LINK">BEGIN_LINK</ph>choose what to sync in settings<ph name="END_LINK">END_LINK</ph> </message> <message name="IDS_IOS_ACCOUNT_UNIFIED_CONSENT_ADD_ACCOUNT" desc="Title of the button to add an account [Length: 15m] [iOS only]"> ADD ACCOUNT @@ -725,10 +725,10 @@ Google Apps </message> <message name="IDS_IOS_GOOGLE_SERVICES_SETTINGS_AUTOCOMPLETE_SEARCHES_AND_URLS_DETAIL" desc="Feature detail text in the settings for the user to enable/disable, to have autocomplete searches and URLs. Text related to 'Autocomplete Searches and URLs' [iOS only]"> - Sends searches from the address bar and search box, and some cookies to your default search engine + Sends some cookies and searches from the address bar and search box to your default search engine </message> <message name="IDS_IOS_GOOGLE_SERVICES_SETTINGS_AUTOCOMPLETE_SEARCHES_AND_URLS_TEXT" desc="Feature title in the settings for the user to enable/disable, to have autocomplete searches and URLs. Text related to 'Sends searches from the address bar and search box, and some cookies to your default search engine' [iOS only]"> - Autocomplete Searches and URLs + Autocomplete searches and URLs </message> <message name="IDS_IOS_GOOGLE_SERVICES_SETTINGS_BETTER_SEARCH_AND_BROWSING_DETAIL" desc="Detail text for a feature in the settings for the user to enable/disable, to make searches andn browsing better. Related to 'Make searches and browsing better'. [iOS only]"> Sends URLs of pages you visit to Google @@ -736,6 +736,9 @@ <message name="IDS_IOS_GOOGLE_SERVICES_SETTINGS_BETTER_SEARCH_AND_BROWSING_TEXT" desc="Title for a feature in the settings for the user to enable/disable, to make searches andn browsing better. Related to 'Sends URLs of pages you visit to Google'. [iOS only]"> Make searches and browsing better </message> + <message name="IDS_IOS_GOOGLE_SERVICES_SETTINGS_ENTER_PASSPHRASE_TO_START_SYNC" desc="Title button to ask the user to tap their passphrase. The sync is blocked until the correct passphrase is entered"> + Enter passphrase to start sync + </message> <message name="IDS_IOS_GOOGLE_SERVICES_SETTINGS_IMPROVE_CHROME_DETAIL" desc="Feature detail text in the settings for the user enable or disable. Related with 'Help improve Chrome's features and performance' feature. [iOS only]"> Automatically sends usage statistics and crash reports to Google </message>
diff --git a/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_GOOGLE_SERVICES_SETTINGS_AUTOCOMPLETE_SEARCHES_AND_URLS_DETAIL.png.sha1 b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_GOOGLE_SERVICES_SETTINGS_AUTOCOMPLETE_SEARCHES_AND_URLS_DETAIL.png.sha1 new file mode 100644 index 0000000..62c965a --- /dev/null +++ b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_GOOGLE_SERVICES_SETTINGS_AUTOCOMPLETE_SEARCHES_AND_URLS_DETAIL.png.sha1
@@ -0,0 +1 @@ +20036a30c85de2978b1d27f90fe14eedc98a8b34 \ No newline at end of file
diff --git a/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_GOOGLE_SERVICES_SETTINGS_AUTOCOMPLETE_SEARCHES_AND_URLS_TEXT.png.sha1 b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_GOOGLE_SERVICES_SETTINGS_AUTOCOMPLETE_SEARCHES_AND_URLS_TEXT.png.sha1 new file mode 100644 index 0000000..62c965a --- /dev/null +++ b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_GOOGLE_SERVICES_SETTINGS_AUTOCOMPLETE_SEARCHES_AND_URLS_TEXT.png.sha1
@@ -0,0 +1 @@ +20036a30c85de2978b1d27f90fe14eedc98a8b34 \ No newline at end of file
diff --git a/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_GOOGLE_SERVICES_SETTINGS_ENTER_PASSPHRASE_TO_START_SYNC.png.sha1 b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_GOOGLE_SERVICES_SETTINGS_ENTER_PASSPHRASE_TO_START_SYNC.png.sha1 new file mode 100644 index 0000000..62c965a --- /dev/null +++ b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_GOOGLE_SERVICES_SETTINGS_ENTER_PASSPHRASE_TO_START_SYNC.png.sha1
@@ -0,0 +1 @@ +20036a30c85de2978b1d27f90fe14eedc98a8b34 \ No newline at end of file
diff --git a/ios/chrome/browser/app_startup_parameters.h b/ios/chrome/browser/app_startup_parameters.h index 4269314..368e8686 100644 --- a/ios/chrome/browser/app_startup_parameters.h +++ b/ios/chrome/browser/app_startup_parameters.h
@@ -17,6 +17,7 @@ FOCUS_OMNIBOX, NTP_TAB_OPENING_POST_OPENING_ACTION_COUNT, SEARCH_TEXT, + SEARCH_IMAGE, }; class GURL; @@ -51,6 +52,8 @@ @property(nonatomic, readwrite, assign) BOOL completePaymentRequest; // Text query that should be executed on startup. @property(nonatomic, readwrite, copy) NSString* textQuery; +// Data for UIImage for image query that should be executed on startup. +@property(nonatomic, readwrite, strong) NSData* imageSearchData; - (instancetype)init NS_UNAVAILABLE;
diff --git a/ios/chrome/browser/browsing_data/browsing_data_remover_impl.mm b/ios/chrome/browser/browsing_data/browsing_data_remover_impl.mm index fe471d0..6725e46 100644 --- a/ios/chrome/browser/browsing_data/browsing_data_remover_impl.mm +++ b/ios/chrome/browser/browsing_data/browsing_data_remover_impl.mm
@@ -24,7 +24,9 @@ #include "base/threading/sequenced_task_runner_handle.h" #include "components/autofill/core/browser/legacy_strike_database.h" #include "components/autofill/core/browser/personal_data_manager.h" +#include "components/autofill/core/browser/strike_database.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" +#include "components/autofill/core/common/autofill_features.h" #include "components/history/core/browser/history_service.h" #include "components/keyed_service/core/service_access_type.h" #include "components/language/core/browser/url_language_histogram.h" @@ -39,6 +41,7 @@ #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/autofill/legacy_strike_database_factory.h" #include "ios/chrome/browser/autofill/personal_data_manager_factory.h" +#include "ios/chrome/browser/autofill/strike_database_factory.h" #include "ios/chrome/browser/bookmarks/bookmark_remover_helper.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/browsing_data/browsing_data_features.h" @@ -428,13 +431,25 @@ web_data_service->RemoveAutofillDataModifiedBetween(delete_begin, delete_end); - // Clear out the Autofill LegacyStrikeDatabase in its entirety. - autofill::LegacyStrikeDatabase* legacy_strike_database = - autofill::LegacyStrikeDatabaseFactory::GetForBrowserState( - browser_state_); - if (legacy_strike_database) - legacy_strike_database->ClearAllStrikes(AdaptCallbackForRepeating( - IgnoreArgument<bool>(CreatePendingTaskCompletionClosure()))); + if (base::FeatureList::IsEnabled( + autofill::features::kAutofillSaveCreditCardUsesStrikeSystemV2)) { + // Clear out the Autofill StrikeDatabase in its entirety. + autofill::StrikeDatabase* strike_database = + autofill::StrikeDatabaseFactory::GetForBrowserState(browser_state_); + if (strike_database) + strike_database->ClearAllStrikes(); + } else if (base::FeatureList::IsEnabled( + autofill::features:: + kAutofillSaveCreditCardUsesStrikeSystem)) { + // Clear out the Autofill LegacyStrikeDatabase in its entirety. + autofill::LegacyStrikeDatabase* legacy_strike_database = + autofill::LegacyStrikeDatabaseFactory::GetForBrowserState( + browser_state_); + if (legacy_strike_database) { + legacy_strike_database->ClearAllStrikes(AdaptCallbackForRepeating( + IgnoreArgument<bool>(CreatePendingTaskCompletionClosure()))); + } + } // Ask for a call back when the above calls are finished. web_data_service->GetDBTaskRunner()->PostTaskAndReply(
diff --git a/ios/chrome/browser/find_in_page/js_findinpage_manager.mm b/ios/chrome/browser/find_in_page/js_findinpage_manager.mm index 2d56bd6..83085cc7 100644 --- a/ios/chrome/browser/find_in_page/js_findinpage_manager.mm +++ b/ios/chrome/browser/find_in_page/js_findinpage_manager.mm
@@ -66,7 +66,7 @@ completionHandler:(void (^)(BOOL, CGPoint))completionHandler; // Helper functions to extract FindInPageEntry from JSON. - (FindInPageEntry)findInPageEntryForJson:(NSString*)jsonStr; -- (FindInPageEntry)entryForListValue:(base::ListValue*)position; +- (FindInPageEntry)entryForListValue:(const base::Value&)position; // Executes |script| which is a piece of JavaScript to move to the next or // previous element in the page and executes |completionHandler| after moving // with the new scroll position passed in. @@ -175,29 +175,24 @@ // Parse JSONs. std::string json = base::SysNSStringToUTF8(result_str); - std::unique_ptr<base::Value> root( - base::JSONReader::ReadDeprecated(json, false)); - if (!root.get()) + base::Optional<base::Value> root = base::JSONReader::Read(json); + if (!root.has_value()) return YES; - if (!root->is_list()) + if (!root.value().is_list()) return YES; - base::ListValue* resultList = static_cast<base::ListValue*>(root.get()); - DCHECK(resultList); - if (resultList) { - if (resultList->GetSize() == 2) { - int numHighlighted = 0; - if (resultList->GetInteger(0, &numHighlighted)) { - if (numHighlighted > 0) { - base::ListValue* position; - if (resultList->GetList(1, &position)) { - [self.findInPageModel updateQuery:nil matches:numHighlighted]; - // Scroll to first match. - FindInPageEntry entry = [self entryForListValue:position]; - [self.findInPageModel updateIndex:entry.index atPoint:entry.point]; - if (point) - *point = entry.point; - } + base::Value::ListStorage& listValues = root.value().GetList(); + if (listValues.size() == 2) { + if (listValues[0].is_int()) { + int numHighlighted = listValues[0].GetInt(); + if (numHighlighted > 0) { + if (listValues[1].is_list()) { + [self.findInPageModel updateQuery:nil matches:numHighlighted]; + // Scroll to first match. + FindInPageEntry entry = [self entryForListValue:listValues[1]]; + [self.findInPageModel updateIndex:entry.index atPoint:entry.point]; + if (point) + *point = entry.point; } } } @@ -223,40 +218,33 @@ - (FindInPageEntry)findInPageEntryForJson:(NSString*)jsonStr { std::string json = base::SysNSStringToUTF8(jsonStr); - std::unique_ptr<base::Value> root( - base::JSONReader::ReadDeprecated(json, false)); - if (!root.get()) + base::Optional<base::Value> root = base::JSONReader::Read(json); + if (!root.has_value()) return kFindInPageEntryZero; - if (!root->is_list()) + if (!root.value().is_list()) return kFindInPageEntryZero; - base::ListValue* position = static_cast<base::ListValue*>(root.get()); - return [self entryForListValue:position]; + return [self entryForListValue:root.value()]; } -- (FindInPageEntry)entryForListValue:(base::ListValue*)position { - if (!position) - return kFindInPageEntryZero; +- (FindInPageEntry)entryForListValue:(const base::Value&)position { + DCHECK(position.is_list()); // Position should always be of length 3, from [index,x,y]. - DCHECK(position->GetSize() == 3); - if (position->GetSize() != 3) + const base::Value::ListStorage& positionList = position.GetList(); + if (positionList.size() != 3) return kFindInPageEntryZero; // The array position comes from the JSON string [index, x, y], which // represents the index of the currently found string, and the x and y // position necessary to center that string. Pull out that data into a // FindInPageEntry struct. - int index; - double x = 0, y = 0; - position->GetInteger(0, &index); - position->GetDouble(1, &x); - position->GetDouble(2, &y); + FindInPageEntry entry; - entry.index = index; - entry.point.x = x; - entry.point.y = y; + entry.index = positionList[0].is_int() ? positionList[0].GetInt() : 0; + entry.point.x = positionList[1].is_double() ? positionList[1].GetDouble() : 0; + entry.point.y = positionList[2].is_double() ? positionList[2].GetDouble() : 0; return entry; }
diff --git a/ios/chrome/browser/payments/ios_payment_instrument_finder.mm b/ios/chrome/browser/payments/ios_payment_instrument_finder.mm index 4e8e1675..bd74073 100644 --- a/ios/chrome/browser/payments/ios_payment_instrument_finder.mm +++ b/ios/chrome/browser/payments/ios_payment_instrument_finder.mm
@@ -163,38 +163,36 @@ std::set<GURL> web_app_manifest_urls; - std::unique_ptr<base::Value> value = base::JSONReader::ReadDeprecated(input); - if (!value) { + base::Optional<base::Value> value = base::JSONReader::Read(input); + if (!value.has_value()) { LOG(ERROR) << "Payment method manifest must be in JSON format."; return false; } - std::unique_ptr<base::DictionaryValue> dict = - base::DictionaryValue::From(std::move(value)); - if (!dict) { + if (!value.value().is_dict()) { LOG(ERROR) << "Payment method manifest must be a JSON dictionary."; return false; } - base::ListValue* list = nullptr; - if (!dict->GetList(kDefaultApplications, &list)) { + const base::Value* list = value.value().FindKeyOfType( + kDefaultApplications, base::Value::Type::LIST); + if (!list) { LOG(ERROR) << "\"" << kDefaultApplications << "\" must be a list."; return false; } - size_t apps_number = list->GetSize(); - if (apps_number > kMaximumNumberOfWebAppManifests) { + const base::Value::ListStorage& apps = list->GetList(); + if (apps.size() > kMaximumNumberOfWebAppManifests) { LOG(ERROR) << "\"" << kDefaultApplications << "\" must contain at most " << kMaximumNumberOfWebAppManifests << " entries."; return false; } - std::string item; - for (size_t i = 0; i < apps_number; ++i) { - if (!list->GetString(i, &item) || item.empty()) + for (const base::Value& app : apps) { + if (!app.is_string() || app.GetString().empty()) continue; - GURL url(item); + GURL url(app.GetString()); if (!url.is_valid() || !url.SchemeIs(url::kHttpsScheme)) continue; @@ -240,55 +238,53 @@ std::string* out_app_name, GURL* out_app_icon_url, GURL* out_universal_link) { - std::unique_ptr<base::Value> value = base::JSONReader::ReadDeprecated(input); - if (!value) { + base::Optional<base::Value> value = base::JSONReader::Read(input); + if (!value.has_value()) { LOG(ERROR) << "Web app manifest must be in JSON format."; return false; } - std::unique_ptr<base::DictionaryValue> dict = - base::DictionaryValue::From(std::move(value)); - if (!dict) { + if (!value.value().is_dict()) { LOG(ERROR) << "Web app manifest must be a JSON dictionary."; return false; } - if (!dict->GetString(kShortName, out_app_name) || out_app_name->empty()) { + const std::string* short_name = value.value().FindStringKey(kShortName); + if (!short_name || short_name->empty()) { LOG(ERROR) << "\"" << kShortName << "\" must be a non-empty ASCII string."; return false; } + *out_app_name = *short_name; - base::ListValue* icons = nullptr; - if (!dict->GetList(kIcons, &icons)) { + const base::Value* list = + value.value().FindKeyOfType(kIcons, base::Value::Type::LIST); + if (!list) { LOG(ERROR) << "\"" << kIcons << "\" must be a list."; return false; } - size_t icons_size = icons->GetSize(); - for (size_t i = 0; i < icons_size; ++i) { - base::DictionaryValue* icon = nullptr; - if (!icons->GetDictionary(i, &icon)) + for (const base::Value& icon : list->GetList()) { + if (!icon.is_dict()) continue; - std::string icon_sizes; + const std::string* icon_sizes = icon.FindStringKey(kIconsSizes); // TODO(crbug.com/752546): Determine acceptable sizes for payment app icon. - if (!icon->GetString(kIconsSizes, &icon_sizes) || - icon_sizes != kIconSizes32) + if (!icon_sizes || *icon_sizes != kIconSizes32) continue; - std::string icon_string; - if (!icon->GetString(kIconsSource, &icon_string) || icon_string.empty()) + const std::string* icon_string = icon.FindStringKey(kIconsSource); + if (!icon_string || icon_string->empty()) continue; // The parsed value at "src" may be a relative path such that the base URL // is the path to the manifest. If so we check that here. - GURL complete_url = web_app_manifest_url.Resolve(icon_string); + GURL complete_url = web_app_manifest_url.Resolve(*icon_string); if (complete_url.is_valid() && complete_url.SchemeIs(url::kHttpsScheme)) { *out_app_icon_url = complete_url; break; } - GURL icon_url(icon_string); + GURL icon_url(*icon_string); if (icon_url.is_valid() && icon_url.SchemeIs(url::kHttpsScheme)) *out_app_icon_url = icon_url; } @@ -296,29 +292,26 @@ if (out_app_icon_url->is_empty()) return false; - base::ListValue* apps = nullptr; - if (!dict->GetList(kRelatedApplications, &apps)) { + list = value.value().FindKeyOfType(kRelatedApplications, + base::Value::Type::LIST); + if (!list) { LOG(ERROR) << "\"" << kRelatedApplications << "\" must be a list."; return false; } - size_t related_applications_size = apps->GetSize(); - for (size_t i = 0; i < related_applications_size; ++i) { - base::DictionaryValue* related_application = nullptr; - if (!apps->GetDictionary(i, &related_application)) + for (const base::Value& app : list->GetList()) { + if (!app.is_dict()) continue; - std::string platform; - if (!related_application->GetString(kPlatform, &platform) || - platform != kPlatformItunes) + const std::string* platform = app.FindStringKey(kPlatform); + if (!platform || *platform != kPlatformItunes) continue; - std::string link; - if (!related_application->GetString(kRelatedApplicationsUrl, &link) || - link.empty()) + const std::string* link = app.FindStringKey(kRelatedApplicationsUrl); + if (!link || link->empty()) continue; - GURL url(link); + GURL url(*link); if (!url.is_valid() || !url.SchemeIs(url::kHttpsScheme)) continue;
diff --git a/ios/chrome/browser/signin/identity_manager_factory.cc b/ios/chrome/browser/signin/identity_manager_factory.cc index 1ea4550..222b60b 100644 --- a/ios/chrome/browser/signin/identity_manager_factory.cc +++ b/ios/chrome/browser/signin/identity_manager_factory.cc
@@ -18,6 +18,7 @@ #include "ios/chrome/browser/signin/signin_manager_factory.h" #include "services/identity/public/cpp/accounts_cookie_mutator_impl.h" #include "services/identity/public/cpp/accounts_mutator.h" +#include "services/identity/public/cpp/diagnostics_provider_impl.h" #include "services/identity/public/cpp/identity_manager.h" #include "services/identity/public/cpp/primary_account_mutator_impl.h" @@ -48,6 +49,11 @@ nullptr, std::make_unique<identity::AccountsCookieMutatorImpl>( ios::GaiaCookieManagerServiceFactory::GetForBrowserState( + browser_state)), + std::make_unique<identity::DiagnosticsProviderImpl>( + ProfileOAuth2TokenServiceFactory::GetForBrowserState( + browser_state), + ios::GaiaCookieManagerServiceFactory::GetForBrowserState( browser_state))) {} };
diff --git a/ios/chrome/browser/tabs/tab.h b/ios/chrome/browser/tabs/tab.h index 815f2dd..14e4043 100644 --- a/ios/chrome/browser/tabs/tab.h +++ b/ios/chrome/browser/tabs/tab.h
@@ -32,8 +32,6 @@ } namespace web { -class NavigationItem; -class NavigationManager; class WebState; } @@ -102,10 +100,6 @@ // Dismisses all modals owned by the tab. - (void)dismissModals; -// Returns the NavigationManager for this tab's WebState. Requires WebState to -// be populated. Can return null. -- (web::NavigationManager*)navigationManager; - // Called before capturing a snapshot for Tab. - (void)willUpdateSnapshot;
diff --git a/ios/chrome/browser/tabs/tab.mm b/ios/chrome/browser/tabs/tab.mm index d2ca42e9..561a56c5 100644 --- a/ios/chrome/browser/tabs/tab.mm +++ b/ios/chrome/browser/tabs/tab.mm
@@ -231,10 +231,6 @@ [self.webController dismissModals]; } -- (web::NavigationManager*)navigationManager { - return self.webState ? self.webState->GetNavigationManager() : nullptr; -} - - (void)willUpdateSnapshot { [_overscrollActionsController clear]; }
diff --git a/ios/chrome/browser/tabs/tab_unittest.mm b/ios/chrome/browser/tabs/tab_unittest.mm index 2ad54c4..19a0cce 100644 --- a/ios/chrome/browser/tabs/tab_unittest.mm +++ b/ios/chrome/browser/tabs/tab_unittest.mm
@@ -220,7 +220,7 @@ tab_ = LegacyTabHelper::GetTabForWebState(web_state_impl_.get()); web::NavigationManager::WebLoadParams load_params( GURL("chrome://version/")); - [tab_ navigationManager]->LoadURLWithParams(load_params); + web_state_impl_->GetNavigationManager()->LoadURLWithParams(load_params); // There should be no entries in the history at this point. history::QueryResults results; @@ -273,7 +273,8 @@ web_state_impl_->SetIsLoading(true); base::string16 new_title = base::SysNSStringToUTF16(title); - [tab_ navigationManager]->GetLastCommittedItem()->SetTitle(new_title); + web_state_impl_->GetNavigationManager()->GetLastCommittedItem()->SetTitle( + new_title); web_state_impl_->OnTitleChanged(); web_state_impl_->SetIsLoading(false); @@ -287,7 +288,7 @@ // The only test that uses it is currently disabled. web::NavigationManager::WebLoadParams params(url); params.transition_type = ui::PAGE_TRANSITION_TYPED; - [tab_ navigationManager]->LoadURLWithParams(params); + web_state_impl_->GetNavigationManager()->LoadURLWithParams(params); web_state_impl_->SetIsLoading(true); web_state_impl_->SetIsLoading(false); web_state_impl_->OnPageLoaded(url, true); @@ -318,13 +319,15 @@ } void CheckCurrentItem(const GURL& expectedUrl, NSString* expectedTitle) { - web::NavigationItem* item = [tab_ navigationManager]->GetVisibleItem(); + web::NavigationItem* item = + web_state_impl_->GetNavigationManager()->GetVisibleItem(); EXPECT_EQ(expectedUrl, item->GetURL()); EXPECT_EQ(base::SysNSStringToUTF16(expectedTitle), item->GetTitle()); } void CheckCurrentItem(const history::URLResult& historyResult) { - web::NavigationItem* item = [tab_ navigationManager]->GetVisibleItem(); + web::NavigationItem* item = + web_state_impl_->GetNavigationManager()->GetVisibleItem(); CheckHistoryResult(historyResult, item->GetURL(), base::SysUTF16ToNSString(item->GetTitle())); }
diff --git a/ios/chrome/browser/ui/autofill/save_card_infobar_egtest.mm b/ios/chrome/browser/ui/autofill/save_card_infobar_egtest.mm index 108f3d6a..3626889 100644 --- a/ios/chrome/browser/ui/autofill/save_card_infobar_egtest.mm +++ b/ios/chrome/browser/ui/autofill/save_card_infobar_egtest.mm
@@ -311,7 +311,7 @@ @"Save card infobar failed to show."); } -- (void)testOfferLocalSave_FullData_RequestFails_StikeDatabaseDisabled { +- (void)testOfferLocalSave_FullData_RequestFails_StrikeDatabaseDisabled { base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature( autofill::features::kAutofillSaveCreditCardUsesStrikeSystemV2); @@ -319,7 +319,7 @@ chrome_test_util::RemoveAllInfoBars(); } -- (void)testOfferLocalSave_FullData_RequestFails_StikeDatabaseEnabled { +- (void)testOfferLocalSave_FullData_RequestFails_StrikeDatabaseEnabled { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature( autofill::features::kAutofillSaveCreditCardUsesStrikeSystemV2); @@ -355,7 +355,7 @@ @"Save card infobar failed to show."); } -- (void)testOfferLocalSave_FullData_PaymentsDeclines_StikeDatabaseDisabled { +- (void)testOfferLocalSave_FullData_PaymentsDeclines_StrikeDatabaseDisabled { base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature( autofill::features::kAutofillSaveCreditCardUsesStrikeSystemV2); @@ -363,7 +363,7 @@ chrome_test_util::RemoveAllInfoBars(); } -- (void)testOfferLocalSave_FullData_PaymentsDeclines_StikeDatabaseEnabled { +- (void)testOfferLocalSave_FullData_PaymentsDeclines_StrikeDatabaseEnabled { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature( autofill::features::kAutofillSaveCreditCardUsesStrikeSystemV2); @@ -421,7 +421,7 @@ @"Save card infobar failed to show."); } -- (void)testOfferUpstream_FullData_PaymentsAccepts_StikeDatabaseDisabled { +- (void)testOfferUpstream_FullData_PaymentsAccepts_StrikeDatabaseDisabled { base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature( autofill::features::kAutofillSaveCreditCardUsesStrikeSystemV2); @@ -429,7 +429,7 @@ chrome_test_util::RemoveAllInfoBars(); } -- (void)testOfferUpstream_FullData_PaymentsAccepts_StikeDatabaseEnabled { +- (void)testOfferUpstream_FullData_PaymentsAccepts_StrikeDatabaseEnabled { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature( autofill::features::kAutofillSaveCreditCardUsesStrikeSystemV2); @@ -464,7 +464,7 @@ @"Save card infobar failed to show."); } -- (void)testOfferUpstream_PartialData_PaymentsAccepts_StikeDatabaseDisabled { +- (void)testOfferUpstream_PartialData_PaymentsAccepts_StrikeDatabaseDisabled { base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature( autofill::features::kAutofillSaveCreditCardUsesStrikeSystemV2); @@ -472,7 +472,7 @@ chrome_test_util::RemoveAllInfoBars(); } -- (void)testOfferUpstream_PartialData_PaymentsAccepts_StikeDatabaseEnabled { +- (void)testOfferUpstream_PartialData_PaymentsAccepts_StrikeDatabaseEnabled { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature( autofill::features::kAutofillSaveCreditCardUsesStrikeSystemV2); @@ -537,7 +537,7 @@ histogram_tester.ExpectTotalCount("Autofill.UploadAcceptedCardOrigin", 0); } -- (void)testUMA_Upstream_UserDeclines_StikeDatabaseDisabled { +- (void)testUMA_Upstream_UserDeclines_StrikeDatabaseDisabled { // TODO(crbug.com/925670): re-enable when fixed. EARL_GREY_TEST_DISABLED(@"Failing regularly on the bots."); @@ -547,7 +547,7 @@ [self UMA_Upstream_UserDeclines]; } -- (void)testUMA_Upstream_UserDeclines_StikeDatabaseEnabled { +- (void)testUMA_Upstream_UserDeclines_StrikeDatabaseEnabled { // TODO(crbug.com/925670): re-enable when fixed. EARL_GREY_TEST_DISABLED(@"Failing regularly on the bots."); @@ -665,7 +665,7 @@ @"No credit card should have been saved."); } -- (void)testUserData_LocalSave_UserDeclines_StikeDatabaseDisabled { +- (void)testUserData_LocalSave_UserDeclines_StrikeDatabaseDisabled { // TODO(crbug.com/925670): re-enable when fixed. EARL_GREY_TEST_DISABLED(@"Failing regularly on the bots."); @@ -675,7 +675,7 @@ [self userData_LocalSave_UserDeclines]; } -- (void)testUserData_LocalSave_UserDeclines_StikeDatabaseEnabled { +- (void)testUserData_LocalSave_UserDeclines_StrikeDatabaseEnabled { // TODO(crbug.com/925670): re-enable when fixed. EARL_GREY_TEST_DISABLED(@"Failing regularly on the bots.");
diff --git a/ios/chrome/browser/ui/browser_view_controller.mm b/ios/chrome/browser/ui/browser_view_controller.mm index 87aec94..fbc84db 100644 --- a/ios/chrome/browser/ui/browser_view_controller.mm +++ b/ios/chrome/browser/ui/browser_view_controller.mm
@@ -2462,8 +2462,8 @@ if (!(self.helper && _browserState)) return; - Tab* tab = self.tabModel.currentTab; - if (![tab navigationManager]) + web::WebState* webState = self.currentWebState; + if (!webState) return; PrerenderService* prerenderService = @@ -2473,7 +2473,7 @@ if (isPrerendered && ![self.helper isToolbarLoading:self.currentWebState]) [self.primaryToolbarCoordinator showPrerenderingAnimation]; - auto* findHelper = FindTabHelper::FromWebState(tab.webState); + auto* findHelper = FindTabHelper::FromWebState(webState); if (findHelper && findHelper->IsFindUIActive()) { [self showFindBarWithAnimation:NO selectText:YES @@ -2481,7 +2481,7 @@ } BOOL hideToolbar = NO; - if (tab.webState) { + if (webState) { // There are times when the NTP can be hidden but before the visibleURL // changes. This can leave the BVC in a blank state where only the bottom // toolbar is visible. Instead, if possible, use the NewTabPageTabHelper @@ -2489,10 +2489,10 @@ BOOL isNTP = false; if (base::FeatureList::IsEnabled(kBrowserContainerContainsNTP)) { NewTabPageTabHelper* NTPHelper = - NewTabPageTabHelper::FromWebState(tab.webState); + NewTabPageTabHelper::FromWebState(webState); isNTP = NTPHelper && NTPHelper->IsActive(); } else { - isNTP = IsVisibleURLNewTabPage(tab.webState); + isNTP = IsVisibleURLNewTabPage(webState); } // Hide the toolbar when displaying content suggestions without the tab // strip, without the focused omnibox, and for UI Refresh, only when in @@ -2813,7 +2813,7 @@ - (id)nativeControllerForTab:(Tab*)tab { id nativeController = tab.webController.nativeController; - if (tab) { + if (tab.webState) { NewTabPageTabHelper* NTPHelper = NewTabPageTabHelper::FromWebState(tab.webState); if (NTPHelper && NTPHelper->IsActive()) @@ -3063,15 +3063,14 @@ - (void)closeWebState:(web::WebState*)webState { // Only allow a web page to close itself if it was opened by DOM, or if there // are no navigation items. - Tab* tab = LegacyTabHelper::GetTabForWebState(webState); - DCHECK(webState->HasOpener() || ![tab navigationManager]->GetItemCount()); - + DCHECK(webState->HasOpener() || + !webState->GetNavigationManager()->GetItemCount()); if (![self tabModel]) return; - - NSUInteger index = [[self tabModel] indexOfTab:tab]; - if (index != NSNotFound) - [[self tabModel] closeTabAtIndex:index]; + WebStateList* webStateList = self.tabModel.webStateList; + int index = webStateList->GetIndexOfWebState(webState); + if (index != WebStateList::kInvalidIndex) + webStateList->CloseWebStateAt(index, WebStateList::CLOSE_USER_ACTION); } - (web::WebState*)webState:(web::WebState*)webState
diff --git a/ios/chrome/browser/ui/page_info/BUILD.gn b/ios/chrome/browser/ui/page_info/BUILD.gn index 632e90fd..f1872f83 100644 --- a/ios/chrome/browser/ui/page_info/BUILD.gn +++ b/ios/chrome/browser/ui/page_info/BUILD.gn
@@ -55,6 +55,7 @@ "//ios/chrome/browser/ui/coordinators:chrome_coordinators", "//ios/chrome/browser/ui/fullscreen:coordinators", "//ios/chrome/browser/ui/page_info/requirements", + "//ios/chrome/browser/web_state_list", "//ios/web", "//ios/web/public", ]
diff --git a/ios/chrome/browser/ui/page_info/page_info_legacy_coordinator.mm b/ios/chrome/browser/ui/page_info/page_info_legacy_coordinator.mm index 9c6987f..a7f3b550 100644 --- a/ios/chrome/browser/ui/page_info/page_info_legacy_coordinator.mm +++ b/ios/chrome/browser/ui/page_info/page_info_legacy_coordinator.mm
@@ -22,6 +22,7 @@ #import "ios/chrome/browser/ui/page_info/requirements/page_info_presentation.h" #import "ios/chrome/browser/ui/page_info/requirements/page_info_reloading.h" #import "ios/chrome/browser/ui/url_loader.h" +#import "ios/chrome/browser/web_state_list/web_state_list.h" #include "ios/web/public/navigation_item.h" #include "ios/web/public/navigation_manager.h" #include "ios/web/public/reload_type.h" @@ -81,9 +82,9 @@ #pragma mark - PageInfoCommands - (void)showPageInfoForOriginPoint:(CGPoint)originPoint { - Tab* tab = self.tabModel.currentTab; - DCHECK([tab navigationManager]); - web::NavigationItem* navItem = [tab navigationManager]->GetVisibleItem(); + web::WebState* webState = self.tabModel.webStateList->GetActiveWebState(); + web::NavigationItem* navItem = + webState->GetNavigationManager()->GetVisibleItem(); // It is fully expected to have a navItem here, as showPageInfoPopup can only // be trigerred by a button enabled when a current item matches some
diff --git a/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.mm b/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.mm index 1f187f5..8783cc1 100644 --- a/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.mm +++ b/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.mm
@@ -517,8 +517,15 @@ SettingsImageDetailTextItem* syncErrorItem = [[SettingsImageDetailTextItem alloc] initWithType:itemType]; syncErrorItem.text = GetNSString(IDS_IOS_SYNC_ERROR_TITLE); - syncErrorItem.detailText = - GetSyncErrorDescriptionForSyncSetupService(self.syncSetupService); + if (itemType == ShowPassphraseDialogErrorItemType) { + // Special case only for the sync passphrase error message. The regular + // error message should be still be displayed in the first settings screen. + syncErrorItem.detailText = GetNSString( + IDS_IOS_GOOGLE_SERVICES_SETTINGS_ENTER_PASSPHRASE_TO_START_SYNC); + } else { + syncErrorItem.detailText = + GetSyncErrorDescriptionForSyncSetupService(self.syncSetupService); + } syncErrorItem.image = [UIImage imageNamed:kGoogleServicesSyncErrorImage]; return syncErrorItem; }
diff --git a/ios/chrome/browser/ui/settings/table_cell_catalog_view_controller.mm b/ios/chrome/browser/ui/settings/table_cell_catalog_view_controller.mm index 42b36f5fa..80c8e370 100644 --- a/ios/chrome/browser/ui/settings/table_cell_catalog_view_controller.mm +++ b/ios/chrome/browser/ui/settings/table_cell_catalog_view_controller.mm
@@ -128,6 +128,16 @@ textImageItem.image = [UIImage imageNamed:@"show_history"]; [model addItem:textImageItem toSectionWithIdentifier:SectionIdentifierText]; + TableViewImageItem* textImageItem2 = + [[TableViewImageItem alloc] initWithType:ItemTypeTextAccessoryImage]; + textImageItem2.title = @"Image item without image, and disabled"; + textImageItem2.textColor = UIColor.redColor; + textImageItem2.detailText = + @"Very very very long detail text for the image cell without image"; + textImageItem2.detailTextColor = UIColor.redColor; + textImageItem2.enabled = NO; + [model addItem:textImageItem2 toSectionWithIdentifier:SectionIdentifierText]; + textImageItem = [[TableViewImageItem alloc] initWithType:ItemTypeTextAccessoryNoImage]; textImageItem.title = @"Image Item with No Image";
diff --git a/ios/chrome/browser/ui/side_swipe/side_swipe_controller.mm b/ios/chrome/browser/ui/side_swipe/side_swipe_controller.mm index 61cf4bb..dd894ee 100644 --- a/ios/chrome/browser/ui/side_swipe/side_swipe_controller.mm +++ b/ios/chrome/browser/ui/side_swipe/side_swipe_controller.mm
@@ -504,7 +504,6 @@ - (void)handleiPhoneTabSwipe:(SideSwipeGestureRecognizer*)gesture { if (gesture.state == UIGestureRecognizerStateBegan) { Tab* currentTab = [model_ currentTab]; - DCHECK(currentTab.webState); inSwipe_ = YES; @@ -513,10 +512,13 @@ // Add horizontal stack view controller. // TODO(crbug.com/904992): Do not use SnapshotGeneratorDelegate from // SideSwipeController. - CGFloat headerHeight = - [self.snapshotDelegate snapshotGenerator:nil - snapshotEdgeInsetsForWebState:currentTab.webState] - .top; + CGFloat headerHeight = 0; + if (currentTab.webState) { + headerHeight = + [self.snapshotDelegate snapshotGenerator:nil + snapshotEdgeInsetsForWebState:currentTab.webState] + .top; + } if (tabSideSwipeView_) { [tabSideSwipeView_ setFrame:frame]; @@ -537,8 +539,10 @@ } // Ensure that there's an up-to-date snapshot of the current tab. - SnapshotTabHelper::FromWebState(currentTab.webState) - ->UpdateSnapshotWithCallback(nil); + if (currentTab.webState) { + SnapshotTabHelper::FromWebState(currentTab.webState) + ->UpdateSnapshotWithCallback(nil); + } // Layout tabs with new snapshots in the current orientation. [tabSideSwipeView_ updateViewsForDirection:gesture.direction];
diff --git a/ios/chrome/browser/ui/table_view/cells/table_view_image_item.h b/ios/chrome/browser/ui/table_view/cells/table_view_image_item.h index dead71ea5..4c5efe3 100644 --- a/ios/chrome/browser/ui/table_view/cells/table_view_image_item.h +++ b/ios/chrome/browser/ui/table_view/cells/table_view_image_item.h
@@ -18,8 +18,16 @@ // The title label in the cell. @property(nonatomic, readwrite, copy) NSString* title; // UIColor for the cell's textLabel. ChromeTableViewStyler's |cellTitleColor| -// takes precedence over the default color, but not over |textColor|. +// takes precedence over black color, but not over |textColor|. @property(nonatomic, strong) UIColor* textColor; + +// UIColor for the cell's detailTextLabel. If not set, +// kTableViewSecondaryLabelLightGrayTextColor is used. +@property(nonatomic, strong) UIColor* detailTextColor; +// Detail text to be displayed. The detail text label is configured wiht +// multiline (no limit). +@property(nonatomic, strong) NSString* detailText; + // Whether the item is enabled. When it is not enabled, the associated cell // cannot be interacted with. @property(nonatomic, assign, getter=isEnabled) BOOL enabled; @@ -33,6 +41,8 @@ @property(nonatomic, readonly, strong) UIImageView* imageView; // The cell title. @property(nonatomic, readonly, strong) UILabel* titleLabel; +// The cell detail text. +@property(nonatomic, readonly, strong) UILabel* detailTextLabel; @end
diff --git a/ios/chrome/browser/ui/table_view/cells/table_view_image_item.mm b/ios/chrome/browser/ui/table_view/cells/table_view_image_item.mm index fcfa04b..3abc0cbd 100644 --- a/ios/chrome/browser/ui/table_view/cells/table_view_image_item.mm +++ b/ios/chrome/browser/ui/table_view/cells/table_view_image_item.mm
@@ -8,6 +8,7 @@ #include "base/mac/foundation_util.h" #import "ios/chrome/browser/ui/table_view/cells/table_view_cells_constants.h" #import "ios/chrome/browser/ui/table_view/chrome_table_view_styler.h" +#import "ios/chrome/browser/ui/util/uikit_ui_util.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -47,6 +48,7 @@ } cell.titleLabel.text = self.title; + cell.detailTextLabel.text = self.detailText; UIColor* cellBackgroundColor = styler.cellBackgroundColor ? styler.cellBackgroundColor : styler.tableViewBackgroundColor; @@ -56,6 +58,14 @@ cell.titleLabel.textColor = self.textColor; } else if (styler.cellTitleColor) { cell.titleLabel.textColor = styler.cellTitleColor; + } else { + cell.textLabel.textColor = UIColor.blackColor; + } + if (self.detailTextColor) { + cell.detailTextLabel.textColor = self.detailTextColor; + } else { + cell.detailTextLabel.textColor = + UIColorFromRGB(kTableViewSecondaryLabelLightGrayTextColor); } cell.userInteractionEnabled = self.enabled; @@ -65,8 +75,9 @@ @implementation TableViewImageCell -// This property overrides the one from UITableViewCell, so this @synthesize +// These properties overrides the ones from UITableViewCell, so this @synthesize // cannot be removed. +@synthesize detailTextLabel = _detailTextLabel; @synthesize imageView = _imageView; - (instancetype)initWithStyle:(UITableViewCellStyle)style @@ -87,16 +98,30 @@ setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis: UILayoutConstraintAxisHorizontal]; + _detailTextLabel = [[UILabel alloc] init]; + _detailTextLabel.font = + [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote]; + _detailTextLabel.adjustsFontForContentSizeCategory = YES; + _detailTextLabel.numberOfLines = 0; + + UIStackView* verticalStack = [[UIStackView alloc] + initWithArrangedSubviews:@[ _titleLabel, _detailTextLabel ]]; + verticalStack.translatesAutoresizingMaskIntoConstraints = NO; + verticalStack.axis = UILayoutConstraintAxisVertical; + verticalStack.spacing = 0; + verticalStack.distribution = UIStackViewDistributionFill; + verticalStack.alignment = UIStackViewAlignmentLeading; + [self.contentView addSubview:verticalStack]; UIStackView* horizontalStack = [[UIStackView alloc] - initWithArrangedSubviews:@[ _imageView, _titleLabel ]]; + initWithArrangedSubviews:@[ _imageView, verticalStack ]]; horizontalStack.translatesAutoresizingMaskIntoConstraints = NO; horizontalStack.axis = UILayoutConstraintAxisHorizontal; horizontalStack.spacing = kTableViewSubViewHorizontalSpacing; horizontalStack.distribution = UIStackViewDistributionFill; horizontalStack.alignment = UIStackViewAlignmentCenter; - [self.contentView addSubview:horizontalStack]; + [NSLayoutConstraint activateConstraints:@[ // Horizontal Stack constraints. [horizontalStack.leadingAnchor @@ -112,13 +137,44 @@ constraintEqualToAnchor:self.contentView.bottomAnchor constant:-kLabelCellVerticalSpacing], ]]; + + [self configureTextLabelForAccessibility: + UIContentSizeCategoryIsAccessibilityCategory( + self.traitCollection.preferredContentSizeCategory)]; } return self; } +#pragma mark - Private + +// Configures -TableViewImageCell.textLabel for accessibility or not. +- (void)configureTextLabelForAccessibility:(BOOL)accessibility { + if (accessibility) { + self.textLabel.numberOfLines = 2; + } else { + self.textLabel.numberOfLines = 1; + } +} + +#pragma mark - UITableViewCell + - (void)prepareForReuse { [super prepareForReuse]; self.userInteractionEnabled = YES; } +#pragma mark - UIView + +- (void)traitCollectionDidChange:(UITraitCollection*)previousTraitCollection { + [super traitCollectionDidChange:previousTraitCollection]; + BOOL isCurrentCategoryAccessibility = + UIContentSizeCategoryIsAccessibilityCategory( + self.traitCollection.preferredContentSizeCategory); + if (isCurrentCategoryAccessibility != + UIContentSizeCategoryIsAccessibilityCategory( + previousTraitCollection.preferredContentSizeCategory)) { + [self configureTextLabelForAccessibility:isCurrentCategoryAccessibility]; + } +} + @end
diff --git a/ios/chrome/browser/ui/table_view/cells/table_view_image_item_unittest.mm b/ios/chrome/browser/ui/table_view/cells/table_view_image_item_unittest.mm index e86ad4f..f75fbdd 100644 --- a/ios/chrome/browser/ui/table_view/cells/table_view_image_item_unittest.mm +++ b/ios/chrome/browser/ui/table_view/cells/table_view_image_item_unittest.mm
@@ -22,9 +22,11 @@ // |configureCell:| and the image are visible. TEST_F(TableViewImageItemTest, ItemProperties) { NSString* text = @"Cell text"; + NSString* detailText = @"Detail text"; TableViewImageItem* item = [[TableViewImageItem alloc] initWithType:0]; item.title = text; + item.detailText = detailText; item.image = [[UIImage alloc] init]; id cell = [[[item cellClass] alloc] init]; @@ -33,10 +35,12 @@ TableViewImageCell* imageCell = base::mac::ObjCCastStrict<TableViewImageCell>(cell); EXPECT_FALSE(imageCell.textLabel.text); + EXPECT_FALSE(imageCell.detailTextLabel.text); EXPECT_FALSE(imageCell.imageView.image); [item configureCell:cell withStyler:[[ChromeTableViewStyler alloc] init]]; EXPECT_NSEQ(text, imageCell.titleLabel.text); + EXPECT_NSEQ(detailText, imageCell.detailTextLabel.text); EXPECT_FALSE(imageCell.imageView.isHidden); }
diff --git a/ios/chrome/browser/ui/tabs/tab_strip_controller.mm b/ios/chrome/browser/ui/tabs/tab_strip_controller.mm index f97ebf8a..8a7964c 100644 --- a/ios/chrome/browser/ui/tabs/tab_strip_controller.mm +++ b/ios/chrome/browser/ui/tabs/tab_strip_controller.mm
@@ -1705,11 +1705,11 @@ DCHECK_NE(NSNotFound, static_cast<NSInteger>(index)); if (index == NSNotFound) return; - Tab* tab = [_tabModel tabAtIndex:index]; + web::WebState* webState = _tabModel.webStateList->GetWebStateAt(index); web::NavigationManager::WebLoadParams params(url); params.transition_type = ui::PAGE_TRANSITION_GENERATED; - tab.navigationManager->LoadURLWithParams(params); + webState->GetNavigationManager()->LoadURLWithParams(params); } @end
diff --git a/ios/chrome/common/app_group/app_group_constants.h b/ios/chrome/common/app_group/app_group_constants.h index 925b89f..3da94891 100644 --- a/ios/chrome/common/app_group/app_group_constants.h +++ b/ios/chrome/common/app_group/app_group_constants.h
@@ -52,6 +52,9 @@ // The command to search some text. Parameter must contain the text. extern const char kChromeAppGroupSearchTextCommand[]; +// The command to search an image. Data parameter must contain the image. +extern const char kChromeAppGroupSearchImageCommand[]; + // The command to trigger a voice search. extern const char kChromeAppGroupVoiceSearchCommand[]; @@ -75,6 +78,10 @@ // command if it requires one. This could be a URL, a string, etc. extern const char kChromeAppGroupCommandTextPreference[]; +// The key in kChromeAppGroupCommandPreference containing the data to use for +// the command if it requires one. This could be an image, etc. +extern const char kChromeAppGroupCommandDataPreference[]; + // The key in kChromeAppGroupCommandPreference containing the index to open for // if the command requires one. extern const char kChromeAppGroupCommandIndexPreference[];
diff --git a/ios/chrome/common/app_group/app_group_constants.mm b/ios/chrome/common/app_group/app_group_constants.mm index 752dd77..f26ab94 100644 --- a/ios/chrome/common/app_group/app_group_constants.mm +++ b/ios/chrome/common/app_group/app_group_constants.mm
@@ -26,10 +26,12 @@ const char kChromeAppGroupCommandAppPreference[] = "SourceApp"; const char kChromeAppGroupCommandCommandPreference[] = "Command"; const char kChromeAppGroupCommandTextPreference[] = "Text"; +const char kChromeAppGroupCommandDataPreference[] = "Data"; const char kChromeAppGroupCommandIndexPreference[] = "Index"; const char kChromeAppGroupOpenURLCommand[] = "openurl"; const char kChromeAppGroupSearchTextCommand[] = "searchtext"; +const char kChromeAppGroupSearchImageCommand[] = "searchimage"; const char kChromeAppGroupVoiceSearchCommand[] = "voicesearch"; const char kChromeAppGroupNewTabCommand[] = "newtab"; const char kChromeAppGroupFocusOmniboxCommand[] = "focusomnibox";
diff --git a/ios/chrome/common/ui_util/BUILD.gn b/ios/chrome/common/ui_util/BUILD.gn index 07f5302..5d6452b 100644 --- a/ios/chrome/common/ui_util/BUILD.gn +++ b/ios/chrome/common/ui_util/BUILD.gn
@@ -6,9 +6,12 @@ sources = [ "constraints_ui_util.h", "constraints_ui_util.mm", + "image_util.h", + "image_util.mm", ] deps = [ "//base", + "//ui/gfx:resize_image_dimensions", ] configs += [ "//build/config/compiler:enable_arc" ] }
diff --git a/ios/chrome/common/ui_util/image_util.h b/ios/chrome/common/ui_util/image_util.h new file mode 100644 index 0000000..74346cc9 --- /dev/null +++ b/ios/chrome/common/ui_util/image_util.h
@@ -0,0 +1,20 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_COMMON_UI_UTIL_IMAGE_UTIL_H_ +#define IOS_CHROME_COMMON_UI_UTIL_IMAGE_UTIL_H_ + +#import <UIKit/UIKit.h> + +/** + Scale down the image if it's too large so it doesn't take too much space + to store or too much data to upload. + This is taken from Google Toolbox for Mac. Extensions should not have + too many dependencies, so this is reproduced here. This should not be used + outside of extensions. Instead, use the simpler version in + //ui/gfx/image/image_util.h. + */ +UIImage* ResizeImageForSearchByImage(UIImage* image); + +#endif // IOS_CHROME_COMMON_UI_UTIL_IMAGE_UTIL_H_
diff --git a/ios/chrome/common/ui_util/image_util.mm b/ios/chrome/common/ui_util/image_util.mm new file mode 100644 index 0000000..d1cf097 --- /dev/null +++ b/ios/chrome/common/ui_util/image_util.mm
@@ -0,0 +1,66 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/common/ui_util/image_util.h" + +#include "ui/gfx/image/resize_image_dimensions.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +UIImage* ResizeImageForSearchByImage(UIImage* image) { + // Check |image|. + if (!image) { + return nil; + } + CGSize imageSize = [image size]; + if (imageSize.height < 1 || imageSize.width < 1) { + return nil; + } + + // Image is already smaller than the max allowed area. + if (image.size.height * image.size.width < gfx::kSearchByImageMaxImageArea) { + return image; + } + // If one dimension is small enough, then no need to resize. + if ((image.size.width < gfx::kSearchByImageMaxImageWidth && + image.size.height < gfx::kSearchByImageMaxImageHeight)) { + return image; + } + + CGSize targetSize = CGSizeMake(gfx::kSearchByImageMaxImageWidth, + gfx::kSearchByImageMaxImageHeight); + if (targetSize.height < 1 || targetSize.width < 1) { + return nil; + } + CGFloat aspectRatio = imageSize.width / imageSize.height; + CGFloat targetAspectRatio = targetSize.width / targetSize.height; + CGRect projectTo = CGRectZero; + // Scale image to ensure it fits inside the specified targetSize. + if (targetAspectRatio < aspectRatio) { + // target is less wide than the original. + projectTo.size.width = targetSize.width; + projectTo.size.height = projectTo.size.width / aspectRatio; + targetSize = projectTo.size; + } else { + // target is wider than the original. + projectTo.size.height = targetSize.height; + projectTo.size.width = projectTo.size.height * aspectRatio; + targetSize = projectTo.size; + } + projectTo = CGRectIntegral(projectTo); + // There's no CGSizeIntegral, so we fake our own. + CGRect integralRect = CGRectZero; + integralRect.size = targetSize; + targetSize = CGRectIntegral(integralRect).size; + + // Resize photo. Use UIImage drawing methods because they respect + // UIImageOrientation as opposed to CGContextDrawImage(). + UIGraphicsBeginImageContext(targetSize); + [image drawInRect:projectTo]; + UIImage* resizedPhoto = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + return resizedPhoto; +}
diff --git a/ios/chrome/search_widget_extension/copied_content_view.h b/ios/chrome/search_widget_extension/copied_content_view.h index 01255ac..82b111d8 100644 --- a/ios/chrome/search_widget_extension/copied_content_view.h +++ b/ios/chrome/search_widget_extension/copied_content_view.h
@@ -13,6 +13,7 @@ CopiedContentTypeNone, CopiedContentTypeURL, CopiedContentTypeString, + CopiedContentTypeImage, }; // View to show and allow opening of the copied URL. Shows a button with the
diff --git a/ios/chrome/search_widget_extension/copied_content_view.mm b/ios/chrome/search_widget_extension/copied_content_view.mm index db5b381..a8630c5 100644 --- a/ios/chrome/search_widget_extension/copied_content_view.mm +++ b/ios/chrome/search_widget_extension/copied_content_view.mm
@@ -181,6 +181,10 @@ contentText = self.copiedText; break; } + case CopiedContentTypeImage: { + titleText = NSLocalizedString(@"IDS_IOS_OPEN_COPIED_IMAGE", nil); + break; + } } self.openCopiedContentTitleLabel.text = titleText; self.copiedContentLabel.text = contentText;
diff --git a/ios/chrome/search_widget_extension/search_widget_extension_localize_strings_config.plist b/ios/chrome/search_widget_extension/search_widget_extension_localize_strings_config.plist index 8e4851a..bb814ba 100644 --- a/ios/chrome/search_widget_extension/search_widget_extension_localize_strings_config.plist +++ b/ios/chrome/search_widget_extension/search_widget_extension_localize_strings_config.plist
@@ -22,6 +22,7 @@ <string>IDS_IOS_NO_COPIED_CONTENT_MESSAGE</string> <string>IDS_IOS_OPEN_COPIED_LINK</string> <string>IDS_IOS_OPEN_COPIED_TEXT</string> + <string>IDS_IOS_OPEN_COPIED_IMAGE</string> </array> </dict> <dict>
diff --git a/ios/chrome/search_widget_extension/search_widget_view_controller.mm b/ios/chrome/search_widget_extension/search_widget_view_controller.mm index 453bc69..c0250b4 100644 --- a/ios/chrome/search_widget_extension/search_widget_view_controller.mm +++ b/ios/chrome/search_widget_extension/search_widget_view_controller.mm
@@ -11,6 +11,7 @@ #include "ios/chrome/common/app_group/app_group_field_trial_version.h" #include "ios/chrome/common/app_group/app_group_metrics.h" #import "ios/chrome/common/ui_util/constraints_ui_util.h" +#import "ios/chrome/common/ui_util/image_util.h" #import "ios/chrome/search_widget_extension/copied_content_view.h" #import "ios/chrome/search_widget_extension/search_widget_view.h" @@ -29,6 +30,7 @@ @interface SearchWidgetViewController ()<SearchWidgetViewActionTarget> @property(nonatomic, weak) SearchWidgetView* widgetView; @property(nonatomic, strong, nullable) NSString* copiedText; +@property(nonatomic, strong, nullable) UIImage* copiedImage; @property(nonatomic) CopiedContentType copiedContentType; @property(nonatomic, strong) ClipboardRecentContentImplIOS* clipboardRecentContent; @@ -40,20 +42,27 @@ - (BOOL)updateWidget; // Opens the main application with the given |command|. - (void)openAppWithCommand:(NSString*)command; -// Opens the main application with the given |command| and |text|. -- (void)openAppWithCommand:(NSString*)command text:(NSString*)text; +// Opens the main application with the given |command|, |text|, and |image|. +- (void)openAppWithCommand:(NSString*)command + text:(NSString*)text + imageData:(NSData*)imageData; // Returns the dictionary of commands to pass via user defaults to open the main -// application for a given |command| and optional |text|. -+ (NSDictionary*)dictForCommand:(NSString*)command text:(NSString*)text; +// application for a given |command| and optional |text| and |image|. ++ (NSDictionary*)dictForCommand:(NSString*)command + text:(NSString*)text + imageData:(NSData*)imageData; // Register a display of the widget in the app_group NSUserDefaults. // Metrics on the widget usage will be sent (if enabled) on the next Chrome // startup. - (void)registerWidgetDisplay; // Sets the copied content type. |copiedText| should be provided if the content -// type requires textual data, otherwise it should be nil. Also saves the data -// and returns YES if the screen needs updating and NO otherwise. +// type requires textual data, otherwise it should be nil. Likewise, +// |copiedImage| should be provided if the content type requires image data. +// Also saves the data and returns YES if the screen needs updating and NO +// otherwise. - (BOOL)setCopiedContentType:(CopiedContentType)type - copiedText:(NSString*)copiedText; + copiedText:(NSString*)copiedText + copiedImage:(UIImage*)copiedImage; @end @@ -128,9 +137,14 @@ self.fieldTrialValues = [sharedDefaults dictionaryForKey:fieldTrialKey]; NSString* copiedText; + UIImage* copiedImage; CopiedContentType type = CopiedContentTypeNone; - if (NSURL* url = [self.clipboardRecentContent recentURLFromClipboard]) { + if (UIImage* image = [self getCopiedImageUsingFlag]) { + copiedImage = image; + type = CopiedContentTypeImage; + } else if (NSURL* url = + [self.clipboardRecentContent recentURLFromClipboard]) { copiedText = url.absoluteString; type = CopiedContentTypeURL; } else if (NSString* text = [self getCopiedTextUsingFlag]) { @@ -138,7 +152,9 @@ type = CopiedContentTypeString; } - return [self setCopiedContentType:type copiedText:copiedText]; + return [self setCopiedContentType:type + copiedText:copiedText + copiedImage:copiedImage]; } // Helper method to encapsulate both checking the flag and getting the copied @@ -151,6 +167,16 @@ return [self.clipboardRecentContent recentTextFromClipboard]; } +// Helper method to encapsulate both checking the flag and getting the copied +// image. +// TODO(crbug.com/932116): Can be removed when the flag is cleaned up. +- (UIImage*)getCopiedImageUsingFlag { + if (!self.copiedContentBehaviorEnabled) { + return nil; + } + return [self.clipboardRecentContent recentImageFromClipboard]; +} + - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator: (id<UIViewControllerTransitionCoordinator>)coordinator { @@ -208,8 +234,9 @@ } - (void)openCopiedContent:(id)sender { - DCHECK(self.copiedText); + DCHECK([self verifyCopiedContentType]); NSString* command; + NSData* imageData; switch (self.copiedContentType) { case CopiedContentTypeURL: command = @@ -219,17 +246,26 @@ command = base::SysUTF8ToNSString(app_group::kChromeAppGroupSearchTextCommand); break; + case CopiedContentTypeImage: { + command = + base::SysUTF8ToNSString(app_group::kChromeAppGroupSearchImageCommand); + + // Resize image before converting to NSData so we can store less data. + UIImage* resizedImage = ResizeImageForSearchByImage(self.copiedImage); + imageData = UIImageJPEGRepresentation(resizedImage, 1.0); + break; + } case CopiedContentTypeNone: NOTREACHED(); return; } - [self openAppWithCommand:command text:self.copiedText]; + [self openAppWithCommand:command text:self.copiedText imageData:imageData]; } #pragma mark - internal - (void)openAppWithCommand:(NSString*)command { - return [self openAppWithCommand:command text:nil]; + return [self openAppWithCommand:command text:nil imageData:nil]; } - (void)registerWidgetDisplay { @@ -240,13 +276,17 @@ forKey:app_group::kSearchExtensionDisplayCount]; } -- (void)openAppWithCommand:(NSString*)command text:(NSString*)text { +- (void)openAppWithCommand:(NSString*)command + text:(NSString*)text + imageData:(NSData*)imageData { NSUserDefaults* sharedDefaults = app_group::GetGroupUserDefaults(); NSString* defaultsKey = base::SysUTF8ToNSString(app_group::kChromeAppGroupCommandPreference); - [sharedDefaults setObject:[SearchWidgetViewController dictForCommand:command - text:text] - forKey:defaultsKey]; + [sharedDefaults + setObject:[SearchWidgetViewController dictForCommand:command + text:text + imageData:imageData] + forKey:defaultsKey]; [sharedDefaults synchronize]; NSString* scheme = base::mac::ObjCCast<NSString>([[NSBundle mainBundle] @@ -265,7 +305,9 @@ [self.extensionContext openURL:openURL completionHandler:nil]; } -+ (NSDictionary*)dictForCommand:(NSString*)command text:(NSString*)text { ++ (NSDictionary*)dictForCommand:(NSString*)command + text:(NSString*)text + imageData:(NSData*)imageData { NSString* timePrefKey = base::SysUTF8ToNSString(app_group::kChromeAppGroupCommandTimePreference); NSString* appPrefKey = @@ -273,36 +315,56 @@ NSString* commandPrefKey = base::SysUTF8ToNSString( app_group::kChromeAppGroupCommandCommandPreference); - if (text) { - NSString* textPrefKey = base::SysUTF8ToNSString( - app_group::kChromeAppGroupCommandTextPreference); - return @{ - timePrefKey : [NSDate date], - appPrefKey : app_group::kOpenCommandSourceSearchExtension, - commandPrefKey : command, - textPrefKey : text, - }; - } - return @{ + NSMutableDictionary* baseKeys = [@{ timePrefKey : [NSDate date], appPrefKey : app_group::kOpenCommandSourceSearchExtension, commandPrefKey : command, - }; + } mutableCopy]; + + if (text) { + NSString* TextPrefKey = base::SysUTF8ToNSString( + app_group::kChromeAppGroupCommandTextPreference); + baseKeys[TextPrefKey] = text; + } + + if (imageData) { + NSString* DataPrefKey = base::SysUTF8ToNSString( + app_group::kChromeAppGroupCommandDataPreference); + baseKeys[DataPrefKey] = imageData; + } + + return baseKeys; } - (BOOL)setCopiedContentType:(CopiedContentType)type - copiedText:(NSString*)copiedText { + copiedText:(NSString*)copiedText + copiedImage:(UIImage*)copiedImage { if (self.copiedContentType == type && - [self.copiedText isEqualToString:copiedText]) { + [self.copiedText isEqualToString:copiedText] && + [self.copiedImage isEqual:copiedImage]) { return NO; } self.copiedContentType = type; self.copiedText = copiedText; + self.copiedImage = copiedImage; [self.widgetView setCopiedContentType:self.copiedContentType copiedText:self.copiedText]; return YES; } +// Verifies that the current copied content type has the required data with it. +- (BOOL)verifyCopiedContentType { + switch (self.copiedContentType) { + case CopiedContentTypeString: + case CopiedContentTypeURL: + return self.copiedText; + case CopiedContentTypeImage: + return self.copiedImage; + case CopiedContentTypeNone: + return true; + } +} + - (BOOL)copiedContentBehaviorEnabled { NSDictionary* storedData = self.fieldTrialValues[@"CopiedContentBehavior"]; if (![kCopiedContentBehaviorVersion
diff --git a/ios/chrome/search_widget_extension/strings/ios_search_widget_extension_strings.grd b/ios/chrome/search_widget_extension/strings/ios_search_widget_extension_strings.grd index ada8007..b30b6ae 100644 --- a/ios/chrome/search_widget_extension/strings/ios_search_widget_extension_strings.grd +++ b/ios/chrome/search_widget_extension/strings/ios_search_widget_extension_strings.grd
@@ -148,12 +148,15 @@ <message name="IDS_IOS_NO_COPIED_CONTENT_MESSAGE" desc="Label in the widget extension for the message shown in the copied link section when there is no copied content."> Content you copy will appear here. </message> - <message name="IDS_IOS_OPEN_COPIED_LINK" desc="Label in the widget extension for the title of the copied content section when there is a copied link displayed."> + <message name="IDS_IOS_OPEN_COPIED_LINK" desc="If a user has a URL on their clipboard, this string will appear as an option on the Chrome iOS widget. The user can select this option to visit the URL. This string is a complete sentence. If necessary for your language, you can translate as 'Visit Link That You Copied.'" meaning="Maximum characters: 27"> Visit Link You Copied </message> - <message name="IDS_IOS_OPEN_COPIED_TEXT" desc="Label in the widget extension for the title of the copied content section when there is copied text displayed."> + <message name="IDS_IOS_OPEN_COPIED_TEXT" desc="If a user has some text on their clipboard, this string will appear as an option on the Chrome iOS widget. The user can select this option to search Google for the text. This string is a complete sentence. If necessary for your language, you can translate as 'Search for Text That You Copied.'" meaning="Maximum characters: 27"> Search for Text You Copied </message> + <message name="IDS_IOS_OPEN_COPIED_IMAGE" desc="If a user has some text on their clipboard, this string will appear as an option on the Chrome iOS widget. The user can select this option to search Google for the text. This string is a complete sentence. If necessary for your language, you can translate as 'Search for Text That You Copied.'" meaning="Maximum characters: 27"> + Search for Image You Copied + </message> </messages> </release> </grit>
diff --git a/ios/chrome/search_widget_extension/strings/ios_search_widget_extension_strings_grd/IDS_IOS_OPEN_COPIED_IMAGE.png.sha1 b/ios/chrome/search_widget_extension/strings/ios_search_widget_extension_strings_grd/IDS_IOS_OPEN_COPIED_IMAGE.png.sha1 new file mode 100644 index 0000000..d622ab8 --- /dev/null +++ b/ios/chrome/search_widget_extension/strings/ios_search_widget_extension_strings_grd/IDS_IOS_OPEN_COPIED_IMAGE.png.sha1
@@ -0,0 +1 @@ +6f8176ab162d480fddad05e5daca81355fdf41a0 \ No newline at end of file
diff --git a/ios/net/cookies/cookie_store_ios.h b/ios/net/cookies/cookie_store_ios.h index e7bb38f..9cf07461 100644 --- a/ios/net/cookies/cookie_store_ios.h +++ b/ios/net/cookies/cookie_store_ios.h
@@ -267,7 +267,8 @@ // asynchronous cache update (using UpdateCachesFromCookieMonster()) and // calling the provided callback. - void UpdateCachesAfterSet(SetCookiesCallback callback, bool success); + void UpdateCachesAfterSet(SetCookiesCallback callback, + net::CanonicalCookie::CookieInclusionStatus status); void UpdateCachesAfterDelete(DeleteCallback callback, uint32_t num_deleted); void UpdateCachesAfterClosure(base::OnceClosure callback);
diff --git a/ios/net/cookies/cookie_store_ios.mm b/ios/net/cookies/cookie_store_ios.mm index 3cbabb6..d2d85815 100644 --- a/ios/net/cookies/cookie_store_ios.mm +++ b/ios/net/cookies/cookie_store_ios.mm
@@ -136,13 +136,13 @@ } // Returns an empty closure if |callback| is null callback or binds the -// callback to |success|. +// callback to |status|. base::OnceClosure BindSetCookiesCallback( CookieStoreIOS::SetCookiesCallback* callback, - bool success) { + net::CanonicalCookie::CookieInclusionStatus status) { base::OnceClosure set_callback; if (!callback->is_null()) { - set_callback = base::BindOnce(std::move(*callback), success); + set_callback = base::BindOnce(std::move(*callback), status); } return set_callback; } @@ -298,7 +298,10 @@ bool has_explicit_domain = HasExplicitDomain(cookie_line); bool has_valid_domain = net::cookie_util::GetCookieDomainWithString(url, domain_string, &dummy); - // A cookie can be set if all of: + net::CanonicalCookie::CookieInclusionStatus status = + net::CanonicalCookie::CookieInclusionStatus::INCLUDE; + + // A cookie can be set if all of the following conditions are met: // a) The cookie line is well-formed // b) The Domain attribute, if present, was not malformed // c) At least one of: @@ -306,17 +309,33 @@ // from the URL, or // 2) The cookie had an explicit Domain for which the URL is allowed // to set cookies. - bool success = (cookie != nil) && !domain_string.empty() && - (!has_explicit_domain || has_valid_domain); - if (success) { - system_store_->SetCookieAsync(cookie, - BindSetCookiesCallback(&callback, true)); + // If |cookie| is nil, the cookie line was not well-formed. + if (cookie == nil) + status = + net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE; + + // If |domain_string| is empty, the domain was not well-formed. + if (domain_string.empty()) + status = + net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_INVALID_DOMAIN; + + // If the cookie had an explicit domain and it's not a domain it's allowed to + // set cookies to. + if (has_explicit_domain && !has_valid_domain) + status = + net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_INVALID_DOMAIN; + + if (status == net::CanonicalCookie::CookieInclusionStatus::INCLUDE) { + system_store_->SetCookieAsync( + cookie, + BindSetCookiesCallback( + &callback, net::CanonicalCookie::CookieInclusionStatus::INCLUDE)); return; } if (!callback.is_null()) - std::move(callback).Run(false); + std::move(callback).Run(status); } void CookieStoreIOS::SetCanonicalCookieAsync( @@ -337,20 +356,24 @@ if (cookie->IsSecure() && !secure_source) { if (!callback.is_null()) - std::move(callback).Run(false); + std::move(callback).Run( + net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_SECURE_ONLY); return; } NSHTTPCookie* ns_cookie = SystemCookieFromCanonicalCookie(*cookie.get()); if (ns_cookie != nil) { - system_store_->SetCookieAsync(ns_cookie, &cookie->CreationDate(), - BindSetCookiesCallback(&callback, true)); + system_store_->SetCookieAsync( + ns_cookie, &cookie->CreationDate(), + BindSetCookiesCallback( + &callback, net::CanonicalCookie::CookieInclusionStatus::INCLUDE)); return; } if (!callback.is_null()) - std::move(callback).Run(false); + std::move(callback).Run( + net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE); } void CookieStoreIOS::GetCookieListWithOptionsAsync( @@ -721,13 +744,14 @@ } } -void CookieStoreIOS::UpdateCachesAfterSet(SetCookiesCallback callback, - bool success) { +void CookieStoreIOS::UpdateCachesAfterSet( + SetCookiesCallback callback, + net::CanonicalCookie::CookieInclusionStatus status) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - if (success) + if (status == net::CanonicalCookie::CookieInclusionStatus::INCLUDE) UpdateCachesFromCookieMonster(); if (!callback.is_null()) - std::move(callback).Run(success); + std::move(callback).Run(status); } void CookieStoreIOS::UpdateCachesAfterDelete(DeleteCallback callback,
diff --git a/ios/net/cookies/cookie_store_ios_test_util.mm b/ios/net/cookies/cookie_store_ios_test_util.mm index 4994b8f..426c0527 100644 --- a/ios/net/cookies/cookie_store_ios_test_util.mm +++ b/ios/net/cookies/cookie_store_ios_test_util.mm
@@ -9,6 +9,7 @@ #include <memory> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/run_loop.h" #include "base/test/test_simple_task_runner.h" #include "base/threading/thread_task_runner_handle.h" @@ -23,12 +24,6 @@ namespace net { -namespace { - -void IgnoreBoolean(bool not_used) {} - -} // namespace - #pragma mark - #pragma mark TestPersistentCookieStore @@ -141,7 +136,7 @@ net::CookieOptions options; options.set_include_httponly(); store->SetCookieWithOptionsAsync(url, cookie_line, options, - base::Bind(&IgnoreBoolean)); + base::DoNothing()); net::CookieStoreIOS::NotifySystemCookiesChanged(); // Wait until the flush is posted. base::RunLoop().RunUntilIdle();
diff --git a/ios/third_party/material_components_ios/README.chromium b/ios/third_party/material_components_ios/README.chromium index 336d6db0..21dc2c9 100644 --- a/ios/third_party/material_components_ios/README.chromium +++ b/ios/third_party/material_components_ios/README.chromium
@@ -1,7 +1,7 @@ Name: Material Components for iOS URL: https://github.com/material-components/material-components-ios Version: 0 -Revision: 63faa33898c3041fcd87ca3abf173b6647e971f3 +Revision: b86526c41f4fd9577b6fc24b4d90a707cd8c5389 License: Apache 2.0 License File: LICENSE Security Critical: yes
diff --git a/ios/third_party/webkit/BUILD.gn b/ios/third_party/webkit/BUILD.gn new file mode 100644 index 0000000..adda1074 --- /dev/null +++ b/ios/third_party/webkit/BUILD.gn
@@ -0,0 +1,46 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/config/gclient_args.gni") +import("//build/config/ios/ios_sdk.gni") + +if (checkout_ios_webkit) { + action("webkit") { + script = "build_webkit.py" + + inputs = [ + # Because it's difficult to list every webkit source file as an input + # here, use the ChangeLog files as a proxy to determine whether or not + # source files have changed. + # TODO(crbug.com/934252): This will not pick up local edits to source + # files, so find a way to properly rebuild when those change. + "src/Tools/ChangeLog", + "src/ChangeLog", + "src/Source/WebKit/ChangeLog", + "src/Source/JavaScriptCore/ChangeLog", + "src/Source/WebKitLegacy/ChangeLog", + "src/Source/WebKitLegacy/ios/ChangeLog", + "src/Source/WebKitLegacy/mac/ChangeLog", + "src/Source/bmalloc/ChangeLog", + "src/Source/WebCore/ChangeLog", + "src/Source/WTF/ChangeLog", + "src/Source/ThirdParty/ChangeLog", + "src/WebKitLibraries/ChangeLog", + ] + + outputs = [ + # The frameworks themselves include many resource files, but as a first + # step, use just the binaries. + "$target_out_dir/Debug-iphonesimulator/JavaScriptCore.framework/JavaScriptCore", + "$target_out_dir/Debug-iphonesimulator/WebCore.framework/WebCore", + "$target_out_dir/Debug-iphonesimulator/WebKit.framework/WebKit", + "$target_out_dir/Debug-iphonesimulator/WebKitLegacy.framework/WebKitLegacy", + ] + + args = [ + "--output_dir", + rebase_path("$target_out_dir"), + ] + } +}
diff --git a/ios/third_party/webkit/build_webkit.py b/ios/third_party/webkit/build_webkit.py new file mode 100755 index 0000000..11341290 --- /dev/null +++ b/ios/third_party/webkit/build_webkit.py
@@ -0,0 +1,39 @@ +#!/usr/bin/env python +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import optparse +import os +import subprocess +import sys + +def main(): + usage = ('%prog [options]\n' + 'Invokes build-webkit with the given options.') + parser = optparse.OptionParser(usage=usage) + parser.add_option('-o', '--output_dir', + help='Output directory for build products.') + (opts, args) = parser.parse_args() + + if not opts.output_dir: + print >>sys.stderr, '--output_dir is required.' + return 1 + + # TODO(crbug.com/934252): "-jobs 2" is passed along to the underlying + # xcodebuild invocation and restricts xcodebuild to two simultaneous + # jobs. This is intended to prevent overloading the machine, because ninja + # will already be spawning a large number of jobs in parallel with xcodebuild, + # but it causes the webkit build to run very slowly. Find a way to increase + # the parallelism here. + command = ['src/Tools/Scripts/build-webkit', '--debug', '--ios-simulator', + '-quiet', '-jobs', '2'] + + env = {'WEBKIT_OUTPUTDIR': opts.output_dir} + cwd = os.path.dirname(os.path.realpath(__file__)) + proc = subprocess.Popen(command, cwd=cwd, env=env) + proc.communicate() + return proc.returncode + +if __name__ == '__main__': + sys.exit(main())
diff --git a/ios/web_view/internal/signin/web_view_identity_manager_factory.mm b/ios/web_view/internal/signin/web_view_identity_manager_factory.mm index 8d3d5f48..0e2ea9c 100644 --- a/ios/web_view/internal/signin/web_view_identity_manager_factory.mm +++ b/ios/web_view/internal/signin/web_view_identity_manager_factory.mm
@@ -16,6 +16,7 @@ #include "ios/web_view/internal/web_view_browser_state.h" #include "services/identity/public/cpp/accounts_cookie_mutator_impl.h" #include "services/identity/public/cpp/accounts_mutator.h" +#include "services/identity/public/cpp/diagnostics_provider_impl.h" #include "services/identity/public/cpp/identity_manager.h" #include "services/identity/public/cpp/primary_account_mutator_impl.h" @@ -52,6 +53,11 @@ nullptr, std::make_unique<identity::AccountsCookieMutatorImpl>( WebViewGaiaCookieManagerServiceFactory::GetForBrowserState( + browser_state)), + std::make_unique<identity::DiagnosticsProviderImpl>( + WebViewOAuth2TokenServiceFactory::GetForBrowserState( + browser_state), + WebViewGaiaCookieManagerServiceFactory::GetForBrowserState( browser_state))) {} };
diff --git a/media/base/android/media_drm_storage.h b/media/base/android/media_drm_storage.h index 6e9a75f..276ebc9 100644 --- a/media/base/android/media_drm_storage.h +++ b/media/base/android/media_drm_storage.h
@@ -14,6 +14,7 @@ #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "base/optional.h" #include "media/base/android/media_drm_key_type.h" #include "media/base/media_export.h" #include "url/origin.h" @@ -29,6 +30,10 @@ class MEDIA_EXPORT MediaDrmStorage : public base::SupportsWeakPtr<MediaDrmStorage> { public: + // When using per-origin provisioning, this is the ID for the origin. + // If not specified, the device specific origin ID is to be used. + using MediaDrmOriginId = base::Optional<base::UnguessableToken>; + struct SessionData { SessionData(std::vector<uint8_t> key_set_id, std::string mime_type, @@ -49,8 +54,7 @@ // Callback for storage initialization. using InitCB = - base::OnceCallback<void(bool success, - const base::UnguessableToken& origin_id)>; + base::OnceCallback<void(bool success, const MediaDrmOriginId& origin_id)>; // Callback to return the result of LoadPersistentSession. |key_set_id| and // |mime_type| must be non-empty if |success| is true, and vice versa.
diff --git a/media/base/android/media_drm_storage_bridge.cc b/media/base/android/media_drm_storage_bridge.cc index 926bca95..081ab9d5 100644 --- a/media/base/android/media_drm_storage_bridge.cc +++ b/media/base/android/media_drm_storage_bridge.cc
@@ -149,13 +149,13 @@ void MediaDrmStorageBridge::OnInitialized( InitCB init_cb, bool success, - const base::UnguessableToken& origin_id) { + const MediaDrmStorage::MediaDrmOriginId& origin_id) { // Note: It's possible that |success| is true but |origin_id| is empty, // to indicate per-device provisioning. In this case, we cannot use // ToString() which would be the string 0000000000000000. Instead, do // not set |origin_id_| so that it remains empty. - if (success && origin_id) { - origin_id_ = origin_id.ToString(); + if (success && origin_id && origin_id.value()) { + origin_id_ = origin_id->ToString(); } else { DCHECK(!origin_id); }
diff --git a/media/base/android/media_drm_storage_bridge.h b/media/base/android/media_drm_storage_bridge.h index 48caa08..4610bee 100644 --- a/media/base/android/media_drm_storage_bridge.h +++ b/media/base/android/media_drm_storage_bridge.h
@@ -76,7 +76,7 @@ void RunAndroidBoolCallback(JavaObjectPtr j_callback, bool success); void OnInitialized(InitCB init_cb, bool success, - const base::UnguessableToken& origin_id); + const MediaDrmStorage::MediaDrmOriginId& origin_id); void OnSessionDataLoaded( JavaObjectPtr j_callback, const std::string& session_id,
diff --git a/media/base/media_switches.cc b/media/base/media_switches.cc index dd61212c..1a142e0 100644 --- a/media/base/media_switches.cc +++ b/media/base/media_switches.cc
@@ -470,9 +470,16 @@ const base::Feature kMediaLearningExperiment{"MediaLearningExperiment", base::FEATURE_DISABLED_BY_DEFAULT}; -// Enables flash to be ducked by audio focus. -const base::Feature kAudioFocusDuckFlash{"AudioFocusDuckFlash", - base::FEATURE_DISABLED_BY_DEFAULT}; +// Enables flash to be ducked by audio focus. This is enabled on Chrome OS which +// has audio focus enabled. +const base::Feature kAudioFocusDuckFlash { + "AudioFocusDuckFlash", +#if defined(OS_CHROMEOS) + base::FEATURE_ENABLED_BY_DEFAULT +#else + base::FEATURE_DISABLED_BY_DEFAULT +#endif +}; // Enables the internal Media Session logic without enabling the Media Session // service.
diff --git a/media/base/video_frame_layout.h b/media/base/video_frame_layout.h index b8ec34a..6825d7ce 100644 --- a/media/base/video_frame_layout.h +++ b/media/base/video_frame_layout.h
@@ -45,9 +45,8 @@ bool operator==(const Plane& rhs) const; bool operator!=(const Plane& rhs) const; - // Strides of a plane, typically greater or equal to the - // width of the surface divided by the horizontal sampling period. Note that - // strides can be negative if the image layout is bottom-up. + // Strides in bytes of a plane. Note that stride can be negative if the + // image layout is bottom-up. int32_t stride = 0; // Offset of a plane, which stands for the offset of a start point of a
diff --git a/media/gpu/v4l2/generic_v4l2_device.cc b/media/gpu/v4l2/generic_v4l2_device.cc index 6246b375..63d688b 100644 --- a/media/gpu/v4l2/generic_v4l2_device.cc +++ b/media/gpu/v4l2/generic_v4l2_device.cc
@@ -362,7 +362,7 @@ auto image = base::MakeRefCounted<gl::GLImageNativePixmap>(size, buffer_format); - bool ret = image->Initialize(pixmap.get()); + bool ret = image->Initialize(std::move(pixmap)); DCHECK(ret); return image; }
diff --git a/media/gpu/v4l2/v4l2_device.cc b/media/gpu/v4l2/v4l2_device.cc index f6b1066..f56b0bb 100644 --- a/media/gpu/v4l2/v4l2_device.cc +++ b/media/gpu/v4l2/v4l2_device.cc
@@ -4,6 +4,8 @@ #include "media/gpu/v4l2/v4l2_device.h" +#include <set> + #include <libdrm/drm_fourcc.h> #include <linux/videodev2.h> #include <string.h> @@ -154,20 +156,66 @@ return usage; } +// A thread-safe pool of buffer indexes, allowing buffers to be obtained and +// returned from different threads. All the methods of this class are +// thread-safe. Users should keep a scoped_refptr to instances of this class +// in order to ensure the list remains alive as long as they need it. +class V4L2BuffersList : public base::RefCountedThreadSafe<V4L2BuffersList> { + public: + V4L2BuffersList() = default; + // Return a buffer to this list. Also can be called to set the initial pool + // of buffers. + // Note that it is illegal to return the same buffer twice. + void ReturnBuffer(size_t buffer_id); + // Get any of the buffers in the list. There is no order guarantee whatsoever. + base::Optional<size_t> GetFreeBuffer(); + // Number of buffers currently in this list. + size_t size() const; + + private: + mutable base::Lock lock_; + std::set<size_t> free_buffers_ GUARDED_BY(lock_); + DISALLOW_COPY_AND_ASSIGN(V4L2BuffersList); +}; + +void V4L2BuffersList::ReturnBuffer(size_t buffer_id) { + base::AutoLock auto_lock(lock_); + + auto inserted = free_buffers_.emplace(buffer_id); + DCHECK(inserted.second); +} + +base::Optional<size_t> V4L2BuffersList::GetFreeBuffer() { + base::AutoLock auto_lock(lock_); + + auto iter = free_buffers_.begin(); + if (iter == free_buffers_.end()) { + DVLOGF(4) << "No free buffer available!"; + return base::nullopt; + } + + size_t buffer_id = *iter; + free_buffers_.erase(iter); + + return buffer_id; +} + +size_t V4L2BuffersList::size() const { + base::AutoLock auto_lock(lock_); + + return free_buffers_.size(); +} + // Module-private class that let users query/write V4L2 buffer information. // It also makes some private V4L2Queue methods available to this module only. class V4L2BufferQueueProxy { public: V4L2BufferQueueProxy(const struct v4l2_buffer* v4l2_buffer, - scoped_refptr<V4L2Queue> queue); - - void ReturnBuffer() { queue_->ReturnBuffer(BufferId()); } + base::WeakPtr<V4L2Queue> queue); + ~V4L2BufferQueueProxy(); bool QueueBuffer(); - - void* GetPlaneMapping(const size_t plane) { - return queue_->buffers_[BufferId()]->GetPlaneMapping(plane); - } + void* GetPlaneMapping(const size_t plane); // Data from the buffer, that users can query and/or write. struct v4l2_buffer v4l2_buffer_; @@ -179,18 +227,27 @@ private: size_t BufferId() const { return v4l2_buffer_.index; } - // The queue must be kept alive as long as the reference to the buffer exists. - scoped_refptr<V4L2Queue> queue_; + // A weak pointer to the queue this buffer belongs to. Will remain valid as + // long as the underlying V4L2 buffer is valid too. + // This can only be accessed from the sequence protected by sequence_checker_. + // Thread-safe methods (like ~V4L2BufferRefBase) must *never* access this. + base::WeakPtr<V4L2Queue> queue_; + // Where to return this buffer if it goes out of scope without being queued. + scoped_refptr<V4L2BuffersList> return_to_; + bool queued = false; + SEQUENCE_CHECKER(sequence_checker_); DISALLOW_COPY_AND_ASSIGN(V4L2BufferQueueProxy); }; V4L2BufferQueueProxy::V4L2BufferQueueProxy( const struct v4l2_buffer* v4l2_buffer, - scoped_refptr<V4L2Queue> queue) - : queue_(std::move(queue)) { + base::WeakPtr<V4L2Queue> queue) + : queue_(std::move(queue)), return_to_(queue_->free_buffers_) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(V4L2_TYPE_IS_MULTIPLANAR(v4l2_buffer->type)); DCHECK_LE(v4l2_buffer->length, base::size(v4l2_planes_)); + DCHECK(return_to_); memcpy(&v4l2_buffer_, v4l2_buffer, sizeof(v4l2_buffer_)); memcpy(v4l2_planes_, v4l2_buffer->m.planes, @@ -198,17 +255,35 @@ v4l2_buffer_.m.planes = v4l2_planes_; } -bool V4L2BufferQueueProxy::QueueBuffer() { - bool queued = queue_->QueueBuffer(&v4l2_buffer_); - - // If an error occurred during queueing, then the buffer must be made - // available again. +V4L2BufferQueueProxy::~V4L2BufferQueueProxy() { + // We are the last reference and are only accessing the thread-safe + // return_to_, so we are safe to call from any sequence. + // If we have been queued, then the queue is our owner so we don't need to + // return to the free buffers list. if (!queued) - ReturnBuffer(); + return_to_->ReturnBuffer(BufferId()); +} + +bool V4L2BufferQueueProxy::QueueBuffer() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + if (!queue_) + return false; + + queued = queue_->QueueBuffer(&v4l2_buffer_); return queued; } +void* V4L2BufferQueueProxy::GetPlaneMapping(const size_t plane) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + if (!queue_) + return nullptr; + + return queue_->buffers_[BufferId()]->GetPlaneMapping(plane); +} + V4L2WritableBufferRef::V4L2WritableBufferRef() { // Invalid buffers can be created from any thread. DETACH_FROM_SEQUENCE(sequence_checker_); @@ -216,7 +291,7 @@ V4L2WritableBufferRef::V4L2WritableBufferRef( const struct v4l2_buffer* v4l2_buffer, - scoped_refptr<V4L2Queue> queue) + base::WeakPtr<V4L2Queue> queue) : buffer_data_(std::make_unique<V4L2BufferQueueProxy>(v4l2_buffer, std::move(queue))) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -232,7 +307,6 @@ // Only valid references should be sequence-checked if (buffer_data_) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - buffer_data_->ReturnBuffer(); } } @@ -244,8 +318,6 @@ if (this == &other) return *this; - if (IsValid()) - buffer_data_->ReturnBuffer(); buffer_data_ = std::move(other.buffer_data_); return *this; @@ -420,17 +492,17 @@ } V4L2ReadableBuffer::V4L2ReadableBuffer(const struct v4l2_buffer* v4l2_buffer, - scoped_refptr<V4L2Queue> queue) + base::WeakPtr<V4L2Queue> queue) : buffer_data_(std::make_unique<V4L2BufferQueueProxy>(v4l2_buffer, std::move(queue))) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } V4L2ReadableBuffer::~V4L2ReadableBuffer() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + // This method is thread-safe. Since we are the destructor, we are guaranteed + // to be called from the only remaining reference to us. Also, we are just + // calling the destructor of buffer_data_, which is also thread-safe. DCHECK(buffer_data_); - - buffer_data_->ReturnBuffer(); } bool V4L2ReadableBuffer::IsLast() const { @@ -479,13 +551,13 @@ public: static V4L2WritableBufferRef CreateWritableRef( const struct v4l2_buffer* v4l2_buffer, - scoped_refptr<V4L2Queue> queue) { + base::WeakPtr<V4L2Queue> queue) { return V4L2WritableBufferRef(v4l2_buffer, std::move(queue)); } static V4L2ReadableBufferRef CreateReadableRef( const struct v4l2_buffer* v4l2_buffer, - scoped_refptr<V4L2Queue> queue) { + base::WeakPtr<V4L2Queue> queue) { return new V4L2ReadableBuffer(v4l2_buffer, std::move(queue)); } }; @@ -493,7 +565,10 @@ V4L2Queue::V4L2Queue(scoped_refptr<V4L2Device> dev, enum v4l2_buf_type type, base::OnceClosure destroy_cb) - : type_(type), device_(dev), destroy_cb_(std::move(destroy_cb)) { + : type_(type), + device_(dev), + destroy_cb_(std::move(destroy_cb)), + weak_this_factory_(this) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } @@ -506,7 +581,7 @@ } DCHECK(queued_buffers_.empty()); - DCHECK(free_buffers_.empty()); + DCHECK(!free_buffers_); if (!buffers_.empty()) { VLOGF(1) << "Buffers are still allocated, trying to deallocate them..."; @@ -518,7 +593,7 @@ size_t V4L2Queue::AllocateBuffers(size_t count, enum v4l2_memory memory) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK_EQ(free_buffers_.size(), 0u); + DCHECK(!free_buffers_); DCHECK_EQ(queued_buffers_.size(), 0u); if (IsStreaming()) { @@ -564,6 +639,8 @@ memory_ = memory; + free_buffers_ = new V4L2BuffersList(); + // Now query all buffer information. for (size_t i = 0; i < reqbufs.count; i++) { auto buffer = V4L2Buffer::Create(device_, type_, memory_, planes_count_, i); @@ -575,10 +652,11 @@ } buffers_.emplace_back(std::move(buffer)); - ReturnBuffer(i); + free_buffers_->ReturnBuffer(i); } - DCHECK_EQ(free_buffers_.size(), buffers_.size()); + DCHECK(free_buffers_); + DCHECK_EQ(free_buffers_->size(), buffers_.size()); DCHECK_EQ(queued_buffers_.size(), 0u); return buffers_.size(); @@ -592,14 +670,13 @@ return false; } - if (buffers_.size() != free_buffers_.size()) { - VPLOGF(1) << "Trying to deallocate buffers while some are still in use!"; - return false; - } - if (buffers_.size() == 0) return true; + weak_this_factory_.InvalidateWeakPtrs(); + buffers_.clear(); + free_buffers_ = nullptr; + // Free all buffers. struct v4l2_requestbuffers reqbufs = {}; reqbufs.count = 0; @@ -612,10 +689,7 @@ return false; } - buffers_.clear(); - free_buffers_.clear(); - - DCHECK_EQ(free_buffers_.size(), 0u); + DCHECK(!free_buffers_); DCHECK_EQ(queued_buffers_.size(), 0u); return true; @@ -636,25 +710,19 @@ V4L2WritableBufferRef V4L2Queue::GetFreeBuffer() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - auto iter = free_buffers_.begin(); - if (iter == free_buffers_.end()) { - VLOGF(3) << "No free buffer available!"; + // No buffers allocated at the moment? + if (!free_buffers_) return V4L2WritableBufferRef(); - } - size_t buffer_id = *iter; - free_buffers_.erase(buffer_id); + auto buffer_id = free_buffers_->GetFreeBuffer(); + + if (!buffer_id.has_value()) + return V4L2WritableBufferRef(); return V4L2BufferRefFactory::CreateWritableRef( - buffers_[buffer_id]->v4l2_buffer(), this); -} - -void V4L2Queue::ReturnBuffer(size_t buffer_id) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - auto inserted = free_buffers_.emplace(buffer_id); - DCHECK_EQ(inserted.second, true); + buffers_[buffer_id.value()]->v4l2_buffer(), + weak_this_factory_.GetWeakPtr()); } bool V4L2Queue::QueueBuffer(struct v4l2_buffer* v4l2_buffer) { @@ -712,8 +780,10 @@ DCHECK(it != queued_buffers_.end()); queued_buffers_.erase(*it); - return std::make_pair( - true, V4L2BufferRefFactory::CreateReadableRef(&v4l2_buffer, this)); + DCHECK(free_buffers_); + return std::make_pair(true, + V4L2BufferRefFactory::CreateReadableRef( + &v4l2_buffer, weak_this_factory_.GetWeakPtr())); } bool V4L2Queue::IsStreaming() const { @@ -754,8 +824,10 @@ return false; } - for (const auto& buffer_id : queued_buffers_) - ReturnBuffer(buffer_id); + for (const auto& buffer_id : queued_buffers_) { + DCHECK(free_buffers_); + free_buffers_->ReturnBuffer(buffer_id); + } queued_buffers_.clear(); @@ -773,7 +845,7 @@ size_t V4L2Queue::FreeBuffersCount() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return free_buffers_.size(); + return free_buffers_ ? free_buffers_->size() : 0; } size_t V4L2Queue::QueuedBuffersCount() const {
diff --git a/media/gpu/v4l2/v4l2_device.h b/media/gpu/v4l2/v4l2_device.h index 3e7b27b7..9cceeed 100644 --- a/media/gpu/v4l2/v4l2_device.h +++ b/media/gpu/v4l2/v4l2_device.h
@@ -45,6 +45,7 @@ class V4L2Queue; class V4L2BufferQueueProxy; +class V4L2BuffersList; // A unique reference to a buffer for clients to prepare and submit. // @@ -117,7 +118,7 @@ bool DoQueue() &&; V4L2WritableBufferRef(const struct v4l2_buffer* v4l2_buffer, - scoped_refptr<V4L2Queue> queue); + base::WeakPtr<V4L2Queue> queue); friend class V4L2BufferRefFactory; std::unique_ptr<V4L2BufferQueueProxy> buffer_data_; @@ -131,8 +132,14 @@ // Clients use this class to query the buffer state and content, and are // guaranteed that the buffer will not be reused until all references are // destroyed. +// All methods of this class must be called from the same sequence, but +// instances of V4L2ReadableBuffer objects can be destroyed from any sequence. +// They can even outlive the V4L2 buffers they originate from. This flexibility +// is required because V4L2ReadableBufferRefs can be embedded into VideoFrames, +// which are then passed to other threads and not necessarily destroyed before +// the V4L2Queue buffers are freed. class MEDIA_GPU_EXPORT V4L2ReadableBuffer - : public base::RefCounted<V4L2ReadableBuffer> { + : public base::RefCountedThreadSafe<V4L2ReadableBuffer> { public: // Returns whether the V4L2_BUF_FLAG_LAST flag is set for this buffer. bool IsLast() const; @@ -149,16 +156,17 @@ size_t BufferId() const; private: + friend class V4L2BufferRefFactory; + friend class base::RefCountedThreadSafe<V4L2ReadableBuffer>; + ~V4L2ReadableBuffer(); V4L2ReadableBuffer(const struct v4l2_buffer* v4l2_buffer, - scoped_refptr<V4L2Queue> queue); - friend class V4L2BufferRefFactory; + base::WeakPtr<V4L2Queue> queue); std::unique_ptr<V4L2BufferQueueProxy> buffer_data_; SEQUENCE_CHECKER(sequence_checker_); - friend class base::RefCounted<V4L2ReadableBuffer>; DISALLOW_COPY_AND_ASSIGN(V4L2ReadableBuffer); }; @@ -256,8 +264,6 @@ private: ~V4L2Queue(); - // Called when clients lose their reference to a buffer. - void ReturnBuffer(size_t buffer_id); // Called when clients request a buffer to be queued. bool QueueBuffer(struct v4l2_buffer* v4l2_buffer); @@ -270,7 +276,7 @@ // Buffers that are available for client to get and submit. // Buffers in this list are not referenced by anyone else than ourselves. - std::set<size_t> free_buffers_; + scoped_refptr<V4L2BuffersList> free_buffers_; // Buffers that have been queued by the client, and not dequeued yet. std::set<size_t> queued_buffers_; @@ -278,6 +284,8 @@ // Callback to call in this queue's destructor. base::OnceClosure destroy_cb_; + base::WeakPtrFactory<V4L2Queue> weak_this_factory_; + V4L2Queue(scoped_refptr<V4L2Device> dev, enum v4l2_buf_type type, base::OnceClosure destroy_cb);
diff --git a/media/gpu/vaapi/BUILD.gn b/media/gpu/vaapi/BUILD.gn index 6f419a6..a6e7cae 100644 --- a/media/gpu/vaapi/BUILD.gn +++ b/media/gpu/vaapi/BUILD.gn
@@ -142,7 +142,6 @@ ":vaapi", "//base", "//base/test:test_support", - "//media", "//media:test_support", "//testing/gtest", "//ui/gfx/geometry",
diff --git a/media/gpu/vaapi/vaapi_jpeg_decode_accelerator.cc b/media/gpu/vaapi/vaapi_jpeg_decode_accelerator.cc index 9e6cec77..8498ba62 100644 --- a/media/gpu/vaapi/vaapi_jpeg_decode_accelerator.cc +++ b/media/gpu/vaapi/vaapi_jpeg_decode_accelerator.cc
@@ -6,41 +6,33 @@ #include <stddef.h> -#include <iostream> #include <utility> -#include <vector> #include <va/va.h> #include "base/bind.h" +#include "base/containers/span.h" #include "base/location.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" +#include "base/numerics/safe_conversions.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "media/base/bitstream_buffer.h" #include "media/base/unaligned_shared_memory.h" #include "media/base/video_frame.h" -#include "media/filters/jpeg_parser.h" +#include "media/base/video_types.h" #include "media/gpu/macros.h" -#include "media/gpu/vaapi/vaapi_jpeg_decoder.h" #include "media/gpu/vaapi/vaapi_utils.h" #include "media/gpu/vaapi/vaapi_wrapper.h" #include "third_party/libyuv/include/libyuv.h" +#include "ui/gfx/geometry/size.h" namespace media { namespace { -// TODO(andrescj): remove this once VaapiJpegDecoder is responsible for -// obtaining the VAImage. -constexpr VAImageFormat kImageFormatI420 = { - .fourcc = VA_FOURCC_I420, - .byte_order = VA_LSB_FIRST, - .bits_per_pixel = 12, -}; - // UMA errors that the VaapiJpegDecodeAccelerator class reports. enum VAJDADecoderFailure { VAAPI_ERROR = 0, @@ -52,6 +44,35 @@ VAJDA_DECODER_FAILURES_MAX + 1); } +static JpegDecodeAccelerator::Error VaapiJpegDecodeStatusToError( + VaapiJpegDecodeStatus status) { + switch (status) { + case VaapiJpegDecodeStatus::kSuccess: + return JpegDecodeAccelerator::Error::NO_ERRORS; + case VaapiJpegDecodeStatus::kParseJpegFailed: + return JpegDecodeAccelerator::Error::PARSE_JPEG_FAILED; + case VaapiJpegDecodeStatus::kUnsupportedSubsampling: + return JpegDecodeAccelerator::Error::UNSUPPORTED_JPEG; + default: + return JpegDecodeAccelerator::Error::PLATFORM_FAILURE; + } +} + +static bool VerifyDataSize(const VAImage* image) { + const gfx::Size dimensions(base::strict_cast<int>(image->width), + base::strict_cast<int>(image->height)); + size_t min_size = 0; + if (image->format.fourcc == VA_FOURCC_I420) { + min_size = VideoFrame::AllocationSize(PIXEL_FORMAT_I420, dimensions); + } else if (image->format.fourcc == VA_FOURCC_YUY2 || + image->format.fourcc == VA_FOURCC('Y', 'U', 'Y', 'V')) { + min_size = VideoFrame::AllocationSize(PIXEL_FORMAT_YUY2, dimensions); + } else { + return false; + } + return base::strict_cast<size_t>(image->data_size) >= min_size; +} + } // namespace void VaapiJpegDecodeAccelerator::NotifyError(int32_t bitstream_buffer_id, @@ -79,8 +100,6 @@ io_task_runner_(io_task_runner), client_(nullptr), decoder_thread_("VaapiJpegDecoderThread"), - va_surface_id_(VA_INVALID_SURFACE), - va_rt_format_(0), weak_this_factory_(this) {} VaapiJpegDecodeAccelerator::~VaapiJpegDecodeAccelerator() { @@ -97,14 +116,8 @@ client_ = client; - vaapi_wrapper_ = - VaapiWrapper::Create(VaapiWrapper::kDecode, VAProfileJPEGBaseline, - base::Bind(&ReportToUMA, VAAPI_ERROR)); - - if (!vaapi_wrapper_.get()) { - VLOGF(1) << "Failed initializing VAAPI"; + if (!decoder_.Initialize(base::BindRepeating(&ReportToUMA, VAAPI_ERROR))) return false; - } if (!decoder_thread_.Start()) { VLOGF(1) << "Failed to start decoding thread."; @@ -115,46 +128,25 @@ return true; } -bool VaapiJpegDecodeAccelerator::OutputPicture( - VASurfaceID va_surface_id, - uint32_t va_surface_format, +bool VaapiJpegDecodeAccelerator::OutputPictureOnTaskRunner( + std::unique_ptr<ScopedVAImage> scoped_image, int32_t input_buffer_id, const scoped_refptr<VideoFrame>& video_frame) { DCHECK(decoder_task_runner_->BelongsToCurrentThread()); - TRACE_EVENT1("jpeg", "VaapiJpegDecodeAccelerator::OutputPicture", + TRACE_EVENT1("jpeg", "VaapiJpegDecodeAccelerator::OutputPictureOnTaskRunner", "input_buffer_id", input_buffer_id); - DVLOGF(4) << "Outputting VASurface " << va_surface_id - << " into video_frame associated with input buffer id " - << input_buffer_id; - - // Specify which image format we will request from the VAAPI. As the expected - // output format is I420, we will first try this format. If converting to I420 - // is not supported by the decoder, we will request the image in its original - // chroma sampling format. - VAImageFormat va_image_format = kImageFormatI420; - if (!VaapiWrapper::IsImageFormatSupported(va_image_format)) { - if (!VaSurfaceFormatToImageFormat(va_surface_format, &va_image_format)) { - VLOGF(1) << "Unsupported surface format"; - return false; - } - } - - const gfx::Size coded_size = video_frame->coded_size(); - auto scoped_image = vaapi_wrapper_->CreateVaImage( - va_surface_id, &va_image_format, coded_size); - if (!scoped_image) { - VLOGF(1) << "Cannot get VAImage"; - return false; - } - const VAImage* image = scoped_image->image(); - auto* mem = static_cast<uint8_t*>(scoped_image->va_buffer()->data()); - // Copy image content from VAImage to VideoFrame. If the image is not in the // I420 format we'll have to convert it. - DCHECK_GE(image->width, coded_size.width()); - DCHECK_GE(image->height, coded_size.height()); + DCHECK(scoped_image); + auto* mem = static_cast<uint8_t*>(scoped_image->va_buffer()->data()); + const VAImage* image = scoped_image->image(); + DCHECK_GE(base::strict_cast<int>(image->width), + video_frame->coded_size().width()); + DCHECK_GE(base::strict_cast<int>(image->height), + video_frame->coded_size().height()); + DCHECK(VerifyDataSize(image)); uint8_t* dst_y = video_frame->data(VideoFrame::kYPlane); uint8_t* dst_u = video_frame->data(VideoFrame::kUPlane); uint8_t* dst_v = video_frame->data(VideoFrame::kVPlane); @@ -162,7 +154,7 @@ size_t dst_u_stride = video_frame->stride(VideoFrame::kUPlane); size_t dst_v_stride = video_frame->stride(VideoFrame::kVPlane); - switch (va_image_format.fourcc) { + switch (image->format.fourcc) { case VA_FOURCC_I420: { DCHECK_EQ(image->num_planes, 3u); const uint8_t* src_y = mem + image->offsets[0]; @@ -174,7 +166,8 @@ if (libyuv::I420Copy(src_y, src_y_stride, src_u, src_u_stride, src_v, src_v_stride, dst_y, dst_y_stride, dst_u, dst_u_stride, dst_v, dst_v_stride, - coded_size.width(), coded_size.height())) { + video_frame->coded_size().width(), + video_frame->coded_size().height())) { VLOGF(1) << "I420Copy failed"; return false; } @@ -187,15 +180,16 @@ const size_t src_yuy2_stride = image->pitches[0]; if (libyuv::YUY2ToI420(src_yuy2, src_yuy2_stride, dst_y, dst_y_stride, dst_u, dst_u_stride, dst_v, dst_v_stride, - coded_size.width(), coded_size.height())) { + video_frame->coded_size().width(), + video_frame->coded_size().height())) { VLOGF(1) << "YUY2ToI420 failed"; return false; } break; } default: - VLOGF(1) << "Can't convert image to I420: unsupported format 0x" - << std::hex << va_image_format.fourcc; + VLOGF(1) << "Can't convert image to I420: unsupported format " + << FourccToString(image->format.fourcc); return false; } @@ -215,54 +209,20 @@ DCHECK(decoder_task_runner_->BelongsToCurrentThread()); TRACE_EVENT0("jpeg", "DecodeTask"); - JpegParseResult parse_result; - if (!ParseJpegPicture(static_cast<const uint8_t*>(shm->memory()), shm->size(), - &parse_result)) { - VLOGF(1) << "ParseJpegPicture failed"; - NotifyError(bitstream_buffer_id, PARSE_JPEG_FAILED); + VaapiJpegDecodeStatus status; + std::unique_ptr<ScopedVAImage> image = decoder_.DoDecode( + base::make_span<const uint8_t>(static_cast<const uint8_t*>(shm->memory()), + shm->size()), + &status); + if (status != VaapiJpegDecodeStatus::kSuccess) { + NotifyError(bitstream_buffer_id, VaapiJpegDecodeStatusToError(status)); return; } - const uint32_t picture_va_rt_format = - VaSurfaceFormatForJpeg(parse_result.frame_header); - if (!picture_va_rt_format) { - VLOGF(1) << "Unsupported subsampling"; - NotifyError(bitstream_buffer_id, UNSUPPORTED_JPEG); - return; - } - - // Reuse VASurface if size doesn't change. - gfx::Size new_coded_size(parse_result.frame_header.coded_width, - parse_result.frame_header.coded_height); - if (new_coded_size != coded_size_ || va_surface_id_ == VA_INVALID_SURFACE || - picture_va_rt_format != va_rt_format_) { - vaapi_wrapper_->DestroyContextAndSurfaces(); - va_surface_id_ = VA_INVALID_SURFACE; - va_rt_format_ = picture_va_rt_format; - - std::vector<VASurfaceID> va_surfaces; - if (!vaapi_wrapper_->CreateContextAndSurfaces(va_rt_format_, new_coded_size, - 1, &va_surfaces)) { - VLOGF(1) << "Create VA surface failed"; - NotifyError(bitstream_buffer_id, PLATFORM_FAILURE); - return; - } - va_surface_id_ = va_surfaces[0]; - coded_size_ = new_coded_size; - } - - if (!VaapiJpegDecoder::DoDecode(vaapi_wrapper_.get(), parse_result, - va_surface_id_)) { - VLOGF(1) << "Decode JPEG failed"; - NotifyError(bitstream_buffer_id, PLATFORM_FAILURE); - return; - } - - if (!OutputPicture(va_surface_id_, picture_va_rt_format, bitstream_buffer_id, - video_frame)) { + if (!OutputPictureOnTaskRunner(std::move(image), bitstream_buffer_id, + video_frame)) { VLOGF(1) << "Output picture failed"; NotifyError(bitstream_buffer_id, PLATFORM_FAILURE); - return; } }
diff --git a/media/gpu/vaapi/vaapi_jpeg_decode_accelerator.h b/media/gpu/vaapi/vaapi_jpeg_decode_accelerator.h index 398ef69..2364ddf5 100644 --- a/media/gpu/vaapi/vaapi_jpeg_decode_accelerator.h +++ b/media/gpu/vaapi/vaapi_jpeg_decode_accelerator.h
@@ -14,13 +14,8 @@ #include "base/memory/weak_ptr.h" #include "base/threading/thread.h" #include "media/gpu/media_gpu_export.h" +#include "media/gpu/vaapi/vaapi_jpeg_decoder.h" #include "media/video/jpeg_decode_accelerator.h" -#include "ui/gfx/geometry/size.h" - -// This data type is defined in va/va.h using typedef, reproduced here. -// TODO(andrescj): remove this once VaapiJpegDecoder is responsible for -// obtaining the VAImage. -using VASurfaceID = unsigned int; namespace base { class SingleThreadTaskRunner; @@ -29,8 +24,8 @@ namespace media { class BitstreamBuffer; +class ScopedVAImage; class UnalignedSharedMemory; -class VaapiWrapper; class VideoFrame; // Class to provide JPEG decode acceleration for Intel systems with hardware @@ -69,13 +64,11 @@ std::unique_ptr<UnalignedSharedMemory> shm, scoped_refptr<VideoFrame> video_frame); - // Puts contents of |va_surface| into given |video_frame|, releases the - // surface and passes the |input_buffer_id| of the resulting picture to - // client for output. - bool OutputPicture(VASurfaceID va_surface_id, - uint32_t va_surface_format, - int32_t input_buffer_id, - const scoped_refptr<VideoFrame>& video_frame); + // Puts contents of |image| into given |video_frame| and passes the + // |input_buffer_id| of the resulting picture to client for output. + bool OutputPictureOnTaskRunner(std::unique_ptr<ScopedVAImage> image, + int32_t input_buffer_id, + const scoped_refptr<VideoFrame>& video_frame); // ChildThread's task runner. const scoped_refptr<base::SingleThreadTaskRunner> task_runner_; @@ -86,23 +79,16 @@ // The client of this class. Client* client_; - scoped_refptr<VaapiWrapper> vaapi_wrapper_; + VaapiJpegDecoder decoder_; - // Comes after vaapi_wrapper_ to ensure its destructor is executed before - // |vaapi_wrapper_| is destroyed. + // Comes after |decoder_| to ensure its destructor is executed before + // |decoder_| is destroyed. base::Thread decoder_thread_; // Use this to post tasks to |decoder_thread_| instead of // |decoder_thread_.task_runner()| because the latter will be NULL once // |decoder_thread_.Stop()| returns. scoped_refptr<base::SingleThreadTaskRunner> decoder_task_runner_; - // The current VA surface for decoding. - VASurfaceID va_surface_id_; - // The coded size associated with |va_surface_id_|. - gfx::Size coded_size_; - // The VA RT format associated with |va_surface_id_|. - unsigned int va_rt_format_; - // WeakPtr factory for use in posting tasks from |decoder_task_runner_| back // to |task_runner_|. Since |decoder_thread_| is a fully owned member of // this class, tasks posted to it may use base::Unretained(this), and tasks
diff --git a/media/gpu/vaapi/vaapi_jpeg_decoder.cc b/media/gpu/vaapi/vaapi_jpeg_decoder.cc index 228ed15..ee16869 100644 --- a/media/gpu/vaapi/vaapi_jpeg_decoder.cc +++ b/media/gpu/vaapi/vaapi_jpeg_decoder.cc
@@ -8,6 +8,7 @@ #include <iostream> #include <type_traits> +#include <vector> #include <va/va.h> @@ -15,6 +16,7 @@ #include "base/stl_util.h" #include "media/filters/jpeg_parser.h" #include "media/gpu/macros.h" +#include "media/gpu/vaapi/vaapi_utils.h" #include "media/gpu/vaapi/vaapi_wrapper.h" namespace media { @@ -33,6 +35,8 @@ .bits_per_pixel = 16, }; +constexpr unsigned int kInvalidVaRtFormat = 0u; + static void FillPictureParameters( const JpegFrameHeader& frame_header, VAPictureParameterBufferJPEGBaseline* pic_param) { @@ -193,10 +197,9 @@ return true; } -} // namespace - -bool VaSurfaceFormatToImageFormat(uint32_t va_rt_format, - VAImageFormat* va_image_format) { +// Convert the specified surface format to the associated output image format. +static bool VaSurfaceFormatToImageFormat(unsigned int va_rt_format, + VAImageFormat* va_image_format) { switch (va_rt_format) { case VA_RT_FORMAT_YUV420: *va_image_format = kImageFormatI420; @@ -209,7 +212,8 @@ } } -unsigned int VaSurfaceFormatForJpeg(const JpegFrameHeader& frame_header) { +static unsigned int VaSurfaceFormatForJpeg( + const JpegFrameHeader& frame_header) { // The range of sampling factor is [1, 4]. Pack them into integer to make the // matching code simpler. For example, 0x211 means the sampling factor are 2, // 1, 1 for 3 components. @@ -244,53 +248,157 @@ << frame_header.num_components << ", h=" << std::hex << h << ", v=" << v; - return 0; + return kInvalidVaRtFormat; } -bool VaapiJpegDecoder::DoDecode(VaapiWrapper* vaapi_wrapper, - const JpegParseResult& parse_result, - VASurfaceID va_surface) { - DCHECK_NE(va_surface, VA_INVALID_SURFACE); - if (!IsVaapiSupportedJpeg(parse_result)) +} // namespace + +VaapiJpegDecoder::VaapiJpegDecoder() + : va_surface_id_(VA_INVALID_SURFACE), va_rt_format_(kInvalidVaRtFormat) {} + +VaapiJpegDecoder::~VaapiJpegDecoder() = default; + +bool VaapiJpegDecoder::Initialize(const base::RepeatingClosure& error_uma_cb) { + vaapi_wrapper_ = VaapiWrapper::Create(VaapiWrapper::kDecode, + VAProfileJPEGBaseline, error_uma_cb); + if (!vaapi_wrapper_) { + VLOGF(1) << "Failed initializing VAAPI"; return false; + } + return true; +} + +std::unique_ptr<ScopedVAImage> VaapiJpegDecoder::DoDecode( + base::span<const uint8_t> encoded_image, + VaapiJpegDecodeStatus* status) { + if (!vaapi_wrapper_) { + VLOGF(1) << "VaapiJpegDecoder has not been initialized"; + *status = VaapiJpegDecodeStatus::kInvalidState; + return nullptr; + } + + // Parse the JPEG encoded data. + JpegParseResult parse_result; + if (!ParseJpegPicture(encoded_image.data(), encoded_image.size(), + &parse_result)) { + VLOGF(1) << "ParseJpegPicture failed"; + *status = VaapiJpegDecodeStatus::kParseJpegFailed; + return nullptr; + } + + // Figure out the right format for the VaSurface. + const unsigned int picture_va_rt_format = + VaSurfaceFormatForJpeg(parse_result.frame_header); + if (picture_va_rt_format == kInvalidVaRtFormat) { + VLOGF(1) << "Unsupported subsampling"; + *status = VaapiJpegDecodeStatus::kUnsupportedSubsampling; + return nullptr; + } + + // Make sure this JPEG can be decoded. + if (!IsVaapiSupportedJpeg(parse_result)) { + VLOGF(1) << "The supplied JPEG is unsupported"; + *status = VaapiJpegDecodeStatus::kUnsupportedJpeg; + return nullptr; + } + + // Prepare the VaSurface for decoding. + const gfx::Size new_coded_size( + base::strict_cast<int>(parse_result.frame_header.coded_width), + base::strict_cast<int>(parse_result.frame_header.coded_height)); + if (new_coded_size != coded_size_ || va_surface_id_ == VA_INVALID_SURFACE || + picture_va_rt_format != va_rt_format_) { + vaapi_wrapper_->DestroyContextAndSurfaces(); + va_surface_id_ = VA_INVALID_SURFACE; + va_rt_format_ = picture_va_rt_format; + + std::vector<VASurfaceID> va_surfaces; + if (!vaapi_wrapper_->CreateContextAndSurfaces(va_rt_format_, new_coded_size, + 1, &va_surfaces)) { + VLOGF(1) << "Could not create the context or the surface"; + *status = VaapiJpegDecodeStatus::kSurfaceCreationFailed; + return nullptr; + } + va_surface_id_ = va_surfaces[0]; + coded_size_ = new_coded_size; + } // Set picture parameters. VAPictureParameterBufferJPEGBaseline pic_param{}; FillPictureParameters(parse_result.frame_header, &pic_param); - if (!vaapi_wrapper->SubmitBuffer(VAPictureParameterBufferType, &pic_param)) { - return false; + if (!vaapi_wrapper_->SubmitBuffer(VAPictureParameterBufferType, &pic_param)) { + VLOGF(1) << "Could not submit VAPictureParameterBufferType"; + *status = VaapiJpegDecodeStatus::kSubmitPicParamsFailed; + return nullptr; } // Set quantization table. VAIQMatrixBufferJPEGBaseline iq_matrix{}; FillIQMatrix(parse_result.q_table, &iq_matrix); - if (!vaapi_wrapper->SubmitBuffer(VAIQMatrixBufferType, &iq_matrix)) { - return false; + if (!vaapi_wrapper_->SubmitBuffer(VAIQMatrixBufferType, &iq_matrix)) { + VLOGF(1) << "Could not submit VAIQMatrixBufferType"; + *status = VaapiJpegDecodeStatus::kSubmitIQMatrixFailed; + return nullptr; } // Set huffman table. VAHuffmanTableBufferJPEGBaseline huffman_table{}; FillHuffmanTable(parse_result.dc_table, parse_result.ac_table, &huffman_table); - if (!vaapi_wrapper->SubmitBuffer(VAHuffmanTableBufferType, &huffman_table)) { - return false; + if (!vaapi_wrapper_->SubmitBuffer(VAHuffmanTableBufferType, &huffman_table)) { + VLOGF(1) << "Could not submit VAHuffmanTableBufferType"; + *status = VaapiJpegDecodeStatus::kSubmitHuffmanFailed; + return nullptr; } // Set slice parameters. VASliceParameterBufferJPEGBaseline slice_param{}; FillSliceParameters(parse_result, &slice_param); - if (!vaapi_wrapper->SubmitBuffer(VASliceParameterBufferType, &slice_param)) { - return false; + if (!vaapi_wrapper_->SubmitBuffer(VASliceParameterBufferType, &slice_param)) { + VLOGF(1) << "Could not submit VASliceParameterBufferType"; + *status = VaapiJpegDecodeStatus::kSubmitSliceParamsFailed; + return nullptr; } // Set scan data. - if (!vaapi_wrapper->SubmitBuffer(VASliceDataBufferType, - parse_result.data_size, - const_cast<char*>(parse_result.data))) { - return false; + if (!vaapi_wrapper_->SubmitBuffer(VASliceDataBufferType, + parse_result.data_size, + const_cast<char*>(parse_result.data))) { + VLOGF(1) << "Could not submit VASliceDataBufferType"; + *status = VaapiJpegDecodeStatus::kSubmitSliceDataFailed; + return nullptr; } - return vaapi_wrapper->ExecuteAndDestroyPendingBuffers(va_surface); + // Execute the decode. + if (!vaapi_wrapper_->ExecuteAndDestroyPendingBuffers(va_surface_id_)) { + VLOGF(1) << "Executing the decode failed"; + *status = VaapiJpegDecodeStatus::kExecuteDecodeFailed; + return nullptr; + } + + // Specify which image format we will request from the VAAPI. As the expected + // output format is I420, we will first try this format. If converting to I420 + // is not supported by the decoder, we will request the image in its original + // chroma sampling format. + VAImageFormat va_image_format = kImageFormatI420; + if (!VaapiWrapper::IsImageFormatSupported(va_image_format) && + !VaSurfaceFormatToImageFormat(va_rt_format_, &va_image_format)) { + VLOGF(1) << "Unsupported surface format"; + *status = VaapiJpegDecodeStatus::kUnsupportedSurfaceFormat; + return nullptr; + } + + auto scoped_image = vaapi_wrapper_->CreateVaImage( + va_surface_id_, &va_image_format, coded_size_); + if (!scoped_image) { + VLOGF(1) << "Cannot get VAImage"; + *status = VaapiJpegDecodeStatus::kCannotGetImage; + return nullptr; + } + + DCHECK_EQ(va_image_format.fourcc, scoped_image->image()->format.fourcc); + *status = VaapiJpegDecodeStatus::kSuccess; + return scoped_image; } } // namespace media
diff --git a/media/gpu/vaapi/vaapi_jpeg_decoder.h b/media/gpu/vaapi/vaapi_jpeg_decoder.h index ccbe54d..36eac7c 100644 --- a/media/gpu/vaapi/vaapi_jpeg_decoder.h +++ b/media/gpu/vaapi/vaapi_jpeg_decoder.h
@@ -7,39 +7,73 @@ #include <stdint.h> -// These data types are defined in va/va.h using typedef, reproduced here. -// TODO(andrescj): revisit this once VaSurfaceFormatToImageFormat() and -// VaSurfaceFormatForJpeg() are moved to the anonymous namespace in the .cc -// file. -using VAImageFormat = struct _VAImageFormat; -using VASurfaceID = unsigned int; +#include <memory> + +#include "base/callback_forward.h" +#include "base/containers/span.h" +#include "base/gtest_prod_util.h" +#include "base/macros.h" +#include "base/memory/scoped_refptr.h" +#include "ui/gfx/geometry/size.h" + +// This data type is defined in va/va.h using typedef, reproduced here. +typedef unsigned int VASurfaceID; namespace media { -struct JpegFrameHeader; -struct JpegParseResult; +class ScopedVAImage; class VaapiWrapper; -// Convert the specified surface format to the associated output image format. -bool VaSurfaceFormatToImageFormat(uint32_t va_rt_format, - VAImageFormat* va_image_format); +enum class VaapiJpegDecodeStatus { + kSuccess, + kParseJpegFailed, + kUnsupportedJpeg, + kUnsupportedSubsampling, + kSurfaceCreationFailed, + kSubmitPicParamsFailed, + kSubmitIQMatrixFailed, + kSubmitHuffmanFailed, + kSubmitSliceParamsFailed, + kSubmitSliceDataFailed, + kExecuteDecodeFailed, + kUnsupportedSurfaceFormat, + kCannotGetImage, + kInvalidState, +}; -unsigned int VaSurfaceFormatForJpeg(const JpegFrameHeader& frame_header); - -class VaapiJpegDecoder { +class VaapiJpegDecoder final { public: - VaapiJpegDecoder() = default; - virtual ~VaapiJpegDecoder() = default; + VaapiJpegDecoder(); + ~VaapiJpegDecoder(); - // Decodes a JPEG picture. It will fill VA-API parameters and call - // corresponding VA-API methods according to the JPEG |parse_result|. Decoded - // data will be outputted to the given |va_surface|. Returns false on failure. - // |vaapi_wrapper| should be initialized in kDecode mode with - // VAProfileJPEGBaseline profile. |va_surface| should be created with size at - // least as large as the picture size. - static bool DoDecode(VaapiWrapper* vaapi_wrapper, - const JpegParseResult& parse_result, - VASurfaceID va_surface); + // Initializes |vaapi_wrapper_| in kDecode mode with VAProfileJPEGBaseline + // profile and |error_uma_cb| for error reporting. + bool Initialize(const base::RepeatingClosure& error_uma_cb); + + // Decodes a JPEG picture. It will fill VA-API parameters and call the + // corresponding VA-API methods according to the JPEG in |encoded_image|. + // Decoded data will be returned as a ScopedVAImage. Returns nullptr on + // failure and sets *|status| to the reason for failure. + std::unique_ptr<ScopedVAImage> DoDecode( + base::span<const uint8_t> encoded_image, + VaapiJpegDecodeStatus* status); + + private: + // TODO(andrescj): move vaapi_utils tests out of vaapi_jpeg_decoder_unittest + // and remove this friend declaration. + friend class VaapiJpegDecoderTest; + FRIEND_TEST_ALL_PREFIXES(VaapiJpegDecoderTest, ScopedVAImage); + + scoped_refptr<VaapiWrapper> vaapi_wrapper_; + + // The current VA surface for decoding. + VASurfaceID va_surface_id_; + // The coded size associated with |va_surface_id_|. + gfx::Size coded_size_; + // The VA RT format associated with |va_surface_id_|. + unsigned int va_rt_format_; + + DISALLOW_COPY_AND_ASSIGN(VaapiJpegDecoder); }; } // namespace media
diff --git a/media/gpu/vaapi/vaapi_jpeg_decoder_unittest.cc b/media/gpu/vaapi/vaapi_jpeg_decoder_unittest.cc index 1cdd1c9..7b39e7a 100644 --- a/media/gpu/vaapi/vaapi_jpeg_decoder_unittest.cc +++ b/media/gpu/vaapi/vaapi_jpeg_decoder_unittest.cc
@@ -15,21 +15,17 @@ #include "testing/gtest/include/gtest/gtest.h" #include "base/bind.h" -#include "base/callback.h" #include "base/command_line.h" +#include "base/containers/span.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/md5.h" -#include "base/memory/scoped_refptr.h" #include "base/strings/string_piece.h" #include "base/synchronization/lock.h" #include "base/test/gtest_util.h" #include "base/thread_annotations.h" #include "media/base/test_data_util.h" -#include "media/base/video_frame.h" -#include "media/base/video_types.h" -#include "media/filters/jpeg_parser.h" #include "media/gpu/vaapi/vaapi_jpeg_decoder.h" #include "media/gpu/vaapi/vaapi_utils.h" #include "media/gpu/vaapi/vaapi_wrapper.h" @@ -38,46 +34,22 @@ namespace media { namespace { -constexpr const char* kTestFilename = "pixel-1280x720.jpg"; +// This file is supported by the VAAPI, so define expectations on the decode +// result. +constexpr const char* kSupportedFilename = "pixel-1280x720.jpg"; constexpr const char* kExpectedMd5SumI420 = "6e9e1716073c9a9a1282e3f0e0dab743"; constexpr const char* kExpectedMd5SumYUYV = "ff313a6aedbc4e157561e5c2d5c2e079"; +// This file is not supported by the VAAPI, so we don't define expectations on +// the decode result. +constexpr const char* kUnsupportedFilename = "pixel-1280x720-grayscale.jpg"; + constexpr VAImageFormat kImageFormatI420 = { .fourcc = VA_FOURCC_I420, .byte_order = VA_LSB_FIRST, .bits_per_pixel = 12, }; -constexpr VAImageFormat kImageFormatYUYV = { - .fourcc = VA_FOURCC('Y', 'U', 'Y', 'V'), - .byte_order = VA_LSB_FIRST, - .bits_per_pixel = 16, -}; - -void LogOnError() { - LOG(FATAL) << "Oh noes! Decoder failed"; -} - -uint32_t GetVASurfaceFormat() { - if (VaapiWrapper::IsImageFormatSupported(kImageFormatI420)) - return VA_RT_FORMAT_YUV420; - else if (VaapiWrapper::IsImageFormatSupported(kImageFormatYUYV)) - return VA_RT_FORMAT_YUV422; - - LOG(FATAL) << "Neither I420 nor YUY2 is supported."; - return 0; -} - -VAImageFormat GetVAImageFormat() { - if (VaapiWrapper::IsImageFormatSupported(kImageFormatI420)) - return kImageFormatI420; - else if (VaapiWrapper::IsImageFormatSupported(kImageFormatYUYV)) - return kImageFormatYUYV; - - LOG(FATAL) << "Neither I420 nor YUY2 is supported."; - return VAImageFormat{}; -} - } // namespace class VaapiJpegDecoderTest : public ::testing::Test { @@ -89,41 +61,29 @@ } void SetUp() override { - base::RepeatingClosure report_error_cb = base::BindRepeating(&LogOnError); - wrapper_ = VaapiWrapper::Create(VaapiWrapper::kDecode, - VAProfileJPEGBaseline, report_error_cb); - ASSERT_TRUE(wrapper_); - - // Load the test data, if not loaded yet. - if (jpeg_data_.size() == 0) { - base::FilePath input_file = FindTestDataFilePath(kTestFilename); - ASSERT_TRUE(base::ReadFileToString(input_file, &jpeg_data_)) - << "failed to read input data from " << input_file.value(); - } + ASSERT_TRUE(decoder_.Initialize(base::BindRepeating( + []() { LOG(FATAL) << "Oh noes! Decoder failed"; }))); } - void TearDown() override { wrapper_ = nullptr; } - base::FilePath FindTestDataFilePath(const std::string& file_name); - bool VerifyDecode(const JpegParseResult& parse_result) const; - bool Decode(VaapiWrapper* vaapi_wrapper, - const JpegParseResult& parse_result, - VASurfaceID va_surface) const; + bool VerifyDecode(base::span<const uint8_t> encoded_image); + std::unique_ptr<ScopedVAImage> Decode( + base::span<const uint8_t> encoded_image); - base::Lock* GetVaapiWrapperLock() const LOCK_RETURNED(wrapper_->va_lock_) { - return wrapper_->va_lock_; + base::Lock* GetVaapiWrapperLock() const + LOCK_RETURNED(decoder_.vaapi_wrapper_->va_lock_) { + return decoder_.vaapi_wrapper_->va_lock_; } VADisplay GetVaapiWrapperVaDisplay() const - EXCLUSIVE_LOCKS_REQUIRED(wrapper_->va_lock_) { - return wrapper_->va_display_; + EXCLUSIVE_LOCKS_REQUIRED(decoder_.vaapi_wrapper_->va_lock_) { + return decoder_.vaapi_wrapper_->va_display_; } protected: - scoped_refptr<VaapiWrapper> wrapper_; - std::string jpeg_data_; std::string test_data_path_; + VaapiJpegDecoder decoder_; }; // Find the location of the specified test file. If a file with specified path @@ -141,97 +101,68 @@ } bool VaapiJpegDecoderTest::VerifyDecode( - const JpegParseResult& parse_result) const { - gfx::Size size(parse_result.frame_header.coded_width, - parse_result.frame_header.coded_height); - - uint32_t va_surface_format = GetVASurfaceFormat(); - VAImageFormat va_image_format = GetVAImageFormat(); - - // Depending on the platform, the HW decoder will either convert the image to - // the I420 format, or use the JPEG's chroma sub-sampling type. - const char* expected_md5sum = nullptr; - VideoPixelFormat pixel_format = PIXEL_FORMAT_UNKNOWN; - if (VaapiWrapper::IsImageFormatSupported(kImageFormatI420)) { - expected_md5sum = kExpectedMd5SumI420; - pixel_format = PIXEL_FORMAT_I420; - } else if (VaapiWrapper::IsImageFormatSupported(kImageFormatYUYV)) { - expected_md5sum = kExpectedMd5SumYUYV; - pixel_format = PIXEL_FORMAT_YUY2; - } else { - LOG(FATAL) << "Neither I420 nor YUY2 is supported."; - } - - std::vector<VASurfaceID> va_surfaces; - if (!wrapper_->CreateContextAndSurfaces(va_surface_format, size, 1, - &va_surfaces)) { - return false; - } - - EXPECT_EQ(va_surfaces.size(), 1u); - if (va_surfaces.size() == 0 || - !Decode(wrapper_.get(), parse_result, va_surfaces[0])) { - LOG(ERROR) << "Decode failed"; - return false; - } - - auto scoped_image = - wrapper_->CreateVaImage(va_surfaces[0], &va_image_format, size); + base::span<const uint8_t> encoded_image) { + std::unique_ptr<ScopedVAImage> scoped_image = Decode(encoded_image); if (!scoped_image) { LOG(ERROR) << "Cannot get VAImage"; return false; } - EXPECT_TRUE(va_image_format.fourcc == scoped_image->image()->format.fourcc); + const char* expected_md5sum = nullptr; + if (scoped_image->image()->format.fourcc == VA_FOURCC_I420) { + expected_md5sum = kExpectedMd5SumI420; + } else if (scoped_image->image()->format.fourcc == VA_FOURCC_YUY2 || + scoped_image->image()->format.fourcc == + VA_FOURCC('Y', 'U', 'Y', 'V')) { + expected_md5sum = kExpectedMd5SumYUYV; + } else { + LOG(FATAL) << "Neither I420 nor YUY2 is supported."; + } + const auto* mem = static_cast<char*>(scoped_image->va_buffer()->data()); - - base::StringPiece result(mem, VideoFrame::AllocationSize(pixel_format, size)); + base::StringPiece result(mem, scoped_image->image()->data_size); EXPECT_EQ(expected_md5sum, base::MD5String(result)); - return true; } -bool VaapiJpegDecoderTest::Decode(VaapiWrapper* vaapi_wrapper, - const JpegParseResult& parse_result, - VASurfaceID va_surface) const { - return VaapiJpegDecoder::DoDecode(vaapi_wrapper, parse_result, va_surface); +std::unique_ptr<ScopedVAImage> VaapiJpegDecoderTest::Decode( + base::span<const uint8_t> encoded_image) { + VaapiJpegDecodeStatus status; + std::unique_ptr<ScopedVAImage> scoped_image = + decoder_.DoDecode(encoded_image, &status); + EXPECT_EQ(!!scoped_image, status == VaapiJpegDecodeStatus::kSuccess); + return scoped_image; } TEST_F(VaapiJpegDecoderTest, DecodeSuccess) { - JpegParseResult parse_result; - ASSERT_TRUE( - ParseJpegPicture(reinterpret_cast<const uint8_t*>(jpeg_data_.data()), - jpeg_data_.size(), &parse_result)); - - EXPECT_TRUE(VerifyDecode(parse_result)); + base::FilePath input_file = FindTestDataFilePath(kSupportedFilename); + std::string jpeg_data; + ASSERT_TRUE(base::ReadFileToString(input_file, &jpeg_data)) + << "failed to read input data from " << input_file.value(); + EXPECT_TRUE(VerifyDecode(base::make_span<const uint8_t>( + reinterpret_cast<const uint8_t*>(jpeg_data.data()), jpeg_data.size()))); } TEST_F(VaapiJpegDecoderTest, DecodeFail) { - JpegParseResult parse_result; - ASSERT_TRUE( - ParseJpegPicture(reinterpret_cast<const uint8_t*>(jpeg_data_.data()), - jpeg_data_.size(), &parse_result)); - // Not supported by VAAPI. - parse_result.frame_header.num_components = 1; - parse_result.scan.num_components = 1; - - gfx::Size size(parse_result.frame_header.coded_width, - parse_result.frame_header.coded_height); - - std::vector<VASurfaceID> va_surfaces; - ASSERT_TRUE(wrapper_->CreateContextAndSurfaces(GetVASurfaceFormat(), size, 1, - &va_surfaces)); - - EXPECT_FALSE(Decode(wrapper_.get(), parse_result, va_surfaces[0])); + base::FilePath input_file = FindTestDataFilePath(kUnsupportedFilename); + std::string jpeg_data; + ASSERT_TRUE(base::ReadFileToString(input_file, &jpeg_data)) + << "failed to read input data from " << input_file.value(); + EXPECT_FALSE(Decode(base::make_span<const uint8_t>( + reinterpret_cast<const uint8_t*>(jpeg_data.data()), jpeg_data.size()))); } // This test exercises the usual ScopedVAImage lifetime. +// +// TODO(andrescj): move ScopedVAImage and ScopedVABufferMapping to a separate +// file so that we don't have to use |decoder_.vaapi_wrapper_|. See +// https://crbug.com/924310. TEST_F(VaapiJpegDecoderTest, ScopedVAImage) { std::vector<VASurfaceID> va_surfaces; const gfx::Size coded_size(64, 64); - ASSERT_TRUE(wrapper_->CreateContextAndSurfaces(VA_RT_FORMAT_YUV420, - coded_size, 1, &va_surfaces)); + ASSERT_TRUE(decoder_.vaapi_wrapper_->CreateContextAndSurfaces( + VA_RT_FORMAT_YUV420, coded_size, 1, &va_surfaces)); ASSERT_EQ(va_surfaces.size(), 1u); std::unique_ptr<ScopedVAImage> scoped_image; @@ -254,6 +185,10 @@ // This test exercises creation of a ScopedVAImage with a bad VASurfaceID. TEST_F(VaapiJpegDecoderTest, BadScopedVAImage) { +#if DCHECK_IS_ON() + ::testing::FLAGS_gtest_death_test_style = "threadsafe"; +#endif + const std::vector<VASurfaceID> va_surfaces = {VA_INVALID_ID}; const gfx::Size coded_size(64, 64); @@ -277,6 +212,7 @@ // This test exercises creation of a ScopedVABufferMapping with bad VABufferIDs. TEST_F(VaapiJpegDecoderTest, BadScopedVABufferMapping) { + ::testing::FLAGS_gtest_death_test_style = "threadsafe"; base::AutoLock auto_lock(*GetVaapiWrapperLock()); // A ScopedVABufferMapping with a VA_INVALID_ID VABufferID is DCHECK()ed.
diff --git a/media/gpu/vaapi/vaapi_picture_native_pixmap_ozone.cc b/media/gpu/vaapi/vaapi_picture_native_pixmap_ozone.cc index ba4b18c0..8cc6b5f1 100644 --- a/media/gpu/vaapi/vaapi_picture_native_pixmap_ozone.cc +++ b/media/gpu/vaapi/vaapi_picture_native_pixmap_ozone.cc
@@ -72,7 +72,7 @@ const gfx::BufferFormat format = pixmap_->GetBufferFormat(); auto image = base::MakeRefCounted<gl::GLImageNativePixmap>(size_, format); - if (!image->Initialize(pixmap_.get())) { + if (!image->Initialize(pixmap_)) { LOG(ERROR) << "Failed to create GLImage"; return false; }
diff --git a/media/media_options.gni b/media/media_options.gni index 362f1edc..fbd9f13 100644 --- a/media/media_options.gni +++ b/media/media_options.gni
@@ -5,6 +5,7 @@ import("//build/config/chrome_build.gni") import("//build/config/chromecast_build.gni") import("//build/config/features.gni") +import("//build/config/jumbo.gni") import("//media/gpu/args.gni") import("//testing/libfuzzer/fuzzer_test.gni") import("//third_party/libaom/options.gni") @@ -78,8 +79,10 @@ # Enable HLS with SAMPLE-AES decryption. enable_hls_sample_aes = proprietary_codecs && is_chromecast - # Enable logging override, e.g. enable DVLOGs at build time. - enable_logging_override = is_chromecast + # Enable logging override, e.g. enable DVLOGs at build time. Must not be + # enabled when |use_jumbo_build| is true, in which case multiple .cc files + # are combined and we could override more logging than expected. + enable_logging_override = !use_jumbo_build && is_chromecast # If true, use cast CMA backend instead of default chromium media pipeline. # TODO(sanfin): Remove this flag when all builds enable CMA. @@ -92,6 +95,9 @@ # enable_hls_sample_aes can only be true if enable_mse_mpeg2ts_stream_parser is. assert(enable_mse_mpeg2ts_stream_parser || !enable_hls_sample_aes) +# Logging override must not be enabled in jumbo builds. +assert(!use_jumbo_build || !enable_logging_override) + if (media_use_ffmpeg) { media_subcomponent_deps += [ "//media/ffmpeg" ] }
diff --git a/media/mojo/interfaces/media_drm_storage.mojom b/media/mojo/interfaces/media_drm_storage.mojom index 753b3ba..ed9c7ca2 100644 --- a/media/mojo/interfaces/media_drm_storage.mojom +++ b/media/mojo/interfaces/media_drm_storage.mojom
@@ -31,7 +31,7 @@ // provisioning is to be used. If Initialize() fails or returns an empty // origin ID then the other methods below should not be called, and will // fail if they are called. - Initialize() => (bool success, mojo_base.mojom.UnguessableToken origin_id); + Initialize() => (bool success, mojo_base.mojom.UnguessableToken? origin_id); // Saves origin information (e.g. origin ID, provision time) in the storage // after MediaDrm is provisioned for current origin. It will clear all
diff --git a/media/mojo/services/mojo_media_drm_storage.cc b/media/mojo/services/mojo_media_drm_storage.cc index 9faa58d..f034f18 100644 --- a/media/mojo/services/mojo_media_drm_storage.cc +++ b/media/mojo/services/mojo_media_drm_storage.cc
@@ -9,6 +9,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" +#include "base/optional.h" #include "base/unguessable_token.h" #include "mojo/public/cpp/bindings/callback_helpers.h" @@ -30,7 +31,7 @@ DVLOG(1) << __func__; media_drm_storage_ptr_->Initialize( mojo::WrapCallbackWithDefaultInvokeIfNotRun(std::move(init_cb), false, - base::UnguessableToken())); + base::nullopt)); } void MojoMediaDrmStorage::OnProvisioned(ResultCB result_cb) {
diff --git a/media/test/data/README.md b/media/test/data/README.md index 4d1cbfe..0497c2a 100644 --- a/media/test/data/README.md +++ b/media/test/data/README.md
@@ -818,6 +818,12 @@ Single MJEPG encoded frame of 1280x720, captured on Chromebook Pixel. This image does not have Huffman table. +#### pixel-1280x720-grayscale.jpg +A version of pixel-1280x720.jpg converted to grayscale using: +``` +jpegtran -grayscale pixel-1280x720.jpg > pixel-1280x720-grayscale.jpg +``` + #### peach_pi-1280x720.jpg Single MJPEG encoded frame of 1280x720, captured on Samsung Chromebook 2(13"). This image has Huffman table.
diff --git a/media/test/data/pixel-1280x720-grayscale.jpg b/media/test/data/pixel-1280x720-grayscale.jpg new file mode 100644 index 0000000..9b06e90 --- /dev/null +++ b/media/test/data/pixel-1280x720-grayscale.jpg Binary files differ
diff --git a/mojo/public/js/BUILD.gn b/mojo/public/js/BUILD.gn index 6a607c0..b27019dd 100644 --- a/mojo/public/js/BUILD.gn +++ b/mojo/public/js/BUILD.gn
@@ -60,14 +60,14 @@ bindings_lite_compiled_file = "$target_gen_dir/mojo_bindings_lite.js" -if (enable_mojom_closure_compile) { - js_library("bindings_lite_sources") { - sources = [ "compile_preamble.js" ] + bindings_lite_sources - deps = [ - "//mojo/public/interfaces/bindings:bindings_js_library_for_compile", - ] - } +js_library("bindings_lite_sources") { + sources = [ "compile_preamble.js" ] + bindings_lite_sources + deps = [ + "//mojo/public/interfaces/bindings:bindings_js_library_for_compile", + ] +} +if (enable_mojom_closure_compile || closure_compile) { js_binary("bindings_lite") { outputs = [ bindings_lite_compiled_file,
diff --git a/mojo/public/js/interface_support.js b/mojo/public/js/interface_support.js index aa49cfb2..9e36eb1 100644 --- a/mojo/public/js/interface_support.js +++ b/mojo/public/js/interface_support.js
@@ -3,7 +3,8 @@ // found in the LICENSE file. 'use strict'; -goog.require('mojo.interfaceControl'); +goog.require('mojo.interfaceControl.kRunMessageId'); +goog.require('mojo.interfaceControl.RunResponseMessageParamsSpec'); goog.require('mojo.internal'); goog.provide('mojo.internal.interfaceSupport'); @@ -27,7 +28,7 @@ mojo.internal.serializeAndSendMessage( this.handle_, mojo.interfaceControl.kRunMessageId, requestId, mojo.internal.kMessageFlagExpectsResponse, - mojo.interfaceControl.RunMessageParams.$, {'input': input}); + mojo.interfaceControl.RunMessageParamsSpec.$, {'input': input}); this.pendingFlushResolvers_.set(requestId, resolve); }); } @@ -47,12 +48,13 @@ handleRunRequest_(requestId, decoder) { const input = decoder.decodeStructInline( - mojo.interfaceControl.RunMessageParams.$.$.structSpec)['input']; + mojo.interfaceControl.RunMessageParamsSpec.$.$.structSpec)['input']; if (input.hasOwnProperty('flushForTesting')) { mojo.internal.serializeAndSendMessage( this.handle_, mojo.interfaceControl.kRunMessageId, requestId, mojo.internal.kMessageFlagIsResponse, - mojo.interfaceControl.RunResponseMessageParams.$, {'output': null}); + mojo.interfaceControl.RunResponseMessageParamsSpec.$, + {'output': null}); return true; }
diff --git a/mojo/public/js/lib/codec.js b/mojo/public/js/lib/codec.js index 2bb7b8a..85f7047 100644 --- a/mojo/public/js/lib/codec.js +++ b/mojo/public/js/lib/codec.js
@@ -349,7 +349,7 @@ if (cls === PackedBool) { var byte = 0; - for (i = 0; i < numberOfElements; ++i) { + for (let i = 0; i < numberOfElements; ++i) { if (val[i]) byte |= (1 << i % 8); if (i % 8 === 7 || i == numberOfElements - 1) {
diff --git a/mojo/public/js/lib/control_message_proxy.js b/mojo/public/js/lib/control_message_proxy.js index c8447cde..1993aefe 100644 --- a/mojo/public/js/lib/control_message_proxy.js +++ b/mojo/public/js/lib/control_message_proxy.js
@@ -54,7 +54,7 @@ * Accepts the response message from the receiver and decodes the message * struct to RunResponseMessageParams. * - * @param {Router} receiver. + * @param {Router} receiver * @param {RunMessageParams} runMessageParams to be sent via a message. * @return {Promise} that resolves to a RunResponseMessageParams. */
diff --git a/mojo/public/tools/bindings/BUILD.gn b/mojo/public/tools/bindings/BUILD.gn index f59f1104..c0a5b6f 100644 --- a/mojo/public/tools/bindings/BUILD.gn +++ b/mojo/public/tools/bindings/BUILD.gn
@@ -70,14 +70,10 @@ "$mojom_generator_root/generators/js_templates/interface_definition.tmpl", "$mojom_generator_root/generators/js_templates/lite/enum_definition.tmpl", "$mojom_generator_root/generators/js_templates/lite/interface_definition.tmpl", - "$mojom_generator_root/generators/js_templates/lite/interface_externs.tmpl", - "$mojom_generator_root/generators/js_templates/lite/module.externs.tmpl", "$mojom_generator_root/generators/js_templates/lite/module_definition.tmpl", "$mojom_generator_root/generators/js_templates/lite/mojom-lite.js.tmpl", "$mojom_generator_root/generators/js_templates/lite/struct_definition.tmpl", - "$mojom_generator_root/generators/js_templates/lite/struct_externs.tmpl", "$mojom_generator_root/generators/js_templates/lite/union_definition.tmpl", - "$mojom_generator_root/generators/js_templates/lite/union_externs.tmpl", "$mojom_generator_root/generators/js_templates/module.amd.tmpl", "$mojom_generator_root/generators/js_templates/module_definition.tmpl", "$mojom_generator_root/generators/js_templates/struct_definition.tmpl",
diff --git a/mojo/public/tools/bindings/generators/js_templates/lite/enum_definition.tmpl b/mojo/public/tools/bindings/generators/js_templates/lite/enum_definition.tmpl index 2b8d4b2a..b6f1293 100644 --- a/mojo/public/tools/bindings/generators/js_templates/lite/enum_definition.tmpl +++ b/mojo/public/tools/bindings/generators/js_templates/lite/enum_definition.tmpl
@@ -1,26 +1,42 @@ -{%- macro enum_def(enum_name, enum) -%} +{%- macro enum_def(enum_spec_parent, enum_parent, enum) -%} {# TODO: Less generic enum annotations would be nice. We do it this way because the bindings generator is still too stupid to generate the right integral constants directly. #} +{% if generate_closure_exports -%} +goog.provide('{{enum_spec_parent}}.{{enum.name}}Spec'); +{%- endif %} /** - * @const {!Object} + * @const { {$: !mojo.internal.MojomType} } * @export */ -{{enum_name}} = { $: mojo.internal.Enum() }; +{{enum_spec_parent}}.{{enum.name}}Spec = { $: mojo.internal.Enum() }; + +/** + * @enum {number} + * @export + */ +{{enum_parent}}.{{enum.name}} = { + {# Set up the enum here, but fill out the values later. #} {%- for field in enum.fields %} -{%- if field.value %} -{{enum_name}}.{{field.name}} = {{field.value|expression_to_text_lite}}; -{%- elif loop.first %} -{{enum_name}}.{{field.name}} = 0; -{%- else %} -{{enum_name}}.{{field.name}} = {{enum_name}}.{{enum.fields[loop.index0 - 1].name}} + 1; -{%- endif %} + {{field.name}}: 0, {%- endfor %} {%- if enum.min_value is not none %} -{{enum_name}}.MIN_VALUE = {{enum.min_value}}; + MIN_VALUE: {{enum.min_value}}, {%- endif %} {%- if enum.max_value is not none %} -{{enum_name}}.MAX_VALUE = {{enum.max_value}}; + MAX_VALUE: {{enum.max_value}}, {%- endif %} +}; +{%- for field in enum.fields %} +{# Suppress type checks since we're assigning number into an enum. #} +/** @suppress {checkTypes} */ +{%- if field.value %} +{{enum_parent}}.{{enum.name}}.{{field.name}} = {{field.value|expression_to_text_lite}}; +{%- elif loop.first %} +{{enum_parent}}.{{enum.name}}.{{field.name}} = 0; +{%- else %} +{{enum_parent}}.{{enum.name}}.{{field.name}} = {{enum_parent}}.{{enum.name}}.{{enum.fields[loop.index0 - 1].name}} + 1; +{%- endif %} +{%- endfor %} {%- endmacro %}
diff --git a/mojo/public/tools/bindings/generators/js_templates/lite/interface_definition.tmpl b/mojo/public/tools/bindings/generators/js_templates/lite/interface_definition.tmpl index e7395e36..874b97f 100644 --- a/mojo/public/tools/bindings/generators/js_templates/lite/interface_definition.tmpl +++ b/mojo/public/tools/bindings/generators/js_templates/lite/interface_definition.tmpl
@@ -1,3 +1,22 @@ +{% macro generateMethodAnnotation(method) %} + /** +{%- for param in method.parameters %} + * @param { {{param.kind|lite_closure_type_with_nullability}} } {{param.name|sanitize_identifier}} +{%- endfor -%} +{%- if method.response_parameters != None %} +{%- if method.response_parameters|length == 0 %} + * @return {Promise} +{%- else %} + * @return {Promise<{ +{%- for response_parameter in method.response_parameters %} + {{response_parameter.name}}: {{response_parameter.kind|lite_closure_type_with_nullability}}, +{%- endfor %} + * }>} +{%- endif %} +{%- endif %} + */ +{% endmacro %} + /** @export */ {{module.namespace}}.{{interface.name}}Request = class { /** @param {!MojoHandle} handle */ @@ -11,14 +30,7 @@ /** @interface */ {{module.namespace}}.{{interface.name}}Interface = class { {%- for method in interface.methods %} - /** -{%- for param in method.parameters %} - * @param { {{param.kind|lite_closure_param_type}} } {{param.name|sanitize_identifier}} -{%- endfor -%} -{%- if method.response_parameters != None %} - * @return {Promise} -{%- endif %} - */ + {{generateMethodAnnotation(method)}} {{method.name}}( {%- for param in method.parameters -%} {{param.name|sanitize_identifier}}{% if not loop.last %}, {% endif %} @@ -28,7 +40,10 @@ }; {%- endif %} -/** @implements { {{module.namespace}}.{{interface.name}}Interface } */ +/** + * @export + * @implements { {{module.namespace}}.{{interface.name}}Interface } + */ {{module.namespace}}.{{interface.name}}Proxy = class { /** @param {MojoHandle=} opt_handle */ constructor(opt_handle) { @@ -41,7 +56,7 @@ opt_handle); /** - * @public {!mojo.internal.interfaceSupport.InterfaceProxyBaseWrapper<!{{module.namespace}}.{{interface.name}}Request>> + * @public {!mojo.internal.interfaceSupport.InterfaceProxyBaseWrapper<!{{module.namespace}}.{{interface.name}}Request>} */ this.$ = new mojo.internal.interfaceSupport.InterfaceProxyBaseWrapper(this.proxy); @@ -53,15 +68,7 @@ {%- set interface_message_id = interface.mojom_name ~ "_" ~ method.mojom_name %} - /** -{%- for param in method.parameters %} - * @param { {{param.kind|lite_closure_param_type}} } {{param.name|sanitize_identifier}} -{%- endfor -%} -{%- if method.response_parameters != None %} - * @return {Promise} -{%- endif %} - * @export - */ + {{generateMethodAnnotation(method)}} {{method.name}}( {%- for param in method.parameters %} {{param.name}}{%- if not loop.last %},{% endif %} @@ -72,9 +79,9 @@ this.proxy.sendMessage( {%- endif %} {{method.ordinal}}, - {{module.namespace}}.{{interface_message_id}}_Params.$, + {{module.namespace}}.{{interface_message_id}}_ParamsSpec.$, {%- if method.response_parameters != None %} - {{module.namespace}}.{{interface_message_id}}_ResponseParams.$, + {{module.namespace}}.{{interface_message_id}}_ResponseParamsSpec.$, {%- else %} null, {%- endif %} @@ -105,9 +112,9 @@ interface.mojom_name ~ "_" ~ method.mojom_name %} this.target_.registerHandler( {{method.ordinal}}, - {{module.namespace}}.{{interface_message_id}}_Params.$, + {{module.namespace}}.{{interface_message_id}}_ParamsSpec.$, {%- if method.response_parameters != None %} - {{module.namespace}}.{{interface_message_id}}_ResponseParams.$, + {{module.namespace}}.{{interface_message_id}}_ResponseParamsSpec.$, {%- else %} null, {%- endif %} @@ -156,9 +163,10 @@ }; {#--- Enums #} -{% from "lite/enum_definition.tmpl" import enum_def %} +{% from "lite/enum_definition.tmpl" import enum_def with context %} {%- for enum in interface.enums %} -{{ enum_def("%s.%s.%s"|format(module.namespace, interface.name, enum.name), +{{ enum_def("%s.%sSpec"|format(module.namespace, interface.name), + "%s.%s"|format(module.namespace, interface.name), enum) }} {%- endfor %} @@ -184,15 +192,18 @@ {% for method in interface.methods %} {%- set interface_message_id = interface.mojom_name ~ "_" ~ method.mojom_name %} - /** @public {!mojo.internal.interfaceSupport.InterfaceCallbackTarget} */ + /** + * @export {!mojo.internal.interfaceSupport.InterfaceCallbackTarget} + */ this.{{method.name}} = new mojo.internal.interfaceSupport.InterfaceCallbackTarget( this.router_); + this.target_.registerHandler( {{method.ordinal}}, - {{module.namespace}}.{{interface_message_id}}_Params.$, + {{module.namespace}}.{{interface_message_id}}_ParamsSpec.$, {%- if method.response_parameters != None %} - {{module.namespace}}.{{interface_message_id}}_ResponseParams.$, + {{module.namespace}}.{{interface_message_id}}_ResponseParamsSpec.$, this.{{method.name}}.createTargetHandler(true /* expectsResponse */)); {%- else %} null,
diff --git a/mojo/public/tools/bindings/generators/js_templates/lite/interface_externs.tmpl b/mojo/public/tools/bindings/generators/js_templates/lite/interface_externs.tmpl deleted file mode 100644 index b1d5ce0..0000000 --- a/mojo/public/tools/bindings/generators/js_templates/lite/interface_externs.tmpl +++ /dev/null
@@ -1,117 +0,0 @@ -{# Note that goog.provide is understood by the Closure Compiler even if the - Closure base library is unavailable. See https://crbug.com/898692 #} -goog.provide('{{module.namespace}}.{{interface.name}}'); -goog.provide('{{module.namespace}}.{{interface.name}}Interface'); -goog.provide('{{module.namespace}}.{{interface.name}}Request'); -goog.provide('{{module.namespace}}.{{interface.name}}Proxy'); -goog.provide('{{module.namespace}}.{{interface.name}}CallbackRouter'); - -{% macro generateInterfaceClassBody() -%} -{%- for method in interface.methods %} - /** -{%- for parameter in method.parameters %} - * @param { {{parameter.kind|lite_closure_type_with_nullability}} } {{parameter.name|sanitize_identifier}} -{%- endfor -%} -{%- if method.response_parameters != None %} -{%- if method.response_parameters|length == 0 %} - * @return {Promise} -{%- else %} - * @return {Promise<{ -{%- for response_parameter in method.response_parameters %} - {{response_parameter.name}}: {{response_parameter.kind|lite_closure_type_with_nullability}}, -{%- endfor %} - * }>} -{%- endif %} -{%- endif %} - */ - {{method.name}}( -{%- for parameter in method.parameters -%} -{{parameter.name|sanitize_identifier}}{% if not loop.last %}, {% endif %} -{%- endfor -%} -) {} -{%- endfor %} -{%- endmacro %} - -/** @interface */ -{{module.namespace}}.{{interface.name}}Interface = class { -{{ generateInterfaceClassBody() }} -}; - -{{module.namespace}}.{{interface.name}}Request = class { - /** @param {!MojoHandle} handle */ - constructor(handle) {} -}; - -/** @implements { {{module.namespace}}.{{interface.name}}Interface } */ -{{module.namespace}}.{{interface.name}}Proxy = class { - constructor() { - /** @public {!{ - * createRequest: function(): !{{module.namespace}}.{{interface.name}}Request, - * close: function(), - * flushForTesting: function(): !Promise - * }} - */ - this.$; - - /** @public {!mojo.internal.ConnectionErrorEventRouter} */ - this.onConnectionError; - } -{{ generateInterfaceClassBody() }} -}; - -{{module.namespace}}.{{interface.name}} = class { - /** @param {!{{module.namespace}}.{{interface.name}}Interface} impl */ - constructor(impl) {} - - /** - * @param {!MojoHandle} handle - */ - bindHandle(handle) {} - - /** - * @return {!{{module.namespace}}.{{interface.name}}Proxy } - */ - static getProxy() {} - - /** - * @return {!{{module.namespace}}.{{interface.name}}Proxy } - */ - createProxy() {} -}; - -/** @const {!string} */ -{{module.namespace}}.{{interface.name}}.$interfaceName; - -{{module.namespace}}.{{interface.name}}CallbackRouter = class { - constructor() { -{%- for method in interface.methods %} - /** @public {!mojo.internal.InterfaceCallbackTarget} */ - this.{{method.name}}; -{%- endfor %} - } - - /** - * @param {!MojoHandle} handle - */ - bindHandle(handle) {} - - /** - * @return {!{{module.namespace}}.{{interface.name}}Proxy } - */ - createProxy() {} - - /** - * @param {number} id An ID returned by a prior call to addListener. - * @return {boolean} True iff the identified listener was found and removed. - */ - removeListener(id) {} -}; - -{#--- Enum definitions #} -{% for enum in interface.enums %} -/** @enum {number} */ -{{module.namespace}}.{{interface.name}}.{{enum.name}} = {}; -{%- for field in enum.fields %} -{{module.namespace}}.{{interface.name}}.{{enum.name}}.{{field.name}}; -{%- endfor %} -{%- endfor %}
diff --git a/mojo/public/tools/bindings/generators/js_templates/lite/module.externs.tmpl b/mojo/public/tools/bindings/generators/js_templates/lite/module.externs.tmpl deleted file mode 100644 index 4e1d235..0000000 --- a/mojo/public/tools/bindings/generators/js_templates/lite/module.externs.tmpl +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -{# Note that goog.provide is understood by the Closure Compiler even if the - Closure base library is unavailable. See https://crbug.com/898692 #} -{#--- Constant definitions #} -{%- for constant in module.constants %} -/** @type { {{constant.kind|closure_type_with_nullability }} } */ -goog.provide('{{module.namespace}}.{{constant.name}}'); -{%- endfor %} - -{#--- Enum definitions #} -{% for enum in enums %} -/** @enum {number} */ -{{module.namespace}}.{{enum.name}} = {}; -{%- for field in enum.fields %} -{{module.namespace}}.{{enum.name}}.{{field.name}}; -{%- endfor %} -{%- endfor %} - -{#--- Interface definitions #} -{%- for interface in interfaces -%} -{%- include "lite/interface_externs.tmpl" %} -{% endfor -%} - -{#--- Struct definitions #} -{%- for struct in structs -%} -{%- include "lite/struct_externs.tmpl" %} -{% endfor -%} - -{#--- Union definitions #} -{%- for union in unions -%} -{%- include "lite/union_externs.tmpl" %} -{% endfor -%}
diff --git a/mojo/public/tools/bindings/generators/js_templates/lite/module_definition.tmpl b/mojo/public/tools/bindings/generators/js_templates/lite/module_definition.tmpl index a6cdc182..e8124d4 100644 --- a/mojo/public/tools/bindings/generators/js_templates/lite/module_definition.tmpl +++ b/mojo/public/tools/bindings/generators/js_templates/lite/module_definition.tmpl
@@ -1,5 +1,9 @@ {#--- Constants #} {%- for constant in module.constants %} +{% if generate_closure_exports -%} +goog.provide('{{module.namespace}}.{{constant.name}}'); + +{%- endif %} /** * @const { {{constant.kind|lite_closure_type_with_nullability}} } * @export @@ -9,9 +13,9 @@ {%- endfor %} {#--- Enums #} -{% from "lite/enum_definition.tmpl" import enum_def %} +{% from "lite/enum_definition.tmpl" import enum_def with context %} {%- for enum in enums %} -{{enum_def("%s.%s"|format(module.namespace, enum.name), enum)}} +{{enum_def(module.namespace, module.namespace, enum)}} {% endfor %} {#--- Interface definitions #} @@ -24,19 +28,25 @@ # mojo.internal.Struct and mojo.internal.Union will fix-up the object # appropriately, and we don't want Closure to complain. #} {% for struct in structs %} +{% if generate_closure_exports -%} +goog.provide('{{module.namespace}}.{{struct.name}}Spec'); +{%- endif %} /** - * @const {!Object} + * @const { {$:!mojo.internal.MojomType}} * @export */ -{{module.namespace}}.{{struct.name}} = +{{module.namespace}}.{{struct.name}}Spec = { $: /** @type {!mojo.internal.MojomType} */ ({}) }; {% endfor %} {%- for union in unions %} +{% if generate_closure_exports -%} +goog.provide('{{module.namespace}}.{{union.name}}Spec'); +{%- endif %} /** - * @const {!Object} + * @const { {$:!mojo.internal.MojomType} } * @export */ -{{module.namespace}}.{{union.name}} = +{{module.namespace}}.{{union.name}}Spec = { $: /** @type {!mojo.internal.MojomType} */ ({}) }; {% endfor %}
diff --git a/mojo/public/tools/bindings/generators/js_templates/lite/mojom-lite.js.tmpl b/mojo/public/tools/bindings/generators/js_templates/lite/mojom-lite.js.tmpl index 4446322..b9b2e32e 100644 --- a/mojo/public/tools/bindings/generators/js_templates/lite/mojom-lite.js.tmpl +++ b/mojo/public/tools/bindings/generators/js_templates/lite/mojom-lite.js.tmpl
@@ -8,11 +8,6 @@ {%- if interfaces %} goog.require('mojo.internal.interfaceSupport'); {%- endif %} - -{% for import in imports -%} -goog.require('{{import.namespace}}'); -{% endfor %} -goog.provide('{{module.namespace}}'); {% endif %} mojo.internal.exportModule('{{module.namespace}}');
diff --git a/mojo/public/tools/bindings/generators/js_templates/lite/struct_definition.tmpl b/mojo/public/tools/bindings/generators/js_templates/lite/struct_definition.tmpl index 60163e7..fa6bd2e7 100644 --- a/mojo/public/tools/bindings/generators/js_templates/lite/struct_definition.tmpl +++ b/mojo/public/tools/bindings/generators/js_templates/lite/struct_definition.tmpl
@@ -7,13 +7,14 @@ {{constant.value|expression_to_text_lite}}; {% endfor %} -{%- from "lite/enum_definition.tmpl" import enum_def %} +{%- from "lite/enum_definition.tmpl" import enum_def with context %} {% for enum in struct.enums %} -{{enum_def("%s.%s.%s"|format(module.namespace, struct.name, enum.name), enum)}} +{{enum_def("%s.%sSpec"|format(module.namespace, struct.name), + "%s.%s"|format(module.namespace, struct.name), enum)}} {% endfor %} mojo.internal.Struct( - {{module.namespace}}.{{struct.name}}.$, + {{module.namespace}}.{{struct.name}}Spec.$, '{{struct.name}}', {{struct.packed|payload_size}}, [ @@ -31,3 +32,21 @@ {%- endif %} {%- endfor %} ]); + +{% if generate_closure_exports -%} +goog.provide('{{module.namespace}}.{{struct.name}}'); + +{% if struct.packed.packed_fields %} +/** + * @typedef { { +{%- for packed_field in struct.packed.packed_fields %} + * {{packed_field.field.name}}: {{packed_field.field.kind|lite_closure_field_type}}, +{%- endfor %} + * } } + */ +{% else %} +/** @typedef {Object} */ +{% endif %} +{{module.namespace}}.{{struct.name}}; + +{%- endif %}
diff --git a/mojo/public/tools/bindings/generators/js_templates/lite/struct_externs.tmpl b/mojo/public/tools/bindings/generators/js_templates/lite/struct_externs.tmpl deleted file mode 100644 index cc22de4..0000000 --- a/mojo/public/tools/bindings/generators/js_templates/lite/struct_externs.tmpl +++ /dev/null
@@ -1,25 +0,0 @@ -{# Note that goog.provide is understood by the Closure Compiler even if the - Closure base library is unavailable. See https://crbug.com/898692 #} -goog.provide('{{module.namespace}}.{{struct.name}}'); - -{% if struct.packed.packed_fields %} -/** - * @typedef { { -{%- for packed_field in struct.packed.packed_fields %} - * {{packed_field.field.name}}: {{packed_field.field.kind|lite_closure_field_type}}, -{%- endfor %} - * } } - */ -{% else %} -/** @typedef {Object} */ -{% endif %} -{{module.namespace}}.{{struct.name}}; - -{#--- Enum definitions #} -{% for enum in struct.enums %} -/** @enum {number} */ -{{module.namespace}}.{{struct.name}}.{{enum.name}} = {}; -{%- for field in enum.fields %} -{{module.namespace}}.{{struct.name}}.{{enum.name}}.{{field.name}}; -{%- endfor %} -{%- endfor %}
diff --git a/mojo/public/tools/bindings/generators/js_templates/lite/test/BUILD.gn b/mojo/public/tools/bindings/generators/js_templates/lite/test/BUILD.gn index 671f91e..ec085c5 100644 --- a/mojo/public/tools/bindings/generators/js_templates/lite/test/BUILD.gn +++ b/mojo/public/tools/bindings/generators/js_templates/lite/test/BUILD.gn
@@ -20,6 +20,6 @@ js_library("test") { deps = [ - ":mojo_bindings_js_externs", + ":mojo_bindings_js_library_for_compile", ] }
diff --git a/mojo/public/tools/bindings/generators/js_templates/lite/test/test.js b/mojo/public/tools/bindings/generators/js_templates/lite/test/test.js index c0a2eba..0ba0164d 100644 --- a/mojo/public/tools/bindings/generators/js_templates/lite/test/test.js +++ b/mojo/public/tools/bindings/generators/js_templates/lite/test/test.js
@@ -7,10 +7,13 @@ let proxy = test.mojom.TestPageHandler.getProxy() // Type infers {?{values: !Array<!string>}} from Promise return type. - let result = await proxy.method1(); + let result = await proxy.method1(' ', 5); /** @type {Array<string>} */ let values = result.values; + + /** @type {test.mojom.TestStruct} */ + let testStruct = result.ts } /** @implements {test.mojom.TestPageInterface} */
diff --git a/mojo/public/tools/bindings/generators/js_templates/lite/test/test.test-mojom b/mojo/public/tools/bindings/generators/js_templates/lite/test/test.test-mojom index 4df1ba1e..2bf5a11 100644 --- a/mojo/public/tools/bindings/generators/js_templates/lite/test/test.test-mojom +++ b/mojo/public/tools/bindings/generators/js_templates/lite/test/test.test-mojom
@@ -24,7 +24,7 @@ }; interface TestPageHandler { - Method1() => (array<string> values); + Method1(string p1, int32 p2) => (array<string> values, TestStruct ts); }; interface TestPage {
diff --git a/mojo/public/tools/bindings/generators/js_templates/lite/union_definition.tmpl b/mojo/public/tools/bindings/generators/js_templates/lite/union_definition.tmpl index 0b8a630..ee63701 100644 --- a/mojo/public/tools/bindings/generators/js_templates/lite/union_definition.tmpl +++ b/mojo/public/tools/bindings/generators/js_templates/lite/union_definition.tmpl
@@ -1,6 +1,6 @@ mojo.internal.Union( - {{module.namespace}}.{{union.name}}.$, '{{union.name}}', + {{module.namespace}}.{{union.name}}Spec.$, '{{union.name}}', { {%- for field in union.fields %} '{{field.name}}': { @@ -12,3 +12,12 @@ }, {%- endfor %} }); + +/** + * @typedef { { +{%- for field in union.fields %} + * {{field.name}}: ({{field.kind|lite_closure_type_with_nullability}}|undefined), +{%- endfor %} + * } } + */ +{{module.namespace}}.{{union.name}};
diff --git a/mojo/public/tools/bindings/generators/js_templates/lite/union_externs.tmpl b/mojo/public/tools/bindings/generators/js_templates/lite/union_externs.tmpl deleted file mode 100644 index 732cf63..0000000 --- a/mojo/public/tools/bindings/generators/js_templates/lite/union_externs.tmpl +++ /dev/null
@@ -1,12 +0,0 @@ -{# Note that goog.provide is understood by the Closure Compiler even if the - Closure base library is unavailable. See https://crbug.com/898692 #} -goog.provide('{{module.namespace}}.{{union.name}}'); - -{{module.namespace}}.{{union.name}} = class { - constructor() { -{%- for field in fields %} - /** @type { {{field.kind|lite_closure_type_with_nullability}} } */ - this.{{field.name}}; -{%- endfor %} - } -};
diff --git a/mojo/public/tools/bindings/generators/mojom_js_generator.py b/mojo/public/tools/bindings/generators/mojom_js_generator.py index 5489141..9eb5f2d 100644 --- a/mojo/public/tools/bindings/generators/mojom_js_generator.py +++ b/mojo/public/tools/bindings/generators/mojom_js_generator.py
@@ -341,10 +341,6 @@ def _GenerateLiteBindingsForCompile(self): return self._GetParameters(for_compile=True) - @UseJinja("lite/module.externs.tmpl") - def _GenerateLiteExterns(self): - return self._GetParameters() - def GenerateFiles(self, args): if self.variant: raise Exception("Variants not supported in JavaScript bindings.") @@ -362,8 +358,6 @@ self.Write(self._GenerateLiteBindings(), "%s-lite.js" % self.module.path) self.Write(self._GenerateLiteBindingsForCompile(), "%s-lite-for-compile.js" % self.module.path) - self.Write(self._GenerateLiteExterns(), - "%s-lite.externs.js" % self.module.path) def _SetUniqueNameForImports(self): used_names = set() @@ -532,19 +526,20 @@ if named_kind.module: name.append(named_kind.module.namespace) if named_kind.parent_kind: - name.append(named_kind.parent_kind.name) + name.append(named_kind.parent_kind.name + "Spec") name.append(named_kind.name) name = ".".join(name) if (mojom.IsStructKind(kind) or mojom.IsUnionKind(kind) or mojom.IsEnumKind(kind)): - return "%s.$" % name + return "%sSpec.$" % name if mojom.IsInterfaceKind(kind): return "mojo.internal.InterfaceProxy(%sProxy)" % name if mojom.IsInterfaceRequestKind(kind): return "mojo.internal.InterfaceRequest(%sRequest)" % name if mojom.IsAssociatedInterfaceKind(kind): - return "mojo.internal.AssociatedInterfaceProxy(%sAssociatedProxy)" % ( + # TODO(rockot): Implement associated interfaces. + return "mojo.internal.AssociatedInterfaceProxy(%sProxy)" % ( name) if mojom.IsAssociatedInterfaceRequestKind(kind): return "mojo.internal.AssociatedInterfaceRequest(%s)" % name @@ -584,7 +579,7 @@ if mojom.IsStructKind(field.kind): assert field.default == "default" return "null"; - return self._ExpressionToText(field.default) + return self._ExpressionToTextLite(field.default) if field.kind in mojom.PRIMITIVES: return _kind_to_javascript_default_value[field.kind] if mojom.IsEnumKind(field.kind):
diff --git a/mojo/public/tools/bindings/mojom.gni b/mojo/public/tools/bindings/mojom.gni index 7469312..7edfa3fd 100644 --- a/mojo/public/tools/bindings/mojom.gni +++ b/mojo/public/tools/bindings/mojom.gni
@@ -1219,7 +1219,6 @@ "$target_gen_dir/$source.externs.js", "$target_gen_dir/$source-lite.js", "$target_gen_dir/$source-lite-for-compile.js", - "$target_gen_dir/$source-lite.externs.js", ] } @@ -1293,48 +1292,30 @@ } } - if (enable_mojom_closure_compile) { - js_library_for_compile_target_name = - "${target_name}_js_library_for_compile" - if (defined(invoker.sources)) { - generator_js_lite_for_compile_outputs = - [ "{{source_gen_dir}}/{{source_file_part}}-lite-for-compile.js" ] - js_library(js_library_for_compile_target_name) { - extra_public_deps = [ ":$generator_js_target_name" ] - sources = process_file_template(invoker.sources, - generator_js_lite_for_compile_outputs) - - deps = [] - foreach(d, all_deps) { - full_name = get_label_info(d, "label_no_toolchain") - deps += [ "${full_name}_js_library_for_compile" ] - } - } - } else { - group(js_library_for_compile_target_name) { - } - } - } - - js_externs_target_suffix = "_js_externs" - js_externs_target_name = "${target_name}${js_externs_target_suffix}" + js_library_for_compile_target_name = "${target_name}_js_library_for_compile" if (defined(invoker.sources)) { - js_library(js_externs_target_name) { - sources = [] + generator_js_lite_for_compile_outputs = + [ "{{source_gen_dir}}/{{source_file_part}}-lite-for-compile.js" ] + js_library(js_library_for_compile_target_name) { extra_public_deps = [ ":$generator_js_target_name" ] - externs_list = [ "${externs_path}/mojo.js" ] - externs_list += process_file_template( - invoker.sources, - [ "{{source_gen_dir}}/{{source_file_part}}-lite.externs.js" ]) + sources = process_file_template(invoker.sources, + generator_js_lite_for_compile_outputs) + externs_list = [ + "${externs_path}/mojo_core.js", + "${externs_path}/pending.js", + ] deps = [] + if (!defined(invoker.disallow_native_types)) { + deps += [ "//mojo/public/js:bindings_lite_sources" ] + } foreach(d, all_deps) { full_name = get_label_info(d, "label_no_toolchain") - deps += [ "${full_name}${js_externs_target_suffix}" ] + deps += [ "${full_name}_js_library_for_compile" ] } } } else { - group(js_externs_target_name) { + group(js_library_for_compile_target_name) { } } }
diff --git a/net/base/address_list.cc b/net/base/address_list.cc index fdc9734..7a783a6 100644 --- a/net/base/address_list.cc +++ b/net/base/address_list.cc
@@ -71,7 +71,7 @@ for (const struct addrinfo* ai = head; ai; ai = ai->ai_next) { IPEndPoint ipe; // NOTE: Ignoring non-INET* families. - if (ipe.FromSockAddr(ai->ai_addr, ai->ai_addrlen)) + if (ipe.FromSockAddr(ai->ai_addr, static_cast<socklen_t>(ai->ai_addrlen))) list.push_back(ipe); else DLOG(WARNING) << "Unknown family found in addrinfo: " << ai->ai_family;
diff --git a/net/base/ip_address.cc b/net/base/ip_address.cc index 6d39175..b7ca4f0 100644 --- a/net/base/ip_address.cc +++ b/net/base/ip_address.cc
@@ -463,7 +463,7 @@ return ip_address->AssignFromIPLiteral(hostname) && ip_address->IsIPv4(); } -unsigned CommonPrefixLength(const IPAddress& a1, const IPAddress& a2) { +size_t CommonPrefixLength(const IPAddress& a1, const IPAddress& a2) { DCHECK_EQ(a1.size(), a2.size()); for (size_t i = 0; i < a1.size(); ++i) { unsigned diff = a1.bytes()[i] ^ a2.bytes()[i]; @@ -479,7 +479,7 @@ return a1.size() * CHAR_BIT; } -unsigned MaskPrefixLength(const IPAddress& mask) { +size_t MaskPrefixLength(const IPAddress& mask) { base::StackVector<uint8_t, 16> all_ones; all_ones->resize(mask.size(), 0xFF); return CommonPrefixLength(mask,
diff --git a/net/base/ip_address.h b/net/base/ip_address.h index f7dc5aa..2f123931 100644 --- a/net/base/ip_address.h +++ b/net/base/ip_address.h
@@ -279,11 +279,10 @@ WARN_UNUSED_RESULT; // Returns number of matching initial bits between the addresses |a1| and |a2|. -NET_EXPORT unsigned CommonPrefixLength(const IPAddress& a1, - const IPAddress& a2); +NET_EXPORT size_t CommonPrefixLength(const IPAddress& a1, const IPAddress& a2); // Computes the number of leading 1-bits in |mask|. -NET_EXPORT unsigned MaskPrefixLength(const IPAddress& mask); +NET_EXPORT size_t MaskPrefixLength(const IPAddress& mask); // Checks whether |address| starts with |prefix|. This provides similar // functionality as IPAddressMatchesPrefix() but doesn't perform automatic IPv4
diff --git a/net/base/ip_endpoint.h b/net/base/ip_endpoint.h index f9eb2775..f7bb248f 100644 --- a/net/base/ip_endpoint.h +++ b/net/base/ip_endpoint.h
@@ -52,8 +52,8 @@ // |address| is the address. // |address_length| is the length of |address|. // Returns true on success, false on failure. - bool FromSockAddr(const struct sockaddr* address, socklen_t address_length) - WARN_UNUSED_RESULT; + bool FromSockAddr(const struct sockaddr* address, + socklen_t address_length) WARN_UNUSED_RESULT; // Returns value as a string (e.g. "127.0.0.1:80"). Returns the empty string // when |address_| is invalid (the port will be ignored).
diff --git a/net/base/mime_util.cc b/net/base/mime_util.cc index c11bd48f..92c09f270 100644 --- a/net/base/mime_util.cc +++ b/net/base/mime_util.cc
@@ -261,7 +261,8 @@ if (mapping.mime_type == mime_type) { const char* extensions = mapping.extensions; const char* extension_end = strchr(extensions, ','); - int len = extension_end ? extension_end - extensions : strlen(extensions); + size_t len = + extension_end ? extension_end - extensions : strlen(extensions); *result = StringToFilePathStringType(base::StringPiece(extensions, len)); return true; }
diff --git a/net/cert/cert_verify_proc_win.cc b/net/cert/cert_verify_proc_win.cc index 45b9fa5e..a7ae954 100644 --- a/net/cert/cert_verify_proc_win.cc +++ b/net/cert/cert_verify_proc_win.cc
@@ -936,7 +936,7 @@ // and used when in cache-only mode. if (!ocsp_response.empty()) { CRYPT_DATA_BLOB ocsp_response_blob; - ocsp_response_blob.cbData = ocsp_response.size(); + ocsp_response_blob.cbData = base::checked_cast<DWORD>(ocsp_response.size()); ocsp_response_blob.pbData = reinterpret_cast<BYTE*>(const_cast<char*>(ocsp_response.data())); CertSetCertificateContextProperty(
diff --git a/net/cookies/canonical_cookie.cc b/net/cookies/canonical_cookie.cc index 91611ac..aaa27709 100644 --- a/net/cookies/canonical_cookie.cc +++ b/net/cookies/canonical_cookie.cc
@@ -189,17 +189,27 @@ const GURL& url, const std::string& cookie_line, const base::Time& creation_time, - const CookieOptions& options) { + const CookieOptions& options, + CookieInclusionStatus* status) { + // Put a pointer on the stack so the rest of the function can assign to it if + // the default nullptr is passed in. + CookieInclusionStatus blank_status; + if (status == nullptr) { + status = &blank_status; + } + ParsedCookie parsed_cookie(cookie_line); if (!parsed_cookie.IsValid()) { VLOG(net::cookie_util::kVlogSetCookies) << "WARNING: Couldn't parse cookie"; + *status = CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE; return nullptr; } if (options.exclude_httponly() && parsed_cookie.IsHttpOnly()) { VLOG(net::cookie_util::kVlogSetCookies) << "Create() is not creating a httponly cookie"; + *status = CookieInclusionStatus::EXCLUDE_HTTP_ONLY; return nullptr; } @@ -207,6 +217,7 @@ if (!GetCookieDomain(url, parsed_cookie, &cookie_domain)) { VLOG(net::cookie_util::kVlogSetCookies) << "Create() failed to get a cookie domain"; + *status = CookieInclusionStatus::EXCLUDE_INVALID_DOMAIN; return nullptr; } @@ -217,6 +228,7 @@ if (parsed_cookie.IsSecure() && !url.SchemeIsCryptographic()) { VLOG(net::cookie_util::kVlogSetCookies) << "Create() is trying to create a secure cookie from an insecure URL"; + *status = CookieInclusionStatus::EXCLUDE_SECURE_ONLY; return nullptr; } @@ -238,6 +250,7 @@ if (!is_cookie_valid) { VLOG(net::cookie_util::kVlogSetCookies) << "Create() failed because the cookie violated prefix rules."; + *status = CookieInclusionStatus::EXCLUDE_INVALID_PREFIX; return nullptr; } @@ -247,6 +260,7 @@ parsed_cookie.IsHttpOnly(), parsed_cookie.SameSite(), parsed_cookie.Priority())); DCHECK(cc->IsCanonical()); + *status = CookieInclusionStatus::INCLUDE; return cc; }
diff --git a/net/cookies/canonical_cookie.h b/net/cookies/canonical_cookie.h index 39413d78..2fca15f 100644 --- a/net/cookies/canonical_cookie.h +++ b/net/cookies/canonical_cookie.h
@@ -22,6 +22,8 @@ class ParsedCookie; +struct CookieWithStatus; + class NET_EXPORT CanonicalCookie { public: CanonicalCookie(); @@ -47,14 +49,36 @@ // Supports the default copy constructor. + // This enum represents if a cookie was included or excluded, and if excluded + // why. + enum class CookieInclusionStatus { + INCLUDE = 0, + EXCLUDE_HTTP_ONLY, + EXCLUDE_SECURE_ONLY, + EXCLUDE_DOMAIN_MISMATCH, + EXCLUDE_NOT_ON_PATH, + EXCLUDE_SAMESITE_STRICT, + EXCLUDE_SAMESITE_LAX, + + // Statuses specific to setting cookies + EXCLUDE_FAILURE_TO_STORE, + EXCLUDE_NONCOOKIEABLE_SCHEME, + EXCLUDE_OVERWRITE_SECURE, + EXCLUDE_OVERWRITE_HTTP_ONLY, + EXCLUDE_INVALID_DOMAIN, + EXCLUDE_INVALID_PREFIX + }; + // Creates a new |CanonicalCookie| from the |cookie_line| and the // |creation_time|. Canonicalizes and validates inputs. May return NULL if - // an attribute value is invalid. |creation_time| may not be null. + // an attribute value is invalid. |creation_time| may not be null. Sets + // optional |status| to the relevent CookieInclusionStatus if provided static std::unique_ptr<CanonicalCookie> Create( const GURL& url, const std::string& cookie_line, const base::Time& creation_time, - const CookieOptions& options); + const CookieOptions& options, + CookieInclusionStatus* status = nullptr); // Create a canonical cookie based on sanitizing the passed inputs in the // context of the passed URL. Returns a null unique pointer if the inputs @@ -141,18 +165,6 @@ // section 5.1.3 of RFC 6265. bool IsDomainMatch(const std::string& host) const; - // This enum represents if a cookie was included or excluded, and if excluded - // why. - enum class CookieInclusionStatus { - INCLUDE = 0, - EXCLUDE_HTTP_ONLY, - EXCLUDE_SECURE_ONLY, - EXCLUDE_DOMAIN_MISMATCH, - EXCLUDE_NOT_ON_PATH, - EXCLUDE_SAMESITE_STRICT, - EXCLUDE_SAMESITE_LAX - }; - // Returns if the cookie should be included (and if not, why) for the given // request |url| using the CookieInclusionStatus enum. HTTP only cookies can // be filter by using appropriate cookie |options|. PLEASE NOTE that this @@ -246,8 +258,6 @@ CookiePriority priority_; }; -typedef std::vector<CanonicalCookie> CookieList; - // These enable us to pass along a list of excluded cookie with the reason they // were excluded struct CookieWithStatus { @@ -255,6 +265,8 @@ CanonicalCookie::CookieInclusionStatus status; }; +typedef std::vector<CanonicalCookie> CookieList; + typedef std::vector<CookieWithStatus> CookieStatusList; } // namespace net
diff --git a/net/cookies/canonical_cookie_unittest.cc b/net/cookies/canonical_cookie_unittest.cc index 87a47908..0b2420fe 100644 --- a/net/cookies/canonical_cookie_unittest.cc +++ b/net/cookies/canonical_cookie_unittest.cc
@@ -97,13 +97,19 @@ // Test creating secure cookies. // https://tools.ietf.org/html/draft-ietf-httpbis-cookie-alone disallows // insecure URLs from setting secure cookies. - cookie = CanonicalCookie::Create(url, "A=2; Secure", creation_time, options); + CanonicalCookie::CookieInclusionStatus status; + cookie = CanonicalCookie::Create(url, "A=2; Secure", creation_time, options, + &status); EXPECT_FALSE(cookie.get()); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_SECURE_ONLY, + status); // Test creating http only cookies. - cookie = - CanonicalCookie::Create(url, "A=2; HttpOnly", creation_time, options); + cookie = CanonicalCookie::Create(url, "A=2; HttpOnly", creation_time, options, + &status); EXPECT_FALSE(cookie.get()); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_HTTP_ONLY, status); + CookieOptions httponly_options; httponly_options.set_include_httponly(); cookie = CanonicalCookie::Create(url, "A=2; HttpOnly", creation_time, @@ -173,21 +179,26 @@ GURL url("http://www.example.com/test/foo.html"); base::Time now = base::Time::Now(); CookieOptions options; + CanonicalCookie::CookieInclusionStatus status; options.set_exclude_httponly(); std::unique_ptr<CanonicalCookie> cookie = - CanonicalCookie::Create(url, "A=2; HttpOnly", now, options); + CanonicalCookie::Create(url, "A=2; HttpOnly", now, options, &status); EXPECT_EQ(nullptr, cookie.get()); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_HTTP_ONLY, status); } TEST(CanonicalCookieTest, CreateWithInvalidDomain) { GURL url("http://www.example.com/test/foo.html"); base::Time now = base::Time::Now(); CookieOptions options; + CanonicalCookie::CookieInclusionStatus status; - std::unique_ptr<CanonicalCookie> cookie = - CanonicalCookie::Create(url, "A=2; Domain=wrongdomain.com", now, options); + std::unique_ptr<CanonicalCookie> cookie = CanonicalCookie::Create( + url, "A=2; Domain=wrongdomain.com", now, options, &status); EXPECT_EQ(nullptr, cookie.get()); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_INVALID_DOMAIN, + status); } TEST(CanonicalCookieTest, EmptyExpiry) { @@ -575,12 +586,16 @@ GURL http_url("http://www.example.test"); base::Time creation_time = base::Time::Now(); CookieOptions options; + CanonicalCookie::CookieInclusionStatus status; // A __Secure- cookie must be Secure. EXPECT_FALSE(CanonicalCookie::Create(https_url, "__Secure-A=B", creation_time, - options)); + options, &status)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_INVALID_PREFIX, + status); EXPECT_FALSE(CanonicalCookie::Create(https_url, "__Secure-A=B; httponly", - creation_time, options)); + creation_time, options, &status)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_HTTP_ONLY, status); // A typoed prefix does not have to be Secure. EXPECT_TRUE(CanonicalCookie::Create(https_url, "__secure-A=B; Secure", @@ -594,7 +609,9 @@ // A __Secure- cookie can't be set on a non-secure origin. EXPECT_FALSE(CanonicalCookie::Create(http_url, "__Secure-A=B; Secure", - creation_time, options)); + creation_time, options, &status)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_SECURE_ONLY, + status); } TEST(CanonicalCookieTest, HostCookiePrefix) { @@ -603,36 +620,52 @@ base::Time creation_time = base::Time::Now(); CookieOptions options; std::string domain = https_url.host(); + CanonicalCookie::CookieInclusionStatus status; // A __Host- cookie must be Secure. EXPECT_FALSE(CanonicalCookie::Create(https_url, "__Host-A=B;", creation_time, - options)); + options, &status)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_INVALID_PREFIX, + status); EXPECT_FALSE(CanonicalCookie::Create( https_url, "__Host-A=B; Domain=" + domain + "; Path=/;", creation_time, - options)); + options, &status)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_INVALID_PREFIX, + status); EXPECT_TRUE(CanonicalCookie::Create(https_url, "__Host-A=B; Path=/; Secure;", creation_time, options)); // A __Host- cookie must be set from a secure scheme. EXPECT_FALSE(CanonicalCookie::Create( http_url, "__Host-A=B; Domain=" + domain + "; Path=/; Secure;", - creation_time, options)); + creation_time, options, &status)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_SECURE_ONLY, + status); EXPECT_TRUE(CanonicalCookie::Create(https_url, "__Host-A=B; Path=/; Secure;", creation_time, options)); // A __Host- cookie can't have a Domain. EXPECT_FALSE(CanonicalCookie::Create( https_url, "__Host-A=B; Domain=" + domain + "; Path=/; Secure;", - creation_time, options)); + creation_time, options, &status)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_INVALID_PREFIX, + status); EXPECT_FALSE(CanonicalCookie::Create( https_url, "__Host-A=B; Domain=" + domain + "; Secure;", creation_time, - options)); + options, &status)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_INVALID_PREFIX, + status); // A __Host- cookie must have a Path of "/". - EXPECT_FALSE(CanonicalCookie::Create( - https_url, "__Host-A=B; Path=/foo; Secure;", creation_time, options)); + EXPECT_FALSE(CanonicalCookie::Create(https_url, + "__Host-A=B; Path=/foo; Secure;", + creation_time, options, &status)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_INVALID_PREFIX, + status); EXPECT_FALSE(CanonicalCookie::Create(https_url, "__Host-A=B; Secure;", - creation_time, options)); + creation_time, options, &status)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_INVALID_PREFIX, + status); EXPECT_TRUE(CanonicalCookie::Create(https_url, "__Host-A=B; Secure; Path=/;", creation_time, options));
diff --git a/net/cookies/cookie_monster.cc b/net/cookies/cookie_monster.cc index ba98b04..2152392 100644 --- a/net/cookies/cookie_monster.cc +++ b/net/cookies/cookie_monster.cc
@@ -705,22 +705,29 @@ DCHECK(thread_checker_.CalledOnValidThread()); if (!HasCookieableScheme(url)) { - MaybeRunCookieCallback(std::move(callback), false); + MaybeRunCookieCallback( + std::move(callback), + CanonicalCookie::CookieInclusionStatus::EXCLUDE_NONCOOKIEABLE_SCHEME); return; } VLOG(net::cookie_util::kVlogSetCookies) << "SetCookie() line: " << cookie_line; - std::unique_ptr<CanonicalCookie> cc( - CanonicalCookie::Create(url, cookie_line, Time::Now(), options)); + CanonicalCookie::CookieInclusionStatus status; - if (!cc.get()) { + std::unique_ptr<CanonicalCookie> cc( + CanonicalCookie::Create(url, cookie_line, Time::Now(), options, &status)); + + if (status != CanonicalCookie::CookieInclusionStatus::INCLUDE) { + DCHECK(!cc); VLOG(net::cookie_util::kVlogSetCookies) << "WARNING: Failed to allocate CanonicalCookie"; - MaybeRunCookieCallback(std::move(callback), false); + MaybeRunCookieCallback(std::move(callback), status); return; } + + DCHECK(cc); SetCanonicalCookie(std::move(cc), url.SchemeIsCryptographic(), !options.exclude_httponly(), std::move(callback)); } @@ -1059,7 +1066,7 @@ } } -bool CookieMonster::DeleteAnyEquivalentCookie( +CanonicalCookie::CookieInclusionStatus CookieMonster::DeleteAnyEquivalentCookie( const std::string& key, const CanonicalCookie& ecc, bool source_secure, @@ -1156,7 +1163,13 @@ } } - return skipped_httponly || skipped_secure_cookie; + if (skipped_httponly) + return CanonicalCookie::CookieInclusionStatus::EXCLUDE_OVERWRITE_HTTP_ONLY; + + if (skipped_secure_cookie) + return CanonicalCookie::CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE; + + return CanonicalCookie::CookieInclusionStatus::INCLUDE; } CookieMonster::CookieMap::iterator CookieMonster::InternalInsertCookie( @@ -1194,9 +1207,17 @@ SetCookiesCallback callback) { DCHECK(thread_checker_.CalledOnValidThread()); - if ((cc->IsSecure() && !secure_source) || - (cc->IsHttpOnly() && !modify_http_only)) { - MaybeRunCookieCallback(std::move(callback), false); + if ((cc->IsSecure() && !secure_source)) { + MaybeRunCookieCallback( + std::move(callback), + CanonicalCookie::CookieInclusionStatus::EXCLUDE_SECURE_ONLY); + return; + } + + if ((cc->IsHttpOnly() && !modify_http_only)) { + MaybeRunCookieCallback( + std::move(callback), + CanonicalCookie::CookieInclusionStatus::EXCLUDE_HTTP_ONLY); return; } @@ -1210,15 +1231,19 @@ bool already_expired = cc->IsExpired(creation_date); base::Time creation_date_to_inherit; - if (DeleteAnyEquivalentCookie(key, *cc, secure_source, !modify_http_only, - already_expired, &creation_date_to_inherit)) { + + CanonicalCookie::CookieInclusionStatus status = + DeleteAnyEquivalentCookie(key, *cc, secure_source, !modify_http_only, + already_expired, &creation_date_to_inherit); + + if (status != CanonicalCookie::CookieInclusionStatus::INCLUDE) { std::string error; error = "SetCookie() not clobbering httponly cookie or secure cookie for " "insecure scheme"; VLOG(net::cookie_util::kVlogSetCookies) << error; - MaybeRunCookieCallback(std::move(callback), false); + MaybeRunCookieCallback(std::move(callback), status); return; } @@ -1266,7 +1291,8 @@ // and we will purge the expired cookies in GetCookies(). GarbageCollect(creation_date, key); - MaybeRunCookieCallback(std::move(callback), true); + MaybeRunCookieCallback(std::move(callback), + CanonicalCookie::CookieInclusionStatus::INCLUDE); } void CookieMonster::SetAllCookies(CookieList list, @@ -1299,7 +1325,8 @@ // shouldn't have a return value. But it should also be deleted (see // https://codereview.chromium.org/2882063002/#msg64), which would // solve the return value problem. - MaybeRunCookieCallback(std::move(callback), true); + MaybeRunCookieCallback(std::move(callback), + CanonicalCookie::CookieInclusionStatus::INCLUDE); } void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie* cc,
diff --git a/net/cookies/cookie_monster.h b/net/cookies/cookie_monster.h index 151511f5..680df39 100644 --- a/net/cookies/cookie_monster.h +++ b/net/cookies/cookie_monster.h
@@ -463,12 +463,13 @@ // |creation_date_to_inherit| will be set to that cookie's creation date. // // NOTE: There should never be more than a single matching equivalent cookie. - bool DeleteAnyEquivalentCookie(const std::string& key, - const CanonicalCookie& ecc, - bool source_secure, - bool skip_httponly, - bool already_expired, - base::Time* creation_date_to_inherit); + CanonicalCookie::CookieInclusionStatus DeleteAnyEquivalentCookie( + const std::string& key, + const CanonicalCookie& ecc, + bool source_secure, + bool skip_httponly, + bool already_expired, + base::Time* creation_date_to_inherit); // Inserts |cc| into cookies_. Returns an iterator that points to the inserted // cookie in cookies_. Guarantee: all iterators to cookies_ remain valid.
diff --git a/net/cookies/cookie_monster_perftest.cc b/net/cookies/cookie_monster_perftest.cc index 9636629..b7c90ec 100644 --- a/net/cookies/cookie_monster_perftest.cc +++ b/net/cookies/cookie_monster_perftest.cc
@@ -68,8 +68,8 @@ } private: - void Run(bool success) { - EXPECT_TRUE(success); + void Run(CanonicalCookie::CookieInclusionStatus status) { + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, status); CookieTestCallback::Run(); } CookieOptions options_;
diff --git a/net/cookies/cookie_monster_unittest.cc b/net/cookies/cookie_monster_unittest.cc index ad22e87e..e20ef24 100644 --- a/net/cookies/cookie_monster_unittest.cc +++ b/net/cookies/cookie_monster_unittest.cc
@@ -147,7 +147,8 @@ GetCookieListCallback callback; cm->GetCookieListWithOptionsAsync( url, options, - base::Bind(&GetCookieListCallback::Run, base::Unretained(&callback))); + base::BindOnce(&GetCookieListCallback::Run, + base::Unretained(&callback))); callback.WaitUntilDone(); return callback.cookies(); } @@ -168,12 +169,13 @@ bool SetAllCookies(CookieMonster* cm, const CookieList& list) { DCHECK(cm); - ResultSavingCookieCallback<bool> callback; - cm->SetAllCookiesAsync(list, - base::Bind(&ResultSavingCookieCallback<bool>::Run, - base::Unretained(&callback))); + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> callback; + cm->SetAllCookiesAsync( + list, base::BindOnce(&ResultSavingCookieCallback< + CanonicalCookie::CookieInclusionStatus>::Run, + base::Unretained(&callback))); callback.WaitUntilDone(); - return callback.result(); + return callback.result() == CanonicalCookie::CookieInclusionStatus::INCLUDE; } bool SetCookieWithCreationTime(CookieMonster* cm, @@ -182,15 +184,16 @@ base::Time creation_time) { DCHECK(cm); DCHECK(!creation_time.is_null()); - ResultSavingCookieCallback<bool> callback; + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> callback; cm->SetCanonicalCookieAsync( CanonicalCookie::Create(url, cookie_line, creation_time, CookieOptions()), url.SchemeIsCryptographic(), /* modify_httponly = */ false, - base::BindOnce(&ResultSavingCookieCallback<bool>::Run, + base::BindOnce(&ResultSavingCookieCallback< + CanonicalCookie::CookieInclusionStatus>::Run, base::Unretained(&callback))); callback.WaitUntilDone(); - return callback.result(); + return callback.result() == CanonicalCookie::CookieInclusionStatus::INCLUDE; } uint32_t DeleteAllCreatedInTimeRange(CookieMonster* cm, @@ -211,8 +214,8 @@ ResultSavingCookieCallback<uint32_t> callback; cm->DeleteAllMatchingInfoAsync( std::move(delete_info), - base::Bind(&ResultSavingCookieCallback<uint32_t>::Run, - base::Unretained(&callback))); + base::BindOnce(&ResultSavingCookieCallback<uint32_t>::Run, + base::Unretained(&callback))); callback.WaitUntilDone(); return callback.result(); } @@ -1096,11 +1099,14 @@ WaitForLoadCall(); - EXPECT_CALL(set_cookies_callback, Run(true)) + EXPECT_CALL(set_cookies_callback, + Run(CanonicalCookie::CookieInclusionStatus::INCLUDE)) .WillOnce(SetCookieAction(&cookie_monster(), http_www_foo_.url(), "X=Y", &set_cookies_callback)); base::RunLoop loop; - EXPECT_CALL(set_cookies_callback, Run(true)).WillOnce(QuitRunLoop(&loop)); + EXPECT_CALL(set_cookies_callback, + Run(CanonicalCookie::CookieInclusionStatus::INCLUDE)) + .WillOnce(QuitRunLoop(&loop)); CompleteLoading(); loop.Run(); @@ -1123,11 +1129,14 @@ WaitForLoadCall(); - EXPECT_CALL(set_cookies_callback, Run(true)) + EXPECT_CALL(set_cookies_callback, + Run(CanonicalCookie::CookieInclusionStatus::INCLUDE)) .WillOnce( SetAllCookiesAction(&cookie_monster(), list, &set_cookies_callback)); base::RunLoop loop; - EXPECT_CALL(set_cookies_callback, Run(true)).WillOnce(QuitRunLoop(&loop)); + EXPECT_CALL(set_cookies_callback, + Run(CanonicalCookie::CookieInclusionStatus::INCLUDE)) + .WillOnce(QuitRunLoop(&loop)); CompleteLoading(); loop.Run(); @@ -1330,7 +1339,8 @@ .WillOnce(GetCookieListForUrlWithOptionsAction( &cookie_monster(), http_www_foo_.url(), &get_cookie_list_callback_deferred)); - EXPECT_CALL(set_cookies_callback, Run(true)); + EXPECT_CALL(set_cookies_callback, + Run(CanonicalCookie::CookieInclusionStatus::INCLUDE)); base::RunLoop loop; EXPECT_CALL(get_cookie_list_callback_deferred, Run(MatchesCookieLine("A=B; X=1"), testing::_)) @@ -1546,10 +1556,16 @@ GURL foo_url("foo://host/path"); GURL http_url("http://host/path"); - EXPECT_TRUE(SetCookie(cm.get(), http_url, "x=1")); - EXPECT_FALSE(SetCookie(cm.get(), foo_url, "x=1")); - EXPECT_TRUE(SetCookie(cm_foo.get(), foo_url, "x=1")); - EXPECT_FALSE(SetCookie(cm_foo.get(), http_url, "x=1")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), http_url, "x=1")); + EXPECT_EQ( + CanonicalCookie::CookieInclusionStatus::EXCLUDE_NONCOOKIEABLE_SCHEME, + SetCookieReturnStatus(cm.get(), foo_url, "x=1")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm_foo.get(), foo_url, "x=1")); + EXPECT_EQ( + CanonicalCookie::CookieInclusionStatus::EXCLUDE_NONCOOKIEABLE_SCHEME, + SetCookieReturnStatus(cm_foo.get(), http_url, "x=1")); } TEST_F(CookieMonsterTest, GetAllCookiesForURL) { @@ -2267,16 +2283,18 @@ new CookieMonster(store.get(), nullptr, &net_log_)); // Get all cookies task that queues a task to set a cookie when executed. - ResultSavingCookieCallback<bool> set_cookie_callback; + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> + set_cookie_callback; cm->SetCookieWithOptionsAsync( kUrl, "a=b", CookieOptions(), - base::Bind(&ResultSavingCookieCallback<bool>::Run, - base::Unretained(&set_cookie_callback))); + base::BindOnce(&ResultSavingCookieCallback< + CanonicalCookie::CookieInclusionStatus>::Run, + base::Unretained(&set_cookie_callback))); GetCookieListCallback get_cookie_list_callback1; cm->GetAllCookiesAsync( - base::Bind(&GetCookieListCallback::Run, - base::Unretained(&get_cookie_list_callback1))); + base::BindOnce(&GetCookieListCallback::Run, + base::Unretained(&get_cookie_list_callback1))); // Two load events should have been queued. ASSERT_EQ(2u, store->commands().size()); @@ -2291,7 +2309,8 @@ // The tasks should run in order, and the get should see the cookies. set_cookie_callback.WaitUntilDone(); - EXPECT_TRUE(set_cookie_callback.result()); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + set_cookie_callback.result()); get_cookie_list_callback1.WaitUntilDone(); EXPECT_EQ(1u, get_cookie_list_callback1.cookies().size()); @@ -2304,8 +2323,8 @@ // The just set cookie should still be in the store. GetCookieListCallback get_cookie_list_callback2; cm->GetAllCookiesAsync( - base::Bind(&GetCookieListCallback::Run, - base::Unretained(&get_cookie_list_callback2))); + base::BindOnce(&GetCookieListCallback::Run, + base::Unretained(&get_cookie_list_callback2))); get_cookie_list_callback2.WaitUntilDone(); EXPECT_EQ(1u, get_cookie_list_callback2.cookies().size()); } @@ -2322,14 +2341,14 @@ new CookieMonster(store.get(), nullptr, &net_log_)); ResultSavingCookieCallback<uint32_t> delete_callback; - cm->DeleteAllAsync(base::Bind(&ResultSavingCookieCallback<uint32_t>::Run, - base::Unretained(&delete_callback))); + cm->DeleteAllAsync(base::BindOnce(&ResultSavingCookieCallback<uint32_t>::Run, + base::Unretained(&delete_callback))); GetCookieListCallback get_cookie_list_callback; cm->GetCookieListWithOptionsAsync( kUrl, CookieOptions(), - base::Bind(&GetCookieListCallback::Run, - base::Unretained(&get_cookie_list_callback))); + base::BindOnce(&GetCookieListCallback::Run, + base::Unretained(&get_cookie_list_callback))); // Only the main load should have been queued. ASSERT_EQ(1u, store->commands().size()); @@ -2364,19 +2383,21 @@ GetCookieListCallback get_cookie_list_callback1; cm->GetAllCookiesAsync( - base::Bind(&GetCookieListCallback::Run, - base::Unretained(&get_cookie_list_callback1))); + base::BindOnce(&GetCookieListCallback::Run, + base::Unretained(&get_cookie_list_callback1))); - ResultSavingCookieCallback<bool> set_cookie_callback; + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> + set_cookie_callback; cm->SetCookieWithOptionsAsync( kUrl, "a=b", CookieOptions(), - base::Bind(&ResultSavingCookieCallback<bool>::Run, - base::Unretained(&set_cookie_callback))); + base::BindOnce(&ResultSavingCookieCallback< + CanonicalCookie::CookieInclusionStatus>::Run, + base::Unretained(&set_cookie_callback))); GetCookieListCallback get_cookie_list_callback2; cm->GetAllCookiesAsync( - base::Bind(&GetCookieListCallback::Run, - base::Unretained(&get_cookie_list_callback2))); + base::BindOnce(&GetCookieListCallback::Run, + base::Unretained(&get_cookie_list_callback2))); // Only the main load should have been queued. ASSERT_EQ(1u, store->commands().size()); @@ -2390,7 +2411,8 @@ EXPECT_EQ(0u, get_cookie_list_callback1.cookies().size()); set_cookie_callback.WaitUntilDone(); - EXPECT_TRUE(set_cookie_callback.result()); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + set_cookie_callback.result()); get_cookie_list_callback2.WaitUntilDone(); EXPECT_EQ(1u, get_cookie_list_callback2.cookies().size()); @@ -2398,10 +2420,10 @@ namespace { -void RunClosureOnCookieListReceived(const base::Closure& closure, +void RunClosureOnCookieListReceived(base::OnceClosure closure, const CookieList& cookie_list, const CookieStatusList& excluded_cookies) { - closure.Run(); + std::move(closure).Run(); } } // namespace @@ -2418,20 +2440,23 @@ new CookieMonster(store.get(), nullptr, &net_log_)); // Get all cookies task that queues a task to set a cookie when executed. - ResultSavingCookieCallback<bool> set_cookie_callback; - cm->GetAllCookiesAsync(base::Bind( + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> + set_cookie_callback; + cm->GetAllCookiesAsync(base::BindOnce( &RunClosureOnCookieListReceived, - base::Bind(&CookieStore::SetCookieWithOptionsAsync, - base::Unretained(cm.get()), kUrl, "a=b", CookieOptions(), - base::Bind(&ResultSavingCookieCallback<bool>::Run, - base::Unretained(&set_cookie_callback))))); + base::BindOnce( + &CookieStore::SetCookieWithOptionsAsync, base::Unretained(cm.get()), + kUrl, "a=b", CookieOptions(), + base::BindOnce(&ResultSavingCookieCallback< + CanonicalCookie::CookieInclusionStatus>::Run, + base::Unretained(&set_cookie_callback))))); // Get cookie task. Queued before the delete task is executed, so should not // see the set cookie. GetCookieListCallback get_cookie_list_callback1; cm->GetAllCookiesAsync( - base::Bind(&GetCookieListCallback::Run, - base::Unretained(&get_cookie_list_callback1))); + base::BindOnce(&GetCookieListCallback::Run, + base::Unretained(&get_cookie_list_callback1))); // Only the main load should have been queued. ASSERT_EQ(1u, store->commands().size()); @@ -2446,13 +2471,14 @@ EXPECT_EQ(0u, get_cookie_list_callback1.cookies().size()); set_cookie_callback.WaitUntilDone(); - EXPECT_TRUE(set_cookie_callback.result()); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + set_cookie_callback.result()); // A subsequent get cookies call should see the new cookie. GetCookieListCallback get_cookie_list_callback2; cm->GetAllCookiesAsync( - base::Bind(&GetCookieListCallback::Run, - base::Unretained(&get_cookie_list_callback2))); + base::BindOnce(&GetCookieListCallback::Run, + base::Unretained(&get_cookie_list_callback2))); get_cookie_list_callback2.WaitUntilDone(); EXPECT_EQ(1u, get_cookie_list_callback2.cookies().size()); } @@ -2467,7 +2493,7 @@ ASSERT_EQ(0, counter->callback_count()); // Before initialization, FlushStore() should just run the callback. - cm->FlushStore(base::Bind(&CallbackCounter::Callback, counter)); + cm->FlushStore(base::BindOnce(&CallbackCounter::Callback, counter)); base::RunLoop().RunUntilIdle(); ASSERT_EQ(0, store->flush_count()); @@ -2482,7 +2508,7 @@ // After initialization, FlushStore() should delegate to the store. GetAllCookies(cm.get()); // Force init. - cm->FlushStore(base::Bind(&CallbackCounter::Callback, counter)); + cm->FlushStore(base::BindOnce(&CallbackCounter::Callback, counter)); base::RunLoop().RunUntilIdle(); ASSERT_EQ(1, store->flush_count()); @@ -2503,7 +2529,7 @@ ASSERT_EQ(2, counter->callback_count()); - cm->FlushStore(base::Bind(&CallbackCounter::Callback, counter)); + cm->FlushStore(base::BindOnce(&CallbackCounter::Callback, counter)); base::RunLoop().RunUntilIdle(); ASSERT_EQ(3, counter->callback_count()); @@ -2951,24 +2977,32 @@ // A non-secure cookie can be created from either a URL with a secure or // insecure scheme. - EXPECT_TRUE(SetCookie(cm.get(), http_url, "A=C;")); - EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=B;")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), http_url, "A=C;")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), https_url, "A=B;")); // A secure cookie cannot be created from a URL with an insecure scheme. - EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=B; Secure")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_SECURE_ONLY, + SetCookieReturnStatus(cm.get(), http_url, "A=B; Secure")); // A secure cookie can be created from a URL with a secure scheme. - EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=B; Secure")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), https_url, "A=B; Secure")); // If a non-secure cookie is created from a URL with an insecure scheme, and a // secure cookie with the same name already exists, do not update the cookie. - EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=B; Secure")); - EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=C;")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), https_url, "A=B; Secure")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE, + SetCookieReturnStatus(cm.get(), http_url, "A=C;")); // If a non-secure cookie is created from a URL with an secure scheme, and a // secure cookie with the same name already exists, update the cookie. - EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=B; Secure")); - EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=C;")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), https_url, "A=B; Secure")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), https_url, "A=C;")); // If a non-secure cookie is created from a URL with an insecure scheme, and // a secure cookie with the same name already exists, do not update the cookie @@ -2976,27 +3010,40 @@ // // With an existing cookie whose path is '/', a cookie with the same name // cannot be set on the same domain, regardless of path: - EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=B; Secure")); - EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=C; path=/")); - EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=C; path=/my/path")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), https_url, "A=B; Secure")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE, + SetCookieReturnStatus(cm.get(), http_url, "A=C; path=/")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE, + SetCookieReturnStatus(cm.get(), http_url, "A=C; path=/my/path")); // But if the existing cookie has a path somewhere under the root, cookies // with the same name may be set for paths which don't overlap the existing // cookie. EXPECT_TRUE( SetCookie(cm.get(), https_url, "WITH_PATH=B; Secure; path=/my/path")); - EXPECT_TRUE(SetCookie(cm.get(), http_url, "WITH_PATH=C")); - EXPECT_TRUE(SetCookie(cm.get(), http_url, "WITH_PATH=C; path=/")); - EXPECT_TRUE(SetCookie(cm.get(), http_url, "WITH_PATH=C; path=/your/path")); - EXPECT_FALSE(SetCookie(cm.get(), http_url, "WITH_PATH=C; path=/my/path")); - EXPECT_FALSE(SetCookie(cm.get(), http_url, "WITH_PATH=C; path=/my/path/sub")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), http_url, "WITH_PATH=C")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), http_url, "WITH_PATH=C; path=/")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), http_url, + "WITH_PATH=C; path=/your/path")); + EXPECT_EQ( + CanonicalCookie::CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE, + SetCookieReturnStatus(cm.get(), http_url, "WITH_PATH=C; path=/my/path")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE, + SetCookieReturnStatus(cm.get(), http_url, + "WITH_PATH=C; path=/my/path/sub")); DeleteAll(cm.get()); // If a secure cookie is set on top of an existing insecure cookie but with a // different path, both are retained. - EXPECT_TRUE(SetCookie(cm.get(), http_url, "A=B; path=/foo")); - EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=C; Secure; path=/")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), http_url, "A=B; path=/foo")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), https_url, "A=C; Secure; path=/")); // Querying from an insecure url gets only the insecure cookie, but querying // from a secure url returns both. @@ -3007,8 +3054,10 @@ // Attempting to set an insecure cookie (from an insecure scheme) that domain- // matches and path-matches the secure cookie fails i.e. the secure cookie is // left alone... - EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=D; path=/foo")); - EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=D; path=/")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE, + SetCookieReturnStatus(cm.get(), http_url, "A=D; path=/foo")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE, + SetCookieReturnStatus(cm.get(), http_url, "A=D; path=/")); EXPECT_THAT(GetCookies(cm.get(), https_foo_url), testing::HasSubstr("A=C")); // ...but the original insecure cookie is still retained. @@ -3017,23 +3066,34 @@ testing::Not(testing::HasSubstr("A=D"))); // Deleting the secure cookie leaves only the original insecure cookie. - EXPECT_TRUE(SetCookie(cm.get(), https_url, - "A=C; path=/; Expires=Thu, 01-Jan-1970 00:00:01 GMT")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus( + cm.get(), https_url, + "A=C; path=/; Expires=Thu, 01-Jan-1970 00:00:01 GMT")); EXPECT_EQ("A=B", GetCookies(cm.get(), https_foo_url)); // If a non-secure cookie is created from a URL with an insecure scheme, and // a secure cookie with the same name already exists, if the domain strings // domain-match, do not update the cookie. - EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=B; Secure")); - EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=C; domain=foo.com")); - EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=C; domain=www.foo.com")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), https_url, "A=B; Secure")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE, + SetCookieReturnStatus(cm.get(), http_url, "A=C; domain=foo.com")); + EXPECT_EQ( + CanonicalCookie::CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE, + SetCookieReturnStatus(cm.get(), http_url, "A=C; domain=www.foo.com")); // Since A=B was set above with no domain string, set a different cookie here // so the insecure examples aren't trying to overwrite the one above. - EXPECT_TRUE(SetCookie(cm.get(), https_url, "B=C; Secure; domain=foo.com")); - EXPECT_FALSE(SetCookie(cm.get(), http_url, "B=D; domain=foo.com")); - EXPECT_FALSE(SetCookie(cm.get(), http_url, "B=D")); - EXPECT_FALSE(SetCookie(cm.get(), http_superdomain_url, "B=D")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), https_url, + "B=C; Secure; domain=foo.com")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE, + SetCookieReturnStatus(cm.get(), http_url, "B=D; domain=foo.com")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE, + SetCookieReturnStatus(cm.get(), http_url, "B=D")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE, + SetCookieReturnStatus(cm.get(), http_superdomain_url, "B=D")); // Verify that if an httponly version of the cookie exists, adding a Secure // version of the cookie still does not overwrite it. @@ -3043,7 +3103,8 @@ include_httponly)); // Note that the lack of an explicit options object below uses the default, // which in this case includes "exclude_httponly = true". - EXPECT_FALSE(SetCookie(cm.get(), https_url, "C=E; Secure")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_OVERWRITE_HTTP_ONLY, + SetCookieReturnStatus(cm.get(), https_url, "C=E; Secure")); TestNetLogEntry::List entries; net_log_.GetEntries(&entries); @@ -3185,14 +3246,19 @@ // Tests that non-equivalent cookies because of the path attribute can be set // successfully. - EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=B; Secure")); - EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=C; path=/some/other/path")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), https_url, "A=B; Secure")); + EXPECT_EQ( + CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), https_url, "A=C; path=/some/other/path")); EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=D; path=/some/other/path")); // Tests that non-equivalent cookies because of the domain attribute can be // set successfully. - EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=B; Secure")); - EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=C; domain=foo.com")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), https_url, "A=B; Secure")); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + SetCookieReturnStatus(cm.get(), https_url, "A=C; domain=foo.com")); EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=D; domain=foo.com")); } @@ -3204,12 +3270,14 @@ CookieMonster cm(persistent_store.get(), nullptr, nullptr); // Start of a canonical cookie set. - ResultSavingCookieCallback<bool> callback_set; + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> + callback_set; cm.SetCanonicalCookieAsync( CanonicalCookie::Create(GURL("http://a.com/"), "A=B", base::Time::Now(), CookieOptions()), false /* secure_source */, false /* modify_httponly */, - base::BindOnce(&ResultSavingCookieCallback<bool>::Run, + base::BindOnce(&ResultSavingCookieCallback< + CanonicalCookie::CookieInclusionStatus>::Run, base::Unretained(&callback_set))); // Get cookies for a different URL. @@ -3288,21 +3356,25 @@ // Write a cookie created at |t1|. auto cookie = CanonicalCookie::Create(url, cookie_line, t1, options); - ResultSavingCookieCallback<bool> set_callback_1; + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> + set_callback_1; cm.SetCanonicalCookieAsync( std::move(cookie), url.SchemeIsCryptographic(), !options.exclude_httponly(), - base::BindOnce(&ResultSavingCookieCallback<bool>::Run, + base::BindOnce(&ResultSavingCookieCallback< + CanonicalCookie::CookieInclusionStatus>::Run, base::Unretained(&set_callback_1))); set_callback_1.WaitUntilDone(); // Overwrite the cookie at |t2|. cookie = CanonicalCookie::Create(url, cookie_line, t2, options); - ResultSavingCookieCallback<bool> set_callback_2; + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> + set_callback_2; cm.SetCanonicalCookieAsync( std::move(cookie), url.SchemeIsCryptographic(), !options.exclude_httponly(), - base::BindOnce(&ResultSavingCookieCallback<bool>::Run, + base::BindOnce(&ResultSavingCookieCallback< + CanonicalCookie::CookieInclusionStatus>::Run, base::Unretained(&set_callback_2))); set_callback_2.WaitUntilDone();
diff --git a/net/cookies/cookie_store.h b/net/cookies/cookie_store.h index b4b4ce4f..086115f3 100644 --- a/net/cookies/cookie_store.h +++ b/net/cookies/cookie_store.h
@@ -45,7 +45,9 @@ typedef base::OnceCallback<void(const CookieList& cookies, const CookieStatusList& excluded_list)> GetCookieListCallback; - typedef base::OnceCallback<void(bool success)> SetCookiesCallback; + typedef base::OnceCallback<void( + CanonicalCookie::CookieInclusionStatus status)> + SetCookiesCallback; typedef base::OnceCallback<void(uint32_t num_deleted)> DeleteCallback; virtual ~CookieStore();
diff --git a/net/cookies/cookie_store_test_helpers.cc b/net/cookies/cookie_store_test_helpers.cc index 7261c7c..022b73a 100644 --- a/net/cookies/cookie_store_test_helpers.cc +++ b/net/cookies/cookie_store_test_helpers.cc
@@ -68,11 +68,13 @@ nullptr /* channel_id_service */, nullptr /* netlog */)), did_run_(false), - result_(false) {} + result_( + CanonicalCookie::CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE) {} DelayedCookieMonster::~DelayedCookieMonster() = default; -void DelayedCookieMonster::SetCookiesInternalCallback(bool result) { +void DelayedCookieMonster::SetCookiesInternalCallback( + CanonicalCookie::CookieInclusionStatus result) { result_ = result; did_run_ = true; }
diff --git a/net/cookies/cookie_store_test_helpers.h b/net/cookies/cookie_store_test_helpers.h index 293425e3..eb7934cee 100644 --- a/net/cookies/cookie_store_test_helpers.h +++ b/net/cookies/cookie_store_test_helpers.h
@@ -93,7 +93,8 @@ private: // Be called immediately from CookieMonster. - void SetCookiesInternalCallback(bool result); + void SetCookiesInternalCallback( + CanonicalCookie::CookieInclusionStatus result); void GetCookiesWithOptionsInternalCallback(const std::string& cookie); void GetCookieListWithOptionsInternalCallback( @@ -113,7 +114,7 @@ DelayedCookieMonsterChangeDispatcher change_dispatcher_; bool did_run_; - bool result_; + CanonicalCookie::CookieInclusionStatus result_; std::string cookie_; std::string cookie_line_; CookieList cookie_list_;
diff --git a/net/cookies/cookie_store_unittest.h b/net/cookies/cookie_store_unittest.h index 96a23f8..d546f45 100644 --- a/net/cookies/cookie_store_unittest.h +++ b/net/cookies/cookie_store_unittest.h
@@ -199,14 +199,14 @@ const std::string& cookie_line, const CookieOptions& options) { DCHECK(cs); - ResultSavingCookieCallback<bool> callback; + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> callback; cs->SetCookieWithOptionsAsync( url, cookie_line, options, - base::Bind( - &ResultSavingCookieCallback<bool>::Run, - base::Unretained(&callback))); + base::BindOnce(&ResultSavingCookieCallback< + CanonicalCookie::CookieInclusionStatus>::Run, + base::Unretained(&callback))); callback.WaitUntilDone(); - return callback.result(); + return callback.result() == CanonicalCookie::CookieInclusionStatus::INCLUDE; } bool SetCanonicalCookie(CookieStore* cs, @@ -214,13 +214,14 @@ bool secure_source, bool can_modify_httponly) { DCHECK(cs); - ResultSavingCookieCallback<bool> callback; + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> callback; cs->SetCanonicalCookieAsync( std::move(cookie), secure_source, can_modify_httponly, - base::Bind(&ResultSavingCookieCallback<bool>::Run, - base::Unretained(&callback))); + base::BindOnce(&ResultSavingCookieCallback< + CanonicalCookie::CookieInclusionStatus>::Run, + base::Unretained(&callback))); callback.WaitUntilDone(); - return callback.result(); + return callback.result() == CanonicalCookie::CookieInclusionStatus::INCLUDE; } bool SetCookieWithServerTime(CookieStore* cs, @@ -243,6 +244,41 @@ return SetCookieWithOptions(cs, url, cookie_line, options); } + CanonicalCookie::CookieInclusionStatus SetCookieReturnStatus( + CookieStore* cs, + const GURL& url, + const std::string& cookie_line) { + CookieOptions options; + if (!CookieStoreTestTraits::supports_http_only) + options.set_include_httponly(); + + DCHECK(cs); + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> callback; + cs->SetCookieWithOptionsAsync( + url, cookie_line, options, + base::BindOnce(&ResultSavingCookieCallback< + CanonicalCookie::CookieInclusionStatus>::Run, + base::Unretained(&callback))); + callback.WaitUntilDone(); + return callback.result(); + } + + CanonicalCookie::CookieInclusionStatus SetCanonicalCookieReturnStatus( + CookieStore* cs, + std::unique_ptr<CanonicalCookie> cookie, + bool secure_source, + bool can_modify_httponly) { + DCHECK(cs); + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> callback; + cs->SetCanonicalCookieAsync( + std::move(cookie), secure_source, can_modify_httponly, + base::BindOnce(&ResultSavingCookieCallback< + CanonicalCookie::CookieInclusionStatus>::Run, + base::Unretained(&callback))); + callback.WaitUntilDone(); + return callback.result(); + } + uint32_t DeleteCanonicalCookie(CookieStore* cs, const CanonicalCookie& cookie) { DCHECK(cs); @@ -528,13 +564,14 @@ false /* secure_source */, true)); // A secure source is required for creating secure cookies. - EXPECT_FALSE(this->SetCanonicalCookie( - cs, - std::make_unique<CanonicalCookie>( - "E", "F", http_foo_host, "/", base::Time(), base::Time(), - base::Time(), true, false, CookieSameSite::DEFAULT_MODE, - COOKIE_PRIORITY_DEFAULT), - false /* secure_source */, true)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_SECURE_ONLY, + this->SetCanonicalCookieReturnStatus( + cs, + std::make_unique<CanonicalCookie>( + "E", "F", http_foo_host, "/", base::Time(), base::Time(), + base::Time(), true, false, CookieSameSite::DEFAULT_MODE, + COOKIE_PRIORITY_DEFAULT), + false /* secure_source */, true)); // A secure source is also required for overwriting secure cookies. Writing // a secure cookie then overwriting it from a non-secure source should fail. @@ -546,24 +583,27 @@ CookieSameSite::DEFAULT_MODE, COOKIE_PRIORITY_DEFAULT), true /* secure_source */, true /* modify_http_only */)); - EXPECT_FALSE(this->SetCanonicalCookie( - cs, - std::make_unique<CanonicalCookie>( - "E", "F", http_foo_host, "/", base::Time(), base::Time(), - base::Time(), true /* secure */, false /* httponly */, - CookieSameSite::DEFAULT_MODE, COOKIE_PRIORITY_DEFAULT), - false /* secure_source */, true /* modify_http_only */)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_SECURE_ONLY, + this->SetCanonicalCookieReturnStatus( + cs, + std::make_unique<CanonicalCookie>( + "E", "F", http_foo_host, "/", base::Time(), base::Time(), + base::Time(), true /* secure */, false /* httponly */, + CookieSameSite::DEFAULT_MODE, COOKIE_PRIORITY_DEFAULT), + false /* secure_source */, true /* modify_http_only */)); if (TypeParam::supports_http_only) { // Permission to modify http only cookies is required to create an // httponly cookie. - EXPECT_FALSE(this->SetCanonicalCookie( - cs, - std::make_unique<CanonicalCookie>( - "G", "H", http_foo_host, "/unique", base::Time(), base::Time(), - base::Time(), false /* secure */, true /* httponly */, - CookieSameSite::DEFAULT_MODE, COOKIE_PRIORITY_DEFAULT), - false /* secure_source */, false /* modify_http_only */)); + EXPECT_EQ( + CanonicalCookie::CookieInclusionStatus::EXCLUDE_HTTP_ONLY, + this->SetCanonicalCookieReturnStatus( + cs, + std::make_unique<CanonicalCookie>( + "G", "H", http_foo_host, "/unique", base::Time(), base::Time(), + base::Time(), false /* secure */, true /* httponly */, + CookieSameSite::DEFAULT_MODE, COOKIE_PRIORITY_DEFAULT), + false /* secure_source */, false /* modify_http_only */)); // Permission to modify httponly cookies is also required to overwrite // an httponly cookie. @@ -575,13 +615,15 @@ CookieSameSite::DEFAULT_MODE, COOKIE_PRIORITY_DEFAULT), false /* secure_source */, true /* modify_http_only */)); - EXPECT_FALSE(this->SetCanonicalCookie( - cs, - std::make_unique<CanonicalCookie>( - "G", "H", http_foo_host, "/unique", base::Time(), base::Time(), - base::Time(), false /* secure */, true /* httponly */, - CookieSameSite::DEFAULT_MODE, COOKIE_PRIORITY_DEFAULT), - false /* secure_source */, false /* modify_http_only */)); + EXPECT_EQ( + CanonicalCookie::CookieInclusionStatus::EXCLUDE_HTTP_ONLY, + this->SetCanonicalCookieReturnStatus( + cs, + std::make_unique<CanonicalCookie>( + "G", "H", http_foo_host, "/unique", base::Time(), base::Time(), + base::Time(), false /* secure */, true /* httponly */, + CookieSameSite::DEFAULT_MODE, COOKIE_PRIORITY_DEFAULT), + false /* secure_source */, false /* modify_http_only */)); } else { // Leave store in same state as if the above tests had been run. EXPECT_TRUE(this->SetCanonicalCookie(
diff --git a/net/dns/address_sorter_posix.cc b/net/dns/address_sorter_posix.cc index ff9059f..b768391 100644 --- a/net/dns/address_sorter_posix.cc +++ b/net/dns/address_sorter_posix.cc
@@ -192,7 +192,7 @@ unsigned precedence; unsigned label; const AddressSorterPosix::SourceAddressInfo* src; - unsigned common_prefix_length; + size_t common_prefix_length; }; // Returns true iff |dst_a| should precede |dst_b| in the address list.
diff --git a/net/dns/address_sorter_posix.h b/net/dns/address_sorter_posix.h index 48ec585..81420f3 100644 --- a/net/dns/address_sorter_posix.h +++ b/net/dns/address_sorter_posix.h
@@ -51,7 +51,7 @@ unsigned label; // Values from the OS, matter only if more than one source address is used. - unsigned prefix_length; + size_t prefix_length; bool deprecated; // vs. preferred RFC4862 bool home; // vs. care-of RFC6275 bool native;
diff --git a/net/dns/address_sorter_win.cc b/net/dns/address_sorter_win.cc index 53dcb035..a64f361 100644 --- a/net/dns/address_sorter_win.cc +++ b/net/dns/address_sorter_win.cc
@@ -56,15 +56,16 @@ Job(const AddressList& list, CallbackType callback) : callback_(std::move(callback)), - buffer_size_(sizeof(SOCKET_ADDRESS_LIST) + - list.size() * - (sizeof(SOCKET_ADDRESS) + sizeof(SOCKADDR_STORAGE))), + buffer_size_((sizeof(SOCKET_ADDRESS_LIST) + + base::CheckedNumeric<DWORD>(list.size()) * + (sizeof(SOCKET_ADDRESS) + sizeof(SOCKADDR_STORAGE))) + .ValueOrDie<DWORD>()), input_buffer_( reinterpret_cast<SOCKET_ADDRESS_LIST*>(malloc(buffer_size_))), output_buffer_( reinterpret_cast<SOCKET_ADDRESS_LIST*>(malloc(buffer_size_))), success_(false) { - input_buffer_->iAddressCount = list.size(); + input_buffer_->iAddressCount = base::checked_cast<INT>(list.size()); SOCKADDR_STORAGE* storage = reinterpret_cast<SOCKADDR_STORAGE*>( input_buffer_->Address + input_buffer_->iAddressCount); @@ -128,7 +129,7 @@ } CallbackType callback_; - const size_t buffer_size_; + const DWORD buffer_size_; std::unique_ptr<SOCKET_ADDRESS_LIST, base::FreeDeleter> input_buffer_; std::unique_ptr<SOCKET_ADDRESS_LIST, base::FreeDeleter> output_buffer_; bool success_;
diff --git a/net/dns/dns_transaction_unittest.cc b/net/dns/dns_transaction_unittest.cc index fcd1eeec..48d7e148d 100644 --- a/net/dns/dns_transaction_unittest.cc +++ b/net/dns/dns_transaction_unittest.cc
@@ -1793,8 +1793,8 @@ CookieCallback() : result_(false), loop_to_quit_(std::make_unique<base::RunLoop>()) {} - void SetCookieCallback(bool result) { - result_ = result; + void SetCookieCallback(CanonicalCookie::CookieInclusionStatus result) { + result_ = (result == CanonicalCookie::CookieInclusionStatus::INCLUDE); loop_to_quit_->Quit(); }
diff --git a/net/dns/host_resolver.h b/net/dns/host_resolver.h index e8e3f8c..d1001e4 100644 --- a/net/dns/host_resolver.h +++ b/net/dns/host_resolver.h
@@ -330,30 +330,8 @@ const NetLogWithSource& net_log, const base::Optional<ResolveHostParameters>& optional_parameters) = 0; - // DEPRECATION NOTE: This method is being replaced by CreateRequest(). New - // callers should prefer CreateRequest() if it works for their needs. - // - // Resolves the given hostname (or IP address literal), filling out the - // |addresses| object upon success. The |info.port| parameter will be set as - // the sin(6)_port field of the sockaddr_in{6} struct. Returns OK if - // successful or an error code upon failure. Returns - // ERR_NAME_NOT_RESOLVED if hostname is invalid, or if it is an - // incompatible IP literal (e.g. IPv6 is disabled and it is an IPv6 - // literal). - // - // If the operation cannot be completed synchronously, ERR_IO_PENDING will - // be returned and the real result code will be passed to the completion - // callback. Otherwise the result code is returned immediately from this - // call. - // - // [out_req] must be owned by a caller. If the request is not completed - // synchronously, it will be filled with a handle to the request. It must be - // completed before the HostResolver itself is destroyed. - // - // Requests can be cancelled any time by deletion of the [out_req]. Deleting - // |out_req| will cancel the request, and cause |callback| not to be invoked. - // - // Profiling information for the request is saved to |net_log| if non-NULL. + // DO NOT USE. This is a no-longer-tested legacy method that will soon be + // deleted. // // TODO(crbug.com/922699): Delete this method once all usage has been // converted to CreateRequest(). @@ -364,16 +342,8 @@ std::unique_ptr<Request>* out_req, const NetLogWithSource& net_log) = 0; - // DEPRECATION NOTE: This method is being replaced by CreateRequest(). New - // callers should prefer CreateRequest() if it works for their needs. Calling - // CreateRequest() with - // |parameters.source = HostResolverSource::LOCAL_ONLY| should provide - // capabilities equivalent to ResolveFromCache(). - // - // Resolves the given hostname (or IP address literal) out of cache or HOSTS - // file (if enabled) only. This is guaranteed to complete synchronously. - // This acts like |Resolve()| if the hostname is IP literal, or cached value - // or HOSTS entry exists. Otherwise, ERR_DNS_CACHE_MISS is returned. + // DO NOT USE. This is a no-longer-tested legacy method that will soon be + // deleted. // // TODO(crbug.com/922699): Delete this method once all usage has been // converted to CreateRequest(). @@ -381,16 +351,8 @@ AddressList* addresses, const NetLogWithSource& net_log) = 0; - // DEPRECATION NOTE: This method is being replaced by CreateRequest(). New - // callers should prefer CreateRequest() if it works for their needs. Calling - // CreateRequest() with - // |parameters.source = HostResolverSource::LOCAL_ONLY| and - // |parameters.cache_usage = ResolveHostParameters::CacheUsage::STALE_ALLOWED| - // should provide capabilities equivalent to ResolveStaleFromCache() - // - // Like |ResolveFromCache()|, but can return a stale result if the - // implementation supports it. Fills in |*stale_info| if a response is - // returned to indicate how stale (or not) it is. + // DO NOT USE. This is a no-longer-tested legacy method that will soon be + // deleted. // // TODO(crbug.com/922699): Delete this method once all usage has been // converted to CreateRequest().
diff --git a/net/dns/host_resolver_impl_unittest.cc b/net/dns/host_resolver_impl_unittest.cc index ef5fe194..5c98ef9 100644 --- a/net/dns/host_resolver_impl_unittest.cc +++ b/net/dns/host_resolver_impl_unittest.cc
@@ -238,15 +238,6 @@ DISALLOW_COPY_AND_ASSIGN(MockHostResolverProc); }; -bool AddressListContains(const AddressList& list, - const std::string& address, - uint16_t port) { - IPAddress ip; - bool rv = ip.AssignFromIPLiteral(address); - DCHECK(rv); - return base::ContainsValue(list, IPEndPoint(ip, port)); -} - class ResolveHostResponseHelper { public: using Callback = @@ -309,135 +300,6 @@ DISALLOW_COPY_AND_ASSIGN(ResolveHostResponseHelper); }; -// A wrapper for requests to a HostResolver. -class Request { - public: - // Base class of handlers to be executed on completion of requests. - struct Handler { - virtual ~Handler() = default; - virtual void Handle(Request* request) = 0; - }; - - Request(const HostResolver::RequestInfo& info, - RequestPriority priority, - size_t index, - HostResolverImpl* resolver, - Handler* handler) - : info_(info), - priority_(priority), - index_(index), - resolver_(resolver), - handler_(handler), - result_(ERR_UNEXPECTED) {} - - int Resolve() { - DCHECK(resolver_); - DCHECK(!request_); - list_ = AddressList(); - result_ = resolver_->Resolve( - info_, priority_, &list_, - base::Bind(&Request::OnComplete, base::Unretained(this)), &request_, - NetLogWithSource()); - if (!list_.empty()) - EXPECT_THAT(result_, IsOk()); - return result_; - } - - int ResolveFromCache() { - DCHECK(resolver_); - DCHECK(!request_); - return resolver_->ResolveFromCache(info_, &list_, NetLogWithSource()); - } - - int ResolveStaleFromCache() { - DCHECK(resolver_); - DCHECK(!request_); - return resolver_->ResolveStaleFromCache(info_, &list_, &staleness_, - NetLogWithSource()); - } - - void ChangePriority(RequestPriority priority) { - DCHECK(resolver_); - DCHECK(request_); - request_->ChangeRequestPriority(priority); - priority_ = priority; - } - - void Cancel() { - DCHECK(resolver_); - DCHECK(request_); - request_.reset(); - } - - const HostResolver::RequestInfo& info() const { return info_; } - size_t index() const { return index_; } - const AddressList& list() const { return list_; } - int result() const { return result_; } - const HostCache::EntryStaleness staleness() const { return staleness_; } - bool completed() const { return result_ != ERR_IO_PENDING; } - bool pending() const { return request_ != nullptr; } - - bool HasAddress(const std::string& address, uint16_t port) const { - return AddressListContains(list_, address, port); - } - - // Returns the number of addresses in |list_|. - unsigned NumberOfAddresses() const { - return list_.size(); - } - - bool HasOneAddress(const std::string& address, uint16_t port) const { - return HasAddress(address, port) && (NumberOfAddresses() == 1u); - } - - // Returns ERR_UNEXPECTED if timed out. - int WaitForResult() { - if (completed()) - return result_; - base::RunLoop run_loop; - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, run_loop.QuitClosure(), TestTimeouts::action_max_timeout()); - base::AutoReset<base::OnceClosure> reset(&quit_closure_, - run_loop.QuitClosure()); - run_loop.Run(); - if (!quit_closure_) - return result_; - else - return ERR_UNEXPECTED; - } - - private: - void OnComplete(int rv) { - EXPECT_TRUE(pending()); - EXPECT_THAT(result_, IsError(ERR_IO_PENDING)); - EXPECT_NE(ERR_IO_PENDING, rv); - result_ = rv; - request_.reset(); - if (!list_.empty()) { - EXPECT_THAT(result_, IsOk()); - EXPECT_EQ(info_.port(), list_.front().port()); - } - if (handler_) - handler_->Handle(this); - if (quit_closure_) - std::move(quit_closure_).Run(); - } - - HostResolver::RequestInfo info_; - RequestPriority priority_; - size_t index_; - HostResolverImpl* resolver_; - Handler* handler_; - base::OnceClosure quit_closure_; - - AddressList list_; - int result_; - std::unique_ptr<HostResolver::Request> request_; - HostCache::EntryStaleness staleness_; - - DISALLOW_COPY_AND_ASSIGN(Request); -}; - // Using LookupAttemptHostResolverProc simulate very long lookups, and control // which attempt resolves the host. class LookupAttemptHostResolverProc : public HostResolverProc { @@ -601,11 +463,6 @@ EXPECT_TRUE(HasAddress(IPAddress::IPv6Localhost(), addresses)); } -// Used to bind the unique_ptr<Request>* into callbacks. -struct RequestHolder { - std::unique_ptr<HostResolver::Request> request; -}; - } // namespace class HostResolverImplTest : public TestWithScopedTaskEnvironment { @@ -628,30 +485,6 @@ } protected: - // A Request::Handler which is a proxy to the HostResolverImplTest fixture. - struct Handler : public Request::Handler { - ~Handler() override = default; - - // Proxy functions so that classes derived from Handler can access them. - Request* CreateRequest(const HostResolver::RequestInfo& info, - RequestPriority priority) { - return test->CreateRequest(info, priority); - } - Request* CreateRequest(const std::string& hostname, int port) { - return test->CreateRequest(hostname, port); - } - Request* CreateRequest(const std::string& hostname) { - return test->CreateRequest(hostname); - } - std::vector<std::unique_ptr<Request>>& requests() { - return test->requests_; - } - - void DeleteResolver() { test->resolver_.reset(); } - - HostResolverImplTest* test; - }; - // testing::Test implementation: void SetUp() override { CreateResolver(); } @@ -671,43 +504,6 @@ resolver_->set_proc_params_for_test(params); } - // The Request will not be made until a call to |Resolve()|, and the Job will - // not start until released by |proc_->SignalXXX|. - Request* CreateRequest(const HostResolver::RequestInfo& info, - RequestPriority priority) { - requests_.push_back(std::make_unique<Request>( - info, priority, requests_.size(), resolver_.get(), handler_.get())); - return requests_.back().get(); - } - - Request* CreateRequest(const std::string& hostname, - int port, - RequestPriority priority, - AddressFamily family) { - HostResolver::RequestInfo info(HostPortPair(hostname, port)); - info.set_address_family(family); - return CreateRequest(info, priority); - } - - Request* CreateRequest(const std::string& hostname, - int port, - RequestPriority priority) { - return CreateRequest(hostname, port, priority, ADDRESS_FAMILY_UNSPECIFIED); - } - - Request* CreateRequest(const std::string& hostname, int port) { - return CreateRequest(hostname, port, MEDIUM); - } - - Request* CreateRequest(const std::string& hostname) { - return CreateRequest(hostname, kDefaultPort); - } - - void set_handler(Handler* handler) { - handler_.reset(handler); - handler_->test = this; - } - // Friendship is not inherited, so use proxies to access those. size_t num_running_dispatcher_jobs() const { DCHECK(resolver_.get()); @@ -727,12 +523,8 @@ return resolver_->IsIPv6Reachable(net_log); } - const HostCache::Entry* GetCacheEntry(const Request& req) { + const HostCache::Entry* GetCacheEntry(const HostCache::Key& key) { DCHECK(resolver_.get() && resolver_->GetHostCache()); - const HostCache::Key key( - req.info().hostname(), - AddressFamilyToDnsQueryType(req.info().address_family()), - req.info().host_resolver_flags(), HostResolverSource::ANY); return resolver_->GetHostCache()->LookupStale(key, base::TimeTicks(), nullptr); } @@ -751,27 +543,12 @@ scoped_refptr<MockHostResolverProc> proc_; std::unique_ptr<HostResolverImpl> resolver_; - std::vector<std::unique_ptr<Request>> requests_; - - std::unique_ptr<Handler> handler_; }; TEST_F(HostResolverImplTest, AsynchronousLookup) { proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42"); proc_->SignalMultiple(1u); - Request* req = CreateRequest("just.testing", 80); - EXPECT_THAT(req->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(req->WaitForResult(), IsOk()); - - EXPECT_TRUE(req->HasOneAddress("192.168.1.42", 80)); - EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname); -} - -TEST_F(HostResolverImplTest, AsynchronousLookup_ResolveHost) { - proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42"); - proc_->SignalMultiple(1u); - ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair("just.testing", 80), NetLogWithSource(), base::nullopt)); @@ -781,6 +558,11 @@ EXPECT_FALSE(response.request()->GetStaleInfo()); EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname); + + const HostCache::Entry* cache_entry = GetCacheEntry( + HostCache::Key("just.testing", DnsQueryType::UNSPECIFIED, + 0 /* host_resolver_flags */, HostResolverSource::ANY)); + EXPECT_TRUE(cache_entry); } TEST_F(HostResolverImplTest, DnsQueryType) { @@ -809,29 +591,6 @@ } TEST_F(HostResolverImplTest, LocalhostIPV4IPV6Lookup) { - Request* req1 = CreateRequest("localhost6", 80, MEDIUM, ADDRESS_FAMILY_IPV4); - EXPECT_THAT(req1->Resolve(), IsOk()); - EXPECT_EQ(0u, req1->NumberOfAddresses()); - - Request* req2 = CreateRequest("localhost6", 80, MEDIUM, ADDRESS_FAMILY_IPV6); - EXPECT_THAT(req2->Resolve(), IsOk()); - EXPECT_TRUE(req2->HasOneAddress("::1", 80)); - - Request* req3 = - CreateRequest("localhost6", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED); - EXPECT_THAT(req3->Resolve(), IsOk()); - EXPECT_TRUE(req3->HasOneAddress("::1", 80)); - - Request* req4 = CreateRequest("localhost", 80, MEDIUM, ADDRESS_FAMILY_IPV4); - EXPECT_THAT(req4->Resolve(), IsOk()); - EXPECT_TRUE(req4->HasOneAddress("127.0.0.1", 80)); - - Request* req5 = CreateRequest("localhost", 80, MEDIUM, ADDRESS_FAMILY_IPV6); - EXPECT_THAT(req5->Resolve(), IsOk()); - EXPECT_TRUE(req5->HasOneAddress("::1", 80)); -} - -TEST_F(HostResolverImplTest, LocalhostIPV4IPV6Lookup_ResolveHost) { HostResolver::ResolveHostParameters parameters; parameters.dns_query_type = DnsQueryType::A; @@ -885,23 +644,6 @@ // literal). proc_->AddRuleForAllFamilies(kIpLiteral, "183.45.32.1"); - HostResolver::RequestInfo info_bypass(HostPortPair(kIpLiteral, 80)); - info_bypass.set_host_resolver_flags(HOST_RESOLVER_SYSTEM_ONLY); - - Request* req = CreateRequest(info_bypass, MEDIUM); - EXPECT_THAT(req->Resolve(), IsOk()); - - EXPECT_TRUE(req->HasAddress(kIpLiteral, 80)); -} - -TEST_F(HostResolverImplTest, - ResolveIPLiteralWithHostResolverSystemOnly_ResolveHost) { - const char kIpLiteral[] = "178.78.32.1"; - // Add a mapping to tell if the resolver proc was called (if it was called, - // then the result will be the remapped value. Otherwise it will be the IP - // literal). - proc_->AddRuleForAllFamilies(kIpLiteral, "183.45.32.1"); - HostResolver::ResolveHostParameters parameters; parameters.source = HostResolverSource::SYSTEM; ResolveHostResponseHelper response(resolver_->CreateRequest( @@ -919,17 +661,6 @@ proc_->AddRuleForAllFamilies("just.testing", ""); proc_->SignalMultiple(1u); - Request* req = CreateRequest("just.testing", 80); - EXPECT_THAT(req->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(req->WaitForResult(), IsError(ERR_NAME_NOT_RESOLVED)); - EXPECT_EQ(0u, req->NumberOfAddresses()); - EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname); -} - -TEST_F(HostResolverImplTest, EmptyListMeansNameNotResolved_ResolveHost) { - proc_->AddRuleForAllFamilies("just.testing", ""); - proc_->SignalMultiple(1u); - ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair("just.testing", 80), NetLogWithSource(), base::nullopt)); @@ -945,21 +676,6 @@ "0.0.0.0"); // Default to failures. proc_->SignalMultiple(1u); - Request* req = CreateRequest("just.testing", 80); - EXPECT_THAT(req->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(req->WaitForResult(), IsError(ERR_NAME_NOT_RESOLVED)); - - EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname); - - // Also test that the error is not cached. - EXPECT_THAT(req->ResolveFromCache(), IsError(ERR_DNS_CACHE_MISS)); -} - -TEST_F(HostResolverImplTest, FailedAsynchronousLookup_ResolveHost) { - proc_->AddRuleForAllFamilies(std::string(), - "0.0.0.0"); // Default to failures. - proc_->SignalMultiple(1u); - ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair("just.testing", 80), NetLogWithSource(), base::nullopt)); EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED)); @@ -969,35 +685,13 @@ EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname); // Also test that the error is not cached. - Request* req = CreateRequest("just.testing", 80); - EXPECT_THAT(req->ResolveFromCache(), IsError(ERR_DNS_CACHE_MISS)); + const HostCache::Entry* cache_entry = GetCacheEntry( + HostCache::Key("just.testing", DnsQueryType::UNSPECIFIED, + 0 /* host_resolver_flags */, HostResolverSource::ANY)); + EXPECT_FALSE(cache_entry); } TEST_F(HostResolverImplTest, AbortedAsynchronousLookup) { - Request* req0 = CreateRequest("just.testing", 80); - EXPECT_THAT(req0->Resolve(), IsError(ERR_IO_PENDING)); - - EXPECT_TRUE(proc_->WaitFor(1u)); - - // Resolver is destroyed while job is running on WorkerPool. - resolver_.reset(); - - proc_->SignalAll(); - - // To ensure there was no spurious callback, complete with a new resolver. - CreateResolver(); - Request* req1 = CreateRequest("just.testing", 80); - EXPECT_THAT(req1->Resolve(), IsError(ERR_IO_PENDING)); - - proc_->SignalMultiple(2u); - - EXPECT_THAT(req1->WaitForResult(), IsOk()); - - // This request was canceled. - EXPECT_FALSE(req0->completed()); -} - -TEST_F(HostResolverImplTest, AbortedAsynchronousLookup_ResolveHost) { ResolveHostResponseHelper response0(resolver_->CreateRequest( HostPortPair("just.testing", 80), NetLogWithSource(), base::nullopt)); ASSERT_FALSE(response0.complete()); @@ -1022,14 +716,6 @@ } TEST_F(HostResolverImplTest, NumericIPv4Address) { - // Stevens says dotted quads with AI_UNSPEC resolve to a single sockaddr_in. - Request* req = CreateRequest("127.1.2.3", 5555); - EXPECT_THAT(req->Resolve(), IsOk()); - - EXPECT_TRUE(req->HasOneAddress("127.1.2.3", 5555)); -} - -TEST_F(HostResolverImplTest, NumericIPv4Address_ResolveHost) { ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair("127.1.2.3", 5555), NetLogWithSource(), base::nullopt)); @@ -1041,15 +727,6 @@ TEST_F(HostResolverImplTest, NumericIPv6Address) { // Resolve a plain IPv6 address. Don't worry about [brackets], because // the caller should have removed them. - Request* req = CreateRequest("2001:db8::1", 5555); - EXPECT_THAT(req->Resolve(), IsOk()); - - EXPECT_TRUE(req->HasOneAddress("2001:db8::1", 5555)); -} - -TEST_F(HostResolverImplTest, NumericIPv6Address_ResolveHost) { - // Resolve a plain IPv6 address. Don't worry about [brackets], because - // the caller should have removed them. ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair("2001:db8::1", 5555), NetLogWithSource(), base::nullopt)); @@ -1059,11 +736,6 @@ } TEST_F(HostResolverImplTest, EmptyHost) { - Request* req = CreateRequest(std::string(), 5555); - EXPECT_THAT(req->Resolve(), IsError(ERR_NAME_NOT_RESOLVED)); -} - -TEST_F(HostResolverImplTest, EmptyHost_ResolveHost) { ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair(std::string(), 5555), NetLogWithSource(), base::nullopt)); @@ -1073,13 +745,6 @@ TEST_F(HostResolverImplTest, EmptyDotsHost) { for (int i = 0; i < 16; ++i) { - Request* req = CreateRequest(std::string(i, '.'), 5555); - EXPECT_THAT(req->Resolve(), IsError(ERR_NAME_NOT_RESOLVED)); - } -} - -TEST_F(HostResolverImplTest, EmptyDotsHost_ResolveHost) { - for (int i = 0; i < 16; ++i) { ResolveHostResponseHelper response( resolver_->CreateRequest(HostPortPair(std::string(i, '.'), 5555), NetLogWithSource(), base::nullopt)); @@ -1090,11 +755,6 @@ } TEST_F(HostResolverImplTest, LongHost) { - Request* req = CreateRequest(std::string(4097, 'a'), 5555); - EXPECT_THAT(req->Resolve(), IsError(ERR_NAME_NOT_RESOLVED)); -} - -TEST_F(HostResolverImplTest, LongHost_ResolveHost) { ResolveHostResponseHelper response( resolver_->CreateRequest(HostPortPair(std::string(4097, 'a'), 5555), NetLogWithSource(), base::nullopt)); @@ -1106,22 +766,6 @@ TEST_F(HostResolverImplTest, DeDupeRequests) { // Start 5 requests, duplicating hosts "a" and "b". Since the resolver_proc is // blocked, these should all pile up until we signal it. - EXPECT_THAT(CreateRequest("a", 80)->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("b", 80)->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("b", 81)->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("a", 82)->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("b", 83)->Resolve(), IsError(ERR_IO_PENDING)); - - proc_->SignalMultiple(2u); // One for "a", one for "b". - - for (size_t i = 0; i < requests_.size(); ++i) { - EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i; - } -} - -TEST_F(HostResolverImplTest, DeDupeRequests_ResolveHost) { - // Start 5 requests, duplicating hosts "a" and "b". Since the resolver_proc is - // blocked, these should all pile up until we signal it. std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses; responses.emplace_back( std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest( @@ -1151,24 +795,6 @@ } TEST_F(HostResolverImplTest, CancelMultipleRequests) { - EXPECT_THAT(CreateRequest("a", 80)->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("b", 80)->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("b", 81)->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("a", 82)->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("b", 83)->Resolve(), IsError(ERR_IO_PENDING)); - - // Cancel everything except request for ("a", 82). - requests_[0]->Cancel(); - requests_[1]->Cancel(); - requests_[2]->Cancel(); - requests_[4]->Cancel(); - - proc_->SignalMultiple(2u); // One for "a", one for "b". - - EXPECT_THAT(requests_[3]->WaitForResult(), IsOk()); -} - -TEST_F(HostResolverImplTest, CancelMultipleRequests_ResolveHost) { std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses; responses.emplace_back( std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest( @@ -1207,33 +833,6 @@ } TEST_F(HostResolverImplTest, CanceledRequestsReleaseJobSlots) { - // Fill up the dispatcher and queue. - for (unsigned i = 0; i < kMaxJobs + 1; ++i) { - std::string hostname = "a_"; - hostname[1] = 'a' + i; - EXPECT_THAT(CreateRequest(hostname, 80)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest(hostname, 81)->Resolve(), - IsError(ERR_IO_PENDING)); - } - - EXPECT_TRUE(proc_->WaitFor(kMaxJobs)); - - // Cancel all but last two. - for (unsigned i = 0; i < requests_.size() - 2; ++i) { - requests_[i]->Cancel(); - } - - EXPECT_TRUE(proc_->WaitFor(kMaxJobs + 1)); - - proc_->SignalAll(); - - size_t num_requests = requests_.size(); - EXPECT_THAT(requests_[num_requests - 1]->WaitForResult(), IsOk()); - EXPECT_THAT(requests_[num_requests - 2]->result(), IsOk()); -} - -TEST_F(HostResolverImplTest, CanceledRequestsReleaseJobSlots_ResolveHost) { std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses; // Fill up the dispatcher and queue. @@ -1272,35 +871,6 @@ } TEST_F(HostResolverImplTest, CancelWithinCallback) { - struct MyHandler : public Handler { - void Handle(Request* req) override { - // Port 80 is the first request that the callback will be invoked for. - // While we are executing within that callback, cancel the other requests - // in the job and start another request. - if (req->index() == 0) { - // Once "a:80" completes, it will cancel "a:81" and "a:82". - requests()[1]->Cancel(); - requests()[2]->Cancel(); - } - } - }; - set_handler(new MyHandler()); - - for (size_t i = 0; i < 4; ++i) { - EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i; - } - - proc_->SignalMultiple(2u); // One for "a". One for "finalrequest". - - EXPECT_THAT(requests_[0]->WaitForResult(), IsOk()); - - Request* final_request = CreateRequest("finalrequest", 70); - EXPECT_THAT(final_request->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(final_request->WaitForResult(), IsOk()); - EXPECT_TRUE(requests_[3]->completed()); -} - -TEST_F(HostResolverImplTest, CancelWithinCallback_ResolveHost) { std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses; auto custom_callback = base::BindLambdaForTesting( [&](CompletionOnceCallback completion_callback, int error) { @@ -1341,32 +911,6 @@ } TEST_F(HostResolverImplTest, DeleteWithinCallback) { - struct MyHandler : public Handler { - void Handle(Request* req) override { - EXPECT_EQ("a", req->info().hostname()); - EXPECT_EQ(80, req->info().port()); - - DeleteResolver(); - - // Quit after returning from OnCompleted (to give it a chance at - // incorrectly running the cancelled tasks). - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); - } - }; - set_handler(new MyHandler()); - - for (size_t i = 0; i < 4; ++i) { - EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i; - } - - proc_->SignalMultiple(1u); // One for "a". - - // |MyHandler| will send quit message once all the requests have finished. - base::RunLoop().Run(); -} - -TEST_F(HostResolverImplTest, DeleteWithinCallback_ResolveHost) { std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses; auto custom_callback = base::BindLambdaForTesting( [&](CompletionOnceCallback completion_callback, int error) { @@ -1407,55 +951,13 @@ } } -TEST_F(HostResolverImplTest, DeleteWithinAbortedCallback) { - struct MyHandler : public Handler { - void Handle(Request* req) override { - EXPECT_EQ("a", req->info().hostname()); - EXPECT_EQ(80, req->info().port()); - - DeleteResolver(); - - // Quit after returning from OnCompleted (to give it a chance at - // incorrectly running the cancelled tasks). - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); - } - }; - set_handler(new MyHandler()); - - // This test assumes that the Jobs will be Aborted in order ["a", "b"] - EXPECT_THAT(CreateRequest("a", 80)->Resolve(), IsError(ERR_IO_PENDING)); - // HostResolverImpl will be deleted before later Requests can complete. - EXPECT_THAT(CreateRequest("a", 81)->Resolve(), IsError(ERR_IO_PENDING)); - // Job for 'b' will be aborted before it can complete. - EXPECT_THAT(CreateRequest("b", 82)->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("b", 83)->Resolve(), IsError(ERR_IO_PENDING)); - - EXPECT_TRUE(proc_->WaitFor(1u)); - - // Triggering an IP address change. - NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests(); - - // |MyHandler| will send quit message once all the requests have finished. - base::RunLoop().Run(); - - EXPECT_THAT(requests_[0]->result(), IsError(ERR_NETWORK_CHANGED)); - EXPECT_THAT(requests_[1]->result(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(requests_[2]->result(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(requests_[3]->result(), IsError(ERR_IO_PENDING)); - // Clean up. - proc_->SignalMultiple(requests_.size()); -} - // Flaky on Fuchsia and Linux ASAN. crbug.com/930483 #if defined(OS_FUCHSIA) || defined(OS_LINUX) -#define MAYBE_DeleteWithinAbortedCallback_ResolveHost \ - DISABLED_DeleteWithinAbortedCallback_ResolveHost +#define MAYBE_DeleteWithinAbortedCallback DISABLED_DeleteWithinAbortedCallback #else -#define MAYBE_DeleteWithinAbortedCallback_ResolveHost \ - DeleteWithinAbortedCallback_ResolveHost +#define MAYBE_DeleteWithinAbortedCallback DeleteWithinAbortedCallback #endif -TEST_F(HostResolverImplTest, MAYBE_DeleteWithinAbortedCallback_ResolveHost) { +TEST_F(HostResolverImplTest, MAYBE_DeleteWithinAbortedCallback) { std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses; ResolveHostResponseHelper::Callback custom_callback = base::BindLambdaForTesting( @@ -1500,37 +1002,6 @@ } TEST_F(HostResolverImplTest, StartWithinCallback) { - struct MyHandler : public Handler { - void Handle(Request* req) override { - if (req->index() == 0) { - // On completing the first request, start another request for "a". - // Since caching is disabled, this will result in another async request. - EXPECT_THAT(CreateRequest("a", 70)->Resolve(), IsError(ERR_IO_PENDING)); - } - } - }; - set_handler(new MyHandler()); - - // Turn off caching for this host resolver. - HostResolver::Options options = DefaultOptions(); - options.enable_caching = false; - resolver_.reset(new TestHostResolverImpl(options, NULL)); - resolver_->set_proc_params_for_test(DefaultParams(proc_.get())); - - for (size_t i = 0; i < 4; ++i) { - EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i; - } - - proc_->SignalMultiple(2u); // One for "a". One for the second "a". - - EXPECT_THAT(requests_[0]->WaitForResult(), IsOk()); - ASSERT_EQ(5u, requests_.size()); - EXPECT_THAT(requests_.back()->WaitForResult(), IsOk()); - - EXPECT_EQ(2u, proc_->GetCaptureList().size()); -} - -TEST_F(HostResolverImplTest, StartWithinCallback_ResolveHost) { std::unique_ptr<ResolveHostResponseHelper> new_response; auto custom_callback = base::BindLambdaForTesting( [&](CompletionOnceCallback completion_callback, int error) { @@ -1552,40 +1023,6 @@ } TEST_F(HostResolverImplTest, BypassCache) { - struct MyHandler : public Handler { - void Handle(Request* req) override { - if (req->index() == 0) { - // On completing the first request, start another request for "a". - // Since caching is enabled, this should complete synchronously. - std::string hostname = req->info().hostname(); - EXPECT_THAT(CreateRequest(hostname, 70)->Resolve(), IsOk()); - EXPECT_THAT(CreateRequest(hostname, 75)->ResolveFromCache(), IsOk()); - - // Ok good. Now make sure that if we ask to bypass the cache, it can no - // longer service the request synchronously. - HostResolver::RequestInfo info(HostPortPair(hostname, 71)); - info.set_allow_cached_response(false); - EXPECT_EQ(ERR_IO_PENDING, - CreateRequest(info, DEFAULT_PRIORITY)->Resolve()); - } else if (71 == req->info().port()) { - // Test is done. - base::RunLoop::QuitCurrentWhenIdleDeprecated(); - } else { - FAIL() << "Unexpected request"; - } - } - }; - set_handler(new MyHandler()); - - EXPECT_THAT(CreateRequest("a", 80)->Resolve(), IsError(ERR_IO_PENDING)); - proc_->SignalMultiple(3u); // Only need two, but be generous. - - // |verifier| will send quit message once all the requests have finished. - base::RunLoop().Run(); - EXPECT_EQ(2u, proc_->GetCaptureList().size()); -} - -TEST_F(HostResolverImplTest, BypassCache_ResolveHost) { proc_->SignalMultiple(2u); ResolveHostResponseHelper initial_response(resolver_->CreateRequest( @@ -1609,37 +1046,9 @@ EXPECT_EQ(2u, proc_->GetCaptureList().size()); } -// Test that IP address changes flush the cache but initial DNS config reads do -// not. -TEST_F(HostResolverImplTest, FlushCacheOnIPAddressChange) { - proc_->SignalMultiple(2u); // One before the flush, one after. - - Request* req = CreateRequest("host1", 70); - EXPECT_THAT(req->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(req->WaitForResult(), IsOk()); - - req = CreateRequest("host1", 75); - EXPECT_THAT(req->Resolve(), IsOk()); // Should complete synchronously. - - // Verify initial DNS config read does not flush cache. - NetworkChangeNotifier::NotifyObserversOfInitialDNSConfigReadForTests(); - req = CreateRequest("host1", 75); - EXPECT_THAT(req->Resolve(), IsOk()); // Should complete synchronously. - - // Flush cache by triggering an IP address change. - NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests(); - base::RunLoop().RunUntilIdle(); // Notification happens async. - - // Resolve "host1" again -- this time it won't be served from cache, so it - // will complete asynchronously. - req = CreateRequest("host1", 80); - EXPECT_THAT(req->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(req->WaitForResult(), IsOk()); -} - // Test that IP address changes flush the cache but initial DNS config reads // do not. -TEST_F(HostResolverImplTest, FlushCacheOnIPAddressChange_ResolveHost) { +TEST_F(HostResolverImplTest, FlushCacheOnIPAddressChange) { proc_->SignalMultiple(2u); // One before the flush, one after. ResolveHostResponseHelper initial_response(resolver_->CreateRequest( @@ -1673,21 +1082,6 @@ // Test that IP address changes send ERR_NETWORK_CHANGED to pending requests. TEST_F(HostResolverImplTest, AbortOnIPAddressChanged) { - Request* req = CreateRequest("host1", 70); - EXPECT_THAT(req->Resolve(), IsError(ERR_IO_PENDING)); - - EXPECT_TRUE(proc_->WaitFor(1u)); - // Triggering an IP address change. - NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests(); - base::RunLoop().RunUntilIdle(); // Notification happens async. - proc_->SignalAll(); - - EXPECT_THAT(req->WaitForResult(), IsError(ERR_NETWORK_CHANGED)); - EXPECT_EQ(0u, resolver_->GetHostCache()->size()); -} - -// Test that IP address changes send ERR_NETWORK_CHANGED to pending requests. -TEST_F(HostResolverImplTest, AbortOnIPAddressChanged_ResolveHost) { ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair("host1", 70), NetLogWithSource(), base::nullopt)); @@ -1706,20 +1100,6 @@ // Test that initial DNS config read signals do not abort pending requests. TEST_F(HostResolverImplTest, DontAbortOnInitialDNSConfigRead) { - Request* req = CreateRequest("host1", 70); - EXPECT_THAT(req->Resolve(), IsError(ERR_IO_PENDING)); - - EXPECT_TRUE(proc_->WaitFor(1u)); - // Triggering initial DNS config read signal. - NetworkChangeNotifier::NotifyObserversOfInitialDNSConfigReadForTests(); - base::RunLoop().RunUntilIdle(); // Notification happens async. - proc_->SignalAll(); - - EXPECT_THAT(req->WaitForResult(), IsOk()); -} - -// Test that initial DNS config read signals do not abort pending requests. -TEST_F(HostResolverImplTest, DontAbortOnInitialDNSConfigRead_ResolveHost) { ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair("host1", 70), NetLogWithSource(), base::nullopt)); @@ -1739,32 +1119,6 @@ TEST_F(HostResolverImplTest, ObeyPoolConstraintsAfterIPAddressChange) { // Runs at most one job at a time. CreateSerialResolver(); - EXPECT_THAT(CreateRequest("a")->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("b")->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("c")->Resolve(), IsError(ERR_IO_PENDING)); - - EXPECT_TRUE(proc_->WaitFor(1u)); - // Triggering an IP address change. - NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests(); - base::RunLoop().RunUntilIdle(); // Notification happens async. - proc_->SignalMultiple(3u); // Let the false-start go so that we can catch it. - - EXPECT_THAT(requests_[0]->WaitForResult(), IsError(ERR_NETWORK_CHANGED)); - - EXPECT_EQ(1u, num_running_dispatcher_jobs()); - - EXPECT_FALSE(requests_[1]->completed()); - EXPECT_FALSE(requests_[2]->completed()); - - EXPECT_THAT(requests_[2]->WaitForResult(), IsOk()); - EXPECT_THAT(requests_[1]->result(), IsOk()); -} - -// Obey pool constraints after IP address has changed. -TEST_F(HostResolverImplTest, - ObeyPoolConstraintsAfterIPAddressChange_ResolveHost) { - // Runs at most one job at a time. - CreateSerialResolver(); std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses; responses.emplace_back( @@ -1803,53 +1157,6 @@ // Tests that a new Request made from the callback of a previously aborted one // will not be aborted. TEST_F(HostResolverImplTest, AbortOnlyExistingRequestsOnIPAddressChange) { - struct MyHandler : public Handler { - void Handle(Request* req) override { - // Start new request for a different hostname to ensure that the order - // of jobs in HostResolverImpl is not stable. - std::string hostname; - if (req->index() == 0) - hostname = "zzz"; - else if (req->index() == 1) - hostname = "aaa"; - else if (req->index() == 2) - hostname = "eee"; - else - return; // A request started from within MyHandler. - EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname)->Resolve()) << hostname; - } - }; - set_handler(new MyHandler()); - - EXPECT_THAT(CreateRequest("bbb")->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("eee")->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("ccc")->Resolve(), IsError(ERR_IO_PENDING)); - - // Wait until all are blocked; - EXPECT_TRUE(proc_->WaitFor(3u)); - // Trigger an IP address change. - NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests(); - // This should abort all running jobs. - base::RunLoop().RunUntilIdle(); - EXPECT_THAT(requests_[0]->result(), IsError(ERR_NETWORK_CHANGED)); - EXPECT_THAT(requests_[1]->result(), IsError(ERR_NETWORK_CHANGED)); - EXPECT_THAT(requests_[2]->result(), IsError(ERR_NETWORK_CHANGED)); - ASSERT_EQ(6u, requests_.size()); - // Unblock all calls to proc. - proc_->SignalMultiple(requests_.size()); - // Run until the re-started requests finish. - EXPECT_THAT(requests_[3]->WaitForResult(), IsOk()); - EXPECT_THAT(requests_[4]->WaitForResult(), IsOk()); - EXPECT_THAT(requests_[5]->WaitForResult(), IsOk()); - // Verify that results of aborted Jobs were not cached. - EXPECT_EQ(6u, proc_->GetCaptureList().size()); - EXPECT_EQ(3u, resolver_->GetHostCache()->size()); -} - -// Tests that a new Request made from the callback of a previously aborted one -// will not be aborted. -TEST_F(HostResolverImplTest, - AbortOnlyExistingRequestsOnIPAddressChange_ResolveHost) { auto custom_callback_template = base::BindLambdaForTesting( [&](const HostPortPair& next_host, std::unique_ptr<ResolveHostResponseHelper>* next_response, @@ -1913,50 +1220,6 @@ TEST_F(HostResolverImplTest, HigherPriorityRequestsStartedFirst) { CreateSerialResolver(); - // Note that at this point the MockHostResolverProc is blocked, so any - // requests we make will not complete. - CreateRequest("req0", 80, LOW); - CreateRequest("req1", 80, MEDIUM); - CreateRequest("req2", 80, MEDIUM); - CreateRequest("req3", 80, LOW); - CreateRequest("req4", 80, HIGHEST); - CreateRequest("req5", 80, LOW); - CreateRequest("req6", 80, LOW); - CreateRequest("req5", 80, HIGHEST); - - for (size_t i = 0; i < requests_.size(); ++i) { - EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i; - } - - // Unblock the resolver thread so the requests can run. - proc_->SignalMultiple(requests_.size()); // More than needed. - - // Wait for all the requests to complete succesfully. - for (size_t i = 0; i < requests_.size(); ++i) { - EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i; - } - - // Since we have restricted to a single concurrent thread in the jobpool, - // the requests should complete in order of priority (with the exception - // of the first request, which gets started right away, since there is - // nothing outstanding). - MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList(); - ASSERT_EQ(7u, capture_list.size()); - - EXPECT_EQ("req0", capture_list[0].hostname); - EXPECT_EQ("req4", capture_list[1].hostname); - EXPECT_EQ("req5", capture_list[2].hostname); - EXPECT_EQ("req1", capture_list[3].hostname); - EXPECT_EQ("req2", capture_list[4].hostname); - EXPECT_EQ("req3", capture_list[5].hostname); - EXPECT_EQ("req6", capture_list[6].hostname); -} - -// Tests that when the maximum threads is set to 1, requests are dequeued -// in order of priority. -TEST_F(HostResolverImplTest, HigherPriorityRequestsStartedFirst_ResolveHost) { - CreateSerialResolver(); - HostResolver::ResolveHostParameters low_priority; low_priority.initial_priority = LOW; HostResolver::ResolveHostParameters medium_priority; @@ -2022,33 +1285,43 @@ } // Test that changing a job's priority affects the dequeueing order. -// TODO(crbug.com/821021): Add ResolveHost test once changing priorities is -// supported. TEST_F(HostResolverImplTest, ChangePriority) { CreateSerialResolver(); - CreateRequest("req0", 80, MEDIUM); - CreateRequest("req1", 80, LOW); - CreateRequest("req2", 80, LOWEST); + HostResolver::ResolveHostParameters lowest_priority; + lowest_priority.initial_priority = LOWEST; + HostResolver::ResolveHostParameters low_priority; + low_priority.initial_priority = LOW; + HostResolver::ResolveHostParameters medium_priority; + medium_priority.initial_priority = MEDIUM; - ASSERT_EQ(3u, requests_.size()); + std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses; + responses.emplace_back( + std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest( + HostPortPair("req0", 80), NetLogWithSource(), medium_priority))); + responses.emplace_back( + std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest( + HostPortPair("req1", 80), NetLogWithSource(), low_priority))); + responses.emplace_back( + std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest( + HostPortPair("req2", 80), NetLogWithSource(), lowest_priority))); // req0 starts immediately; without ChangePriority, req1 and then req2 should // run. - EXPECT_THAT(requests_[0]->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(requests_[1]->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(requests_[2]->Resolve(), IsError(ERR_IO_PENDING)); + for (const auto& response : responses) { + ASSERT_FALSE(response->complete()); + } - // Changing req2 to HIGH should make it run before req1. + // Changing req2 to HIGHEST should make it run before req1. // (It can't run before req0, since req0 started immediately.) - requests_[2]->ChangePriority(HIGHEST); + responses[2]->request()->ChangeRequestPriority(HIGHEST); // Let all 3 requests finish. proc_->SignalMultiple(3u); - EXPECT_THAT(requests_[0]->WaitForResult(), IsOk()); - EXPECT_THAT(requests_[1]->WaitForResult(), IsOk()); - EXPECT_THAT(requests_[2]->WaitForResult(), IsOk()); + for (auto& response : responses) { + EXPECT_THAT(response->result_error(), IsOk()); + } MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList(); ASSERT_EQ(3u, capture_list.size()); @@ -2062,49 +1335,6 @@ TEST_F(HostResolverImplTest, CancelPendingRequest) { CreateSerialResolver(); - CreateRequest("req0", 80, LOWEST); - CreateRequest("req1", 80, HIGHEST); // Will cancel. - CreateRequest("req2", 80, MEDIUM); - CreateRequest("req3", 80, LOW); - CreateRequest("req4", 80, HIGHEST); // Will cancel. - CreateRequest("req5", 80, LOWEST); // Will cancel. - CreateRequest("req6", 80, MEDIUM); - - // Start all of the requests. - for (size_t i = 0; i < requests_.size(); ++i) { - EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i; - } - - // Cancel some requests - requests_[1]->Cancel(); - requests_[4]->Cancel(); - requests_[5]->Cancel(); - - // Unblock the resolver thread so the requests can run. - proc_->SignalMultiple(requests_.size()); // More than needed. - - // Wait for all the requests to complete succesfully. - for (size_t i = 0; i < requests_.size(); ++i) { - if (!requests_[i]->pending()) - continue; // Don't wait for the requests we cancelled. - EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i; - } - - // Verify that they called out the the resolver proc (which runs on the - // resolver thread) in the expected order. - MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList(); - ASSERT_EQ(4u, capture_list.size()); - - EXPECT_EQ("req0", capture_list[0].hostname); - EXPECT_EQ("req2", capture_list[1].hostname); - EXPECT_EQ("req6", capture_list[2].hostname); - EXPECT_EQ("req3", capture_list[3].hostname); -} - -// Try cancelling a job which has not started yet. -TEST_F(HostResolverImplTest, CancelPendingRequest_ResolveHost) { - CreateSerialResolver(); - HostResolver::ResolveHostParameters lowest_priority; lowest_priority.initial_priority = LOWEST; HostResolver::ResolveHostParameters low_priority; @@ -2178,73 +1408,6 @@ const size_t kMaxPendingJobs = 3u; resolver_->SetMaxQueuedJobsForTesting(kMaxPendingJobs); - // Note that at this point the MockHostResolverProc is blocked, so any - // requests we make will not complete. - - EXPECT_THAT(CreateRequest("req0", 80, LOWEST)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("req1", 80, HIGHEST)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("req2", 80, MEDIUM)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("req3", 80, MEDIUM)->Resolve(), - IsError(ERR_IO_PENDING)); - - // At this point, there are 3 enqueued jobs. - // Insertion of subsequent requests will cause evictions - // based on priority. - - EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, - CreateRequest("req4", 80, LOW)->Resolve()); // Evicts itself! - - EXPECT_THAT(CreateRequest("req5", 80, MEDIUM)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(requests_[2]->result(), - IsError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE)); - EXPECT_THAT(CreateRequest("req6", 80, HIGHEST)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(requests_[3]->result(), - IsError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE)); - EXPECT_THAT(CreateRequest("req7", 80, MEDIUM)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(requests_[5]->result(), - IsError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE)); - - // Unblock the resolver thread so the requests can run. - proc_->SignalMultiple(4u); - - // The rest should succeed. - EXPECT_THAT(requests_[7]->WaitForResult(), IsOk()); - EXPECT_THAT(requests_[0]->result(), IsOk()); - EXPECT_THAT(requests_[1]->result(), IsOk()); - EXPECT_THAT(requests_[6]->result(), IsOk()); - - // Verify that they called out the the resolver proc (which runs on the - // resolver thread) in the expected order. - MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList(); - ASSERT_EQ(4u, capture_list.size()); - - EXPECT_EQ("req0", capture_list[0].hostname); - EXPECT_EQ("req1", capture_list[1].hostname); - EXPECT_EQ("req6", capture_list[2].hostname); - EXPECT_EQ("req7", capture_list[3].hostname); - - // Verify that the evicted (incomplete) requests were not cached. - EXPECT_EQ(4u, resolver_->GetHostCache()->size()); - - for (size_t i = 0; i < requests_.size(); ++i) { - EXPECT_TRUE(requests_[i]->completed()) << i; - } -} - -// Test that when too many requests are enqueued, old ones start to be aborted. -TEST_F(HostResolverImplTest, QueueOverflow_ResolveHost) { - CreateSerialResolver(); - - // Allow only 3 queued jobs. - const size_t kMaxPendingJobs = 3u; - resolver_->SetMaxQueuedJobsForTesting(kMaxPendingJobs); - HostResolver::ResolveHostParameters lowest_priority; lowest_priority.initial_priority = LOWEST; HostResolver::ResolveHostParameters low_priority; @@ -2334,7 +1497,7 @@ } // Tests that jobs can self-evict by setting the max queue to 0. -TEST_F(HostResolverImplTest, QueueOverflow_ResolveHost_SelfEvict) { +TEST_F(HostResolverImplTest, QueueOverflow_SelfEvict) { CreateSerialResolver(); resolver_->SetMaxQueuedJobsForTesting(0); @@ -2356,36 +1519,9 @@ EXPECT_TRUE(run_response.request()->GetAddressResults()); } -// Make sure that the address family parameter is respected when raw IPs are -// passed in. -TEST_F(HostResolverImplTest, AddressFamilyWithRawIPs) { - Request* request = - CreateRequest("127.0.0.1", 80, MEDIUM, ADDRESS_FAMILY_IPV4); - EXPECT_THAT(request->Resolve(), IsOk()); - EXPECT_TRUE(request->HasOneAddress("127.0.0.1", 80)); - - request = CreateRequest("127.0.0.1", 80, MEDIUM, ADDRESS_FAMILY_IPV6); - EXPECT_THAT(request->Resolve(), IsError(ERR_NAME_NOT_RESOLVED)); - - request = CreateRequest("127.0.0.1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED); - EXPECT_THAT(request->Resolve(), IsOk()); - EXPECT_TRUE(request->HasOneAddress("127.0.0.1", 80)); - - request = CreateRequest("::1", 80, MEDIUM, ADDRESS_FAMILY_IPV4); - EXPECT_THAT(request->Resolve(), IsError(ERR_NAME_NOT_RESOLVED)); - - request = CreateRequest("::1", 80, MEDIUM, ADDRESS_FAMILY_IPV6); - EXPECT_THAT(request->Resolve(), IsOk()); - EXPECT_TRUE(request->HasOneAddress("::1", 80)); - - request = CreateRequest("::1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED); - EXPECT_THAT(request->Resolve(), IsOk()); - EXPECT_TRUE(request->HasOneAddress("::1", 80)); -} - // Make sure that the dns query type parameter is respected when raw IPs are // passed in. -TEST_F(HostResolverImplTest, AddressFamilyWithRawIPs_ResolveHost) { +TEST_F(HostResolverImplTest, AddressFamilyWithRawIPs) { HostResolver::ResolveHostParameters v4_parameters; v4_parameters.dns_query_type = DnsQueryType::A; @@ -2427,56 +1563,7 @@ testing::ElementsAre(CreateExpected("::1", 80))); } -TEST_F(HostResolverImplTest, ResolveFromCache) { - proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42"); - proc_->SignalMultiple(1u); // Need only one. - - HostResolver::RequestInfo info(HostPortPair("just.testing", 80)); - - // First query will miss the cache. - EXPECT_EQ(ERR_DNS_CACHE_MISS, - CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache()); - - // This time, we fetch normally. - EXPECT_THAT(CreateRequest(info, DEFAULT_PRIORITY)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(requests_[1]->WaitForResult(), IsOk()); - - // Now we should be able to fetch from the cache. - EXPECT_THAT(CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache(), - IsOk()); - EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.1.42", 80)); -} - -TEST_F(HostResolverImplTest, ResolveFromCacheInvalidName) { - proc_->AddRuleForAllFamilies("foo,bar.com", "192.168.1.42"); - - HostResolver::RequestInfo info(HostPortPair("foo,bar.com", 80)); - - // Query should be rejected before it makes it to the cache. - EXPECT_THAT(CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache(), - IsError(ERR_NAME_NOT_RESOLVED)); - - // Query should be rejected without attempting to resolve it. - EXPECT_THAT(CreateRequest(info, DEFAULT_PRIORITY)->Resolve(), - IsError(ERR_NAME_NOT_RESOLVED)); - EXPECT_THAT(requests_[1]->WaitForResult(), IsError(ERR_NAME_NOT_RESOLVED)); -} - -TEST_F(HostResolverImplTest, ResolveFromCacheInvalidNameLocalhost) { - HostResolver::RequestInfo info(HostPortPair("foo,bar.localhost", 80)); - - // Query should be rejected before it makes it to the localhost check. - EXPECT_THAT(CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache(), - IsError(ERR_NAME_NOT_RESOLVED)); - - // Query should be rejected without attempting to resolve it. - EXPECT_THAT(CreateRequest(info, DEFAULT_PRIORITY)->Resolve(), - IsError(ERR_NAME_NOT_RESOLVED)); - EXPECT_THAT(requests_[1]->WaitForResult(), IsError(ERR_NAME_NOT_RESOLVED)); -} - -TEST_F(HostResolverImplTest, SourceNone_FromCache) { +TEST_F(HostResolverImplTest, LocalOnly_FromCache) { proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42"); proc_->SignalMultiple(1u); // Need only one. @@ -2510,7 +1597,7 @@ EXPECT_FALSE(cache_hit_request.request()->GetStaleInfo().value().is_stale()); } -TEST_F(HostResolverImplTest, SourceNone_StaleEntry) { +TEST_F(HostResolverImplTest, LocalOnly_StaleEntry) { proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42"); proc_->SignalMultiple(1u); // Need only one. @@ -2544,7 +1631,7 @@ EXPECT_FALSE(stale_request.request()->GetStaleInfo()); } -TEST_F(HostResolverImplTest, SourceNone_FromIp) { +TEST_F(HostResolverImplTest, LocalOnly_FromIp) { HostResolver::ResolveHostParameters source_none_parameters; source_none_parameters.source = HostResolverSource::LOCAL_ONLY; @@ -2559,7 +1646,7 @@ EXPECT_FALSE(response.request()->GetStaleInfo()); } -TEST_F(HostResolverImplTest, SourceNone_InvalidName) { +TEST_F(HostResolverImplTest, LocalOnly_InvalidName) { proc_->AddRuleForAllFamilies("foo,bar.com", "192.168.1.42"); HostResolver::ResolveHostParameters source_none_parameters; @@ -2576,7 +1663,7 @@ EXPECT_FALSE(response.request()->GetStaleInfo()); } -TEST_F(HostResolverImplTest, SourceNone_InvalidLocalhost) { +TEST_F(HostResolverImplTest, LocalOnly_InvalidLocalhost) { HostResolver::ResolveHostParameters source_none_parameters; source_none_parameters.source = HostResolverSource::LOCAL_ONLY; @@ -2591,87 +1678,6 @@ EXPECT_FALSE(response.request()->GetStaleInfo()); } -TEST_F(HostResolverImplTest, ResolveStaleFromCache) { - proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42"); - proc_->SignalMultiple(1u); // Need only one. - - HostResolver::RequestInfo info(HostPortPair("just.testing", 80)); - - // First query will miss the cache. - EXPECT_EQ(ERR_DNS_CACHE_MISS, - CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache()); - - // This time, we fetch normally. - EXPECT_THAT(CreateRequest(info, DEFAULT_PRIORITY)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(requests_[1]->WaitForResult(), IsOk()); - - // Now we should be able to fetch from the cache. - EXPECT_THAT(CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache(), - IsOk()); - EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.1.42", 80)); - EXPECT_THAT(CreateRequest(info, DEFAULT_PRIORITY)->ResolveStaleFromCache(), - IsOk()); - EXPECT_TRUE(requests_[3]->HasOneAddress("192.168.1.42", 80)); - EXPECT_FALSE(requests_[3]->staleness().is_stale()); - - MakeCacheStale(); - - // Now we should be able to fetch from the cache only if we use - // ResolveStaleFromCache. - EXPECT_EQ(ERR_DNS_CACHE_MISS, - CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache()); - EXPECT_THAT(CreateRequest(info, DEFAULT_PRIORITY)->ResolveStaleFromCache(), - IsOk()); - EXPECT_TRUE(requests_[5]->HasOneAddress("192.168.1.42", 80)); - EXPECT_TRUE(requests_[5]->staleness().is_stale()); -} - -TEST_F(HostResolverImplTest, ResolveStaleFromCacheError) { - proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42"); - proc_->SignalMultiple(1u); // Need only one. - - HostResolver::RequestInfo info(HostPortPair("just.testing", 80)); - - // First query will miss the cache. - EXPECT_EQ(ERR_DNS_CACHE_MISS, - CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache()); - - // This time, we fetch normally. - EXPECT_THAT(CreateRequest(info, DEFAULT_PRIORITY)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(requests_[1]->WaitForResult(), IsOk()); - - // Now we should be able to fetch from the cache. - EXPECT_THAT(CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache(), - IsOk()); - EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.1.42", 80)); - EXPECT_THAT(CreateRequest(info, DEFAULT_PRIORITY)->ResolveStaleFromCache(), - IsOk()); - EXPECT_TRUE(requests_[3]->HasOneAddress("192.168.1.42", 80)); - EXPECT_FALSE(requests_[3]->staleness().is_stale()); - - MakeCacheStale(); - - proc_->AddRuleForAllFamilies("just.testing", ""); - proc_->SignalMultiple(1u); - - // Now make another query, and return an error this time. - EXPECT_THAT(CreateRequest(info, DEFAULT_PRIORITY)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(requests_[4]->WaitForResult(), IsError(ERR_NAME_NOT_RESOLVED)); - - // Now we should be able to fetch from the cache only if we use - // ResolveStaleFromCache, and the result should be the older good result, not - // the error. - EXPECT_EQ(ERR_DNS_CACHE_MISS, - CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache()); - EXPECT_THAT(CreateRequest(info, DEFAULT_PRIORITY)->ResolveStaleFromCache(), - IsOk()); - EXPECT_TRUE(requests_[6]->HasOneAddress("192.168.1.42", 80)); - EXPECT_TRUE(requests_[6]->staleness().is_stale()); -} - TEST_F(HostResolverImplTest, StaleAllowed) { proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42"); proc_->SignalMultiple(1u); // Need only one. @@ -2763,66 +1769,6 @@ base::TimeDelta kSleepFudgeFactor = base::TimeDelta::FromMilliseconds(1); scoped_refptr<LookupAttemptHostResolverProc> resolver_proc( - new LookupAttemptHostResolverProc( - NULL, kAttemptNumberToResolve, kTotalAttempts)); - - HostResolverImpl::ProcTaskParams params = DefaultParams(resolver_proc.get()); - base::TimeDelta unresponsive_delay = params.unresponsive_delay; - int retry_factor = params.retry_factor; - - resolver_.reset(new TestHostResolverImpl(DefaultOptions(), NULL)); - resolver_->set_proc_params_for_test(params); - - // Override the current thread task runner, so we can simulate the passage of - // time and avoid any actual sleeps. - auto test_task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>(); - base::ScopedClosureRunner task_runner_override_scoped_cleanup = - base::ThreadTaskRunnerHandle::OverrideForTesting(test_task_runner); - - // Resolve "host1". - HostResolver::RequestInfo info(HostPortPair("host1", 70)); - Request* req = CreateRequest(info, DEFAULT_PRIORITY); - EXPECT_THAT(req->Resolve(), IsError(ERR_IO_PENDING)); - - resolver_proc->WaitForNAttemptsToBeBlocked(1); - - test_task_runner->FastForwardBy(unresponsive_delay + kSleepFudgeFactor); - resolver_proc->WaitForNAttemptsToBeBlocked(2); - - test_task_runner->FastForwardBy(unresponsive_delay * retry_factor + - kSleepFudgeFactor); - - resolver_proc->WaitForAllAttemptsToFinish(); - test_task_runner->RunUntilIdle(); - - // Resolve returns -4 to indicate that 3rd attempt has resolved the host. - // Since we're using a TestMockTimeTaskRunner, the RunLoop stuff in - // WaitForResult will fail if it actually has to wait, but unless there's an - // error, the result should be immediately ready by this point. - EXPECT_EQ(-4, req->WaitForResult()); - - // We should be done with retries, but make sure none erroneously happen. - test_task_runner->FastForwardUntilNoTasksRemain(); - - EXPECT_EQ(resolver_proc->total_attempts_resolved(), kTotalAttempts); - EXPECT_EQ(resolver_proc->resolved_attempt_number(), kAttemptNumberToResolve); -} - -// Test the retry attempts simulating host resolver proc that takes too long. -TEST_F(HostResolverImplTest, MultipleAttempts_ResolveHost) { - // Total number of attempts would be 3 and we want the 3rd attempt to resolve - // the host. First and second attempt will be forced to wait until they get - // word that a resolution has completed. The 3rd resolution attempt will try - // to get done ASAP, and won't wait. - int kAttemptNumberToResolve = 3; - int kTotalAttempts = 3; - - // Add a little bit of extra fudge to the delay to allow reasonable - // flexibility for time > vs >= etc. We don't need to fail the test if we - // retry at t=6001 instead of t=6000. - base::TimeDelta kSleepFudgeFactor = base::TimeDelta::FromMilliseconds(1); - - scoped_refptr<LookupAttemptHostResolverProc> resolver_proc( new LookupAttemptHostResolverProc(NULL, kAttemptNumberToResolve, kTotalAttempts)); @@ -2883,59 +1829,6 @@ proc_->AddRuleForAllFamilies("not_reserved3", "10.0.53.53"); proc_->SignalMultiple(6u); - Request* request; - - request = CreateRequest("single"); - EXPECT_THAT(request->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(request->WaitForResult(), IsError(ERR_ICANN_NAME_COLLISION)); - - // ERR_ICANN_NAME_COLLISION is cached like any other error, using a - // fixed TTL for failed entries from proc-based resolver. That said, the - // fixed TTL is 0, so it will never be cached. - request = CreateRequest("single"); - EXPECT_THAT(request->ResolveFromCache(), IsError(ERR_DNS_CACHE_MISS)); - - request = CreateRequest("multiple"); - EXPECT_THAT(request->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(request->WaitForResult(), IsError(ERR_ICANN_NAME_COLLISION)); - - // Resolving an IP literal of 127.0.53.53 however is allowed. - EXPECT_THAT(CreateRequest("127.0.53.53")->Resolve(), IsOk()); - - // Moreover the address should not be recognized when embedded in an IPv6 - // address. - request = CreateRequest("ipv6"); - EXPECT_THAT(request->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(request->WaitForResult(), IsOk()); - - // Try some other IPs which are similar, but NOT an exact match on - // 127.0.53.53. - request = CreateRequest("not_reserved1"); - EXPECT_THAT(request->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(request->WaitForResult(), IsOk()); - - request = CreateRequest("not_reserved2"); - EXPECT_THAT(request->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(request->WaitForResult(), IsOk()); - - request = CreateRequest("not_reserved3"); - EXPECT_THAT(request->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(request->WaitForResult(), IsOk()); -} - -// If a host resolves to a list that includes 127.0.53.53, this is treated as -// an error. 127.0.53.53 is a localhost address, however it has been given a -// special significance by ICANN to help surface name collision resulting from -// the new gTLDs. -TEST_F(HostResolverImplTest, NameCollisionIcann_ResolveHost) { - proc_->AddRuleForAllFamilies("single", "127.0.53.53"); - proc_->AddRuleForAllFamilies("multiple", "127.0.0.1,127.0.53.53"); - proc_->AddRuleForAllFamilies("ipv6", "::127.0.53.53"); - proc_->AddRuleForAllFamilies("not_reserved1", "53.53.0.127"); - proc_->AddRuleForAllFamilies("not_reserved2", "127.0.53.54"); - proc_->AddRuleForAllFamilies("not_reserved3", "10.0.53.53"); - proc_->SignalMultiple(6u); - ResolveHostResponseHelper single_response(resolver_->CreateRequest( HostPortPair("single", 80), NetLogWithSource(), base::nullopt)); EXPECT_THAT(single_response.result_error(), @@ -2945,8 +1838,10 @@ // ERR_ICANN_NAME_COLLISION is cached like any other error, using a fixed TTL // for failed entries from proc-based resolver. That said, the fixed TTL is 0, // so it should never be cached. - Request* cache_request = CreateRequest("single"); - EXPECT_THAT(cache_request->ResolveFromCache(), IsError(ERR_DNS_CACHE_MISS)); + const HostCache::Entry* cache_entry = GetCacheEntry( + HostCache::Key("single", DnsQueryType::UNSPECIFIED, + 0 /* host_resolver_flags */, HostResolverSource::ANY)); + EXPECT_FALSE(cache_entry); ResolveHostResponseHelper multiple_response(resolver_->CreateRequest( HostPortPair("multiple", 80), NetLogWithSource(), base::nullopt)); @@ -3012,82 +1907,6 @@ EXPECT_TRUE(cached); } -// Test that it's safe for callers to bind input objects with the input -// callback, eg that we don't destroy the callback before finishing a -// synchronously-handled request. In no way is this an encouraged way to use -// the resolver, but we have callers doing this stuff, and we don't want to -// break them. -TEST_F(HostResolverImplTest, InputObjectsBoundToCallback) { - HostResolver::RequestInfo info(HostPortPair("localhost", 65)); - - auto addresses = std::make_unique<AddressList>(); - AddressList* raw_addresses = addresses.get(); - - auto request = std::make_unique<RequestHolder>(); - std::unique_ptr<HostResolver::Request>* raw_request = &request->request; - - base::RunLoop run_loop; - bool callback_invoked = false; - auto callback = base::BindLambdaForTesting( - [&](std::unique_ptr<AddressList> addresses, - std::unique_ptr<RequestHolder> request_holder, int error) { - callback_invoked = true; - run_loop.Quit(); - }); - - int result = resolver_->Resolve( - info, RequestPriority::DEFAULT_PRIORITY, raw_addresses, - base::BindOnce(callback, std::move(addresses), std::move(request)), - raw_request, NetLogWithSource()); - - // Result should be synchronous and successful. If the callback is destroyed - // early, Resolve() would likely crash on accessing addresses. - EXPECT_THAT(result, IsOk()); - run_loop.RunUntilIdle(); - EXPECT_FALSE(callback_invoked); -} - -// Test that it's safe for callers to bind input objects with the input -// callback. In no way is this an encouraged way to use the resolver, but we -// have callers doing this stuff, and we don't want to break them. -TEST_F(HostResolverImplTest, InputObjectsBoundToCallback_Async) { - HostResolver::RequestInfo info(HostPortPair("just.testing", 65)); - - auto addresses = std::make_unique<AddressList>(); - AddressList* raw_addresses = addresses.get(); - - auto request = std::make_unique<RequestHolder>(); - std::unique_ptr<HostResolver::Request>* raw_request = &request->request; - - base::RunLoop run_loop; - int result_error; - std::unique_ptr<AddressList> result_addresses; - std::unique_ptr<HostResolver::Request> result_request; - auto callback = base::BindLambdaForTesting( - [&](std::unique_ptr<AddressList> addresses, - std::unique_ptr<RequestHolder> request_holder, int error) { - result_addresses = std::move(addresses); - result_request = std::move(request_holder->request); - result_error = error; - run_loop.Quit(); - }); - - proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42"); - proc_->SignalMultiple(1u); - - int result = resolver_->Resolve( - info, RequestPriority::DEFAULT_PRIORITY, raw_addresses, - base::BindOnce(callback, std::move(addresses), std::move(request)), - raw_request, NetLogWithSource()); - ASSERT_THAT(result, IsError(ERR_IO_PENDING)); - run_loop.Run(); - - EXPECT_THAT(result_error, IsOk()); - EXPECT_THAT(result_addresses->endpoints(), - testing::ElementsAre(CreateExpected("192.168.1.42", 65))); - EXPECT_TRUE(result_request); -} - TEST_F(HostResolverImplTest, IncludeCanonicalName) { proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42", HOST_RESOLVER_CANONNAME, "canon.name"); @@ -3128,7 +1947,7 @@ EXPECT_THAT(response_no_flag.result_error(), IsError(ERR_NAME_NOT_RESOLVED)); } -TEST_F(HostResolverImplTest, IsSpeculative_ResolveHost) { +TEST_F(HostResolverImplTest, IsSpeculative) { proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42"); proc_->SignalMultiple(1u); @@ -4139,10 +2958,6 @@ MockDnsClient* dns_client_; }; -// TODO(szym): Test AbortAllInProgressJobs due to DnsConfig change. - -// TODO(cbentzel): Test a mix of requests with different HostResolverFlags. - // RFC 6761 localhost names should always resolve to loopback. TEST_F(HostResolverImplDnsTest, LocalhostLookup) { // Add a rule resolving localhost names to a non-loopback IP and test @@ -4151,30 +2966,6 @@ proc_->AddRuleForAllFamilies("localhost", "192.168.1.42"); proc_->AddRuleForAllFamilies("localhost.", "192.168.1.42"); - Request* req0 = CreateRequest("foo.localhost", 80); - EXPECT_THAT(req0->Resolve(), IsOk()); - EXPECT_TRUE(req0->HasAddress("127.0.0.1", 80)); - EXPECT_TRUE(req0->HasAddress("::1", 80)); - - Request* req1 = CreateRequest("localhost", 80); - EXPECT_THAT(req1->Resolve(), IsOk()); - EXPECT_TRUE(req1->HasAddress("127.0.0.1", 80)); - EXPECT_TRUE(req1->HasAddress("::1", 80)); - - Request* req2 = CreateRequest("localhost.", 80); - EXPECT_THAT(req2->Resolve(), IsOk()); - EXPECT_TRUE(req2->HasAddress("127.0.0.1", 80)); - EXPECT_TRUE(req2->HasAddress("::1", 80)); -} - -// RFC 6761 localhost names should always resolve to loopback. -TEST_F(HostResolverImplDnsTest, LocalhostLookup_ResolveHost) { - // Add a rule resolving localhost names to a non-loopback IP and test - // that they still resolves to loopback. - proc_->AddRuleForAllFamilies("foo.localhost", "192.168.1.42"); - proc_->AddRuleForAllFamilies("localhost", "192.168.1.42"); - proc_->AddRuleForAllFamilies("localhost.", "192.168.1.42"); - ResolveHostResponseHelper response0(resolver_->CreateRequest( HostPortPair("foo.localhost", 80), NetLogWithSource(), base::nullopt)); EXPECT_THAT(response0.result_error(), IsOk()); @@ -4210,32 +3001,6 @@ config.hosts = hosts; ChangeDnsConfig(config); - Request* req1 = CreateRequest("localhost", 80); - EXPECT_THAT(req1->Resolve(), IsOk()); - EXPECT_TRUE(req1->HasAddress("127.0.0.1", 80)); - EXPECT_TRUE(req1->HasAddress("::1", 80)); - EXPECT_FALSE(req1->HasAddress("192.168.1.1", 80)); - - Request* req2 = CreateRequest("foo.localhost", 80); - EXPECT_THAT(req2->Resolve(), IsOk()); - EXPECT_TRUE(req2->HasAddress("127.0.0.1", 80)); - EXPECT_TRUE(req2->HasAddress("::1", 80)); - EXPECT_FALSE(req2->HasAddress("192.168.1.2", 80)); -} - -// RFC 6761 localhost names should always resolve to loopback, even if a HOSTS -// file is active. -TEST_F(HostResolverImplDnsTest, LocalhostLookupWithHosts_ResolveHost) { - DnsHosts hosts; - hosts[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV4)] = - IPAddress({192, 168, 1, 1}); - hosts[DnsHostsKey("foo.localhost", ADDRESS_FAMILY_IPV4)] = - IPAddress({192, 168, 1, 2}); - - DnsConfig config = CreateValidDnsConfig(); - config.hosts = hosts; - ChangeDnsConfig(config); - ResolveHostResponseHelper response0(resolver_->CreateRequest( HostPortPair("localhost", 80), NetLogWithSource(), base::nullopt)); EXPECT_THAT(response0.result_error(), IsOk()); @@ -4257,54 +3022,6 @@ // All other hostnames will fail in proc_. // Initially there is no config, so client should not be invoked. - EXPECT_THAT(CreateRequest("ok_fail", 80)->Resolve(), IsError(ERR_IO_PENDING)); - proc_->SignalMultiple(requests_.size()); - - EXPECT_THAT(requests_[0]->WaitForResult(), IsError(ERR_NAME_NOT_RESOLVED)); - - ChangeDnsConfig(CreateValidDnsConfig()); - - EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80, MEDIUM, - ADDRESS_FAMILY_IPV4)->Resolve()); - EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_fail", 80, MEDIUM, - ADDRESS_FAMILY_IPV4)->Resolve()); - EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_succeed", 80, MEDIUM, - ADDRESS_FAMILY_IPV4)->Resolve()); - - proc_->SignalMultiple(requests_.size()); - - for (size_t i = 1; i < requests_.size(); ++i) - EXPECT_NE(ERR_UNEXPECTED, requests_[i]->WaitForResult()) << i; - - EXPECT_THAT(requests_[1]->result(), IsOk()); - // Resolved by MockDnsClient. - EXPECT_TRUE(requests_[1]->HasOneAddress("127.0.0.1", 80)); - - // Resolutions done by DnsClient are known to have performed a DNS lookup, - // so they should result in a cache entry with SOURCE_DNS. - const HostCache::Entry* cache_entry = GetCacheEntry(*requests_[1]); - ASSERT_NE(nullptr, cache_entry); - EXPECT_EQ(HostCache::Entry::SOURCE_DNS, cache_entry->source()); - - // Fallback to ProcTask. - EXPECT_THAT(requests_[2]->result(), IsError(ERR_NAME_NOT_RESOLVED)); - EXPECT_THAT(requests_[3]->result(), IsOk()); - EXPECT_TRUE(requests_[3]->HasOneAddress("192.168.1.102", 80)); - - // Resolutions done by ProcTask could have performed a DNS lookup, or - // consulted a HOSTS file, or anything else, so they should result in a cache - // entry with SOURCE_UNKNOWN. - cache_entry = GetCacheEntry(*requests_[3]); - ASSERT_NE(nullptr, cache_entry); - EXPECT_EQ(HostCache::Entry::SOURCE_UNKNOWN, cache_entry->source()); -} - -// Test successful and fallback resolutions in HostResolverImpl::DnsTask. -TEST_F(HostResolverImplDnsTest, DnsTask_ResolveHost) { - proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102"); - // All other hostnames will fail in proc_. - - // Initially there is no config, so client should not be invoked. ResolveHostResponseHelper initial_response(resolver_->CreateRequest( HostPortPair("ok_fail", 80), NetLogWithSource(), base::nullopt)); EXPECT_FALSE(initial_response.complete()); @@ -4348,56 +3065,6 @@ // Set empty DnsConfig. ChangeDnsConfig(DnsConfig()); // Initially there is no config, so client should not be invoked. - EXPECT_THAT(CreateRequest("ok_fail", 80)->Resolve(), IsError(ERR_IO_PENDING)); - // There is no config, so fallback to ProcTask must work. - EXPECT_THAT(CreateRequest("nx_succeed", 80)->Resolve(), - IsError(ERR_IO_PENDING)); - proc_->SignalMultiple(requests_.size()); - - EXPECT_THAT(requests_[0]->WaitForResult(), IsError(ERR_NAME_NOT_RESOLVED)); - EXPECT_THAT(requests_[1]->WaitForResult(), IsOk()); - EXPECT_TRUE(requests_[1]->HasOneAddress("192.168.1.102", 80)); - - ChangeDnsConfig(CreateValidDnsConfig()); - - EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_abort", 80, MEDIUM, - ADDRESS_FAMILY_IPV4)->Resolve()); - EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_abort", 80, MEDIUM, - ADDRESS_FAMILY_IPV4)->Resolve()); - - // Simulate the case when the preference or policy has disabled the DNS client - // causing AbortDnsTasks. - UseMockDnsClient(CreateValidDnsConfig(), CreateDefaultDnsRules()); - - // First request is resolved by MockDnsClient, others should fail due to - // disabled fallback to ProcTask. - EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80, MEDIUM, - ADDRESS_FAMILY_IPV4)->Resolve()); - EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_fail", 80, MEDIUM, - ADDRESS_FAMILY_IPV4)->Resolve()); - proc_->SignalMultiple(requests_.size()); - - // Aborted due to Network Change. - EXPECT_THAT(requests_[2]->WaitForResult(), IsError(ERR_NETWORK_CHANGED)); - EXPECT_THAT(requests_[3]->WaitForResult(), IsError(ERR_NETWORK_CHANGED)); - // Resolved by MockDnsClient. - EXPECT_THAT(requests_[4]->WaitForResult(), IsOk()); - EXPECT_TRUE(requests_[4]->HasOneAddress("127.0.0.1", 80)); - // Fallback to ProcTask is disabled. - EXPECT_THAT(requests_[5]->WaitForResult(), IsError(ERR_NAME_NOT_RESOLVED)); -} - -// Test successful and failing resolutions in HostResolverImpl::DnsTask when -// fallback to ProcTask is disabled. -TEST_F(HostResolverImplDnsTest, NoFallbackToProcTask_ResolveHost) { - set_allow_fallback_to_proctask(false); - - proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102"); - // All other hostnames will fail in proc_. - - // Set empty DnsConfig. - ChangeDnsConfig(DnsConfig()); - // Initially there is no config, so client should not be invoked. ResolveHostResponseHelper initial_response0(resolver_->CreateRequest( HostPortPair("ok_fail", 80), NetLogWithSource(), base::nullopt)); ResolveHostResponseHelper initial_response1(resolver_->CreateRequest( @@ -4444,32 +3111,6 @@ // Test behavior of OnDnsTaskFailure when Job is aborted. TEST_F(HostResolverImplDnsTest, OnDnsTaskFailureAbortedJob) { ChangeDnsConfig(CreateValidDnsConfig()); - EXPECT_THAT(CreateRequest("nx_abort", 80)->Resolve(), - IsError(ERR_IO_PENDING)); - // Abort all jobs here. - CreateResolver(); - proc_->SignalMultiple(requests_.size()); - // Run to completion. - base::RunLoop().RunUntilIdle(); // Notification happens async. - // It shouldn't crash during OnDnsTaskFailure callbacks. - EXPECT_THAT(requests_[0]->result(), IsError(ERR_IO_PENDING)); - - // Repeat test with Fallback to ProcTask disabled - set_allow_fallback_to_proctask(false); - ChangeDnsConfig(CreateValidDnsConfig()); - EXPECT_THAT(CreateRequest("nx_abort", 80)->Resolve(), - IsError(ERR_IO_PENDING)); - // Abort all jobs here. - CreateResolver(); - // Run to completion. - base::RunLoop().RunUntilIdle(); // Notification happens async. - // It shouldn't crash during OnDnsTaskFailure callbacks. - EXPECT_THAT(requests_[1]->result(), IsError(ERR_IO_PENDING)); -} - -// Test behavior of OnDnsTaskFailure when Job is aborted. -TEST_F(HostResolverImplDnsTest, OnDnsTaskFailureAbortedJob_ResolveHost) { - ChangeDnsConfig(CreateValidDnsConfig()); ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair("nx_abort", 80), NetLogWithSource(), base::nullopt)); // Abort all jobs here. @@ -4602,33 +3243,6 @@ proc_->AddRuleForAllFamilies("4nx", "192.168.1.101"); // All other hostnames will fail in proc_. - EXPECT_THAT(CreateRequest("ok", 80)->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("4ok", 80)->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("6ok", 80)->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("4nx", 80)->Resolve(), IsError(ERR_IO_PENDING)); - - proc_->SignalMultiple(requests_.size()); - - for (size_t i = 0; i < requests_.size(); ++i) - EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i; - - EXPECT_EQ(2u, requests_[0]->NumberOfAddresses()); - EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80)); - EXPECT_TRUE(requests_[0]->HasAddress("::1", 80)); - EXPECT_EQ(1u, requests_[1]->NumberOfAddresses()); - EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80)); - EXPECT_EQ(1u, requests_[2]->NumberOfAddresses()); - EXPECT_TRUE(requests_[2]->HasAddress("::1", 80)); - EXPECT_EQ(1u, requests_[3]->NumberOfAddresses()); - EXPECT_TRUE(requests_[3]->HasAddress("192.168.1.101", 80)); -} - -TEST_F(HostResolverImplDnsTest, DnsTaskUnspec_ResolveHost) { - ChangeDnsConfig(CreateValidDnsConfig()); - - proc_->AddRuleForAllFamilies("4nx", "192.168.1.101"); - // All other hostnames will fail in proc_. - std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses; responses.emplace_back( std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest( @@ -4663,34 +3277,6 @@ TEST_F(HostResolverImplDnsTest, NameCollisionIcann) { ChangeDnsConfig(CreateValidDnsConfig()); - // When the resolver returns an A record with 127.0.53.53 it should be mapped - // to a special error. - EXPECT_THAT(CreateRequest("4collision", 80)->Resolve(), - IsError(ERR_IO_PENDING)); - - EXPECT_THAT(requests_[0]->WaitForResult(), IsError(ERR_ICANN_NAME_COLLISION)); - - // When the resolver returns an AAAA record with ::127.0.53.53 it should - // work just like any other IP. (Despite having the same suffix, it is not - // considered special) - EXPECT_THAT(CreateRequest("6collision", 80)->Resolve(), - IsError(ERR_IO_PENDING)); - - EXPECT_THAT(requests_[1]->WaitForResult(), IsError(OK)); - EXPECT_TRUE(requests_[1]->HasAddress("::127.0.53.53", 80)); - - // The mock responses for 4collision (and 6collision) have a TTL of 1 day. - // Test whether the ERR_ICANN_NAME_COLLISION failure was cached. - // On the one hand caching the failure makes sense, as the error is derived - // from the IP in the response. However for consistency with the the proc- - // based implementation the TTL is unused. - EXPECT_THAT(CreateRequest("4collision", 80)->ResolveFromCache(), - IsError(ERR_DNS_CACHE_MISS)); -} - -TEST_F(HostResolverImplDnsTest, NameCollisionIcann_ResolveHost) { - ChangeDnsConfig(CreateValidDnsConfig()); - // When the resolver returns an A record with 127.0.53.53 it should be // mapped to a special error. ResolveHostResponseHelper response_ipv4(resolver_->CreateRequest( @@ -4717,60 +3303,6 @@ std::string()); // Default to failures. proc_->SignalMultiple(1u); // For the first request which misses. - Request* req0 = CreateRequest("nx_ipv4", 80); - EXPECT_THAT(req0->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(req0->WaitForResult(), IsError(ERR_NAME_NOT_RESOLVED)); - - IPAddress local_ipv4 = IPAddress::IPv4Localhost(); - IPAddress local_ipv6 = IPAddress::IPv6Localhost(); - - DnsHosts hosts; - hosts[DnsHostsKey("nx_ipv4", ADDRESS_FAMILY_IPV4)] = local_ipv4; - hosts[DnsHostsKey("nx_ipv6", ADDRESS_FAMILY_IPV6)] = local_ipv6; - hosts[DnsHostsKey("nx_both", ADDRESS_FAMILY_IPV4)] = local_ipv4; - hosts[DnsHostsKey("nx_both", ADDRESS_FAMILY_IPV6)] = local_ipv6; - - // Update HOSTS file. - config.hosts = hosts; - ChangeDnsConfig(config); - - Request* req1 = CreateRequest("nx_ipv4", 80); - EXPECT_THAT(req1->Resolve(), IsOk()); - EXPECT_TRUE(req1->HasOneAddress("127.0.0.1", 80)); - - Request* req2 = CreateRequest("nx_ipv6", 80); - EXPECT_THAT(req2->Resolve(), IsOk()); - EXPECT_TRUE(req2->HasOneAddress("::1", 80)); - - Request* req3 = CreateRequest("nx_both", 80); - EXPECT_THAT(req3->Resolve(), IsOk()); - EXPECT_TRUE(req3->HasAddress("127.0.0.1", 80) && - req3->HasAddress("::1", 80)); - - // Requests with specified AddressFamily. - Request* req4 = CreateRequest("nx_ipv4", 80, MEDIUM, ADDRESS_FAMILY_IPV4); - EXPECT_THAT(req4->Resolve(), IsOk()); - EXPECT_TRUE(req4->HasOneAddress("127.0.0.1", 80)); - - Request* req5 = CreateRequest("nx_ipv6", 80, MEDIUM, ADDRESS_FAMILY_IPV6); - EXPECT_THAT(req5->Resolve(), IsOk()); - EXPECT_TRUE(req5->HasOneAddress("::1", 80)); - - // Request with upper case. - Request* req6 = CreateRequest("nx_IPV4", 80); - EXPECT_THAT(req6->Resolve(), IsOk()); - EXPECT_TRUE(req6->HasOneAddress("127.0.0.1", 80)); -} - -TEST_F(HostResolverImplDnsTest, ServeFromHosts_ResolveHost) { - // Initially, use empty HOSTS file. - DnsConfig config = CreateValidDnsConfig(); - ChangeDnsConfig(config); - - proc_->AddRuleForAllFamilies(std::string(), - std::string()); // Default to failures. - proc_->SignalMultiple(1u); // For the first request which misses. - ResolveHostResponseHelper initial_response(resolver_->CreateRequest( HostPortPair("nx_ipv4", 80), NetLogWithSource(), base::nullopt)); EXPECT_THAT(initial_response.result_error(), IsError(ERR_NAME_NOT_RESOLVED)); @@ -4850,43 +3382,6 @@ std::string()); // Default to failures. proc_->SignalMultiple(1u); // For the first request which fails. - Request* req1 = CreateRequest("nx_ipv4", 80); - EXPECT_THAT(req1->Resolve(), IsError(ERR_IO_PENDING)); - Request* req2 = CreateRequest("nx_ipv6", 80); - EXPECT_THAT(req2->Resolve(), IsError(ERR_IO_PENDING)); - - DnsHosts hosts; - hosts[DnsHostsKey("nx_ipv4", ADDRESS_FAMILY_IPV4)] = - IPAddress::IPv4Localhost(); - hosts[DnsHostsKey("nx_ipv6", ADDRESS_FAMILY_IPV6)] = - IPAddress::IPv6Localhost(); - - config.hosts = hosts; - ChangeDnsConfig(config); - - EXPECT_THAT(req1->WaitForResult(), IsError(ERR_NETWORK_CHANGED)); - EXPECT_THAT(req2->WaitForResult(), IsOk()); - EXPECT_TRUE(req2->HasOneAddress("::1", 80)); - - // Resolutions done by consulting the HOSTS file when the DNS config changes - // should result in a cache entry with SOURCE_HOSTS. - const HostCache::Entry* cache_entry = GetCacheEntry(*req2); - ASSERT_THAT(cache_entry, NotNull()); - EXPECT_EQ(HostCache::Entry::SOURCE_HOSTS, cache_entry->source()); -} - -TEST_F(HostResolverImplDnsTest, CacheHostsLookupOnConfigChange_ResolveHost) { - // Only allow 1 resolution at a time, so that the second lookup is queued and - // occurs when the DNS config changes. - CreateResolverWithLimitsAndParams(1u, DefaultParams(proc_.get()), - true /* ipv6_reachable */); - DnsConfig config = CreateValidDnsConfig(); - ChangeDnsConfig(config); - - proc_->AddRuleForAllFamilies(std::string(), - std::string()); // Default to failures. - proc_->SignalMultiple(1u); // For the first request which fails. - ResolveHostResponseHelper failure_response(resolver_->CreateRequest( HostPortPair("nx_ipv4", 80), NetLogWithSource(), base::nullopt)); ResolveHostResponseHelper queued_response(resolver_->CreateRequest( @@ -4909,39 +3404,16 @@ // Resolutions done by consulting the HOSTS file when the DNS config changes // should result in a cache entry with SOURCE_HOSTS. - const HostCache::Entry* cache_entry = - GetCacheEntry(*CreateRequest("nx_ipv6", 80)); + const HostCache::Entry* cache_entry = GetCacheEntry( + HostCache::Key("nx_ipv6", DnsQueryType::UNSPECIFIED, + 0 /* host_resolver_flags */, HostResolverSource::ANY)); ASSERT_THAT(cache_entry, NotNull()); EXPECT_EQ(HostCache::Entry::SOURCE_HOSTS, cache_entry->source()); } -TEST_F(HostResolverImplDnsTest, BypassDnsTask) { - ChangeDnsConfig(CreateValidDnsConfig()); - - proc_->AddRuleForAllFamilies(std::string(), - std::string()); // Default to failures. - - EXPECT_THAT(CreateRequest("ok.local", 80)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("ok.local.", 80)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("oklocal", 80)->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("oklocal.", 80)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("ok", 80)->Resolve(), IsError(ERR_IO_PENDING)); - - proc_->SignalMultiple(requests_.size()); - - for (size_t i = 0; i < 2; ++i) - EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[i]->WaitForResult()) << i; - - for (size_t i = 2; i < requests_.size(); ++i) - EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i; -} - // Test that hosts ending in ".local" or ".local." are resolved using the system // resolver. -TEST_F(HostResolverImplDnsTest, BypassDnsTask_ResolveHost) { +TEST_F(HostResolverImplDnsTest, BypassDnsTask) { ChangeDnsConfig(CreateValidDnsConfig()); proc_->AddRuleForAllFamilies(std::string(), @@ -5035,25 +3507,6 @@ } TEST_F(HostResolverImplDnsTest, SystemOnlyBypassesDnsTask) { - ChangeDnsConfig(CreateValidDnsConfig()); - - proc_->AddRuleForAllFamilies(std::string(), std::string()); - - HostResolver::RequestInfo info_bypass(HostPortPair("ok", 80)); - info_bypass.set_host_resolver_flags(HOST_RESOLVER_SYSTEM_ONLY); - EXPECT_THAT(CreateRequest(info_bypass, MEDIUM)->Resolve(), - IsError(ERR_IO_PENDING)); - - HostResolver::RequestInfo info(HostPortPair("ok", 80)); - EXPECT_THAT(CreateRequest(info, MEDIUM)->Resolve(), IsError(ERR_IO_PENDING)); - - proc_->SignalMultiple(requests_.size()); - - EXPECT_THAT(requests_[0]->WaitForResult(), IsError(ERR_NAME_NOT_RESOLVED)); - EXPECT_THAT(requests_[1]->WaitForResult(), IsOk()); -} - -TEST_F(HostResolverImplDnsTest, SystemOnlyBypassesDnsTask_ResolveHost) { // Ensure DNS task requests will succeed and system (proc) requests will fail. ChangeDnsConfig(CreateValidDnsConfig()); proc_->AddRuleForAllFamilies(std::string(), std::string()); @@ -5079,46 +3532,6 @@ std::string()); // Default to failures. // Check that DnsTask works. - Request* req = CreateRequest("ok_1", 80); - EXPECT_THAT(req->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(req->WaitForResult(), IsOk()); - - for (unsigned i = 0; i < maximum_dns_failures(); ++i) { - // Use custom names to require separate Jobs. - std::string hostname = base::StringPrintf("nx_%u", i); - // Ensure fallback to ProcTask succeeds. - proc_->AddRuleForAllFamilies(hostname, "192.168.1.101"); - EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 80)->Resolve()) << i; - } - - proc_->SignalMultiple(requests_.size()); - - for (size_t i = 0; i < requests_.size(); ++i) - EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i; - - ASSERT_FALSE(proc_->HasBlockedRequests()); - - // DnsTask should be disabled by now. - req = CreateRequest("ok_2", 80); - EXPECT_THAT(req->Resolve(), IsError(ERR_IO_PENDING)); - proc_->SignalMultiple(1u); - EXPECT_THAT(req->WaitForResult(), IsError(ERR_NAME_NOT_RESOLVED)); - - // Check that it is re-enabled after DNS change. - ChangeDnsConfig(CreateValidDnsConfig()); - req = CreateRequest("ok_3", 80); - EXPECT_THAT(req->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(req->WaitForResult(), IsOk()); -} - -TEST_F(HostResolverImplDnsTest, - DisableDnsClientOnPersistentFailure_ResolveHost) { - ChangeDnsConfig(CreateValidDnsConfig()); - - proc_->AddRuleForAllFamilies(std::string(), - std::string()); // Default to failures. - - // Check that DnsTask works. ResolveHostResponseHelper initial_response(resolver_->CreateRequest( HostPortPair("ok_1", 80), NetLogWithSource(), base::nullopt)); EXPECT_THAT(initial_response.result_error(), IsOk()); @@ -5165,34 +3578,6 @@ // |proc_| defaults to successes. // 20 failures interleaved with 20 successes. - for (unsigned i = 0; i < 40; ++i) { - // Use custom names to require separate Jobs. - std::string hostname = (i % 2) == 0 ? base::StringPrintf("nx_%u", i) - : base::StringPrintf("ok_%u", i); - EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 80)->Resolve()) << i; - } - - proc_->SignalMultiple(requests_.size()); - - for (size_t i = 0; i < requests_.size(); ++i) - EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i; - - // Make |proc_| default to failures. - proc_->AddRuleForAllFamilies(std::string(), std::string()); - - // DnsTask should still be enabled. - Request* req = CreateRequest("ok_last", 80); - EXPECT_THAT(req->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(req->WaitForResult(), IsOk()); -} - -TEST_F(HostResolverImplDnsTest, - DontDisableDnsClientOnSporadicFailure_ResolveHost) { - ChangeDnsConfig(CreateValidDnsConfig()); - - // |proc_| defaults to successes. - - // 20 failures interleaved with 20 successes. std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses; for (unsigned i = 0; i < 40; ++i) { // Use custom names to require separate Jobs. @@ -5205,8 +3590,8 @@ proc_->SignalMultiple(40u); - for (size_t i = 0; i < requests_.size(); ++i) - EXPECT_THAT(responses[i]->result_error(), IsOk()); + for (const auto& response : responses) + EXPECT_THAT(response->result_error(), IsOk()); // Make |proc_| default to failures. proc_->AddRuleForAllFamilies(std::string(), std::string()); @@ -5221,71 +3606,6 @@ // global IPv6 address. See SystemHostResolverCall for rationale. // Test both the DnsClient and system host resolver paths. TEST_F(HostResolverImplDnsTest, DualFamilyLocalhost) { - // Use regular SystemHostResolverCall! - scoped_refptr<HostResolverProc> proc(new SystemHostResolverProc()); - resolver_.reset(new TestHostResolverImpl(DefaultOptions(), NULL, false)); - resolver_->set_proc_params_for_test(DefaultParams(proc.get())); - - UseMockDnsClient(DnsConfig(), CreateDefaultDnsRules()); - - // Get the expected output. - AddressList addrlist; - int rv = proc->Resolve("localhost", ADDRESS_FAMILY_UNSPECIFIED, 0, &addrlist, - NULL); - if (rv != OK) - return; - - for (unsigned i = 0; i < addrlist.size(); ++i) - LOG(WARNING) << addrlist[i].ToString(); - - bool saw_ipv4 = AddressListContains(addrlist, "127.0.0.1", 0); - bool saw_ipv6 = AddressListContains(addrlist, "::1", 0); - if (!saw_ipv4 && !saw_ipv6) - return; - - // Try without DnsClient. - DnsConfig config = CreateValidDnsConfig(); - config.use_local_ipv6 = false; - ChangeDnsConfig(config); - HostResolver::RequestInfo info_proc(HostPortPair("localhost", 80)); - info_proc.set_address_family(ADDRESS_FAMILY_UNSPECIFIED); - info_proc.set_host_resolver_flags(HOST_RESOLVER_SYSTEM_ONLY); - Request* req = CreateRequest(info_proc, DEFAULT_PRIORITY); - - EXPECT_THAT(req->Resolve(), IsOk()); - - EXPECT_TRUE(req->HasAddress("127.0.0.1", 80)); - EXPECT_TRUE(req->HasAddress("::1", 80)); - - // Configure DnsClient with dual-host HOSTS file. - DnsConfig config_hosts = CreateValidDnsConfig(); - DnsHosts hosts; - IPAddress local_ipv4 = IPAddress::IPv4Localhost(); - IPAddress local_ipv6 = IPAddress::IPv6Localhost(); - if (saw_ipv4) - hosts[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV4)] = local_ipv4; - if (saw_ipv6) - hosts[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV6)] = local_ipv6; - config_hosts.hosts = hosts; - - ChangeDnsConfig(config_hosts); - HostResolver::RequestInfo info_hosts(HostPortPair("localhost", 80)); - info_hosts.set_address_family(ADDRESS_FAMILY_UNSPECIFIED); - req = CreateRequest(info_hosts, DEFAULT_PRIORITY); - // Expect synchronous resolution from DnsHosts. - EXPECT_THAT(req->Resolve(), IsOk()); - - // Localhost names always resolve to IPv4 and IPv6, regardless of the content - // written into the HOSTS file above based on the results of the - // SystemHostResolverCall at the top of this test. - EXPECT_TRUE(req->HasAddress("127.0.0.1", 80)); - EXPECT_TRUE(req->HasAddress("::1", 80)); -} - -// Confirm that resolving "localhost" is unrestricted even if there are no -// global IPv6 address. See SystemHostResolverCall for rationale. -// Test both the DnsClient and system host resolver paths. -TEST_F(HostResolverImplDnsTest, DualFamilyLocalhost_ResolveHost) { CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_.get()), false /* ipv6_reachable */); @@ -5328,18 +3648,6 @@ // Cancel a request with a single DNS transaction active. TEST_F(HostResolverImplDnsTest, CancelWithOneTransactionActive) { - ChangeDnsConfig(CreateValidDnsConfig()); - - EXPECT_EQ(ERR_IO_PENDING, - CreateRequest("ok", 80, MEDIUM, ADDRESS_FAMILY_IPV4)->Resolve()); - EXPECT_EQ(1u, num_running_dispatcher_jobs()); - requests_[0]->Cancel(); - - // Dispatcher state checked in TearDown. -} - -// Cancel a request with a single DNS transaction active. -TEST_F(HostResolverImplDnsTest, CancelWithOneTransactionActive_ResolveHost) { // Disable ipv6 to ensure we'll only try a single transaction for the host. CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_.get()), false /* ipv6_reachable */); @@ -5364,19 +3672,6 @@ CreateSerialResolver(); ChangeDnsConfig(CreateValidDnsConfig()); - EXPECT_THAT(CreateRequest("ok", 80)->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_EQ(1u, num_running_dispatcher_jobs()); - requests_[0]->Cancel(); - - // Dispatcher state checked in TearDown. -} - -// Cancel a request with a single DNS transaction active and another pending. -TEST_F(HostResolverImplDnsTest, - CancelWithOneTransactionActiveOnePending_ResolveHost) { - CreateSerialResolver(); - ChangeDnsConfig(CreateValidDnsConfig()); - ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair("ok", 80), NetLogWithSource(), base::nullopt)); EXPECT_EQ(1u, num_running_dispatcher_jobs()); @@ -5392,17 +3687,6 @@ TEST_F(HostResolverImplDnsTest, CancelWithTwoTransactionsActive) { ChangeDnsConfig(CreateValidDnsConfig()); - EXPECT_THAT(CreateRequest("ok", 80)->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_EQ(2u, num_running_dispatcher_jobs()); - requests_[0]->Cancel(); - - // Dispatcher state checked in TearDown. -} - -// Cancel a request with two DNS transactions active. -TEST_F(HostResolverImplDnsTest, CancelWithTwoTransactionsActive_ResolveHost) { - ChangeDnsConfig(CreateValidDnsConfig()); - ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair("ok", 80), NetLogWithSource(), base::nullopt)); EXPECT_EQ(2u, num_running_dispatcher_jobs()); @@ -5422,30 +3706,6 @@ ChangeDnsConfig(CreateValidDnsConfig()); - // First active job is an IPv4 request. - EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80, MEDIUM, - ADDRESS_FAMILY_IPV4)->Resolve()); - - // Add 10 more DNS lookups for different hostnames. First 4 should have two - // active jobs, next one has a single active job, and one pending. Others - // should all be queued. - for (int i = 0; i < 10; ++i) { - EXPECT_EQ(ERR_IO_PENDING, CreateRequest( - base::StringPrintf("ok%i", i))->Resolve()); - } - EXPECT_EQ(10u, num_running_dispatcher_jobs()); - - resolver_.reset(); -} - -// Delete a resolver with some active requests and some queued requests. -TEST_F(HostResolverImplDnsTest, DeleteWithActiveTransactions_ResolveHost) { - // At most 10 Jobs active at once. - CreateResolverWithLimitsAndParams(10u, DefaultParams(proc_.get()), - true /* ipv6_reachable */); - - ChangeDnsConfig(CreateValidDnsConfig()); - // Add 12 DNS lookups (creating well more than 10 transaction). std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses; for (int i = 0; i < 12; ++i) { @@ -5468,22 +3728,6 @@ TEST_F(HostResolverImplDnsTest, CancelWithIPv6TransactionActive) { ChangeDnsConfig(CreateValidDnsConfig()); - EXPECT_THAT(CreateRequest("6slow_ok", 80)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_EQ(2u, num_running_dispatcher_jobs()); - - // The IPv4 request should complete, the IPv6 request is still pending. - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1u, num_running_dispatcher_jobs()); - requests_[0]->Cancel(); - - // Dispatcher state checked in TearDown. -} - -// Cancel a request with only the IPv6 transaction active. -TEST_F(HostResolverImplDnsTest, CancelWithIPv6TransactionActive_ResolveHost) { - ChangeDnsConfig(CreateValidDnsConfig()); - ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair("6slow_ok", 80), NetLogWithSource(), base::nullopt)); EXPECT_EQ(2u, num_running_dispatcher_jobs()); @@ -5504,22 +3748,6 @@ set_allow_fallback_to_proctask(false); ChangeDnsConfig(CreateValidDnsConfig()); - EXPECT_THAT(CreateRequest("4slow_ok", 80)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_EQ(2u, num_running_dispatcher_jobs()); - - // The IPv6 request should complete, the IPv4 request is still pending. - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1u, num_running_dispatcher_jobs()); - - requests_[0]->Cancel(); -} - -// Cancel a request with only the IPv4 transaction pending. -TEST_F(HostResolverImplDnsTest, CancelWithIPv4TransactionPending_ResolveHost) { - set_allow_fallback_to_proctask(false); - ChangeDnsConfig(CreateValidDnsConfig()); - ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair("4slow_ok", 80), NetLogWithSource(), base::nullopt)); EXPECT_EQ(2u, num_running_dispatcher_jobs()); @@ -5538,46 +3766,6 @@ set_allow_fallback_to_proctask(false); ChangeDnsConfig(CreateValidDnsConfig()); - EXPECT_THAT(CreateRequest("4slow_ok", 80)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("4slow_4ok", 80)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("4slow_4timeout", 80)->Resolve(), - IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("4slow_6timeout", 80)->Resolve(), - IsError(ERR_IO_PENDING)); - - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(requests_[0]->completed()); - EXPECT_FALSE(requests_[1]->completed()); - EXPECT_FALSE(requests_[2]->completed()); - // The IPv6 of request 3 should have failed and resulted in cancelling the - // IPv4 request. - EXPECT_TRUE(requests_[3]->completed()); - EXPECT_THAT(requests_[3]->result(), IsError(ERR_DNS_TIMED_OUT)); - EXPECT_EQ(3u, num_running_dispatcher_jobs()); - - dns_client_->CompleteDelayedTransactions(); - EXPECT_TRUE(requests_[0]->completed()); - EXPECT_THAT(requests_[0]->result(), IsOk()); - EXPECT_EQ(2u, requests_[0]->NumberOfAddresses()); - EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80)); - EXPECT_TRUE(requests_[0]->HasAddress("::1", 80)); - - EXPECT_TRUE(requests_[1]->completed()); - EXPECT_THAT(requests_[1]->result(), IsOk()); - EXPECT_EQ(1u, requests_[1]->NumberOfAddresses()); - EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80)); - - EXPECT_TRUE(requests_[2]->completed()); - EXPECT_THAT(requests_[2]->result(), IsError(ERR_DNS_TIMED_OUT)); -} - -// Test cases where AAAA completes first. -TEST_F(HostResolverImplDnsTest, AAAACompletesFirst_ResolveHost) { - set_allow_fallback_to_proctask(false); - ChangeDnsConfig(CreateValidDnsConfig()); - std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses; responses.emplace_back( std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest( @@ -5620,23 +3808,6 @@ set_allow_fallback_to_proctask(false); ChangeDnsConfig(CreateValidDnsConfig()); - EXPECT_THAT(CreateRequest("ok", 80)->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_EQ(1u, num_running_dispatcher_jobs()); - - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(requests_[0]->completed()); - EXPECT_THAT(requests_[0]->result(), IsOk()); - EXPECT_EQ(2u, requests_[0]->NumberOfAddresses()); - EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80)); - EXPECT_TRUE(requests_[0]->HasAddress("::1", 80)); -} - -// Test the case where only a single transaction slot is available. -TEST_F(HostResolverImplDnsTest, SerialResolver_ResolveHost) { - CreateSerialResolver(); - set_allow_fallback_to_proctask(false); - ChangeDnsConfig(CreateValidDnsConfig()); - ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair("ok", 80), NetLogWithSource(), base::nullopt)); EXPECT_FALSE(response.complete()); @@ -5650,40 +3821,10 @@ CreateExpected("::1", 80))); } -// Test the case where the AAAA query is started when another transaction -// completes. -TEST_F(HostResolverImplDnsTest, AAAAStartsAfterOtherJobFinishes) { - CreateResolverWithLimitsAndParams(2u, DefaultParams(proc_.get()), - true /* ipv6_reachable */); - set_allow_fallback_to_proctask(false); - ChangeDnsConfig(CreateValidDnsConfig()); - - EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80, MEDIUM, - ADDRESS_FAMILY_IPV4)->Resolve()); - EXPECT_EQ(ERR_IO_PENDING, - CreateRequest("4slow_ok", 80, MEDIUM)->Resolve()); - // An IPv4 request should have been started pending for each job. - EXPECT_EQ(2u, num_running_dispatcher_jobs()); - - // Request 0's IPv4 request should complete, starting Request 1's IPv6 - // request, which should also complete. - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1u, num_running_dispatcher_jobs()); - EXPECT_TRUE(requests_[0]->completed()); - EXPECT_FALSE(requests_[1]->completed()); - - dns_client_->CompleteDelayedTransactions(); - EXPECT_TRUE(requests_[1]->completed()); - EXPECT_THAT(requests_[1]->result(), IsOk()); - EXPECT_EQ(2u, requests_[1]->NumberOfAddresses()); - EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80)); - EXPECT_TRUE(requests_[1]->HasAddress("::1", 80)); -} - // Test the case where subsequent transactions are handled on transaction // completion when only part of a multi-transaction request could be initially // started. -TEST_F(HostResolverImplDnsTest, AAAAStartsAfterOtherJobFinishes_ResolveHost) { +TEST_F(HostResolverImplDnsTest, AAAAStartsAfterOtherJobFinishes) { CreateResolverWithLimitsAndParams(3u, DefaultParams(proc_.get()), true /* ipv6_reachable */); set_allow_fallback_to_proctask(false); @@ -5713,19 +3854,6 @@ // Tests the case that a Job with a single transaction receives an empty address // list, triggering fallback to ProcTask. TEST_F(HostResolverImplDnsTest, IPv4EmptyFallback) { - ChangeDnsConfig(CreateValidDnsConfig()); - proc_->AddRuleForAllFamilies("empty_fallback", "192.168.0.1"); - proc_->SignalMultiple(1u); - EXPECT_EQ(ERR_IO_PENDING, - CreateRequest("empty_fallback", 80, MEDIUM, - ADDRESS_FAMILY_IPV4)->Resolve()); - EXPECT_THAT(requests_[0]->WaitForResult(), IsOk()); - EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80)); -} - -// Tests the case that a Job with a single transaction receives an empty address -// list, triggering fallback to ProcTask. -TEST_F(HostResolverImplDnsTest, IPv4EmptyFallback_ResolveHost) { // Disable ipv6 to ensure we'll only try a single transaction for the host. CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_.get()), false /* ipv6_reachable */); @@ -5750,19 +3878,6 @@ ChangeDnsConfig(CreateValidDnsConfig()); proc_->AddRuleForAllFamilies("empty_fallback", "192.168.0.1"); proc_->SignalMultiple(1u); - EXPECT_EQ(ERR_IO_PENDING, - CreateRequest("empty_fallback", 80, MEDIUM, - ADDRESS_FAMILY_UNSPECIFIED)->Resolve()); - EXPECT_THAT(requests_[0]->WaitForResult(), IsOk()); - EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80)); -} - -// Tests the case that a Job with two transactions receives two empty address -// lists, triggering fallback to ProcTask. -TEST_F(HostResolverImplDnsTest, UnspecEmptyFallback_ResolveHost) { - ChangeDnsConfig(CreateValidDnsConfig()); - proc_->AddRuleForAllFamilies("empty_fallback", "192.168.0.1"); - proc_->SignalMultiple(1u); ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair("empty_fallback", 80), NetLogWithSource(), base::nullopt)); @@ -5774,44 +3889,6 @@ // Tests getting a new invalid DnsConfig while there are active DnsTasks. TEST_F(HostResolverImplDnsTest, InvalidDnsConfigWithPendingRequests) { - // At most 3 jobs active at once. This number is important, since we want to - // make sure that aborting the first HostResolverImpl::Job does not trigger - // another DnsTransaction on the second Job when it releases its second - // prioritized dispatcher slot. - CreateResolverWithLimitsAndParams(3u, DefaultParams(proc_.get()), - true /* ipv6_reachable */); - - ChangeDnsConfig(CreateValidDnsConfig()); - - proc_->AddRuleForAllFamilies("slow_nx1", "192.168.0.1"); - proc_->AddRuleForAllFamilies("slow_nx2", "192.168.0.2"); - proc_->AddRuleForAllFamilies("ok", "192.168.0.3"); - - // First active job gets two slots. - EXPECT_THAT(CreateRequest("slow_nx1")->Resolve(), IsError(ERR_IO_PENDING)); - // Next job gets one slot, and waits on another. - EXPECT_THAT(CreateRequest("slow_nx2")->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(CreateRequest("ok")->Resolve(), IsError(ERR_IO_PENDING)); - - EXPECT_EQ(3u, num_running_dispatcher_jobs()); - - // Clear DNS config. Two in-progress jobs should be aborted, and the next one - // should use a ProcTask. - ChangeDnsConfig(DnsConfig()); - EXPECT_THAT(requests_[0]->WaitForResult(), IsError(ERR_NETWORK_CHANGED)); - EXPECT_THAT(requests_[1]->WaitForResult(), IsError(ERR_NETWORK_CHANGED)); - - // Finish up the third job. Should bypass the DnsClient, and get its results - // from MockHostResolverProc. - EXPECT_FALSE(requests_[2]->completed()); - proc_->SignalMultiple(1u); - EXPECT_THAT(requests_[2]->WaitForResult(), IsOk()); - EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.0.3", 80)); -} - -// Tests getting a new invalid DnsConfig while there are active DnsTasks. -TEST_F(HostResolverImplDnsTest, - InvalidDnsConfigWithPendingRequests_ResolveHost) { // At most 3 jobs active at once. This number is important, since we want // to make sure that aborting the first HostResolverImpl::Job does not // trigger another DnsTransaction on the second Job when it releases its @@ -5860,25 +3937,9 @@ testing::ElementsAre(CreateExpected("192.168.0.3", 80))); } -// Test that initial DNS config read signals do not abort pending requests when -// using DnsClient. -TEST_F(HostResolverImplDnsTest, DontAbortOnInitialDNSConfigRead) { - // DnsClient is enabled, but there's no DnsConfig, so the request should start - // using ProcTask. - Request* req = CreateRequest("host1", 70); - EXPECT_THAT(req->Resolve(), IsError(ERR_IO_PENDING)); - - EXPECT_TRUE(proc_->WaitFor(1u)); - // Send the initial config read signal, with a valid config. - SetInitialDnsConfig(CreateValidDnsConfig()); - proc_->SignalAll(); - - EXPECT_THAT(req->WaitForResult(), IsOk()); -} - // Test that initial DNS config read signals do not abort pending requests // when using DnsClient. -TEST_F(HostResolverImplDnsTest, DontAbortOnInitialDNSConfigRead_ResolveHost) { +TEST_F(HostResolverImplDnsTest, DontAbortOnInitialDNSConfigRead) { // DnsClient is enabled, but there's no DnsConfig, so the request should start // using ProcTask. ResolveHostResponseHelper response(resolver_->CreateRequest( @@ -5901,57 +3962,6 @@ // result in different behavior when aborting in-progress DnsTasks. Having // a DnsTask that has one job active and one in the queue when another job // occupying two slots has its DnsTask aborted is the case most likely to run - // into problems. - for (size_t limit = 1u; limit < 6u; ++limit) { - CreateResolverWithLimitsAndParams(limit, DefaultParams(proc_.get()), - true /* ipv6_reachable */); - - ChangeDnsConfig(CreateValidDnsConfig()); - - // Queue up enough failures to disable DnsTasks. These will all fall back - // to ProcTasks, and succeed there. - for (unsigned i = 0u; i < maximum_dns_failures(); ++i) { - std::string host = base::StringPrintf("nx%u", i); - proc_->AddRuleForAllFamilies(host, "192.168.0.1"); - EXPECT_THAT(CreateRequest(host)->Resolve(), IsError(ERR_IO_PENDING)); - } - - // These requests should all bypass DnsTasks, due to the above failures, - // so should end up using ProcTasks. - proc_->AddRuleForAllFamilies("slow_ok1", "192.168.0.2"); - EXPECT_THAT(CreateRequest("slow_ok1")->Resolve(), IsError(ERR_IO_PENDING)); - proc_->AddRuleForAllFamilies("slow_ok2", "192.168.0.3"); - EXPECT_THAT(CreateRequest("slow_ok2")->Resolve(), IsError(ERR_IO_PENDING)); - proc_->AddRuleForAllFamilies("slow_ok3", "192.168.0.4"); - EXPECT_THAT(CreateRequest("slow_ok3")->Resolve(), IsError(ERR_IO_PENDING)); - proc_->SignalMultiple(maximum_dns_failures() + 3); - - for (size_t i = 0u; i < maximum_dns_failures(); ++i) { - EXPECT_THAT(requests_[i]->WaitForResult(), IsOk()); - EXPECT_TRUE(requests_[i]->HasOneAddress("192.168.0.1", 80)); - } - - EXPECT_THAT(requests_[maximum_dns_failures()]->WaitForResult(), IsOk()); - EXPECT_TRUE(requests_[maximum_dns_failures()]->HasOneAddress( - "192.168.0.2", 80)); - EXPECT_THAT(requests_[maximum_dns_failures() + 1]->WaitForResult(), IsOk()); - EXPECT_TRUE(requests_[maximum_dns_failures() + 1]->HasOneAddress( - "192.168.0.3", 80)); - EXPECT_THAT(requests_[maximum_dns_failures() + 2]->WaitForResult(), IsOk()); - EXPECT_TRUE(requests_[maximum_dns_failures() + 2]->HasOneAddress( - "192.168.0.4", 80)); - requests_.clear(); - } -} - -// Tests the case that DnsClient is automatically disabled due to failures -// while there are active DnsTasks. -TEST_F(HostResolverImplDnsTest, - AutomaticallyDisableDnsClientWithPendingRequests_ResolveHost) { - // Trying different limits is important for this test: Different limits - // result in different behavior when aborting in-progress DnsTasks. Having - // a DnsTask that has one job active and one in the queue when another job - // occupying two slots has its DnsTask aborted is the case most likely to run // into problems. Try limits between [1, 2 * # of non failure requests]. for (size_t limit = 1u; limit < 10u; ++limit) { CreateResolverWithLimitsAndParams(limit, DefaultParams(proc_.get()), @@ -6049,47 +4059,6 @@ proc_->AddRuleForAllFamilies("slow_ok2", "192.168.0.2"); proc_->AddRuleForAllFamilies("ok", "192.168.0.3"); - // First active job gets two slots. - EXPECT_THAT(CreateRequest("slow_ok1")->Resolve(), IsError(ERR_IO_PENDING)); - // Next job gets one slot, and waits on another. - EXPECT_THAT(CreateRequest("slow_ok2")->Resolve(), IsError(ERR_IO_PENDING)); - // Next one is queued. - EXPECT_THAT(CreateRequest("ok")->Resolve(), IsError(ERR_IO_PENDING)); - - EXPECT_EQ(3u, num_running_dispatcher_jobs()); - - // Clear DnsClient. The two in-progress jobs should fall back to a ProcTask, - // and the next one should be started with a ProcTask. - resolver_->SetDnsClient(std::unique_ptr<DnsClient>()); - - // All three in-progress requests should now be running a ProcTask. - EXPECT_EQ(3u, num_running_dispatcher_jobs()); - proc_->SignalMultiple(3u); - - EXPECT_THAT(requests_[0]->WaitForResult(), IsOk()); - EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80)); - EXPECT_THAT(requests_[1]->WaitForResult(), IsOk()); - EXPECT_TRUE(requests_[1]->HasOneAddress("192.168.0.2", 80)); - EXPECT_THAT(requests_[2]->WaitForResult(), IsOk()); - EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.0.3", 80)); -} - -// Tests a call to SetDnsClient while there are active DnsTasks. -TEST_F(HostResolverImplDnsTest, - ManuallyDisableDnsClientWithPendingRequests_ResolveHost) { - // At most 3 jobs active at once. This number is important, since we want to - // make sure that aborting the first HostResolverImpl::Job does not trigger - // another DnsTransaction on the second Job when it releases its second - // prioritized dispatcher slot. - CreateResolverWithLimitsAndParams(3u, DefaultParams(proc_.get()), - true /* ipv6_reachable */); - - ChangeDnsConfig(CreateValidDnsConfig()); - - proc_->AddRuleForAllFamilies("slow_ok1", "192.168.0.1"); - proc_->AddRuleForAllFamilies("slow_ok2", "192.168.0.2"); - proc_->AddRuleForAllFamilies("ok", "192.168.0.3"); - std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses; // First active job gets two slots. responses.emplace_back( @@ -6149,95 +4118,6 @@ HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6); proc_->AddRule("h1", ADDRESS_FAMILY_IPV6, "::2"); - CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED); - CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV4); - CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV6); - - // Start all of the requests. - for (size_t i = 0u; i < requests_.size(); ++i) { - EXPECT_THAT(requests_[i]->Resolve(), IsError(ERR_IO_PENDING)) << i; - } - - proc_->SignalMultiple(requests_.size()); - - // Wait for all the requests to complete. - for (size_t i = 0u; i < requests_.size(); ++i) { - EXPECT_THAT(requests_[i]->WaitForResult(), IsOk()) << i; - } - - // Since the requests all had the same priority and we limited the thread - // count to 1, they should have completed in the same order as they were - // requested. - MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList(); - ASSERT_EQ(3u, capture_list.size()); - - EXPECT_EQ("h1", capture_list[0].hostname); - EXPECT_EQ(ADDRESS_FAMILY_IPV4, capture_list[0].address_family); - - EXPECT_EQ("h1", capture_list[1].hostname); - EXPECT_EQ(ADDRESS_FAMILY_IPV4, capture_list[1].address_family); - - EXPECT_EQ("h1", capture_list[2].hostname); - EXPECT_EQ(ADDRESS_FAMILY_IPV6, capture_list[2].address_family); - - // Now check that the correct resolved IP addresses were returned. - EXPECT_TRUE(requests_[0]->HasOneAddress("1.0.0.1", 80)); - EXPECT_TRUE(requests_[1]->HasOneAddress("1.0.0.1", 80)); - EXPECT_TRUE(requests_[2]->HasOneAddress("::2", 80)); - - // Now repeat the test on non-wifi to check that IPv6 is used as normal - // after the network changes. - notifier.mock_network_change_notifier()->SetConnectionType( - NetworkChangeNotifier::CONNECTION_4G); - base::RunLoop().RunUntilIdle(); // Wait for NetworkChangeNotifier. - - CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED); - CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV4); - CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV6); - - // The IPv4 and IPv6 requests are in cache, but the UNSPECIFIED one isn't. - EXPECT_THAT(requests_[3]->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(requests_[4]->Resolve(), IsOk()); - EXPECT_THAT(requests_[5]->Resolve(), IsOk()); - - proc_->SignalMultiple(1); - - EXPECT_THAT(requests_[3]->WaitForResult(), IsOk()); - - // The MockHostResolverProc has only seen one new request. - capture_list = proc_->GetCaptureList(); - ASSERT_EQ(4u, capture_list.size()); - - EXPECT_EQ("h1", capture_list[3].hostname); - EXPECT_EQ(ADDRESS_FAMILY_UNSPECIFIED, capture_list[3].address_family); - - // Now check that the correct resolved IP addresses were returned. - EXPECT_TRUE(requests_[3]->HasOneAddress("::3", 80)); - EXPECT_TRUE(requests_[4]->HasOneAddress("1.0.0.1", 80)); - EXPECT_TRUE(requests_[5]->HasOneAddress("::2", 80)); -} - -TEST_F(HostResolverImplDnsTest, NoIPv6OnWifi_ResolveHost) { - // CreateSerialResolver will destroy the current resolver_ which will attempt - // to remove itself from the NetworkChangeNotifier. If this happens after a - // new NetworkChangeNotifier is active, then it will not remove itself from - // the old NetworkChangeNotifier which is a potential use-after-free. - resolver_ = nullptr; - test::ScopedMockNetworkChangeNotifier notifier; - CreateSerialResolver(); // To guarantee order of resolutions. - resolver_->SetNoIPv6OnWifi(true); - - notifier.mock_network_change_notifier()->SetConnectionType( - NetworkChangeNotifier::CONNECTION_WIFI); - // Needed so IPv6 availability check isn't skipped. - ChangeDnsConfig(CreateValidDnsConfig()); - - proc_->AddRule("h1", ADDRESS_FAMILY_UNSPECIFIED, "::3"); - proc_->AddRule("h1", ADDRESS_FAMILY_IPV4, "1.0.0.1"); - proc_->AddRule("h1", ADDRESS_FAMILY_IPV4, "1.0.0.1", - HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6); - proc_->AddRule("h1", ADDRESS_FAMILY_IPV6, "::2"); - ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair("h1", 80), NetLogWithSource(), base::nullopt)); HostResolver::ResolveHostParameters parameters; @@ -6299,38 +4179,6 @@ CreateResolver(); set_allow_fallback_to_proctask(false); ChangeDnsConfig(CreateValidDnsConfig()); - // NODATA - Request* request = CreateRequest("empty"); - EXPECT_THAT(request->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(request->WaitForResult(), IsError(ERR_NAME_NOT_RESOLVED)); - EXPECT_THAT(request->NumberOfAddresses(), 0); - HostCache::Key key(request->info().hostname(), DnsQueryType::UNSPECIFIED, 0, - HostResolverSource::ANY); - HostCache::EntryStaleness staleness; - const HostCache::Entry* cache_entry = - resolver_->GetHostCache()->Lookup(key, base::TimeTicks::Now()); - EXPECT_TRUE(!!cache_entry); - EXPECT_TRUE(cache_entry->has_ttl()); - EXPECT_THAT(cache_entry->ttl(), base::TimeDelta::FromSeconds(86400)); - - // NXDOMAIN - request = CreateRequest("nodomain"); - EXPECT_THAT(request->Resolve(), IsError(ERR_IO_PENDING)); - EXPECT_THAT(request->WaitForResult(), IsError(ERR_NAME_NOT_RESOLVED)); - EXPECT_THAT(request->NumberOfAddresses(), 0); - HostCache::Key nxkey(request->info().hostname(), DnsQueryType::UNSPECIFIED, 0, - HostResolverSource::ANY); - cache_entry = - resolver_->GetHostCache()->Lookup(nxkey, base::TimeTicks::Now()); - EXPECT_TRUE(!!cache_entry); - EXPECT_TRUE(cache_entry->has_ttl()); - EXPECT_THAT(cache_entry->ttl(), base::TimeDelta::FromSeconds(86400)); -} - -TEST_F(HostResolverImplDnsTest, NotFoundTTL_ResolveHost) { - CreateResolver(); - set_allow_fallback_to_proctask(false); - ChangeDnsConfig(CreateValidDnsConfig()); // NODATA ResolveHostResponseHelper no_data_response(resolver_->CreateRequest( @@ -6400,26 +4248,6 @@ UseMockDnsClient(CreateValidDnsConfig(), std::move(rules)); set_allow_fallback_to_proctask(false); - Request* request = CreateRequest("alias", 80); - EXPECT_THAT(request->Resolve(), IsError(ERR_IO_PENDING)); - ASSERT_THAT(request->WaitForResult(), IsOk()); - - // HostResolver may still give name, but if so, it must be correct. - std::string result_name = request->list().canonical_name(); - EXPECT_TRUE(result_name.empty() || result_name == "canonical"); -} - -TEST_F(HostResolverImplDnsTest, NoCanonicalName_CreateRequest) { - MockDnsClientRuleList rules; - AddDnsRule(&rules, "alias", dns_protocol::kTypeA, IPAddress::IPv4Localhost(), - "canonical", false); - AddDnsRule(&rules, "alias", dns_protocol::kTypeAAAA, - IPAddress::IPv6Localhost(), "canonical", false); - - CreateResolver(); - UseMockDnsClient(CreateValidDnsConfig(), std::move(rules)); - set_allow_fallback_to_proctask(false); - ResolveHostResponseHelper response(resolver_->CreateRequest( HostPortPair("alias", 80), NetLogWithSource(), base::nullopt)); ASSERT_THAT(response.result_error(), IsOk()); @@ -6430,7 +4258,7 @@ EXPECT_TRUE(result_name.empty() || result_name == "canonical"); } -TEST_F(HostResolverImplDnsTest, CanonicalName_CreateRequest) { +TEST_F(HostResolverImplDnsTest, CanonicalName) { MockDnsClientRuleList rules; AddDnsRule(&rules, "alias", dns_protocol::kTypeA, IPAddress::IPv4Localhost(), "canonical", false); @@ -6452,7 +4280,7 @@ "canonical"); } -TEST_F(HostResolverImplDnsTest, CanonicalName_PreferV6_CreateRequest) { +TEST_F(HostResolverImplDnsTest, CanonicalName_PreferV6) { MockDnsClientRuleList rules; AddDnsRule(&rules, "alias", dns_protocol::kTypeA, IPAddress::IPv4Localhost(), "wrong", false); @@ -6476,7 +4304,7 @@ "correct"); } -TEST_F(HostResolverImplDnsTest, CanonicalName_V4Only_CreateRequest) { +TEST_F(HostResolverImplDnsTest, CanonicalName_V4Only) { MockDnsClientRuleList rules; AddDnsRule(&rules, "alias", dns_protocol::kTypeA, IPAddress::IPv4Localhost(), "correct", false);
diff --git a/net/extras/sqlite/sqlite_persistent_cookie_store_unittest.cc b/net/extras/sqlite/sqlite_persistent_cookie_store_unittest.cc index 6f673ab9..656faf6c 100644 --- a/net/extras/sqlite/sqlite_persistent_cookie_store_unittest.cc +++ b/net/extras/sqlite/sqlite_persistent_cookie_store_unittest.cc
@@ -1229,26 +1229,32 @@ std::unique_ptr<CookieMonster> cookie_monster = std::make_unique<CookieMonster>(store_.get(), nullptr, nullptr); cookie_monster->SetCookieableSchemes({"gopher", "http"}); - ResultSavingCookieCallback<bool> set_cookie_callback; + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> + set_cookie_callback; cookie_monster->SetCookieWithOptionsAsync( GURL("gopher://subdomain.gopheriffic.com/page"), "A=B; max-age=3600", CookieOptions(), - base::BindOnce(&ResultSavingCookieCallback<bool>::Run, + base::BindOnce(&ResultSavingCookieCallback< + CanonicalCookie::CookieInclusionStatus>::Run, base::Unretained(&set_cookie_callback))); set_cookie_callback.WaitUntilDone(); - EXPECT_TRUE(set_cookie_callback.result()); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + set_cookie_callback.result()); // Also insert a whole bunch of cookies to slow down the background loading of // all the cookies. for (int i = 0; i < 50; ++i) { - ResultSavingCookieCallback<bool> set_cookie_callback2; + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> + set_cookie_callback2; cookie_monster->SetCookieWithOptionsAsync( GURL(base::StringPrintf("http://example%d.com/", i)), "A=B; max-age=3600", CookieOptions(), - base::BindOnce(&ResultSavingCookieCallback<bool>::Run, + base::BindOnce(&ResultSavingCookieCallback< + CanonicalCookie::CookieInclusionStatus>::Run, base::Unretained(&set_cookie_callback2))); set_cookie_callback2.WaitUntilDone(); - EXPECT_TRUE(set_cookie_callback2.result()); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + set_cookie_callback2.result()); } net::TestClosure flush_closure; @@ -1289,13 +1295,16 @@ std::unique_ptr<CookieMonster> cookie_monster = std::make_unique<CookieMonster>(store_.get(), nullptr, nullptr); - ResultSavingCookieCallback<bool> set_cookie_callback; + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> + set_cookie_callback; cookie_monster->SetCookieWithOptionsAsync( GURL("http://www.example.com/"), "A=B; max-age=3600", CookieOptions(), - base::BindOnce(&ResultSavingCookieCallback<bool>::Run, + base::BindOnce(&ResultSavingCookieCallback< + CanonicalCookie::CookieInclusionStatus>::Run, base::Unretained(&set_cookie_callback))); set_cookie_callback.WaitUntilDone(); - EXPECT_TRUE(set_cookie_callback.result()); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + set_cookie_callback.result()); // Things should commit once going out of scope. }
diff --git a/net/http/http_auth_challenge_tokenizer.cc b/net/http/http_auth_challenge_tokenizer.cc index 7ccd60b2..dfeb632 100644 --- a/net/http/http_auth_challenge_tokenizer.cc +++ b/net/http/http_auth_challenge_tokenizer.cc
@@ -32,7 +32,7 @@ // (See https://bugzilla.mozilla.org/show_bug.cgi?id=230351.) // // Our base64 decoder requires that the length be a multiple of 4. - int encoded_length = params_end_ - params_begin_; + auto encoded_length = params_end_ - params_begin_; while (encoded_length > 0 && encoded_length % 4 != 0 && params_begin_[encoded_length - 1] == '=') { --encoded_length;
diff --git a/net/http/http_network_transaction_unittest.cc b/net/http/http_network_transaction_unittest.cc index b3ac220..580cc8e 100644 --- a/net/http/http_network_transaction_unittest.cc +++ b/net/http/http_network_transaction_unittest.cc
@@ -666,7 +666,7 @@ void CloseIdleSockets() override {} void CloseIdleSocketsInGroup(const std::string& group_name) override {} int IdleSocketCount() const override { return 0; } - int IdleSocketCountInGroup(const std::string& group_name) const override { + size_t IdleSocketCountInGroup(const std::string& group_name) const override { return 0; } LoadState GetLoadState(const std::string& group_name, @@ -13496,18 +13496,15 @@ // and TestRound's created with the default constructor should not be used. struct TestRound { TestRound() - : expected_rv(ERR_UNEXPECTED), - extra_write(NULL), - extra_read(NULL) { - } - TestRound(const MockWrite& write_arg, const MockRead& read_arg, + : expected_rv(ERR_UNEXPECTED), extra_write(NULL), extra_read(NULL) {} + TestRound(const MockWrite& write_arg, + const MockRead& read_arg, int expected_rv_arg) : write(write_arg), read(read_arg), expected_rv(expected_rv_arg), extra_write(NULL), - extra_read(NULL) { - } + extra_read(NULL) {} TestRound(const MockWrite& write_arg, const MockRead& read_arg, int expected_rv_arg, const MockWrite* extra_write_arg, const MockRead* extra_read_arg) @@ -14456,7 +14453,7 @@ response = trans.GetResponseInfo(); ASSERT_TRUE(response); EXPECT_TRUE(response->auth_challenge); - EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup)); + EXPECT_EQ(0u, transport_pool->IdleSocketCountInGroup(kSocketGroup)); EXPECT_EQ(HttpAuthHandlerMock::State::WAIT_FOR_GENERATE_AUTH_TOKEN, auth_handler->state()); @@ -14481,7 +14478,7 @@ response = trans.GetResponseInfo(); ASSERT_TRUE(response); EXPECT_FALSE(response->auth_challenge); - EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup)); + EXPECT_EQ(0u, transport_pool->IdleSocketCountInGroup(kSocketGroup)); EXPECT_EQ(HttpAuthHandlerMock::State::WAIT_FOR_GENERATE_AUTH_TOKEN, auth_handler->state()); @@ -14494,7 +14491,7 @@ response = trans.GetResponseInfo(); ASSERT_TRUE(response); EXPECT_FALSE(response->auth_challenge); - EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup)); + EXPECT_EQ(0u, transport_pool->IdleSocketCountInGroup(kSocketGroup)); EXPECT_EQ(HttpAuthHandlerMock::State::WAIT_FOR_GENERATE_AUTH_TOKEN, auth_handler->state()); @@ -14507,7 +14504,7 @@ response = trans.GetResponseInfo(); ASSERT_TRUE(response); EXPECT_FALSE(response->auth_challenge); - EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup)); + EXPECT_EQ(0u, transport_pool->IdleSocketCountInGroup(kSocketGroup)); // In WAIT_FOR_CHALLENGE, although in reality the auth handler is done. A real // auth handler should transition to a DONE state in concert with the remote @@ -14527,7 +14524,7 @@ EXPECT_EQ(0, rv); // There are still 0 idle sockets, since the trans_compete transaction // will be handed it immediately after trans releases it to the group. - EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup)); + EXPECT_EQ(0u, transport_pool->IdleSocketCountInGroup(kSocketGroup)); // The competing request can now finish. Wait for the headers and then // read the body. @@ -14541,7 +14538,7 @@ EXPECT_EQ(0, rv); // Finally, the socket is released to the group. - EXPECT_EQ(1, transport_pool->IdleSocketCountInGroup(kSocketGroup)); + EXPECT_EQ(1u, transport_pool->IdleSocketCountInGroup(kSocketGroup)); } // This tests the case that a request is issued via http instead of spdy after
diff --git a/net/http/http_proxy_client_socket_wrapper.cc b/net/http/http_proxy_client_socket_wrapper.cc index 8ab8d6f..f128a49 100644 --- a/net/http/http_proxy_client_socket_wrapper.cc +++ b/net/http/http_proxy_client_socket_wrapper.cc
@@ -793,16 +793,8 @@ if (reconnect) { // Attempt to create a new one. transport_socket_.reset(); - - // Reconnect with HIGHEST priority to get in front of other requests that - // don't yet have the information |http_auth_controller_| does. - // TODO(mmenke): This may still result in waiting in line, if there are - // other HIGHEST priority requests. Consider a workaround for - // that. Starting the new request before releasing the old - // socket and using RespectLimits::Disabled would work, - // without exceding the the socket pool limits (Since the old - // socket would free up the extra socket slot when destroyed). - priority_ = HIGHEST; + using_spdy_ = false; + negotiated_protocol_ = NextProto(); next_state_ = STATE_BEGIN_CONNECT; return OK; }
diff --git a/net/http/http_server_properties_impl_unittest.cc b/net/http/http_server_properties_impl_unittest.cc index 32b67392..5ae3d35 100644 --- a/net/http/http_server_properties_impl_unittest.cc +++ b/net/http/http_server_properties_impl_unittest.cc
@@ -1185,7 +1185,7 @@ FastForwardBy(BROKEN_ALT_SVC_EXPIRE_DELAYS[i]); // Ensure brokenness of |alternative_service1| has expired. - EXPECT_FALSE(MainThreadHasPendingTask()); + EXPECT_EQ(0u, GetPendingMainThreadTaskCount()); EXPECT_FALSE(impl_.IsAlternativeServiceBroken(alternative_service1)); }
diff --git a/net/http/http_server_properties_manager_unittest.cc b/net/http/http_server_properties_manager_unittest.cc index 4238c04..7a78852 100644 --- a/net/http/http_server_properties_manager_unittest.cc +++ b/net/http/http_server_properties_manager_unittest.cc
@@ -121,7 +121,7 @@ EXPECT_FALSE(http_server_props_manager_->IsInitialized()); pref_delegate_->SetPrefs(base::DictionaryValue()); EXPECT_TRUE(http_server_props_manager_->IsInitialized()); - EXPECT_FALSE(MainThreadHasPendingTask()); + EXPECT_EQ(0u, GetPendingMainThreadTaskCount()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); } @@ -277,7 +277,7 @@ pref_delegate_->SetPrefs(http_server_properties_dict); // Should be a delayed task to update the cache from the prefs file. - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); // Verify SupportsSpdy. @@ -401,7 +401,7 @@ pref_delegate_->SetPrefs(http_server_properties_dict); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); // Prefs should have been overwritten, due to the bad data. EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); @@ -463,7 +463,7 @@ pref_delegate_->SetPrefs(http_server_properties_dict); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); // Prefs should have been overwritten, due to the bad data. EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); @@ -485,7 +485,7 @@ // Run the task. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); @@ -493,7 +493,7 @@ // update. http_server_props_manager_->SetSupportsSpdy(spdy_server, true); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_FALSE(MainThreadHasPendingTask()); + EXPECT_EQ(0u, GetPendingMainThreadTaskCount()); EXPECT_TRUE(http_server_props_manager_->SupportsRequestPriority(spdy_server)); } @@ -527,7 +527,7 @@ EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); FastForwardBy(base::TimeDelta::FromMilliseconds(20)); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_FALSE(MainThreadHasPendingTask()); + EXPECT_EQ(0u, GetPendingMainThreadTaskCount()); EXPECT_TRUE(http_server_props_manager_->SupportsRequestPriority(spdy_server)); EXPECT_TRUE( @@ -558,7 +558,7 @@ // Run the task. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); @@ -611,7 +611,7 @@ http_server_props_manager_->SetAlternativeServices( spdy_server_mail, AlternativeServiceInfoVector()); - EXPECT_FALSE(MainThreadHasPendingTask()); + EXPECT_EQ(0u, GetPendingMainThreadTaskCount()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_FALSE(HasAlternativeService(spdy_server_mail)); @@ -653,7 +653,7 @@ EXPECT_EQ(2u, GetPendingMainThreadTaskCount()); // Run the task. - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); @@ -702,7 +702,7 @@ EXPECT_EQ(2u, GetPendingMainThreadTaskCount()); // Run the task. - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); @@ -751,7 +751,7 @@ EXPECT_EQ(2u, GetPendingMainThreadTaskCount()); // Run the task. - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); @@ -797,7 +797,7 @@ EXPECT_EQ(2u, GetPendingMainThreadTaskCount()); // Run the task. - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); @@ -818,7 +818,7 @@ // Run the task. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); @@ -828,7 +828,7 @@ // Another task should not be scheduled. http_server_props_manager_->SetSupportsQuic(true, actual_address); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_FALSE(MainThreadHasPendingTask()); + EXPECT_EQ(0u, GetPendingMainThreadTaskCount()); } TEST_P(HttpServerPropertiesManagerTest, ServerNetworkStats) { @@ -844,14 +844,14 @@ // Run the task. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); // Another task should not be scheduled. http_server_props_manager_->SetServerNetworkStats(mail_server, stats1); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_FALSE(MainThreadHasPendingTask()); + EXPECT_EQ(GetPendingMainThreadTaskCount(), 0u); const ServerNetworkStats* stats2 = http_server_props_manager_->GetServerNetworkStats(mail_server); @@ -861,7 +861,7 @@ // Run the task. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); @@ -882,7 +882,7 @@ // Run the task. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); @@ -893,7 +893,7 @@ http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id, quic_server_info1); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_FALSE(MainThreadHasPendingTask()); + EXPECT_EQ(0u, GetPendingMainThreadTaskCount()); } TEST_P(HttpServerPropertiesManagerTest, Clear) { @@ -930,7 +930,7 @@ // Advance time by just enough so that the prefs update task is executed but // not the task to expire the brokenness of |broken_alternative_service|. FastForwardBy(HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting()); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( @@ -1230,7 +1230,7 @@ // Since this test has no pref corruption, there shouldn't be any pref update. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_FALSE(MainThreadHasPendingTask()); + EXPECT_EQ(0u, GetPendingMainThreadTaskCount()); // Schedule one more cache update. The task should be successfully scheduled // on the task runner. @@ -1487,7 +1487,7 @@ // Update Prefs. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); @@ -1590,7 +1590,7 @@ // Update Prefs. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); @@ -1625,7 +1625,7 @@ // Update Prefs. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); @@ -1654,7 +1654,7 @@ server_www, alternative_service_info_vector_3)); // No Prefs update. - EXPECT_FALSE(MainThreadHasPendingTask()); + EXPECT_EQ(0u, GetPendingMainThreadTaskCount()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); } @@ -1672,11 +1672,11 @@ cached_recently_broken_service); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); // Run the prefs update task but not the expiration task for // |cached_broken_service|. FastForwardBy(HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting()); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); // Load the |pref_delegate_| with some JSON to verify updating the cache from @@ -1730,11 +1730,11 @@ pref_delegate_->SetPrefs(*server_dict); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); // Run the cache update task but not the expiration task for // |cached_broken_service|. FastForwardBy(NextMainThreadPendingTaskDelay()); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); // // Verify alternative service info for https://www.google.com @@ -1848,7 +1848,7 @@ http_server_props_manager_->MarkAlternativeServiceBroken( prefs_broken_service); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardBy(base::TimeDelta::FromMinutes(10) - base::TimeDelta::FromInternalValue(1)); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( @@ -1860,7 +1860,7 @@ // when marked broken. http_server_props_manager_->MarkAlternativeServiceBroken( cached_recently_broken_service); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardBy(base::TimeDelta::FromMinutes(40) - base::TimeDelta::FromInternalValue(1)); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( @@ -1872,7 +1872,7 @@ // marked broken. http_server_props_manager_->MarkAlternativeServiceBroken( cached_broken_service); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardBy(base::TimeDelta::FromMinutes(20) - base::TimeDelta::FromInternalValue(1)); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( @@ -1884,7 +1884,7 @@ // marked broken. http_server_props_manager_->MarkAlternativeServiceBroken( cached_broken_service2); - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); FastForwardBy(base::TimeDelta::FromMinutes(10) - base::TimeDelta::FromInternalValue(1)); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken(
diff --git a/net/http/http_stream_factory_job_controller_unittest.cc b/net/http/http_stream_factory_job_controller_unittest.cc index 48b6a89..7741fa0 100644 --- a/net/http/http_stream_factory_job_controller_unittest.cc +++ b/net/http/http_stream_factory_job_controller_unittest.cc
@@ -1708,7 +1708,7 @@ session_deps_.host_resolver->ResolveAllPending(); // Task to resume main job in 15 microseconds should be posted. - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); EXPECT_CALL(*job_factory_.main_job(), Resume()).Times(0); FastForwardBy(base::TimeDelta::FromMicroseconds(14)); EXPECT_CALL(*job_factory_.main_job(), Resume()).Times(1); @@ -1774,7 +1774,7 @@ EXPECT_FALSE(JobControllerPeer::main_job_is_resumed(job_controller_)); // Task to resume main job in 15us should be posted. - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); EXPECT_CALL(*job_factory_.main_job(), Resume()).Times(0); FastForwardBy(base::TimeDelta::FromMicroseconds(14)); EXPECT_CALL(*job_factory_.main_job(), Resume()).Times(1); @@ -1913,7 +1913,7 @@ EXPECT_FALSE(JobControllerPeer::main_job_is_resumed(job_controller_)); // Task to resume main job in 3 seconds should be posted. - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); EXPECT_CALL(*job_factory_.main_job(), Resume()).Times(0); FastForwardBy(kMaxDelayTimeForMainJob - base::TimeDelta::FromMicroseconds(1)); EXPECT_CALL(*job_factory_.main_job(), Resume()).Times(1); @@ -1973,7 +1973,7 @@ EXPECT_FALSE(JobControllerPeer::main_job_is_resumed(job_controller_)); // Task to resume main job in 15us should be posted. - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); EXPECT_CALL(*job_factory_.main_job(), Resume()).Times(0); FastForwardBy(base::TimeDelta::FromMicroseconds(1)); @@ -1990,7 +1990,7 @@ // Verify there is another task to resume main job with delay but should // not call Resume() on the main job as main job has been resumed. - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); EXPECT_CALL(*job_factory_.main_job(), Resume()).Times(0); FastForwardBy(base::TimeDelta::FromMicroseconds(15)); @@ -2094,7 +2094,7 @@ EXPECT_FALSE(JobControllerPeer::main_job_is_resumed(job_controller_)); // Task to resume main job in 15us should be posted. - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_NE(0u, GetPendingMainThreadTaskCount()); EXPECT_CALL(*job_factory_.main_job(), Resume()).Times(0); FastForwardBy(base::TimeDelta::FromMicroseconds(14)); EXPECT_CALL(*job_factory_.main_job(), Resume()).Times(1); @@ -2452,7 +2452,7 @@ EXPECT_CALL(*request_delegates[i].get(), OnStreamReadyImpl(_, _, _)); } - EXPECT_TRUE(MainThreadHasPendingTask()); + EXPECT_GT(GetPendingMainThreadTaskCount(), 0u); FastForwardBy(base::TimeDelta::FromMilliseconds( HttpStreamFactory::Job::kHTTP2ThrottleMs)); base::RunLoop().RunUntilIdle();
diff --git a/net/http/http_stream_factory_unittest.cc b/net/http/http_stream_factory_unittest.cc index 83ace9c0..db1c5665 100644 --- a/net/http/http_stream_factory_unittest.cc +++ b/net/http/http_stream_factory_unittest.cc
@@ -443,7 +443,7 @@ ADD_FAILURE(); return 0; } - int IdleSocketCountInGroup(const std::string& group_name) const override { + size_t IdleSocketCountInGroup(const std::string& group_name) const override { ADD_FAILURE(); return 0; }
diff --git a/net/http/http_stream_parser.cc b/net/http/http_stream_parser.cc index 95a2c9f9..786ff57 100644 --- a/net/http/http_stream_parser.cc +++ b/net/http/http_stream_parser.cc
@@ -820,12 +820,12 @@ // Accepting truncated headers over HTTPS is a potential security // vulnerability, so just return an error in that case. // - // If response_header_start_offset_ is -1, this may be a < 8 byte HTTP/0.9 - // response. However, accepting such a response over HTTPS would allow a - // MITM to truncate an HTTP/1.x status line to look like a short HTTP/0.9 - // response if the peer put a record boundary at the first 8 bytes. To - // ensure that all response headers received over HTTPS are pristine, treat - // such responses as errors. + // If response_header_start_offset_ is -1, this may be a < 8 + // byte HTTP/0.9 response. However, accepting such a response over HTTPS + // would allow a MITM to truncate an HTTP/1.x status line to look like a + // short HTTP/0.9 response if the peer put a record boundary at the first 8 + // bytes. To ensure that all response headers received over HTTPS are + // pristine, treat such responses as errors. // // TODO(mmenke): Returning ERR_RESPONSE_HEADERS_TRUNCATED when a response // looks like an HTTP/0.9 response is weird. Should either come up with
diff --git a/net/http/http_util.cc b/net/http/http_util.cc index 23b71d0..2baf637 100644 --- a/net/http/http_util.cc +++ b/net/http/http_util.cc
@@ -817,8 +817,8 @@ AcceptLanguageBuilder builder; - const int size = languages.size(); - for (int i = 0; i < size; ++i) { + const size_t size = languages.size(); + for (size_t i = 0; i < size; ++i) { const std::string& language = languages[i]; builder.AddLanguageCode(language); @@ -827,7 +827,7 @@ // Look ahead and add the base language if the next language is not part // of the same family. - const int j = i + 1; + const size_t j = i + 1; if (j >= size || GetBaseLanguageCode(languages[j]) != base_language) { builder.AddLanguageCode(base_language); }
diff --git a/net/http/http_util.h b/net/http/http_util.h index cf007043..bb34abc6 100644 --- a/net/http/http_util.h +++ b/net/http/http_util.h
@@ -164,6 +164,7 @@ // Returns the start of the status line, or -1 if no status line was found. // This allows for 4 bytes of junk to precede the status line (which is what // mozilla does too). + // TODO(921389): Convert this to return size_t. static int LocateStartOfStatusLine(const char* buf, int buf_len); // Returns index beyond the end-of-headers marker or -1 if not found. RFC @@ -173,12 +174,14 @@ // as end-of-headers (just like Mozilla). The first line of |buf| is // considered the status line, even if empty. // The parameter |i| is the offset within |buf| to begin searching from. + // TODO(921389): Convert this to return size_t. static int LocateEndOfHeaders(const char* buf, int buf_len, int i = 0); // Same as |LocateEndOfHeaders|, but does not expect a status line, so can be // used on multi-part responses or HTTP/1.x trailers. As a result, if |buf| // starts with a single [CR]LF, it is considered an empty header list, as // opposed to an empty status line above a header list. + // TODO(921389): Convert this to return size_t. static int LocateEndOfAdditionalHeaders(const char* buf, int buf_len, int i = 0);
diff --git a/net/http/http_util_unittest.cc b/net/http/http_util_unittest.cc index 7883b3e4..53eefb4 100644 --- a/net/http/http_util_unittest.cc +++ b/net/http/http_util_unittest.cc
@@ -342,7 +342,7 @@ {"foo\nbar\r\n\njunk", 10}, }; for (size_t i = 0; i < base::size(tests); ++i) { - int input_len = static_cast<int>(strlen(tests[i].input)); + size_t input_len = strlen(tests[i].input); int eoh = HttpUtil::LocateEndOfHeaders(tests[i].input, input_len); EXPECT_EQ(tests[i].expected_result, eoh); } @@ -366,7 +366,7 @@ {"foo\nbar\r\n\njunk", 10}, }; for (size_t i = 0; i < base::size(tests); ++i) { - int input_len = static_cast<int>(strlen(tests[i].input)); + size_t input_len = strlen(tests[i].input); int eoh = HttpUtil::LocateEndOfAdditionalHeaders(tests[i].input, input_len); EXPECT_EQ(tests[i].expected_result, eoh); }
diff --git a/net/quic/quic_proxy_client_socket.cc b/net/quic/quic_proxy_client_socket.cc index c21ee5c..e0e22c7 100644 --- a/net/quic/quic_proxy_client_socket.cc +++ b/net/quic/quic_proxy_client_socket.cc
@@ -68,7 +68,7 @@ // stream may not be reused and a new QuicProxyClientSocket must be // created (possibly on top of the same QUIC Session). next_state_ = STATE_DISCONNECTED; - return OK; + return ERR_UNABLE_TO_REUSE_CONNECTION_FOR_PROXY_AUTH; } bool QuicProxyClientSocket::IsUsingSpdy() const {
diff --git a/net/reporting/reporting_uploader_unittest.cc b/net/reporting/reporting_uploader_unittest.cc index 1cf86c90..b9b4174 100644 --- a/net/reporting/reporting_uploader_unittest.cc +++ b/net/reporting/reporting_uploader_unittest.cc
@@ -440,13 +440,16 @@ server_.RegisterRequestHandler(base::BindRepeating(&ReturnResponse, HTTP_OK)); ASSERT_TRUE(server_.Start()); - ResultSavingCookieCallback<bool> cookie_callback; + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> + cookie_callback; context_.cookie_store()->SetCookieWithOptionsAsync( server_.GetURL("/"), "foo=bar", CookieOptions(), - base::BindRepeating(&ResultSavingCookieCallback<bool>::Run, + base::BindRepeating(&ResultSavingCookieCallback< + CanonicalCookie::CookieInclusionStatus>::Run, base::Unretained(&cookie_callback))); cookie_callback.WaitUntilDone(); - ASSERT_TRUE(cookie_callback.result()); + ASSERT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + cookie_callback.result()); TestUploadCallback upload_callback; uploader_->StartUpload(kOrigin, server_.GetURL("/"), kUploadBody, 0,
diff --git a/net/socket/client_socket_pool.h b/net/socket/client_socket_pool.h index 7894baf..40aba7e 100644 --- a/net/socket/client_socket_pool.h +++ b/net/socket/client_socket_pool.h
@@ -170,7 +170,8 @@ virtual int IdleSocketCount() const = 0; // The total number of idle sockets in a connection group. - virtual int IdleSocketCountInGroup(const std::string& group_name) const = 0; + virtual size_t IdleSocketCountInGroup( + const std::string& group_name) const = 0; // Determine the LoadState of a connecting ClientSocketHandle. virtual LoadState GetLoadState(const std::string& group_name,
diff --git a/net/socket/client_socket_pool_base.cc b/net/socket/client_socket_pool_base.cc index 77bbb4a6..35ce507 100644 --- a/net/socket/client_socket_pool_base.cc +++ b/net/socket/client_socket_pool_base.cc
@@ -530,7 +530,7 @@ RemoveGroup(it); } -int ClientSocketPoolBaseHelper::IdleSocketCountInGroup( +size_t ClientSocketPoolBaseHelper::IdleSocketCountInGroup( const std::string& group_name) const { auto i = group_map_.find(group_name); CHECK(i != group_map_.end());
diff --git a/net/socket/client_socket_pool_base.h b/net/socket/client_socket_pool_base.h index 90cbb92..ce53dca 100644 --- a/net/socket/client_socket_pool_base.h +++ b/net/socket/client_socket_pool_base.h
@@ -218,7 +218,7 @@ // See ClientSocketPool::IdleSocketCountInGroup() for documentation on this // function. - int IdleSocketCountInGroup(const std::string& group_name) const; + size_t IdleSocketCountInGroup(const std::string& group_name) const; // See ClientSocketPool::GetLoadState() for documentation on this function. LoadState GetLoadState(const std::string& group_name, @@ -231,15 +231,16 @@ ClientSocketPool::kMaxConnectRetryIntervalMs); } - int NumNeverAssignedConnectJobsInGroup(const std::string& group_name) const { + size_t NumNeverAssignedConnectJobsInGroup( + const std::string& group_name) const { return group_map_.find(group_name)->second->never_assigned_job_count(); } - int NumUnassignedConnectJobsInGroup(const std::string& group_name) const { + size_t NumUnassignedConnectJobsInGroup(const std::string& group_name) const { return group_map_.find(group_name)->second->unassigned_job_count(); } - int NumConnectJobsInGroup(const std::string& group_name) const { + size_t NumConnectJobsInGroup(const std::string& group_name) const { return group_map_.find(group_name)->second->jobs().size(); } @@ -806,7 +807,7 @@ int idle_socket_count() const { return helper_.idle_socket_count(); } - int IdleSocketCountInGroup(const std::string& group_name) const { + size_t IdleSocketCountInGroup(const std::string& group_name) const { return helper_.IdleSocketCountInGroup(group_name); } @@ -824,15 +825,16 @@ return helper_.OnConnectJobComplete(result, job); } - int NumNeverAssignedConnectJobsInGroup(const std::string& group_name) const { + size_t NumNeverAssignedConnectJobsInGroup( + const std::string& group_name) const { return helper_.NumNeverAssignedConnectJobsInGroup(group_name); } - int NumUnassignedConnectJobsInGroup(const std::string& group_name) const { + size_t NumUnassignedConnectJobsInGroup(const std::string& group_name) const { return helper_.NumUnassignedConnectJobsInGroup(group_name); } - int NumConnectJobsInGroup(const std::string& group_name) const { + size_t NumConnectJobsInGroup(const std::string& group_name) const { return helper_.NumConnectJobsInGroup(group_name); }
diff --git a/net/socket/client_socket_pool_base_unittest.cc b/net/socket/client_socket_pool_base_unittest.cc index 164b7f8..b63f49d 100644 --- a/net/socket/client_socket_pool_base_unittest.cc +++ b/net/socket/client_socket_pool_base_unittest.cc
@@ -514,8 +514,7 @@ : job_type_(TestConnectJob::kMockJob), job_types_(NULL), client_socket_factory_(client_socket_factory), - net_log_(net_log) { - } + net_log_(net_log) {} ~TestConnectJobFactory() override = default; @@ -630,7 +629,7 @@ int IdleSocketCount() const override { return base_.idle_socket_count(); } - int IdleSocketCountInGroup(const std::string& group_name) const override { + size_t IdleSocketCountInGroup(const std::string& group_name) const override { return base_.IdleSocketCountInGroup(group_name); } @@ -656,15 +655,16 @@ const TestClientSocketPoolBase* base() const { return &base_; } - int NumNeverAssignedConnectJobsInGroup(const std::string& group_name) const { + size_t NumNeverAssignedConnectJobsInGroup( + const std::string& group_name) const { return base_.NumNeverAssignedConnectJobsInGroup(group_name); } - int NumUnassignedConnectJobsInGroup(const std::string& group_name) const { + size_t NumUnassignedConnectJobsInGroup(const std::string& group_name) const { return base_.NumUnassignedConnectJobsInGroup(group_name); } - int NumConnectJobsInGroup(const std::string& group_name) const { + size_t NumConnectJobsInGroup(const std::string& group_name) const { return base_.NumConnectJobsInGroup(group_name); } @@ -1268,17 +1268,17 @@ NetLogWithSource())); // Since it is stalled, it should have no connect jobs. - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("foo")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("foo")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("foo")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("foo")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("foo")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("foo")); // Cancel the stalled request. handles[0].Reset(); // Now we should have a connect job. - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("foo")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("foo")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("foo")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("foo")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("foo")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("foo")); // The stalled socket should connect. EXPECT_THAT(callback.WaitForResult(), IsOk()); @@ -1286,9 +1286,9 @@ EXPECT_EQ(kDefaultMaxSockets + 1, client_socket_factory_.allocation_count()); EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("foo")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("foo")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("foo")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("foo")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("foo")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("foo")); // Dropping out of scope will close all handles and return them to idle. } @@ -1770,7 +1770,7 @@ // Closing idle sockets should not get us into trouble, but in the bug // we were hitting a CHECK here. - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); pool_->CloseIdleSockets(); // Run the released socket wakeups. @@ -1906,16 +1906,20 @@ EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING)); EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING)); - EXPECT_EQ(kDefaultMaxSocketsPerGroup, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(kDefaultMaxSocketsPerGroup, + static_cast<int>(pool_->NumConnectJobsInGroup("a"))); (*requests())[2]->handle()->Reset(); (*requests())[3]->handle()->Reset(); - EXPECT_EQ(kDefaultMaxSocketsPerGroup, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(kDefaultMaxSocketsPerGroup, + static_cast<int>(pool_->NumConnectJobsInGroup("a"))); (*requests())[1]->handle()->Reset(); - EXPECT_EQ(kDefaultMaxSocketsPerGroup, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(kDefaultMaxSocketsPerGroup, + static_cast<int>(pool_->NumConnectJobsInGroup("a"))); (*requests())[0]->handle()->Reset(); - EXPECT_EQ(kDefaultMaxSocketsPerGroup, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(kDefaultMaxSocketsPerGroup, + static_cast<int>(pool_->NumConnectJobsInGroup("a"))); } // When requests and ConnectJobs are not coupled, the request will get serviced @@ -1965,11 +1969,11 @@ client_socket_factory_.SignalJobs(); EXPECT_THAT(req3.WaitForResult(), IsOk()); - ASSERT_EQ(3U, request_order.size()); + ASSERT_EQ(3u, request_order.size()); EXPECT_EQ(&req1, request_order[0]); EXPECT_EQ(&req2, request_order[1]); EXPECT_EQ(&req3, request_order[2]); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); } // The requests are not coupled to the jobs. So, the requests should finish in @@ -2007,7 +2011,7 @@ EXPECT_THAT(req2.WaitForResult(), IsOk()); EXPECT_THAT(req3.WaitForResult(), IsError(ERR_CONNECTION_FAILED)); - ASSERT_EQ(3U, request_order.size()); + ASSERT_EQ(3u, request_order.size()); EXPECT_EQ(&req1, request_order[0]); EXPECT_EQ(&req2, request_order[1]); EXPECT_EQ(&req3, request_order[2]); @@ -2294,7 +2298,7 @@ TestLoadTimingInfoConnectedReused(handle); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); TestNetLogEntry::List entries; @@ -2364,7 +2368,7 @@ // Make sure the idle socket is closed. ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); TestNetLogEntry::List entries; @@ -2810,9 +2814,9 @@ ClientSocketPool::RespectLimits::ENABLED, callback.callback(), pool_.get(), NetLogWithSource())); ASSERT_TRUE(pool_->HasGroup("bar")); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("bar")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("bar")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("bar")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("bar")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("bar")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("bar")); // Cancel the socket request. This should cancel the backup timer. Wait for // the backup time to see if it indeed got canceled. @@ -2821,7 +2825,7 @@ FastForwardBy(base::TimeDelta::FromMilliseconds( ClientSocketPool::kMaxConnectRetryIntervalMs / 2 * 3)); ASSERT_TRUE(pool_->HasGroup("bar")); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("bar")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("bar")); } TEST_F(ClientSocketPoolBaseTest, CancelBackupSocketAfterFinishingAllRequests) { @@ -2846,7 +2850,7 @@ ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), pool_.get(), NetLogWithSource())); ASSERT_TRUE(pool_->HasGroup("bar")); - EXPECT_EQ(2, pool_->NumConnectJobsInGroup("bar")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("bar")); // Cancel request 1 and then complete request 2. With the requests finished, // the backup timer should be cancelled. @@ -2875,7 +2879,7 @@ // No idle sockets, no pending jobs. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); // Create a second socket to the same host, but this one will wait. connect_job_factory_->set_job_type(TestConnectJob::kMockWaitingJob); @@ -2886,7 +2890,7 @@ callback.callback(), pool_.get(), NetLogWithSource())); // No idle sockets, and one connecting job. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); // Return the first handle to the pool. This will initiate the delayed // binding. @@ -2896,17 +2900,17 @@ // Still no idle sockets, still one pending connect job. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); // The second socket connected, even though it was a Waiting Job. EXPECT_THAT(callback.WaitForResult(), IsOk()); // And we can see there is still one job waiting. - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); // Finally, signal the waiting Connect. client_socket_factory_.SignalJobs(); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); base::RunLoop().RunUntilIdle(); } @@ -2927,7 +2931,7 @@ // No idle sockets, no pending jobs. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); // Create a second socket to the same host, but this one will wait. connect_job_factory_->set_job_type(TestConnectJob::kMockWaitingJob); @@ -2938,7 +2942,7 @@ callback.callback(), pool_.get(), NetLogWithSource())); // No idle sockets, and one connecting job. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); // Return the first handle to the pool. This will initiate the delayed // binding. @@ -2948,17 +2952,17 @@ // Still no idle sockets, still one pending connect job. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); // The second socket connected, even though it was a Waiting Job. EXPECT_THAT(callback.WaitForResult(), IsOk()); // And we can see there is still one job waiting. - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); // Finally, signal the waiting Connect. client_socket_factory_.SignalJobs(); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); base::RunLoop().RunUntilIdle(); } @@ -2981,7 +2985,7 @@ // No idle sockets, no pending jobs. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); // Create a second socket to the same host, but this one will wait. connect_job_factory_->set_job_type(TestConnectJob::kMockWaitingJob); @@ -2992,7 +2996,7 @@ callback.callback(), pool_.get(), NetLogWithSource())); // No idle sockets, and one connecting job. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); // Return the first handle to the pool. This will initiate the delayed // binding. @@ -3002,17 +3006,17 @@ // Still no idle sockets, still one pending connect job. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); // The second socket connected, even though it was a Waiting Job. EXPECT_THAT(callback.WaitForResult(), IsOk()); // And we can see there is still one job waiting. - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); // Finally, signal the waiting Connect. client_socket_factory_.SignalJobs(); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); base::RunLoop().RunUntilIdle(); } @@ -3035,7 +3039,7 @@ handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); // Make the second request synchronously fail. This should make the Group // empty. @@ -3050,7 +3054,7 @@ ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); EXPECT_THAT(callback1.WaitForResult(), IsError(ERR_CONNECTION_FAILED)); EXPECT_THAT(callback2.WaitForResult(), IsError(ERR_CONNECTION_FAILED)); @@ -3124,10 +3128,10 @@ pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(2, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(2, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(2, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(2u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(2u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); ClientSocketHandle handle1; TestCompletionCallback callback1; @@ -3145,20 +3149,20 @@ ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(2, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_THAT(callback1.WaitForResult(), IsOk()); EXPECT_THAT(callback2.WaitForResult(), IsOk()); handle1.Reset(); handle2.Reset(); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(2, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(2u, pool_->IdleSocketCountInGroup("a")); } TEST_F(ClientSocketPoolBaseTest, RequestSocketsWhenAlreadyHaveAConnectJob) { @@ -3174,17 +3178,17 @@ callback1.callback(), pool_.get(), NetLogWithSource())); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(2, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); ClientSocketHandle handle2; TestCompletionCallback callback2; @@ -3194,20 +3198,20 @@ ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(2, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_THAT(callback1.WaitForResult(), IsOk()); EXPECT_THAT(callback2.WaitForResult(), IsOk()); handle1.Reset(); handle2.Reset(); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(2, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(2u, pool_->IdleSocketCountInGroup("a")); } TEST_F(ClientSocketPoolBaseTest, @@ -3240,17 +3244,17 @@ callback3.callback(), pool_.get(), NetLogWithSource())); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(3, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(3u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(3, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(3u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_THAT(callback1.WaitForResult(), IsOk()); EXPECT_THAT(callback2.WaitForResult(), IsOk()); @@ -3259,10 +3263,10 @@ handle2.Reset(); handle3.Reset(); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(3, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(3u, pool_->IdleSocketCountInGroup("a")); } TEST_F(ClientSocketPoolBaseTest, RequestSocketsAtMaxSocketLimit) { @@ -3274,9 +3278,12 @@ pool_->RequestSockets("a", ¶ms_, kDefaultMaxSockets, NetLogWithSource()); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(kDefaultMaxSockets, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(kDefaultMaxSockets, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(kDefaultMaxSockets, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(kDefaultMaxSockets, + static_cast<int>(pool_->NumConnectJobsInGroup("a"))); + EXPECT_EQ(kDefaultMaxSockets, + static_cast<int>(pool_->NumNeverAssignedConnectJobsInGroup("a"))); + EXPECT_EQ(kDefaultMaxSockets, + static_cast<int>(pool_->NumUnassignedConnectJobsInGroup("a"))); ASSERT_FALSE(pool_->HasGroup("b")); @@ -3295,11 +3302,12 @@ NetLogWithSource()); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(kDefaultMaxSockets - 1, pool_->NumConnectJobsInGroup("a")); EXPECT_EQ(kDefaultMaxSockets - 1, - pool_->NumNeverAssignedConnectJobsInGroup("a")); + static_cast<int>(pool_->NumConnectJobsInGroup("a"))); EXPECT_EQ(kDefaultMaxSockets - 1, - pool_->NumUnassignedConnectJobsInGroup("a")); + static_cast<int>(pool_->NumNeverAssignedConnectJobsInGroup("a"))); + EXPECT_EQ(kDefaultMaxSockets - 1, + static_cast<int>(pool_->NumUnassignedConnectJobsInGroup("a"))); EXPECT_FALSE(pool_->IsStalled()); ASSERT_FALSE(pool_->HasGroup("b")); @@ -3307,7 +3315,7 @@ pool_->RequestSockets("b", ¶ms_, kDefaultMaxSockets, NetLogWithSource()); ASSERT_TRUE(pool_->HasGroup("b")); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("b")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("b")); EXPECT_FALSE(pool_->IsStalled()); } @@ -3326,17 +3334,17 @@ handle1.Reset(); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); } TEST_F(ClientSocketPoolBaseTest, RequestSocketsCountActiveSockets) { @@ -3353,18 +3361,18 @@ ASSERT_THAT(callback1.WaitForResult(), IsOk()); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); } @@ -3376,18 +3384,20 @@ NetLogWithSource()); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(kDefaultMaxSocketsPerGroup, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(kDefaultMaxSocketsPerGroup, + static_cast<int>(pool_->IdleSocketCountInGroup("a"))); pool_->RequestSockets("b", ¶ms_, kDefaultMaxSocketsPerGroup, NetLogWithSource()); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("b")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("b")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("b")); - EXPECT_EQ(kDefaultMaxSocketsPerGroup, pool_->IdleSocketCountInGroup("b")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("b")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("b")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("b")); + EXPECT_EQ(kDefaultMaxSocketsPerGroup, + static_cast<int>(pool_->IdleSocketCountInGroup("b"))); } TEST_F(ClientSocketPoolBaseTest, RequestSocketsSynchronousError) { @@ -3414,18 +3424,18 @@ pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(2, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(2, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(2, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(2u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(2u, pool_->NumUnassignedConnectJobsInGroup("a")); EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(2, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(2, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(2, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(2u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(2u, pool_->NumUnassignedConnectJobsInGroup("a")); EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); ClientSocketHandle handle1; TestCompletionCallback callback1; @@ -3438,11 +3448,11 @@ client_socket_factory_.SignalJob(0); EXPECT_THAT(callback1.WaitForResult(), IsOk()); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); ClientSocketHandle handle2; TestCompletionCallback callback2; @@ -3454,27 +3464,27 @@ client_socket_factory_.SignalJob(0); EXPECT_THAT(callback2.WaitForResult(), IsOk()); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); EXPECT_EQ(2, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); handle1.Reset(); handle2.Reset(); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(2, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(2u, pool_->IdleSocketCountInGroup("a")); pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(2, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(2u, pool_->IdleSocketCountInGroup("a")); } TEST_F(ClientSocketPoolBaseTest, RequestSocketsDifferentNumSockets) { @@ -3484,28 +3494,28 @@ pool_->RequestSockets("a", ¶ms_, 1, NetLogWithSource()); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(2, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(2, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(2, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(2u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(2u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); pool_->RequestSockets("a", ¶ms_, 3, NetLogWithSource()); - EXPECT_EQ(3, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(3, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(3, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(3u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(3u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(3u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); pool_->RequestSockets("a", ¶ms_, 1, NetLogWithSource()); - EXPECT_EQ(3, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(3, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(3, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(3u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(3u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(3u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); } TEST_F(ClientSocketPoolBaseTest, PreconnectJobsTakenByNormalRequests) { @@ -3515,10 +3525,10 @@ pool_->RequestSockets("a", ¶ms_, 1, NetLogWithSource()); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); ClientSocketHandle handle1; TestCompletionCallback callback1; @@ -3528,18 +3538,18 @@ ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); client_socket_factory_.SignalJobs(); EXPECT_THAT(callback1.WaitForResult(), IsOk()); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); // Make sure if a preconnected socket is not fully connected when a request @@ -3547,7 +3557,7 @@ TestLoadTimingInfoConnectedNotReused(handle1); handle1.Reset(); - EXPECT_EQ(1, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); } // Checks that fully connected preconnect jobs have no connect times, and are @@ -3558,10 +3568,10 @@ pool_->RequestSockets("a", ¶ms_, 1, NetLogWithSource()); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); ClientSocketHandle handle; TestCompletionCallback callback; @@ -3571,7 +3581,7 @@ callback.callback(), pool_.get(), NetLogWithSource())); // Make sure the idle socket was used. - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); TestLoadTimingInfoConnectedReused(handle); handle.Reset(); @@ -3597,20 +3607,20 @@ ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), pool_.get(), NetLogWithSource())); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); client_socket_factory_.SignalJobs(); ASSERT_THAT(callback1.WaitForResult(), IsOk()); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); handle1.Reset(); - EXPECT_EQ(1, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); // Set up two active sockets in "b". ClientSocketHandle handle2; @@ -3627,17 +3637,17 @@ callback2.callback(), pool_.get(), NetLogWithSource())); ASSERT_TRUE(pool_->HasGroup("b")); - EXPECT_EQ(2, pool_->NumConnectJobsInGroup("b")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("b")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("b")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("b")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("b")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("b")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("b")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("b")); client_socket_factory_.SignalJobs(); ASSERT_THAT(callback1.WaitForResult(), IsOk()); ASSERT_THAT(callback2.WaitForResult(), IsOk()); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("b")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("b")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("b")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("b")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("b")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("b")); EXPECT_EQ(2, pool_->NumActiveSocketsInGroup("b")); // Now we have 1 idle socket in "a" and 2 active sockets in "b". This means @@ -3646,15 +3656,15 @@ // sockets for "a", and "b" should still have 2 active sockets. pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("b")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("b")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("b")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("b")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("b")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("b")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("b")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("b")); EXPECT_EQ(2, pool_->NumActiveSocketsInGroup("b")); // Now release the 2 active sockets for "b". This will give us 1 idle socket @@ -3662,19 +3672,19 @@ // "a" should result in closing 1 for "b". handle1.Reset(); handle2.Reset(); - EXPECT_EQ(2, pool_->IdleSocketCountInGroup("b")); + EXPECT_EQ(2u, pool_->IdleSocketCountInGroup("b")); EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("b")); pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("b")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("b")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("b")); - EXPECT_EQ(1, pool_->IdleSocketCountInGroup("b")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("b")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("b")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("b")); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("b")); EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("b")); } @@ -3687,10 +3697,10 @@ connect_job_factory_->set_timeout_duration( base::TimeDelta::FromMilliseconds(500)); pool_->RequestSockets("a", ¶ms_, 1, NetLogWithSource()); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); // Verify the backup timer doesn't create a backup job, by making // the backup job a pending job instead of a waiting job, so it @@ -3710,10 +3720,10 @@ // Make the ConnectJob hang forever. connect_job_factory_->set_job_type(TestConnectJob::kMockWaitingJob); pool_->RequestSockets("a", ¶ms_, 1, NetLogWithSource()); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); base::RunLoop().RunUntilIdle(); // Make the backup job be a pending job, so it completes normally. @@ -3725,19 +3735,19 @@ ClientSocketPool::RespectLimits::ENABLED, callback.callback(), pool_.get(), NetLogWithSource())); // Timer has started, but the backup connect job shouldn't be created yet. - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); ASSERT_THAT(callback.WaitForResult(), IsOk()); // The hung connect job should still be there, but everything else should be // complete. - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); } @@ -3750,10 +3760,10 @@ pool_->RequestSockets("a", ¶ms_, 1, NetLogWithSource()); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); // Fail future jobs to be sure that handle receives the preconnected socket // rather than closing it and making a new one. @@ -3766,10 +3776,10 @@ callback.callback(), pool_.get(), NetLogWithSource())); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); // Drain the pending read. @@ -3779,7 +3789,7 @@ handle.Reset(); // The socket should be usable now that it's idle again. - EXPECT_EQ(1, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); } TEST_F(ClientSocketPoolBaseTest, RequestGetsAssignedJob) { @@ -3794,10 +3804,10 @@ ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); } @@ -3814,10 +3824,10 @@ ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); ClientSocketHandle handle2; TestCompletionCallback callback2; @@ -3827,10 +3837,10 @@ ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(2, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle2)); @@ -3839,11 +3849,11 @@ client_socket_factory_.SignalJob(0); EXPECT_THAT(callback1.WaitForResult(), IsOk()); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle2)); } @@ -3855,10 +3865,10 @@ pool_->RequestSockets("a", ¶ms_, 1, NetLogWithSource()); ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); ClientSocketHandle handle1; TestCompletionCallback callback1; @@ -3868,10 +3878,10 @@ ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); } @@ -3888,10 +3898,10 @@ ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); @@ -3904,10 +3914,10 @@ ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); // The highest priority request should steal the job from the default priority // request. @@ -3927,10 +3937,10 @@ callback_lowest.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); ClientSocketHandle handle_highest; TestCompletionCallback callback_highest; @@ -3940,10 +3950,10 @@ callback_highest.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(2, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); ClientSocketHandle handle_low; TestCompletionCallback callback_low; @@ -3953,10 +3963,10 @@ callback_low.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(3, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(3u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); ClientSocketHandle handle_lowest2; TestCompletionCallback callback_lowest2; @@ -3966,10 +3976,10 @@ callback_lowest2.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(3, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(3u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); // The top three requests in the queue should have jobs. EXPECT_TRUE( @@ -3991,10 +4001,10 @@ callback_medium.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(3, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(3u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_TRUE( pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle_highest)); EXPECT_TRUE( @@ -4019,10 +4029,10 @@ ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); ClientSocketHandle handle2; TestCompletionCallback callback2; @@ -4032,10 +4042,10 @@ ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); // The second request doesn't get a job because we are at the limit. EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); @@ -4060,10 +4070,10 @@ ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); @@ -4075,10 +4085,10 @@ ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); // The second request doesn't get a job because we are the limit. EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); @@ -4086,10 +4096,10 @@ // The second request should get a job upon cancelling the first request. handle1.Reset(); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle2)); } @@ -4106,10 +4116,10 @@ ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); ClientSocketHandle handle2; TestCompletionCallback callback2; @@ -4119,10 +4129,10 @@ ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(2, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle2)); @@ -4132,11 +4142,11 @@ // job. client_socket_factory_.SignalJob(1); EXPECT_THAT(callback1.WaitForResult(), IsOk()); - EXPECT_EQ(1, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumUnassignedConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); EXPECT_TRUE(handle1.socket()); EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle2)); } @@ -4419,21 +4429,21 @@ EXPECT_EQ( OK, StartRequestWithIgnoreLimits( "a", MAXIMUM_PRIORITY, ClientSocketPool::RespectLimits::ENABLED)); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); connect_job_factory_->set_job_type(TestConnectJob::kMockPendingJob); EXPECT_EQ(ERR_IO_PENDING, StartRequestWithIgnoreLimits( "a", MAXIMUM_PRIORITY, ClientSocketPool::RespectLimits::ENABLED)); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); // Issue a request that ignores the limits, so a new ConnectJob is // created. EXPECT_EQ(ERR_IO_PENDING, StartRequestWithIgnoreLimits( "a", MAXIMUM_PRIORITY, ClientSocketPool::RespectLimits::DISABLED)); - ASSERT_EQ(1, pool_->NumConnectJobsInGroup("a")); + ASSERT_EQ(1u, pool_->NumConnectJobsInGroup("a")); EXPECT_THAT(request(2)->WaitForResult(), IsOk()); EXPECT_FALSE(request(1)->have_result()); @@ -4449,26 +4459,26 @@ EXPECT_EQ( OK, StartRequestWithIgnoreLimits( "a", MAXIMUM_PRIORITY, ClientSocketPool::RespectLimits::ENABLED)); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); connect_job_factory_->set_job_type(TestConnectJob::kMockPendingJob); EXPECT_EQ(ERR_IO_PENDING, StartRequestWithIgnoreLimits( "a", MAXIMUM_PRIORITY, ClientSocketPool::RespectLimits::ENABLED)); - EXPECT_EQ(0, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); // Issue a request with RespectLimits::DISABLED, so a new ConnectJob is // created. EXPECT_EQ(ERR_IO_PENDING, StartRequestWithIgnoreLimits( "a", MAXIMUM_PRIORITY, ClientSocketPool::RespectLimits::DISABLED)); - ASSERT_EQ(1, pool_->NumConnectJobsInGroup("a")); + ASSERT_EQ(1u, pool_->NumConnectJobsInGroup("a")); // Cancel the pending request with RespectLimits::ENABLED. The ConnectJob // should not be cancelled. request(1)->handle()->Reset(); - ASSERT_EQ(1, pool_->NumConnectJobsInGroup("a")); + ASSERT_EQ(1u, pool_->NumConnectJobsInGroup("a")); EXPECT_THAT(request(2)->WaitForResult(), IsOk()); EXPECT_FALSE(request(1)->have_result());
diff --git a/net/socket/ssl_client_socket_impl.cc b/net/socket/ssl_client_socket_impl.cc index 627807e..efa267ce 100644 --- a/net/socket/ssl_client_socket_impl.cc +++ b/net/socket/ssl_client_socket_impl.cc
@@ -1625,7 +1625,8 @@ NetLogEventType::SSL_CLIENT_CERT_PROVIDED, NetLog::IntCallback( "cert_count", - 1 + ssl_config_.client_cert->intermediate_buffers().size())); + base::checked_cast<int>( + 1 + ssl_config_.client_cert->intermediate_buffers().size()))); return 1; } #endif // defined(OS_IOS)
diff --git a/net/socket/transport_client_socket_pool.cc b/net/socket/transport_client_socket_pool.cc index 9ac3e121..da3119d3 100644 --- a/net/socket/transport_client_socket_pool.cc +++ b/net/socket/transport_client_socket_pool.cc
@@ -301,7 +301,7 @@ return base_.idle_socket_count(); } -int TransportClientSocketPool::IdleSocketCountInGroup( +size_t TransportClientSocketPool::IdleSocketCountInGroup( const std::string& group_name) const { return base_.IdleSocketCountInGroup(group_name); }
diff --git a/net/socket/transport_client_socket_pool.h b/net/socket/transport_client_socket_pool.h index a70a0f2..355d709 100644 --- a/net/socket/transport_client_socket_pool.h +++ b/net/socket/transport_client_socket_pool.h
@@ -150,7 +150,7 @@ void CloseIdleSockets() override; void CloseIdleSocketsInGroup(const std::string& group_name) override; int IdleSocketCount() const override; - int IdleSocketCountInGroup(const std::string& group_name) const override; + size_t IdleSocketCountInGroup(const std::string& group_name) const override; LoadState GetLoadState(const std::string& group_name, const ClientSocketHandle* handle) const override; std::unique_ptr<base::DictionaryValue> GetInfoAsValue(
diff --git a/net/socket/websocket_transport_client_socket_pool.cc b/net/socket/websocket_transport_client_socket_pool.cc index 737e976..7463cd6 100644 --- a/net/socket/websocket_transport_client_socket_pool.cc +++ b/net/socket/websocket_transport_client_socket_pool.cc
@@ -269,7 +269,7 @@ return 0; } -int WebSocketTransportClientSocketPool::IdleSocketCountInGroup( +size_t WebSocketTransportClientSocketPool::IdleSocketCountInGroup( const std::string& group_name) const { return 0; }
diff --git a/net/socket/websocket_transport_client_socket_pool.h b/net/socket/websocket_transport_client_socket_pool.h index 0d33467..6c52b2b 100644 --- a/net/socket/websocket_transport_client_socket_pool.h +++ b/net/socket/websocket_transport_client_socket_pool.h
@@ -97,7 +97,7 @@ void CloseIdleSockets() override; void CloseIdleSocketsInGroup(const std::string& group_name) override; int IdleSocketCount() const override; - int IdleSocketCountInGroup(const std::string& group_name) const override; + size_t IdleSocketCountInGroup(const std::string& group_name) const override; LoadState GetLoadState(const std::string& group_name, const ClientSocketHandle* handle) const override; std::unique_ptr<base::DictionaryValue> GetInfoAsValue(
diff --git a/net/spdy/spdy_proxy_client_socket.cc b/net/spdy/spdy_proxy_client_socket.cc index 79247c1..000d10a8 100644 --- a/net/spdy/spdy_proxy_client_socket.cc +++ b/net/spdy/spdy_proxy_client_socket.cc
@@ -80,7 +80,7 @@ // stream may not be reused and a new SpdyProxyClientSocket must be // created (possibly on top of the same SPDY Session). next_state_ = STATE_DISCONNECTED; - return OK; + return ERR_UNABLE_TO_REUSE_CONNECTION_FOR_PROXY_AUTH; } bool SpdyProxyClientSocket::IsUsingSpdy() const {
diff --git a/net/spdy/spdy_session_unittest.cc b/net/spdy/spdy_session_unittest.cc index c6eca79..f63490b5 100644 --- a/net/spdy/spdy_session_unittest.cc +++ b/net/spdy/spdy_session_unittest.cc
@@ -1141,7 +1141,7 @@ EXPECT_THAT(delegate.WaitForClose(), IsError(ERR_CONNECTION_CLOSED)); - EXPECT_FALSE(MainThreadHasPendingTask()); + EXPECT_TRUE(MainThreadIsIdle()); EXPECT_FALSE(HasSpdySession(spdy_session_pool_, key_)); EXPECT_FALSE(session_); EXPECT_FALSE(spdy_stream1); @@ -1873,7 +1873,7 @@ // Since no response to PING has been received, // CheckPingStatus() closes the connection. - EXPECT_FALSE(MainThreadHasPendingTask()); + EXPECT_TRUE(MainThreadIsIdle()); EXPECT_FALSE(HasSpdySession(spdy_session_pool_, key_)); EXPECT_FALSE(session_); EXPECT_FALSE(spdy_stream1);
diff --git a/net/ssl/channel_id_service.cc b/net/ssl/channel_id_service.cc index c2e4792..cfe70ca 100644 --- a/net/ssl/channel_id_service.cc +++ b/net/ssl/channel_id_service.cc
@@ -418,7 +418,7 @@ return err; } -int ChannelIDService::channel_id_count() { +size_t ChannelIDService::channel_id_count() { return channel_id_store_->GetChannelIDCount(); }
diff --git a/net/ssl/channel_id_service.h b/net/ssl/channel_id_service.h index f5ffaf3e..595dfef5 100644 --- a/net/ssl/channel_id_service.h +++ b/net/ssl/channel_id_service.h
@@ -122,7 +122,7 @@ int GetUniqueID() const { return id_; } // Public only for unit testing. - int channel_id_count(); + size_t channel_id_count(); uint64_t requests() const { return requests_; } uint64_t key_store_hits() const { return key_store_hits_; } uint64_t inflight_joins() const { return inflight_joins_; }
diff --git a/net/ssl/channel_id_service_unittest.cc b/net/ssl/channel_id_service_unittest.cc index d24cc49..97373cb 100644 --- a/net/ssl/channel_id_service_unittest.cc +++ b/net/ssl/channel_id_service_unittest.cc
@@ -54,14 +54,14 @@ channel_id_count_ = 1; } - int GetChannelIDCount() override { return channel_id_count_; } + size_t GetChannelIDCount() override { return channel_id_count_; } void CallGetChannelIDCallbackWithResult(int err, crypto::ECPrivateKey* key); private: GetChannelIDCallback callback_; std::string server_identifier_; - int channel_id_count_; + size_t channel_id_count_; }; int MockChannelIDStoreWithAsyncGet::GetChannelID( @@ -125,11 +125,11 @@ // Synchronous completion, because the store is initialized. std::unique_ptr<crypto::ECPrivateKey> key; - EXPECT_EQ(0, service_->channel_id_count()); + EXPECT_EQ(0u, service_->channel_id_count()); error = service_->GetChannelID(host, &key, callback.callback(), &request); EXPECT_THAT(error, IsError(ERR_FILE_NOT_FOUND)); EXPECT_FALSE(request.is_active()); - EXPECT_EQ(0, service_->channel_id_count()); + EXPECT_EQ(0u, service_->channel_id_count()); EXPECT_FALSE(key); } @@ -142,14 +142,14 @@ // Asynchronous completion. std::unique_ptr<crypto::ECPrivateKey> key1; - EXPECT_EQ(0, service_->channel_id_count()); + EXPECT_EQ(0u, service_->channel_id_count()); error = service_->GetOrCreateChannelID(host, &key1, callback.callback(), &request); EXPECT_THAT(error, IsError(ERR_IO_PENDING)); EXPECT_TRUE(request.is_active()); error = callback.WaitForResult(); EXPECT_THAT(error, IsOk()); - EXPECT_EQ(1, service_->channel_id_count()); + EXPECT_EQ(1u, service_->channel_id_count()); EXPECT_TRUE(key1); EXPECT_FALSE(request.is_active()); @@ -159,7 +159,7 @@ &request); EXPECT_FALSE(request.is_active()); EXPECT_THAT(error, IsOk()); - EXPECT_EQ(1, service_->channel_id_count()); + EXPECT_EQ(1u, service_->channel_id_count()); EXPECT_TRUE(KeysEqual(key1.get(), key2.get())); // Synchronous get. @@ -167,7 +167,7 @@ error = service_->GetChannelID(host, &key3, callback.callback(), &request); EXPECT_FALSE(request.is_active()); EXPECT_THAT(error, IsOk()); - EXPECT_EQ(1, service_->channel_id_count()); + EXPECT_EQ(1u, service_->channel_id_count()); EXPECT_TRUE(KeysEqual(key1.get(), key3.get())); EXPECT_EQ(3u, service_->requests()); @@ -182,14 +182,14 @@ std::string host1("encrypted.google.com"); std::unique_ptr<crypto::ECPrivateKey> key1; - EXPECT_EQ(0, service_->channel_id_count()); + EXPECT_EQ(0u, service_->channel_id_count()); error = service_->GetOrCreateChannelID(host1, &key1, callback.callback(), &request); EXPECT_THAT(error, IsError(ERR_IO_PENDING)); EXPECT_TRUE(request.is_active()); error = callback.WaitForResult(); EXPECT_THAT(error, IsOk()); - EXPECT_EQ(1, service_->channel_id_count()); + EXPECT_EQ(1u, service_->channel_id_count()); std::string host2("www.verisign.com"); std::unique_ptr<crypto::ECPrivateKey> key2; @@ -199,7 +199,7 @@ EXPECT_TRUE(request.is_active()); error = callback.WaitForResult(); EXPECT_THAT(error, IsOk()); - EXPECT_EQ(2, service_->channel_id_count()); + EXPECT_EQ(2u, service_->channel_id_count()); std::string host3("www.twitter.com"); std::unique_ptr<crypto::ECPrivateKey> key3; @@ -209,7 +209,7 @@ EXPECT_TRUE(request.is_active()); error = callback.WaitForResult(); EXPECT_THAT(error, IsOk()); - EXPECT_EQ(3, service_->channel_id_count()); + EXPECT_EQ(3u, service_->channel_id_count()); EXPECT_FALSE(KeysEqual(key1.get(), key2.get())); EXPECT_FALSE(KeysEqual(key1.get(), key3.get())); @@ -304,7 +304,7 @@ // Even though the original request was cancelled, the service will still // store the result, it just doesn't call the callback. - EXPECT_EQ(1, service_->channel_id_count()); + EXPECT_EQ(1u, service_->channel_id_count()); } // Tests that destructing the Request cancels the request. @@ -329,7 +329,7 @@ // Even though the original request was cancelled, the service will still // store the result, it just doesn't call the callback. - EXPECT_EQ(1, service_->channel_id_count()); + EXPECT_EQ(1u, service_->channel_id_count()); } TEST_F(ChannelIDServiceTest, DestructionWithPendingRequest) { @@ -426,7 +426,7 @@ EXPECT_FALSE(KeysEqual(key1.get(), key3.get())); EXPECT_FALSE(KeysEqual(key2.get(), key3.get())); - EXPECT_EQ(3, service_->channel_id_count()); + EXPECT_EQ(3u, service_->channel_id_count()); } TEST_F(ChannelIDServiceTest, AsyncStoreGetOrCreateNoChannelIDsInStore) { @@ -443,7 +443,7 @@ // Asynchronous completion with no certs in the store. std::unique_ptr<crypto::ECPrivateKey> key; - EXPECT_EQ(0, service_->channel_id_count()); + EXPECT_EQ(0u, service_->channel_id_count()); error = service_->GetOrCreateChannelID(host, &key, callback.callback(), &request); EXPECT_THAT(error, IsError(ERR_IO_PENDING)); @@ -453,7 +453,7 @@ error = callback.WaitForResult(); EXPECT_THAT(error, IsOk()); - EXPECT_EQ(1, service_->channel_id_count()); + EXPECT_EQ(1u, service_->channel_id_count()); EXPECT_TRUE(key); EXPECT_FALSE(request.is_active()); } @@ -472,7 +472,7 @@ // Asynchronous completion with no certs in the store. std::unique_ptr<crypto::ECPrivateKey> key; - EXPECT_EQ(0, service_->channel_id_count()); + EXPECT_EQ(0u, service_->channel_id_count()); error = service_->GetChannelID(host, &key, callback.callback(), &request); EXPECT_THAT(error, IsError(ERR_IO_PENDING)); EXPECT_TRUE(request.is_active()); @@ -481,7 +481,7 @@ error = callback.WaitForResult(); EXPECT_THAT(error, IsError(ERR_FILE_NOT_FOUND)); - EXPECT_EQ(0, service_->channel_id_count()); + EXPECT_EQ(0u, service_->channel_id_count()); EXPECT_EQ(0u, service_->workers_created()); EXPECT_FALSE(key); EXPECT_FALSE(request.is_active()); @@ -501,7 +501,7 @@ // Asynchronous completion with a cert in the store. std::unique_ptr<crypto::ECPrivateKey> key; - EXPECT_EQ(0, service_->channel_id_count()); + EXPECT_EQ(0u, service_->channel_id_count()); error = service_->GetOrCreateChannelID(host, &key, callback.callback(), &request); EXPECT_THAT(error, IsError(ERR_IO_PENDING)); @@ -513,7 +513,7 @@ error = callback.WaitForResult(); EXPECT_THAT(error, IsOk()); - EXPECT_EQ(1, service_->channel_id_count()); + EXPECT_EQ(1u, service_->channel_id_count()); EXPECT_EQ(1u, service_->requests()); EXPECT_EQ(1u, service_->key_store_hits()); // Because the cert was found in the store, no new workers should have been @@ -539,7 +539,7 @@ // Asynchronous completion with a cert in the store. std::unique_ptr<crypto::ECPrivateKey> key; std::string private_key, spki; - EXPECT_EQ(0, service_->channel_id_count()); + EXPECT_EQ(0u, service_->channel_id_count()); error = service_->GetChannelID(host, &key, callback.callback(), &request); EXPECT_THAT(error, IsError(ERR_IO_PENDING)); EXPECT_TRUE(request.is_active()); @@ -550,7 +550,7 @@ error = callback.WaitForResult(); EXPECT_THAT(error, IsOk()); - EXPECT_EQ(1, service_->channel_id_count()); + EXPECT_EQ(1u, service_->channel_id_count()); EXPECT_EQ(1u, service_->requests()); EXPECT_EQ(1u, service_->key_store_hits()); // Because the cert was found in the store, no new workers should have been @@ -574,7 +574,7 @@ TestCompletionCallback callback1; ChannelIDService::Request request1; std::unique_ptr<crypto::ECPrivateKey> key1; - EXPECT_EQ(0, service_->channel_id_count()); + EXPECT_EQ(0u, service_->channel_id_count()); error = service_->GetChannelID(host, &key1, callback1.callback(), &request1); EXPECT_THAT(error, IsError(ERR_IO_PENDING)); EXPECT_TRUE(request1.is_active()); @@ -583,7 +583,7 @@ TestCompletionCallback callback2; ChannelIDService::Request request2; std::unique_ptr<crypto::ECPrivateKey> key2; - EXPECT_EQ(0, service_->channel_id_count()); + EXPECT_EQ(0u, service_->channel_id_count()); error = service_->GetOrCreateChannelID(host, &key2, callback2.callback(), &request2); EXPECT_THAT(error, IsError(ERR_IO_PENDING)); @@ -599,8 +599,8 @@ EXPECT_THAT(error, IsOk()); // One cert is created, one request is joined. - EXPECT_EQ(2U, service_->requests()); - EXPECT_EQ(1, service_->channel_id_count()); + EXPECT_EQ(2u, service_->requests()); + EXPECT_EQ(1u, service_->channel_id_count()); EXPECT_EQ(1u, service_->workers_created()); EXPECT_EQ(1u, service_->inflight_joins()); EXPECT_TRUE(key1);
diff --git a/net/ssl/channel_id_store.h b/net/ssl/channel_id_store.h index 7e1e9e8e..e26c61a 100644 --- a/net/ssl/channel_id_store.h +++ b/net/ssl/channel_id_store.h
@@ -100,7 +100,7 @@ // Returns the number of keypairs in the store. May return 0 if the backing // store is not loaded yet. // Public only for unit testing. - virtual int GetChannelIDCount() = 0; + virtual size_t GetChannelIDCount() = 0; // When invoked, instructs the store to keep session related data on // destruction.
diff --git a/net/ssl/default_channel_id_store.cc b/net/ssl/default_channel_id_store.cc index 5c6fdd82..bcde2a5a 100644 --- a/net/ssl/default_channel_id_store.cc +++ b/net/ssl/default_channel_id_store.cc
@@ -270,7 +270,7 @@ store_->Flush(); } -int DefaultChannelIDStore::GetChannelIDCount() { +size_t DefaultChannelIDStore::GetChannelIDCount() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); return channel_ids_.size();
diff --git a/net/ssl/default_channel_id_store.h b/net/ssl/default_channel_id_store.h index 2815500..d7daeff3 100644 --- a/net/ssl/default_channel_id_store.h +++ b/net/ssl/default_channel_id_store.h
@@ -61,7 +61,7 @@ void DeleteAll(base::OnceClosure callback) override; void GetAllChannelIDs(GetChannelIDListCallback callback) override; void Flush() override; - int GetChannelIDCount() override; + size_t GetChannelIDCount() override; void SetForceKeepSessionState() override; bool IsEphemeral() override;
diff --git a/net/ssl/default_channel_id_store_unittest.cc b/net/ssl/default_channel_id_store_unittest.cc index 3f3ecb30..8cb947f46 100644 --- a/net/ssl/default_channel_id_store_unittest.cc +++ b/net/ssl/default_channel_id_store_unittest.cc
@@ -148,16 +148,16 @@ // Make sure channel_ids load properly. DefaultChannelIDStore store(persistent_store.get()); // Load has not occurred yet. - EXPECT_EQ(0, store.GetChannelIDCount()); + EXPECT_EQ(0u, store.GetChannelIDCount()); store.SetChannelID(std::make_unique<ChannelIDStore::ChannelID>( "verisign.com", base::Time(), crypto::ECPrivateKey::Create())); // Wait for load & queued set task. base::RunLoop().RunUntilIdle(); - EXPECT_EQ(2, store.GetChannelIDCount()); + EXPECT_EQ(2u, store.GetChannelIDCount()); store.SetChannelID(std::make_unique<ChannelIDStore::ChannelID>( "twitter.com", base::Time(), crypto::ECPrivateKey::Create())); // Set should be synchronous now that load is done. - EXPECT_EQ(3, store.GetChannelIDCount()); + EXPECT_EQ(3u, store.GetChannelIDCount()); } //TODO(mattm): add more tests of without a persistent store? @@ -168,7 +168,7 @@ crypto::ECPrivateKey::Create()); std::unique_ptr<crypto::ECPrivateKey> key; - EXPECT_EQ(0, store.GetChannelIDCount()); + EXPECT_EQ(0u, store.GetChannelIDCount()); EXPECT_EQ(ERR_FILE_NOT_FOUND, store.GetChannelID("verisign.com", &key, base::Bind(&GetChannelIDCallbackNotCalled))); @@ -188,7 +188,7 @@ crypto::ECPrivateKey::Create()); std::unique_ptr<crypto::ECPrivateKey> key; - EXPECT_EQ(0, store.GetChannelIDCount()); + EXPECT_EQ(0u, store.GetChannelIDCount()); store.SetChannelID(std::make_unique<ChannelIDStore::ChannelID>( "verisign.com", base::Time::FromInternalValue(123), crypto::ECPrivateKey::Create())); @@ -198,7 +198,7 @@ // Wait for load & queued set tasks. base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, store.GetChannelIDCount()); + EXPECT_EQ(1u, store.GetChannelIDCount()); EXPECT_EQ(OK, store.GetChannelID("verisign.com", &key, base::Bind(&GetChannelIDCallbackNotCalled))); EXPECT_TRUE(KeysEqual(expected_key.get(), key.get())); @@ -215,7 +215,7 @@ DefaultChannelIDStore store(persistent_store.get()); AsyncGetChannelIDHelper helper; std::unique_ptr<crypto::ECPrivateKey> key; - EXPECT_EQ(0, store.GetChannelIDCount()); + EXPECT_EQ(0u, store.GetChannelIDCount()); EXPECT_EQ(ERR_IO_PENDING, store.GetChannelID("verisign.com", &key, base::Bind(&AsyncGetChannelIDHelper::Callback, @@ -223,7 +223,7 @@ // Wait for load & queued get tasks. base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, store.GetChannelIDCount()); + EXPECT_EQ(1u, store.GetChannelIDCount()); EXPECT_FALSE(key); EXPECT_TRUE(helper.called_); EXPECT_THAT(helper.err_, IsOk()); @@ -244,11 +244,11 @@ // Wait for load & queued set tasks. base::RunLoop().RunUntilIdle(); - EXPECT_EQ(3, store.GetChannelIDCount()); + EXPECT_EQ(3u, store.GetChannelIDCount()); int delete_finished = 0; store.DeleteAll(base::Bind(&CallCounter, &delete_finished)); ASSERT_EQ(1, delete_finished); - EXPECT_EQ(0, store.GetChannelIDCount()); + EXPECT_EQ(0u, store.GetChannelIDCount()); } TEST_F(DefaultChannelIDStoreTest, TestDeleteForDomains) { @@ -263,7 +263,7 @@ "harvard.com", base::Time(), crypto::ECPrivateKey::Create())); // Wait for load & queued set tasks. base::RunLoop().RunUntilIdle(); - EXPECT_EQ(3, store.GetChannelIDCount()); + EXPECT_EQ(3u, store.GetChannelIDCount()); // Whitelist deletion. int deletions_finished = 0; @@ -272,7 +272,7 @@ base::Time(), base::Time(), base::Bind(&CallCounter, &deletions_finished)); ASSERT_EQ(1, deletions_finished); - EXPECT_EQ(2, store.GetChannelIDCount()); + EXPECT_EQ(2u, store.GetChannelIDCount()); ChannelIDStore::ChannelIDList channel_ids; store.GetAllChannelIDs(base::Bind(GetAllCallback, &channel_ids)); EXPECT_EQ("google.com", channel_ids.begin()->server_identifier()); @@ -284,7 +284,7 @@ base::Time(), base::Time(), base::Bind(&CallCounter, &deletions_finished)); ASSERT_EQ(2, deletions_finished); - EXPECT_EQ(1, store.GetChannelIDCount()); + EXPECT_EQ(1u, store.GetChannelIDCount()); store.GetAllChannelIDs(base::Bind(GetAllCallback, &channel_ids)); EXPECT_EQ("google.com", channel_ids.begin()->server_identifier()); } @@ -308,7 +308,7 @@ EXPECT_EQ(0u, pre_channel_ids.size()); // Wait for load & queued tasks. base::RunLoop().RunUntilIdle(); - EXPECT_EQ(0, store.GetChannelIDCount()); + EXPECT_EQ(0u, store.GetChannelIDCount()); EXPECT_EQ(2u, pre_channel_ids.size()); EXPECT_EQ(0u, post_channel_ids.size()); } @@ -318,7 +318,7 @@ DefaultChannelIDStore store(persistent_store.get()); std::unique_ptr<crypto::ECPrivateKey> key; - EXPECT_EQ(0, store.GetChannelIDCount()); + EXPECT_EQ(0u, store.GetChannelIDCount()); store.SetChannelID(std::make_unique<ChannelIDStore::ChannelID>( "verisign.com", base::Time(), crypto::ECPrivateKey::Create())); // Wait for load & queued set task. @@ -327,12 +327,12 @@ store.SetChannelID(std::make_unique<ChannelIDStore::ChannelID>( "google.com", base::Time(), crypto::ECPrivateKey::Create())); - EXPECT_EQ(2, store.GetChannelIDCount()); + EXPECT_EQ(2u, store.GetChannelIDCount()); int delete_finished = 0; store.DeleteChannelID("verisign.com", base::Bind(&CallCounter, &delete_finished)); ASSERT_EQ(1, delete_finished); - EXPECT_EQ(1, store.GetChannelIDCount()); + EXPECT_EQ(1u, store.GetChannelIDCount()); EXPECT_EQ(ERR_FILE_NOT_FOUND, store.GetChannelID("verisign.com", &key, base::Bind(&GetChannelIDCallbackNotCalled))); @@ -342,7 +342,7 @@ store.DeleteChannelID("google.com", base::Bind(&CallCounter, &delete2_finished)); ASSERT_EQ(1, delete2_finished); - EXPECT_EQ(0, store.GetChannelIDCount()); + EXPECT_EQ(0u, store.GetChannelIDCount()); EXPECT_EQ(ERR_FILE_NOT_FOUND, store.GetChannelID("google.com", &key, base::Bind(&GetChannelIDCallbackNotCalled))); @@ -365,7 +365,7 @@ AsyncGetChannelIDHelper a_helper; AsyncGetChannelIDHelper b_helper; std::unique_ptr<crypto::ECPrivateKey> key; - EXPECT_EQ(0, store.GetChannelIDCount()); + EXPECT_EQ(0u, store.GetChannelIDCount()); EXPECT_EQ(ERR_IO_PENDING, store.GetChannelID("a.com", &key, base::Bind(&AsyncGetChannelIDHelper::Callback, @@ -381,7 +381,7 @@ // Wait for load & queued tasks. base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, delete_finished); - EXPECT_EQ(1, store.GetChannelIDCount()); + EXPECT_EQ(1u, store.GetChannelIDCount()); EXPECT_FALSE(key); EXPECT_TRUE(a_helper.called_); EXPECT_THAT(a_helper.err_, IsError(ERR_FILE_NOT_FOUND)); @@ -397,7 +397,7 @@ scoped_refptr<MockPersistentStore> persistent_store(new MockPersistentStore); DefaultChannelIDStore store(persistent_store.get()); - EXPECT_EQ(0, store.GetChannelIDCount()); + EXPECT_EQ(0u, store.GetChannelIDCount()); store.SetChannelID(std::make_unique<ChannelIDStore::ChannelID>( "verisign.com", base::Time(), crypto::ECPrivateKey::Create())); store.SetChannelID(std::make_unique<ChannelIDStore::ChannelID>( @@ -409,7 +409,7 @@ // Wait for load & queued set tasks. base::RunLoop().RunUntilIdle(); - EXPECT_EQ(4, store.GetChannelIDCount()); + EXPECT_EQ(4u, store.GetChannelIDCount()); ChannelIDStore::ChannelIDList channel_ids; store.GetAllChannelIDs(base::Bind(GetAllCallback, &channel_ids)); EXPECT_EQ(4u, channel_ids.size());
diff --git a/net/test/test_with_scoped_task_environment.h b/net/test/test_with_scoped_task_environment.h index a2a9f24..0967647 100644 --- a/net/test/test_with_scoped_task_environment.h +++ b/net/test/test_with_scoped_task_environment.h
@@ -34,8 +34,8 @@ base::test::ScopedTaskEnvironment::NowSource now_source) : scoped_task_environment_(type, now_source) {} - bool MainThreadHasPendingTask() const WARN_UNUSED_RESULT { - return scoped_task_environment_.MainThreadHasPendingTask(); + bool MainThreadIsIdle() const WARN_UNUSED_RESULT { + return scoped_task_environment_.MainThreadIsIdle(); } void RunUntilIdle() { scoped_task_environment_.RunUntilIdle(); }
diff --git a/net/third_party/quic/core/http/spdy_utils.cc b/net/third_party/quic/core/http/spdy_utils.cc index f18b87d..ade7e9e 100644 --- a/net/third_party/quic/core/http/spdy_utils.cc +++ b/net/third_party/quic/core/http/spdy_utils.cc
@@ -255,12 +255,12 @@ // Validate the scheme; this is to ensure a scheme of "foo://bar" is not // parsed as a URL of "foo://bar://baz" when combined with a host of "baz". std::string canonical_scheme; - url::StdStringCanonOutput canon_output(&canonical_scheme); + url::StdStringCanonOutput canon_scheme_output(&canonical_scheme); url::Component canon_component; url::Component scheme_component(0, scheme.size()); - if (!url::CanonicalizeScheme(scheme.data(), scheme_component, &canon_output, - &canon_component) || + if (!url::CanonicalizeScheme(scheme.data(), scheme_component, + &canon_scheme_output, &canon_component) || !canon_component.is_nonempty() || canon_component.begin != 0) { return QuicString(); } @@ -304,13 +304,13 @@ } } - // Validate the host by attempting to canoncalize it. Invalid characters + // Validate the host by attempting to canonicalize it. Invalid characters // will result in a canonicalization failure (e.g. '/') std::string canon_host; - canon_output = url::StdStringCanonOutput(&canon_host); + url::StdStringCanonOutput canon_host_output(&canon_host); canon_component.reset(); - if (!url::CanonicalizeHost(authority.data(), host_component, &canon_output, - &canon_component) || + if (!url::CanonicalizeHost(authority.data(), host_component, + &canon_host_output, &canon_component) || !canon_component.is_nonempty() || canon_component.begin != 0) { return QuicString(); }
diff --git a/net/url_request/http_with_dns_over_https_unittest.cc b/net/url_request/http_with_dns_over_https_unittest.cc index f04e303..7bb2e8c0 100644 --- a/net/url_request/http_with_dns_over_https_unittest.cc +++ b/net/url_request/http_with_dns_over_https_unittest.cc
@@ -208,7 +208,7 @@ EXPECT_EQ(network_session ->GetTransportSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL) ->IdleSocketCountInGroup(group_name), - 1); + 1u); // Make a request that will trigger a DoH query as well. TestDelegate d;
diff --git a/net/websockets/websocket_stream_cookie_test.cc b/net/websockets/websocket_stream_cookie_test.cc index c93324b..65b5645 100644 --- a/net/websockets/websocket_stream_cookie_test.cc +++ b/net/websockets/websocket_stream_cookie_test.cc
@@ -82,12 +82,13 @@ base::RunLoop().RunUntilIdle(); } - static void SetCookieHelperFunction(const base::Closure& task, - base::WeakPtr<bool> weak_is_called, - base::WeakPtr<bool> weak_result, - bool success) { + static void SetCookieHelperFunction( + const base::RepeatingClosure& task, + base::WeakPtr<bool> weak_is_called, + base::WeakPtr<bool> weak_result, + CanonicalCookie::CookieInclusionStatus status) { *weak_is_called = true; - *weak_result = success; + *weak_result = (status == CanonicalCookie::CookieInclusionStatus::INCLUDE); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, task); } };
diff --git a/pdf/pdf_features.cc b/pdf/pdf_features.cc index 2b9d28a7..89c4cb9 100644 --- a/pdf/pdf_features.cc +++ b/pdf/pdf_features.cc
@@ -10,8 +10,14 @@ const base::Feature kSaveEditedPDFForm{"SaveEditedPDFForm", base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kPDFAnnotations{"PDFAnnotations", - base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kPDFAnnotations { + "PDFAnnotations", +#if defined(OS_CHROMEOS) + base::FEATURE_ENABLED_BY_DEFAULT +#else + base::FEATURE_DISABLED_BY_DEFAULT +#endif // defined(OS_CHROMEOS) +}; } // namespace features } // namespace chrome_pdf
diff --git a/services/identity/public/cpp/BUILD.gn b/services/identity/public/cpp/BUILD.gn index ceb24d15..206ad63 100644 --- a/services/identity/public/cpp/BUILD.gn +++ b/services/identity/public/cpp/BUILD.gn
@@ -14,6 +14,9 @@ "accounts_in_cookie_jar_info.cc", "accounts_in_cookie_jar_info.h", "accounts_mutator.h", + "diagnostics_provider.h", + "diagnostics_provider_impl.cc", + "diagnostics_provider_impl.h", "identity_manager.cc", "identity_manager.h", "primary_account_access_token_fetcher.cc", @@ -77,13 +80,14 @@ public_deps = [ ":cpp", + "//components/signin/core/browser:internals_test_support", + "//components/sync_preferences:test_support", + "//google_apis:test_support", ] deps = [ "//components/image_fetcher/core:test_support", "//components/signin/core/browser", - "//components/signin/core/browser:internals_test_support", - "//components/sync_preferences:test_support", ] } @@ -92,6 +96,7 @@ sources = [ "accounts_cookie_mutator_unittest.cc", "accounts_mutator_unittest.cc", + "diagnostics_provider_unittest.cc", "primary_account_mutator_unittest.cc", ] @@ -103,6 +108,7 @@ "//components/signin/core/browser:internals_test_support", "//components/sync_preferences:test_support", "//services/network:test_support", + "//testing/gmock", "//testing/gtest", ] }
diff --git a/services/identity/public/cpp/DEPS b/services/identity/public/cpp/DEPS index ab8f906..8f047c21 100644 --- a/services/identity/public/cpp/DEPS +++ b/services/identity/public/cpp/DEPS
@@ -18,6 +18,7 @@ "+google_apis/gaia/google_service_auth_error.h", "+google_apis/gaia/oauth2_access_token_consumer.h", "+google_apis/gaia/oauth2_token_service.h", + "+google_apis/gaia/oauth2_token_service_delegate.h", "+services/network/public/cpp", ] @@ -40,4 +41,7 @@ "+services/network/test/test_cookie_manager.h", "+services/network/test/test_url_loader_factory.h", ], + "diagnostics_provider_unittest.cc": [ + "+google_apis/gaia/fake_oauth2_token_service_delegate.h", + ] }
diff --git a/services/identity/public/cpp/diagnostics_provider.h b/services/identity/public/cpp/diagnostics_provider.h new file mode 100644 index 0000000..487b422 --- /dev/null +++ b/services/identity/public/cpp/diagnostics_provider.h
@@ -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. + +#ifndef SERVICES_IDENTITY_PUBLIC_CPP_DIAGNOSTICS_PROVIDER_H_ +#define SERVICES_IDENTITY_PUBLIC_CPP_DIAGNOSTICS_PROVIDER_H_ + +#include <string> + +#include "base/macros.h" +#include "google_apis/gaia/oauth2_token_service_delegate.h" + +namespace identity { + +// DiagnosticsProvider is the interface to obtain diagnostics about +// IdentityManager internals. +class DiagnosticsProvider { + public: + DiagnosticsProvider() = default; + virtual ~DiagnosticsProvider() = default; + + // Returns the state of the load credentials operation. + virtual OAuth2TokenServiceDelegate::LoadCredentialsState + GetDetailedStateOfLoadingOfRefreshTokens() const = 0; + + // Returns the time until a access token request can be sent (will be zero if + // the release time is in the past). + virtual base::TimeDelta GetDelayBeforeMakingAccessTokenRequests() const = 0; + + // Returns the time until a cookie request can be sent (will be zero if the + // release time is in the past). + virtual base::TimeDelta GetDelayBeforeMakingCookieRequests() const = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(DiagnosticsProvider); +}; + +} // namespace identity + +#endif // SERVICES_IDENTITY_PUBLIC_CPP_DIAGNOSTICS_PROVIDER_H_
diff --git a/services/identity/public/cpp/diagnostics_provider_impl.cc b/services/identity/public/cpp/diagnostics_provider_impl.cc new file mode 100644 index 0000000..b00e48b --- /dev/null +++ b/services/identity/public/cpp/diagnostics_provider_impl.cc
@@ -0,0 +1,44 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "services/identity/public/cpp/diagnostics_provider_impl.h" + +#include "components/signin/core/browser/gaia_cookie_manager_service.h" +#include "components/signin/core/browser/profile_oauth2_token_service.h" +#include "google_apis/gaia/oauth2_token_service_delegate.h" + +namespace identity { + +DiagnosticsProviderImpl::DiagnosticsProviderImpl( + ProfileOAuth2TokenService* profile_oauth2_token_service, + GaiaCookieManagerService* gaia_cookie_manager_service) + : gaia_cookie_manager_service_(gaia_cookie_manager_service), + profile_oauth2_token_service_(profile_oauth2_token_service) { + DCHECK(gaia_cookie_manager_service_); + DCHECK(profile_oauth2_token_service_); +} + +DiagnosticsProviderImpl::~DiagnosticsProviderImpl() {} + +OAuth2TokenServiceDelegate::LoadCredentialsState +DiagnosticsProviderImpl::GetDetailedStateOfLoadingOfRefreshTokens() const { + DCHECK(profile_oauth2_token_service_->GetDelegate()); + return profile_oauth2_token_service_->GetDelegate()->load_credentials_state(); +} + +base::TimeDelta +DiagnosticsProviderImpl::GetDelayBeforeMakingAccessTokenRequests() const { + const net::BackoffEntry* backoff_entry = + profile_oauth2_token_service_->GetDelegateBackoffEntry(); + return backoff_entry ? backoff_entry->GetTimeUntilRelease() + : base::TimeDelta(); +} + +base::TimeDelta DiagnosticsProviderImpl::GetDelayBeforeMakingCookieRequests() + const { + DCHECK(gaia_cookie_manager_service_->GetBackoffEntry()); + return gaia_cookie_manager_service_->GetBackoffEntry()->GetTimeUntilRelease(); +} + +} // namespace identity \ No newline at end of file
diff --git a/services/identity/public/cpp/diagnostics_provider_impl.h b/services/identity/public/cpp/diagnostics_provider_impl.h new file mode 100644 index 0000000..13c22650 --- /dev/null +++ b/services/identity/public/cpp/diagnostics_provider_impl.h
@@ -0,0 +1,45 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef SERVICES_IDENTITY_PUBLIC_CPP_DIAGNOSTICS_PROVIDER_IMPL_H_ +#define SERVICES_IDENTITY_PUBLIC_CPP_DIAGNOSTICS_PROVIDER_IMPL_H_ + +#include "base/macros.h" +#include "services/identity/public/cpp/diagnostics_provider.h" + +class GaiaCookieManagerService; +class ProfileOAuth2TokenService; + +namespace identity { + +// Concrete implementation of the DiagnosticsProvider interface. +class DiagnosticsProviderImpl final : public DiagnosticsProvider { + public: + DiagnosticsProviderImpl( + ProfileOAuth2TokenService* profile_oauth2_token_service, + GaiaCookieManagerService* gaia_cookie_manager_service); + ~DiagnosticsProviderImpl() override; + + // Returns the state of the load credentials operation. + OAuth2TokenServiceDelegate::LoadCredentialsState + GetDetailedStateOfLoadingOfRefreshTokens() const override; + + // Returns the time until a access token request can be sent (will be zero if + // the release time is in the past). + base::TimeDelta GetDelayBeforeMakingAccessTokenRequests() const override; + + // Returns the time until a cookie request can be sent (will be zero if the + // release time is in the past). + base::TimeDelta GetDelayBeforeMakingCookieRequests() const override; + + private: + GaiaCookieManagerService* gaia_cookie_manager_service_; + ProfileOAuth2TokenService* profile_oauth2_token_service_; + + DISALLOW_COPY_AND_ASSIGN(DiagnosticsProviderImpl); +}; + +} // namespace identity + +#endif // SERVICES_IDENTITY_PUBLIC_CPP_DIAGNOSTICS_PROVIDER_IMPL_H_
diff --git a/services/identity/public/cpp/diagnostics_provider_unittest.cc b/services/identity/public/cpp/diagnostics_provider_unittest.cc new file mode 100644 index 0000000..b616c3c --- /dev/null +++ b/services/identity/public/cpp/diagnostics_provider_unittest.cc
@@ -0,0 +1,77 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "services/identity/public/cpp/diagnostics_provider_impl.h" + +#include "base/macros.h" +#include "base/test/scoped_task_environment.h" +#include "services/identity/public/cpp/identity_test_environment.h" +#include "testing/gtest/include/gtest/gtest.h" + +const char kAccountId[] = "user@gmail.com"; + +namespace { + +class DiagnosticsProviderTest : public testing::Test { + public: + DiagnosticsProviderTest() = default; + + identity::IdentityTestEnvironment* identity_test_env() { + return &identity_test_env_; + } + + identity::DiagnosticsProvider* diagnostics_provider() { + return identity_test_env_.identity_manager()->GetDiagnosticsProvider(); + } + + protected: + base::test::ScopedTaskEnvironment scoped_task_environment_; + + private: + identity::IdentityTestEnvironment identity_test_env_; + + DISALLOW_COPY_AND_ASSIGN(DiagnosticsProviderTest); +}; + +} // namespace + +TEST_F(DiagnosticsProviderTest, Basic) { + // Accessing the DiagnosticProvider should not crash. + ASSERT_TRUE(identity_test_env()->identity_manager()); + EXPECT_TRUE( + identity_test_env()->identity_manager()->GetDiagnosticsProvider()); +} + +TEST_F(DiagnosticsProviderTest, GetDetailedStateOfLoadingOfRefreshTokens) { + EXPECT_EQ(OAuth2TokenServiceDelegate::LoadCredentialsState:: + LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + diagnostics_provider()->GetDetailedStateOfLoadingOfRefreshTokens()); +} + +TEST_F(DiagnosticsProviderTest, GetDelayBeforeMakingAccessTokenRequests) { + base::TimeDelta zero; + EXPECT_EQ(diagnostics_provider()->GetDelayBeforeMakingAccessTokenRequests(), + zero); + std::string account_id = + identity_test_env()->MakeAccountAvailable(kAccountId).account_id; + identity_test_env()->UpdatePersistentErrorOfRefreshTokenForAccount( + account_id, GoogleServiceAuthError( + GoogleServiceAuthError::State::SERVICE_UNAVAILABLE)); + EXPECT_GT(diagnostics_provider()->GetDelayBeforeMakingAccessTokenRequests(), + zero); +} + +TEST_F(DiagnosticsProviderTest, GetDelayBeforeMakingCookieRequests) { + base::TimeDelta zero; + identity_test_env() + ->identity_manager() + ->GetAccountsCookieMutator() + ->AddAccountToCookie(kAccountId, gaia::GaiaSource::kChrome, + base::DoNothing()); + EXPECT_EQ(diagnostics_provider()->GetDelayBeforeMakingCookieRequests(), zero); + + identity_test_env()->SimulateMergeSessionFailure( + GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED)); + EXPECT_GT(diagnostics_provider()->GetDelayBeforeMakingCookieRequests(), zero); +} \ No newline at end of file
diff --git a/services/identity/public/cpp/identity_manager.cc b/services/identity/public/cpp/identity_manager.cc index d960705..4c63543 100644 --- a/services/identity/public/cpp/identity_manager.cc +++ b/services/identity/public/cpp/identity_manager.cc
@@ -12,6 +12,7 @@ #include "google_apis/gaia/gaia_auth_util.h" #include "services/identity/public/cpp/accounts_cookie_mutator.h" #include "services/identity/public/cpp/accounts_mutator.h" +#include "services/identity/public/cpp/diagnostics_provider.h" #include "services/identity/public/cpp/primary_account_mutator.h" #include "services/network/public/cpp/shared_url_loader_factory.h" @@ -42,7 +43,8 @@ GaiaCookieManagerService* gaia_cookie_manager_service, std::unique_ptr<PrimaryAccountMutator> primary_account_mutator, std::unique_ptr<AccountsMutator> accounts_mutator, - std::unique_ptr<AccountsCookieMutator> accounts_cookie_mutator) + std::unique_ptr<AccountsCookieMutator> accounts_cookie_mutator, + std::unique_ptr<DiagnosticsProvider> diagnostics_provider) : signin_manager_(signin_manager), token_service_(token_service), account_fetcher_service_(account_fetcher_service), @@ -50,9 +52,11 @@ gaia_cookie_manager_service_(gaia_cookie_manager_service), primary_account_mutator_(std::move(primary_account_mutator)), accounts_mutator_(std::move(accounts_mutator)), - accounts_cookie_mutator_(std::move(accounts_cookie_mutator)) { + accounts_cookie_mutator_(std::move(accounts_cookie_mutator)), + diagnostics_provider_(std::move(diagnostics_provider)) { DCHECK(account_fetcher_service_); DCHECK(accounts_cookie_mutator_); + DCHECK(diagnostics_provider_); signin_manager_->AddObserver(this); token_service_->AddDiagnosticsObserver(this); token_service_->AddObserver(this); @@ -287,6 +291,10 @@ token_service_->LoadCredentials(primary_account_id); } +DiagnosticsProvider* IdentityManager::GetDiagnosticsProvider() { + return diagnostics_provider_.get(); +} + std::string IdentityManager::LegacySeedAccountInfo(const AccountInfo& info) { return account_tracker_service_->SeedAccountInfo(info); } @@ -480,6 +488,15 @@ } } +void IdentityManager::OnFetchAccessTokenComplete(const std::string& account_id, + const std::string& consumer_id, + const ScopeSet& scopes, + GoogleServiceAuthError error, + base::Time expiration_time) { + for (auto& observer : diagnostics_observer_list_) + observer.OnAccessTokenRequestCompleted(account_id, error, scopes); +} + void IdentityManager::OnAccessTokenRemoved(const std::string& account_id, const ScopeSet& scopes) { for (auto& observer : diagnostics_observer_list_)
diff --git a/services/identity/public/cpp/identity_manager.h b/services/identity/public/cpp/identity_manager.h index 7d58b9f..0717b32 100644 --- a/services/identity/public/cpp/identity_manager.h +++ b/services/identity/public/cpp/identity_manager.h
@@ -19,6 +19,7 @@ #include "components/signin/core/browser/signin_metrics.h" #include "components/signin/core/browser/ubertoken_fetcher.h" #include "services/identity/public/cpp/access_token_fetcher.h" +#include "services/identity/public/cpp/accounts_cookie_mutator.h" #include "services/identity/public/cpp/accounts_in_cookie_jar_info.h" #include "services/identity/public/cpp/scope_set.h" @@ -51,6 +52,7 @@ class AccountsMutator; class AccountsCookieMutator; +class DiagnosticsProvider; class PrimaryAccountMutator; enum class ClearPrimaryAccountPolicy; struct CookieParams; @@ -167,6 +169,12 @@ const std::string& consumer_id, const identity::ScopeSet& scopes) {} + // Called when an access token request is completed. Contains diagnostic + // information about the access token request. + virtual void OnAccessTokenRequestCompleted(const std::string& account_id, + GoogleServiceAuthError error, + const ScopeSet& scopes) {} + // Called when an access token was removed. virtual void OnAccessTokenRemovedFromCache(const std::string& account_id, const ScopeSet& scopes) {} @@ -202,7 +210,8 @@ GaiaCookieManagerService* gaia_cookie_manager_service, std::unique_ptr<PrimaryAccountMutator> primary_account_mutator, std::unique_ptr<AccountsMutator> accounts_mutator, - std::unique_ptr<AccountsCookieMutator> accounts_cookie_mutator); + std::unique_ptr<AccountsCookieMutator> accounts_cookie_mutator, + std::unique_ptr<DiagnosticsProvider> diagnostics_provider); ~IdentityManager() override; // Provides access to the extended information of the user's primary account. @@ -370,6 +379,10 @@ void LegacyLoadCredentialsForSupervisedUser( const std::string& primary_account_id); + // Returns pointer to the object used to obtain diagnostics about the internal + // state of IdentityManager. + DiagnosticsProvider* GetDiagnosticsProvider(); + // Picks the correct account_id for the specified account depending on the // migration state. // NOTE: This method is added temporarily until when the delegate is moved @@ -525,6 +538,11 @@ const std::string& account_id, const std::string& consumer_id, const OAuth2TokenService::ScopeSet& scopes) override; + void OnFetchAccessTokenComplete(const std::string& account_id, + const std::string& consumer_id, + const ScopeSet& scopes, + GoogleServiceAuthError error, + base::Time expiration_time) override; void OnAccessTokenRemoved(const std::string& account_id, const ScopeSet& scopes) override; void OnRefreshTokenAvailableFromSource(const std::string& account_id, @@ -559,6 +577,9 @@ // functionality is supported on all platforms. std::unique_ptr<AccountsCookieMutator> accounts_cookie_mutator_; + // DiagnosticsProvider instance. + std::unique_ptr<DiagnosticsProvider> diagnostics_provider_; + // Lists of observers. // Makes sure lists are empty on destruction. base::ObserverList<Observer, true>::Unchecked observer_list_;
diff --git a/services/identity/public/cpp/identity_manager_unittest.cc b/services/identity/public/cpp/identity_manager_unittest.cc index aa48533d..f3f65d0a 100644 --- a/services/identity/public/cpp/identity_manager_unittest.cc +++ b/services/identity/public/cpp/identity_manager_unittest.cc
@@ -30,6 +30,7 @@ #include "services/identity/public/cpp/accounts_cookie_mutator.h" #include "services/identity/public/cpp/accounts_cookie_mutator_impl.h" #include "services/identity/public/cpp/accounts_mutator.h" +#include "services/identity/public/cpp/diagnostics_provider_impl.h" #include "services/identity/public/cpp/identity_manager.h" #include "services/identity/public/cpp/identity_test_utils.h" #include "services/identity/public/cpp/primary_account_mutator.h" @@ -229,6 +230,11 @@ on_access_token_requested_callback_ = std::move(callback); } + void set_on_access_token_request_completed_callback( + base::OnceClosure callback) { + on_access_token_request_completed_callback_ = std::move(callback); + } + const std::string& token_requestor_account_id() { return token_requestor_account_id_; } @@ -244,6 +250,15 @@ const identity::ScopeSet& token_remover_scopes() { return token_remover_scopes_; } + const std::string& on_access_token_request_completed_account_id() { + return access_token_request_completed_account_id_; + } + const identity::ScopeSet& on_access_token_request_completed_scopes() { + return access_token_request_completed_scopes_; + } + const GoogleServiceAuthError& on_access_token_request_completed_error() { + return access_token_request_completed_error_; + } private: // IdentityManager::DiagnosticsObserver: @@ -264,13 +279,28 @@ token_remover_scopes_ = scopes; } + void OnAccessTokenRequestCompleted(const std::string& account_id, + GoogleServiceAuthError error, + const ScopeSet& scopes) override { + access_token_request_completed_account_id_ = account_id; + access_token_request_completed_scopes_ = scopes; + access_token_request_completed_error_ = error; + + if (on_access_token_request_completed_callback_) + std::move(on_access_token_request_completed_callback_).Run(); + } + IdentityManager* identity_manager_; base::OnceClosure on_access_token_requested_callback_; + base::OnceClosure on_access_token_request_completed_callback_; std::string token_requestor_account_id_; std::string token_requestor_consumer_id_; std::string token_remover_account_id_; identity::ScopeSet token_requestor_scopes_; identity::ScopeSet token_remover_scopes_; + std::string access_token_request_completed_account_id_; + identity::ScopeSet access_token_request_completed_scopes_; + GoogleServiceAuthError access_token_request_completed_error_; }; } // namespace @@ -399,7 +429,9 @@ signin_manager_.get(), &token_service_, &account_fetcher_, &account_tracker_, &gaia_cookie_manager_service_, nullptr, nullptr, std::make_unique<AccountsCookieMutatorImpl>( - &gaia_cookie_manager_service_))); + &gaia_cookie_manager_service_), + std::make_unique<DiagnosticsProviderImpl>( + &token_service_, &gaia_cookie_manager_service_))); identity_manager_observer_.reset( new TestIdentityManagerObserver(identity_manager_.get())); identity_manager_diagnostics_observer_.reset( @@ -1279,6 +1311,92 @@ identity_manager_diagnostics_observer()->token_requestor_scopes()); } +TEST_F(IdentityManagerTest, + ObserveAccessTokenRequestCompletionWithoutRefreshToken) { + base::RunLoop run_loop; + identity_manager_diagnostics_observer() + ->set_on_access_token_request_completed_callback(run_loop.QuitClosure()); + + std::set<std::string> scopes{"scope"}; + AccessTokenFetcher::TokenCallback callback = base::BindOnce( + [](GoogleServiceAuthError error, AccessTokenInfo access_token_info) {}); + // Account has no refresh token. + std::unique_ptr<AccessTokenFetcher> token_fetcher = + identity_manager()->CreateAccessTokenFetcherForAccount( + identity_manager()->GetPrimaryAccountId(), "dummy_consumer", scopes, + std::move(callback), AccessTokenFetcher::Mode::kImmediate); + + run_loop.Run(); + + EXPECT_TRUE(token_fetcher); + EXPECT_EQ(GoogleServiceAuthError(GoogleServiceAuthError::USER_NOT_SIGNED_UP), + identity_manager_diagnostics_observer() + ->on_access_token_request_completed_error()); +} + +TEST_F(IdentityManagerTest, + ObserveAccessTokenRequestCompletionWithRefreshToken) { + base::RunLoop run_loop; + identity_manager_diagnostics_observer() + ->set_on_access_token_request_completed_callback(run_loop.QuitClosure()); + + signin_manager()->SetAuthenticatedAccountInfo(kTestGaiaId, kTestEmail); + std::string account_id = signin_manager()->GetAuthenticatedAccountId(); + token_service()->UpdateCredentials(account_id, "refresh_token"); + token_service()->set_auto_post_fetch_response_on_message_loop(true); + + std::set<std::string> scopes{"scope"}; + AccessTokenFetcher::TokenCallback callback = base::BindOnce( + [](GoogleServiceAuthError error, AccessTokenInfo access_token_info) {}); + // This should result in a request for an access token without an error. + std::unique_ptr<AccessTokenFetcher> token_fetcher = + identity_manager()->CreateAccessTokenFetcherForAccount( + identity_manager()->GetPrimaryAccountId(), "dummy_consumer", scopes, + std::move(callback), AccessTokenFetcher::Mode::kImmediate); + + run_loop.Run(); + + EXPECT_TRUE(token_fetcher); + EXPECT_EQ(account_id, identity_manager_diagnostics_observer() + ->on_access_token_request_completed_account_id()); + EXPECT_EQ(scopes, identity_manager_diagnostics_observer() + ->on_access_token_request_completed_scopes()); + EXPECT_EQ(GoogleServiceAuthError(GoogleServiceAuthError::NONE), + identity_manager_diagnostics_observer() + ->on_access_token_request_completed_error()); +} + +TEST_F(IdentityManagerTest, + ObserveAccessTokenRequestCompletionAfterRevokingRefreshToken) { + base::RunLoop run_loop; + identity_manager_diagnostics_observer() + ->set_on_access_token_request_completed_callback(run_loop.QuitClosure()); + + account_tracker()->SeedAccountInfo(kTestGaiaId2, kTestEmail2); + std::string account_id2 = + account_tracker()->FindAccountInfoByGaiaId(kTestGaiaId2).account_id; + token_service()->UpdateCredentials(account_id2, "refresh_token"); + + std::set<std::string> scopes{"scope"}; + AccessTokenFetcher::TokenCallback callback = base::BindOnce( + [](GoogleServiceAuthError error, AccessTokenInfo access_token_info) {}); + // This should result in a request for an access token. + std::unique_ptr<AccessTokenFetcher> token_fetcher = + identity_manager()->CreateAccessTokenFetcherForAccount( + account_id2, "dummy_consumer 2", scopes, std::move(callback), + AccessTokenFetcher::Mode::kImmediate); + + // Revoke the refresh token result cancelling access token request. + token_service()->RevokeCredentials(account_id2); + + run_loop.Run(); + + EXPECT_TRUE(token_fetcher); + EXPECT_EQ(GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED), + identity_manager_diagnostics_observer() + ->on_access_token_request_completed_error()); +} + TEST_F(IdentityManagerTest, GetAccountsCookieMutator) { AccountsCookieMutator* mutator = identity_manager()->GetAccountsCookieMutator();
diff --git a/services/identity/public/cpp/identity_test_environment.cc b/services/identity/public/cpp/identity_test_environment.cc index da0d4d2..de01f26 100644 --- a/services/identity/public/cpp/identity_test_environment.cc +++ b/services/identity/public/cpp/identity_test_environment.cc
@@ -16,6 +16,7 @@ #include "services/identity/public/cpp/accounts_cookie_mutator.h" #include "services/identity/public/cpp/accounts_cookie_mutator_impl.h" #include "services/identity/public/cpp/accounts_mutator.h" +#include "services/identity/public/cpp/diagnostics_provider_impl.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" @@ -299,6 +300,9 @@ token_service_, account_tracker_service_, signin_manager_, pref_service_); #endif + std::unique_ptr<DiagnosticsProvider> diagnostics_provider = + std::make_unique<DiagnosticsProviderImpl>(token_service_, + gaia_cookie_manager_service_); std::unique_ptr<AccountsCookieMutator> accounts_cookie_mutator = std::make_unique<AccountsCookieMutatorImpl>( @@ -308,7 +312,7 @@ signin_manager_, token_service_, account_fetcher_service_, account_tracker_service_, gaia_cookie_manager_service_, std::move(primary_account_mutator), std::move(accounts_mutator), - std::move(accounts_cookie_mutator)); + std::move(accounts_cookie_mutator), std::move(diagnostics_provider)); } test_identity_manager_observer_ = @@ -584,4 +588,13 @@ picture_url); } +void IdentityTestEnvironment::SimulateMergeSessionFailure( + const GoogleServiceAuthError& auth_error) { + // GaiaCookieManagerService changes the visibility of inherited method + // OnMergeSessionFailure from public to private. Cast to a base class pointer + // to use call the method. + static_cast<GaiaAuthConsumer*>(gaia_cookie_manager_service_) + ->OnMergeSessionFailure(auth_error); +} + } // namespace identity
diff --git a/services/identity/public/cpp/identity_test_environment.h b/services/identity/public/cpp/identity_test_environment.h index d96249b0..220b1c0 100644 --- a/services/identity/public/cpp/identity_test_environment.h +++ b/services/identity/public/cpp/identity_test_environment.h
@@ -285,6 +285,9 @@ const std::string& locale, const std::string& picture_url); + // Simulates a merge session failure with |auth_error| as the error. + void SimulateMergeSessionFailure(const GoogleServiceAuthError& auth_error); + private: friend class ::IdentityTestEnvironmentChromeBrowserStateAdaptor; friend class ::IdentityTestEnvironmentProfileAdaptor;
diff --git a/services/media_session/audio_focus_manager.cc b/services/media_session/audio_focus_manager.cc index aeddd8a..84d249f4 100644 --- a/services/media_session/audio_focus_manager.cc +++ b/services/media_session/audio_focus_manager.cc
@@ -317,7 +317,7 @@ return; } - EnforceAudioFocusAbandon(); + EnforceAudioFocus(); MaybeUpdateActiveSession(); // Notify observers that we lost audio focus. @@ -416,27 +416,6 @@ std::move(callback).Run(); } -void AudioFocusManager::EnforceAudioFocusAbandon() { - // Allow the top-most MediaSession having force duck to unduck even if - // it is not active. - if (enforcement_mode_ != mojom::EnforcementMode::kNone) { - for (auto iter = audio_focus_stack_.rbegin(); - iter != audio_focus_stack_.rend(); ++iter) { - if (!(*iter)->info()->force_duck) - continue; - - // TODO(beccahughes): Replace with std::rotate. - auto duck_row = std::move(*iter); - duck_row->session()->StopDucking(); - audio_focus_stack_.erase(std::next(iter).base()); - audio_focus_stack_.push_back(std::move(duck_row)); - return; - } - } - - EnforceAudioFocus(); -} - void AudioFocusManager::EnforceAudioFocus() { DCHECK_NE(mojom::EnforcementMode::kDefault, enforcement_mode_); if (audio_focus_stack_.empty())
diff --git a/services/media_session/audio_focus_manager.h b/services/media_session/audio_focus_manager.h index 50d72f6..fb71e664 100644 --- a/services/media_session/audio_focus_manager.h +++ b/services/media_session/audio_focus_manager.h
@@ -107,7 +107,6 @@ base::OnceCallback<void()>); void AbandonAudioFocusInternal(RequestId); - void EnforceAudioFocusAbandon(); void EnforceAudioFocus(); void MaybeUpdateActiveSession();
diff --git a/services/media_session/audio_focus_manager_unittest.cc b/services/media_session/audio_focus_manager_unittest.cc index 029188f..3fdd27c 100644 --- a/services/media_session/audio_focus_manager_unittest.cc +++ b/services/media_session/audio_focus_manager_unittest.cc
@@ -680,8 +680,7 @@ GetState(&media_session_1)); } -TEST_P(AudioFocusManagerTest, - AbandoningGainFocusRevokesTopMostForceDuckSession) { +TEST_P(AudioFocusManagerTest, ForceDuckSessionShouldAlwaysBeDuckedFromGain) { test::MockMediaSession media_session_1(true /* force_duck */); test::MockMediaSession media_session_2; test::MockMediaSession media_session_3; @@ -702,8 +701,34 @@ GetState(&media_session_1)); media_session_3.AbandonAudioFocusFromClient(); - EXPECT_EQ(IsEnforcementEnabled() ? request_id_1 : request_id_2, - GetAudioFocusedSession()); + EXPECT_EQ(request_id_2, GetAudioFocusedSession()); + EXPECT_EQ(GetStateFromParam(mojom::MediaSessionInfo::SessionState::kDucking), + GetState(&media_session_1)); + + media_session_2.AbandonAudioFocusFromClient(); + EXPECT_EQ(request_id_1, GetAudioFocusedSession()); + EXPECT_EQ(mojom::MediaSessionInfo::SessionState::kActive, + GetState(&media_session_1)); +} + +TEST_P(AudioFocusManagerTest, + ForceDuckSessionShouldAlwaysBeDuckedFromTransient) { + test::MockMediaSession media_session_1(true /* force_duck */); + test::MockMediaSession media_session_2; + + AudioFocusManager::RequestId request_id_1 = + RequestAudioFocus(&media_session_1, mojom::AudioFocusType::kGain); + RequestAudioFocus(&media_session_2, mojom::AudioFocusType::kGainTransient); + + EXPECT_EQ(mojom::MediaSessionInfo::SessionState::kActive, + GetState(&media_session_2)); + EXPECT_EQ(GetStateFromParam(mojom::MediaSessionInfo::SessionState::kDucking), + GetState(&media_session_1)); + + media_session_2.AbandonAudioFocusFromClient(); + EXPECT_EQ(request_id_1, GetAudioFocusedSession()); + EXPECT_EQ(mojom::MediaSessionInfo::SessionState::kActive, + GetState(&media_session_1)); } TEST_P(AudioFocusManagerTest, AudioFocusObserver_RequestNoop) {
diff --git a/services/network/cookie_manager.cc b/services/network/cookie_manager.cc index 0b2ac0f..5565df5 100644 --- a/services/network/cookie_manager.cc +++ b/services/network/cookie_manager.cc
@@ -60,6 +60,18 @@ std::move(callback)); } +net::CookieStore::SetCookiesCallback StatusToBool( + base::OnceCallback<void(bool)> callback) { + return base::BindOnce( + [](base::OnceCallback<void(bool)> callback, + const net::CanonicalCookie::CookieInclusionStatus status) { + bool success = + (status == net::CanonicalCookie::CookieInclusionStatus::INCLUDE); + std::move(callback).Run(success); + }, + std::move(callback)); +} + } // namespace CookieManager::ListenerRegistration::ListenerRegistration() {} @@ -128,7 +140,7 @@ SetCanonicalCookieCallback callback) { cookie_store_->SetCanonicalCookieAsync( std::make_unique<net::CanonicalCookie>(cookie), secure_source, - modify_http_only, std::move(callback)); + modify_http_only, StatusToBool(std::move(callback))); } void CookieManager::DeleteCanonicalCookie(
diff --git a/services/network/cookie_manager_unittest.cc b/services/network/cookie_manager_unittest.cc index 2497c61..848122d5 100644 --- a/services/network/cookie_manager_unittest.cc +++ b/services/network/cookie_manager_unittest.cc
@@ -183,14 +183,17 @@ bool SetCanonicalCookie(const net::CanonicalCookie& cookie, bool secure_source, bool can_modify_httponly) { - net::ResultSavingCookieCallback<bool> callback; + net::ResultSavingCookieCallback<net::CanonicalCookie::CookieInclusionStatus> + callback; cookie_monster_->SetCanonicalCookieAsync( std::make_unique<net::CanonicalCookie>(cookie), secure_source, can_modify_httponly, - base::BindOnce(&net::ResultSavingCookieCallback<bool>::Run, + base::BindOnce(&net::ResultSavingCookieCallback< + net::CanonicalCookie::CookieInclusionStatus>::Run, base::Unretained(&callback))); callback.WaitUntilDone(); - return callback.result(); + return callback.result() == + net::CanonicalCookie::CookieInclusionStatus::INCLUDE; } std::string DumpAllCookies() {
diff --git a/services/network/cross_origin_read_blocking.cc b/services/network/cross_origin_read_blocking.cc index 38bd1e4d..43a06b1 100644 --- a/services/network/cross_origin_read_blocking.cc +++ b/services/network/cross_origin_read_blocking.cc
@@ -568,6 +568,12 @@ const ResourceResponse& response, base::Optional<url::Origin> request_initiator_site_lock, mojom::FetchRequestMode fetch_request_mode) { + // TODO(lukasza): Remove |initiator_compatibility_| field once the UMAs + // depending on it are expired (e.g. see + // SiteIsolation.XSD.NetworkService.InitiatorLockCompatibility). + initiator_compatibility_ = VerifyRequestInitiatorLock( + request_initiator_site_lock, request.initiator()); + content_length_ = response.head.content_length; http_response_code_ = response.head.headers ? response.head.headers->response_code() : 0; @@ -600,16 +606,14 @@ return kAllow; } - // Treat a missing initiator as an empty origin to be safe, though we don't - // expect this to happen. Unfortunately, this requires a copy. - url::Origin initiator; - initiator_compatibility_ = VerifyRequestInitiatorLock( - request_initiator_site_lock_, request.initiator()); - bool block_untrustworthy_initiator = - ShouldEnforceInitiatorLock() && - initiator_compatibility_ == InitiatorLockCompatibility::kIncorrectLock; - if (request.initiator().has_value() && !block_untrustworthy_initiator) - initiator = request.initiator().value(); + // Compute the |initiator| of the request, falling back to a unique origin if + // there was no initiator or if it was incompatible with the lock. Using a + // unique origin makes CORB treat the response as cross-origin and thus + // considers it eligible for blocking (based on content-type, sniffing, etc.). + url::Origin initiator = GetTrustworthyInitiator( + ShouldEnforceInitiatorLock() ? request_initiator_site_lock_ + : base::nullopt, + request); // Don't block same-origin documents. if (initiator.IsSameOriginWith(target_origin))
diff --git a/services/network/cross_origin_resource_policy.cc b/services/network/cross_origin_resource_policy.cc index 7b55b7d2..4737cc7 100644 --- a/services/network/cross_origin_resource_policy.cc +++ b/services/network/cross_origin_resource_policy.cc
@@ -124,22 +124,12 @@ return kAllow; } - // Compute |target_origin| and |initiator|. Initial, opaque |initiator| will - // be used unless request.initiator() has a value that is compatible with the - // |request_initiator_site_lock|. - url::Origin target_origin = url::Origin::Create(request.url()); - url::Origin initiator; - InitiatorLockCompatibility initiator_compatibility = - VerifyRequestInitiatorLock(request_initiator_site_lock, - request.initiator()); - if (request.initiator().has_value() && - initiator_compatibility != InitiatorLockCompatibility::kIncorrectLock) { - initiator = request.initiator().value(); - } - // From https://fetch.spec.whatwg.org/#cross-origin-resource-policy-header: // > 2. If request’s origin is same origin with request’s current URL’s // origin, then return allowed. + url::Origin target_origin = url::Origin::Create(request.url()); + url::Origin initiator = + GetTrustworthyInitiator(request_initiator_site_lock, request); if (initiator == target_origin) return kAllow;
diff --git a/services/network/initiator_lock_compatibility.cc b/services/network/initiator_lock_compatibility.cc index 7ca032b..1fcec799 100644 --- a/services/network/initiator_lock_compatibility.cc +++ b/services/network/initiator_lock_compatibility.cc
@@ -68,4 +68,24 @@ request.request_initiator); } +url::Origin GetTrustworthyInitiator( + const base::Optional<url::Origin>& request_initiator_site_lock, + const net::URLRequest& request) { + // Returning a unique origin as a fallback should be safe - such origin will + // be considered cross-origin from all other origins. + url::Origin unique_origin_fallback; + + if (!request.initiator().has_value()) + return unique_origin_fallback; + + InitiatorLockCompatibility initiator_compatibility = + VerifyRequestInitiatorLock(request_initiator_site_lock, + request.initiator()); + if (initiator_compatibility == InitiatorLockCompatibility::kIncorrectLock) + return unique_origin_fallback; + + // If all the checks above passed, then |request.initiator()| is trustworthy. + return request.initiator().value(); +} + } // namespace network
diff --git a/services/network/initiator_lock_compatibility.h b/services/network/initiator_lock_compatibility.h index 6b18910..d0d7ff8 100644 --- a/services/network/initiator_lock_compatibility.h +++ b/services/network/initiator_lock_compatibility.h
@@ -9,6 +9,10 @@ #include "base/optional.h" #include "url/origin.h" +namespace net { +class URLRequest; +} // namespace net + namespace network { struct ResourceRequest; @@ -59,6 +63,16 @@ const base::Optional<url::Origin>& request_initiator_site_lock, const base::Optional<url::Origin>& request_initiator); +// Gets initiator of |request|, falling back to a unique origin if +// 1) |request.initiator()| is missing or +// 2) |request.initiator()| is incompatible with |request_initiator_site_lock|. +// +// |request_initiator_site_lock| should come from +// URLLoaderFactoryParams::request_initiator_site_lock. +url::Origin GetTrustworthyInitiator( + const base::Optional<url::Origin>& request_initiator_site_lock, + const net::URLRequest& request); + } // namespace network #endif // SERVICES_NETWORK_INITIATOR_LOCK_COMPATIBILITY_H_
diff --git a/services/network/mojo_host_resolver_impl.cc b/services/network/mojo_host_resolver_impl.cc index 4811c4a7..6f31cac 100644 --- a/services/network/mojo_host_resolver_impl.cc +++ b/services/network/mojo_host_resolver_impl.cc
@@ -5,12 +5,15 @@ #include "services/network/mojo_host_resolver_impl.h" #include <utility> +#include <vector> #include "base/bind.h" -#include "net/base/address_list.h" +#include "base/logging.h" +#include "net/base/host_port_pair.h" +#include "net/base/ip_address.h" #include "net/base/net_errors.h" -#include "net/base/network_interfaces.h" #include "net/dns/host_resolver.h" +#include "net/dns/public/dns_query_type.h" namespace network { @@ -21,7 +24,8 @@ public: Job(MojoHostResolverImpl* resolver_service, net::HostResolver* resolver, - const net::HostResolver::RequestInfo& request_info, + const std::string& hostname, + bool is_ex, const net::NetLogWithSource& net_log, proxy_resolver::mojom::HostResolverRequestClientPtr client); ~Job(); @@ -41,12 +45,9 @@ // This Job's iterator in |resolver_service_|, so the Job may be removed on // completion. std::list<Job>::iterator iter_; - net::HostResolver* resolver_; - net::HostResolver::RequestInfo request_info_; - const net::NetLogWithSource net_log_; proxy_resolver::mojom::HostResolverRequestClientPtr client_; - std::unique_ptr<net::HostResolver::Request> request_; - net::AddressList result_; + const std::string hostname_; + std::unique_ptr<net::HostResolver::ResolveHostRequest> request_; base::ThreadChecker thread_checker_; }; @@ -59,17 +60,12 @@ } void MojoHostResolverImpl::Resolve( - std::unique_ptr<net::HostResolver::RequestInfo> request_info, + const std::string& hostname, + bool is_ex, proxy_resolver::mojom::HostResolverRequestClientPtr client) { DCHECK(thread_checker_.CalledOnValidThread()); - if (request_info->is_my_ip_address()) { - // The proxy resolver running inside a sandbox may not be able to get the - // correct host name. Instead, fill it ourself if the request is for our own - // IP address. - request_info->set_host_port_pair(net::HostPortPair(net::GetHostName(), 80)); - } - pending_jobs_.emplace_front(this, resolver_, *request_info, net_log_, + pending_jobs_.emplace_front(this, resolver_, hostname, is_ex, net_log_, std::move(client)); auto job = pending_jobs_.begin(); job->set_iter(job); @@ -84,28 +80,30 @@ MojoHostResolverImpl::Job::Job( MojoHostResolverImpl* resolver_service, net::HostResolver* resolver, - const net::HostResolver::RequestInfo& request_info, + const std::string& hostname, + bool is_ex, const net::NetLogWithSource& net_log, proxy_resolver::mojom::HostResolverRequestClientPtr client) : resolver_service_(resolver_service), - resolver_(resolver), - request_info_(request_info), - net_log_(net_log), - client_(std::move(client)) { + client_(std::move(client)), + hostname_(hostname) { client_.set_connection_error_handler(base::Bind( &MojoHostResolverImpl::Job::OnConnectionError, base::Unretained(this))); + + net::HostResolver::ResolveHostParameters parameters; + if (!is_ex) + parameters.dns_query_type = net::DnsQueryType::A; + request_ = resolver->CreateRequest(net::HostPortPair(hostname_, 0), net_log, + parameters); } void MojoHostResolverImpl::Job::Start() { // The caller is responsible for setting up |iter_|. DCHECK_EQ(this, &*iter_); - DVLOG(1) << "Resolve " << request_info_.host_port_pair().ToString(); - int result = - resolver_->Resolve(request_info_, net::DEFAULT_PRIORITY, &result_, - base::Bind(&MojoHostResolverImpl::Job::OnResolveDone, - base::Unretained(this)), - &request_, net_log_); + DVLOG(1) << "Resolve " << hostname_; + int result = request_->Start(base::BindOnce( + &MojoHostResolverImpl::Job::OnResolveDone, base::Unretained(this))); if (result != net::ERR_IO_PENDING) OnResolveDone(result); @@ -115,14 +113,23 @@ void MojoHostResolverImpl::Job::OnResolveDone(int result) { DCHECK(thread_checker_.CalledOnValidThread()); + + std::vector<net::IPAddress> result_addresses; + if (request_->GetAddressResults()) { + for (const auto& endpoint : + request_->GetAddressResults().value().endpoints()) { + result_addresses.push_back(endpoint.address()); + } + } + request_.reset(); - DVLOG(1) << "Resolved " << request_info_.host_port_pair().ToString() - << " with error " << result << " and " << result_.size() - << " results!"; - for (const auto& address : result_) { + DVLOG(1) << "Resolved " << hostname_ << " with error " << result << " and " + << result_addresses.size() << " results!"; + for (const auto& address : result_addresses) { DVLOG(1) << address.ToString(); } - client_->ReportResult(result, result_); + client_->ReportResult(result, result_addresses); + resolver_service_->DeleteJob(iter_); } @@ -130,8 +137,7 @@ DCHECK(thread_checker_.CalledOnValidThread()); // |resolver_service_| should always outlive us. DCHECK(resolver_service_); - DVLOG(1) << "Connection error on request for " - << request_info_.host_port_pair().ToString(); + DVLOG(1) << "Connection error on request for " << hostname_; resolver_service_->DeleteJob(iter_); }
diff --git a/services/network/mojo_host_resolver_impl.h b/services/network/mojo_host_resolver_impl.h index 33016bc3..a13169e 100644 --- a/services/network/mojo_host_resolver_impl.h +++ b/services/network/mojo_host_resolver_impl.h
@@ -7,6 +7,7 @@ #include <list> #include <memory> +#include <string> #include "base/component_export.h" #include "base/macros.h" @@ -36,7 +37,8 @@ const net::NetLogWithSource& net_log); ~MojoHostResolverImpl(); - void Resolve(std::unique_ptr<net::HostResolver::RequestInfo> request_info, + void Resolve(const std::string& hostname, + bool is_ex, proxy_resolver::mojom::HostResolverRequestClientPtr client); bool request_in_progress() { return !pending_jobs_.empty(); }
diff --git a/services/network/mojo_host_resolver_impl_unittest.cc b/services/network/mojo_host_resolver_impl_unittest.cc index 6024b9a6..02b2f68 100644 --- a/services/network/mojo_host_resolver_impl_unittest.cc +++ b/services/network/mojo_host_resolver_impl_unittest.cc
@@ -6,6 +6,7 @@ #include <string> #include <utility> +#include <vector> #include "base/bind.h" #include "base/callback_helpers.h" @@ -14,7 +15,8 @@ #include "base/time/time.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/interface_request.h" -#include "net/base/address_list.h" +#include "net/base/address_family.h" +#include "net/base/ip_address.h" #include "net/base/net_errors.h" #include "net/dns/mock_host_resolver.h" #include "net/test/gtest_util.h" @@ -43,11 +45,12 @@ void WaitForConnectionError(); int32_t error_; - net::AddressList results_; + std::vector<net::IPAddress> results_; private: // Overridden from proxy_resolver::mojom::HostResolverRequestClient. - void ReportResult(int32_t error, const net::AddressList& results) override; + void ReportResult(int32_t error, + const std::vector<net::IPAddress>& results) override; // Mojo error handler. void OnConnectionError(); @@ -75,8 +78,9 @@ run_loop.Run(); } -void TestRequestClient::ReportResult(int32_t error, - const net::AddressList& results) { +void TestRequestClient::ReportResult( + int32_t error, + const std::vector<net::IPAddress>& results) { if (!run_loop_quit_closure_.is_null()) { run_loop_quit_closure_.Run(); } @@ -91,78 +95,39 @@ connection_error_quit_closure_.Run(); } -class CallbackMockHostResolver : public net::MockHostResolver { - public: - CallbackMockHostResolver() = default; - ~CallbackMockHostResolver() override = default; - - // Set a callback to run whenever Resolve is called. Callback is cleared after - // every run. - void SetResolveCallback(base::Closure callback) { - resolve_callback_ = callback; - } - - // Overridden from MockHostResolver. - int Resolve(const RequestInfo& info, - net::RequestPriority priority, - net::AddressList* addresses, - net::CompletionOnceCallback callback, - std::unique_ptr<Request>* request, - const net::NetLogWithSource& net_log) override; - - private: - base::Closure resolve_callback_; -}; - -int CallbackMockHostResolver::Resolve(const RequestInfo& info, - net::RequestPriority priority, - net::AddressList* addresses, - net::CompletionOnceCallback callback, - std::unique_ptr<Request>* request, - const net::NetLogWithSource& net_log) { - int result = MockHostResolver::Resolve(info, priority, addresses, - std::move(callback), request, net_log); - if (!resolve_callback_.is_null()) { - std::move(resolve_callback_).Run(); - } - return result; -} - } // namespace class MojoHostResolverImplTest : public testing::Test { protected: + const net::IPAddress kExampleComAddress{1, 2, 3, 4}; + const net::IPAddress kExampleComAddressIpv6{1, 2, 3, 4, 5, 6, 7, 8, + 9, 10, 11, 12, 13, 14, 15, 16}; + const net::IPAddress kChromiumOrgAddress{8, 8, 8, 8}; + void SetUp() override { - mock_host_resolver_.rules()->AddRule("example.com", "1.2.3.4"); - mock_host_resolver_.rules()->AddRule("chromium.org", "8.8.8.8"); + mock_host_resolver_.rules()->AddRuleForAddressFamily( + "example.com", net::ADDRESS_FAMILY_IPV4, kExampleComAddress.ToString()); + mock_host_resolver_.rules()->AddRule("example.com", + kExampleComAddressIpv6.ToString()); + mock_host_resolver_.rules()->AddRule("chromium.org", + kChromiumOrgAddress.ToString()); mock_host_resolver_.rules()->AddSimulatedFailure("failure.fail"); resolver_service_.reset(new MojoHostResolverImpl(&mock_host_resolver_, net::NetLogWithSource())); } - std::unique_ptr<net::HostResolver::RequestInfo> - CreateRequest(const std::string& host, uint16_t port, bool is_my_ip_address) { - std::unique_ptr<net::HostResolver::RequestInfo> request = - std::make_unique<net::HostResolver::RequestInfo>( - net::HostPortPair(host, port)); - request->set_is_my_ip_address(is_my_ip_address); - request->set_address_family(net::ADDRESS_FAMILY_IPV4); - return request; - } - // Wait until the mock resolver has received |num| resolve requests. void WaitForRequests(size_t num) { while (mock_host_resolver_.num_resolve() < num) { base::RunLoop run_loop; - mock_host_resolver_.SetResolveCallback(run_loop.QuitClosure()); - run_loop.Run(); + run_loop.RunUntilIdle(); } } base::test::ScopedTaskEnvironment scoped_task_environment_; - CallbackMockHostResolver mock_host_resolver_; + net::MockHostResolver mock_host_resolver_; std::unique_ptr<MojoHostResolverImpl> resolver_service_; }; @@ -170,14 +135,12 @@ proxy_resolver::mojom::HostResolverRequestClientPtr client_ptr; TestRequestClient client(mojo::MakeRequest(&client_ptr)); - resolver_service_->Resolve(CreateRequest("example.com", 80, false), + resolver_service_->Resolve("example.com", false /* is_ex */, std::move(client_ptr)); client.WaitForResult(); EXPECT_THAT(client.error_, IsOk()); - net::AddressList& address_list = client.results_; - EXPECT_EQ(1U, address_list.size()); - EXPECT_EQ("1.2.3.4:80", address_list[0].ToString()); + EXPECT_THAT(client.results_, testing::ElementsAre(kExampleComAddress)); } TEST_F(MojoHostResolverImplTest, ResolveSynchronous) { @@ -186,14 +149,12 @@ mock_host_resolver_.set_synchronous_mode(true); - resolver_service_->Resolve(CreateRequest("example.com", 80, false), + resolver_service_->Resolve("example.com", false /* is_ex */, std::move(client_ptr)); client.WaitForResult(); EXPECT_THAT(client.error_, IsOk()); - net::AddressList& address_list = client.results_; - EXPECT_EQ(1U, address_list.size()); - EXPECT_EQ("1.2.3.4:80", address_list[0].ToString()); + EXPECT_THAT(client.results_, testing::ElementsAre(kExampleComAddress)); } TEST_F(MojoHostResolverImplTest, ResolveMultiple) { @@ -204,9 +165,9 @@ mock_host_resolver_.set_ondemand_mode(true); - resolver_service_->Resolve(CreateRequest("example.com", 80, false), + resolver_service_->Resolve("example.com", false /* is_ex */, std::move(client1_ptr)); - resolver_service_->Resolve(CreateRequest("chromium.org", 80, false), + resolver_service_->Resolve("chromium.org", false /* is_ex */, std::move(client2_ptr)); WaitForRequests(2); mock_host_resolver_.ResolveAllPending(); @@ -215,13 +176,9 @@ client2.WaitForResult(); EXPECT_THAT(client1.error_, IsOk()); - net::AddressList& address_list1 = client1.results_; - EXPECT_EQ(1U, address_list1.size()); - EXPECT_EQ("1.2.3.4:80", address_list1[0].ToString()); + EXPECT_THAT(client1.results_, testing::ElementsAre(kExampleComAddress)); EXPECT_THAT(client2.error_, IsOk()); - net::AddressList& address_list2 = client2.results_; - EXPECT_EQ(1U, address_list2.size()); - EXPECT_EQ("8.8.8.8:80", address_list2[0].ToString()); + EXPECT_THAT(client2.results_, testing::ElementsAre(kChromiumOrgAddress)); } TEST_F(MojoHostResolverImplTest, ResolveDuplicate) { @@ -232,9 +189,9 @@ mock_host_resolver_.set_ondemand_mode(true); - resolver_service_->Resolve(CreateRequest("example.com", 80, false), + resolver_service_->Resolve("example.com", false /* is_ex */, std::move(client1_ptr)); - resolver_service_->Resolve(CreateRequest("example.com", 80, false), + resolver_service_->Resolve("example.com", false /* is_ex */, std::move(client2_ptr)); WaitForRequests(2); mock_host_resolver_.ResolveAllPending(); @@ -243,20 +200,16 @@ client2.WaitForResult(); EXPECT_THAT(client1.error_, IsOk()); - net::AddressList& address_list1 = client1.results_; - EXPECT_EQ(1U, address_list1.size()); - EXPECT_EQ("1.2.3.4:80", address_list1[0].ToString()); + EXPECT_THAT(client1.results_, testing::ElementsAre(kExampleComAddress)); EXPECT_THAT(client2.error_, IsOk()); - net::AddressList& address_list2 = client2.results_; - EXPECT_EQ(1U, address_list2.size()); - EXPECT_EQ("1.2.3.4:80", address_list2[0].ToString()); + EXPECT_THAT(client2.results_, testing::ElementsAre(kExampleComAddress)); } TEST_F(MojoHostResolverImplTest, ResolveFailure) { proxy_resolver::mojom::HostResolverRequestClientPtr client_ptr; TestRequestClient client(mojo::MakeRequest(&client_ptr)); - resolver_service_->Resolve(CreateRequest("failure.fail", 80, false), + resolver_service_->Resolve("failure.fail", false /* is_ex */, std::move(client_ptr)); client.WaitForResult(); @@ -264,6 +217,18 @@ EXPECT_TRUE(client.results_.empty()); } +TEST_F(MojoHostResolverImplTest, ResolveEx) { + proxy_resolver::mojom::HostResolverRequestClientPtr client_ptr; + TestRequestClient client(mojo::MakeRequest(&client_ptr)); + + resolver_service_->Resolve("example.com", true /* is_ex */, + std::move(client_ptr)); + client.WaitForResult(); + + EXPECT_THAT(client.error_, IsOk()); + EXPECT_THAT(client.results_, testing::ElementsAre(kExampleComAddressIpv6)); +} + TEST_F(MojoHostResolverImplTest, DestroyClient) { proxy_resolver::mojom::HostResolverRequestClientPtr client_ptr; std::unique_ptr<TestRequestClient> client( @@ -271,7 +236,7 @@ mock_host_resolver_.set_ondemand_mode(true); - resolver_service_->Resolve(CreateRequest("example.com", 80, false), + resolver_service_->Resolve("example.com", false /* is_ex */, std::move(client_ptr)); WaitForRequests(1);
diff --git a/services/network/proxy_config_service_mojo_unittest.cc b/services/network/proxy_config_service_mojo_unittest.cc index ed7b315..207694c9 100644 --- a/services/network/proxy_config_service_mojo_unittest.cc +++ b/services/network/proxy_config_service_mojo_unittest.cc
@@ -62,26 +62,48 @@ DISALLOW_COPY_AND_ASSIGN(TestProxyConfigServiceObserver); }; +// Test fixture for notifying ProxyConfigServiceMojo of changes through the +// client interface, and watching the subsequent values it emits to registered +// net::ProxyConfigService::Observers. +class ProxyConfigServiceMojoTest : public testing::Test { + public: + ProxyConfigServiceMojoTest() + : scoped_task_environment_( + base::test::ScopedTaskEnvironment::MainThreadType::IO), + proxy_config_service_(mojo::MakeRequest(&config_client_), + base::Optional<net::ProxyConfigWithAnnotation>(), + nullptr), + observer_(&proxy_config_service_) { + proxy_config_service_.AddObserver(&observer_); + } + + ~ProxyConfigServiceMojoTest() override { + proxy_config_service_.RemoveObserver(&observer_); + } + + protected: + // After notifying a new configuration through |config_client_|, waits for the + // observers to have been notified. + void WaitForConfig() { scoped_task_environment_.RunUntilIdle(); } + + base::test::ScopedTaskEnvironment scoped_task_environment_; + mojom::ProxyConfigClientPtr config_client_; + ProxyConfigServiceMojo proxy_config_service_; + TestProxyConfigServiceObserver observer_; + + DISALLOW_COPY_AND_ASSIGN(ProxyConfigServiceMojoTest); +}; + // Most tests of this class are in network_context_unittests. // Makes sure that a ProxyConfigService::Observer is correctly notified of // changes when the ProxyConfig changes, and is not informed of them in the case // of "changes" that result in the same ProxyConfig as before. -TEST(ProxyConfigServiceMojoTest, ObserveProxyChanges) { - base::test::ScopedTaskEnvironment scoped_task_environment( - base::test::ScopedTaskEnvironment::MainThreadType::IO); - - mojom::ProxyConfigClientPtr config_client; - ProxyConfigServiceMojo proxy_config_service( - mojo::MakeRequest(&config_client), - base::Optional<net::ProxyConfigWithAnnotation>(), nullptr); - TestProxyConfigServiceObserver observer(&proxy_config_service); - proxy_config_service.AddObserver(&observer); - +TEST_F(ProxyConfigServiceMojoTest, ObserveProxyChanges) { net::ProxyConfigWithAnnotation proxy_config; // The service should start without a config. EXPECT_EQ(net::ProxyConfigService::CONFIG_PENDING, - proxy_config_service.GetLatestProxyConfig(&proxy_config)); + proxy_config_service_.GetLatestProxyConfig(&proxy_config)); net::ProxyConfig proxy_configs[3]; proxy_configs[0].proxy_rules().ParseFromString("http=foopy:80"); @@ -90,29 +112,62 @@ for (const auto& proxy_config : proxy_configs) { // Set the proxy configuration to something that does not match the old one. - config_client->OnProxyConfigUpdated(net::ProxyConfigWithAnnotation( + config_client_->OnProxyConfigUpdated(net::ProxyConfigWithAnnotation( proxy_config, TRAFFIC_ANNOTATION_FOR_TESTS)); - scoped_task_environment.RunUntilIdle(); - EXPECT_EQ(1, observer.GetAndResetConfigChanges()); - EXPECT_TRUE(proxy_config.Equals(observer.observed_config().value())); + WaitForConfig(); + EXPECT_EQ(1, observer_.GetAndResetConfigChanges()); + EXPECT_TRUE(proxy_config.Equals(observer_.observed_config().value())); net::ProxyConfigWithAnnotation retrieved_config; EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID, - proxy_config_service.GetLatestProxyConfig(&retrieved_config)); + proxy_config_service_.GetLatestProxyConfig(&retrieved_config)); EXPECT_TRUE(proxy_config.Equals(retrieved_config.value())); // Set the proxy configuration to the same value again. There should be not // be another proxy config changed notification. - config_client->OnProxyConfigUpdated(net::ProxyConfigWithAnnotation( + config_client_->OnProxyConfigUpdated(net::ProxyConfigWithAnnotation( proxy_config, TRAFFIC_ANNOTATION_FOR_TESTS)); - scoped_task_environment.RunUntilIdle(); - EXPECT_EQ(0, observer.GetAndResetConfigChanges()); - EXPECT_TRUE(proxy_config.Equals(observer.observed_config().value())); + WaitForConfig(); + EXPECT_EQ(0, observer_.GetAndResetConfigChanges()); + EXPECT_TRUE(proxy_config.Equals(observer_.observed_config().value())); EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID, - proxy_config_service.GetLatestProxyConfig(&retrieved_config)); + proxy_config_service_.GetLatestProxyConfig(&retrieved_config)); EXPECT_TRUE(proxy_config.Equals(retrieved_config.value())); } +} - proxy_config_service.RemoveObserver(&observer); +// Creates a URL that has length |url::kMaxURLChars + 1|. +GURL CreateLargeURL() { + std::string spec; + spec.reserve(url::kMaxURLChars + 1); + spec.assign("http://test.invalid/"); + spec.append(url::kMaxURLChars + 1 - spec.size(), 'x'); + return GURL(spec); +} + +// Tests what happens when ProxyConfigServiceMojo is updated to using a +// ProxyConfig with a large URL. GURL does not impose size limits, however some +// internals like url.mojom.Url do. +TEST_F(ProxyConfigServiceMojoTest, LargePacUrlNotTruncated) { + // Create a config using a large, valid, PAC URL. + net::ProxyConfig orig_config; + GURL large_url = CreateLargeURL(); + EXPECT_TRUE(large_url.is_valid()); + EXPECT_EQ(url::kMaxURLChars + 1, large_url.possibly_invalid_spec().size()); + orig_config.set_pac_url(large_url); + + // Notify the ProxyConfigServiceMojo of this URL through the client interface. + config_client_->OnProxyConfigUpdated(net::ProxyConfigWithAnnotation( + orig_config, TRAFFIC_ANNOTATION_FOR_TESTS)); + + WaitForConfig(); + + // Read back the ProxyConfig that was observed (which has been serialized + // through a Mojo pipe). + const GURL& observed_url = observer_.observed_config().value().pac_url(); + + // The URL should be unchanged, and not changed by the Mojo serialization. + EXPECT_EQ(large_url, observed_url); + EXPECT_EQ(url::kMaxURLChars + 1, observed_url.possibly_invalid_spec().size()); } } // namespace
diff --git a/services/network/proxy_resolver_factory_mojo.cc b/services/network/proxy_resolver_factory_mojo.cc index b398f5d9..5d6a8c5 100644 --- a/services/network/proxy_resolver_factory_mojo.cc +++ b/services/network/proxy_resolver_factory_mojo.cc
@@ -5,7 +5,9 @@ #include "services/network/proxy_resolver_factory_mojo.h" #include <set> +#include <string> #include <utility> +#include <vector> #include "base/bind.h" #include "base/callback.h" @@ -18,6 +20,7 @@ #include "base/task_runner.h" #include "base/values.h" #include "mojo/public/cpp/bindings/binding.h" +#include "net/base/ip_address.h" #include "net/base/load_states.h" #include "net/base/net_errors.h" #include "net/log/net_log.h" @@ -27,6 +30,7 @@ #include "net/proxy_resolution/pac_file_data.h" #include "net/proxy_resolution/pac_library.h" #include "net/proxy_resolution/proxy_info.h" +#include "net/proxy_resolution/proxy_resolve_dns_operation.h" #include "net/proxy_resolution/proxy_resolver.h" #include "net/proxy_resolution/proxy_resolver_error_observer.h" #include "services/network/mojo_host_resolver_impl.h" @@ -52,7 +56,7 @@ bool is_ex, proxy_resolver::mojom::HostResolverRequestClientPtrInfo client_info) { // Resolve the list of IP addresses. - net::IPAddressList my_ip_addresses = + std::vector<net::IPAddress> my_ip_addresses = is_ex ? net::PacMyIpAddressEx() : net::PacMyIpAddress(); proxy_resolver::mojom::HostResolverRequestClientPtr client; @@ -68,11 +72,7 @@ if (my_ip_addresses.empty()) my_ip_addresses.push_back(net::IPAddress::IPv4Localhost()); - // Convert to a net::AddressList. - net::AddressList list; - for (const auto& ip : my_ip_addresses) - list.push_back(net::IPEndPoint(ip, 80)); - client->ReportResult(net::OK, list); + client->ReportResult(net::OK, my_ip_addresses); } // A mixin that forwards logging to (Bound)NetLog and ProxyResolverErrorObserver @@ -116,18 +116,20 @@ // TODO(eroman): Split the client interfaces so ResolveDns() does not also // carry the myIpAddress(Ex) requests. void ResolveDns( - std::unique_ptr<net::HostResolver::RequestInfo> request_info, + const std::string& hostname, + net::ProxyResolveDnsOperation operation, proxy_resolver::mojom::HostResolverRequestClientPtr client) override { - if (request_info->is_my_ip_address()) { - bool is_ex = - request_info->address_family() == net::ADDRESS_FAMILY_UNSPECIFIED; + bool is_ex = operation == net::ProxyResolveDnsOperation::DNS_RESOLVE_EX || + operation == net::ProxyResolveDnsOperation::MY_IP_ADDRESS_EX; + if (operation == net::ProxyResolveDnsOperation::MY_IP_ADDRESS || + operation == net::ProxyResolveDnsOperation::MY_IP_ADDRESS_EX) { GetMyIpAddressTaskRuner()->PostTask( FROM_HERE, base::BindOnce(&DoMyIpAddressOnWorker, is_ex, client.PassInterface())); } else { // Request was for dnsResolve() or dnsResolveEx(). - host_resolver_.Resolve(std::move(request_info), std::move(client)); + host_resolver_.Resolve(hostname, is_ex, std::move(client)); } }
diff --git a/services/network/proxy_resolver_factory_mojo_unittest.cc b/services/network/proxy_resolver_factory_mojo_unittest.cc index 0bc76797..c3756ab 100644 --- a/services/network/proxy_resolver_factory_mojo_unittest.cc +++ b/services/network/proxy_resolver_factory_mojo_unittest.cc
@@ -21,12 +21,13 @@ #include "net/base/load_states.h" #include "net/base/net_errors.h" #include "net/base/test_completion_callback.h" -#include "net/dns/host_resolver.h" +#include "net/dns/mock_host_resolver.h" #include "net/log/net_log_event_type.h" #include "net/log/net_log_with_source.h" #include "net/log/test_net_log.h" #include "net/proxy_resolution/pac_file_data.h" #include "net/proxy_resolution/proxy_info.h" +#include "net/proxy_resolution/proxy_resolve_dns_operation.h" #include "net/proxy_resolution/proxy_resolver.h" #include "net/proxy_resolution/proxy_resolver_error_observer.h" #include "net/proxy_resolution/proxy_resolver_factory.h" @@ -275,11 +276,11 @@ break; } case GetProxyForUrlAction::MAKE_DNS_REQUEST: { - auto request = std::make_unique<net::HostResolver::RequestInfo>( - net::HostPortPair(url.spec(), 12345)); proxy_resolver::mojom::HostResolverRequestClientPtr dns_client; mojo::MakeRequest(&dns_client); - client->ResolveDns(std::move(request), std::move(dns_client)); + client->ResolveDns(url.host(), + net::ProxyResolveDnsOperation::DNS_RESOLVE_EX, + std::move(dns_client)); blocked_clients_.push_back( std::make_unique< proxy_resolver::mojom::ProxyResolverRequestClientPtr>( @@ -455,11 +456,11 @@ break; } case CreateProxyResolverAction::MAKE_DNS_REQUEST: { - auto request = std::make_unique<net::HostResolver::RequestInfo>( - net::HostPortPair(pac_script, 12345)); proxy_resolver::mojom::HostResolverRequestClientPtr dns_client; mojo::MakeRequest(&dns_client); - client->ResolveDns(std::move(request), std::move(dns_client)); + client->ResolveDns(pac_script, + net::ProxyResolveDnsOperation::DNS_RESOLVE_EX, + std::move(dns_client)); blocked_clients_.push_back( std::make_unique< proxy_resolver::mojom::ProxyResolverFactoryRequestClientPtr>( @@ -480,61 +481,6 @@ std::move(callback).Run(result); } -class MockHostResolver : public net::HostResolver { - public: - enum Event { - DNS_REQUEST, - }; - - // net::HostResolver overrides. - std::unique_ptr<HostResolver::ResolveHostRequest> CreateRequest( - const net::HostPortPair& host, - const net::NetLogWithSource& source_net_log, - const base::Optional<ResolveHostParameters>& optional_parameters) - override { - // TODO(crbug.com/821021): Implement. - NOTIMPLEMENTED(); - return nullptr; - } - - int Resolve(const RequestInfo& info, - net::RequestPriority priority, - net::AddressList* addresses, - net::CompletionOnceCallback callback, - std::unique_ptr<Request>* request, - const net::NetLogWithSource& source_net_log) override { - waiter_.NotifyEvent(DNS_REQUEST); - return net::ERR_IO_PENDING; - } - - int ResolveFromCache(const RequestInfo& info, - net::AddressList* addresses, - const net::NetLogWithSource& source_net_log) override { - return net::ERR_DNS_CACHE_MISS; - } - - int ResolveStaleFromCache( - const RequestInfo& info, - net::AddressList* addresses, - net::HostCache::EntryStaleness* stale_info, - const net::NetLogWithSource& source_net_log) override { - return net::ERR_DNS_CACHE_MISS; - } - - net::HostCache* GetHostCache() override { return nullptr; } - - bool HasCached(base::StringPiece hostname, - net::HostCache::Entry::Source* source_out, - net::HostCache::EntryStaleness* stale_out) const override { - return false; - } - - net::EventWaiter<Event>& waiter() { return waiter_; } - - private: - net::EventWaiter<Event> waiter_; -}; - void CheckCapturedNetLogEntries(const std::string& expected_string, const net::TestNetLogEntry::List& entries) { ASSERT_EQ(2u, entries.size()); @@ -598,7 +544,7 @@ } base::test::ScopedTaskEnvironment task_environment_; - MockHostResolver host_resolver_; + net::HangingHostResolver host_resolver_; net::TestNetLog net_log_; std::unique_ptr<MockMojoProxyResolverFactory> mock_proxy_resolver_factory_; std::unique_ptr<net::ProxyResolverFactory> proxy_resolver_factory_mojo_; @@ -804,9 +750,13 @@ proxy_resolver_factory_mojo_->CreateProxyResolver( pac_script, &proxy_resolver_mojo_, callback.callback(), &request)); ASSERT_TRUE(request); - host_resolver_.waiter().WaitForEvent(MockHostResolver::DNS_REQUEST); + + base::RunLoop run_loop; + run_loop.RunUntilIdle(); + mock_proxy_resolver_factory_->ClearBlockedClients(); callback.WaitForResult(); + EXPECT_EQ(1, host_resolver_.num_cancellations()); } TEST_F(ProxyResolverFactoryMojoTest, GetProxyForURL) { @@ -972,10 +922,12 @@ EXPECT_THAT(request->Resolve(), IsError(net::ERR_IO_PENDING)); EXPECT_EQ(net::LOAD_STATE_RESOLVING_PROXY_FOR_URL, request->load_state()); - host_resolver_.waiter().WaitForEvent(MockHostResolver::DNS_REQUEST); - EXPECT_EQ(net::LOAD_STATE_RESOLVING_HOST_IN_PAC_FILE, request->load_state()); + base::RunLoop run_loop; + run_loop.RunUntilIdle(); + mock_proxy_resolver_.ClearBlockedClients(); request->WaitForResult(); + EXPECT_EQ(1, host_resolver_.num_cancellations()); } TEST_F(ProxyResolverFactoryMojoTest, DeleteResolver) {
diff --git a/services/network/public/cpp/proxy_config_mojom_traits.cc b/services/network/public/cpp/proxy_config_mojom_traits.cc index f0bb5ea1..15b58d9 100644 --- a/services/network/public/cpp/proxy_config_mojom_traits.cc +++ b/services/network/public/cpp/proxy_config_mojom_traits.cc
@@ -109,12 +109,12 @@ bool StructTraits<network::mojom::ProxyConfigDataView, net::ProxyConfig>::Read( network::mojom::ProxyConfigDataView data, net::ProxyConfig* out_proxy_config) { - GURL pac_url; + std::string pac_url; if (!data.ReadPacUrl(&pac_url) || !data.ReadProxyRules(&out_proxy_config->proxy_rules())) { return false; } - out_proxy_config->set_pac_url(pac_url); + out_proxy_config->set_pac_url(GURL(pac_url)); out_proxy_config->set_auto_detect(data.auto_detect()); out_proxy_config->set_pac_mandatory(data.pac_mandatory());
diff --git a/services/network/public/cpp/proxy_config_mojom_traits.h b/services/network/public/cpp/proxy_config_mojom_traits.h index 7045730..6d60b0d 100644 --- a/services/network/public/cpp/proxy_config_mojom_traits.h +++ b/services/network/public/cpp/proxy_config_mojom_traits.h
@@ -6,6 +6,8 @@ #define SERVICES_NETWORK_PUBLIC_CPP_PROXY_CONFIG_MOJOM_TRAITS_H_ #include "base/component_export.h" +#include "mojo/public/cpp/base/big_buffer_mojom_traits.h" +#include "mojo/public/cpp/base/big_string_mojom_traits.h" #include "net/proxy_resolution/proxy_bypass_rules.h" #include "net/proxy_resolution/proxy_config.h" #include "net/proxy_resolution/proxy_list.h" @@ -93,7 +95,9 @@ StructTraits<network::mojom::ProxyConfigDataView, net::ProxyConfig> { public: static bool auto_detect(const net::ProxyConfig& r) { return r.auto_detect(); } - static const GURL& pac_url(const net::ProxyConfig& r) { return r.pac_url(); } + static const std::string& pac_url(const net::ProxyConfig& r) { + return r.pac_url().possibly_invalid_spec(); + } static bool pac_mandatory(const net::ProxyConfig& r) { return r.pac_mandatory(); }
diff --git a/services/network/public/mojom/proxy_config.mojom b/services/network/public/mojom/proxy_config.mojom index d728e82..a1965d2 100644 --- a/services/network/public/mojom/proxy_config.mojom +++ b/services/network/public/mojom/proxy_config.mojom
@@ -4,8 +4,7 @@ module network.mojom; -import "url/mojom/url.mojom"; - +import "mojo/public/mojom/base/big_string.mojom"; // This corresponds to the string representation of net::ProxyConfigBypassRules. struct ProxyBypassRules { array<string> rules; @@ -39,7 +38,10 @@ // These fields mirror those of net::ProxyConfig. struct ProxyConfig { bool auto_detect; - url.mojom.Url pac_url; + // Note that a |BigString| is used rather than a |url.mojom.Url|, since + // |url.mojom.Url| imposes a smaller limit on URL size than GURL, and + // ProxyConfig::pac_url may contain large data: URLs that exceed this limit. + mojo_base.mojom.BigString pac_url; bool pac_mandatory; ProxyRules proxy_rules; -}; \ No newline at end of file +};
diff --git a/services/network/restricted_cookie_manager.cc b/services/network/restricted_cookie_manager.cc index 7721ac21..e6ddf37 100644 --- a/services/network/restricted_cookie_manager.cc +++ b/services/network/restricted_cookie_manager.cc
@@ -45,6 +45,18 @@ return mojom::CookieChangeCause::EXPLICIT; } +net::CookieStore::SetCookiesCallback StatusToBool( + base::OnceCallback<void(bool)> callback) { + return base::BindOnce( + [](base::OnceCallback<void(bool)> callback, + const net::CanonicalCookie::CookieInclusionStatus status) { + bool success = + (status == net::CanonicalCookie::CookieInclusionStatus::INCLUDE); + std::move(callback).Run(success); + }, + std::move(callback)); +} + } // anonymous namespace class RestrictedCookieManager::Listener : public base::LinkNode<Listener> { @@ -213,7 +225,7 @@ bool modify_http_only = false; cookie_store_->SetCanonicalCookieAsync(std::move(sanitized_cookie), secure_source, modify_http_only, - std::move(callback)); + StatusToBool(std::move(callback))); } void RestrictedCookieManager::AddChangeListener(
diff --git a/services/network/restricted_cookie_manager_unittest.cc b/services/network/restricted_cookie_manager_unittest.cc index 85314b1..c20e8f2 100644 --- a/services/network/restricted_cookie_manager_unittest.cc +++ b/services/network/restricted_cookie_manager_unittest.cc
@@ -107,14 +107,17 @@ bool SetCanonicalCookie(const net::CanonicalCookie& cookie, bool secure_source, bool can_modify_httponly) { - net::ResultSavingCookieCallback<bool> callback; + net::ResultSavingCookieCallback<net::CanonicalCookie::CookieInclusionStatus> + callback; cookie_monster_.SetCanonicalCookieAsync( std::make_unique<net::CanonicalCookie>(cookie), secure_source, can_modify_httponly, - base::BindOnce(&net::ResultSavingCookieCallback<bool>::Run, + base::BindOnce(&net::ResultSavingCookieCallback< + net::CanonicalCookie::CookieInclusionStatus>::Run, base::Unretained(&callback))); callback.WaitUntilDone(); - return callback.result(); + return callback.result() == + net::CanonicalCookie::CookieInclusionStatus::INCLUDE; } // Simplified helper for SetCanonicalCookie.
diff --git a/services/proxy_resolver/host_resolver_mojo.cc b/services/proxy_resolver/host_resolver_mojo.cc index b32c1c2..b31e20b 100644 --- a/services/proxy_resolver/host_resolver_mojo.cc +++ b/services/proxy_resolver/host_resolver_mojo.cc
@@ -85,16 +85,17 @@ // mojom::HostResolverRequestClient override void ReportResult(int32_t error, - const net::AddressList& address_list) override { + const std::vector<net::IPAddress>& result) override { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (error == net::OK) - results_ = AddressListToAddresses(address_list); + results_ = result; if (host_cache_) { base::TimeDelta ttl = error == net::OK ? kCacheEntryTTL : kNegativeCacheEntryTTL; - net::HostCache::Entry entry(error, address_list, - net::HostCache::Entry::SOURCE_UNKNOWN, ttl); + net::HostCache::Entry entry( + error, net::AddressList::CreateFromIPAddressList(result, ""), + net::HostCache::Entry::SOURCE_UNKNOWN, ttl); host_cache_->Set(CacheKeyForRequest(hostname_, operation_), entry, base::TimeTicks::Now(), ttl); } @@ -117,9 +118,7 @@ return entry->error(); } - void OnConnectionError() { - ReportResult(net::ERR_FAILED, net::AddressList()); - } + void OnConnectionError() { ReportResult(net::ERR_FAILED, {} /* result */); } static std::vector<net::IPAddress> AddressListToAddresses( net::AddressList address_list) {
diff --git a/services/proxy_resolver/host_resolver_mojo_unittest.cc b/services/proxy_resolver/host_resolver_mojo_unittest.cc index 6575cd80..95f7355 100644 --- a/services/proxy_resolver/host_resolver_mojo_unittest.cc +++ b/services/proxy_resolver/host_resolver_mojo_unittest.cc
@@ -12,7 +12,6 @@ #include "base/bind.h" #include "base/test/scoped_task_environment.h" #include "mojo/public/cpp/bindings/binding.h" -#include "net/base/address_list.h" #include "net/base/ip_address.h" #include "net/base/net_errors.h" #include "net/base/request_priority.h" @@ -69,9 +68,10 @@ return result; } - static HostResolverAction ReturnResult(const net::AddressList& address_list) { + static HostResolverAction ReturnResult( + std::vector<net::IPAddress> addresses) { HostResolverAction result; - result.addresses = address_list; + result.addresses = std::move(addresses); return result; } @@ -88,7 +88,7 @@ } Action action = COMPLETE; - net::AddressList addresses; + std::vector<net::IPAddress> addresses; net::Error error = net::OK; }; @@ -135,7 +135,7 @@ switch (actions_[results_returned_].action) { case HostResolverAction::COMPLETE: client->ReportResult(actions_[results_returned_].error, - std::move(actions_[results_returned_].addresses)); + actions_[results_returned_].addresses); break; case HostResolverAction::RETAIN: requests_.push_back(std::make_unique<MockMojoHostResolverRequest>( @@ -183,36 +183,30 @@ std::unique_ptr<HostResolverMojo> resolver_; - std::unique_ptr<net::HostResolver::Request> request_; - Waiter waiter_; }; TEST_F(HostResolverMojoTest, Basic) { - net::AddressList address_list; + std::vector<net::IPAddress> addresses; net::IPAddress address(1, 2, 3, 4); - address_list.push_back(net::IPEndPoint(address, 80)); - address_list.push_back( - net::IPEndPoint(ConvertIPv4ToIPv4MappedIPv6(address), 80)); - mock_resolver_->AddAction(HostResolverAction::ReturnResult(address_list)); + addresses.push_back(address); + addresses.push_back(ConvertIPv4ToIPv4MappedIPv6(address)); + mock_resolver_->AddAction(HostResolverAction::ReturnResult(addresses)); std::vector<net::IPAddress> result; EXPECT_THAT(Resolve("example.com", &result), IsOk()); - ASSERT_EQ(2u, result.size()); - EXPECT_EQ(address_list[0].address(), result[0]); - EXPECT_EQ(address_list[1].address(), result[1]); + EXPECT_EQ(addresses, result); ASSERT_EQ(1u, mock_resolver_->requests().size()); EXPECT_EQ("example.com", mock_resolver_->requests()[0]); } TEST_F(HostResolverMojoTest, ResolveCachedResult) { - net::AddressList address_list; + std::vector<net::IPAddress> addresses; net::IPAddress address(1, 2, 3, 4); - address_list.push_back(net::IPEndPoint(address, 80)); - address_list.push_back( - net::IPEndPoint(ConvertIPv4ToIPv4MappedIPv6(address), 80)); - mock_resolver_->AddAction(HostResolverAction::ReturnResult(address_list)); + addresses.push_back(address); + addresses.push_back(ConvertIPv4ToIPv4MappedIPv6(address)); + mock_resolver_->AddAction(HostResolverAction::ReturnResult(addresses)); // Load results into cache. std::vector<net::IPAddress> result; @@ -222,17 +216,14 @@ // Expect results from cache. result.clear(); EXPECT_THAT(Resolve("example.com", &result), IsOk()); - ASSERT_EQ(2u, result.size()); - EXPECT_EQ(address_list[0].address(), result[0]); - EXPECT_EQ(address_list[1].address(), result[1]); + EXPECT_EQ(addresses, result); EXPECT_EQ(1u, mock_resolver_->requests().size()); } TEST_F(HostResolverMojoTest, Multiple) { - net::AddressList address_list; - net::IPAddress address(1, 2, 3, 4); - address_list.push_back(net::IPEndPoint(address, 80)); - mock_resolver_->AddAction(HostResolverAction::ReturnResult(address_list)); + std::vector<net::IPAddress> addresses; + addresses.emplace_back(1, 2, 3, 4); + mock_resolver_->AddAction(HostResolverAction::ReturnResult(addresses)); mock_resolver_->AddAction( HostResolverAction::ReturnError(net::ERR_NAME_NOT_RESOLVED)); @@ -250,8 +241,7 @@ EXPECT_THAT(callback1.GetResult(net::ERR_IO_PENDING), IsOk()); EXPECT_THAT(callback2.GetResult(net::ERR_IO_PENDING), IsError(net::ERR_NAME_NOT_RESOLVED)); - ASSERT_EQ(1u, request1->GetResults().size()); - EXPECT_EQ(address_list[0].address(), request1->GetResults()[0]); + EXPECT_EQ(addresses, request1->GetResults()); ASSERT_EQ(0u, request2->GetResults().size()); EXPECT_THAT(mock_resolver_->requests(),
diff --git a/services/proxy_resolver/mojo_proxy_resolver_v8_tracing_bindings.h b/services/proxy_resolver/mojo_proxy_resolver_v8_tracing_bindings.h index 6c92678..5e24c2e1 100644 --- a/services/proxy_resolver/mojo_proxy_resolver_v8_tracing_bindings.h +++ b/services/proxy_resolver/mojo_proxy_resolver_v8_tracing_bindings.h
@@ -66,22 +66,7 @@ net::ProxyResolveDnsOperation operation, mojom::HostResolverRequestClientPtr client) override { DCHECK(thread_checker_.CalledOnValidThread()); - - net::HostPortPair host_port = net::HostPortPair(hostname, 80); - auto info = std::make_unique<net::HostResolver::RequestInfo>(host_port); - - // Flag myIpAddress requests. - if (operation == net::ProxyResolveDnsOperation::MY_IP_ADDRESS || - operation == net::ProxyResolveDnsOperation::MY_IP_ADDRESS_EX) - info->set_is_my_ip_address(true); - - // The non-ex flavors are limited to IPv4 results. - if (operation == net::ProxyResolveDnsOperation::MY_IP_ADDRESS || - operation == net::ProxyResolveDnsOperation::DNS_RESOLVE) { - info->set_address_family(net::ADDRESS_FAMILY_IPV4); - } - - client_->ResolveDns(std::move(info), std::move(client)); + client_->ResolveDns(hostname, operation, std::move(client)); } base::ThreadChecker thread_checker_;
diff --git a/services/proxy_resolver/mojo_proxy_resolver_v8_tracing_bindings_unittest.cc b/services/proxy_resolver/mojo_proxy_resolver_v8_tracing_bindings_unittest.cc index c4afd48..25cf98401 100644 --- a/services/proxy_resolver/mojo_proxy_resolver_v8_tracing_bindings_unittest.cc +++ b/services/proxy_resolver/mojo_proxy_resolver_v8_tracing_bindings_unittest.cc
@@ -29,7 +29,8 @@ errors_.push_back(std::make_pair(line_number, message)); } - void ResolveDns(std::unique_ptr<net::HostResolver::RequestInfo> request_info, + void ResolveDns(const std::string& hostname, + net::ProxyResolveDnsOperation operation, mojom::HostResolverRequestClientPtr client) {} protected:
diff --git a/services/proxy_resolver/proxy_resolver_factory_impl_unittest.cc b/services/proxy_resolver/proxy_resolver_factory_impl_unittest.cc index 95fed2b2..7f8765f 100644 --- a/services/proxy_resolver/proxy_resolver_factory_impl_unittest.cc +++ b/services/proxy_resolver/proxy_resolver_factory_impl_unittest.cc
@@ -15,6 +15,7 @@ #include "net/base/completion_once_callback.h" #include "net/base/test_completion_callback.h" #include "net/proxy_resolution/mock_proxy_resolver.h" +#include "net/proxy_resolution/proxy_resolve_dns_operation.h" #include "net/proxy_resolution/proxy_resolver_v8_tracing.h" #include "net/test/event_waiter.h" #include "net/test/gtest_util.h" @@ -145,7 +146,8 @@ void OnError(int32_t line_number, const std::string& message) override {} - void ResolveDns(std::unique_ptr<net::HostResolver::RequestInfo> request_info, + void ResolveDns(const std::string& hostname, + net::ProxyResolveDnsOperation operation, mojom::HostResolverRequestClientPtr client) override {} void WaitForNoServiceRefs() {
diff --git a/services/proxy_resolver/proxy_resolver_impl_unittest.cc b/services/proxy_resolver/proxy_resolver_impl_unittest.cc index 2708c1a..a3dc37c 100644 --- a/services/proxy_resolver/proxy_resolver_impl_unittest.cc +++ b/services/proxy_resolver/proxy_resolver_impl_unittest.cc
@@ -18,6 +18,7 @@ #include "net/base/proxy_server.h" #include "net/proxy_resolution/mock_proxy_resolver.h" #include "net/proxy_resolution/proxy_info.h" +#include "net/proxy_resolution/proxy_resolve_dns_operation.h" #include "net/proxy_resolution/proxy_resolver_v8_tracing.h" #include "net/test/event_waiter.h" #include "net/test/gtest_util.h" @@ -52,7 +53,8 @@ void ReportResult(int32_t error, const net::ProxyInfo& results) override; void Alert(const std::string& message) override; void OnError(int32_t line_number, const std::string& message) override; - void ResolveDns(std::unique_ptr<net::HostResolver::RequestInfo> request_info, + void ResolveDns(const std::string& hostname, + net::ProxyResolveDnsOperation operation, mojom::HostResolverRequestClientPtr client) override; // Mojo error handler. @@ -96,9 +98,10 @@ void TestRequestClient::OnError(int32_t line_number, const std::string& message) {} -void TestRequestClient::ResolveDns( - std::unique_ptr<net::HostResolver::RequestInfo> request_info, - mojom::HostResolverRequestClientPtr client) {} +void TestRequestClient::ResolveDns(const std::string& hostname, + net::ProxyResolveDnsOperation operation, + mojom::HostResolverRequestClientPtr client) { +} void TestRequestClient::OnConnectionError() { event_waiter_.NotifyEvent(CONNECTION_ERROR);
diff --git a/services/proxy_resolver/public/cpp/mojo_host_struct_traits.cc b/services/proxy_resolver/public/cpp/mojo_host_struct_traits.cc index 22dbb687..123a70a 100644 --- a/services/proxy_resolver/public/cpp/mojo_host_struct_traits.cc +++ b/services/proxy_resolver/public/cpp/mojo_host_struct_traits.cc
@@ -12,24 +12,47 @@ namespace mojo { // static -bool StructTraits<proxy_resolver::mojom::HostResolverRequestInfoDataView, - std::unique_ptr<net::HostResolver::RequestInfo>>:: - Read(proxy_resolver::mojom::HostResolverRequestInfoDataView data, - std::unique_ptr<net::HostResolver::RequestInfo>* out) { - base::StringPiece host; - if (!data.ReadHost(&host)) - return false; +proxy_resolver::mojom::HostResolveOperation +EnumTraits<proxy_resolver::mojom::HostResolveOperation, + net::ProxyResolveDnsOperation>::ToMojom(net::ProxyResolveDnsOperation + input) { + switch (input) { + case net::ProxyResolveDnsOperation::DNS_RESOLVE: + return proxy_resolver::mojom::HostResolveOperation::DNS_RESOLVE; + case net::ProxyResolveDnsOperation::DNS_RESOLVE_EX: + return proxy_resolver::mojom::HostResolveOperation::DNS_RESOLVE_EX; + case net::ProxyResolveDnsOperation::MY_IP_ADDRESS: + return proxy_resolver::mojom::HostResolveOperation::MY_IP_ADDRESS; + case net::ProxyResolveDnsOperation::MY_IP_ADDRESS_EX: + return proxy_resolver::mojom::HostResolveOperation::MY_IP_ADDRESS_EX; + } - net::AddressFamily address_family; - if (!data.ReadAddressFamily(&address_family)) - return false; + NOTREACHED(); + return proxy_resolver::mojom::HostResolveOperation::kMinValue; +} - *out = std::make_unique<net::HostResolver::RequestInfo>( - net::HostPortPair(host.as_string(), data.port())); - net::HostResolver::RequestInfo& request = **out; - request.set_address_family(address_family); - request.set_is_my_ip_address(data.is_my_ip_address()); - return true; +// static +bool EnumTraits<proxy_resolver::mojom::HostResolveOperation, + net::ProxyResolveDnsOperation>:: + FromMojom(proxy_resolver::mojom::HostResolveOperation input, + net::ProxyResolveDnsOperation* output) { + switch (input) { + case proxy_resolver::mojom::HostResolveOperation::DNS_RESOLVE: + *output = net::ProxyResolveDnsOperation::DNS_RESOLVE; + return true; + case proxy_resolver::mojom::HostResolveOperation::DNS_RESOLVE_EX: + *output = net::ProxyResolveDnsOperation::DNS_RESOLVE_EX; + return true; + case proxy_resolver::mojom::HostResolveOperation::MY_IP_ADDRESS: + *output = net::ProxyResolveDnsOperation::MY_IP_ADDRESS; + return true; + case proxy_resolver::mojom::HostResolveOperation::MY_IP_ADDRESS_EX: + *output = net::ProxyResolveDnsOperation::MY_IP_ADDRESS_EX; + return true; + } + + NOTREACHED(); + return false; } } // namespace mojo
diff --git a/services/proxy_resolver/public/cpp/mojo_host_struct_traits.h b/services/proxy_resolver/public/cpp/mojo_host_struct_traits.h index 8ce1032..01c80a8 100644 --- a/services/proxy_resolver/public/cpp/mojo_host_struct_traits.h +++ b/services/proxy_resolver/public/cpp/mojo_host_struct_traits.h
@@ -7,38 +7,19 @@ #include "base/strings/string_piece.h" #include "mojo/public/cpp/bindings/enum_traits.h" -#include "mojo/public/cpp/bindings/struct_traits.h" -#include "net/dns/host_resolver.h" -#include "services/network/public/mojom/address_family.mojom.h" +#include "net/proxy_resolution/proxy_resolve_dns_operation.h" #include "services/proxy_resolver/public/mojom/proxy_resolver.mojom.h" namespace mojo { template <> -struct StructTraits<proxy_resolver::mojom::HostResolverRequestInfoDataView, - std::unique_ptr<net::HostResolver::RequestInfo>> { - static base::StringPiece host( - const std::unique_ptr<net::HostResolver::RequestInfo>& obj) { - return obj->hostname(); - } +struct EnumTraits<proxy_resolver::mojom::HostResolveOperation, + net::ProxyResolveDnsOperation> { + static proxy_resolver::mojom::HostResolveOperation ToMojom( + net::ProxyResolveDnsOperation input); - static uint16_t port( - const std::unique_ptr<net::HostResolver::RequestInfo>& obj) { - return obj->port(); - } - - static net::AddressFamily address_family( - const std::unique_ptr<net::HostResolver::RequestInfo>& obj) { - return obj->address_family(); - } - - static bool is_my_ip_address( - const std::unique_ptr<net::HostResolver::RequestInfo>& obj) { - return obj->is_my_ip_address(); - } - - static bool Read(proxy_resolver::mojom::HostResolverRequestInfoDataView obj, - std::unique_ptr<net::HostResolver::RequestInfo>* output); + static bool FromMojom(proxy_resolver::mojom::HostResolveOperation input, + net::ProxyResolveDnsOperation* output); }; } // namespace mojo
diff --git a/services/proxy_resolver/public/cpp/proxy_resolver.typemap b/services/proxy_resolver/public/cpp/proxy_resolver.typemap index db0c85d..7f6d138 100644 --- a/services/proxy_resolver/public/cpp/proxy_resolver.typemap +++ b/services/proxy_resolver/public/cpp/proxy_resolver.typemap
@@ -5,8 +5,8 @@ mojom = "//services/proxy_resolver/public/mojom/proxy_resolver.mojom" public_headers = [ "//net/base/proxy_server.h", - "//net/dns/host_resolver.h", "//net/proxy_resolution/proxy_info.h", + "//net/proxy_resolution/proxy_resolve_dns_operation.h", ] traits_headers = [ "//services/proxy_resolver/public/cpp/mojo_host_struct_traits.h", @@ -17,7 +17,7 @@ "//services/proxy_resolver/public/cpp/proxy_resolver_mojom_traits.cc", ] type_mappings = [ - "proxy_resolver.mojom.HostResolverRequestInfo=std::unique_ptr<net::HostResolver::RequestInfo>[move_only]", + "proxy_resolver.mojom.HostResolveOperation=net::ProxyResolveDnsOperation", "proxy_resolver.mojom.ProxyInfo=net::ProxyInfo", "proxy_resolver.mojom.ProxyServer=net::ProxyServer", "proxy_resolver.mojom.ProxyServer::Scheme=net::ProxyScheme",
diff --git a/services/proxy_resolver/public/mojom/proxy_resolver.mojom b/services/proxy_resolver/public/mojom/proxy_resolver.mojom index a08a6e8..a8f5fa9 100644 --- a/services/proxy_resolver/public/mojom/proxy_resolver.mojom +++ b/services/proxy_resolver/public/mojom/proxy_resolver.mojom
@@ -7,26 +7,24 @@ // TODO(amistry): Resolve the conflict between these two sets of definitions. module proxy_resolver.mojom; -import "services/network/public/mojom/address_family.mojom"; -import "services/network/public/mojom/address_list.mojom"; +import "services/network/public/mojom/ip_address.mojom"; import "url/mojom/url.mojom"; const string kProxyResolverServiceName = "proxy_resolver"; -// Mirror of net::HostResolver::RequestInfo. -// TODO(mmenke): Remove this struct, in favor of passing values directly. -struct HostResolverRequestInfo { - string host; - uint16 port; - network.mojom.AddressFamily address_family; - bool is_my_ip_address; +// Mirror of net::ProxyResolveDnsOperation. +enum HostResolveOperation { + DNS_RESOLVE, + DNS_RESOLVE_EX, + MY_IP_ADDRESS, + MY_IP_ADDRESS_EX, }; // Interface for waiting for the result of a HostResolver query. -// TODO(mmenke): Remove this struct, in favor of callbacks. +// TODO(mmenke): Remove this interface, in favor of callbacks. interface HostResolverRequestClient { // |error| is a value in net::Error. - ReportResult(int32 error, network.mojom.AddressList result); + ReportResult(int32 error, array<network.mojom.IPAddress> result); }; // Mirror of net::ProxyServer::Scheme. @@ -65,7 +63,8 @@ Alert(string error); OnError(int32 line_number, string error); - ResolveDns(HostResolverRequestInfo request_info, + ResolveDns(string host, + HostResolveOperation operation, HostResolverRequestClient client); }; @@ -86,6 +85,7 @@ Alert(string error); OnError(int32 line_number, string error); - ResolveDns(HostResolverRequestInfo request_info, + ResolveDns(string host, + HostResolveOperation operation, HostResolverRequestClient client); };
diff --git a/services/service_manager/sandbox/mac/gpu_v2.sb b/services/service_manager/sandbox/mac/gpu_v2.sb index 69baee1..6a051984 100644 --- a/services/service_manager/sandbox/mac/gpu_v2.sb +++ b/services/service_manager/sandbox/mac/gpu_v2.sb
@@ -42,9 +42,11 @@ ; Needed for VideoToolbox usage - https://crbug.com/767037 (if (>= os-version 1013) - (allow mach-lookup (global-name "com.apple.coremedia.videodecoder")) - (allow mach-lookup (global-name "com.apple.coremedia.videoencoder")) -) + (allow mach-lookup + (xpc-service-name "com.apple.coremedia.videodecoder") + (xpc-service-name "com.apple.coremedia.videoencoder") + (xpc-service-name-regex #"\.apple-extension-service$") +)) (allow sysctl-read (sysctl-name "hw.logicalcpu_max")
diff --git a/services/tracing/perfetto/json_trace_exporter.cc b/services/tracing/perfetto/json_trace_exporter.cc index 92f2064..ab92eb26 100644 --- a/services/tracing/perfetto/json_trace_exporter.cc +++ b/services/tracing/perfetto/json_trace_exporter.cc
@@ -375,7 +375,7 @@ std::string out; out.reserve(kReserveCapacity); - if (!has_output_json_preamble_) { + if (label_filter_.empty() && !has_output_json_preamble_) { out = "{\"traceEvents\":["; has_output_json_preamble_ = true; } @@ -397,25 +397,27 @@ auto& bundle = packet.chrome_events(); - std::unordered_map<int, std::string> string_table; - for (auto& string_table_entry : bundle.string_table()) { - string_table[string_table_entry.index()] = string_table_entry.value(); - } - - for (auto& event : bundle.trace_events()) { - if (out.size() > kTraceEventBufferSizeInBytes) { - json_callback_.Run(out, nullptr, true); - out.clear(); + if (label_filter_.empty() || label_filter_ == "traceEvents") { + std::unordered_map<int, std::string> string_table; + for (auto& string_table_entry : bundle.string_table()) { + string_table[string_table_entry.index()] = string_table_entry.value(); } - if (has_output_first_event_) { - out += ",\n"; - } else { - has_output_first_event_ = true; - } + for (auto& event : bundle.trace_events()) { + if (out.size() > kTraceEventBufferSizeInBytes) { + json_callback_.Run(out, nullptr, true); + out.clear(); + } - OutputJSONFromTraceEventProto(event, string_table, - argument_filter_predicate_, &out); + if (has_output_first_event_) { + out += ",\n"; + } else { + has_output_first_event_ = true; + } + + OutputJSONFromTraceEventProto(event, string_table, + argument_filter_predicate_, &out); + } } for (auto& metadata : bundle.metadata()) { @@ -465,10 +467,13 @@ } if (!has_more) { - out += "]"; + if (label_filter_.empty()) { + out += "]"; + } - if (!legacy_system_ftrace_output_.empty() || - !legacy_system_trace_events_.empty()) { + if ((label_filter_.empty() || label_filter_ == "systemTraceEvents") && + (!legacy_system_ftrace_output_.empty() || + !legacy_system_trace_events_.empty())) { // Should only have system events (e.g. ETW) or system ftrace output. DCHECK(legacy_system_ftrace_output_.empty() || legacy_system_trace_events_.empty()); @@ -483,14 +488,16 @@ } } - if (!metadata_->empty()) { - out += ",\"metadata\":"; - std::string json_value; - base::JSONWriter::Write(*metadata_, &json_value); - out += json_value; - } + if (label_filter_.empty()) { + if (!metadata_->empty()) { + out += ",\"metadata\":"; + std::string json_value; + base::JSONWriter::Write(*metadata_, &json_value); + out += json_value; + } - out += "}"; + out += "}"; + } } json_callback_.Run(out, metadata_.get(), has_more);
diff --git a/services/tracing/perfetto/json_trace_exporter.h b/services/tracing/perfetto/json_trace_exporter.h index bf481d7f..8db05e2 100644 --- a/services/tracing/perfetto/json_trace_exporter.h +++ b/services/tracing/perfetto/json_trace_exporter.h
@@ -59,6 +59,10 @@ argument_filter_predicate_ = predicate; } + void set_label_filter(const std::string& label_filter) { + label_filter_ = label_filter; + } + private: OnTraceEventJSONCallback json_callback_; bool has_output_json_preamble_ = false; @@ -66,6 +70,7 @@ std::unique_ptr<base::DictionaryValue> metadata_; std::string legacy_system_ftrace_output_; std::string legacy_system_trace_events_; + std::string label_filter_; ArgumentFilterPredicate argument_filter_predicate_;
diff --git a/services/tracing/perfetto/perfetto_tracing_coordinator.cc b/services/tracing/perfetto/perfetto_tracing_coordinator.cc index cacdcd1..a02b533b 100644 --- a/services/tracing/perfetto/perfetto_tracing_coordinator.cc +++ b/services/tracing/perfetto/perfetto_tracing_coordinator.cc
@@ -50,7 +50,7 @@ perfetto::TraceConfig trace_config; size_t size_limit = chrome_trace_config_obj.GetTraceBufferSizeInKb(); if (size_limit == 0) { - size_limit = 400 * 1024; + size_limit = 100 * 1024; } trace_config.add_buffers()->set_size_kb(size_limit); @@ -101,9 +101,11 @@ } void StopAndFlush(mojo::ScopedDataPipeProducerHandle stream, + const std::string& agent_label, StopAndFlushCallback callback) { stream_ = std::move(stream); stop_and_flush_callback_ = std::move(callback); + json_trace_exporter_->set_label_filter(agent_label); consumer_endpoint_->DisableTracing(); } @@ -281,6 +283,7 @@ void PerfettoTracingCoordinator::StopAndFlushInternal( mojo::ScopedDataPipeProducerHandle stream, + const std::string& agent_label, StopAndFlushCallback callback) { if (start_tracing_callback_) { // We received a |StopAndFlush| command before receiving |StartTracing| acks @@ -289,13 +292,14 @@ FROM_HERE, base::BindOnce(&PerfettoTracingCoordinator::StopAndFlushInternal, weak_factory_.GetWeakPtr(), std::move(stream), - std::move(callback)), + agent_label, std::move(callback)), base::TimeDelta::FromMilliseconds( mojom::kStopTracingRetryTimeMilliseconds)); return; } - tracing_session_->StopAndFlush(std::move(stream), std::move(callback)); + tracing_session_->StopAndFlush(std::move(stream), agent_label, + std::move(callback)); } void PerfettoTracingCoordinator::StopAndFlushAgent( @@ -306,7 +310,7 @@ DCHECK(tracing_session_); ClearConnectedPIDs(); - StopAndFlushInternal(std::move(stream), std::move(callback)); + StopAndFlushInternal(std::move(stream), agent_label, std::move(callback)); } void PerfettoTracingCoordinator::IsTracing(IsTracingCallback callback) {
diff --git a/services/tracing/perfetto/perfetto_tracing_coordinator.h b/services/tracing/perfetto/perfetto_tracing_coordinator.h index 554346b..1a8318db 100644 --- a/services/tracing/perfetto/perfetto_tracing_coordinator.h +++ b/services/tracing/perfetto/perfetto_tracing_coordinator.h
@@ -52,6 +52,7 @@ void OnClientConnectionError() override; void OnNewAgentConnected(AgentRegistry::AgentEntry* agent_entry); void StopAndFlushInternal(mojo::ScopedDataPipeProducerHandle stream, + const std::string& agent_label, StopAndFlushCallback callback); mojo::Binding<mojom::Coordinator> binding_;
diff --git a/services/tracing/public/cpp/tracing_features.cc b/services/tracing/public/cpp/tracing_features.cc index 66704a3b..08887d9 100644 --- a/services/tracing/public/cpp/tracing_features.cc +++ b/services/tracing/public/cpp/tracing_features.cc
@@ -20,8 +20,14 @@ base::FEATURE_DISABLED_BY_DEFAULT}; // Runs the tracing service as an in-process browser service. -const base::Feature kTracingServiceInProcess{"TracingServiceInProcess", - base::FEATURE_ENABLED_BY_DEFAULT}; +const base::Feature kTracingServiceInProcess { + "TracingServiceInProcess", +#if defined(OS_ANDROID) + base::FEATURE_ENABLED_BY_DEFAULT +#else + base::FEATURE_DISABLED_BY_DEFAULT +#endif +}; } // namespace features
diff --git a/services/ws/proxy_window.cc b/services/ws/proxy_window.cc index 7aca60894..71cba95 100644 --- a/services/ws/proxy_window.cc +++ b/services/ws/proxy_window.cc
@@ -173,11 +173,20 @@ } protected: + // Returns true if the event is a pinch event generated from the touchpad. + bool IsPinchEventOnTouchpad(const ui::Event& event) { + return event.IsPinchEvent() && + event.AsGestureEvent()->details().device_type() == + ui::GestureDeviceType::DEVICE_TOUCHPAD; + } + // Returns true if the event should be ignored (not forwarded to the client). bool ShouldIgnoreEvent(const ui::Event& event) { // It's assumed clients do their own gesture recognizition, which means - // GestureEvents should not be forwarded to clients. - if (event.IsGestureEvent()) + // GestureEvents should not be forwarded to clients. Pinch events are + // exceptional since they aren't created through gesture recognition but + // from the touchpad directly. See https://crbug.com/933985. + if (event.IsGestureEvent() && !IsPinchEventOnTouchpad(event)) return true; if (static_cast<aura::Window*>(event.target()) != window()) {
diff --git a/services/ws/proxy_window_unittest.cc b/services/ws/proxy_window_unittest.cc index c5992cf4..ba13f9523b 100644 --- a/services/ws/proxy_window_unittest.cc +++ b/services/ws/proxy_window_unittest.cc
@@ -16,6 +16,7 @@ #include "ui/aura/mus/client_surface_embedder.h" #include "ui/events/event.h" #include "ui/events/event_constants.h" +#include "ui/events/test/event_generator.h" #include "ui/wm/core/easy_resize_window_targeter.h" namespace ws { @@ -88,4 +89,52 @@ EXPECT_EQ(top_level, setup.root()->targeter()->FindTargetForEvent( setup.root(), &mouse_event_2)); } + +TEST(ProxyWindow, ShouldSendPinchEventFromTouchpads) { + WindowServiceTestSetup setup; + + aura::Window* top_level = + setup.window_tree_test_helper()->NewTopLevelWindow(); + ASSERT_TRUE(top_level); + const gfx::Rect top_level_bounds(100, 200, 200, 200); + top_level->SetBounds(top_level_bounds); + top_level->Show(); + + setup.changes()->clear(); + + ui::test::EventGenerator event_generator(top_level->GetRootWindow()); + + // The pinch zoom from touchscreen -- that shouldn't be sent; the gesture + // recognition in the client will create them. + const gfx::Point points[] = {gfx::Point(110, 210), gfx::Point(190, 290)}; + const gfx::Vector2d deltas[] = {gfx::Vector2d(20, 20), + gfx::Vector2d(-20, -20)}; + const int delay_fingers[] = {0, 10}; + event_generator.GestureMultiFingerScrollWithDelays( + 2, points, deltas, delay_fingers, delay_fingers, 0, 10); + bool has_input_event = false; + for (auto& c : *setup.changes()) { + if (c.type != CHANGE_TYPE_INPUT_EVENT) + continue; + has_input_event = true; + EXPECT_LE(ui::ET_TOUCH_RELEASED, c.event_action); + EXPECT_GE(ui::ET_TOUCH_CANCELLED, c.event_action); + } + EXPECT_TRUE(has_input_event); + + setup.changes()->clear(); + + // The pinch event from touchpad, this should be sent since the gesture + // recognition isn't involved. + ui::GestureEventDetails details(ui::ET_GESTURE_PINCH_BEGIN); + details.set_device_type(ui::GestureDeviceType::DEVICE_TOUCHPAD); + ui::GestureEvent pinch_event(110, 220, 0 /* flags */, base::TimeTicks::Now(), + details); + ignore_result( + setup.aura_test_helper()->event_sink()->OnEventFromSource(&pinch_event)); + auto iter = FirstChangeOfType(*setup.changes(), CHANGE_TYPE_INPUT_EVENT); + ASSERT_NE(iter, setup.changes()->end()); + EXPECT_EQ(ui::ET_GESTURE_PINCH_BEGIN, iter->event_action); +} + } // namespace ws
diff --git a/services/ws/public/mojom/window_tree.mojom b/services/ws/public/mojom/window_tree.mojom index 41aa2e2..635d2a5 100644 --- a/services/ws/public/mojom/window_tree.mojom +++ b/services/ws/public/mojom/window_tree.mojom
@@ -112,6 +112,7 @@ // change the child-sequence number portion of the id. Supplying a different // embed token results in failure, and changes to the parent sequence number // are ignored. + // |bounds| are in DIPs. SetWindowBounds( uint32 change_id, uint64 window_id,
diff --git a/services/ws/window_tree.cc b/services/ws/window_tree.cc index 5213213..1c3e1558 100644 --- a/services/ws/window_tree.cc +++ b/services/ws/window_tree.cc
@@ -166,8 +166,8 @@ const ui::Event& event) { // As gesture recognition runs in the client, GestureEvents should not be // forwarded. ProxyWindow's event processing should ensure no GestureEvents - // are sent. - DCHECK(!event.IsGestureEvent()); + // are sent. Some pinch events are allowed. + DCHECK(!event.IsGestureEvent() || event.IsPinchEvent()); const uint32_t event_id = GenerateEventAckId(); auto* in_flight_event_queue = @@ -2163,9 +2163,19 @@ // Clear |pending_drag_source_window_id_| to cancel posted drag loop task. pending_drag_source_window_id_ = kInvalidTransportId; + aura::Window* window = GetWindowByTransportId(window_id); + if (!window) { + DVLOG(1) << "CancelDragDrop failed (no window)"; + return; + } + + if (!IsClientCreatedWindow(window)) { + DVLOG(1) << "CancelDragDrop failed (access denied)"; + return; + } + // Cancel the current drag loop if it is running. - window_service_->delegate()->CancelDragLoop( - GetWindowByTransportId(window_id)); + window_service_->delegate()->CancelDragLoop(window); } void WindowTree::ObserveTopmostWindow(mojom::MoveLoopSource source,
diff --git a/skia/ext/test_fonts_mac.mm b/skia/ext/test_fonts_mac.mm index 3f89ce5..da6b2935 100644 --- a/skia/ext/test_fonts_mac.mm +++ b/skia/ext/test_fonts_mac.mm
@@ -7,30 +7,25 @@ #include <AppKit/AppKit.h> #include <Foundation/Foundation.h> +#include "base/files/file_path.h" #include "base/logging.h" -#include "base/mac/bundle_locations.h" +#include "base/mac/foundation_util.h" +#include "base/stl_util.h" +#include "base/strings/sys_string_conversions.h" namespace skia { void ConfigureTestFont() { // Load font files in the resource folder. - static const char* const kFontFileNames[] = {"Ahem.TTF", + static const char* const kFontFileNames[] = {"Ahem.ttf", "ChromiumAATTest.ttf"}; - // mainBundle is Content Shell Helper.app. Go two levels up to find - // Content Shell.app. Due to DumpRenderTree injecting the font files into - // its direct dependents, it's not easily possible to put the ttf files into - // the helper's resource directory instead of the outer bundle's resource - // directory. - NSString* bundle = [base::mac::FrameworkBundle() bundlePath]; - bundle = [bundle stringByAppendingPathComponent:@"../.."]; - NSURL* resources_directory = [[NSBundle bundleWithPath:bundle] resourceURL]; - NSMutableArray* font_urls = [NSMutableArray array]; for (unsigned i = 0; i < base::size(kFontFileNames); ++i) { - NSURL* font_url = [resources_directory - URLByAppendingPathComponent: - [NSString stringWithUTF8String:kFontFileNames[i]]]; + base::ScopedCFTypeRef<CFStringRef> file_name( + base::SysUTF8ToCFStringRef(kFontFileNames[i])); + NSURL* font_url = base::mac::FilePathToNSURL( + base::mac::PathForFrameworkBundleResource(file_name)); [font_urls addObject:[font_url absoluteURL]]; }
diff --git a/storage/browser/blob/view_blob_internals_job.cc b/storage/browser/blob/view_blob_internals_job.cc index 34e9f8a4..e405ff85 100644 --- a/storage/browser/blob/view_blob_internals_job.cc +++ b/storage/browser/blob/view_blob_internals_job.cc
@@ -225,7 +225,7 @@ const BlobEntry& blob_data, const std::string& content_type, const std::string& content_disposition, - int refcount, + size_t refcount, std::string* out) { StartHTMLList(out);
diff --git a/storage/browser/blob/view_blob_internals_job.h b/storage/browser/blob/view_blob_internals_job.h index 8a01c77..9080d25 100644 --- a/storage/browser/blob/view_blob_internals_job.h +++ b/storage/browser/blob/view_blob_internals_job.h
@@ -49,7 +49,7 @@ static void GenerateHTMLForBlobData(const BlobEntry& blob_data, const std::string& content_type, const std::string& content_disposition, - int refcount, + size_t refcount, std::string* out); BlobStorageContext* blob_storage_context_;
diff --git a/storage/browser/fileapi/file_system_file_stream_reader.cc b/storage/browser/fileapi/file_system_file_stream_reader.cc index df504693..19a45d9 100644 --- a/storage/browser/fileapi/file_system_file_stream_reader.cc +++ b/storage/browser/fileapi/file_system_file_stream_reader.cc
@@ -120,7 +120,7 @@ return; } - int rv = file_reader_->GetLength(base::BindOnce( + int64_t rv = file_reader_->GetLength(base::BindOnce( &FileSystemFileStreamReader::OnGetLength, weak_factory_.GetWeakPtr())); if (rv != net::ERR_IO_PENDING) std::move(get_length_callback_).Run(rv);
diff --git a/storage/browser/fileapi/file_system_operation_impl_unittest.cc b/storage/browser/fileapi/file_system_operation_impl_unittest.cc index ec677ee..26fb335 100644 --- a/storage/browser/fileapi/file_system_operation_impl_unittest.cc +++ b/storage/browser/fileapi/file_system_operation_impl_unittest.cc
@@ -1208,7 +1208,7 @@ TEST_F(FileSystemOperationImplTest, TestMoveSuccessSrcDirRecursiveWithQuota) { FileSystemURL src(CreateDirectory("src")); - int src_path_cost = GetUsage(); + int64_t src_path_cost = GetUsage(); FileSystemURL dest(CreateDirectory("dest")); FileSystemURL child_file1(CreateFile("src/file1")); @@ -1217,7 +1217,7 @@ FileSystemURL grandchild_file1(CreateFile("src/dir/file1")); FileSystemURL grandchild_file2(CreateFile("src/dir/file2")); - int total_path_cost = GetUsage(); + int64_t total_path_cost = GetUsage(); EXPECT_EQ(0, GetDataSizeOnDisk()); EXPECT_EQ(base::File::FILE_OK, Truncate(child_file1, 5000));
diff --git a/storage/browser/fileapi/local_file_stream_reader.cc b/storage/browser/fileapi/local_file_stream_reader.cc index 4073f0b..5a84940 100644 --- a/storage/browser/fileapi/local_file_stream_reader.cc +++ b/storage/browser/fileapi/local_file_stream_reader.cc
@@ -72,9 +72,12 @@ if (stream_impl_) return stream_impl_->Read(buf, buf_len, std::move(callback)); - return Open(base::BindOnce(&LocalFileStreamReader::DidOpenForRead, - weak_factory_.GetWeakPtr(), base::RetainedRef(buf), - buf_len, std::move(callback))); + + Open(base::BindOnce(&LocalFileStreamReader::DidOpenForRead, + weak_factory_.GetWeakPtr(), base::RetainedRef(buf), + buf_len, std::move(callback))); + + return net::ERR_IO_PENDING; } int64_t LocalFileStreamReader::GetLength( @@ -101,16 +104,17 @@ has_pending_open_(false), weak_factory_(this) {} -int LocalFileStreamReader::Open(net::CompletionOnceCallback callback) { +void LocalFileStreamReader::Open(net::CompletionOnceCallback callback) { DCHECK(!has_pending_open_); DCHECK(!stream_impl_.get()); has_pending_open_ = true; // Call GetLength first to make it perform last-modified-time verification, - // and then call DidVerifyForOpen for do the rest. - return GetLength(base::BindOnce(&LocalFileStreamReader::DidVerifyForOpen, - weak_factory_.GetWeakPtr(), - std::move(callback))); + // and then call DidVerifyForOpen to do the rest. + int64_t verify_result = GetLength( + base::BindOnce(&LocalFileStreamReader::DidVerifyForOpen, + weak_factory_.GetWeakPtr(), std::move(callback))); + DCHECK_EQ(verify_result, net::ERR_IO_PENDING); } void LocalFileStreamReader::DidVerifyForOpen(
diff --git a/storage/browser/fileapi/local_file_stream_reader.h b/storage/browser/fileapi/local_file_stream_reader.h index 7b0b269..bcd5e91 100644 --- a/storage/browser/fileapi/local_file_stream_reader.h +++ b/storage/browser/fileapi/local_file_stream_reader.h
@@ -53,7 +53,7 @@ const base::FilePath& file_path, int64_t initial_offset, const base::Time& expected_modification_time); - int Open(net::CompletionOnceCallback callback); + void Open(net::CompletionOnceCallback callback); // Callbacks that are chained from Open for Read. void DidVerifyForOpen(net::CompletionOnceCallback callback,
diff --git a/testing/buildbot/chromium.chromiumos.json b/testing/buildbot/chromium.chromiumos.json index cbc74060..1b83212 100644 --- a/testing/buildbot/chromium.chromiumos.json +++ b/testing/buildbot/chromium.chromiumos.json
@@ -411,7 +411,6 @@ "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/chromeos.base_unittests.filter" ], - "experiment_percentage": 100, "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -428,7 +427,6 @@ } }, { - "experiment_percentage": 100, "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -445,7 +443,6 @@ } }, { - "experiment_percentage": 100, "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -606,11 +603,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -873,11 +869,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -1303,11 +1298,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -1570,11 +1564,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true },
diff --git a/testing/buildbot/chromium.clang.json b/testing/buildbot/chromium.clang.json index 386f1e3..42aa207 100644 --- a/testing/buildbot/chromium.clang.json +++ b/testing/buildbot/chromium.clang.json
@@ -96,11 +96,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -369,11 +368,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -786,11 +784,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -1310,11 +1307,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -1978,11 +1974,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -2502,11 +2497,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -3158,11 +3152,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -3682,11 +3675,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -9539,11 +9531,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -9805,11 +9796,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -10213,12 +10203,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter", + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter", "--test-launcher-print-test-stdio=always" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -10563,12 +10552,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter", + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter", "--test-launcher-print-test-stdio=always" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -11046,11 +11034,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -11312,11 +11299,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -11660,11 +11646,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -11926,11 +11911,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -12271,11 +12255,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -12515,11 +12498,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -12871,11 +12853,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -13137,11 +13118,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -13494,11 +13474,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -13760,11 +13739,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -14112,11 +14090,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -14361,11 +14338,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -14814,12 +14790,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter", + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter", "--test-launcher-print-test-stdio=always" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -15106,12 +15081,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter", + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter", "--test-launcher-print-test-stdio=always" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -15511,11 +15485,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -15819,11 +15792,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -16194,11 +16166,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -16502,11 +16473,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -16877,11 +16847,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -17185,11 +17154,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -17560,11 +17528,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -17868,11 +17835,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -18243,11 +18209,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -18551,11 +18516,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -18926,11 +18890,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -19234,11 +19197,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -19609,11 +19571,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -19917,11 +19878,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -20292,11 +20252,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -20600,11 +20559,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -20975,11 +20933,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -21283,11 +21240,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -21658,11 +21614,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -21966,11 +21921,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -22341,11 +22295,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -22607,11 +22560,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -23019,11 +22971,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -23532,11 +23483,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index fe02df0..7a2c8e1 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -421,11 +421,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -670,11 +669,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -2621,11 +2619,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": false }, @@ -2919,11 +2916,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": false }, @@ -3974,6 +3970,24 @@ "swarming": { "can_use_on_swarming_builders": true }, + "test": "blink_common_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "blink_heap_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "blink_platform_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, "test": "cast_runner_browsertests" }, { @@ -4143,6 +4157,39 @@ } ] }, + "test": "blink_common_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "kvm": "1" + } + ] + }, + "test": "blink_heap_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "kvm": "1" + } + ] + }, + "test": "blink_platform_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "kvm": "1" + } + ] + }, "test": "cast_runner_browsertests" }, { @@ -4412,6 +4459,39 @@ } ] }, + "test": "blink_common_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "kvm": "1" + } + ] + }, + "test": "blink_heap_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "kvm": "1" + } + ] + }, + "test": "blink_platform_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "kvm": "1" + } + ] + }, "test": "cast_runner_browsertests" }, { @@ -6073,11 +6153,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -6339,11 +6418,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -6865,12 +6943,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], "isolate_coverage_data": true, - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -7156,12 +7233,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], "isolate_coverage_data": true, - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -10281,11 +10357,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -10547,11 +10622,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -11307,11 +11381,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -11871,11 +11944,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [
diff --git a/testing/buildbot/chromium.linux.json b/testing/buildbot/chromium.linux.json index 2f54501..3254dc0b 100644 --- a/testing/buildbot/chromium.linux.json +++ b/testing/buildbot/chromium.linux.json
@@ -1145,11 +1145,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -1411,11 +1410,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -1950,11 +1948,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -2216,11 +2213,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -2691,11 +2687,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -2957,11 +2952,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -3494,11 +3488,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -3945,11 +3938,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [
diff --git a/testing/buildbot/chromium.mac.json b/testing/buildbot/chromium.mac.json index 9f5fafe..d788972 100644 --- a/testing/buildbot/chromium.mac.json +++ b/testing/buildbot/chromium.mac.json
@@ -165,11 +165,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -558,11 +557,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -1328,11 +1326,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -1721,11 +1718,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -2508,11 +2504,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -2967,11 +2962,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -3737,11 +3731,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -4130,11 +4123,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -4893,11 +4885,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -5286,11 +5277,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [
diff --git a/testing/buildbot/chromium.memory.json b/testing/buildbot/chromium.memory.json index e92d0b6..53f8b3e 100644 --- a/testing/buildbot/chromium.memory.json +++ b/testing/buildbot/chromium.memory.json
@@ -2770,12 +2770,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter", + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter", "--test-launcher-print-test-stdio=always" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -3092,12 +3091,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter", + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter", "--test-launcher-print-test-stdio=always" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -3604,11 +3602,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -3895,11 +3892,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -4339,12 +4335,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter", + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter", "--test-launcher-print-test-stdio=always" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -4691,12 +4686,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter", + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter", "--test-launcher-print-test-stdio=always" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -5420,12 +5414,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter", + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter", "--test-launcher-print-test-stdio=always" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -5988,12 +5981,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter", + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter", "--test-launcher-print-test-stdio=always" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -6891,12 +6883,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter", + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter", "--test-launcher-print-test-stdio=always" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -7469,12 +7460,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter", + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter", "--test-launcher-print-test-stdio=always" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -8186,12 +8176,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter", + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter", "--test-launcher-print-test-stdio=always" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -8515,12 +8504,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter", + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter", "--test-launcher-print-test-stdio=always" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -8989,12 +8977,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter", + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter", "--test-launcher-print-test-stdio=always" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -9281,12 +9268,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter", + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter", "--test-launcher-print-test-stdio=always" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -9855,11 +9841,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -10379,11 +10364,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [
diff --git a/testing/buildbot/chromium.perf.json b/testing/buildbot/chromium.perf.json index ec8f9f6..0e5819e5 100644 --- a/testing/buildbot/chromium.perf.json +++ b/testing/buildbot/chromium.perf.json
@@ -684,6 +684,51 @@ } ] }, + "android-go_webview-perf": { + "isolated_scripts": [ + { + "args": [ + "-v", + "--browser=android-webview-google", + "--upload-results", + "--webview-embedder-apk=../../out/Release/apks/SystemWebViewShell.apk", + "--test-shard-map-filename=android-go_webview-perf_map.json" + ], + "isolate_name": "performance_webview_test_suite", + "merge": { + "script": "//tools/perf/process_perf_results.py" + }, + "name": "performance_webview_test_suite", + "override_compile_targets": [ + "performance_webview_test_suite" + ], + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "device_os": "O", + "device_os_flavor": "google", + "device_type": "gobo", + "os": "Android", + "pool": "chrome.tests.perf-webview" + } + ], + "expiration": 7200, + "hard_timeout": 36000, + "ignore_task_failure": false, + "io_timeout": 1800, + "shards": 25 + }, + "trigger_script": { + "args": [ + "--multiple-dimension-script-verbose", + "True" + ], + "script": "//testing/trigger_scripts/perf_device_trigger.py" + } + } + ] + }, "android-nexus5x-perf": { "isolated_scripts": [ {
diff --git a/testing/buildbot/chromium.win.json b/testing/buildbot/chromium.win.json index 4997893..8e0cb978 100644 --- a/testing/buildbot/chromium.win.json +++ b/testing/buildbot/chromium.win.json
@@ -123,11 +123,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -431,11 +430,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -1020,11 +1018,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -1591,11 +1588,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -1982,6 +1978,7 @@ "test": "storage_unittests" }, { + "experiment_percentage": 100, "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -2799,12 +2796,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], "experiment_percentage": 100, - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -3624,11 +3620,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -3890,11 +3885,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true }, @@ -4404,11 +4398,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -4712,11 +4705,10 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true },
diff --git a/testing/buildbot/filters/BUILD.gn b/testing/buildbot/filters/BUILD.gn index a7210a8..19336a1 100644 --- a/testing/buildbot/filters/BUILD.gn +++ b/testing/buildbot/filters/BUILD.gn
@@ -22,7 +22,7 @@ data = [ "//testing/buildbot/filters/chromeos.mash.browser_tests.filter", "//testing/buildbot/filters/chromeos.mash.fyi.browser_tests.filter", - "//testing/buildbot/filters/webui_polymer2_browser_tests.filter", + "//testing/buildbot/filters/webui_polymer1_browser_tests.filter", "//testing/buildbot/filters/webrtc_functional.browser_tests.filter", ] } @@ -76,7 +76,7 @@ data = [ "//testing/buildbot/filters/chromeos.mash.fyi.interactive_ui_tests.filter", - "//testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter", + "//testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter", ] }
diff --git a/testing/buildbot/filters/chromeos.mash.fyi.interactive_ui_tests.filter b/testing/buildbot/filters/chromeos.mash.fyi.interactive_ui_tests.filter index eaa6a2a..b91a9b4 100644 --- a/testing/buildbot/filters/chromeos.mash.fyi.interactive_ui_tests.filter +++ b/testing/buildbot/filters/chromeos.mash.fyi.interactive_ui_tests.filter
@@ -31,6 +31,14 @@ -StickyKeysBrowserTest.OverlayShown -StickyKeysBrowserTest.SearchLeftOmnibox -SwitchAccessTest.IgnoresVirtualKeyEvents +-TestAsNormalAndGuestUser/SpokenFeedbackAppListTest.DisabledFullscreenExpandButton/0 +-TestAsNormalAndGuestUser/SpokenFeedbackAppListTest.DisabledFullscreenExpandButton/1 +-TestAsNormalAndGuestUser/SpokenFeedbackAppListTest.FullscreenLauncherFocusTraversal/0 +-TestAsNormalAndGuestUser/SpokenFeedbackAppListTest.FullscreenLauncherFocusTraversal/1 +-TestAsNormalAndGuestUser/SpokenFeedbackAppListTest.LauncherStateTransition/0 +-TestAsNormalAndGuestUser/SpokenFeedbackAppListTest.LauncherStateTransition/1 +-TestAsNormalAndGuestUser/SpokenFeedbackAppListTest.FullscreenLauncherFocusTraversal/0 +-TestAsNormalAndGuestUser/SpokenFeedbackAppListTest.FullscreenLauncherFocusTraversal/1 -TestAsNormalAndGuestUser/SpokenFeedbackTest.ChromeVoxNextTabRecovery/0 -TestAsNormalAndGuestUser/SpokenFeedbackTest.ChromeVoxNextTabRecovery/1 -TestAsNormalAndGuestUser/SpokenFeedbackTest.ChromeVoxShiftSearch/0
diff --git a/testing/buildbot/filters/mojo.fyi.network_webview_CTS_test.filter b/testing/buildbot/filters/mojo.fyi.network_webview_CTS_test.filter index 79d04d4..f5d050a 100644 --- a/testing/buildbot/filters/mojo.fyi.network_webview_CTS_test.filter +++ b/testing/buildbot/filters/mojo.fyi.network_webview_CTS_test.filter
@@ -20,9 +20,6 @@ -android.webkit.cts.CookieManagerTest.testAcceptCookie -android.webkit.cts.CookieManagerTest.testRemoveCookies -android.webkit.cts.CookieManagerTest.testThirdPartyCookie --android.webkit.cts.HttpAuthHandlerTest.testCancel --android.webkit.cts.HttpAuthHandlerTest.testProceed --android.webkit.cts.HttpAuthHandlerTest.testUseHttpAuthUsernamePassword -android.webkit.cts.WebChromeClientTest.testOnJsBeforeUnloadIsCalled -android.webkit.cts.WebViewClientTest.testOnReceivedError -android.webkit.cts.WebViewClientTest.testShouldOverrideUrlLoading
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 4c00a9f6..ebff8b3 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
@@ -20,35 +20,18 @@ -org.chromium.android_webview.test.AwContentsClientShouldInterceptRequestTest.testLoadDataWithBaseUrlTriggersShouldInterceptRequest # https://crbug.com/893575 --org.chromium.android_webview.test.CookieManagerStartupTest.testShouldInterceptRequestDeadlock -org.chromium.android_webview.test.CookieManagerStartupTest.testStartup # https://crbug.com/893576 -org.chromium.android_webview.test.CookieManagerTest.testAcceptCookie_falseWontSetCookies -org.chromium.android_webview.test.CookieManagerTest.testAcceptFileSchemeCookies --org.chromium.android_webview.test.CookieManagerTest.testEmbedderCanSeeRestrictedCookies --org.chromium.android_webview.test.CookieManagerTest.testRejectFileSchemeCookies -org.chromium.android_webview.test.CookieManagerTest.testThirdPartyCookie --org.chromium.android_webview.test.CookieManagerTest.testThirdPartyCookieForWebSocketEnabledCase --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.testThirdPartyCookieInIframe # https://crbug.com/893582 -org.chromium.android_webview.test.SafeBrowsingTest.testSafeBrowsingDontProceedCausesNetworkErrorForMainFrame
diff --git a/testing/buildbot/filters/webui_polymer2_browser_tests.filter b/testing/buildbot/filters/webui_polymer1_browser_tests.filter similarity index 86% rename from testing/buildbot/filters/webui_polymer2_browser_tests.filter rename to testing/buildbot/filters/webui_polymer1_browser_tests.filter index 80bc674..2081c92 100644 --- a/testing/buildbot/filters/webui_polymer2_browser_tests.filter +++ b/testing/buildbot/filters/webui_polymer1_browser_tests.filter
@@ -1,43 +1,19 @@ -# crbug.com/738611: Need to test all of WebUI with Polymer 2 while the migration +# crbug.com/738611: Need to test all of WebUI with Polymer 1 while the migration # is still ongoing. - -# Failing tests -# -# The following tests are currently failing with Polymer 2, either on Desktop or -# CrOS. Need to be fixed and moved to the "Passing tests" section further down -# in this file. -# -# NOTE: Please do not add new exclusions to this file. Instead fix the test in -# question such that it passes with --enable-features=WebUIPolymer2 and, on -# Chrome OS, --disable-features=WebUIPolymer2Exceptions (and with GN -# optimize_webui=true and false). -# -# Note that some of these tests only fail inconsistently (like with -# --gtest_repeat=5, but might pass on a single invocation). - -# ChromeOS only test failures. --DemoSetupTest.BackOnArcTermsScreen --DemoSetupTest.ClickConnectedNetworkOnNetworkScreen --DemoSetupTest.ClickNetworkOnNetworkScreen --DemoSetupTest.OfflineSetupFlowError --DemoSetupTest.OfflineSetupFlowSuccess --DemoSetupTest.OnlineSetupFlowCrosComponentFailure --DemoSetupTest.OnlineSetupFlowError --DemoSetupTest.OnlineSetupFlowSuccess --DemoSetupTest.ShowOfflineSetupOptionOnNetworkList --EulaTest.LoadOffline - -# Passing tests -# # For practical reasons, we don't run all browser_tests with the WebUIPolymer2 -# flag enabled. Only the tests matching below are executed. It is possible that +# flag disabled. Only the tests matching below are executed. It is possible that # some tests that might be affected by the flag are not in the list below. -# Once all known failures have been fixed, we can upload a CL with the feature -# enabled by default and run the full set of tests, and collect any missing -# failing tests. +# If additional failures are found, add the affected tests to the list below, to +# prevent future regressions. ActiveDirectoryJoinTest.* AppManagementAppTest.* +AppManagementDomSwitchTest.* +AppManagementMainViewTest.* +AppManagementMetadataViewTest.* +AppManagementReducersTest.* +AppManagementRouterTest.* +AppManagementPwaPermissionViewTest.* AudioPlayerBrowserTest.* AutofillBrowserTest.* BluetoothInternalsTest.* @@ -90,7 +66,7 @@ CrElementsToolbarSearchFieldTest.* CrExtensionsActivityLogTest.* CrExtensionsActivityLogHistoryTest.* -CrExtensionsActivityLogItemTest.* +CrExtensionsActivityLogHistoryItemTest.* CrExtensionsActivityLogStreamTest.* CrExtensionsActivityLogStreamItemTest.* CrExtensionsA11yTest.*
diff --git a/testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter b/testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter new file mode 100644 index 0000000..9f593642 --- /dev/null +++ b/testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter
@@ -0,0 +1,25 @@ +# crbug.com/738611: Need to test all of WebUI with Polymer 1 while the migration +# is still ongoing. + +# For practical reasons, we don't run all interactive_ui_tests with the +# WebUIPolymer2 flag disabled. Only the tests matching below are executed. It is +# possible that some tests that might be affected by the flag are not in the +# list below. If additional failures are found, add the affected tests to the +# list below, to prevent future regressions. + +BookmarksFocusTest.All +CrElementsActionMenuTest.All +CrElementsCheckboxTest.All +CrElementsInputTest.All +CrElementsProfileAvatarSelectorFocusTest.All +CrElementsToggleTest.All +CrExtensionsOptionsPageTest.All +CrSettingsAnimatedPagesTest.All +CrSettingsFocusRowBehavior.FocusTest +CrSettingsSyncPageTest.All +HistoryFocusTest.All +PrintPreviewDestinationDialogInteractiveTest.* +PrintPreviewNumberSettingsSectionInteractiveTest.BlurResetsEmptyInput +PrintPreviewPagesSettingsTest.* +PrintPreviewPrintHeaderInteractiveTest.FocusPrintOnReady +SettingsUIBrowserTest.All
diff --git a/testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter b/testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter deleted file mode 100644 index f4ab42c4..0000000 --- a/testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter +++ /dev/null
@@ -1,55 +0,0 @@ -# crbug.com/738611: Need to test all of WebUI with Polymer 2 while the migration -# is still ongoing. -# -# Failing tests -# -# The following tests are currently failing with Polymer 2 on CrOS only. Need to -# be fixed and moved to the "Passing tests" section further down in this file. -# -# NOTE: Please do not add new exclusions to this file. Instead fix the test in -# question such that it passes with --enable-features=WebUIPolymer2 and, on -# Chrome OS, --disable-features=WebUIPolymer2Exceptions (and with GN -# optimize_webui=true and false). - -# Failing on Chrome OS only: --LoginUITest.OobeCatchException --LoginUITest.OobeNoExceptions - -# Failing on Chrome OS MSAN only: --ActiveDirectoryLoginAutocompleteTest.PRE_TestAutocomplete --ActiveDirectoryLoginAutocompleteTest.PRE_LoginSuccess --ActiveDirectoryLoginTest.PRE_PasswordChange_LoginSuccess --ActiveDirectoryLoginTest.PRE_PasswordChange_UIErrors --ActiveDirectoryLoginTest.PRE_LoginErrors --ActiveDirectoryLoginTest.PRE_LoginSuccess --ActiveDirectoryLoginTest.PRE_PasswordChange_ReopenClearErrors --LoginSigninTest.WebUIVisible --LoginUITest.PRE_InterruptedAutoStartEnrollment --LoginUITest.InterruptedAutoStartEnrollment --LoginUITest.PRE_LoginNoExceptions --LoginUITest.LoginNoExceptions --LoginUITest.PRE_LoginUIVisible --OobeDisplayChooserTest.RemovingPrimaryDisplaySanityCheck --OobeTest.Accelerator --OobeTest.NewUser - -# Passing tests -# -# There are overall very few WebUI interactive_ui_tests, so list them here -# explicitly, instead of running all interactive_ui_tests. -BookmarksFocusTest.All -CrElementsActionMenuTest.All -CrElementsCheckboxTest.All -CrElementsInputTest.All -CrElementsProfileAvatarSelectorFocusTest.All -CrElementsToggleTest.All -CrExtensionsOptionsPageTest.All -CrSettingsAnimatedPagesTest.All -CrSettingsFocusRowBehavior.FocusTest -CrSettingsSyncPageTest.All -HistoryFocusTest.All -PrintPreviewDestinationDialogInteractiveTest.* -PrintPreviewNumberSettingsSectionInteractiveTest.BlurResetsEmptyInput -PrintPreviewPagesSettingsTest.* -PrintPreviewPrintHeaderInteractiveTest.FocusPrintOnReady -SettingsUIBrowserTest.All
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index 09ab97df..95325be 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -55,6 +55,24 @@ }, }, }, + 'blink_common_unittests': { + 'remove_from': [ + # chromium.linux + 'Fuchsia x64', + ], + }, + 'blink_heap_unittests': { + 'remove_from': [ + # chromium.linux + 'Fuchsia x64', + ], + }, + 'blink_platform_unittests': { + 'remove_from': [ + # chromium.linux + 'Fuchsia x64', + ], + }, 'browser_tests': { 'remove_from': [ # chromium.clang @@ -1044,6 +1062,9 @@ 'shards': 2, }, }, + 'Win10 Tests x64': { + 'experiment_percentage': 100, # https://crbug.com/933356 + }, 'Win10 Tests x64 (dbg)': { 'experiment_percentage': 100, # https://crbug.com/840369 }, @@ -1651,13 +1672,13 @@ }, }, }, - 'webui_polymer2_browser_tests': { + 'webui_polymer1_browser_tests': { 'remove_from': [ # chromium.win 'Win10 Tests x64 (dbg)', # Matches browser_tests. ], }, - 'webui_polymer2_interactive_ui_tests': { + 'webui_polymer1_interactive_ui_tests': { 'modifications': { # Match interactive_ui_tests, see https://crbug.com/840369 # chromium.win
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index a19d5df..5a5b6ad 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -462,20 +462,13 @@ }, 'chromeos_device_kevin_tests': { - # TODO(crbug.com/866062): Bump these out of experimental once the bot's - # got a few green builds. 'base_unittests': { 'args': [ '--test-launcher-filter-file=../../testing/buildbot/filters/chromeos.base_unittests.filter', ], - 'experiment_percentage': 100, }, - 'chrome_kevin_tast_tests': { - 'experiment_percentage': 100, - }, - 'cros_vm_sanity_test': { - 'experiment_percentage': 100, - }, + 'chrome_kevin_tast_tests': {}, + 'cros_vm_sanity_test': {}, }, 'chromeos_isolated_scripts': { @@ -2753,6 +2746,9 @@ 'fuchsia_gtests': { 'angle_unittests': {}, 'base_unittests': {}, + 'blink_common_unittests': {}, + 'blink_heap_unittests': {}, + 'blink_platform_unittests': {}, 'cast_runner_browsertests': {}, 'cast_runner_integration_tests': {}, 'content_unittests': { @@ -4062,22 +4058,20 @@ 'snapshot_unittests': {}, 'sync_integration_tests': {}, 'views_unittests': {}, - 'webui_polymer2_browser_tests': { + 'webui_polymer1_browser_tests': { 'args': [ - '--enable-features=WebUIPolymer2', - '--disable-features=WebUIPolymer2Exceptions', - '--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter', + '--disable-features=WebUIPolymer2', + '--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter', ], 'swarming': { 'shards': 4, }, 'test': 'browser_tests', }, - 'webui_polymer2_interactive_ui_tests': { + 'webui_polymer1_interactive_ui_tests': { 'args': [ - '--enable-features=WebUIPolymer2', - '--disable-features=WebUIPolymer2Exceptions', - '--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter', + '--disable-features=WebUIPolymer2', + '--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter', ], 'test': 'interactive_ui_tests', },
diff --git a/testing/buildbot/tryserver.chromium.linux.json b/testing/buildbot/tryserver.chromium.linux.json index b107bcf8..4fd99cae 100644 --- a/testing/buildbot/tryserver.chromium.linux.json +++ b/testing/buildbot/tryserver.chromium.linux.json
@@ -110,12 +110,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_browser_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" ], "isolate_coverage_data": true, - "name": "webui_polymer2_browser_tests", + "name": "webui_polymer1_browser_tests", "swarming": { "can_use_on_swarming_builders": true, "shards": 4 @@ -401,12 +400,11 @@ }, { "args": [ - "--enable-features=WebUIPolymer2", - "--disable-features=WebUIPolymer2Exceptions", - "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer2_interactive_ui_tests.filter" + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" ], "isolate_coverage_data": true, - "name": "webui_polymer2_interactive_ui_tests", + "name": "webui_polymer1_interactive_ui_tests", "swarming": { "can_use_on_swarming_builders": true },
diff --git a/testing/trigger_scripts/base_test_triggerer.py b/testing/trigger_scripts/base_test_triggerer.py index e576e338..ccca8c02 100755 --- a/testing/trigger_scripts/base_test_triggerer.py +++ b/testing/trigger_scripts/base_test_triggerer.py
@@ -267,9 +267,9 @@ sys.stderr.write('Failed to trigger a task, aborting\n') return ret result_json = self.read_json_from_temp_file(json_temp) - if shard_index == 0: + if not merged_json: # Copy the entire JSON -- in particular, the "request" - # dictionary -- from shard 0. "swarming.py collect" uses + # dictionary -- from the first shard. "swarming.py collect" uses # some keys from this dictionary, in particular related to # expiration. It also contains useful debugging information. merged_json = copy.deepcopy(result_json)
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 5642c6a..dfc6f73 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -1353,6 +1353,21 @@ ] } ], + "DarkModeWindows": [ + { + "platforms": [ + "windows" + ], + "experiments": [ + { + "name": "DarkMode", + "enable_features": [ + "DarkMode" + ] + } + ] + } + ], "DataCompressionProxyLoFi": [ { "platforms": [ @@ -1729,6 +1744,21 @@ ] } ], + "EnableChromeOSAccountManager": [ + { + "platforms": [ + "chromeos" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "ChromeOSAccountManager" + ] + } + ] + } + ], "EnableCsrssLockdown": [ { "platforms": [ @@ -3827,7 +3857,7 @@ { "name": "Enabled", "params": { - "connection_options": "NSTP" + "connection_options": "5RTO,NSTP" } } ] @@ -5365,7 +5395,7 @@ ] } ], - "VizHitTestDrawQuad": [ + "VizHitTest": [ { "platforms": [ "android", @@ -5376,8 +5406,11 @@ ], "experiments": [ { - "name": "Enabled", + "name": "VizHitTestSurfaceLayer", "enable_features": [ + "VizHitTestSurfaceLayer" + ], + "disable_features": [ "VizHitTestDrawQuad" ] } @@ -5546,7 +5579,7 @@ ] } ], - "WebRTC-Audio-OpusMinPacketLossRate": [ + "WebRTC-Audio-NewOpusPacketLossRateOptimization": [ { "platforms": [ "windows", @@ -5556,7 +5589,7 @@ ], "experiments": [ { - "name": "Enabled" + "name": "Enabled-0-20-1" } ] }
diff --git a/third_party/blink/PRESUBMIT.py b/third_party/blink/PRESUBMIT.py index 8318d54..dc710aa 100644 --- a/third_party/blink/PRESUBMIT.py +++ b/third_party/blink/PRESUBMIT.py
@@ -58,8 +58,8 @@ if f.LocalPath().startswith(public_folder) and \ not f.LocalPath() in allow_blink_files: error_list = public_blink_mojom_errors - elif match.group(1) not in ('-blink', '-blink-forward'): - # Neither -shared.h, -blink.h nor -blink-forward.h. + elif match.group(1) not in ('-blink', '-blink-forward', '-blink-test-utils'): + # Neither -shared.h, -blink.h, -blink-forward.h nor -blink-test-utils.h. error_list = non_blink_mojom_errors if error_list is not None:
diff --git a/third_party/blink/PRESUBMIT_test.py b/third_party/blink/PRESUBMIT_test.py index 95d9b54..e7cf59ca 100755 --- a/third_party/blink/PRESUBMIT_test.py +++ b/third_party/blink/PRESUBMIT_test.py
@@ -129,6 +129,7 @@ potentially_bad_content = """ #include "public/platform/modules/cache_storage.mojom-blink.h" #include "public/platform/modules/cache_storage.mojom-blink-forward.h" + #include "public/platform/modules/cache_storage.mojom-blink-test-utils.h" """ mock_input_api.files = [ MockAffectedFile('third_party/blink/renderer/core/a_header.h',
diff --git a/third_party/blink/common/notifications/notification_struct_traits.cc b/third_party/blink/common/notifications/notification_struct_traits.cc index 97248882..04aec5c 100644 --- a/third_party/blink/common/notifications/notification_struct_traits.cc +++ b/third_party/blink/common/notifications/notification_struct_traits.cc
@@ -39,47 +39,9 @@ namespace mojo { -using blink::mojom::NotificationDirection; using blink::mojom::NotificationActionType; // static -NotificationDirection -EnumTraits<NotificationDirection, blink::PlatformNotificationData::Direction>:: - ToMojom(blink::PlatformNotificationData::Direction input) { - switch (input) { - case blink::PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT: - return NotificationDirection::LEFT_TO_RIGHT; - case blink::PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT: - return NotificationDirection::RIGHT_TO_LEFT; - case blink::PlatformNotificationData::DIRECTION_AUTO: - return NotificationDirection::AUTO; - } - - NOTREACHED(); - return NotificationDirection::AUTO; -} - -// static -bool EnumTraits<NotificationDirection, - blink::PlatformNotificationData::Direction>:: - FromMojom(NotificationDirection input, - blink::PlatformNotificationData::Direction* out) { - switch (input) { - case NotificationDirection::LEFT_TO_RIGHT: - *out = blink::PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT; - return true; - case NotificationDirection::RIGHT_TO_LEFT: - *out = blink::PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT; - return true; - case NotificationDirection::AUTO: - *out = blink::PlatformNotificationData::DIRECTION_AUTO; - return true; - } - - return false; -} - -// static NotificationActionType EnumTraits<NotificationActionType, blink::PlatformNotificationActionType>:: ToMojom(blink::PlatformNotificationActionType input) {
diff --git a/third_party/blink/common/notifications/notification_struct_traits_unittest.cc b/third_party/blink/common/notifications/notification_struct_traits_unittest.cc index 6327a13..d4dc8d8 100644 --- a/third_party/blink/common/notifications/notification_struct_traits_unittest.cc +++ b/third_party/blink/common/notifications/notification_struct_traits_unittest.cc
@@ -39,8 +39,7 @@ TEST(NotificationStructTraitsTest, NotificationDataRoundtrip) { PlatformNotificationData notification_data; notification_data.title = base::ASCIIToUTF16("Title of my notification"); - notification_data.direction = - PlatformNotificationData::Direction::DIRECTION_AUTO; + notification_data.direction = mojom::NotificationDirection::AUTO; notification_data.lang = "test-lang"; notification_data.body = base::ASCIIToUTF16("Notification body."); notification_data.tag = "notification-tag";
diff --git a/third_party/blink/public/common/notifications/notification_struct_traits.h b/third_party/blink/public/common/notifications/notification_struct_traits.h index 142e67c..ed9b056 100644 --- a/third_party/blink/public/common/notifications/notification_struct_traits.h +++ b/third_party/blink/public/common/notifications/notification_struct_traits.h
@@ -19,17 +19,6 @@ namespace mojo { template <> -struct BLINK_COMMON_EXPORT - EnumTraits<blink::mojom::NotificationDirection, - blink::PlatformNotificationData::Direction> { - static blink::mojom::NotificationDirection ToMojom( - blink::PlatformNotificationData::Direction input); - - static bool FromMojom(blink::mojom::NotificationDirection input, - blink::PlatformNotificationData::Direction* out); -}; - -template <> struct BLINK_COMMON_EXPORT EnumTraits<blink::mojom::NotificationActionType, blink::PlatformNotificationActionType> { static blink::mojom::NotificationActionType ToMojom( @@ -80,7 +69,7 @@ return data.title; } - static blink::PlatformNotificationData::Direction direction( + static blink::mojom::NotificationDirection direction( const blink::PlatformNotificationData& data) { return data.direction; }
diff --git a/third_party/blink/public/common/notifications/notification_types.typemap b/third_party/blink/public/common/notifications/notification_types.typemap index 0910c23..9adfb765 100644 --- a/third_party/blink/public/common/notifications/notification_types.typemap +++ b/third_party/blink/public/common/notifications/notification_types.typemap
@@ -13,6 +13,5 @@ ] type_mappings = [ "blink.mojom.NotificationData=blink::PlatformNotificationData", - "blink.mojom.NotificationDirection=blink::PlatformNotificationData::Direction", "blink.mojom.NotificationResources=blink::NotificationResources", ]
diff --git a/third_party/blink/public/common/notifications/platform_notification_data.h b/third_party/blink/public/common/notifications/platform_notification_data.h index 06727e6..dc77e0f 100644 --- a/third_party/blink/public/common/notifications/platform_notification_data.h +++ b/third_party/blink/public/common/notifications/platform_notification_data.h
@@ -12,6 +12,7 @@ #include "base/strings/string16.h" #include "base/time/time.h" #include "third_party/blink/public/common/common_export.h" +#include "third_party/blink/public/mojom/notifications/notification.mojom.h" #include "url/gurl.h" namespace blink { @@ -54,19 +55,12 @@ PlatformNotificationData(const PlatformNotificationData& other); ~PlatformNotificationData(); - enum Direction { - DIRECTION_LEFT_TO_RIGHT, - DIRECTION_RIGHT_TO_LEFT, - DIRECTION_AUTO, - - DIRECTION_LAST = DIRECTION_AUTO - }; - // Title to be displayed with the Web Notification. base::string16 title; // Hint to determine the directionality of the displayed notification. - Direction direction = DIRECTION_LEFT_TO_RIGHT; + mojom::NotificationDirection direction = + mojom::NotificationDirection::LEFT_TO_RIGHT; // BCP 47 language tag describing the notification's contents. Optional. std::string lang;
diff --git a/third_party/blink/public/mojom/appcache/appcache.mojom b/third_party/blink/public/mojom/appcache/appcache.mojom index 0503d0b..33c3e9e 100644 --- a/third_party/blink/public/mojom/appcache/appcache.mojom +++ b/third_party/blink/public/mojom/appcache/appcache.mojom
@@ -62,7 +62,8 @@ // // TODO(mek): Move this method to DocumentInterfaceBroker to stop passing // frame ID over mojo. - RegisterHost(AppCacheHost& host_request, int32 host_id, int32 render_frame_id); + RegisterHost(AppCacheHost& host_request, AppCacheFrontend frontend, + int32 host_id, int32 render_frame_id); }; interface AppCacheHost { @@ -115,28 +116,26 @@ // AppCache messages sent from the browser to the renderer process. interface AppCacheFrontend { // Notifies the renderer of the appcache that has been selected for a - // a particular host. This is sent in reply to AppCacheHostMsg_SelectCache. - CacheSelected(int32 host_id, AppCacheInfo info); + // a particular host. This is sent in reply to AppCacheHost.SelectCache. + CacheSelected(AppCacheInfo info); // Notifies the renderer of an AppCache event other than the // progress event which has a seperate message. - EventRaised(array<int32> host_ids, AppCacheEventID event_id); + EventRaised(AppCacheEventID event_id); // Notifies the renderer of an AppCache progress event. - ProgressEventRaised(array<int32> host_ids, - url.mojom.Url url, + ProgressEventRaised(url.mojom.Url url, int32 total, int32 complete); // Notifies the renderer of an AppCache error event. - ErrorEventRaised(array<int32> host_ids, AppCacheErrorDetails error_details); + ErrorEventRaised(AppCacheErrorDetails error_details); // Notifies the renderer of an AppCache logging message. - LogMessage(int32 host_id, ConsoleMessageLevel log_level, string message); + LogMessage(ConsoleMessageLevel log_level, string message); // In the network service world this message sets the URLLoaderFactory to be // used for subresources. - SetSubresourceFactory(int32 host_id, - network.mojom.URLLoaderFactory url_loader_factory); + SetSubresourceFactory(network.mojom.URLLoaderFactory url_loader_factory); };
diff --git a/third_party/blink/public/platform/web_feature.mojom b/third_party/blink/public/platform/web_feature.mojom index 3df7e20f..e9e0db8 100644 --- a/third_party/blink/public/platform/web_feature.mojom +++ b/third_party/blink/public/platform/web_feature.mojom
@@ -2230,6 +2230,7 @@ kClientHintsUAPlatform = 2791, kClientHintsUAModel = 2792, kAnimationFrameCancelledWithinFrame = 2793, + kSchedulingIsInputPending = 2794, // Add new features immediately above this line. Don't change assigned // numbers of any item, and don't reuse removed slots.
diff --git a/third_party/blink/public/platform/web_localized_string.h b/third_party/blink/public/platform/web_localized_string.h index 50160f5..2fa5e42 100644 --- a/third_party/blink/public/platform/web_localized_string.h +++ b/third_party/blink/public/platform/web_localized_string.h
@@ -61,6 +61,7 @@ kAXMediaOverflowButtonHelp, kAXMediaPauseButton, kAXMediaPlayButton, + kAXMediaPlaybackError, kAXMediaShowClosedCaptionsMenuButton, kAXMediaTimeRemainingDisplay, kAXMediaTimeRemainingDisplayHelp,
diff --git a/third_party/blink/public/platform/web_rtc_data_channel_handler.h b/third_party/blink/public/platform/web_rtc_data_channel_handler.h index 15e80db7..e5a1f60 100644 --- a/third_party/blink/public/platform/web_rtc_data_channel_handler.h +++ b/third_party/blink/public/platform/web_rtc_data_channel_handler.h
@@ -44,11 +44,11 @@ virtual bool IsReliable() { return true; } virtual bool Ordered() const = 0; - virtual unsigned short MaxRetransmitTime() const = 0; - virtual unsigned short MaxRetransmits() const = 0; + virtual uint16_t MaxRetransmitTime() const = 0; + virtual uint16_t MaxRetransmits() const = 0; virtual WebString Protocol() const = 0; virtual bool Negotiated() const = 0; - virtual unsigned short Id() const = 0; + virtual uint16_t Id() const = 0; virtual WebRTCDataChannelHandlerClient::ReadyState GetState() const = 0; virtual unsigned long BufferedAmount() = 0;
diff --git a/third_party/blink/public/platform/web_runtime_features.h b/third_party/blink/public/platform/web_runtime_features.h index 2a7d253..cb55b46c 100644 --- a/third_party/blink/public/platform/web_runtime_features.h +++ b/third_party/blink/public/platform/web_runtime_features.h
@@ -179,7 +179,6 @@ BLINK_PLATFORM_EXPORT static void EnableUserActivationV2(bool); BLINK_PLATFORM_EXPORT static void EnableV8IdleTasks(bool); BLINK_PLATFORM_EXPORT static void EnableWebAuth(bool); - BLINK_PLATFORM_EXPORT static void EnableWebAuthGetTransports(bool); BLINK_PLATFORM_EXPORT static void EnableWebBluetooth(bool); BLINK_PLATFORM_EXPORT static void EnableWebBluetoothScanning(bool); BLINK_PLATFORM_EXPORT static void EnableWebGL2ComputeContext(bool);
diff --git a/third_party/blink/renderer/bindings/core/v8/script_streamer_test.cc b/third_party/blink/renderer/bindings/core/v8/script_streamer_test.cc index fafa3996..0516132 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_streamer_test.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_streamer_test.cc
@@ -23,9 +23,9 @@ #include "third_party/blink/renderer/core/script/classic_script.h" #include "third_party/blink/renderer/core/script/mock_script_element_base.h" #include "third_party/blink/renderer/core/testing/dummy_page_holder.h" -#include "third_party/blink/renderer/platform/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/exported/wrapped_resource_response.h" #include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_loader.h" #include "third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h" #include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
diff --git a/third_party/blink/renderer/bindings/modules/v8/generated.gni b/third_party/blink/renderer/bindings/modules/v8/generated.gni index 4df4bd2..127398d 100644 --- a/third_party/blink/renderer/bindings/modules/v8/generated.gni +++ b/third_party/blink/renderer/bindings/modules/v8/generated.gni
@@ -103,6 +103,8 @@ "$bindings_modules_v8_output_dir/v8_navigator_user_media_success_callback.h", "$bindings_modules_v8_output_dir/v8_notification_permission_callback.cc", "$bindings_modules_v8_output_dir/v8_notification_permission_callback.h", + "$bindings_modules_v8_output_dir/v8_paint_callback.cc", + "$bindings_modules_v8_output_dir/v8_paint_callback.h", "$bindings_modules_v8_output_dir/v8_position_callback.cc", "$bindings_modules_v8_output_dir/v8_position_callback.h", "$bindings_modules_v8_output_dir/v8_position_error_callback.cc",
diff --git a/third_party/blink/renderer/build/scripts/core/style/make_computed_style_base.py b/third_party/blink/renderer/build/scripts/core/style/make_computed_style_base.py index 1f248f9..f7225f7 100755 --- a/third_party/blink/renderer/build/scripts/core/style/make_computed_style_base.py +++ b/third_party/blink/renderer/build/scripts/core/style/make_computed_style_base.py
@@ -61,8 +61,8 @@ 'TabSize', 'float', # Aligns like int - 'ScrollSnapType', - 'ScrollSnapAlign', + 'cc::ScrollSnapType', + 'cc::ScrollSnapAlign', 'BorderValue', 'StyleColor', 'Color',
diff --git a/third_party/blink/renderer/core/BUILD.gn b/third_party/blink/renderer/core/BUILD.gn index ed41674..91e1b2b 100644 --- a/third_party/blink/renderer/core/BUILD.gn +++ b/third_party/blink/renderer/core/BUILD.gn
@@ -178,6 +178,7 @@ "//third_party/blink/renderer/core/animation", "//third_party/blink/renderer/core/aom", "//third_party/blink/renderer/core/clipboard", + "//third_party/blink/renderer/core/content_capture", "//third_party/blink/renderer/core/context_features", "//third_party/blink/renderer/core/css", "//third_party/blink/renderer/core/display_lock", @@ -1731,6 +1732,7 @@ "animation/timing_input_test.cc", "clipboard/data_object_test.cc", "clipboard/data_transfer_test.cc", + "content_capture/content_capture_test.cc", "css/active_style_sheets_test.cc", "css/affected_by_pseudo_test.cc", "css/css_calculation_value_test.cc", @@ -2119,6 +2121,7 @@ "page/chrome_client_test.cc", "page/context_menu_controller_test.cc", "page/drag_controller_test.cc", + "page/drag_image_test.cc", "page/focus_controller_test.cc", "page/page_popup_client_test.cc", "page/print_context_test.cc",
diff --git a/third_party/blink/renderer/core/DEPS b/third_party/blink/renderer/core/DEPS index 0e5cd10..c267a7a 100644 --- a/third_party/blink/renderer/core/DEPS +++ b/third_party/blink/renderer/core/DEPS
@@ -49,6 +49,7 @@ "+services/service_manager/public", "+services/ws/public/mojom/ime/ime.mojom-shared.h", "+skia/public/interfaces/bitmap_skbitmap_struct_traits.h", + "+skia/ext/image_operations.h", "+skia/ext/skia_utils_mac.h", "+third_party/blink/public/common", "+third_party/blink/public/mojom",
diff --git a/third_party/blink/renderer/core/accessibility/ax_object_cache.h b/third_party/blink/renderer/core/accessibility/ax_object_cache.h index e9dfdd7..b531636 100644 --- a/third_party/blink/renderer/core/accessibility/ax_object_cache.h +++ b/third_party/blink/renderer/core/accessibility/ax_object_cache.h
@@ -68,6 +68,7 @@ virtual void ListboxActiveIndexChanged(HTMLSelectElement*) = 0; virtual void LocationChanged(LayoutObject*) = 0; virtual void RadiobuttonRemovedFromGroup(HTMLInputElement*) = 0; + virtual void ImageLoaded(LayoutObject*) = 0; virtual void Remove(AccessibleNode*) = 0; virtual void Remove(LayoutObject*) = 0;
diff --git a/third_party/blink/renderer/core/animation/css/css_animations.cc b/third_party/blink/renderer/core/animation/css/css_animations.cc index 151cc0e7..bd8fb87d 100644 --- a/third_party/blink/renderer/core/animation/css/css_animations.cc +++ b/third_party/blink/renderer/core/animation/css/css_animations.cc
@@ -1336,7 +1336,7 @@ return false; if (tree_scope.RootNode() == tree_scope.GetDocument()) return false; - return ToShadowRoot(tree_scope.RootNode()).host() == element; + return To<ShadowRoot>(tree_scope.RootNode()).host() == element; } bool CSSAnimations::IsAnimatingCustomProperties(
diff --git a/third_party/blink/renderer/core/animation/worklet_animation_controller.h b/third_party/blink/renderer/core/animation/worklet_animation_controller.h index 3b9bdb7..0acfb2f 100644 --- a/third_party/blink/renderer/core/animation/worklet_animation_controller.h +++ b/third_party/blink/renderer/core/animation/worklet_animation_controller.h
@@ -58,8 +58,6 @@ void SetMutationUpdate( std::unique_ptr<AnimationWorkletOutput> output) override; - void NotifyAnimationsPending() override {} - void NotifyAnimationsReady() override {} void SynchronizeAnimatorName(const String& animator_name) override; // Returns true if the animator with given name is registered in
diff --git a/third_party/blink/renderer/core/clipboard/data_object.cc b/third_party/blink/renderer/core/clipboard/data_object.cc index 5e3fefb..63be43d7 100644 --- a/third_party/blink/renderer/core/clipboard/data_object.cc +++ b/third_party/blink/renderer/core/clipboard/data_object.cc
@@ -352,8 +352,7 @@ item.binary_data_content_disposition = original_item->Title(); } else if (original_item->IsFilename()) { Blob* blob = original_item->GetAsFile(); - if (blob->IsFile()) { - File* file = ToFile(blob); + if (auto* file = DynamicTo<File>(blob)) { if (file->HasBackingFile()) { item.storage_type = WebDragData::Item::kStorageTypeFilename; item.filename_data = file->GetPath();
diff --git a/third_party/blink/renderer/core/clipboard/data_object_test.cc b/third_party/blink/renderer/core/clipboard/data_object_test.cc index 929af5bd..f523b21 100644 --- a/third_party/blink/renderer/core/clipboard/data_object_test.cc +++ b/third_party/blink/renderer/core/clipboard/data_object_test.cc
@@ -95,7 +95,8 @@ Blob* blob = item->GetAsFile(); ASSERT_TRUE(blob->IsFile()); - File* file = ToFile(blob); + auto* file = DynamicTo<File>(blob); + ASSERT_TRUE(file); EXPECT_TRUE(file->HasBackingFile()); EXPECT_EQ(File::kIsUserVisible, file->GetUserVisibility()); EXPECT_EQ(file_path, file->GetPath()); @@ -112,8 +113,8 @@ EXPECT_EQ(DataObjectItem::kFileKind, item->Kind()); Blob* blob = item->GetAsFile(); - ASSERT_TRUE(blob->IsFile()); - File* file = ToFile(blob); + auto* file = DynamicTo<File>(blob); + ASSERT_TRUE(file); EXPECT_TRUE(file->HasBackingFile()); EXPECT_EQ(File::kIsUserVisible, file->GetUserVisibility()); EXPECT_EQ(file_path, file->GetPath());
diff --git a/third_party/blink/renderer/core/clipboard/data_transfer.cc b/third_party/blink/renderer/core/clipboard/data_transfer.cc index a772f4c..eda7c59 100644 --- a/third_party/blink/renderer/core/clipboard/data_transfer.cc +++ b/third_party/blink/renderer/core/clipboard/data_transfer.cc
@@ -48,11 +48,11 @@ #include "third_party/blink/renderer/core/layout/layout_object.h" #include "third_party/blink/renderer/core/loader/resource/image_resource_content.h" #include "third_party/blink/renderer/core/page/chrome_client.h" +#include "third_party/blink/renderer/core/page/drag_image.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/core/paint/paint_info.h" #include "third_party/blink/renderer/core/paint/paint_layer.h" #include "third_party/blink/renderer/core/paint/paint_layer_painter.h" -#include "third_party/blink/renderer/platform/drag_image.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_canvas.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_record_builder.h" #include "third_party/blink/renderer/platform/graphics/static_bitmap_image.h" @@ -327,8 +327,8 @@ for (uint32_t i = 0; i < data_object_->length(); ++i) { if (data_object_->Item(i)->Kind() == DataObjectItem::kFileKind) { Blob* blob = data_object_->Item(i)->GetAsFile(); - if (blob && blob->IsFile()) - files->Append(ToFile(blob)); + if (auto* file = DynamicTo<File>(blob)) + files->Append(file); } }
diff --git a/third_party/blink/renderer/core/clipboard/data_transfer_test.cc b/third_party/blink/renderer/core/clipboard/data_transfer_test.cc index 70f5749f..4674a8ab 100644 --- a/third_party/blink/renderer/core/clipboard/data_transfer_test.cc +++ b/third_party/blink/renderer/core/clipboard/data_transfer_test.cc
@@ -10,9 +10,9 @@ #include "third_party/blink/renderer/core/frame/local_frame_view.h" #include "third_party/blink/renderer/core/frame/settings.h" #include "third_party/blink/renderer/core/layout/layout_object.h" +#include "third_party/blink/renderer/core/page/drag_image.h" #include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h" #include "third_party/blink/renderer/core/testing/core_unit_test_helper.h" -#include "third_party/blink/renderer/platform/drag_image.h" namespace blink {
diff --git a/third_party/blink/renderer/core/content_capture/BUILD.gn b/third_party/blink/renderer/core/content_capture/BUILD.gn new file mode 100644 index 0000000..5178de8 --- /dev/null +++ b/third_party/blink/renderer/core/content_capture/BUILD.gn
@@ -0,0 +1,17 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//third_party/blink/renderer/core/core.gni") + +blink_core_sources("content_capture") { + sources = [ + "content_capture_client.h", + "content_capture_manager.cc", + "content_capture_manager.h", + "content_capture_task.cc", + "content_capture_task.h", + "content_holder.cc", + "content_holder.h", + ] +}
diff --git a/third_party/blink/renderer/core/content_capture/DEPS b/third_party/blink/renderer/core/content_capture/DEPS new file mode 100644 index 0000000..01e64c0 --- /dev/null +++ b/third_party/blink/renderer/core/content_capture/DEPS
@@ -0,0 +1,6 @@ +include_rules = [ + "+base/logging.h", + "+cc/paint/node_holder.h", + "+cc/paint/text_holder.h", + "+cc/trees/layer_tree_host.h", +]
diff --git a/third_party/blink/renderer/core/content_capture/OWNERS b/third_party/blink/renderer/core/content_capture/OWNERS new file mode 100644 index 0000000..bc2e55f --- /dev/null +++ b/third_party/blink/renderer/core/content_capture/OWNERS
@@ -0,0 +1,4 @@ +pdr@chromium.org +michaelbai@chromium.org +skyostil@chromium.org +wangxianzhu@chromium.org
diff --git a/third_party/blink/renderer/core/content_capture/README.md b/third_party/blink/renderer/core/content_capture/README.md new file mode 100644 index 0000000..bb87b29c --- /dev/null +++ b/third_party/blink/renderer/core/content_capture/README.md
@@ -0,0 +1,28 @@ +# ContentCapture + +[Rendered](https://chromium.googlesource.com/chromium/src/+/master/third_party/blink/renderer/core/content_capture/README.md) + +This directory contains ContentCapture which is for capturing on-screen text +content and streaming it to a client. + +The implementation injects a cc::NodeHolder into cc::DrawTextBlobOp in paint +stage, schedules a best-effort task to retrieve on-screen text content (using +an r-tree to capture all cc::NodeHolder intersecting the screen), and streams +the text out through ContentCaptureClient interface. The ContentCaptureTask is +a best-effort task in the idle queue and could be paused if there are +higher-priority tasks. + +There are two ways to associate cc::NodeHolder with Node which are being +compared. One of these approaches will be removed once performance data is +available. + + 1. NodeHolder::Type::kID where the ID from DOMNodeIds::IdForNode() is used to +identify nodes. + 2. NodeHolder::Type::kTextHolder which uses ContentCapture’s implementation of +cc::TextHolder to identify the node. Since the NodeHolder is captured and sent +out in a separate task, the Node could be removed. To avoid using removed +Nodes, a weak pointer to Node is implemented. This weak pointer will be reset +when the Node associated with the LayoutText is destroyed. Though a Node can be +associated with multiple LayoutObjects, only the main LayoutObject has the +pointer back to Node, so it isn’t a problem to use the removing of LayoutText +to reset the pointer to the Node.
diff --git a/third_party/blink/renderer/core/content_capture/content_capture_client.h b/third_party/blink/renderer/core/content_capture/content_capture_client.h new file mode 100644 index 0000000..2db30e4 --- /dev/null +++ b/third_party/blink/renderer/core/content_capture/content_capture_client.h
@@ -0,0 +1,44 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CONTENT_CAPTURE_CONTENT_CAPTURE_CLIENT_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_CONTENT_CAPTURE_CONTENT_CAPTURE_CLIENT_H_ + +#include <vector> + +#include "third_party/blink/renderer/core/content_capture/content_holder.h" +#include "third_party/blink/renderer/core/core_export.h" +#include "third_party/blink/renderer/platform/heap/handle.h" + +namespace blink { + +class ContentHolder; + +// The interface ContentCapture client should be implemented. +class CORE_EXPORT ContentCaptureClient + : public GarbageCollectedFinalized<ContentCaptureClient> { + public: + virtual ~ContentCaptureClient() = default; + + // Returns if ContentCapture should be enable. + virtual bool IsContentCaptureEnabled() = 0; + + // Returns the NodeHolder::Type should be used in ContentCapture. + virtual NodeHolder::Type GetNodeHolderType() const = 0; + + // Invoked when a list of |content| is captured, |first_content| indicates if + // this is first captured content. + virtual void DidCaptureContent( + const std::vector<scoped_refptr<ContentHolder>>& content, + bool first_content) = 0; + + // Invoked when the content is removed, |content_ids| is a list of id of + // removed content. + virtual void DidRemoveContent(const std::vector<int64_t>& content_ids) = 0; + virtual void Trace(blink::Visitor* visitor) {} +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CONTENT_CAPTURE_CONTENT_CAPTURE_CLIENT_H_
diff --git a/third_party/blink/renderer/core/content_capture/content_capture_manager.cc b/third_party/blink/renderer/core/content_capture/content_capture_manager.cc new file mode 100644 index 0000000..da97918 --- /dev/null +++ b/third_party/blink/renderer/core/content_capture/content_capture_manager.cc
@@ -0,0 +1,96 @@ +// 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/core/content_capture/content_capture_manager.h" + +#include "third_party/blink/renderer/core/content_capture/content_holder.h" +#include "third_party/blink/renderer/core/layout/layout_text.h" + +namespace blink { + +ContentCaptureManager::ContentCaptureManager(Document& document, + NodeHolder::Type type) + : document_(&document), node_holder_type_(type) {} + +ContentCaptureManager::~ContentCaptureManager() = default; + +NodeHolder ContentCaptureManager::GetNodeHolder(Node& node) { + if (first_node_holder_created_) { + ScheduleTask(ContentCaptureTask::ScheduleReason::kContentChange); + } else { + ScheduleTask(ContentCaptureTask::ScheduleReason::kFirstContentChange); + first_node_holder_created_ = true; + } + if (node_holder_type_ == NodeHolder::Type::kID) + return NodeHolder(DOMNodeIds::IdForNode(&node)); + return NodeHolder(base::MakeRefCounted<ContentHolder>(node)); +} + +void ContentCaptureManager::ScheduleTask( + ContentCaptureTask::ScheduleReason reason) { + if (!content_capture_idle_task_.get()) { + content_capture_idle_task_ = CreateContentCaptureTask(); + } + content_capture_idle_task_->Schedule(reason); +} + +scoped_refptr<ContentCaptureTask> +ContentCaptureManager::CreateContentCaptureTask() { + return base::MakeRefCounted<ContentCaptureTask>(*document_, *this); +} + +void ContentCaptureManager::NotifyNodeDetached(const NodeHolder& node_holder) { + if (node_holder.type == NodeHolder::Type::kID) { + Node* node = DOMNodeIds::NodeForId(node_holder.id); + if (node && HasSent(*node)) + content_capture_idle_task_->OnNodeDetached(*node); + } else if (node_holder.type == NodeHolder::Type::kTextHolder) { + ContentHolder* content_holder = + static_cast<ContentHolder*>(node_holder.text_holder.get()); + if (!content_holder || !content_holder->IsValid() || + !content_holder->HasSent()) { + return; + } + content_capture_idle_task_->OnNodeDetached(*(content_holder->GetNode())); + } +} + +void ContentCaptureManager::OnLayoutTextWillBeDestroyed( + NodeHolder node_holder) { + DCHECK(!node_holder.is_empty); + NotifyNodeDetached(node_holder); + if (node_holder.type == NodeHolder::Type::kTextHolder) { + ContentHolder* content_holder = + static_cast<ContentHolder*>(node_holder.text_holder.get()); + if (content_holder) + content_holder->OnNodeDetachedFromLayoutTree(); + } + ScheduleTask(ContentCaptureTask::ScheduleReason::kContentChange); +} + +void ContentCaptureManager::OnScrollPositionChanged() { + ScheduleTask(ContentCaptureTask::ScheduleReason::kScrolling); +} + +bool ContentCaptureManager::HasSent(const Node& node) { + return sent_nodes_.Contains(&node); +} + +void ContentCaptureManager::OnSent(const Node& node) { + sent_nodes_.insert(WeakMember<const Node>(&node)); +} + +void ContentCaptureManager::Trace(Visitor* visitor) { + visitor->Trace(document_); + visitor->Trace(sent_nodes_); +} + +void ContentCaptureManager::Shutdown() { + if (content_capture_idle_task_) { + content_capture_idle_task_->Shutdown(); + content_capture_idle_task_.reset(); + } +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/content_capture/content_capture_manager.h b/third_party/blink/renderer/core/content_capture/content_capture_manager.h new file mode 100644 index 0000000..aedec07 --- /dev/null +++ b/third_party/blink/renderer/core/content_capture/content_capture_manager.h
@@ -0,0 +1,79 @@ +// 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_CORE_CONTENT_CAPTURE_CONTENT_CAPTURE_MANAGER_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_CONTENT_CAPTURE_CONTENT_CAPTURE_MANAGER_H_ + +#include "base/memory/scoped_refptr.h" +#include "third_party/blink/renderer/core/content_capture/content_capture_task.h" +#include "third_party/blink/renderer/core/content_capture/content_holder.h" +#include "third_party/blink/renderer/core/core_export.h" +#include "third_party/blink/renderer/core/dom/dom_node_ids.h" + +namespace blink { + +class Document; +class Node; + +// This class is used to create the NodeHolder, and start the ContentCaptureTask +// when necessary. The ContentCaptureManager is owned by Document. +class CORE_EXPORT ContentCaptureManager + : public GarbageCollectedFinalized<ContentCaptureManager>, + public ContentCaptureTask::Delegate { + public: + ContentCaptureManager(Document& document, NodeHolder::Type type); + ~ContentCaptureManager() override; + + // Creates and returns NodeHolder for the given |node|, and schedules + // ContentCaptureTask if it isn't already scheduled. + // Can't use const Node& for parameter, because |node| is passed to + // DOMNodeIds::IdForNode(Node*). + NodeHolder GetNodeHolder(Node& node); + + // Invokes when the |node_holder| asscociated LayoutText will be destroyed. + void OnLayoutTextWillBeDestroyed(NodeHolder node_holder); + + // Invokes when scroll position was changed. + void OnScrollPositionChanged(); + + // Invokes when the document shutdown. + void Shutdown(); + + // ContentCaptureTask::Delegate, these methods have to be in this class + // because the node stores in HeapHashSet. + bool HasSent(const Node& node) override; + void OnSent(const Node& node) override; + + void EnableContentCaptureTask() { should_capture_content_ = true; } + + virtual void Trace(blink::Visitor*); + + protected: + virtual scoped_refptr<ContentCaptureTask> CreateContentCaptureTask(); + + private: + void NotifyNodeDetached(const NodeHolder& node_holder); + void ScheduleTask(ContentCaptureTask::ScheduleReason reason); + + // Indicates if the ContentCaptureTask should be started. + bool should_capture_content_ = false; + + scoped_refptr<ContentCaptureTask> content_capture_idle_task_; + + Member<Document> document_; + + // Indicates the NodeHolder::Type should be used. + NodeHolder::Type node_holder_type_; + + // Indicates if the first NodeHolder is created. + bool first_node_holder_created_ = false; + + // The list of nodes that have been sent, only used when + // |node_identification_method| is kNodeID. + HeapHashSet<WeakMember<const Node>> sent_nodes_; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CONTENT_CAPTURE_CONTENT_CAPTURE_MANAGER_H_
diff --git a/third_party/blink/renderer/core/content_capture/content_capture_task.cc b/third_party/blink/renderer/core/content_capture/content_capture_task.cc new file mode 100644 index 0000000..84aadf11 --- /dev/null +++ b/third_party/blink/renderer/core/content_capture/content_capture_task.cc
@@ -0,0 +1,211 @@ +// 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/core/content_capture/content_capture_task.h" + +#include "base/auto_reset.h" +#include "cc/trees/layer_tree_host.h" +#include "third_party/blink/renderer/core/content_capture/content_capture_client.h" +#include "third_party/blink/renderer/core/content_capture/content_holder.h" +#include "third_party/blink/renderer/core/dom/dom_node_ids.h" +#include "third_party/blink/renderer/core/frame/local_frame_client.h" +#include "third_party/blink/renderer/core/layout/layout_text.h" +#include "third_party/blink/renderer/core/paint/paint_layer.h" +#include "third_party/blink/renderer/platform/graphics/graphics_layer.h" +#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h" +#include "third_party/blink/renderer/platform/wtf/functional.h" + +namespace blink { + +ContentCaptureTask::ContentCaptureTask(Document& document, Delegate& delegate) + : document_(&document), delegate_(&delegate) {} + +ContentCaptureTask::~ContentCaptureTask() {} + +void ContentCaptureTask::Shutdown() { + DCHECK(document_); + document_ = nullptr; + delegate_ = nullptr; +} + +void ContentCaptureTask::OnNodeDetached(const Node& node) { + if (!session_) { + session_ = std::make_unique<Session>(); + } + // TODO(michaelbai): might limit the size of detached_nodes. + session_->detached_nodes.push_back(reinterpret_cast<int64_t>(&node)); +} + +bool ContentCaptureTask::CaptureContent(std::vector<cc::NodeHolder>& data) { + // Because this is called from a different task, the frame may be in any + // lifecycle step so we need to early-out in many cases. + // TODO(michaelbai): runs task in main frame, and sends the captured content + // for each document separately. + if (const auto* frame = document_->GetFrame()) { + if (const auto* root_frame_view = frame->LocalFrameRoot().View()) { + if (const auto* cc_layer = root_frame_view->RootCcLayer()) { + if (auto* layer_tree_host = cc_layer->layer_tree_host()) + return layer_tree_host->CaptureContent(&data); + } + } + } + return false; +} + +bool ContentCaptureTask::CaptureContent() { + DCHECK(session_); + bool success = CaptureContent(session_->captured_content); + session_->unsent = session_->captured_content.begin(); + return success; +} + +void ContentCaptureTask::SendContent() { + DCHECK(session_); + std::vector<scoped_refptr<ContentHolder>> content_batch; + content_batch.reserve(kBatchSize); + for (; session_->unsent != session_->captured_content.end() && + content_batch.size() < kBatchSize; + ++session_->unsent) { + scoped_refptr<ContentHolder> content_holder; + if (session_->unsent->type == cc::NodeHolder::Type::kID) { + Node* node = DOMNodeIds::NodeForId(session_->unsent->id); + if (node && node->GetLayoutObject() && !delegate_->HasSent(*node)) { + content_holder = base::MakeRefCounted<ContentHolder>(*node); + delegate_->OnSent(*node); + content_batch.push_back(content_holder); + } + } else if (session_->unsent->type == cc::NodeHolder::Type::kTextHolder && + session_->unsent->text_holder) { + content_holder = scoped_refptr<ContentHolder>( + static_cast<ContentHolder*>(session_->unsent->text_holder.get())); + if (content_holder && content_holder->IsValid() && + !content_holder->HasSent()) { + content_holder->SetHasSent(); + content_batch.push_back(content_holder); + } + } + } + if (!content_batch.empty()) { + GetContentCaptureClient()->DidCaptureContent(content_batch, + !has_first_data_sent_); + has_first_data_sent_ = true; + } + if (session_->unsent == session_->captured_content.end()) + session_->captured_content.clear(); +} + +ContentCaptureClient* ContentCaptureTask::GetContentCaptureClient() { + // TODO(michaelbai): Enable this after integrate with document. + // return document_->GetFrame()->Client()->GetContentCaptureClient(); + return nullptr; +} + +bool ContentCaptureTask::ProcessSession() { + DCHECK(session_); + while (!session_->captured_content.empty()) { + SendContent(); + if (ShouldPause()) { + return session_->captured_content.empty() && + session_->detached_nodes.empty(); + } + } + // Sent the detached nodes. + if (!session_->detached_nodes.empty()) { + GetContentCaptureClient()->DidRemoveContent(session_->detached_nodes); + session_->detached_nodes.clear(); + } + session_.reset(); + return true; +} + +bool ContentCaptureTask::RunInternal() { + base::AutoReset<TaskState> state(&task_state_, TaskState::kProcessRetryTask); + // Already shutdown. + if (!document_ || !GetContentCaptureClient()) + return true; + + do { + switch (task_state_) { + case TaskState::kProcessRetryTask: + if (session_) { + if (!ProcessSession()) + return false; + } + task_state_ = TaskState::kCaptureContent; + break; + case TaskState::kCaptureContent: + if (!has_content_change_) + return true; + session_ = std::make_unique<Session>(); + if (!CaptureContent()) { + // Don't schedule task again in this case. + return true; + } + has_content_change_ = false; + if (session_->captured_content.empty()) + return true; + + task_state_ = TaskState::kProcessCurrentSession; + break; + case TaskState::kProcessCurrentSession: + return ProcessSession(); + break; + default: + return true; + } + } while (!ShouldPause()); + return false; +} + +void ContentCaptureTask::Run(TimerBase*) { + TRACE_EVENT0("blink", "CaptureContentTask::Run"); + is_scheduled_ = false; + bool success = RunInternal(); + if (success) { + session_.reset(); + } else { + ScheduleInternal(ScheduleReason::kRetryTask); + } +} + +void ContentCaptureTask::ScheduleInternal(ScheduleReason reason) { + DCHECK(document_); + if (is_scheduled_) + return; + + int delay_ms = 0; + switch (reason) { + case ScheduleReason::kFirstContentChange: + case ScheduleReason::kScrolling: + case ScheduleReason::kRetryTask: + delay_ms = kTaskShortDelayInMS; + break; + case ScheduleReason::kContentChange: + delay_ms = kTaskLongDelayInMS; + break; + } + + if (!delay_task_) { + scoped_refptr<base::SingleThreadTaskRunner> task_runner = + document_->GetTaskRunner(TaskType::kInternalContentCapture); + delay_task_ = std::make_unique<TaskRunnerTimer<ContentCaptureTask>>( + task_runner, this, &ContentCaptureTask::Run); + } + + delay_task_->StartOneShot(base::TimeDelta::FromMilliseconds(delay_ms), + FROM_HERE); + is_scheduled_ = true; +} + +void ContentCaptureTask::Schedule(ScheduleReason reason) { + DCHECK(document_); + has_content_change_ = true; + ScheduleInternal(reason); +} + +bool ContentCaptureTask::ShouldPause() { + return ThreadScheduler::Current()->ShouldYieldForHighPriorityWork(); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/content_capture/content_capture_task.h b/third_party/blink/renderer/core/content_capture/content_capture_task.h new file mode 100644 index 0000000..03ba3f2 --- /dev/null +++ b/third_party/blink/renderer/core/content_capture/content_capture_task.h
@@ -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. + +#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CONTENT_CAPTURE_CONTENT_CAPTURE_TASK_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_CONTENT_CAPTURE_CONTENT_CAPTURE_TASK_H_ + +#include <memory> +#include <vector> + +#include "cc/paint/node_holder.h" +#include "third_party/blink/renderer/core/core_export.h" +#include "third_party/blink/renderer/platform/timer.h" +#include "third_party/blink/renderer/platform/wtf/ref_counted.h" + +namespace blink { + +class ContentCaptureClient; +class Document; +class Node; + +// This class is used to capture the on-screen content and send them out +// through ContentCaptureClient. +class CORE_EXPORT ContentCaptureTask : public RefCounted<ContentCaptureTask> { + USING_FAST_MALLOC(ContentCaptureTask); + + public: + // This class is used for DOMNodeIds. + class Delegate { + public: + // Return if the give |node| has been sent out. + virtual bool HasSent(const Node& node) = 0; + // Notify the |node| has been sent. + virtual void OnSent(const Node& node) = 0; + + protected: + virtual ~Delegate() = default; + }; + + enum class ScheduleReason { + kFirstContentChange, + kContentChange, + kScrolling, + kRetryTask, + }; + + enum class TaskState { + kProcessRetryTask, + kCaptureContent, + kProcessCurrentSession, + kStop, + }; + + ContentCaptureTask(Document& document, Delegate& delegate); + virtual ~ContentCaptureTask(); + + // Schedule the task if it hasn't been done. + void Schedule(ScheduleReason reason); + void Shutdown(); + + // Invoked when the |node| is detached from LayoutTree. + void OnNodeDetached(const Node& node); + + // Make those const public for testing purpose. + static constexpr size_t kBatchSize = 5; + + // Schedules the task with short delay for kFirstContentChange, kScrolling and + // kRetryTask, with long delay for kContentChange. + static constexpr int kTaskShortDelayInMS = 500; + static constexpr int kTaskLongDelayInMS = 5000; + + TaskState GetTaskStateForTesting() const { return task_state_; } + + protected: + // All protected data and methods are for testing purpose. + // Return true if the task should pause. + virtual bool ShouldPause(); + virtual bool CaptureContent(std::vector<cc::NodeHolder>& data); + virtual ContentCaptureClient* GetContentCaptureClient(); + + private: + struct Session { + // The list of the captured content. + std::vector<cc::NodeHolder> captured_content; + // The first NodeHolder in |captured_content| hasn't been sent. + std::vector<cc::NodeHolder>::iterator unsent = captured_content.end(); + // The list of content id of node that has been detached from LayoutTree + // since the last running. + std::vector<int64_t> detached_nodes; + }; + + // Callback method of delay_task_, runs the content capture task and + // reschedule it if it necessary. + void Run(TimerBase*); + + // The actual run method, return if the task completed. + bool RunInternal(); + + // Runs the sub task to capture content. + bool CaptureContent(); + + // Runs the sub task to process the captured content and the detached nodes. + bool ProcessSession(); + + // Sends the captured content in batch. + void SendContent(); + + void ScheduleInternal(ScheduleReason reason); + + std::unique_ptr<Session> session_; + bool is_scheduled_ = false; + + // Indicates if there is content change since last run. + bool has_content_change_ = false; + + // Indicates if first data has been sent out. + bool has_first_data_sent_ = false; + UntracedMember<Document> document_; + Delegate* delegate_; + std::unique_ptr<TaskRunnerTimer<ContentCaptureTask>> delay_task_; + TaskState task_state_ = TaskState::kStop; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CONTENT_CAPTURE_CONTENT_CAPTURE_TASK_H_
diff --git a/third_party/blink/renderer/core/content_capture/content_capture_test.cc b/third_party/blink/renderer/core/content_capture/content_capture_test.cc new file mode 100644 index 0000000..a0f1be40 --- /dev/null +++ b/third_party/blink/renderer/core/content_capture/content_capture_test.cc
@@ -0,0 +1,353 @@ +// 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/core/content_capture/content_capture_manager.h" + +#include "third_party/blink/renderer/core/content_capture/content_capture_client.h" +#include "third_party/blink/renderer/core/dom/element.h" +#include "third_party/blink/renderer/core/dom/node.h" +#include "third_party/blink/renderer/core/layout/layout_object.h" +#include "third_party/blink/renderer/core/layout/layout_text.h" +#include "third_party/blink/renderer/core/testing/page_test_base.h" + +namespace blink { + +class ContentCaptureClientTestHelper : public ContentCaptureClient { + public: + ContentCaptureClientTestHelper(NodeHolder::Type type) + : node_holder_type_(type) {} + ~ContentCaptureClientTestHelper() override = default; + + bool IsContentCaptureEnabled() override { return true; } + + NodeHolder::Type GetNodeHolderType() const override { + return node_holder_type_; + } + + void DidCaptureContent(const std::vector<scoped_refptr<ContentHolder>>& data, + bool first_data) override { + data_ = data; + first_data_ = first_data; + } + + void DidRemoveContent(const std::vector<int64_t>& data) override { + removed_data_ = data; + } + + bool FirstData() const { return first_data_; } + + const std::vector<scoped_refptr<ContentHolder>>& Data() const { + return data_; + } + + const std::vector<int64_t>& RemovedData() const { return removed_data_; } + + void ResetResults() { + first_data_ = false; + data_.clear(); + removed_data_.clear(); + } + + private: + bool first_data_ = false; + std::vector<scoped_refptr<ContentHolder>> data_; + std::vector<int64_t> removed_data_; + NodeHolder::Type node_holder_type_; +}; + +class ContentCaptureTaskTestHelper : public ContentCaptureTask { + public: + ContentCaptureTaskTestHelper(Document& document, + Delegate& delegate, + ContentCaptureClient& content_capture_client) + : ContentCaptureTask(document, delegate), + content_capture_client_(&content_capture_client) {} + + void SetCapturedContent(const std::vector<cc::NodeHolder> captured_content) { + captured_content_ = captured_content; + } + + void SetTaskStopState(TaskState state) { task_stop_state_ = state; } + + void ResetIsCaptureContentCalled() { is_capture_content_called_ = false; } + + bool IsCaptureContentCalled() { return is_capture_content_called_; } + + protected: + bool CaptureContent(std::vector<cc::NodeHolder>& data) override { + is_capture_content_called_ = true; + for (auto cc : captured_content_) + data.push_back(cc); + return true; + } + + ContentCaptureClient* GetContentCaptureClient() override { + return content_capture_client_; + } + + bool ShouldPause() override { + return GetTaskStateForTesting() == task_stop_state_; + } + + private: + std::vector<cc::NodeHolder> captured_content_; + UntracedMember<ContentCaptureClient> content_capture_client_; + TaskState task_stop_state_ = TaskState::kStop; + bool is_capture_content_called_ = false; +}; + +class ContentCaptureManagerTestHelper : public ContentCaptureManager { + public: + ContentCaptureManagerTestHelper( + Document& document, + ContentCaptureClientTestHelper& content_capture_client) + : ContentCaptureManager(document, + content_capture_client.GetNodeHolderType()), + content_capture_client_(&content_capture_client) { + content_capture_task_ = base::MakeRefCounted<ContentCaptureTaskTestHelper>( + document, *this, content_capture_client); + } + + scoped_refptr<ContentCaptureTaskTestHelper> GetContentCaptureTask() { + return content_capture_task_; + } + + protected: + scoped_refptr<ContentCaptureTask> CreateContentCaptureTask() override { + return content_capture_task_; + } + + private: + scoped_refptr<ContentCaptureTaskTestHelper> content_capture_task_; + UntracedMember<ContentCaptureClientTestHelper> content_capture_client_; +}; + +class ContentCaptureTest + : public PageTestBase, + public ::testing::WithParamInterface<NodeHolder::Type> { + public: + ContentCaptureTest() { EnablePlatform(); } + + void SetUp() override { + PageTestBase::SetUp(); + SetHtmlInnerHTML( + "<!DOCTYPE HTML>" + "<p id='p1'>1</p>" + "<p id='p2'>2</p>" + "<p id='p3'>3</p>" + "<p id='p4'>4</p>" + "<p id='p5'>5</p>" + "<p id='p6'>6</p>" + "<p id='p7'>7</p>" + "<p id='p8'>8</p>"); + platform()->SetAutoAdvanceNowToPendingTasks(false); + // TODO(michaelbai): ContentCaptureManager should be get from Document. + content_capture_client_ = + MakeGarbageCollected<ContentCaptureClientTestHelper>(GetParam()); + content_capture_manager_ = + MakeGarbageCollected<ContentCaptureManagerTestHelper>( + GetDocument(), *content_capture_client_); + + InitNodeHolders(); + // Setup captured content to ContentCaptureTask, it isn't necessary once + // ContentCaptureManager is created by Document. + content_capture_manager_->GetContentCaptureTask()->SetCapturedContent( + node_holders_); + } + + ContentCaptureManagerTestHelper* GetContentCaptureManager() const { + return content_capture_manager_; + } + + ContentCaptureClientTestHelper* GetContentCaptureClient() const { + return content_capture_client_; + } + + scoped_refptr<ContentCaptureTaskTestHelper> GetContentCaptureTask() const { + return GetContentCaptureManager()->GetContentCaptureTask(); + } + + void RunContentCaptureTask() { + ResetResult(); + platform()->RunForPeriod(base::TimeDelta::FromMilliseconds( + ContentCaptureTask::kTaskShortDelayInMS)); + } + + void RunLongDelayContentCaptureTask() { + ResetResult(); + platform()->RunForPeriod(base::TimeDelta::FromMilliseconds( + ContentCaptureTask::kTaskLongDelayInMS)); + } + + void RemoveNode(NodeHolder node_holder, Node* node) { + // Remove the node. + node->remove(); + GetContentCaptureManager()->OnLayoutTextWillBeDestroyed(node_holder); + } + + size_t GetExpectedFirstResultSize() { return ContentCaptureTask::kBatchSize; } + + size_t GetExpectedSecondResultSize() { + return node_holders_.size() - GetExpectedFirstResultSize(); + } + + const std::vector<NodeHolder>& NodeHolders() const { return node_holders_; } + const std::vector<Node*> Nodes() const { return nodes_; } + + private: + void ResetResult() { + GetContentCaptureTask()->ResetIsCaptureContentCalled(); + GetContentCaptureClient()->ResetResults(); + } + + // TODO(michaelbai): Remove this once integrate with LayoutText. + void InitNodeHolders() { + std::vector<std::string> ids{"p1", "p2", "p3", "p4", + "p5", "p6", "p7", "p8"}; + for (auto id : ids) { + Node* node = GetElementById(id.c_str())->firstChild(); + CHECK(node); + LayoutObject* layout_object = node->GetLayoutObject(); + CHECK(layout_object); + CHECK(layout_object->IsText()); + nodes_.push_back(node); + node_holders_.push_back(GetContentCaptureManager()->GetNodeHolder(*node)); + } + } + + std::vector<Node*> nodes_; + std::vector<NodeHolder> node_holders_; + Persistent<ContentCaptureClientTestHelper> content_capture_client_; + Persistent<ContentCaptureManagerTestHelper> content_capture_manager_; +}; + +INSTANTIATE_TEST_SUITE_P(, + ContentCaptureTest, + testing::Values(NodeHolder::Type::kID, + NodeHolder::Type::kTextHolder)); + +TEST_P(ContentCaptureTest, Basic) { + RunContentCaptureTask(); + EXPECT_EQ(ContentCaptureTask::TaskState::kStop, + GetContentCaptureTask()->GetTaskStateForTesting()); + EXPECT_FALSE(GetContentCaptureClient()->Data().empty()); + EXPECT_EQ(GetExpectedSecondResultSize(), + GetContentCaptureClient()->Data().size()); +} + +TEST_P(ContentCaptureTest, PauseAndResume) { + // The task stops before captures content. + GetContentCaptureTask()->SetTaskStopState( + ContentCaptureTask::TaskState::kCaptureContent); + RunContentCaptureTask(); + EXPECT_FALSE(GetContentCaptureClient()->FirstData()); + EXPECT_TRUE(GetContentCaptureClient()->Data().empty()); + EXPECT_TRUE(GetContentCaptureClient()->RemovedData().empty()); + EXPECT_FALSE(GetContentCaptureTask()->IsCaptureContentCalled()); + + // The task stops before sends the captured content out. + GetContentCaptureTask()->SetTaskStopState( + ContentCaptureTask::TaskState::kProcessCurrentSession); + RunContentCaptureTask(); + EXPECT_FALSE(GetContentCaptureClient()->FirstData()); + EXPECT_TRUE(GetContentCaptureClient()->Data().empty()); + EXPECT_TRUE(GetContentCaptureClient()->RemovedData().empty()); + EXPECT_TRUE(GetContentCaptureTask()->IsCaptureContentCalled()); + + // The task should be stop at kProcessRetryTask because the captured content + // needs to be sent with 2 batch. + GetContentCaptureTask()->SetTaskStopState( + ContentCaptureTask::TaskState::kProcessRetryTask); + RunContentCaptureTask(); + EXPECT_TRUE(GetContentCaptureClient()->FirstData()); + EXPECT_FALSE(GetContentCaptureClient()->Data().empty()); + EXPECT_TRUE(GetContentCaptureClient()->RemovedData().empty()); + EXPECT_EQ(GetExpectedFirstResultSize(), + GetContentCaptureClient()->Data().size()); + + // Run task until it stops, task will not capture content, because there is no + // content change, so we have 3 NodeHolders. + GetContentCaptureTask()->SetTaskStopState( + ContentCaptureTask::TaskState::kStop); + RunContentCaptureTask(); + EXPECT_FALSE(GetContentCaptureClient()->FirstData()); + EXPECT_FALSE(GetContentCaptureClient()->Data().empty()); + EXPECT_TRUE(GetContentCaptureClient()->RemovedData().empty()); + EXPECT_EQ(GetExpectedSecondResultSize(), + GetContentCaptureClient()->Data().size()); + EXPECT_FALSE(GetContentCaptureTask()->IsCaptureContentCalled()); +} + +TEST_P(ContentCaptureTest, NodeOnlySendOnce) { + // Send all nodes + RunContentCaptureTask(); + EXPECT_FALSE(GetContentCaptureClient()->Data().empty()); + EXPECT_EQ(GetExpectedSecondResultSize(), + GetContentCaptureClient()->Data().size()); + EXPECT_TRUE(GetContentCaptureTask()->IsCaptureContentCalled()); + + GetContentCaptureManager()->OnScrollPositionChanged(); + RunContentCaptureTask(); + EXPECT_TRUE(GetContentCaptureTask()->IsCaptureContentCalled()); + EXPECT_TRUE(GetContentCaptureClient()->Data().empty()); + EXPECT_TRUE(GetContentCaptureClient()->RemovedData().empty()); +} + +TEST_P(ContentCaptureTest, RemoveNodeBeforeSendingOut) { + // Capture the content, but didn't send them. + GetContentCaptureTask()->SetTaskStopState( + ContentCaptureTask::TaskState::kProcessCurrentSession); + RunContentCaptureTask(); + EXPECT_TRUE(GetContentCaptureClient()->Data().empty()); + EXPECT_TRUE(GetContentCaptureTask()->IsCaptureContentCalled()); + + // Remove the node and sent the captured content out. + RemoveNode(NodeHolders().at(0), Nodes().at(0)); + GetContentCaptureTask()->SetTaskStopState( + ContentCaptureTask::TaskState::kProcessRetryTask); + RunContentCaptureTask(); + EXPECT_EQ(GetExpectedFirstResultSize(), + GetContentCaptureClient()->Data().size()); + EXPECT_EQ(0u, GetContentCaptureClient()->RemovedData().size()); + RunContentCaptureTask(); + // Total 7 content returned instead of 8. + EXPECT_EQ(GetExpectedSecondResultSize() - 1, + GetContentCaptureClient()->Data().size()); + EXPECT_EQ(0u, GetContentCaptureClient()->RemovedData().size()); + RunContentCaptureTask(); + // No removed node because it hasn't been sent out. + EXPECT_EQ(0u, GetContentCaptureClient()->Data().size()); + EXPECT_EQ(0u, GetContentCaptureClient()->RemovedData().size()); +} + +TEST_P(ContentCaptureTest, RemoveNodeAfterSendingOut) { + // Captures the content, but didn't send them. + GetContentCaptureTask()->SetTaskStopState( + ContentCaptureTask::TaskState::kProcessCurrentSession); + RunContentCaptureTask(); + EXPECT_TRUE(GetContentCaptureClient()->Data().empty()); + EXPECT_TRUE(GetContentCaptureTask()->IsCaptureContentCalled()); + + // Sends first batch. + GetContentCaptureTask()->SetTaskStopState( + ContentCaptureTask::TaskState::kProcessRetryTask); + RunContentCaptureTask(); + EXPECT_EQ(GetExpectedFirstResultSize(), + GetContentCaptureClient()->Data().size()); + EXPECT_EQ(0u, GetContentCaptureClient()->RemovedData().size()); + + // Sends second batch. + RunContentCaptureTask(); + EXPECT_EQ(GetExpectedSecondResultSize(), + GetContentCaptureClient()->Data().size()); + EXPECT_EQ(0u, GetContentCaptureClient()->RemovedData().size()); + + // Remove the node. + RemoveNode(NodeHolders().at(0), Nodes().at(0)); + RunLongDelayContentCaptureTask(); + EXPECT_EQ(0u, GetContentCaptureClient()->Data().size()); + EXPECT_EQ(1u, GetContentCaptureClient()->RemovedData().size()); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/content_capture/content_holder.cc b/third_party/blink/renderer/core/content_capture/content_holder.cc new file mode 100644 index 0000000..2e455870 --- /dev/null +++ b/third_party/blink/renderer/core/content_capture/content_holder.cc
@@ -0,0 +1,37 @@ +// 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/core/content_capture/content_holder.h" + +#include "third_party/blink/renderer/core/dom/node.h" +#include "third_party/blink/renderer/core/layout/layout_object.h" + +namespace blink { + +ContentHolder::ContentHolder(Node& node) : node_(&node) {} + +ContentHolder::~ContentHolder() {} + +String ContentHolder::GetValue() const { + DCHECK(IsValid()); + if (node_) + return node_->nodeValue(); + return String(); +} + +IntRect ContentHolder::GetBoundingBox() const { + DCHECK(IsValid()); + if (node_ && node_->GetLayoutObject()) + return EnclosedIntRect(node_->GetLayoutObject()->VisualRectInDocument()); + return IntRect(); +} + +uint64_t ContentHolder::GetId() const { + DCHECK(IsValid()); + if (node_) + return reinterpret_cast<uint64_t>(node_.Get()); + return 0; +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/content_capture/content_holder.h b/third_party/blink/renderer/core/content_capture/content_holder.h new file mode 100644 index 0000000..cc0f33cc --- /dev/null +++ b/third_party/blink/renderer/core/content_capture/content_holder.h
@@ -0,0 +1,47 @@ +// 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_CORE_CONTENT_CAPTURE_CONTENT_HOLDER_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_CONTENT_CAPTURE_CONTENT_HOLDER_H_ + +#include "cc/paint/node_holder.h" +#include "cc/paint/text_holder.h" +#include "third_party/blink/renderer/core/core_export.h" +#include "third_party/blink/renderer/platform/geometry/int_rect.h" +#include "third_party/blink/renderer/platform/heap/member.h" +#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" + +namespace blink { + +using NodeHolder = cc::NodeHolder; + +class Node; + +class CORE_EXPORT ContentHolder : public cc::TextHolder { + public: + ContentHolder(Node& node); + ~ContentHolder() override; + + bool IsValid() const { return node_; } + + String GetValue() const; + IntRect GetBoundingBox() const; + uint64_t GetId() const; + + void SetHasSent() { has_sent_ = true; } + bool HasSent() const { return has_sent_; } + + const Node* GetNode() { return node_; } + + void OnNodeDetachedFromLayoutTree() { node_ = nullptr; } + + private: + bool has_sent_ = false; + + UntracedMember<const Node> node_; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CONTENT_CAPTURE_CONTENT_HOLDER_H_
diff --git a/third_party/blink/renderer/core/css/css_font_face_src_value.cc b/third_party/blink/renderer/core/css/css_font_face_src_value.cc index 5499dfe..36b1a21c 100644 --- a/third_party/blink/renderer/core/css/css_font_face_src_value.cc +++ b/third_party/blink/renderer/core/css/css_font_face_src_value.cc
@@ -32,9 +32,9 @@ #include "third_party/blink/renderer/core/dom/node.h" #include "third_party/blink/renderer/core/loader/resource/font_resource.h" #include "third_party/blink/renderer/core/workers/worker_global_scope.h" -#include "third_party/blink/renderer/platform/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/fonts/font_cache.h" #include "third_party/blink/renderer/platform/fonts/font_custom_platform_data.h" +#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
diff --git a/third_party/blink/renderer/core/css/css_image_set_value.h b/third_party/blink/renderer/core/css/css_image_set_value.h index 43b9db23..a4bf9f61 100644 --- a/third_party/blink/renderer/core/css/css_image_set_value.h +++ b/third_party/blink/renderer/core/css/css_image_set_value.h
@@ -28,7 +28,7 @@ #include "third_party/blink/renderer/core/css/css_value_list.h" #include "third_party/blink/renderer/core/css/parser/css_parser_mode.h" -#include "third_party/blink/renderer/platform/cross_origin_attribute_value.h" +#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h" #include "third_party/blink/renderer/platform/weborigin/referrer.h" #include "third_party/blink/renderer/platform/wtf/allocator.h"
diff --git a/third_party/blink/renderer/core/css/css_image_value.cc b/third_party/blink/renderer/core/css/css_image_value.cc index 7627124ae..2009f277 100644 --- a/third_party/blink/renderer/core/css/css_image_value.cc +++ b/third_party/blink/renderer/core/css/css_image_value.cc
@@ -25,7 +25,7 @@ #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/loader/resource/image_resource_content.h" #include "third_party/blink/renderer/core/style/style_fetched_image.h" -#include "third_party/blink/renderer/platform/cross_origin_attribute_value.h" +#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
diff --git a/third_party/blink/renderer/core/css/css_image_value.h b/third_party/blink/renderer/core/css/css_image_value.h index ec7e0cfe..84aa0530 100644 --- a/third_party/blink/renderer/core/css/css_image_value.h +++ b/third_party/blink/renderer/core/css/css_image_value.h
@@ -24,7 +24,7 @@ #include "base/memory/scoped_refptr.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/css/css_value.h" -#include "third_party/blink/renderer/platform/cross_origin_attribute_value.h" +#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h" #include "third_party/blink/renderer/platform/weborigin/referrer.h"
diff --git a/third_party/blink/renderer/core/css/css_properties.json5 b/third_party/blink/renderer/core/css/css_properties.json5 index 6ffc1ab..7c3fc80 100644 --- a/third_party/blink/renderer/core/css/css_properties.json5 +++ b/third_party/blink/renderer/core/css/css_properties.json5
@@ -2788,10 +2788,10 @@ property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"], field_group: "*", field_template: "external", - include_paths: ["third_party/blink/renderer/platform/scroll/scroll_snap_data.h"], - default_value: "ScrollSnapAlign()", + include_paths: ["cc/input/scroll_snap_data.h"], + default_value: "cc::ScrollSnapAlign()", getter: "GetScrollSnapAlign", - type_name: "ScrollSnapAlign", + type_name: "cc::ScrollSnapAlign", converter: "ConvertSnapAlign", keywords: ["none", "start", "end", "center"], typedom_types: ["Keyword"] @@ -2809,10 +2809,10 @@ property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"], field_group: "*", field_template: "external", - include_paths: ["third_party/blink/renderer/platform/scroll/scroll_snap_data.h"], - default_value: "ScrollSnapType()", + include_paths: ["cc/input/scroll_snap_data.h"], + default_value: "cc::ScrollSnapType()", getter: "GetScrollSnapType", - type_name: "ScrollSnapType", + type_name: "cc::ScrollSnapType", converter: "ConvertSnapType", keywords: ["none", "x", "y", "block", "inline", "both", "mandatory", "proximity"], typedom_types: ["Keyword"]
diff --git a/third_party/blink/renderer/core/css/properties/computed_style_utils.cc b/third_party/blink/renderer/core/css/properties/computed_style_utils.cc index 462de37..9ec60f97 100644 --- a/third_party/blink/renderer/core/css/properties/computed_style_utils.cc +++ b/third_party/blink/renderer/core/css/properties/computed_style_utils.cc
@@ -2035,7 +2035,7 @@ } CSSValue* ComputedStyleUtils::ValueForScrollSnapType( - const ScrollSnapType& type, + const cc::ScrollSnapType& type, const ComputedStyle& style) { if (!type.is_none) { return CSSValuePair::Create(CSSIdentifierValue::Create(type.axis), @@ -2046,7 +2046,7 @@ } CSSValue* ComputedStyleUtils::ValueForScrollSnapAlign( - const ScrollSnapAlign& align, + const cc::ScrollSnapAlign& align, const ComputedStyle& style) { return CSSValuePair::Create( CSSIdentifierValue::Create(align.alignment_block),
diff --git a/third_party/blink/renderer/core/css/properties/computed_style_utils.h b/third_party/blink/renderer/core/css/properties/computed_style_utils.h index c4dead78..c656870 100644 --- a/third_party/blink/renderer/core/css/properties/computed_style_utils.h +++ b/third_party/blink/renderer/core/css/properties/computed_style_utils.h
@@ -5,6 +5,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_COMPUTED_STYLE_UTILS_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_COMPUTED_STYLE_UTILS_H_ +#include "cc/input/scroll_snap_data.h" #include "third_party/blink/renderer/core/css/css_border_image_slice_value.h" #include "third_party/blink/renderer/core/css/css_identifier_value.h" #include "third_party/blink/renderer/core/css/css_value_list.h" @@ -164,9 +165,9 @@ bool use_spread); static CSSValue* ValueForFilter(const ComputedStyle&, const FilterOperations&); - static CSSValue* ValueForScrollSnapType(const ScrollSnapType&, + static CSSValue* ValueForScrollSnapType(const cc::ScrollSnapType&, const ComputedStyle&); - static CSSValue* ValueForScrollSnapAlign(const ScrollSnapAlign&, + static CSSValue* ValueForScrollSnapAlign(const cc::ScrollSnapAlign&, const ComputedStyle&); static CSSValue* ValueForPageBreakBetween(EBreakBetween); static CSSValue* ValueForWebkitColumnBreakBetween(EBreakBetween);
diff --git a/third_party/blink/renderer/core/css/resolver/css_variable_resolver.cc b/third_party/blink/renderer/core/css/resolver/css_variable_resolver.cc index 02878a9..42139d63 100644 --- a/third_party/blink/renderer/core/css/resolver/css_variable_resolver.cc +++ b/third_party/blink/renderer/core/css/resolver/css_variable_resolver.cc
@@ -436,8 +436,8 @@ const AtomicString& name) { // If we are in a User Agent Shadow DOM then we should not record metrics. ContainerNode& scope_root = state_.GetTreeScope().RootNode(); - bool is_ua_scope = - scope_root.IsShadowRoot() && ToShadowRoot(scope_root).IsUserAgent(); + auto* shadow_root = DynamicTo<ShadowRoot>(&scope_root); + bool is_ua_scope = shadow_root && shadow_root->IsUserAgent(); return state_.GetDocument() .GetStyleEngine()
diff --git a/third_party/blink/renderer/core/css/resolver/element_style_resources.h b/third_party/blink/renderer/core/css/resolver/element_style_resources.h index 7bed2c5..15d1c997 100644 --- a/third_party/blink/renderer/core/css/resolver/element_style_resources.h +++ b/third_party/blink/renderer/core/css/resolver/element_style_resources.h
@@ -27,9 +27,9 @@ #include "base/macros.h" #include "third_party/blink/renderer/core/css/css_property_id_templates.h" #include "third_party/blink/renderer/core/css/css_property_names.h" -#include "third_party/blink/renderer/platform/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/graphics/color.h" #include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h"
diff --git a/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc b/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc index 1ecd871..e800e87 100644 --- a/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc +++ b/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc
@@ -175,7 +175,7 @@ const TreeScope& tree_scope) { if (tree_scope.RootNode() == tree_scope.GetDocument()) return tree_scope.GetDocument(); - return ToShadowRoot(tree_scope.RootNode()).host(); + return To<ShadowRoot>(tree_scope.RootNode()).host(); } void ScopedStyleResolver::KeyframesRulesAdded(const TreeScope& tree_scope) {
diff --git a/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc b/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc index 6fa4fa64..31d29fd7 100644 --- a/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc +++ b/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc
@@ -29,7 +29,6 @@ #include <algorithm> #include "build/build_config.h" -#include "cc/input/scroll_snap_data.h" #include "third_party/blink/renderer/core/css/basic_shape_functions.h" #include "third_party/blink/renderer/core/css/css_axis_value.h" #include "third_party/blink/renderer/core/css/css_color_value.h" @@ -1498,9 +1497,11 @@ z); } -ScrollSnapType StyleBuilderConverter::ConvertSnapType(StyleResolverState&, - const CSSValue& value) { - ScrollSnapType snapType = ComputedStyleInitialValues::InitialScrollSnapType(); +cc::ScrollSnapType StyleBuilderConverter::ConvertSnapType( + StyleResolverState&, + const CSSValue& value) { + cc::ScrollSnapType snapType = + ComputedStyleInitialValues::InitialScrollSnapType(); if (value.IsValuePair()) { const CSSValuePair& pair = ToCSSValuePair(value); snapType.is_none = false; @@ -1521,9 +1522,10 @@ return snapType; } -ScrollSnapAlign StyleBuilderConverter::ConvertSnapAlign(StyleResolverState&, - const CSSValue& value) { - ScrollSnapAlign snapAlign = +cc::ScrollSnapAlign StyleBuilderConverter::ConvertSnapAlign( + StyleResolverState&, + const CSSValue& value) { + cc::ScrollSnapAlign snapAlign = ComputedStyleInitialValues::InitialScrollSnapAlign(); if (value.IsValuePair()) { const CSSValuePair& pair = ToCSSValuePair(value);
diff --git a/third_party/blink/renderer/core/css/resolver/style_builder_converter.h b/third_party/blink/renderer/core/css/resolver/style_builder_converter.h index bbfbfaf..2c4be91 100644 --- a/third_party/blink/renderer/core/css/resolver/style_builder_converter.h +++ b/third_party/blink/renderer/core/css/resolver/style_builder_converter.h
@@ -27,6 +27,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_BUILDER_CONVERTER_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_BUILDER_CONVERTER_H_ +#include "cc/input/scroll_snap_data.h" #include "third_party/blink/renderer/core/css/css_function_value.h" #include "third_party/blink/renderer/core/css/css_identifier_value.h" #include "third_party/blink/renderer/core/css/css_primitive_value.h" @@ -231,8 +232,10 @@ const OrderedNamedGridLines&, NamedGridLinesMap&); - static ScrollSnapType ConvertSnapType(StyleResolverState&, const CSSValue&); - static ScrollSnapAlign ConvertSnapAlign(StyleResolverState&, const CSSValue&); + static cc::ScrollSnapType ConvertSnapType(StyleResolverState&, + const CSSValue&); + static cc::ScrollSnapAlign ConvertSnapAlign(StyleResolverState&, + const CSSValue&); static scoped_refptr<TranslateTransformOperation> ConvertTranslate( StyleResolverState&, const CSSValue&);
diff --git a/third_party/blink/renderer/core/css/selector_checker.cc b/third_party/blink/renderer/core/css/selector_checker.cc index c45c40e..d71eaf07 100644 --- a/third_party/blink/renderer/core/css/selector_checker.cc +++ b/third_party/blink/renderer/core/css/selector_checker.cc
@@ -283,8 +283,8 @@ } static inline bool IsV0ShadowRoot(const Node* node) { - return node && node->IsShadowRoot() && - ToShadowRoot(node)->GetType() == ShadowRootType::V0; + auto* shadow_root = DynamicTo<ShadowRoot>(node); + return shadow_root && shadow_root->GetType() == ShadowRootType::V0; } SelectorChecker::MatchStatus SelectorChecker::MatchForPseudoShadow( @@ -299,8 +299,8 @@ } static inline Element* ParentOrV0ShadowHostElement(const Element& element) { - if (element.parentNode() && element.parentNode()->IsShadowRoot()) { - if (ToShadowRoot(element.parentNode())->GetType() != ShadowRootType::V0) + if (auto* shadow_root = DynamicTo<ShadowRoot>(element.parentNode())) { + if (shadow_root->GetType() != ShadowRootType::V0) return nullptr; } return element.ParentOrShadowHostElement(); @@ -1065,8 +1065,8 @@ return false; if (context.scope == &element.GetDocument()) return element == element.GetDocument().documentElement(); - if (context.scope->IsShadowRoot()) - return element == ToShadowRoot(context.scope)->host(); + if (auto* shadow_root = DynamicTo<ShadowRoot>(context.scope.Get())) + return element == shadow_root->host(); return context.scope == &element; case CSSSelector::kPseudoUnresolved: return !element.IsDefined() && element.IsUnresolvedV0CustomElement();
diff --git a/third_party/blink/renderer/core/css/style_engine.cc b/third_party/blink/renderer/core/css/style_engine.cc index a08682a9..f8613fc 100644 --- a/third_party/blink/renderer/core/css/style_engine.cc +++ b/third_party/blink/renderer/core/css/style_engine.cc
@@ -115,7 +115,7 @@ if (result.is_new_entry) { result.stored_value->value = MakeGarbageCollected<ShadowTreeStyleSheetCollection>( - ToShadowRoot(tree_scope)); + To<ShadowRoot>(tree_scope)); } return *result.stored_value->value.Get(); } @@ -271,7 +271,7 @@ shadow_root = insertion_point.ContainingShadowRoot(); TreeScope& tree_scope = - shadow_root ? *ToTreeScope(shadow_root) : GetDocument(); + shadow_root ? *To<TreeScope>(shadow_root) : GetDocument(); TreeScopeStyleSheetCollection* collection = StyleSheetCollectionFor(tree_scope); // After detaching document, collection could be null. In the case, @@ -1102,10 +1102,11 @@ pending_invalidations_.ScheduleInvalidationSetsForNode(invalidation_lists, node); - if (!node.IsShadowRoot()) + auto* shadow_root = DynamicTo<ShadowRoot>(node); + if (!shadow_root) return; - Element& host = ToShadowRoot(node).host(); + Element& host = shadow_root->host(); if (host.NeedsStyleRecalc()) return; @@ -1168,8 +1169,8 @@ ScheduleTypeRuleSetInvalidations(tree_scope.RootNode(), rule_sets); bool invalidate_slotted = false; - if (tree_scope.RootNode().IsShadowRoot()) { - Element& host = ToShadowRoot(tree_scope.RootNode()).host(); + if (auto* shadow_root = DynamicTo<ShadowRoot>(&tree_scope.RootNode())) { + Element& host = shadow_root->host(); ScheduleRuleSetInvalidationsForElement(host, rule_sets); if (host.GetStyleChangeType() >= kSubtreeStyleChange) return;
diff --git a/third_party/blink/renderer/core/css/style_invalidation_root.cc b/third_party/blink/renderer/core/css/style_invalidation_root.cc index e5b3711..798ed798 100644 --- a/third_party/blink/renderer/core/css/style_invalidation_root.cc +++ b/third_party/blink/renderer/core/css/style_invalidation_root.cc
@@ -12,8 +12,8 @@ Element* StyleInvalidationRoot::RootElement() const { Node* root_node = GetRootNode(); DCHECK(root_node); - if (root_node->IsShadowRoot()) - return &ToShadowRoot(root_node)->host(); + if (auto* shadow_root = DynamicTo<ShadowRoot>(root_node)) + return &shadow_root->host(); if (root_node->IsDocumentNode()) return root_node->GetDocument().documentElement(); return ToElement(root_node);
diff --git a/third_party/blink/renderer/core/css/style_recalc_root.cc b/third_party/blink/renderer/core/css/style_recalc_root.cc index d490428..8c88771 100644 --- a/third_party/blink/renderer/core/css/style_recalc_root.cc +++ b/third_party/blink/renderer/core/css/style_recalc_root.cc
@@ -27,7 +27,7 @@ TreeScope* tree_scope = &root_node->GetTreeScope(); while (!tree_scope->ParentTreeScope()->RootNode().IsDocumentNode()) tree_scope = tree_scope->ParentTreeScope(); - return ToShadowRoot(tree_scope->RootNode()).host(); + return To<ShadowRoot>(tree_scope->RootNode()).host(); } if (root_node->IsTextNode()) return *root_node->parentElement();
diff --git a/third_party/blink/renderer/core/dom/document.cc b/third_party/blink/renderer/core/dom/document.cc index 54df489..b952a323 100644 --- a/third_party/blink/renderer/core/dom/document.cc +++ b/third_party/blink/renderer/core/dom/document.cc
@@ -34,6 +34,7 @@ #include "base/auto_reset.h" #include "base/macros.h" #include "base/optional.h" +#include "cc/input/scroll_snap_data.h" #include "services/metrics/public/cpp/mojo_ukm_recorder.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_source_id.h" @@ -2055,7 +2056,7 @@ // propagate it too. GapLength column_gap = overflow_style->ColumnGap(); - ScrollSnapType snap_type = overflow_style->GetScrollSnapType(); + cc::ScrollSnapType snap_type = overflow_style->GetScrollSnapType(); ScrollBehavior scroll_behavior = document_element_style->GetScrollBehavior(); EOverscrollBehavior overscroll_behavior_x =
diff --git a/third_party/blink/renderer/core/dom/dom_implementation.cc b/third_party/blink/renderer/core/dom/dom_implementation.cc index 31d7915..cfaba79 100644 --- a/third_party/blink/renderer/core/dom/dom_implementation.cc +++ b/third_party/blink/renderer/core/dom/dom_implementation.cc
@@ -258,8 +258,10 @@ // We do not want QuickTime to take over all image types, obviously. if ((type == "application/pdf" || type == "text/pdf") && plugin_data && plugin_data->SupportsMimeType(type)) { - return PluginDocument::Create( - init, plugin_data->PluginBackgroundColorForMimeType(type)); + return RuntimeEnabledFeatures::MimeHandlerViewInCrossProcessFrameEnabled() + ? HTMLDocument::Create(init) + : PluginDocument::Create( + init, plugin_data->PluginBackgroundColorForMimeType(type)); } // multipart/x-mixed-replace is only supported for images. if (MIMETypeRegistry::IsSupportedImageResourceMIMEType(type) ||
diff --git a/third_party/blink/renderer/core/dom/element.cc b/third_party/blink/renderer/core/dom/element.cc index ea5a44c..2c19cf3 100644 --- a/third_party/blink/renderer/core/dom/element.cc +++ b/third_party/blink/renderer/core/dom/element.cc
@@ -28,6 +28,7 @@ #include <memory> +#include "cc/input/scroll_snap_data.h" #include "third_party/blink/public/platform/web_scroll_into_view_params.h" #include "third_party/blink/renderer/bindings/core/v8/dictionary.h" #include "third_party/blink/renderer/bindings/core/v8/scroll_into_view_options_or_boolean.h" @@ -827,8 +828,8 @@ FloatPoint end_point(new_left * box->Style()->EffectiveZoom(), box->ScrollTop().ToFloat()); - std::unique_ptr<SnapSelectionStrategy> strategy = - SnapSelectionStrategy::CreateForEndPosition( + std::unique_ptr<cc::SnapSelectionStrategy> strategy = + cc::SnapSelectionStrategy::CreateForEndPosition( gfx::ScrollOffset(end_point), true, false); end_point = GetDocument() .GetSnapCoordinator() @@ -859,8 +860,8 @@ FloatPoint end_point(box->ScrollLeft().ToFloat(), new_top * box->Style()->EffectiveZoom()); - std::unique_ptr<SnapSelectionStrategy> strategy = - SnapSelectionStrategy::CreateForEndPosition( + std::unique_ptr<cc::SnapSelectionStrategy> strategy = + cc::SnapSelectionStrategy::CreateForEndPosition( gfx::ScrollOffset(end_point), false, true); end_point = GetDocument() .GetSnapCoordinator() @@ -980,9 +981,9 @@ gfx::ScrollOffset new_offset(current_position + displacement); FloatPoint new_position(new_offset.x(), new_offset.y()); - std::unique_ptr<SnapSelectionStrategy> strategy = - SnapSelectionStrategy::CreateForEndAndDirection(current_position, - displacement); + std::unique_ptr<cc::SnapSelectionStrategy> strategy = + cc::SnapSelectionStrategy::CreateForEndAndDirection(current_position, + displacement); new_position = GetDocument() .GetSnapCoordinator() ->GetSnapPosition(*box, *strategy) @@ -1011,8 +1012,8 @@ box->Style()->EffectiveZoom()); } - std::unique_ptr<SnapSelectionStrategy> strategy = - SnapSelectionStrategy::CreateForEndPosition( + std::unique_ptr<cc::SnapSelectionStrategy> strategy = + cc::SnapSelectionStrategy::CreateForEndPosition( gfx::ScrollOffset(new_position), scroll_to_options->hasLeft(), scroll_to_options->hasTop()); new_position = GetDocument() @@ -1050,9 +1051,9 @@ FloatPoint(displacement.x(), displacement.y()); gfx::ScrollOffset current_position(viewport->ScrollPosition()); - std::unique_ptr<SnapSelectionStrategy> strategy = - SnapSelectionStrategy::CreateForEndAndDirection(current_position, - displacement); + std::unique_ptr<cc::SnapSelectionStrategy> strategy = + cc::SnapSelectionStrategy::CreateForEndAndDirection(current_position, + displacement); new_position = GetDocument() .GetSnapCoordinator() @@ -1087,8 +1088,8 @@ } FloatPoint new_position = viewport->ScrollOffsetToPosition(new_offset); - std::unique_ptr<SnapSelectionStrategy> strategy = - SnapSelectionStrategy::CreateForEndPosition( + std::unique_ptr<cc::SnapSelectionStrategy> strategy = + cc::SnapSelectionStrategy::CreateForEndPosition( gfx::ScrollOffset(new_position), scroll_to_options->hasLeft(), scroll_to_options->hasTop()); new_position = @@ -2199,16 +2200,6 @@ element_animations->UpdateAnimationFlags(*style); } - if (style->HasTransform()) { - if (const CSSPropertyValueSet* inline_style = InlineStyle()) { - style->SetHasInlineTransform( - inline_style->HasProperty(CSSPropertyTransform) || - inline_style->HasProperty(CSSPropertyTranslate) || - inline_style->HasProperty(CSSPropertyRotate) || - inline_style->HasProperty(CSSPropertyScale)); - } - } - style->UpdateIsStackingContext(this == GetDocument().documentElement(), IsInTopLayer(), IsSVGForeignObjectElement(*this));
diff --git a/third_party/blink/renderer/core/dom/events/event_path.cc b/third_party/blink/renderer/core/dom/events/event_path.cc index d5bc6014..302ceab 100644 --- a/third_party/blink/renderer/core/dom/events/event_path.cc +++ b/third_party/blink/renderer/core/dom/events/event_path.cc
@@ -118,9 +118,8 @@ continue; } } - if (current->IsShadowRoot()) { - if (event_ && - ShouldStopAtShadowRoot(*event_, *ToShadowRoot(current), *node_)) + if (auto* shadow_root = DynamicTo<ShadowRoot>(current)) { + if (event_ && ShouldStopAtShadowRoot(*event_, *shadow_root, *node_)) break; current = current->OwnerShadowHost(); nodes_in_path.push_back(current);
diff --git a/third_party/blink/renderer/core/dom/events/tree_scope_event_context.cc b/third_party/blink/renderer/core/dom/events/tree_scope_event_context.cc index 5d9e768..7af87ee 100644 --- a/third_party/blink/renderer/core/dom/events/tree_scope_event_context.cc +++ b/third_party/blink/renderer/core/dom/events/tree_scope_event_context.cc
@@ -110,8 +110,9 @@ int order_number, TreeScopeEventContext* nearest_ancestor_closed_tree_scope_event_context) { pre_order_ = order_number; + auto* shadow_root = DynamicTo<ShadowRoot>(&RootNode()); containing_closed_shadow_tree_ = - (RootNode().IsShadowRoot() && !ToShadowRoot(RootNode()).IsOpenOrV0()) + (shadow_root && !shadow_root->IsOpenOrV0()) ? this : nearest_ancestor_closed_tree_scope_event_context; for (const auto& context : children_) {
diff --git a/third_party/blink/renderer/core/dom/flat_tree_traversal.cc b/third_party/blink/renderer/core/dom/flat_tree_traversal.cc index 27505913..a1e7bf9 100644 --- a/third_party/blink/renderer/core/dom/flat_tree_traversal.cc +++ b/third_party/blink/renderer/core/dom/flat_tree_traversal.cc
@@ -212,9 +212,9 @@ ContainerNode* parent = node.parentNode(); if (!parent) return nullptr; - if (!parent->IsShadowRoot()) + auto* shadow_root = DynamicTo<ShadowRoot>(parent); + if (!shadow_root) return parent; - ShadowRoot* shadow_root = ToShadowRoot(parent); return &shadow_root->host(); }
diff --git a/third_party/blink/renderer/core/dom/node.cc b/third_party/blink/renderer/core/dom/node.cc index 1233980..50815259 100644 --- a/third_party/blink/renderer/core/dom/node.cc +++ b/third_party/blink/renderer/core/dom/node.cc
@@ -984,7 +984,8 @@ const TreeScope* scope = &GetTreeScope(); for (; scope->ParentTreeScope(); scope = scope->ParentTreeScope()) { const ContainerNode& root = scope->RootNode(); - if (root.IsShadowRoot() && !ToShadowRoot(root).IsOpenOrV0()) + auto* shadow_root = DynamicTo<ShadowRoot>(root); + if (shadow_root && !shadow_root->IsOpenOrV0()) break; } @@ -1558,7 +1559,7 @@ ShadowRoot* Node::ContainingShadowRoot() const { Node& root = GetTreeScope().RootNode(); - return root.IsShadowRoot() ? ToShadowRoot(&root) : nullptr; + return DynamicTo<ShadowRoot>(root); } Node* Node::NonBoundaryShadowTreeRootNode() { @@ -1585,8 +1586,8 @@ if (!parent) return nullptr; - if (parent->IsShadowRoot()) - return &ToShadowRoot(parent)->host(); + if (auto* shadow_root = DynamicTo<ShadowRoot>(parent)) + return &shadow_root->host(); if (!parent->IsElementNode()) return nullptr; @@ -2064,11 +2065,11 @@ String Node::ToString() const { if (getNodeType() == Node::kProcessingInstructionNode) return "?" + nodeName(); - if (IsShadowRoot()) { + if (auto* shadow_root = DynamicTo<ShadowRoot>(this)) { // nodeName of ShadowRoot is #document-fragment. It's confused with // DocumentFragment. std::stringstream shadow_root_type; - shadow_root_type << ToShadowRoot(this)->GetType(); + shadow_root_type << shadow_root->GetType(); String shadow_root_type_str(shadow_root_type.str().c_str()); return "#shadow-root(" + shadow_root_type_str + ")"; }
diff --git a/third_party/blink/renderer/core/dom/node.h b/third_party/blink/renderer/core/dom/node.h index 1c39afe..c6c64c3 100644 --- a/third_party/blink/renderer/core/dom/node.h +++ b/third_party/blink/renderer/core/dom/node.h
@@ -308,6 +308,7 @@ virtual bool IsMediaControlElement() const { return false; } virtual bool IsMediaControls() const { return false; } + virtual bool IsMediaElement() const { return false; } virtual bool IsTextTrackContainer() const { return false; } virtual bool IsVTTElement() const { return false; } virtual bool IsAttributeNode() const { return false; }
diff --git a/third_party/blink/renderer/core/dom/shadow_root.h b/third_party/blink/renderer/core/dom/shadow_root.h index 71323d7..c507569 100644 --- a/third_party/blink/renderer/core/dom/shadow_root.h +++ b/third_party/blink/renderer/core/dom/shadow_root.h
@@ -36,6 +36,7 @@ #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable_visitor.h" #include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h" +#include "third_party/blink/renderer/platform/wtf/casting.h" namespace blink { @@ -234,13 +235,19 @@ return *shadow_root_v0_; } -DEFINE_NODE_TYPE_CASTS(ShadowRoot, IsShadowRoot()); -DEFINE_TYPE_CASTS(ShadowRoot, - TreeScope, - treeScope, - treeScope->RootNode().IsShadowRoot(), - treeScope.RootNode().IsShadowRoot()); -DEFINE_TYPE_CASTS(TreeScope, ShadowRoot, shadowRoot, true, true); +template <> +struct DowncastTraits<ShadowRoot> { + static bool AllowFrom(const Node& node) { return node.IsShadowRoot(); } + + static bool AllowFrom(const TreeScope& tree_scope) { + return tree_scope.RootNode().IsShadowRoot(); + } +}; + +template <> +struct DowncastTraits<TreeScope> { + static bool AllowFrom(const ShadowRoot& shadow_root) { return true; } +}; CORE_EXPORT std::ostream& operator<<(std::ostream&, const ShadowRootType&);
diff --git a/third_party/blink/renderer/core/dom/tree_scope.cc b/third_party/blink/renderer/core/dom/tree_scope.cc index 1f5d8b6a..657ea7d 100644 --- a/third_party/blink/renderer/core/dom/tree_scope.cc +++ b/third_party/blink/renderer/core/dom/tree_scope.cc
@@ -452,7 +452,7 @@ return const_cast<Element*>(&target); Node& first_different_scope_root = (*target_ancestor_riterator).Get()->RootNode(); - return &ToShadowRoot(first_different_scope_root).host(); + return &To<ShadowRoot>(first_different_scope_root).host(); } Element* TreeScope::AdjustedFocusedElementInternal(
diff --git a/third_party/blink/renderer/core/dom/tree_scope_adopter.cc b/third_party/blink/renderer/core/dom/tree_scope_adopter.cc index 7b27e50..be34678 100644 --- a/third_party/blink/renderer/core/dom/tree_scope_adopter.cc +++ b/third_party/blink/renderer/core/dom/tree_scope_adopter.cc
@@ -168,8 +168,8 @@ new_document); } - if (node.IsShadowRoot()) - ToShadowRoot(node).SetDocument(new_document); + if (auto* shadow_root = DynamicTo<ShadowRoot>(node)) + shadow_root->SetDocument(new_document); #if DCHECK_IS_ON() g_did_move_to_new_document_was_called = false;
diff --git a/third_party/blink/renderer/core/editing/editor.cc b/third_party/blink/renderer/core/editing/editor.cc index a2b01c8..103c496 100644 --- a/third_party/blink/renderer/core/editing/editor.cc +++ b/third_party/blink/renderer/core/editing/editor.cc
@@ -506,7 +506,7 @@ LocalFrame* focused_or_main_frame = ToLocalFrame(page->GetFocusController().FocusedOrMainFrame()); focused_or_main_frame->Selection().RevealSelection( - ScrollAlignment::kAlignCenterIfNeeded); + ScrollAlignment::kAlignToEdgeIfNeeded); } } @@ -519,13 +519,10 @@ VisiblePosition caret = GetFrameSelection().ComputeVisibleSelectionInDOMTree().VisibleStart(); - bool align_to_edge = IsEndOfEditableOrNonEditableContent(caret); DCHECK(GetFrame().GetDocument()); if (!TypingCommand::InsertLineBreak(*GetFrame().GetDocument())) return false; - RevealSelectionAfterEditingOperation( - align_to_edge ? ScrollAlignment::kAlignToEdgeIfNeeded - : ScrollAlignment::kAlignCenterIfNeeded); + RevealSelectionAfterEditingOperation(ScrollAlignment::kAlignToEdgeIfNeeded); return true; } @@ -539,14 +536,11 @@ VisiblePosition caret = GetFrameSelection().ComputeVisibleSelectionInDOMTree().VisibleStart(); - bool align_to_edge = IsEndOfEditableOrNonEditableContent(caret); DCHECK(GetFrame().GetDocument()); EditingState editing_state; if (!TypingCommand::InsertParagraphSeparator(*GetFrame().GetDocument())) return false; - RevealSelectionAfterEditingOperation( - align_to_edge ? ScrollAlignment::kAlignToEdgeIfNeeded - : ScrollAlignment::kAlignCenterIfNeeded); + RevealSelectionAfterEditingOperation(ScrollAlignment::kAlignToEdgeIfNeeded); return true; }
diff --git a/third_party/blink/renderer/core/editing/editor.h b/third_party/blink/renderer/core/editing/editor.h index 7780440..f3fde3c 100644 --- a/third_party/blink/renderer/core/editing/editor.h +++ b/third_party/blink/renderer/core/editing/editor.h
@@ -226,7 +226,7 @@ void Trace(blink::Visitor*); void RevealSelectionAfterEditingOperation( - const ScrollAlignment& = ScrollAlignment::kAlignCenterIfNeeded); + const ScrollAlignment& = ScrollAlignment::kAlignToEdgeIfNeeded); private: Member<LocalFrame> frame_;
diff --git a/third_party/blink/renderer/core/editing/finder/find_buffer.cc b/third_party/blink/renderer/core/editing/finder/find_buffer.cc index 5cb2d8e0..3d9a42a 100644 --- a/third_party/blink/renderer/core/editing/finder/find_buffer.cc +++ b/third_party/blink/renderer/core/editing/finder/find_buffer.cc
@@ -301,7 +301,8 @@ } // Move the node so we wouldn't encounter this node or its descendants // later. - buffer_.push_back(kObjectReplacementCharacter); + if (!IsHTMLWBRElement(ToHTMLElement(*node))) + buffer_.push_back(kObjectReplacementCharacter); node = FlatTreeTraversal::NextSkippingChildren(*node); continue; }
diff --git a/third_party/blink/renderer/core/editing/finder/find_buffer_test.cc b/third_party/blink/renderer/core/editing/finder/find_buffer_test.cc index 59cdd434..7f41a0e3 100644 --- a/third_party/blink/renderer/core/editing/finder/find_buffer_test.cc +++ b/third_party/blink/renderer/core/editing/finder/find_buffer_test.cc
@@ -610,4 +610,18 @@ EXPECT_EQ(FindBuffer::BufferMatchResult({0, 4}), results->front()); } +TEST_F(FindBufferTest, WBRTest) { + SetBodyContent("fi<wbr>nd and fin<wbr>d"); + FindBuffer buffer(WholeDocumentRange()); + const auto results = buffer.FindMatches("find", 0); + ASSERT_EQ(2u, results->CountForTesting()); +} + +TEST_F(FindBufferTest, InputTest) { + SetBodyContent("fi<input type='text'>nd and fin<input type='text'>d"); + FindBuffer buffer(WholeDocumentRange()); + const auto results = buffer.FindMatches("find", 0); + ASSERT_EQ(0u, results->CountForTesting()); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/editing/finder/find_task_controller.cc b/third_party/blink/renderer/core/editing/finder/find_task_controller.cc index 9d66cc1..80b67e7 100644 --- a/third_party/blink/renderer/core/editing/finder/find_task_controller.cc +++ b/third_party/blink/renderer/core/editing/finder/find_task_controller.cc
@@ -301,4 +301,8 @@ visitor->Trace(resume_finding_from_range_); } +void FindTaskController::ResetLastFindRequestCompletedWithNoMatches() { + last_find_request_completed_with_no_matches_ = false; +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/editing/finder/find_task_controller.h b/third_party/blink/renderer/core/editing/finder/find_task_controller.h index 1b99f852..327d0348 100644 --- a/third_party/blink/renderer/core/editing/finder/find_task_controller.h +++ b/third_party/blink/renderer/core/editing/finder/find_task_controller.h
@@ -76,6 +76,8 @@ void Trace(Visitor* visitor); + void ResetLastFindRequestCompletedWithNoMatches(); + private: void RequestIdleFindTask(int identifier, const WebString& search_text,
diff --git a/third_party/blink/renderer/core/editing/finder/text_finder.cc b/third_party/blink/renderer/core/editing/finder/text_finder.cc index 2f29bab9..4463625 100644 --- a/third_party/blink/renderer/core/editing/finder/text_finder.cc +++ b/third_party/blink/renderer/core/editing/finder/text_finder.cc
@@ -206,7 +206,7 @@ } // We found something, so the result of the previous scoping may be outdated. - last_find_request_completed_with_no_matches_ = false; + find_task_controller_->ResetLastFindRequestCompletedWithNoMatches(); return true; } @@ -661,7 +661,6 @@ find_match_markers_version_(0), should_locate_active_rect_(false), scoping_in_progress_(false), - last_find_request_completed_with_no_matches_(false), find_match_rects_are_valid_(false) {} TextFinder::~TextFinder() = default;
diff --git a/third_party/blink/renderer/core/editing/finder/text_finder.h b/third_party/blink/renderer/core/editing/finder/text_finder.h index a3a330c..06a3bbc 100644 --- a/third_party/blink/renderer/core/editing/finder/text_finder.h +++ b/third_party/blink/renderer/core/editing/finder/text_finder.h
@@ -240,10 +240,6 @@ // Keeps track of whether there is an scoping effort ongoing in the frame. bool scoping_in_progress_; - // Keeps track of whether the last find request completed its scoping effort - // without finding any matches in this frame. - bool last_find_request_completed_with_no_matches_; - // Determines if the rects in the find-in-page matches cache of this frame // are invalid and should be recomputed. bool find_match_rects_are_valid_;
diff --git a/third_party/blink/renderer/core/editing/iterators/text_iterator.cc b/third_party/blink/renderer/core/editing/iterators/text_iterator.cc index 5f82f479..fe63db5 100644 --- a/third_party/blink/renderer/core/editing/iterators/text_iterator.cc +++ b/third_party/blink/renderer/core/editing/iterators/text_iterator.cc
@@ -85,7 +85,7 @@ // |node| is neither a shadow root nor the owner of a layout object. static bool NotSkipping(const Node& node) { return node.GetLayoutObject() || HasDisplayContents(node) || - (node.IsShadowRoot() && node.OwnerShadowHost()->GetLayoutObject()); + (IsA<ShadowRoot>(node) && node.OwnerShadowHost()->GetLayoutObject()); } template <typename Strategy> @@ -311,13 +311,13 @@ LayoutObject* layout_object = node_->GetLayoutObject(); if (!layout_object) { - if (node_->IsShadowRoot() || HasDisplayContents(*node_)) { + if (IsA<ShadowRoot>(node_.Get()) || HasDisplayContents(*node_)) { // Shadow roots or display: contents elements don't have LayoutObjects, // but we want to visit children anyway. iteration_progress_ = iteration_progress_ < kHandledNode ? kHandledNode : iteration_progress_; - handle_shadow_root_ = node_->IsShadowRoot(); + handle_shadow_root_ = IsA<ShadowRoot>(node_.Get()); } else { iteration_progress_ = kHandledChildren; } @@ -421,12 +421,12 @@ // 4. Reached the top of a shadow root. If it's created by author, // then try to visit the next // sibling shadow root, if any. - if (!node_->IsShadowRoot()) { + const auto* shadow_root = DynamicTo<ShadowRoot>(node_.Get()); + if (!shadow_root) { NOTREACHED(); should_stop_ = true; return; } - const ShadowRoot* shadow_root = ToShadowRoot(node_); if (shadow_root->GetType() == ShadowRootType::V0 || shadow_root->GetType() == ShadowRootType::kOpen) { // We are the shadow root; exit from here and go back to
diff --git a/third_party/blink/renderer/core/editing/visible_units_line_test.cc b/third_party/blink/renderer/core/editing/visible_units_line_test.cc index 62b6fe4a..0190437 100644 --- a/third_party/blink/renderer/core/editing/visible_units_line_test.cc +++ b/third_party/blink/renderer/core/editing/visible_units_line_test.cc
@@ -64,6 +64,10 @@ ::testing::Bool()); TEST_F(VisibleUnitsLineTest, endOfLine) { + // TODO(crbug.com/922407): This test fails with LayoutNG. + if (RuntimeEnabledFeatures::LayoutNGEnabled()) + return; + const char* body_content = "<a id=host><b id=one>11</b><b id=two>22</b></a><i id=three>333</i><i " "id=four>4444</i><br>"; @@ -149,6 +153,10 @@ } TEST_F(VisibleUnitsLineTest, isEndOfLine) { + // TODO(crbug.com/922407): This test fails with LayoutNG. + if (RuntimeEnabledFeatures::LayoutNGEnabled()) + return; + const char* body_content = "<a id=host><b id=one>11</b><b id=two>22</b></a><i id=three>333</i><i " "id=four>4444</i><br>"; @@ -193,6 +201,10 @@ } TEST_F(VisibleUnitsLineTest, isLogicalEndOfLine) { + // TODO(crbug.com/922407): This test fails with LayoutNG. + if (RuntimeEnabledFeatures::LayoutNGEnabled()) + return; + const char* body_content = "<a id=host><b id=one>11</b><b id=two>22</b></a><i id=three>333</i><i " "id=four>4444</i><br>"; @@ -301,6 +313,10 @@ } TEST_F(VisibleUnitsLineTest, isStartOfLine) { + // TODO(crbug.com/922407): This test fails with LayoutNG. + if (RuntimeEnabledFeatures::LayoutNGEnabled()) + return; + const char* body_content = "<a id=host><b id=one>11</b><b id=two>22</b></a><i id=three>333</i><i " "id=four>4444</i><br>"; @@ -345,6 +361,10 @@ } TEST_F(VisibleUnitsLineTest, logicalEndOfLine) { + // TODO(crbug.com/922407): This test fails with LayoutNG. + if (RuntimeEnabledFeatures::LayoutNGEnabled()) + return; + const char* body_content = "<a id=host><b id=one>11</b><b id=two>22</b></a><i id=three>333</i><i " "id=four>4444</i><br>"; @@ -430,6 +450,10 @@ } TEST_F(VisibleUnitsLineTest, logicalStartOfLine) { + // TODO(crbug.com/922407): This test fails with LayoutNG. + if (RuntimeEnabledFeatures::LayoutNGEnabled()) + return; + const char* body_content = "<a id=host><b id=one>11</b><b id=two>22</b></a><i id=three>333</i><i " "id=four>4444</i><br>"; @@ -515,6 +539,10 @@ } TEST_F(VisibleUnitsLineTest, startOfLine) { + // TODO(crbug.com/922407): This test fails with LayoutNG. + if (RuntimeEnabledFeatures::LayoutNGEnabled()) + return; + const char* body_content = "<a id=host><b id=one>11</b><b id=two>22</b></a><i id=three>333</i><i " "id=four>4444</i><br>";
diff --git a/third_party/blink/renderer/core/execution_context/context_lifecycle_observer.cc b/third_party/blink/renderer/core/execution_context/context_lifecycle_observer.cc index b7ae0b0..716c084 100644 --- a/third_party/blink/renderer/core/execution_context/context_lifecycle_observer.cc +++ b/third_party/blink/renderer/core/execution_context/context_lifecycle_observer.cc
@@ -18,7 +18,7 @@ ExecutionContext* ContextClient::GetExecutionContext() const { return execution_context_ && !execution_context_->IsContextDestroyed() - ? execution_context_ + ? execution_context_.Get() : nullptr; }
diff --git a/third_party/blink/renderer/core/exported/web_frame_serializer.cc b/third_party/blink/renderer/core/exported/web_frame_serializer.cc index c97eeab..4f1161d 100644 --- a/third_party/blink/renderer/core/exported/web_frame_serializer.cc +++ b/third_party/blink/renderer/core/exported/web_frame_serializer.cc
@@ -70,7 +70,7 @@ #include "third_party/blink/renderer/platform/loader/fetch/resource_response.h" #include "third_party/blink/renderer/platform/mhtml/mhtml_archive.h" #include "third_party/blink/renderer/platform/mhtml/mhtml_parser.h" -#include "third_party/blink/renderer/platform/serialized_resource.h" +#include "third_party/blink/renderer/platform/mhtml/serialized_resource.h" #include "third_party/blink/renderer/platform/shared_buffer.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/wtf/assertions.h"
diff --git a/third_party/blink/renderer/core/exported/web_frame_test.cc b/third_party/blink/renderer/core/exported/web_frame_test.cc index 87d0dccc..a183152 100644 --- a/third_party/blink/renderer/core/exported/web_frame_test.cc +++ b/third_party/blink/renderer/core/exported/web_frame_test.cc
@@ -132,6 +132,7 @@ #include "third_party/blink/renderer/core/loader/document_loader.h" #include "third_party/blink/renderer/core/loader/frame_load_request.h" #include "third_party/blink/renderer/core/page/chrome_client.h" +#include "third_party/blink/renderer/core/page/drag_image.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/core/page/scoped_page_pauser.h" #include "third_party/blink/renderer/core/page/scrolling/top_document_root_scroller_controller.h" @@ -146,7 +147,6 @@ #include "third_party/blink/renderer/core/trustedtypes/trusted_url.h" #include "third_party/blink/renderer/platform/bindings/microtask.h" #include "third_party/blink/renderer/platform/cursor.h" -#include "third_party/blink/renderer/platform/drag_image.h" #include "third_party/blink/renderer/platform/exported/wrapped_resource_request.h" #include "third_party/blink/renderer/platform/graphics/graphics_layer.h" #include "third_party/blink/renderer/platform/keyboard_codes.h"
diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc index 4321830..d7a9c05 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.cc +++ b/third_party/blink/renderer/core/exported/web_view_impl.cc
@@ -147,8 +147,6 @@ #include "third_party/blink/renderer/core/timing/window_performance.h" #include "third_party/blink/renderer/platform/cursor.h" #include "third_party/blink/renderer/platform/fonts/font_cache.h" -#include "third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.h" -#include "third_party/blink/renderer/platform/graphics/compositor_mutator_client.h" #include "third_party/blink/renderer/platform/graphics/gpu/drawing_buffer.h" #include "third_party/blink/renderer/platform/graphics/image.h" #include "third_party/blink/renderer/platform/histogram.h" @@ -839,16 +837,12 @@ WebRect WebViewImpl::WidenRectWithinPageBounds(const WebRect& source, int target_margin, int minimum_margin) { - WebSize max_size; - IntSize scroll_offset; - if (MainFrame()) { - // TODO(lukasza): https://crbug.com/734209: The DCHECK below holds now, but - // only because all of the callers don't support OOPIFs and exit early if - // the main frame is not local. - DCHECK(MainFrame()->IsWebLocalFrame()); - max_size = MainFrame()->ToWebLocalFrame()->DocumentSize(); - scroll_offset = MainFrame()->ToWebLocalFrame()->GetScrollOffset(); - } + // Caller should guarantee that the main frame exists and is local. + DCHECK(MainFrame()); + DCHECK(MainFrame()->IsWebLocalFrame()); + WebSize max_size = MainFrame()->ToWebLocalFrame()->DocumentSize(); + IntSize scroll_offset = MainFrame()->ToWebLocalFrame()->GetScrollOffset(); + int left_margin = target_margin; int right_margin = target_margin; @@ -1266,7 +1260,6 @@ GetPage()->WillCloseLayerTreeView(*layer_tree_view_, nullptr); animation_host_ = nullptr; - mutator_dispatcher_ = nullptr; layer_tree_view_ = nullptr; } @@ -3421,20 +3414,6 @@ DrawingBuffer::ForceNextDrawingBufferCreationToFail(); } -base::WeakPtr<AnimationWorkletMutatorDispatcherImpl> -WebViewImpl::EnsureCompositorMutatorDispatcher( - scoped_refptr<base::SingleThreadTaskRunner>* mutator_task_runner) { - if (!mutator_task_runner_) { - layer_tree_view_->SetMutatorClient( - AnimationWorkletMutatorDispatcherImpl::CreateCompositorThreadClient( - &mutator_dispatcher_, &mutator_task_runner_)); - } - - DCHECK(mutator_task_runner_); - *mutator_task_runner = mutator_task_runner_; - return mutator_dispatcher_; -} - float WebViewImpl::DeviceScaleFactor() const { // TODO(oshima): Investigate if this should return the ScreenInfo's scale // factor rather than page's scale factor, which can be 1 in use-zoom-for-dsf
diff --git a/third_party/blink/renderer/core/exported/web_view_impl.h b/third_party/blink/renderer/core/exported/web_view_impl.h index 0a44b85..4a9e570 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.h +++ b/third_party/blink/renderer/core/exported/web_view_impl.h
@@ -74,7 +74,6 @@ } namespace blink { -class AnimationWorkletMutatorDispatcherImpl; class BrowserControls; class DevToolsEmulator; class Frame; @@ -506,6 +505,8 @@ // Helper function: Widens the width of |source| by the specified margins // while keeping it smaller than page width. + // + // This method can only be called if the main frame is local. WebRect WidenRectWithinPageBounds(const WebRect& source, int target_margin, int minimum_margin); @@ -533,12 +534,6 @@ LocalFrame* FocusedLocalFrameInWidget() const; LocalFrame* FocusedLocalFrameAvailableForIme() const; - // Create or return cached mutation distributor. The WeakPtr must only be - // dereferenced on the returned |mutator_task_runner|. - base::WeakPtr<AnimationWorkletMutatorDispatcherImpl> - EnsureCompositorMutatorDispatcher( - scoped_refptr<base::SingleThreadTaskRunner>* mutator_task_runner); - bool ScrollFocusedEditableElementIntoView(); // Finds the zoom and scroll parameters for zooming into an editable element // with bounds |element_bounds_in_document| and caret bounds @@ -689,12 +684,6 @@ FloatSize elastic_overscroll_; - // This is owned by the LayerTreeHostImpl, and should only be used on the - // compositor thread, so we keep the TaskRunner where you post tasks to - // make that happen. - base::WeakPtr<AnimationWorkletMutatorDispatcherImpl> mutator_dispatcher_; - scoped_refptr<base::SingleThreadTaskRunner> mutator_task_runner_; - Persistent<EventListener> popup_mouse_wheel_event_listener_; // The local root whose document has |popup_mouse_wheel_event_listener_|
diff --git a/third_party/blink/renderer/core/fileapi/file.h b/third_party/blink/renderer/core/fileapi/file.h index 4a2b3a42..474c226 100644 --- a/third_party/blink/renderer/core/fileapi/file.h +++ b/third_party/blink/renderer/core/fileapi/file.h
@@ -31,6 +31,7 @@ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/fileapi/blob.h" #include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/wtf/casting.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { @@ -264,7 +265,10 @@ String relative_path_; }; -DEFINE_TYPE_CASTS(File, Blob, blob, blob->IsFile(), blob.IsFile()); +template <> +struct DowncastTraits<File> { + static bool AllowFrom(const Blob& blob) { return blob.IsFile(); } +}; } // namespace blink
diff --git a/third_party/blink/renderer/core/fileapi/file_reader.cc b/third_party/blink/renderer/core/fileapi/file_reader.cc index bbb53cb..2d52fa1 100644 --- a/third_party/blink/renderer/core/fileapi/file_reader.cc +++ b/third_party/blink/renderer/core/fileapi/file_reader.cc
@@ -57,7 +57,7 @@ } const CString Utf8FilePath(Blob* blob) { - return blob->HasBackingFile() ? ToFile(blob)->GetPath().Utf8() : ""; + return blob->HasBackingFile() ? To<File>(blob)->GetPath().Utf8() : ""; } } // namespace
diff --git a/third_party/blink/renderer/core/frame/frame_serializer.cc b/third_party/blink/renderer/core/frame/frame_serializer.cc index c4db16d5..cc15dd0 100644 --- a/third_party/blink/renderer/core/frame/frame_serializer.cc +++ b/third_party/blink/renderer/core/frame/frame_serializer.cc
@@ -63,7 +63,7 @@ #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/histogram.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h" -#include "third_party/blink/renderer/platform/serialized_resource.h" +#include "third_party/blink/renderer/platform/mhtml/serialized_resource.h" #include "third_party/blink/renderer/platform/wtf/hash_set.h" #include "third_party/blink/renderer/platform/wtf/text/cstring.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
diff --git a/third_party/blink/renderer/core/frame/frame_serializer_test.cc b/third_party/blink/renderer/core/frame/frame_serializer_test.cc index 83ecd24c..bdb9e0b9 100644 --- a/third_party/blink/renderer/core/frame/frame_serializer_test.cc +++ b/third_party/blink/renderer/core/frame/frame_serializer_test.cc
@@ -45,8 +45,8 @@ #include "third_party/blink/renderer/core/frame/frame_test_helpers.h" #include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_error.h" +#include "third_party/blink/renderer/platform/mhtml/serialized_resource.h" #include "third_party/blink/renderer/platform/scheduler/public/thread.h" -#include "third_party/blink/renderer/platform/serialized_resource.h" #include "third_party/blink/renderer/platform/testing/testing_platform_support.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" #include "third_party/blink/renderer/platform/testing/url_test_helpers.h"
diff --git a/third_party/blink/renderer/core/frame/local_dom_window.cc b/third_party/blink/renderer/core/frame/local_dom_window.cc index 33268ed..e5211bb 100644 --- a/third_party/blink/renderer/core/frame/local_dom_window.cc +++ b/third_party/blink/renderer/core/frame/local_dom_window.cc
@@ -29,6 +29,7 @@ #include <memory> #include <utility> +#include "cc/input/scroll_snap_data.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/public/platform/web_screen_info.h" @@ -1027,8 +1028,8 @@ y * GetFrame()->PageZoomFactor()); FloatPoint new_scaled_position = current_position + scaled_delta; - std::unique_ptr<SnapSelectionStrategy> strategy = - SnapSelectionStrategy::CreateForEndAndDirection( + std::unique_ptr<cc::SnapSelectionStrategy> strategy = + cc::SnapSelectionStrategy::CreateForEndAndDirection( gfx::ScrollOffset(current_position), gfx::ScrollOffset(scaled_delta)); new_scaled_position = document() @@ -1091,8 +1092,8 @@ FloatPoint new_scaled_position = viewport->ScrollOffsetToPosition(ScrollOffset(scaled_x, scaled_y)); - std::unique_ptr<SnapSelectionStrategy> strategy = - SnapSelectionStrategy::CreateForEndPosition( + std::unique_ptr<cc::SnapSelectionStrategy> strategy = + cc::SnapSelectionStrategy::CreateForEndPosition( gfx::ScrollOffset(new_scaled_position), scroll_to_options->hasLeft(), scroll_to_options->hasTop()); new_scaled_position =
diff --git a/third_party/blink/renderer/core/frame/mhtml_archive_test.cc b/third_party/blink/renderer/core/frame/mhtml_archive_test.cc index 45e62bc6..03adaec 100644 --- a/third_party/blink/renderer/core/frame/mhtml_archive_test.cc +++ b/third_party/blink/renderer/core/frame/mhtml_archive_test.cc
@@ -36,7 +36,7 @@ #include "third_party/blink/renderer/platform/date_components.h" #include "third_party/blink/renderer/platform/mhtml/mhtml_archive.h" #include "third_party/blink/renderer/platform/mhtml/mhtml_parser.h" -#include "third_party/blink/renderer/platform/serialized_resource.h" +#include "third_party/blink/renderer/platform/mhtml/serialized_resource.h" #include "third_party/blink/renderer/platform/shared_buffer.h" #include "third_party/blink/renderer/platform/testing/testing_platform_support.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
diff --git a/third_party/blink/renderer/core/frame/root_frame_viewport.cc b/third_party/blink/renderer/core/frame/root_frame_viewport.cc index b982371..0bcb4ed 100644 --- a/third_party/blink/renderer/core/frame/root_frame_viewport.cc +++ b/third_party/blink/renderer/core/frame/root_frame_viewport.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/core/frame/root_frame_viewport.h" +#include "cc/input/scroll_snap_data.h" #include "third_party/blink/public/platform/web_scroll_into_view_params.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" #include "third_party/blink/renderer/core/layout/layout_box.h" @@ -295,9 +296,9 @@ new_scroll_offset = ClampToUserScrollableOffset(new_scroll_offset); FloatPoint end_point = ScrollOffsetToPosition(new_scroll_offset); - std::unique_ptr<SnapSelectionStrategy> strategy = - SnapSelectionStrategy::CreateForEndPosition(gfx::ScrollOffset(end_point), - true, true); + std::unique_ptr<cc::SnapSelectionStrategy> strategy = + cc::SnapSelectionStrategy::CreateForEndPosition( + gfx::ScrollOffset(end_point), true, true); if (GetLayoutBox()) { end_point = GetLayoutBox() ->GetDocument()
diff --git a/third_party/blink/renderer/core/frame/scheduling.idl b/third_party/blink/renderer/core/frame/scheduling.idl index c701deba..6da75165 100644 --- a/third_party/blink/renderer/core/frame/scheduling.idl +++ b/third_party/blink/renderer/core/frame/scheduling.idl
@@ -5,5 +5,5 @@ // https://github.com/tdresser/is-input-pending [OriginTrialEnabled=ExperimentalIsInputPending] interface Scheduling { - [CallWith=ScriptState, OriginTrialEnabled=ExperimentalIsInputPending] boolean isInputPending(optional sequence<DOMString> inputTypes = []); + [CallWith=ScriptState, MeasureAs=SchedulingIsInputPending, OriginTrialEnabled=ExperimentalIsInputPending] boolean isInputPending(optional sequence<DOMString> inputTypes = []); };
diff --git a/third_party/blink/renderer/core/frame/web_frame_widget_base.cc b/third_party/blink/renderer/core/frame/web_frame_widget_base.cc index 7e4bc630..b84c1f3 100644 --- a/third_party/blink/renderer/core/frame/web_frame_widget_base.cc +++ b/third_party/blink/renderer/core/frame/web_frame_widget_base.cc
@@ -32,6 +32,8 @@ #include "third_party/blink/renderer/core/page/focus_controller.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/core/page/pointer_lock_controller.h" +#include "third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.h" +#include "third_party/blink/renderer/platform/graphics/compositor_mutator_client.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" namespace blink { @@ -60,6 +62,7 @@ } void WebFrameWidgetBase::Close() { + mutator_dispatcher_ = nullptr; local_root_->SetFrameWidget(nullptr); local_root_ = nullptr; client_ = nullptr; @@ -448,4 +451,18 @@ return WebLocalFrameImpl::FromFrame(FocusedLocalFrameInWidget()); } +base::WeakPtr<AnimationWorkletMutatorDispatcherImpl> +WebFrameWidgetBase::EnsureCompositorMutatorDispatcher( + scoped_refptr<base::SingleThreadTaskRunner>* mutator_task_runner) { + if (!mutator_task_runner_) { + GetLayerTreeView()->SetMutatorClient( + AnimationWorkletMutatorDispatcherImpl::CreateCompositorThreadClient( + &mutator_dispatcher_, &mutator_task_runner_)); + } + + DCHECK(mutator_task_runner_); + *mutator_task_runner = mutator_task_runner_; + return mutator_dispatcher_; +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/frame/web_frame_widget_base.h b/third_party/blink/renderer/core/frame/web_frame_widget_base.h index eb8451a..4dce506 100644 --- a/third_party/blink/renderer/core/frame/web_frame_widget_base.h +++ b/third_party/blink/renderer/core/frame/web_frame_widget_base.h
@@ -55,9 +55,13 @@ virtual bool ForSubframe() const = 0; virtual void IntrinsicSizingInfoChanged(const IntrinsicSizingInfo&) {} - virtual base::WeakPtr<AnimationWorkletMutatorDispatcherImpl> + + // Creates or returns cached mutator dispatcher. This usually requires a + // round trip to the compositor. The returned WeakPtr must only be + // dereferenced on the output |mutator_task_runner|. + base::WeakPtr<AnimationWorkletMutatorDispatcherImpl> EnsureCompositorMutatorDispatcher( - scoped_refptr<base::SingleThreadTaskRunner>* mutator_task_runner) = 0; + scoped_refptr<base::SingleThreadTaskRunner>* mutator_task_runner); // Sets the root graphics layer. |GraphicsLayer| can be null when detaching // the root layer. @@ -187,6 +191,12 @@ static bool ignore_input_events_; scoped_refptr<UserGestureToken> pointer_lock_gesture_token_; + // This is owned by the LayerTreeHostImpl, and should only be used on the + // compositor thread, so we keep the TaskRunner where you post tasks to + // make that happen. + base::WeakPtr<AnimationWorkletMutatorDispatcherImpl> mutator_dispatcher_; + scoped_refptr<base::SingleThreadTaskRunner> mutator_task_runner_; + friend class WebViewImpl; };
diff --git a/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc b/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc index 1b9051f..7b52e82 100644 --- a/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc +++ b/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc
@@ -81,9 +81,7 @@ #include "third_party/blink/renderer/core/page/pointer_lock_controller.h" #include "third_party/blink/renderer/core/page/validation_message_client.h" #include "third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h" -#include "third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.h" #include "third_party/blink/renderer/platform/graphics/color.h" -#include "third_party/blink/renderer/platform/graphics/compositor_mutator_client.h" #include "third_party/blink/renderer/platform/keyboard_codes.h" namespace blink { @@ -172,7 +170,6 @@ WebFrameWidgetBase::Close(); - mutator_dispatcher_ = nullptr; layer_tree_view_ = nullptr; animation_host_ = nullptr; root_layer_ = nullptr; @@ -534,20 +531,6 @@ Client()->IntrinsicSizingInfoChanged(web_sizing_info); } -base::WeakPtr<AnimationWorkletMutatorDispatcherImpl> -WebFrameWidgetImpl::EnsureCompositorMutatorDispatcher( - scoped_refptr<base::SingleThreadTaskRunner>* mutator_task_runner) { - if (!mutator_task_runner_) { - layer_tree_view_->SetMutatorClient( - AnimationWorkletMutatorDispatcherImpl::CreateCompositorThreadClient( - &mutator_dispatcher_, &mutator_task_runner_)); - } - - DCHECK(mutator_task_runner_); - *mutator_task_runner = mutator_task_runner_; - return mutator_dispatcher_; -} - void WebFrameWidgetImpl::ApplyViewportChanges(const ApplyViewportChangesArgs&) { } @@ -985,7 +968,6 @@ void WebFrameWidgetImpl::SetLayerTreeView(WebLayerTreeView* layer_tree_view, cc::AnimationHost* animation_host) { DCHECK(Client()); - DCHECK(!mutator_dispatcher_); layer_tree_view_ = layer_tree_view; animation_host_ = animation_host;
diff --git a/third_party/blink/renderer/core/frame/web_frame_widget_impl.h b/third_party/blink/renderer/core/frame/web_frame_widget_impl.h index 8c6b4ea..dc5675d 100644 --- a/third_party/blink/renderer/core/frame/web_frame_widget_impl.h +++ b/third_party/blink/renderer/core/frame/web_frame_widget_impl.h
@@ -55,7 +55,6 @@ } namespace blink { -class AnimationWorkletMutatorDispatcherImpl; class Frame; class Element; class HTMLPlugInElement; @@ -123,12 +122,6 @@ Element* FocusedElement() const; PaintLayerCompositor* Compositor() const; - // Create or return cached mutation distributor. This usually requires a - // round trip to the compositor. The output task runner is the one to use - // for sending mutations using the WeakPtr. - base::WeakPtr<AnimationWorkletMutatorDispatcherImpl> - EnsureCompositorMutatorDispatcher(scoped_refptr<base::SingleThreadTaskRunner>* - mutator_task_runner) override; // WebFrameWidgetBase overrides: void SetLayerTreeView(WebLayerTreeView*, cc::AnimationHost*) override; @@ -196,12 +189,6 @@ Member<HTMLPlugInElement> mouse_capture_element_; scoped_refptr<UserGestureToken> mouse_capture_gesture_token_; - // This is owned by the LayerTreeHostImpl, and should only be used on the - // compositor thread, so we keep the TaskRunner where you post tasks to - // make that happen. - base::WeakPtr<AnimationWorkletMutatorDispatcherImpl> mutator_dispatcher_; - scoped_refptr<base::SingleThreadTaskRunner> mutator_task_runner_; - WebLayerTreeView* layer_tree_view_ = nullptr; cc::AnimationHost* animation_host_ = nullptr; scoped_refptr<cc::Layer> root_layer_;
diff --git a/third_party/blink/renderer/core/frame/web_view_frame_widget.cc b/third_party/blink/renderer/core/frame/web_view_frame_widget.cc index 2d35cf4..60ee232 100644 --- a/third_party/blink/renderer/core/frame/web_view_frame_widget.cc +++ b/third_party/blink/renderer/core/frame/web_view_frame_widget.cc
@@ -173,12 +173,6 @@ NOTREACHED(); } -base::WeakPtr<AnimationWorkletMutatorDispatcherImpl> -WebViewFrameWidget::EnsureCompositorMutatorDispatcher( - scoped_refptr<base::SingleThreadTaskRunner>* mutator_task_runner) { - return web_view_->EnsureCompositorMutatorDispatcher(mutator_task_runner); -} - void WebViewFrameWidget::SetRootGraphicsLayer(GraphicsLayer* layer) { web_view_->SetRootGraphicsLayer(layer); }
diff --git a/third_party/blink/renderer/core/frame/web_view_frame_widget.h b/third_party/blink/renderer/core/frame/web_view_frame_widget.h index 5ea0099..dad1e28 100644 --- a/third_party/blink/renderer/core/frame/web_view_frame_widget.h +++ b/third_party/blink/renderer/core/frame/web_view_frame_widget.h
@@ -86,9 +86,6 @@ // WebFrameWidgetBase overrides: void SetLayerTreeView(WebLayerTreeView*, cc::AnimationHost*) override; bool ForSubframe() const override { return false; } - base::WeakPtr<AnimationWorkletMutatorDispatcherImpl> - EnsureCompositorMutatorDispatcher( - scoped_refptr<base::SingleThreadTaskRunner>*) override; void SetRootGraphicsLayer(GraphicsLayer*) override; GraphicsLayer* RootGraphicsLayer() const override; void SetRootLayer(scoped_refptr<cc::Layer>) override;
diff --git a/third_party/blink/renderer/core/fullscreen/fullscreen.cc b/third_party/blink/renderer/core/fullscreen/fullscreen.cc index c8bbd0f1..5c3bf4f 100644 --- a/third_party/blink/renderer/core/fullscreen/fullscreen.cc +++ b/third_party/blink/renderer/core/fullscreen/fullscreen.cc
@@ -506,7 +506,8 @@ // TODO(kochi): Once V0 code is removed, we can use the same logic for // Document and ShadowRoot. - if (!scope.RootNode().IsShadowRoot()) { + auto* shadow_root = DynamicTo<ShadowRoot>(scope.RootNode()); + if (!shadow_root) { // For Shadow DOM V0 compatibility: We allow returning an element in V0 // shadow tree, even though it leaks the Shadow DOM. if (element->IsInV0ShadowTree()) { @@ -514,7 +515,7 @@ WebFeature::kDocumentFullscreenElementInV0Shadow); return element; } - } else if (!ToShadowRoot(scope.RootNode()).IsV1()) { + } else if (!shadow_root->IsV1()) { return nullptr; } return scope.AdjustedElement(*element);
diff --git a/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc b/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc index f41de290..649a24cd 100644 --- a/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc +++ b/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc
@@ -446,7 +446,7 @@ const base::TimeTicks start_time = WTF::CurrentTimeTicks(); const scoped_refptr<CanvasResource> canvas_resource = - ResourceProvider()->ProduceFrame(); + ResourceProvider()->ProduceCanvasResource(); const FloatRect src_rect(0, 0, Size().Width(), Size().Height()); dirty_rect_.Intersect(src_rect); const IntRect int_dirty = EnclosingIntRect(dirty_rect_);
diff --git a/third_party/blink/renderer/core/html/cross_origin_attribute.h b/third_party/blink/renderer/core/html/cross_origin_attribute.h index fad0b84..d88bb701 100644 --- a/third_party/blink/renderer/core/html/cross_origin_attribute.h +++ b/third_party/blink/renderer/core/html/cross_origin_attribute.h
@@ -5,7 +5,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CROSS_ORIGIN_ATTRIBUTE_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CROSS_ORIGIN_ATTRIBUTE_H_ -#include "third_party/blink/renderer/platform/cross_origin_attribute_value.h" +#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink {
diff --git a/third_party/blink/renderer/core/html/forms/form_data.cc b/third_party/blink/renderer/core/html/forms/form_data.cc index c30528f8..39ee396 100644 --- a/third_party/blink/renderer/core/html/forms/form_data.cc +++ b/third_party/blink/renderer/core/html/forms/form_data.cc
@@ -261,8 +261,7 @@ // filename. if (entry->GetBlob()) { String name; - if (entry->GetBlob()->IsFile()) { - File* file = ToFile(entry->GetBlob()); + if (auto* file = DynamicTo<File>(entry->GetBlob())) { // For file blob, use the filename (or relative path if it is // present) as the name. name = file->webkitRelativePath().IsEmpty() @@ -303,7 +302,7 @@ form_data->AppendData(header.data(), header.size()); if (entry->GetBlob()) { if (entry->GetBlob()->HasBackingFile()) { - File* file = ToFile(entry->GetBlob()); + auto* file = To<File>(entry->GetBlob()); // Do not add the file if the path is empty. if (!file->GetPath().IsEmpty()) form_data->AppendFile(file->GetPath()); @@ -355,8 +354,7 @@ // entries. // FIXME: Consider applying the name during insertion. - if (GetBlob()->IsFile()) { - File* file = ToFile(GetBlob()); + if (auto* file = DynamicTo<File>(GetBlob())) { if (Filename().IsNull()) return file; return file->Clone(Filename());
diff --git a/third_party/blink/renderer/core/html/html_anchor_element.cc b/third_party/blink/renderer/core/html/html_anchor_element.cc index 4903dd6..8680172 100644 --- a/third_party/blink/renderer/core/html/html_anchor_element.cc +++ b/third_party/blink/renderer/core/html/html_anchor_element.cc
@@ -433,7 +433,7 @@ request.SetSuggestedFilename( static_cast<String>(FastGetAttribute(kDownloadAttr))); request.SetRequestContext(mojom::RequestContextType::DOWNLOAD); - request.SetRequestorOrigin(SecurityOrigin::Create(GetDocument().Url())); + request.SetRequestorOrigin(GetDocument().GetSecurityOrigin()); frame->Client()->DownloadURL(request, DownloadCrossOriginRedirects::kNavigate); return;
diff --git a/third_party/blink/renderer/core/html/media/html_media_element.h b/third_party/blink/renderer/core/html/media/html_media_element.h index b785d9e..9bbeefca 100644 --- a/third_party/blink/renderer/core/html/media/html_media_element.h +++ b/third_party/blink/renderer/core/html/media/html_media_element.h
@@ -97,6 +97,8 @@ // Returns attributes that should be checked against Trusted Types const AttrNameToTrustedType& GetCheckedAttributeTypes() const override; + bool IsMediaElement() const override { return true; } + static MIMETypeRegistry::SupportsType GetSupportsType(const ContentType&); enum class RecordMetricsBehavior { kDoNotRecord, kDoRecord };
diff --git a/third_party/blink/renderer/core/html/parser/preload_request.cc b/third_party/blink/renderer/core/html/parser/preload_request.cc index 8cea788..c1b81cc 100644 --- a/third_party/blink/renderer/core/html/parser/preload_request.cc +++ b/third_party/blink/renderer/core/html/parser/preload_request.cc
@@ -11,7 +11,7 @@ #include "third_party/blink/renderer/core/loader/preload_helper.h" #include "third_party/blink/renderer/core/script/document_write_intervention.h" #include "third_party/blink/renderer/core/script/script_loader.h" -#include "third_party/blink/renderer/platform/cross_origin_attribute_value.h" +#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_info.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
diff --git a/third_party/blink/renderer/core/html/parser/preload_request.h b/third_party/blink/renderer/core/html/parser/preload_request.h index 82bf24aa..f787b7ad 100644 --- a/third_party/blink/renderer/core/html/parser/preload_request.h +++ b/third_party/blink/renderer/core/html/parser/preload_request.h
@@ -12,8 +12,8 @@ #include "third_party/blink/public/mojom/script/script_type.mojom-blink.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/script/script.h" -#include "third_party/blink/renderer/platform/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.h" +#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h" #include "third_party/blink/renderer/platform/loader/fetch/integrity_metadata.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
diff --git a/third_party/blink/renderer/core/input/event_handler.cc b/third_party/blink/renderer/core/input/event_handler.cc index e62ac9f1..7bf1fe0 100644 --- a/third_party/blink/renderer/core/input/event_handler.cc +++ b/third_party/blink/renderer/core/input/event_handler.cc
@@ -117,8 +117,9 @@ Node* target_node = mev.InnerNode(); if (!target_node || !target_node->parentNode()) return true; - return target_node->IsShadowRoot() && - IsHTMLInputElement(ToShadowRoot(target_node)->host()); + if (auto* shadow_root = DynamicTo<ShadowRoot>(target_node)) + return IsHTMLInputElement(shadow_root->host()); + return false; } } // namespace
diff --git a/third_party/blink/renderer/core/input/scroll_manager.cc b/third_party/blink/renderer/core/input/scroll_manager.cc index 9be44ff..df0039b 100644 --- a/third_party/blink/renderer/core/input/scroll_manager.cc +++ b/third_party/blink/renderer/core/input/scroll_manager.cc
@@ -5,6 +5,8 @@ #include "third_party/blink/renderer/core/input/scroll_manager.h" #include <memory> + +#include "cc/input/scroll_snap_data.h" #include "third_party/blink/renderer/core/dom/dom_node_ids.h" #include "third_party/blink/renderer/core/dom/node_computed_style.h" #include "third_party/blink/renderer/core/events/gesture_event.h" @@ -701,8 +703,8 @@ FloatPoint current_position = scrollable_area->ScrollPosition(); *out_initial_position = gfx::Vector2dF(current_position); - std::unique_ptr<SnapSelectionStrategy> strategy = - SnapSelectionStrategy::CreateForEndAndDirection( + std::unique_ptr<cc::SnapSelectionStrategy> strategy = + cc::SnapSelectionStrategy::CreateForEndAndDirection( gfx::ScrollOffset(*out_initial_position), gfx::ScrollOffset(natural_displacement)); base::Optional<FloatPoint> snap_end =
diff --git a/third_party/blink/renderer/core/inspector/inspector_dom_agent.cc b/third_party/blink/renderer/core/inspector/inspector_dom_agent.cc index 5d1b1d5..27ef975 100644 --- a/third_party/blink/renderer/core/inspector/inspector_dom_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_dom_agent.cc
@@ -398,10 +398,10 @@ return nullptr; Node* candidate = node; - while (candidate && !candidate->IsShadowRoot()) + while (candidate && !IsA<ShadowRoot>(candidate)) candidate = candidate->ParentOrShadowHostNode(); DCHECK(candidate); - ShadowRoot* shadow_root = ToShadowRoot(candidate); + ShadowRoot* shadow_root = To<ShadowRoot>(candidate); return shadow_root->IsUserAgent() ? shadow_root : nullptr; } @@ -412,7 +412,7 @@ return response; if (node->IsInShadowTree()) { - if (node->IsShadowRoot()) + if (IsA<ShadowRoot>(node)) return Response::Error("Cannot edit shadow roots"); if (UserAgentShadowRoot(node)) return Response::Error("Cannot edit nodes from user-agent shadow trees"); @@ -944,16 +944,15 @@ do { if (node == stay_within) return nullptr; - if (node->IsShadowRoot()) { - const ShadowRoot* shadow_root = ToShadowRoot(node); + auto* shadow_root = DynamicTo<ShadowRoot>(node); + if (shadow_root) { Element& host = shadow_root->host(); if (host.HasChildren()) return host.firstChild(); } if (node->nextSibling()) return node->nextSibling(); - node = - node->IsShadowRoot() ? &ToShadowRoot(node)->host() : node->parentNode(); + node = shadow_root ? &shadow_root->host() : node->parentNode(); } while (node); return nullptr; @@ -1547,8 +1546,8 @@ Attr* attribute = ToAttr(node); value->setName(attribute->name()); value->setValue(attribute->value()); - } else if (node->IsShadowRoot()) { - value->setShadowRootType(GetShadowRootType(ToShadowRoot(node))); + } else if (auto* shadow_root = DynamicTo<ShadowRoot>(node)) { + value->setShadowRootType(GetShadowRootType(shadow_root)); } if (node->IsContainerNode()) {
diff --git a/third_party/blink/renderer/core/layout/layout_block.cc b/third_party/blink/renderer/core/layout/layout_block.cc index bfa6a13..3be4c70 100644 --- a/third_party/blink/renderer/core/layout/layout_block.cc +++ b/third_party/blink/renderer/core/layout/layout_block.cc
@@ -1710,9 +1710,10 @@ if (IsRootEditableElement(*GetNode())) return true; - if (GetNode()->IsShadowRoot() && - IsHTMLInputElement(ToShadowRoot(GetNode())->host())) - return true; + if (auto* shadow_root = DynamicTo<ShadowRoot>(GetNode())) { + if (IsHTMLInputElement(shadow_root->host())) + return true; + } return false; }
diff --git a/third_party/blink/renderer/core/layout/layout_box.cc b/third_party/blink/renderer/core/layout/layout_box.cc index f87b471..12cb7dc 100644 --- a/third_party/blink/renderer/core/layout/layout_box.cc +++ b/third_party/blink/renderer/core/layout/layout_box.cc
@@ -28,6 +28,8 @@ #include <math.h> #include <algorithm> + +#include "cc/input/scroll_snap_data.h" #include "third_party/blink/public/platform/web_rect.h" #include "third_party/blink/public/platform/web_scroll_into_view_params.h" #include "third_party/blink/renderer/core/dom/document.h" @@ -458,19 +460,19 @@ bool allows_snap_container = GetNode() != GetDocument().ViewportDefiningElement(); - ScrollSnapType old_snap_type = - old_style ? old_style->GetScrollSnapType() : ScrollSnapType(); - ScrollSnapType new_snap_type = new_style && allows_snap_container - ? new_style->GetScrollSnapType() - : ScrollSnapType(); + cc::ScrollSnapType old_snap_type = + old_style ? old_style->GetScrollSnapType() : cc::ScrollSnapType(); + cc::ScrollSnapType new_snap_type = new_style && allows_snap_container + ? new_style->GetScrollSnapType() + : cc::ScrollSnapType(); if (old_snap_type != new_snap_type) snap_coordinator->SnapContainerDidChange(*this, new_snap_type); - ScrollSnapAlign old_snap_align = - old_style ? old_style->GetScrollSnapAlign() : ScrollSnapAlign(); - ScrollSnapAlign new_snap_align = new_style && allows_snap_container - ? new_style->GetScrollSnapAlign() - : ScrollSnapAlign(); + cc::ScrollSnapAlign old_snap_align = + old_style ? old_style->GetScrollSnapAlign() : cc::ScrollSnapAlign(); + cc::ScrollSnapAlign new_snap_align = new_style && allows_snap_container + ? new_style->GetScrollSnapAlign() + : cc::ScrollSnapAlign(); if (old_snap_align != new_snap_align) snap_coordinator->SnapAreaDidChange(*this, new_snap_align); }
diff --git a/third_party/blink/renderer/core/layout/layout_image.cc b/third_party/blink/renderer/core/layout/layout_image.cc index 56e2005..f513e41f 100644 --- a/third_party/blink/renderer/core/layout/layout_image.cc +++ b/third_party/blink/renderer/core/layout/layout_image.cc
@@ -240,6 +240,7 @@ } void LayoutImage::ImageNotifyFinished(ImageResourceContent* new_image) { + LayoutObject::ImageNotifyFinished(new_image); if (!image_resource_) return;
diff --git a/third_party/blink/renderer/core/layout/layout_object.cc b/third_party/blink/renderer/core/layout/layout_object.cc index c483bbde..fc17a78 100644 --- a/third_party/blink/renderer/core/layout/layout_object.cc +++ b/third_party/blink/renderer/core/layout/layout_object.cc
@@ -3815,6 +3815,11 @@ ImageChanged(static_cast<WrappedImagePtr>(image), defer); } +void LayoutObject::ImageNotifyFinished(ImageResourceContent*) { + if (AXObjectCache* cache = GetDocument().ExistingAXObjectCache()) + cache->ImageLoaded(this); +} + Element* LayoutObject::OffsetParent(const Element* base) const { if (IsDocumentElement() || IsBody()) return nullptr;
diff --git a/third_party/blink/renderer/core/layout/layout_object.h b/third_party/blink/renderer/core/layout/layout_object.h index c121181..624c0ca 100644 --- a/third_party/blink/renderer/core/layout/layout_object.h +++ b/third_party/blink/renderer/core/layout/layout_object.h
@@ -1723,6 +1723,7 @@ // ImageResourceObserver override. void ImageChanged(ImageResourceContent*, CanDeferInvalidation) final; void ImageChanged(WrappedImagePtr, CanDeferInvalidation) override {} + void ImageNotifyFinished(ImageResourceContent*) override; bool WillRenderImage() final; bool GetImageAnimationPolicy(ImageAnimationPolicy&) final;
diff --git a/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_rect.cc b/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_rect.cc index f2cd5ba..d470aba 100644 --- a/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_rect.cc +++ b/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_rect.cc
@@ -6,10 +6,6 @@ namespace blink { -bool NGBfcRect::IsEmpty() const { - return start_offset == end_offset; -} - bool NGBfcRect::operator==(const NGBfcRect& other) const { return start_offset == other.start_offset && end_offset == other.end_offset; }
diff --git a/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_rect.h b/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_rect.h index 397a581..03d6bb9 100644 --- a/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_rect.h +++ b/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_rect.h
@@ -21,17 +21,11 @@ DCHECK_GE(end_offset.block_offset, start_offset.block_offset); } - bool IsEmpty() const; - LayoutUnit LineStartOffset() const { return start_offset.line_offset; } LayoutUnit LineEndOffset() const { return end_offset.line_offset; } LayoutUnit BlockStartOffset() const { return start_offset.block_offset; } LayoutUnit BlockEndOffset() const { return end_offset.block_offset; } - NGBfcOffset LineEndBlockStartOffset() const { - return {LineEndOffset(), BlockStartOffset()}; - } - LayoutUnit BlockSize() const { if (end_offset.block_offset == LayoutUnit::Max()) return LayoutUnit::Max(); @@ -44,7 +38,6 @@ return end_offset.line_offset - start_offset.line_offset; } - NGLogicalSize Size() const { return {InlineSize(), BlockSize()}; } bool operator==(const NGBfcRect& other) const; bool operator!=(const NGBfcRect& other) const { return !(*this == other); }
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_caret_navigator.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_caret_navigator.cc index 64babf9..7590ce303 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_caret_navigator.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_caret_navigator.cc
@@ -338,7 +338,7 @@ DCHECK(forward_character.index.has_value()); const Position forward_caret = - EdgeOfInternal(forward_character.index.value(), opposite_direction); + EdgeOfInternal(*forward_character.index, opposite_direction); return {VisualMovementResultType::kWithinContext, forward_caret}; } @@ -357,14 +357,14 @@ if (next.has_passed_character) has_passed_character = true; - runner = next.position.value(); + runner = *next.position; last_position = runner; // TODO(xiaochengh): Handle the case where we reach a different line with a // different base direction, which occurs with 'unicode-bidi: plain-text'. } DCHECK(last_position.has_value()); - return {VisualMovementResultType::kWithinContext, last_position.value()}; + return {VisualMovementResultType::kWithinContext, *last_position}; } } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position.cc index c606f29..7db1ec6 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position.cc
@@ -155,7 +155,7 @@ NGOffsetMapping::GetFor(before_node)->GetTextContentOffset(before_node); // We should have offset mapping for atomic inline boxes. DCHECK(maybe_offset_before.has_value()); - return maybe_offset_before.value(); + return *maybe_offset_before; } // Returns a |kFailed| resolution if |offset| doesn't belong to the atomic @@ -251,7 +251,7 @@ ToNGPhysicalTextFragment(caret_position.fragment->PhysicalFragment()); if (!text_fragment.IsLineBreak()) return false; - return caret_position.text_offset.value() == text_fragment.EndOffset(); + return *caret_position.text_offset == text_fragment.EndOffset(); } NGCaretPosition BetterCandidateBetween(const NGCaretPosition& current, @@ -326,7 +326,7 @@ return NGCaretPosition(); } - const unsigned offset = maybe_offset.value(); + const unsigned offset = *maybe_offset; const TextAffinity affinity = position.Affinity(); return ComputeNGCaretPosition(*context, offset, affinity); } @@ -358,10 +358,9 @@ return PositionWithAffinity(); const NGPhysicalTextFragment& text_fragment = ToNGPhysicalTextFragment(fragment->PhysicalFragment()); - const TextAffinity affinity = - text_offset.value() == text_fragment.EndOffset() - ? TextAffinity::kUpstreamIfPossible - : TextAffinity::kDownstream; + const TextAffinity affinity = *text_offset == text_fragment.EndOffset() + ? TextAffinity::kUpstreamIfPossible + : TextAffinity::kDownstream; return PositionWithAffinity(position, affinity); } NOTREACHED();
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position_test.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position_test.cc index 6446ddb3..050225eb 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position_test.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position_test.cc
@@ -214,8 +214,7 @@ const Position wrap_position(text_c, 1); const NGOffsetMapping& mapping = *NGOffsetMapping::GetFor(wrap_position); - const unsigned wrap_offset = - mapping.GetTextContentOffset(wrap_position).value(); + const unsigned wrap_offset = *mapping.GetTextContentOffset(wrap_position); TEST_CARET(ComputeNGCaretPosition(wrap_offset, TextAffinity::kUpstream), fragment_c, kAtTextOffset, base::Optional<unsigned>(wrap_offset)); @@ -240,8 +239,7 @@ const Position wrap_position(text_c, 1); const NGOffsetMapping& mapping = *NGOffsetMapping::GetFor(wrap_position); - const unsigned wrap_offset = - mapping.GetTextContentOffset(wrap_position).value(); + const unsigned wrap_offset = *mapping.GetTextContentOffset(wrap_position); TEST_CARET(ComputeNGCaretPosition(wrap_offset, TextAffinity::kUpstream), fragment_c, kAtTextOffset, base::Optional<unsigned>(wrap_offset)); @@ -267,8 +265,7 @@ const Position wrap_position(text_c, 1); const NGOffsetMapping& mapping = *NGOffsetMapping::GetFor(wrap_position); - const unsigned wrap_offset = - mapping.GetTextContentOffset(wrap_position).value(); + const unsigned wrap_offset = *mapping.GetTextContentOffset(wrap_position); TEST_CARET(ComputeNGCaretPosition(wrap_offset, TextAffinity::kUpstream), fragment_c, kAtTextOffset, base::Optional<unsigned>(wrap_offset)); @@ -288,7 +285,7 @@ // Test caret position of "|bar", which shouldn't be affected by ::before const Position position(text, 0); const NGOffsetMapping& mapping = *NGOffsetMapping::GetFor(position); - const unsigned text_offset = mapping.GetTextContentOffset(position).value(); + const unsigned text_offset = *mapping.GetTextContentOffset(position); TEST_CARET(ComputeNGCaretPosition(text_offset, TextAffinity::kDownstream), text_fragment, kAtTextOffset,
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.cc index 0c26dd8..3130447 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.cc
@@ -27,7 +27,7 @@ const Vector<NGInlineItem>& items, unsigned item_index) { if (box_states_.has_value() && items_ == &items && item_index_ == item_index) - return &box_states_.value(); + return &*box_states_; return nullptr; }
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.h b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.h index 68c7995..1480a9f 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.h +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.h
@@ -23,7 +23,7 @@ public: // Returns the NGInlineLayoutStateStack in this context. bool HasBoxStates() const { return box_states_.has_value(); } - NGInlineLayoutStateStack* BoxStates() { return &box_states_.value(); } + NGInlineLayoutStateStack* BoxStates() { return &*box_states_; } NGInlineLayoutStateStack* ResetBoxStates() { return &box_states_.emplace(); } // Returns the box states in this context if it exists and it can be used to
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc index 103e5737..a662c14 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc
@@ -938,7 +938,7 @@ continue; LayoutUnit origin_bfc_block_offset = - is_empty_inline ? ConstraintSpace().FloatsBfcBlockOffset().value() + is_empty_inline ? *ConstraintSpace().FloatsBfcBlockOffset() : ConstraintSpace().BfcOffset().block_offset; NGPositionedFloat positioned_float = PositionFloat(
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm_test.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm_test.cc index 9ea9479b..1734258d 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm_test.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm_test.cc
@@ -233,7 +233,7 @@ auto* block_box = ToNGPhysicalBoxFragment(layout_result->PhysicalFragment()); EXPECT_TRUE(layout_result->BfcBlockOffset().has_value()); - EXPECT_EQ(0, layout_result->BfcBlockOffset().value()); + EXPECT_EQ(0, *layout_result->BfcBlockOffset()); EXPECT_EQ(0, layout_result->BfcLineOffset()); NGPhysicalOffset line_offset = block_box->Children()[0].Offset();
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc index 75c921e..e562161 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc
@@ -506,7 +506,7 @@ NGInlineItemsBuilder builder(&data->items); const bool update_layout = true; CollectInlinesInternal(block, &builder, previous_text, - marker.has_value() ? &marker.value() : nullptr, + marker.has_value() ? &*marker : nullptr, update_layout); data->text_content = builder.ToString();
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.cc index ad531312..2e2abcd7 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.cc
@@ -683,7 +683,7 @@ } if (saved_line_break_type.has_value()) - break_iterator_.SetBreakType(saved_line_break_type.value()); + break_iterator_.SetBreakType(*saved_line_break_type); // If there was only one break opportunity in this item, it may form a word // with previous and/or next item. Fallback to |HandleText()|.
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.cc index f3d95df..b8823217 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.cc
@@ -72,7 +72,7 @@ auto& child = *it; if (base::Optional<LayoutUnit> candidate = EllipsisOffset( line_width, ellipsis_width, &child == first_child, &child)) { - ellipsis_inline_offset = candidate.value(); + ellipsis_inline_offset = *candidate; ellipsized_fragment = child.PhysicalFragment(); DCHECK(ellipsized_fragment); break; @@ -84,7 +84,7 @@ for (auto& child : *line_box) { if (base::Optional<LayoutUnit> candidate = EllipsisOffset( line_width, ellipsis_width, &child == first_child, &child)) { - ellipsis_inline_offset = candidate.value(); + ellipsis_inline_offset = *candidate; ellipsized_fragment = child.PhysicalFragment(); DCHECK(ellipsized_fragment); break;
diff --git a/third_party/blink/renderer/core/layout/ng/layout_ng_mixin.cc b/third_party/blink/renderer/core/layout/ng/layout_ng_mixin.cc index 0031829c..b4ee5fb 100644 --- a/third_party/blink/renderer/core/layout/ng/layout_ng_mixin.cc +++ b/third_party/blink/renderer/core/layout/ng/layout_ng_mixin.cc
@@ -247,7 +247,7 @@ if (Base::ChildrenInline()) { if (base::Optional<LayoutUnit> offset = FragmentBaseline(NGBaselineAlgorithmType::kFirstLine)) { - return offset.value(); + return *offset; } } return Base::FirstLineBoxBaseline(); @@ -259,7 +259,7 @@ if (Base::ChildrenInline()) { if (base::Optional<LayoutUnit> offset = FragmentBaseline(NGBaselineAlgorithmType::kAtomicInline)) { - return offset.value(); + return *offset; } } return Base::InlineBlockBaseline(line_direction); @@ -312,7 +312,7 @@ return nullptr; if (bfc_block_offset.has_value()) { - bfc_block_offset = bfc_block_offset.value() - + bfc_block_offset = *bfc_block_offset - old_space.BfcOffset().block_offset + new_space.BfcOffset().block_offset; }
diff --git a/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.cc b/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.cc index 398345bf..140918f 100644 --- a/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.cc +++ b/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.cc
@@ -160,7 +160,7 @@ NGBfcOffset origin_offset = { container_builder->BfcLineOffset() + border_scrollbar_padding.inline_start, - container_builder->BfcBlockOffset().value() + marker_block_offset}; + *container_builder->BfcBlockOffset() + marker_block_offset}; LayoutUnit available_size = container_builder->InlineSize() - border_scrollbar_padding.inline_start - border_scrollbar_padding.inline_end;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.cc b/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.cc index 57fe1f2c..333fcf7 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.cc
@@ -106,8 +106,8 @@ } else { // !left available_width -= *right; } - LayoutUnit margins = (margin_left ? margin_left.value() : LayoutUnit()) + - (margin_right ? margin_right.value() : LayoutUnit()); + LayoutUnit margins = (margin_left ? *margin_left : LayoutUnit()) + + (margin_right ? *margin_right : LayoutUnit()); return (available_width - margins).ClampNegativeToZero(); } @@ -130,8 +130,8 @@ } else { // !top available_height -= *bottom; } - LayoutUnit margins = (margin_top ? margin_top.value() : LayoutUnit()) + - (margin_bottom ? margin_bottom.value() : LayoutUnit()); + LayoutUnit margins = (margin_top ? *margin_top : LayoutUnit()) + + (margin_bottom ? *margin_bottom : LayoutUnit()); return (available_height - margins).ClampNegativeToZero(); } @@ -550,7 +550,7 @@ width = ResolveWidth(space, style, border_padding, child_minmax, style.Width(), LengthResolveType::kContentSize); } else if (replaced_size.has_value()) { - width = replaced_size.value().inline_size; + width = replaced_size->inline_size; } ComputeAbsoluteHorizontal( space, style, border_padding, width, static_position, child_minmax, @@ -561,7 +561,7 @@ height = ResolveHeight(space, style, border_padding, child_minmax, style.Height(), LengthResolveType::kContentSize); } else if (replaced_size.has_value()) { - height = replaced_size.value().inline_size; + height = replaced_size->inline_size; } ComputeAbsoluteVertical( space, style, border_padding, height, static_position, child_minmax, @@ -594,7 +594,7 @@ height = ResolveHeight(space, style, border_padding, child_minmax, style.Height(), LengthResolveType::kContentSize); } else if (replaced_size.has_value()) { - height = replaced_size.value().block_size; + height = replaced_size->block_size; } ComputeAbsoluteVertical( space, style, border_padding, height, static_position, child_minmax, @@ -605,7 +605,7 @@ width = ResolveWidth(space, style, border_padding, child_minmax, style.Width(), LengthResolveType::kContentSize); } else if (replaced_size.has_value()) { - width = replaced_size.value().block_size; + width = replaced_size->block_size; } ComputeAbsoluteHorizontal( space, style, border_padding, width, static_position, child_minmax,
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc index 35dc0d31..a9b6885 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc
@@ -109,9 +109,9 @@ return IsEmptyBlock(child_space.IsNewFormattingContext(), layout_result); } -LayoutUnit LogicalFromBfcLineOffset(const NGFragment& fragment, - LayoutUnit child_bfc_line_offset, +LayoutUnit LogicalFromBfcLineOffset(LayoutUnit child_bfc_line_offset, LayoutUnit parent_bfc_line_offset, + LayoutUnit child_inline_size, LayoutUnit parent_inline_size, TextDirection direction) { // We need to respect the current text direction to calculate the logical @@ -122,19 +122,19 @@ LayoutUnit inline_offset = direction == TextDirection::kLtr ? relative_line_offset - : parent_inline_size - relative_line_offset - fragment.InlineSize(); + : parent_inline_size - relative_line_offset - child_inline_size; return inline_offset; } -NGLogicalOffset LogicalFromBfcOffsets(const NGFragment& fragment, - const NGBfcOffset& child_bfc_offset, +NGLogicalOffset LogicalFromBfcOffsets(const NGBfcOffset& child_bfc_offset, const NGBfcOffset& parent_bfc_offset, + LayoutUnit child_inline_size, LayoutUnit parent_inline_size, TextDirection direction) { LayoutUnit inline_offset = LogicalFromBfcLineOffset( - fragment, child_bfc_offset.line_offset, parent_bfc_offset.line_offset, - parent_inline_size, direction); + child_bfc_offset.line_offset, parent_bfc_offset.line_offset, + child_inline_size, parent_inline_size, direction); return {inline_offset, child_bfc_offset.block_offset - parent_bfc_offset.block_offset}; @@ -337,13 +337,13 @@ if (child_bfc_block_offset) { return LogicalFromBfcOffsets( - fragment, {child_bfc_line_offset, child_bfc_block_offset.value()}, - ContainerBfcOffset(), inline_size, direction); + {child_bfc_line_offset, *child_bfc_block_offset}, ContainerBfcOffset(), + fragment.InlineSize(), inline_size, direction); } LayoutUnit inline_offset = LogicalFromBfcLineOffset( - fragment, child_bfc_line_offset, container_builder_.BfcLineOffset(), - inline_size, direction); + child_bfc_line_offset, container_builder_.BfcLineOffset(), + fragment.InlineSize(), inline_size, direction); // If we've reached here, both the child and the current layout don't have a // BFC block offset yet. Children in this situation are always placed at a @@ -462,7 +462,7 @@ // establish a new formatting context), that may not be the case, // though. There may e.g. be clearance involved, or inline-start margins. if (ConstraintSpace().IsNewFormattingContext()) - DCHECK_EQ(container_builder_.BfcBlockOffset().value(), LayoutUnit()); + DCHECK_EQ(*container_builder_.BfcBlockOffset(), LayoutUnit()); // If this is a new formatting context, or if we're resuming from a break // token, no margin strut must be lingering around at this point. if (ConstraintSpace().IsNewFormattingContext() || is_resuming_) @@ -814,17 +814,8 @@ const NGPreviousInflowPosition& previous_inflow_position, NGBlockNode child) { const ComputedStyle& child_style = child.Style(); - LayoutUnit inline_offset = border_scrollbar_padding_.inline_start; - if (child_style.IsOriginalDisplayInlineType()) { - // If this out-of-flow child is inline type, its static position should - // honor the 'text-align' property. - inline_offset += - InlineOffsetForTextAlign(Style(), child_available_size_.inline_size); - } - // TODO(ikilpatrick): Determine which of the child's margins need to be - // included for the static position. - NGLogicalOffset offset = {inline_offset, + NGLogicalOffset offset = {border_scrollbar_padding_.inline_start, previous_inflow_position.logical_block_offset}; // We only include the margin strut in the OOF static-position if we know we @@ -832,6 +823,37 @@ if (container_builder_.BfcBlockOffset()) offset.block_offset += previous_inflow_position.margin_strut.Sum(); + if (child_style.IsOriginalDisplayInlineType()) { + // OOF-positioned nodes which were initially inline-level, however are in a + // block-level context, pretend they are in an inline-level context. E.g. + // they avoid floats, and respect text-align. + const TextDirection direction = ConstraintSpace().Direction(); + LayoutUnit child_origin_line_offset = + container_builder_.BfcLineOffset() + + border_scrollbar_padding_.LineLeft(direction); + + // Find a layout opportunity, this is where we would have placed a + // zero-sized line. + NGLayoutOpportunity opportunity = exclusion_space_.FindLayoutOpportunity( + {child_origin_line_offset, BfcBlockOffset() + offset.block_offset}, + child_available_size_.inline_size, /* minimum_size */ NGLogicalSize()); + + LayoutUnit child_line_offset = IsLtr(direction) + ? opportunity.rect.LineStartOffset() + : opportunity.rect.LineEndOffset(); + + // Convert back to the logical coordinate system. As the conversion is on + // an OOF-positioned node, we pretent it has zero inline-size. + offset.inline_offset = LogicalFromBfcLineOffset( + child_line_offset, container_builder_.BfcLineOffset(), + /* child_inline_size */ LayoutUnit(), + container_builder_.Size().inline_size, direction); + + // Adjust for text alignment, within the layout opportunity. + offset.inline_offset += + InlineOffsetForTextAlign(Style(), opportunity.rect.InlineSize()); + } + container_builder_.AddOutOfFlowChildCandidate(child, offset); } @@ -866,7 +888,7 @@ LayoutUnit origin_block_offset = container_builder_.BfcBlockOffset() ? NextBorderEdge(previous_inflow_position) - : ConstraintSpace().FloatsBfcBlockOffset().value(); + : *ConstraintSpace().FloatsBfcBlockOffset(); PositionPendingFloats(origin_block_offset); } } @@ -986,12 +1008,12 @@ // The BFC block offset was calculated when we got to this child, with // the child's margin adjoining. Since that turned out to be wrong, // re-resolve the BFC block offset without the child's margin. - LayoutUnit old_offset = container_builder_.BfcBlockOffset().value(); + LayoutUnit old_offset = *container_builder_.BfcBlockOffset(); container_builder_.ResetBfcBlockOffset(); ResolveBfcBlockOffset(previous_inflow_position, non_adjoining_bfc_offset_estimate); if ((bfc_offset_already_resolved || had_pending_floats) && - old_offset != container_builder_.BfcBlockOffset().value()) { + old_offset != *container_builder_.BfcBlockOffset()) { // The first BFC block offset resolution turned out to be wrong, and we // positioned preceding adjacent floats based on that. Now we have to // roll back and position them at the correct offset. The only expected @@ -1058,7 +1080,7 @@ opportunity.rect.start_offset.block_offset); NGLogicalOffset logical_offset = LogicalFromBfcOffsets( - fragment, child_bfc_offset, ContainerBfcOffset(), + child_bfc_offset, ContainerBfcOffset(), fragment.InlineSize(), container_builder_.Size().inline_size, ConstraintSpace().Direction()); if (ConstraintSpace().HasBlockFragmentation()) { @@ -1287,7 +1309,7 @@ ResolveBfcBlockOffset(previous_inflow_position, has_clearance ? NextBorderEdge(*previous_inflow_position) - : child_bfc_block_offset.value()); + : *child_bfc_block_offset); return false; } @@ -1339,7 +1361,7 @@ // this container will get the same offset, unless it has already been // resolved. if (!ResolveBfcBlockOffset(previous_inflow_position, - child_bfc_block_offset.value())) + *child_bfc_block_offset)) return false; } @@ -1590,7 +1612,7 @@ logical_block_offset += margin_before_clearance; // Calculate and apply actual clearance. - LayoutUnit clearance = child_bfc_block_offset.value() - + LayoutUnit clearance = *child_bfc_block_offset - layout_result.EndMarginStrut().Sum() - NextBorderEdge(previous_inflow_position); logical_block_offset += clearance; @@ -1657,7 +1679,7 @@ LayoutUnit NGBlockLayoutAlgorithm::FragmentainerSpaceAvailable() const { DCHECK(container_builder_.BfcBlockOffset()); return ConstraintSpace().FragmentainerSpaceAtBfcStart() - - container_builder_.BfcBlockOffset().value(); + *container_builder_.BfcBlockOffset(); } bool NGBlockLayoutAlgorithm::IsFragmentainerOutOfSpace( @@ -2048,8 +2070,7 @@ if (!container_builder_.BfcBlockOffset() && ConstraintSpace().FloatsBfcBlockOffset()) { - builder.SetFloatsBfcBlockOffset( - ConstraintSpace().FloatsBfcBlockOffset().value()); + builder.SetFloatsBfcBlockOffset(*ConstraintSpace().FloatsBfcBlockOffset()); } if (floats_bfc_block_offset) @@ -2159,7 +2180,7 @@ if (child->IsBox()) { const NGPhysicalBoxFragment* box = ToNGPhysicalBoxFragment(child); if (base::Optional<LayoutUnit> baseline = box->Baseline(request)) { - container_builder_.AddBaseline(request, baseline.value() + child_offset); + container_builder_.AddBaseline(request, *baseline + child_offset); return true; } } @@ -2244,13 +2265,12 @@ return true; // If the previous BFC block offset matches the new one, we can continue. // Otherwise, we need to abort. - LayoutUnit old_bfc_block_offset = - ConstraintSpace().FloatsBfcBlockOffset().value(); + LayoutUnit old_bfc_block_offset = *ConstraintSpace().FloatsBfcBlockOffset(); // In order to determine if the two offsets are equal, we also need to adjust // floats offset by the clearance offset. ApplyClearance(ConstraintSpace(), &old_bfc_block_offset); - return container_builder_.BfcBlockOffset().value() != old_bfc_block_offset; + return *container_builder_.BfcBlockOffset() != old_bfc_block_offset; } void NGBlockLayoutAlgorithm::PositionPendingFloats( @@ -2264,10 +2284,9 @@ border_scrollbar_padding_.LineLeft(ConstraintSpace().Direction()), origin_block_offset}; - LayoutUnit bfc_block_offset = - container_builder_.BfcBlockOffset() - ? container_builder_.BfcBlockOffset().value() - : ConstraintSpace().FloatsBfcBlockOffset().value(); + LayoutUnit bfc_block_offset = container_builder_.BfcBlockOffset() + ? *container_builder_.BfcBlockOffset() + : *ConstraintSpace().FloatsBfcBlockOffset(); NGBfcOffset bfc_offset = {ConstraintSpace().BfcOffset().line_offset, bfc_block_offset}; @@ -2283,7 +2302,7 @@ *positioned_float.layout_result->PhysicalFragment()); NGLogicalOffset logical_offset = LogicalFromBfcOffsets( - child_fragment, positioned_float.bfc_offset, bfc_offset, + positioned_float.bfc_offset, bfc_offset, child_fragment.InlineSize(), container_builder_.Size().inline_size, ConstraintSpace().Direction()); container_builder_.AddChild(*positioned_float.layout_result, @@ -2310,7 +2329,7 @@ if (container_builder_.BfcBlockOffset()) { NGMarginStrut body_strut = end_margin_strut; body_strut.Append(body_block_end_margin, /* is_quirky */ false); - margin_sum = container_builder_.BfcBlockOffset().value() - + margin_sum = *container_builder_.BfcBlockOffset() - ConstraintSpace().BfcOffset().block_offset + body_strut.Sum(); } else {
diff --git a/third_party/blink/renderer/core/layout/ng/ng_box_fragment.cc b/third_party/blink/renderer/core/layout/ng/ng_box_fragment.cc index 2214302d..64f44d4 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_box_fragment.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_box_fragment.cc
@@ -32,7 +32,7 @@ // Check if we have a propagated baseline. if (base::Optional<LayoutUnit> baseline = physical_fragment.Baseline(request)) { - LayoutUnit ascent = baseline.value(); + LayoutUnit ascent = *baseline; LayoutUnit descent = BlockSize() - ascent; // For replaced elements, inline-block elements, and inline-table
diff --git a/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc b/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc index 2075e08..cab323c 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc
@@ -53,8 +53,7 @@ linebox_offset + descendant.offset_to_container_box, descendant.fragment->Size()); if (containing_lineboxes.first == linebox) { - containing_block_geometry.value().start_fragment_union_rect.Unite( - fragment_rect); + containing_block_geometry->start_fragment_union_rect.Unite(fragment_rect); } else if (!containing_lineboxes.first) { containing_lineboxes.first = linebox; containing_block_geometry = @@ -63,11 +62,10 @@ } // Skip fragments within an empty line boxes for the end fragment. if (containing_lineboxes.second == linebox) { - containing_block_geometry.value().end_fragment_union_rect.Unite( - fragment_rect); + containing_block_geometry->end_fragment_union_rect.Unite(fragment_rect); } else if (!containing_lineboxes.second || !linebox->IsEmptyLineBox()) { containing_lineboxes.second = linebox; - containing_block_geometry.value().end_fragment_union_rect = fragment_rect; + containing_block_geometry->end_fragment_union_rect = fragment_rect; } } }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc index 0f5c7bfa..3ec68c67 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc
@@ -209,7 +209,7 @@ base::Optional<MinMaxSize> min_max_sizes = algorithm.ComputeMinMaxSize(child_input); DCHECK(min_max_sizes.has_value()); - MinMaxSize sizes = min_max_sizes.value(); + MinMaxSize sizes = *min_max_sizes; // If column-width is non-auto, pick the larger of that and intrinsic column // width.
diff --git a/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.cc index a01b1141..5def47c 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.cc
@@ -274,6 +274,7 @@ container_builder_.SetInlineSize(border_box_size_.inline_size); container_builder_.SetBorders(borders_); container_builder_.SetPadding(padding_); + container_builder_.SetIntrinsicBlockSize(intrinsic_block_size); GiveLinesAndItemsFinalPositionAndSize();
diff --git a/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc b/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc index c76f32fb..83b2b7e0 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc
@@ -79,8 +79,7 @@ DCHECK_EQ(style.GetWritingMode(), parent_space.GetWritingMode()); LayoutUnit fragmentation_offset = - parent_space.FragmentainerSpaceAtBfcStart() - - origin_block_offset.value(); + parent_space.FragmentainerSpaceAtBfcStart() - *origin_block_offset; builder.SetFragmentainerBlockSize(parent_space.FragmentainerBlockSize()); builder.SetFragmentainerSpaceAtBfcStart(fragmentation_offset); builder.SetFragmentationType(parent_space.BlockFragmentationType());
diff --git a/third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h b/third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h index 2bbbf293..aa4aa8b 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h
@@ -79,7 +79,7 @@ NGBfcOffset ContainerBfcOffset() const { DCHECK(container_builder_.BfcBlockOffset()); return {container_builder_.BfcLineOffset(), - container_builder_.BfcBlockOffset().value()}; + *container_builder_.BfcBlockOffset()}; } NGInputNodeType Node() const { return node_; }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc index 6e979218..97de473 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc
@@ -89,7 +89,7 @@ LayoutUnit()); default_containing_block_.content_size_for_fixed = initial_containing_block_fixed_size - ? initial_containing_block_fixed_size.value() + ? *initial_containing_block_fixed_size : default_containing_block_.content_size_for_absolute; default_containing_block_.container_offset = NGLogicalOffset( @@ -263,7 +263,7 @@ // Step 1 - determine the start_offset. const NGPhysicalOffsetRect& start_rect = - block_info.value.value().start_fragment_union_rect; + block_info.value->start_fragment_union_rect; NGLogicalOffset start_offset = start_rect.offset.ConvertToLogical( container_writing_mode, container_direction, container_builder_physical_size, start_rect.size); @@ -276,7 +276,7 @@ // Step 2 - determine the end_offset. const NGPhysicalOffsetRect& end_rect = - block_info.value.value().end_fragment_union_rect; + block_info.value->end_fragment_union_rect; NGLogicalOffset end_offset = end_rect.offset.ConvertToLogical( container_writing_mode, container_direction, container_builder_physical_size, end_rect.size); @@ -449,9 +449,9 @@ layout_result->PhysicalFragment()->Size().height); if (y.has_value()) { if (IsHorizontalWritingMode(container_writing_mode)) - offset->block_offset = y.value(); + offset->block_offset = *y; else - offset->inline_offset = y.value(); + offset->inline_offset = *y; } // Special case: oof css container is a split inline.
diff --git a/third_party/blink/renderer/core/layout/ng/ng_relative_utils.cc b/third_party/blink/renderer/core/layout/ng/ng_relative_utils.cc index d7b970f..2bdb995 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_relative_utils.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_relative_utils.cc
@@ -43,30 +43,30 @@ right = LayoutUnit(); } if (!left) - left = -right.value(); + left = -*right; if (!right) - right = -left.value(); + right = -*left; if (!top && !bottom) { top = LayoutUnit(); bottom = LayoutUnit(); } if (!top) - top = -bottom.value(); + top = -*bottom; if (!bottom) - bottom = -top.value(); + bottom = -*top; if (IsHorizontalWritingMode(container_writing_mode)) { if (IsLtr(container_direction)) - offset.left = left.value(); + offset.left = *left; else - offset.left = -right.value(); - offset.top = top.value(); + offset.left = -*right; + offset.top = *top; } else { if (IsLtr(container_direction)) - offset.top = top.value(); + offset.top = *top; else - offset.top = -bottom.value(); - offset.left = left.value(); + offset.top = -*bottom; + offset.left = *left; } return offset; }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_text_decoration_offset.cc b/third_party/blink/renderer/core/layout/ng/ng_text_decoration_offset.cc index 0446cfb..9d7badb 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_text_decoration_offset.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_text_decoration_offset.cc
@@ -27,7 +27,7 @@ if (base::Optional<LayoutUnit> baseline = decorating_box_->Baseline(baseline_request)) - offset = baseline.value(); + offset = *baseline; } if (offset == LayoutUnit::Max()) {
diff --git a/third_party/blink/renderer/core/layout/scrollbars_test.cc b/third_party/blink/renderer/core/layout/scrollbars_test.cc index 21f3a385f..b8085aa 100644 --- a/third_party/blink/renderer/core/layout/scrollbars_test.cc +++ b/third_party/blink/renderer/core/layout/scrollbars_test.cc
@@ -1432,6 +1432,10 @@ #else TEST_P(ScrollbarAppearanceTest, NativeScrollbarChangeToMobileByEmulator) { #endif + // TODO(crbug.com/934634): This test fails with LayoutNG. + if (RuntimeEnabledFeatures::LayoutNGEnabled()) + return; + ScopedTestingPlatformSupport<ScrollbarTestingPlatformSupport> platform; bool use_overlay_scrollbar = GetParam();
diff --git a/third_party/blink/renderer/core/loader/empty_clients.h b/third_party/blink/renderer/core/loader/empty_clients.h index b5952bc1..c5c7a5b 100644 --- a/third_party/blink/renderer/core/loader/empty_clients.h +++ b/third_party/blink/renderer/core/loader/empty_clients.h
@@ -46,7 +46,6 @@ #include "third_party/blink/renderer/core/frame/remote_frame_client.h" #include "third_party/blink/renderer/core/page/chrome_client.h" #include "third_party/blink/renderer/core/page/page.h" -#include "third_party/blink/renderer/platform/drag_image.h" #include "third_party/blink/renderer/platform/exported/wrapped_resource_request.h" #include "third_party/blink/renderer/platform/geometry/float_point.h" #include "third_party/blink/renderer/platform/geometry/float_rect.h"
diff --git a/third_party/blink/renderer/core/loader/frame_loader.cc b/third_party/blink/renderer/core/loader/frame_loader.cc index 1d8f9e8..28570537 100644 --- a/third_party/blink/renderer/core/loader/frame_loader.cc +++ b/third_party/blink/renderer/core/loader/frame_loader.cc
@@ -164,11 +164,10 @@ : mojom::FetchCacheMode::kValidateCache; if (!document_loader_ || !document_loader_->GetHistoryItem()) return ResourceRequest(); + ResourceRequest request = document_loader_->GetHistoryItem()->GenerateResourceRequest(cache_mode); - - // Set requestor origin to be the current URL's origin. - request.SetRequestorOrigin(SecurityOrigin::Create(request.Url())); + request.SetRequestorOrigin(frame_->GetSecurityContext()->GetSecurityOrigin()); // ClientRedirectPolicy is an indication that this load was triggered by some // direct interaction with the page. If this reload is not a client redirect,
diff --git a/third_party/blink/renderer/core/loader/ping_loader.cc b/third_party/blink/renderer/core/loader/ping_loader.cc index fa66a5b..bd6b119 100644 --- a/third_party/blink/renderer/core/loader/ping_loader.cc +++ b/third_party/blink/renderer/core/loader/ping_loader.cc
@@ -105,7 +105,7 @@ scoped_refptr<EncodedFormData> entity_body = EncodedFormData::Create(); if (data_->HasBackingFile()) - entity_body->AppendFile(ToFile(data_)->GetPath()); + entity_body->AppendFile(To<File>(data_.Get())->GetPath()); else entity_body->AppendBlob(data_->Uuid(), data_->GetBlobDataHandle());
diff --git a/third_party/blink/renderer/core/loader/text_track_loader.h b/third_party/blink/renderer/core/loader/text_track_loader.h index a10870f4..b3dac32 100644 --- a/third_party/blink/renderer/core/loader/text_track_loader.h +++ b/third_party/blink/renderer/core/loader/text_track_loader.h
@@ -27,8 +27,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_TEXT_TRACK_LOADER_H_ #include "third_party/blink/renderer/core/html/track/vtt/vtt_parser.h" -#include "third_party/blink/renderer/platform/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/loader/fetch/raw_resource.h" namespace blink {
diff --git a/third_party/blink/renderer/core/page/BUILD.gn b/third_party/blink/renderer/core/page/BUILD.gn index f3619c9..670b231e 100644 --- a/third_party/blink/renderer/core/page/BUILD.gn +++ b/third_party/blink/renderer/core/page/BUILD.gn
@@ -22,6 +22,8 @@ "drag_controller.h", "drag_data.cc", "drag_data.h", + "drag_image.cc", + "drag_image.h", "drag_state.h", "event_with_hit_test_results.h", "focus_changed_observer.cc",
diff --git a/third_party/blink/renderer/core/page/drag_controller.cc b/third_party/blink/renderer/core/page/drag_controller.cc index 818638f9..205ec9c 100644 --- a/third_party/blink/renderer/core/page/drag_controller.cc +++ b/third_party/blink/renderer/core/page/drag_controller.cc
@@ -77,11 +77,11 @@ #include "third_party/blink/renderer/core/loader/resource/image_resource_content.h" #include "third_party/blink/renderer/core/page/chrome_client.h" #include "third_party/blink/renderer/core/page/drag_data.h" +#include "third_party/blink/renderer/core/page/drag_image.h" #include "third_party/blink/renderer/core/page/drag_state.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/core/svg/graphics/svg_image_for_container.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" -#include "third_party/blink/renderer/platform/drag_image.h" #include "third_party/blink/renderer/platform/geometry/int_rect.h" #include "third_party/blink/renderer/platform/geometry/int_size.h" #include "third_party/blink/renderer/platform/graphics/bitmap_image.h"
diff --git a/third_party/blink/renderer/core/page/drag_controller_test.cc b/third_party/blink/renderer/core/page/drag_controller_test.cc index 111b2481..fae24496c 100644 --- a/third_party/blink/renderer/core/page/drag_controller_test.cc +++ b/third_party/blink/renderer/core/page/drag_controller_test.cc
@@ -15,12 +15,12 @@ #include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" #include "third_party/blink/renderer/core/page/autoscroll_controller.h" #include "third_party/blink/renderer/core/page/drag_data.h" +#include "third_party/blink/renderer/core/page/drag_image.h" #include "third_party/blink/renderer/core/page/drag_state.h" #include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h" #include "third_party/blink/renderer/core/testing/core_unit_test_helper.h" #include "third_party/blink/renderer/core/testing/sim/sim_request.h" #include "third_party/blink/renderer/core/testing/sim/sim_test.h" -#include "third_party/blink/renderer/platform/drag_image.h" namespace blink {
diff --git a/third_party/blink/renderer/platform/drag_image.cc b/third_party/blink/renderer/core/page/drag_image.cc similarity index 83% rename from third_party/blink/renderer/platform/drag_image.cc rename to third_party/blink/renderer/core/page/drag_image.cc index 904764f1..2e1fedb2 100644 --- a/third_party/blink/renderer/platform/drag_image.cc +++ b/third_party/blink/renderer/core/page/drag_image.cc
@@ -23,7 +23,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "third_party/blink/renderer/platform/drag_image.h" +#include "third_party/blink/renderer/core/page/drag_image.h" #include <algorithm> #include <memory> @@ -53,11 +53,6 @@ #include "third_party/blink/renderer/platform/transforms/affine_transform.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" -#include "third_party/skia/include/core/SkCanvas.h" -#include "third_party/skia/include/core/SkColorSpaceXformCanvas.h" -#include "third_party/skia/include/core/SkImage.h" -#include "third_party/skia/include/core/SkMatrix.h" -#include "third_party/skia/include/core/SkSurface.h" namespace blink { @@ -77,56 +72,6 @@ } // anonymous namespace -PaintImage DragImage::ResizeAndOrientImage( - const PaintImage& image, - ImageOrientation orientation, - FloatSize image_scale, - float opacity, - InterpolationQuality interpolation_quality) { - IntSize size(image.width(), image.height()); - size.Scale(image_scale.Width(), image_scale.Height()); - AffineTransform transform; - if (orientation != kDefaultImageOrientation) { - if (orientation.UsesWidthAsHeight()) - size = size.TransposedSize(); - transform *= orientation.TransformFromDefault(FloatSize(size)); - } - transform.ScaleNonUniform(image_scale.Width(), image_scale.Height()); - - if (size.IsEmpty()) - return PaintImage(); - - if (transform.IsIdentity() && opacity == 1) { - // Nothing to adjust, just use the original. - DCHECK_EQ(image.width(), size.Width()); - DCHECK_EQ(image.height(), size.Height()); - return image; - } - - const SkImageInfo info = - SkImageInfo::MakeN32(size.Width(), size.Height(), kPremul_SkAlphaType, - SkColorSpace::MakeSRGB()); - sk_sp<SkSurface> surface = SkSurface::MakeRaster(info); - if (!surface) - return PaintImage(); - - SkPaint paint; - DCHECK_GE(opacity, 0); - DCHECK_LE(opacity, 1); - paint.setAlpha(opacity * 255); - paint.setFilterQuality(interpolation_quality == kInterpolationNone - ? kNone_SkFilterQuality - : kHigh_SkFilterQuality); - - SkCanvas* canvas = surface->getCanvas(); - canvas->concat(AffineTransformToSkMatrix(transform)); - canvas->drawImage(image.GetSkImage(), 0, 0, &paint); - - return PaintImageBuilder::WithProperties(std::move(image)) - .set_image(surface->makeImageSnapshot(), PaintImage::GetNextContentId()) - .TakePaintImage(); -} - FloatSize DragImage::ClampedImageScale(const IntSize& image_size, const IntSize& size, const IntSize& max_size) { @@ -169,8 +114,8 @@ orientation = ToBitmapImage(image)->CurrentFrameOrientation(); SkBitmap bm; - paint_image = ResizeAndOrientImage(paint_image, orientation, image_scale, - opacity, interpolation_quality); + paint_image = Image::ResizeAndOrientImage( + paint_image, orientation, image_scale, opacity, interpolation_quality); if (!paint_image || !paint_image.GetSkImage()->asLegacyBitmap(&bm)) return nullptr;
diff --git a/third_party/blink/renderer/platform/drag_image.h b/third_party/blink/renderer/core/page/drag_image.h similarity index 87% rename from third_party/blink/renderer/platform/drag_image.h rename to third_party/blink/renderer/core/page/drag_image.h index c57ea8f..b2fbcd0 100644 --- a/third_party/blink/renderer/platform/drag_image.h +++ b/third_party/blink/renderer/core/page/drag_image.h
@@ -23,12 +23,13 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_DRAG_IMAGE_H_ -#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_DRAG_IMAGE_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_DRAG_IMAGE_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_DRAG_IMAGE_H_ #include <memory> #include "base/macros.h" +#include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/geometry/float_size.h" #include "third_party/blink/renderer/platform/geometry/int_size.h" #include "third_party/blink/renderer/platform/graphics/graphics_types.h" @@ -38,7 +39,6 @@ #include "third_party/blink/renderer/platform/wtf/allocator.h" #include "third_party/blink/renderer/platform/wtf/forward.h" #include "third_party/skia/include/core/SkBitmap.h" -#include "third_party/skia/include/core/SkRefCnt.h" namespace blink { @@ -46,7 +46,7 @@ class Image; class KURL; -class PLATFORM_EXPORT DragImage { +class CORE_EXPORT DragImage { USING_FAST_MALLOC(DragImage); public: @@ -74,13 +74,6 @@ void Scale(float scale_x, float scale_y); - static PaintImage ResizeAndOrientImage( - const PaintImage&, - ImageOrientation, - FloatSize image_scale = FloatSize(1, 1), - float opacity = 1.0, - InterpolationQuality = kInterpolationNone); - private: DragImage(const SkBitmap&, float resolution_scale, InterpolationQuality); @@ -93,4 +86,4 @@ } // namespace blink -#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_DRAG_IMAGE_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_DRAG_IMAGE_H_
diff --git a/third_party/blink/renderer/platform/drag_image_test.cc b/third_party/blink/renderer/core/page/drag_image_test.cc similarity index 96% rename from third_party/blink/renderer/platform/drag_image_test.cc rename to third_party/blink/renderer/core/page/drag_image_test.cc index 173177f..a14478b2 100644 --- a/third_party/blink/renderer/platform/drag_image_test.cc +++ b/third_party/blink/renderer/core/page/drag_image_test.cc
@@ -28,7 +28,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "third_party/blink/renderer/platform/drag_image.h" +#include "third_party/blink/renderer/core/page/drag_image.h" #include <memory> #include "base/memory/scoped_refptr.h" @@ -39,10 +39,7 @@ #include "third_party/blink/renderer/platform/graphics/image.h" #include "third_party/blink/renderer/platform/graphics/skia/skia_utils.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" -#include "third_party/skia/include/core/SkCanvas.h" -#include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkImage.h" -#include "third_party/skia/include/core/SkPixelRef.h" #include "third_party/skia/include/core/SkSurface.h" namespace blink {
diff --git a/third_party/blink/renderer/core/page/focus_controller.cc b/third_party/blink/renderer/core/page/focus_controller.cc index 8ef3cd21..93c970a 100644 --- a/third_party/blink/renderer/core/page/focus_controller.cc +++ b/third_party/blink/renderer/core/page/focus_controller.cc
@@ -118,7 +118,7 @@ private: Element* TreeOwner(ContainerNode* node) { - if (ShadowRoot* shadow_root = ToShadowRootOrNull(node)) + if (ShadowRoot* shadow_root = DynamicTo<ShadowRoot>(node)) return &shadow_root->host(); // FIXME: Figure out the right thing for OOPI here. if (Frame* frame = node->GetDocument().GetFrame())
diff --git a/third_party/blink/renderer/core/page/scrolling/snap_coordinator.cc b/third_party/blink/renderer/core/page/scrolling/snap_coordinator.cc index 9ea64b0..d06e52d 100644 --- a/third_party/blink/renderer/core/page/scrolling/snap_coordinator.cc +++ b/third_party/blink/renderer/core/page/scrolling/snap_coordinator.cc
@@ -4,7 +4,6 @@ #include "third_party/blink/renderer/core/page/scrolling/snap_coordinator.h" -#include "cc/input/scroll_snap_data.h" #include "third_party/blink/renderer/core/dom/element.h" #include "third_party/blink/renderer/core/dom/node.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" @@ -52,7 +51,7 @@ } void SnapCoordinator::SnapAreaDidChange(LayoutBox& snap_area, - ScrollSnapAlign scroll_snap_align) { + cc::ScrollSnapAlign scroll_snap_align) { LayoutBox* old_container = snap_area.SnapContainer(); if (scroll_snap_align.alignment_inline == cc::SnapAlignment::kNone && scroll_snap_align.alignment_block == cc::SnapAlignment::kNone) { @@ -89,8 +88,9 @@ : layout_box.GetScrollableArea(); } -static ScrollSnapType GetPhysicalSnapType(const LayoutBox& snap_container) { - ScrollSnapType scroll_snap_type = snap_container.Style()->GetScrollSnapType(); +static cc::ScrollSnapType GetPhysicalSnapType(const LayoutBox& snap_container) { + cc::ScrollSnapType scroll_snap_type = + snap_container.Style()->GetScrollSnapType(); if (scroll_snap_type.axis == cc::SnapAxis::kInline) { if (snap_container.Style()->IsHorizontalWritingMode()) scroll_snap_type.axis = cc::SnapAxis::kX; @@ -111,7 +111,8 @@ if (snap_container.Style()->GetScrollSnapType().is_none) return; - SnapContainerData snap_container_data(GetPhysicalSnapType(snap_container)); + cc::SnapContainerData snap_container_data( + GetPhysicalSnapType(snap_container)); ScrollableArea* scrollable_area = ScrollableAreaForSnapping(snap_container); if (!scrollable_area) @@ -172,10 +173,10 @@ snap_container_map_.Set(&snap_container, snap_container_data); } -static ScrollSnapAlign GetPhysicalAlignment( +static cc::ScrollSnapAlign GetPhysicalAlignment( const ComputedStyle& area_style, const ComputedStyle& container_style) { - ScrollSnapAlign align = area_style.GetScrollSnapAlign(); + cc::ScrollSnapAlign align = area_style.GetScrollSnapAlign(); if (container_style.IsHorizontalWritingMode()) return align; @@ -193,12 +194,12 @@ return align; } -SnapAreaData SnapCoordinator::CalculateSnapAreaData( +cc::SnapAreaData SnapCoordinator::CalculateSnapAreaData( const LayoutBox& snap_area, const LayoutBox& snap_container) { const ComputedStyle* container_style = snap_container.Style(); const ComputedStyle* area_style = snap_area.Style(); - SnapAreaData snap_area_data; + cc::SnapAreaData snap_area_data; // We assume that the snap_container is the snap_area's ancestor in layout // tree, as the snap_container is found by walking up the layout tree in @@ -227,7 +228,8 @@ area_rect.Expand(area_margin); snap_area_data.rect = FloatRect(area_rect); - ScrollSnapAlign align = GetPhysicalAlignment(*area_style, *container_style); + cc::ScrollSnapAlign align = + GetPhysicalAlignment(*area_style, *container_style); snap_area_data.scroll_snap_align = align; snap_area_data.must_snap = @@ -238,12 +240,12 @@ base::Optional<FloatPoint> SnapCoordinator::GetSnapPosition( const LayoutBox& snap_container, - const SnapSelectionStrategy& strategy) const { + const cc::SnapSelectionStrategy& strategy) const { auto iter = snap_container_map_.find(&snap_container); if (iter == snap_container_map_.end()) return base::nullopt; - const SnapContainerData& data = iter->value; + const cc::SnapContainerData& data = iter->value; if (!data.size()) return base::nullopt; @@ -271,8 +273,8 @@ const FloatPoint& end_position, bool scrolled_x, bool scrolled_y) const { - std::unique_ptr<SnapSelectionStrategy> strategy = - SnapSelectionStrategy::CreateForEndPosition( + std::unique_ptr<cc::SnapSelectionStrategy> strategy = + cc::SnapSelectionStrategy::CreateForEndPosition( gfx::ScrollOffset(end_position), scrolled_x, scrolled_y); return PerformSnapping(snap_container, *strategy); } @@ -283,8 +285,8 @@ if (!scrollable_area) return false; FloatPoint current_position = scrollable_area->ScrollPosition(); - std::unique_ptr<SnapSelectionStrategy> strategy = - SnapSelectionStrategy::CreateForDirection( + std::unique_ptr<cc::SnapSelectionStrategy> strategy = + cc::SnapSelectionStrategy::CreateForDirection( gfx::ScrollOffset(current_position), gfx::ScrollOffset(delta.Width(), delta.Height())); return PerformSnapping(snap_container, *strategy); @@ -296,8 +298,8 @@ if (!scrollable_area) return false; FloatPoint current_position = scrollable_area->ScrollPosition(); - std::unique_ptr<SnapSelectionStrategy> strategy = - SnapSelectionStrategy::CreateForEndAndDirection( + std::unique_ptr<cc::SnapSelectionStrategy> strategy = + cc::SnapSelectionStrategy::CreateForEndAndDirection( gfx::ScrollOffset(current_position), gfx::ScrollOffset(delta.Width(), delta.Height())); return PerformSnapping(snap_container, *strategy); @@ -305,7 +307,7 @@ bool SnapCoordinator::PerformSnapping( const LayoutBox& snap_container, - const SnapSelectionStrategy& strategy) const { + const cc::SnapSelectionStrategy& strategy) const { ScrollableArea* scrollable_area = ScrollableAreaForSnapping(snap_container); if (!scrollable_area) return false; @@ -325,8 +327,9 @@ return true; } -void SnapCoordinator::SnapContainerDidChange(LayoutBox& snap_container, - ScrollSnapType scroll_snap_type) { +void SnapCoordinator::SnapContainerDidChange( + LayoutBox& snap_container, + cc::ScrollSnapType scroll_snap_type) { snap_container.SetNeedsPaintPropertyUpdate(); if (scroll_snap_type.is_none) { snap_container_map_.erase(&snap_container); @@ -345,7 +348,7 @@ // container or from existing areas in orphan pool. } -base::Optional<SnapContainerData> SnapCoordinator::GetSnapContainerData( +base::Optional<cc::SnapContainerData> SnapCoordinator::GetSnapContainerData( const LayoutBox& snap_container) const { auto iter = snap_container_map_.find(&snap_container); if (iter != snap_container_map_.end()) {
diff --git a/third_party/blink/renderer/core/page/scrolling/snap_coordinator.h b/third_party/blink/renderer/core/page/scrolling/snap_coordinator.h index 3d811bb..17f27d37 100644 --- a/third_party/blink/renderer/core/page/scrolling/snap_coordinator.h +++ b/third_party/blink/renderer/core/page/scrolling/snap_coordinator.h
@@ -6,9 +6,11 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_SCROLLING_SNAP_COORDINATOR_H_ #include "base/macros.h" +#include "cc/input/scroll_snap_data.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/css/css_primitive_value_mappings.h" #include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/scroll/scroll_snap_data.h" namespace blink { @@ -36,17 +38,17 @@ ~SnapCoordinator(); void Trace(blink::Visitor* visitor) {} - void SnapContainerDidChange(LayoutBox&, ScrollSnapType); - void SnapAreaDidChange(LayoutBox&, ScrollSnapAlign); + void SnapContainerDidChange(LayoutBox&, cc::ScrollSnapType); + void SnapAreaDidChange(LayoutBox&, cc::ScrollSnapAlign); // Returns the SnapContainerData if the snap container has one. - base::Optional<SnapContainerData> GetSnapContainerData( + base::Optional<cc::SnapContainerData> GetSnapContainerData( const LayoutBox& snap_container) const; // Calculate the SnapAreaData for the specific snap area in its snap // container. - SnapAreaData CalculateSnapAreaData(const LayoutBox& snap_area, - const LayoutBox& snap_container); + cc::SnapAreaData CalculateSnapAreaData(const LayoutBox& snap_area, + const LayoutBox& snap_container); // Called by LocalFrameView::PerformPostLayoutTasks(), so that the snap data // are updated whenever a layout happens. @@ -72,7 +74,7 @@ base::Optional<FloatPoint> GetSnapPosition( const LayoutBox& snap_container, - const SnapSelectionStrategy& strategy) const; + const cc::SnapSelectionStrategy& strategy) const; #ifndef NDEBUG void ShowSnapAreaMap(); @@ -83,9 +85,9 @@ private: friend class SnapCoordinatorTest; bool PerformSnapping(const LayoutBox& snap_container, - const SnapSelectionStrategy& strategy) const; + const cc::SnapSelectionStrategy& strategy) const; - HashMap<const LayoutBox*, SnapContainerData> snap_container_map_; + HashMap<const LayoutBox*, cc::SnapContainerData> snap_container_map_; DISALLOW_COPY_AND_ASSIGN(SnapCoordinator); };
diff --git a/third_party/blink/renderer/core/page/scrolling/snap_coordinator_test.cc b/third_party/blink/renderer/core/page/scrolling/snap_coordinator_test.cc index a561dc1..d432d43 100644 --- a/third_party/blink/renderer/core/page/scrolling/snap_coordinator_test.cc +++ b/third_party/blink/renderer/core/page/scrolling/snap_coordinator_test.cc
@@ -325,22 +325,22 @@ GetDocument().UpdateStyleAndLayout(); SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator(); - base::Optional<SnapContainerData> data = + base::Optional<cc::SnapContainerData> data = snap_coordinator->GetSnapContainerData(*scroller_element->GetLayoutBox()); EXPECT_TRUE(data.has_value()); - SnapContainerData actual_container = data.value(); + cc::SnapContainerData actual_container = data.value(); FloatPoint max_position = scrollable_area->ScrollOffsetToPosition( scrollable_area->MaximumScrollOffset()); double width = scroller_element->clientWidth(); double height = scroller_element->clientHeight(); - SnapContainerData expected_container( - ScrollSnapType(false, cc::SnapAxis::kBoth, - cc::SnapStrictness::kMandatory), + cc::SnapContainerData expected_container( + cc::ScrollSnapType(false, cc::SnapAxis::kBoth, + cc::SnapStrictness::kMandatory), gfx::RectF(10, 10, width - 20, height - 20), gfx::ScrollOffset(max_position.X(), max_position.Y())); - SnapAreaData expected_area(ScrollSnapAlign(cc::SnapAlignment::kStart), - gfx::RectF(192, 192, 116, 116), false); + cc::SnapAreaData expected_area(cc::ScrollSnapAlign(cc::SnapAlignment::kStart), + gfx::RectF(192, 192, 116, 116), false); expected_container.AddSnapAreaData(expected_area); EXPECT_EQ_CONTAINER(expected_container, actual_container); @@ -359,22 +359,22 @@ GetDocument().UpdateStyleAndLayout(); SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator(); - base::Optional<SnapContainerData> data = + base::Optional<cc::SnapContainerData> data = snap_coordinator->GetSnapContainerData(*scroller_element->GetLayoutBox()); EXPECT_TRUE(data.has_value()); - SnapContainerData actual_container = data.value(); + cc::SnapContainerData actual_container = data.value(); FloatPoint max_position = scrollable_area->ScrollOffsetToPosition( scrollable_area->MaximumScrollOffset()); double width = scroller_element->clientWidth(); double height = scroller_element->clientHeight(); - SnapContainerData expected_container( - ScrollSnapType(false, cc::SnapAxis::kBoth, - cc::SnapStrictness::kMandatory), + cc::SnapContainerData expected_container( + cc::ScrollSnapType(false, cc::SnapAxis::kBoth, + cc::SnapStrictness::kMandatory), gfx::RectF(10, 10, width - 20, height - 20), gfx::ScrollOffset(max_position.X(), max_position.Y())); - SnapAreaData expected_area(ScrollSnapAlign(cc::SnapAlignment::kStart), - gfx::RectF(192, 192, 116, 116), false); + cc::SnapAreaData expected_area(cc::ScrollSnapAlign(cc::SnapAlignment::kStart), + gfx::RectF(192, 192, 116, 116), false); expected_container.AddSnapAreaData(expected_area); EXPECT_EQ_CONTAINER(expected_container, actual_container); @@ -416,24 +416,24 @@ area_element->setAttribute(kStyleAttr, "scroll-snap-align: start;"); GetDocument().UpdateStyleAndLayout(); SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator(); - base::Optional<SnapContainerData> data = + base::Optional<cc::SnapContainerData> data = snap_coordinator->GetSnapContainerData(*GetDocument().GetLayoutView()); EXPECT_TRUE(data.has_value()); - SnapContainerData actual_container = data.value(); + cc::SnapContainerData actual_container = data.value(); FloatPoint max_position = scrollable_area->ScrollOffsetToPosition( scrollable_area->MaximumScrollOffset()); double width = body->clientWidth(); double height = body->clientHeight(); - SnapContainerData expected_container( - ScrollSnapType(false, cc::SnapAxis::kBoth, - cc::SnapStrictness::kMandatory), + cc::SnapContainerData expected_container( + cc::ScrollSnapType(false, cc::SnapAxis::kBoth, + cc::SnapStrictness::kMandatory), gfx::RectF(0, 0, width, height), gfx::ScrollOffset(max_position.X(), max_position.Y())); - SnapAreaData expected_area(ScrollSnapAlign(cc::SnapAlignment::kStart), - gfx::RectF(200, 200, 100, 100), false); + cc::SnapAreaData expected_area(cc::ScrollSnapAlign(cc::SnapAlignment::kStart), + gfx::RectF(200, 200, 100, 100), false); expected_container.AddSnapAreaData(expected_area); EXPECT_EQ_CONTAINER(expected_container, actual_container); @@ -451,10 +451,10 @@ kStyleAttr, "margin: 3px; border: 10px solid; padding: 4px;"); GetDocument().UpdateStyleAndLayout(); SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator(); - base::Optional<SnapContainerData> data = + base::Optional<cc::SnapContainerData> data = snap_coordinator->GetSnapContainerData(*scroller_element->GetLayoutBox()); EXPECT_TRUE(data.has_value()); - SnapContainerData actual_container = data.value(); + cc::SnapContainerData actual_container = data.value(); ScrollableArea* scrollable_area = scroller_element->GetLayoutBox()->GetScrollableArea(); @@ -465,9 +465,9 @@ double height = scroller_element->clientHeight(); // rect.x = rect.y = scroller.border + scroller.scroll-padding - SnapContainerData expected_container( - ScrollSnapType(false, cc::SnapAxis::kBoth, - cc::SnapStrictness::kMandatory), + cc::SnapContainerData expected_container( + cc::ScrollSnapType(false, cc::SnapAxis::kBoth, + cc::SnapStrictness::kMandatory), gfx::RectF(20, 20, width - 20, height - 20), gfx::ScrollOffset(max_position.X(), max_position.Y())); // rect.x = scroller.border + scroller.padding + area.left + area.margin @@ -478,8 +478,8 @@ // 2 * (area.padding + area.border + area.scroll-margin) // rect.height = area.height + // 2 * (area.padding + area.border + area.scroll-margin) - SnapAreaData expected_area(ScrollSnapAlign(cc::SnapAlignment::kStart), - gfx::RectF(208, 208, 144, 144), false); + cc::SnapAreaData expected_area(cc::ScrollSnapAlign(cc::SnapAlignment::kStart), + gfx::RectF(208, 208, 144, 144), false); expected_container.AddSnapAreaData(expected_area); EXPECT_EQ_CONTAINER(expected_container, actual_container); @@ -494,10 +494,10 @@ GetDocument().UpdateStyleAndLayout(); Element* scroller_element = GetDocument().getElementById("scroller"); SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator(); - base::Optional<SnapContainerData> data = + base::Optional<cc::SnapContainerData> data = snap_coordinator->GetSnapContainerData(*scroller_element->GetLayoutBox()); EXPECT_TRUE(data.has_value()); - SnapContainerData actual_container = data.value(); + cc::SnapContainerData actual_container = data.value(); ScrollableArea* scrollable_area = scroller_element->GetLayoutBox()->GetScrollableArea(); @@ -507,13 +507,13 @@ double width = scroller_element->clientWidth(); double height = scroller_element->clientHeight(); - SnapContainerData expected_container( - ScrollSnapType(false, cc::SnapAxis::kBoth, - cc::SnapStrictness::kMandatory), + cc::SnapContainerData expected_container( + cc::ScrollSnapType(false, cc::SnapAxis::kBoth, + cc::SnapStrictness::kMandatory), gfx::RectF(10, 10, width - 20, height - 20), gfx::ScrollOffset(max_position.X(), max_position.Y())); - SnapAreaData expected_area(ScrollSnapAlign(cc::SnapAlignment::kStart), - gfx::RectF(208, 208, 84, 84), false); + cc::SnapAreaData expected_area(cc::ScrollSnapAlign(cc::SnapAlignment::kStart), + gfx::RectF(208, 208, 84, 84), false); expected_container.AddSnapAreaData(expected_area); EXPECT_EQ_CONTAINER(expected_container, actual_container); @@ -541,10 +541,10 @@ )HTML"); GetDocument().UpdateStyleAndLayout(); SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator(); - base::Optional<SnapContainerData> data = + base::Optional<cc::SnapContainerData> data = snap_coordinator->GetSnapContainerData(*scroller_element->GetLayoutBox()); EXPECT_TRUE(data.has_value()); - SnapContainerData actual_container = data.value(); + cc::SnapContainerData actual_container = data.value(); ScrollableArea* scrollable_area = scroller_element->GetLayoutBox()->GetScrollableArea(); @@ -554,13 +554,14 @@ double width = scroller_element->clientWidth(); double height = scroller_element->clientHeight(); - SnapContainerData expected_container( - ScrollSnapType(false, cc::SnapAxis::kBoth, - cc::SnapStrictness::kMandatory), + cc::SnapContainerData expected_container( + cc::ScrollSnapType(false, cc::SnapAxis::kBoth, + cc::SnapStrictness::kMandatory), gfx::RectF(16, 10, width - 28, height - 24), gfx::ScrollOffset(max_position.X(), max_position.Y())); - SnapAreaData expected_area(ScrollSnapAlign(cc::SnapAlignment::kCenter), - gfx::RectF(192, 198, 112, 108), false); + cc::SnapAreaData expected_area( + cc::ScrollSnapAlign(cc::SnapAlignment::kCenter), + gfx::RectF(192, 198, 112, 108), false); expected_container.AddSnapAreaData(expected_area); EXPECT_EQ_CONTAINER(expected_container, actual_container); @@ -575,10 +576,10 @@ GetDocument().UpdateStyleAndLayout(); Element* scroller_element = GetDocument().getElementById("scroller"); SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator(); - base::Optional<SnapContainerData> data = + base::Optional<cc::SnapContainerData> data = snap_coordinator->GetSnapContainerData(*scroller_element->GetLayoutBox()); EXPECT_TRUE(data.has_value()); - SnapContainerData actual_container = data.value(); + cc::SnapContainerData actual_container = data.value(); ScrollableArea* scrollable_area = scroller_element->GetLayoutBox()->GetScrollableArea(); @@ -587,16 +588,16 @@ double width = scroller_element->clientWidth(); double height = scroller_element->clientHeight(); - SnapContainerData expected_container( - ScrollSnapType(false, cc::SnapAxis::kBoth, - cc::SnapStrictness::kMandatory), + cc::SnapContainerData expected_container( + cc::ScrollSnapType(false, cc::SnapAxis::kBoth, + cc::SnapStrictness::kMandatory), gfx::RectF(10, 10, width - 20, height - 20), gfx::ScrollOffset(max_position.X(), max_position.Y())); // The area is scaled from center, so it pushes the area's top-left corner to // (50, 50). - SnapAreaData expected_area(ScrollSnapAlign(cc::SnapAlignment::kEnd), - gfx::RectF(42, 42, 416, 416), false); + cc::SnapAreaData expected_area(cc::ScrollSnapAlign(cc::SnapAlignment::kEnd), + gfx::RectF(42, 42, 416, 416), false); expected_container.AddSnapAreaData(expected_area); EXPECT_EQ_CONTAINER(expected_container, actual_container); @@ -612,10 +613,10 @@ scroller_element->setAttribute(kStyleAttr, "writing-mode: vertical-rl;"); GetDocument().UpdateStyleAndLayout(); SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator(); - base::Optional<SnapContainerData> data = + base::Optional<cc::SnapContainerData> data = snap_coordinator->GetSnapContainerData(*scroller_element->GetLayoutBox()); EXPECT_TRUE(data.has_value()); - SnapContainerData actual_container = data.value(); + cc::SnapContainerData actual_container = data.value(); ScrollableArea* scrollable_area = scroller_element->GetLayoutBox()->GetScrollableArea(); @@ -625,15 +626,15 @@ double width = scroller_element->clientWidth(); double height = scroller_element->clientHeight(); - SnapContainerData expected_container( - ScrollSnapType(false, cc::SnapAxis::kBoth, - cc::SnapStrictness::kMandatory), + cc::SnapContainerData expected_container( + cc::ScrollSnapType(false, cc::SnapAxis::kBoth, + cc::SnapStrictness::kMandatory), gfx::RectF(10, 10, width - 20, height - 20), gfx::ScrollOffset(max_position.X(), max_position.Y())); // Under vertical-rl writing mode, 'start' should align to the right // and 'end' should align to the left. - SnapAreaData expected_area( - ScrollSnapAlign(cc::SnapAlignment::kStart, cc::SnapAlignment::kEnd), + cc::SnapAreaData expected_area( + cc::ScrollSnapAlign(cc::SnapAlignment::kStart, cc::SnapAlignment::kEnd), gfx::RectF(192, 192, 116, 116), false); expected_container.AddSnapAreaData(expected_area);
diff --git a/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc b/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc index dc8c72b4..4baba33 100644 --- a/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc +++ b/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc
@@ -320,10 +320,13 @@ void ImagePaintTimingDetector::RecordImage(const LayoutObject& object, const PaintLayer& painting_layer) { + // TODO(crbug.com/933479): Use LayoutObject::GeneratingNode() to include + // anonymous objects' rect. Node* node = object.GetNode(); if (!node) return; DOMNodeId node_id = DOMNodeIds::IdForNode(node); + DCHECK_NE(node_id, kInvalidDOMNodeId); if (size_zero_ids_.Contains(node_id)) return; // The node is reattached. @@ -331,15 +334,15 @@ detached_ids_.erase(node_id); if (!id_record_map_.Contains(node_id) && is_recording_) { - LayoutRect invalidated_rect = object.FirstFragment().VisualRect(); + LayoutRect visual_rect = object.FragmentsVisualRectBoundingBox(); // Before the image resource is loaded, <img> has size 0, so we do not // record the first size until the invalidated rect's size becomes // non-empty. - if (invalidated_rect.IsEmpty()) + if (visual_rect.IsEmpty()) return; uint64_t rect_size = frame_view_->GetPaintTimingDetector().CalculateVisualSize( - invalidated_rect, painting_layer); + visual_rect, painting_layer); if (rect_size == 0) { // When rect_size == 0, it either means the image is size 0 or the image // is out of viewport. Either way, we don't track this image anymore, to
diff --git a/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc b/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc index cbf8e77a..85b7ebc 100644 --- a/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc +++ b/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc
@@ -16,7 +16,6 @@ #include "third_party/blink/renderer/platform/scroll/scroll_types.h" #include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" -#include "third_party/blink/renderer/platform/testing/url_test_helpers.h" #include "third_party/blink/renderer/platform/testing/wtf/scoped_mock_clock.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkSurface.h" @@ -124,12 +123,6 @@ ToSVGImageElement(element)->SetImageForTest(content); } - void RegisterMockedHttpURLLoad(const std::string& file_name) { - url_test_helpers::RegisterMockedURLLoadFromBase( - WebString::FromUTF8(base_url_), test::CoreTestDataPath(), - WebString::FromUTF8(file_name)); - } - void SimulateScroll() { GetPaintTimingDetector().NotifyScroll(kUserScroll); } private: @@ -156,7 +149,6 @@ SetBodyInnerHTML(R"HTML( <div></div> )HTML"); - UpdateAllLifecyclePhasesForTest(); ImageRecord* record = FindLargestPaintCandidate(); EXPECT_FALSE(record); } @@ -394,7 +386,6 @@ SetBodyInnerHTML(R"HTML( <div></div> )HTML"); - UpdateAllLifecyclePhasesForTest(); ImageRecord* record = FindLastPaintCandidate(); EXPECT_FALSE(record); } @@ -423,7 +414,6 @@ <img height="7" width="7" id="3"></img> </div> )HTML"); - UpdateAllLifecyclePhasesForTest(); SetImageAndPaint("1", 10, 10); UpdateAllLifecyclePhasesForTest(); clock.Advance(TimeDelta::FromSecondsD(1)); @@ -620,50 +610,44 @@ } TEST_F(ImagePaintTimingDetectorTest, BackgroundImage) { - RegisterMockedHttpURLLoad("white-1x1.png"); SetBodyInnerHTML(R"HTML( <style> div { - background-image: url('white-1x1.png'); + background-image: url(data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==); } </style> <div> place-holder </div> )HTML"); - UpdateAllLifecyclePhasesForTest(); ImageRecord* record = FindLastPaintCandidate(); EXPECT_TRUE(record); EXPECT_EQ(CountRecords(), 1u); } TEST_F(ImagePaintTimingDetectorTest, BackgroundImage_IgnoreBody) { - RegisterMockedHttpURLLoad("white-1x1.png"); SetBodyInnerHTML(R"HTML( <style> body { - background-image: url('white-1x1.png'); + background-image: url(data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==); } </style> <body> </body> )HTML"); - UpdateAllLifecyclePhasesForTest(); EXPECT_EQ(CountRecords(), 0u); } TEST_F(ImagePaintTimingDetectorTest, BackgroundImage_IgnoreHtml) { - RegisterMockedHttpURLLoad("white-1x1.png"); SetBodyInnerHTML(R"HTML( <html> <style> html { - background-image: url('white-1x1.png'); + background-image: url(data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==); } </style> </html> )HTML"); - UpdateAllLifecyclePhasesForTest(); EXPECT_EQ(CountRecords(), 0u); } @@ -678,7 +662,6 @@ place-holder </div> )HTML"); - UpdateAllLifecyclePhasesForTest(); EXPECT_EQ(CountRecords(), 0u); }
diff --git a/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.h b/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.h index 67b4e98..9fb7e2b 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.h +++ b/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.h
@@ -13,14 +13,6 @@ class NGPaintFragment; -// Used for return value of traversing fragment tree. -struct CORE_EXPORT NGPaintFragmentWithContainerOffset { - DISALLOW_NEW(); - NGPaintFragment* fragment; - // Offset relative to container fragment - NGPhysicalOffset container_offset; -}; - // Represents an NGPaintFragment by its parent and its index in the parent's // |Children()| vector. struct CORE_EXPORT NGPaintFragmentTraversalContext {
diff --git a/third_party/blink/renderer/core/paint/object_paint_invalidator_test.cc b/third_party/blink/renderer/core/paint/object_paint_invalidator_test.cc index 8c639ac8..c6b6732 100644 --- a/third_party/blink/renderer/core/paint/object_paint_invalidator_test.cc +++ b/third_party/blink/renderer/core/paint/object_paint_invalidator_test.cc
@@ -76,6 +76,10 @@ if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) return; + // TODO(crbug.com/922645): This test fails with LayoutNG. + if (RuntimeEnabledFeatures::LayoutNGEnabled()) + return; + EnableCompositing(); SetBodyInnerHTML(R"HTML( <div id='compositedContainer' style='position: relative; @@ -159,6 +163,10 @@ if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) return; + // TODO(crbug.com/922645): This test fails with LayoutNG. + if (RuntimeEnabledFeatures::LayoutNGEnabled()) + return; + EnableCompositing(); SetBodyInnerHTML(R"HTML( <div id='compositedContainer' style='position: relative; @@ -223,6 +231,10 @@ if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) return; + // TODO(crbug.com/922645): This test fails with LayoutNG. + if (RuntimeEnabledFeatures::LayoutNGEnabled()) + return; + EnableCompositing(); SetBodyInnerHTML(R"HTML( <span id='span' style='position: relative; will-change: transform'>
diff --git a/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc b/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc index 8f72d7a..98cc98b 100644 --- a/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc +++ b/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc
@@ -46,6 +46,7 @@ #include "base/numerics/checked_math.h" #include "base/single_thread_task_runner.h" +#include "cc/input/scroll_snap_data.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/public/platform/web_scroll_into_view_params.h" @@ -2057,9 +2058,9 @@ } FloatPoint end_point = ScrollOffsetToPosition(new_scroll_offset); - std::unique_ptr<SnapSelectionStrategy> strategy = - SnapSelectionStrategy::CreateForEndPosition(gfx::ScrollOffset(end_point), - true, true); + std::unique_ptr<cc::SnapSelectionStrategy> strategy = + cc::SnapSelectionStrategy::CreateForEndPosition( + gfx::ScrollOffset(end_point), true, true); end_point = GetLayoutBox() ->GetDocument() .GetSnapCoordinator()
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 aaa7b1b7..206cc1cc 100644 --- a/third_party/blink/renderer/core/paint/paint_timing_detector.cc +++ b/third_party/blink/renderer/core/paint/paint_timing_detector.cc
@@ -27,14 +27,9 @@ image_paint_timing_detector_( MakeGarbageCollected<ImagePaintTimingDetector>(frame_view)) {} -void PaintTimingDetector::NotifyPrePaintFinished() { - // The image detector is hooking up the prepaint stage. - image_paint_timing_detector_->OnPrePaintFinished(); -} - void PaintTimingDetector::NotifyPaintFinished() { - // The text detector is hooking up the paint stage. text_paint_timing_detector_->OnPaintFinished(); + image_paint_timing_detector_->OnPrePaintFinished(); } void PaintTimingDetector::NotifyObjectPrePaint( @@ -51,6 +46,7 @@ // Todo(maxlg): add other detectors here. } +// static void PaintTimingDetector::NotifyTextPaint( const Node* node, const PropertyTreeState& current_paint_chunk_properties) { @@ -62,6 +58,7 @@ NotifyTextPaint(*object, current_paint_chunk_properties); } +// static void PaintTimingDetector::NotifyTextPaint( const LayoutObject& object, const PropertyTreeState& current_paint_chunk_properties) {
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 1446645..424614cd 100644 --- a/third_party/blink/renderer/core/paint/paint_timing_detector.h +++ b/third_party/blink/renderer/core/paint/paint_timing_detector.h
@@ -37,7 +37,6 @@ static void NotifyTextPaint(const LayoutObject& object, const PropertyTreeState&); void NotifyNodeRemoved(const LayoutObject& object); - void NotifyPrePaintFinished(); void NotifyPaintFinished(); void NotifyInputEvent(WebInputEvent::Type); bool NeedToNotifyInputOrScroll();
diff --git a/third_party/blink/renderer/core/paint/pre_paint_tree_walk.cc b/third_party/blink/renderer/core/paint/pre_paint_tree_walk.cc index ae3c3bdc..ca32653 100644 --- a/third_party/blink/renderer/core/paint/pre_paint_tree_walk.cc +++ b/third_party/blink/renderer/core/paint/pre_paint_tree_walk.cc
@@ -137,9 +137,6 @@ if (origin_trials::JankTrackingEnabled(frame_view.GetFrame().GetDocument())) frame_view.GetJankTracker().NotifyPrePaintFinished(); - if (RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled()) { - frame_view.GetPaintTimingDetector().NotifyPrePaintFinished(); - } context_storage_.pop_back(); }
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 f69506cf..6b1abd9f 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
@@ -184,6 +184,8 @@ const PropertyTreeState& current_paint_chunk_properties) { if (!is_recording_) return; + // TODO(crbug.com/933479): Use LayoutObject::GeneratingNode() to include + // anonymous objects' rect. Node* node = object.GetNode(); if (!node) return;
diff --git a/third_party/blink/renderer/core/script/document_write_intervention.h b/third_party/blink/renderer/core/script/document_write_intervention.h index b68b5413..3b4961b 100644 --- a/third_party/blink/renderer/core/script/document_write_intervention.h +++ b/third_party/blink/renderer/core/script/document_write_intervention.h
@@ -5,7 +5,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_DOCUMENT_WRITE_INTERVENTION_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_DOCUMENT_WRITE_INTERVENTION_H_ -#include "third_party/blink/renderer/platform/cross_origin_attribute_value.h" +#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h" // document.write() intervention may
diff --git a/third_party/blink/renderer/core/style/computed_style.cc b/third_party/blink/renderer/core/style/computed_style.cc index b93f8a6..609c633 100644 --- a/third_party/blink/renderer/core/style/computed_style.cc +++ b/third_party/blink/renderer/core/style/computed_style.cc
@@ -883,7 +883,6 @@ HasCurrentFilterAnimation() != other.HasCurrentFilterAnimation() || HasCurrentBackdropFilterAnimation() != other.HasCurrentBackdropFilterAnimation() || - HasInlineTransform() != other.HasInlineTransform() || BackfaceVisibility() != other.BackfaceVisibility() || HasWillChangeCompositingHint() != other.HasWillChangeCompositingHint() || UsedTransformStyle3D() != other.UsedTransformStyle3D() ||
diff --git a/third_party/blink/renderer/core/style/computed_style_extra_fields.json5 b/third_party/blink/renderer/core/style/computed_style_extra_fields.json5 index eac0508..4279172 100644 --- a/third_party/blink/renderer/core/style/computed_style_extra_fields.json5 +++ b/third_party/blink/renderer/core/style/computed_style_extra_fields.json5
@@ -833,13 +833,6 @@ field_group: "*", default_value: "false", }, - { - name: "HasInlineTransform", - field_template: "primitive", - type_name: "bool", - field_group: "*", - default_value: "false", - }, // Style adjustment for appearance is disabled when certain properties are set. { name: "HasAuthorBackground",
diff --git a/third_party/blink/renderer/core/style/computed_style_test.cc b/third_party/blink/renderer/core/style/computed_style_test.cc index b3060da..a2e26f8 100644 --- a/third_party/blink/renderer/core/style/computed_style_test.cc +++ b/third_party/blink/renderer/core/style/computed_style_test.cc
@@ -195,17 +195,6 @@ } TEST(ComputedStyleTest, - UpdatePropertySpecificDifferencesCompositingReasonsInlineTransform) { - scoped_refptr<ComputedStyle> style = ComputedStyle::Create(); - scoped_refptr<ComputedStyle> other = ComputedStyle::Clone(*style); - - other->SetHasInlineTransform(true); - StyleDifference diff; - style->UpdatePropertySpecificDifferences(*other, diff); - EXPECT_TRUE(diff.CompositingReasonsChanged()); -} - -TEST(ComputedStyleTest, UpdatePropertySpecificDifferencesCompositingReasonsBackfaceVisibility) { scoped_refptr<ComputedStyle> style = ComputedStyle::Create(); scoped_refptr<ComputedStyle> other = ComputedStyle::Clone(*style);
diff --git a/third_party/blink/renderer/core/svg/svg_path_query.h b/third_party/blink/renderer/core/svg/svg_path_query.h index 046667f..c4b5738 100644 --- a/third_party/blink/renderer/core/svg/svg_path_query.h +++ b/third_party/blink/renderer/core/svg/svg_path_query.h
@@ -21,12 +21,16 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_PATH_QUERY_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_PATH_QUERY_H_ +#include "third_party/blink/renderer/platform/wtf/allocator.h" + namespace blink { class FloatPoint; class SVGPathByteStream; class SVGPathQuery { + STACK_ALLOCATED(); + public: explicit SVGPathQuery(const SVGPathByteStream&);
diff --git a/third_party/blink/renderer/core/testing/internals.cc b/third_party/blink/renderer/core/testing/internals.cc index 992d12c..6d29d691 100644 --- a/third_party/blink/renderer/core/testing/internals.cc +++ b/third_party/blink/renderer/core/testing/internals.cc
@@ -540,14 +540,14 @@ const TreeScope* tree_scope1 = IsA<Document>(node1) ? static_cast<const TreeScope*>(To<Document>(node1)) - : node1->IsShadowRoot() - ? static_cast<const TreeScope*>(ToShadowRoot(node1)) + : IsA<ShadowRoot>(node1) + ? static_cast<const TreeScope*>(To<ShadowRoot>(node1)) : nullptr; const TreeScope* tree_scope2 = IsA<Document>(node2) ? static_cast<const TreeScope*>(To<Document>(node2)) - : node2->IsShadowRoot() - ? static_cast<const TreeScope*>(ToShadowRoot(node2)) + : IsA<ShadowRoot>(node2) + ? static_cast<const TreeScope*>(To<ShadowRoot>(node2)) : nullptr; if (!tree_scope1 || !tree_scope2) { exception_state.ThrowDOMException( @@ -619,37 +619,37 @@ bool Internals::hasShadowInsertionPoint(const Node* root, ExceptionState& exception_state) const { DCHECK(root); - if (!root->IsShadowRoot()) { + if (!IsA<ShadowRoot>(root)) { exception_state.ThrowDOMException( DOMExceptionCode::kInvalidAccessError, "The node argument is not a shadow root."); return false; } - return ToShadowRoot(root)->V0().ContainsShadowElements(); + return To<ShadowRoot>(root)->V0().ContainsShadowElements(); } bool Internals::hasContentElement(const Node* root, ExceptionState& exception_state) const { DCHECK(root); - if (!root->IsShadowRoot()) { + if (!IsA<ShadowRoot>(root)) { exception_state.ThrowDOMException( DOMExceptionCode::kInvalidAccessError, "The node argument is not a shadow root."); return false; } - return ToShadowRoot(root)->V0().ContainsContentElements(); + return To<ShadowRoot>(root)->V0().ContainsContentElements(); } uint32_t Internals::countElementShadow(const Node* root, ExceptionState& exception_state) const { DCHECK(root); - if (!root->IsShadowRoot()) { + if (!IsA<ShadowRoot>(root)) { exception_state.ThrowDOMException( DOMExceptionCode::kInvalidAccessError, "The node argument is not a shadow root."); return 0; } - return ToShadowRoot(root)->ChildShadowRootCount(); + return To<ShadowRoot>(root)->ChildShadowRootCount(); } Node* Internals::nextSiblingInFlatTree(Node* node, @@ -766,14 +766,15 @@ String Internals::shadowRootType(const Node* root, ExceptionState& exception_state) const { DCHECK(root); - if (!root->IsShadowRoot()) { + auto* shadow_root = DynamicTo<ShadowRoot>(root); + if (!shadow_root) { exception_state.ThrowDOMException( DOMExceptionCode::kInvalidAccessError, "The node provided is not a shadow root."); return String(); } - switch (ToShadowRoot(root)->GetType()) { + switch (shadow_root->GetType()) { case ShadowRootType::kUserAgent: return String("UserAgentShadowRoot"); case ShadowRootType::V0:
diff --git a/third_party/blink/renderer/core/testing/sim/sim_canvas.h b/third_party/blink/renderer/core/testing/sim/sim_canvas.h index cf086d5..64a92cd 100644 --- a/third_party/blink/renderer/core/testing/sim/sim_canvas.h +++ b/third_party/blink/renderer/core/testing/sim/sim_canvas.h
@@ -6,6 +6,7 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_SIM_SIM_CANVAS_H_ #include "third_party/blink/renderer/platform/graphics/color.h" +#include "third_party/blink/renderer/platform/wtf/allocator.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/vector.h" #include "third_party/skia/include/core/SkCanvas.h" @@ -24,6 +25,8 @@ }; class Commands { + DISALLOW_NEW(); + public: size_t DrawCount() const { return commands_.size(); } size_t DrawCount(CommandType, const String& color_string = String()) const;
diff --git a/third_party/blink/renderer/core/testing/sim/sim_page.h b/third_party/blink/renderer/core/testing/sim/sim_page.h index f1792ac7..a2c4c57f 100644 --- a/third_party/blink/renderer/core/testing/sim/sim_page.h +++ b/third_party/blink/renderer/core/testing/sim/sim_page.h
@@ -6,12 +6,15 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_SIM_SIM_PAGE_H_ #include "third_party/blink/renderer/platform/heap/persistent.h" +#include "third_party/blink/renderer/platform/wtf/allocator.h" namespace blink { class Page; class SimPage final { + DISALLOW_NEW(); + public: explicit SimPage(); ~SimPage();
diff --git a/third_party/blink/renderer/core/timing/event_timing.h b/third_party/blink/renderer/core/timing/event_timing.h index 59bacd8..f18a3d57 100644 --- a/third_party/blink/renderer/core/timing/event_timing.h +++ b/third_party/blink/renderer/core/timing/event_timing.h
@@ -9,6 +9,7 @@ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/timing/window_performance.h" +#include "third_party/blink/renderer/platform/wtf/allocator.h" namespace blink { @@ -19,6 +20,8 @@ // input latency. // See also: https://github.com/wicg/event-timing class CORE_EXPORT EventTiming final { + USING_FAST_MALLOC(EventTiming); + public: explicit EventTiming(LocalDOMWindow*);
diff --git a/third_party/blink/renderer/core/timing/sub_task_attribution.h b/third_party/blink/renderer/core/timing/sub_task_attribution.h index d34b049..dc0ce764 100644 --- a/third_party/blink/renderer/core/timing/sub_task_attribution.h +++ b/third_party/blink/renderer/core/timing/sub_task_attribution.h
@@ -9,12 +9,15 @@ #include "third_party/blink/renderer/core/dom/dom_high_res_time_stamp.h" #include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/wtf/allocator.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/time.h" namespace blink { class SubTaskAttribution { + USING_FAST_MALLOC(SubTaskAttribution); + public: using EntriesVector = Vector<std::unique_ptr<SubTaskAttribution>>;
diff --git a/third_party/blink/renderer/core/timing/time_clamper.h b/third_party/blink/renderer/core/timing/time_clamper.h index d8644ee..8f29456 100644 --- a/third_party/blink/renderer/core/timing/time_clamper.h +++ b/third_party/blink/renderer/core/timing/time_clamper.h
@@ -8,12 +8,15 @@ #include "base/macros.h" #include "build/build_config.h" #include "third_party/blink/renderer/core/core_export.h" +#include "third_party/blink/renderer/platform/wtf/allocator.h" #include <stdint.h> namespace blink { class CORE_EXPORT TimeClamper { + USING_FAST_MALLOC(TimeClamper); + public: // As site isolation is enabled on desktop platforms, we can safely provide // more timing resolution. Jittering is still enabled everywhere.
diff --git a/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc b/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc index fe5a798..cc5f108 100644 --- a/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc +++ b/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc
@@ -876,7 +876,7 @@ // FIXME: add support for uploading bundles. http_body = EncodedFormData::Create(); if (body->HasBackingFile()) { - File* file = ToFile(body); + auto* file = To<File>(body); if (!file->GetPath().IsEmpty()) http_body->AppendFile(file->GetPath()); else
diff --git a/third_party/blink/renderer/modules/accessibility/BUILD.gn b/third_party/blink/renderer/modules/accessibility/BUILD.gn index ae01f5a..b9c7828c 100644 --- a/third_party/blink/renderer/modules/accessibility/BUILD.gn +++ b/third_party/blink/renderer/modules/accessibility/BUILD.gn
@@ -22,6 +22,8 @@ "ax_list_box_option.h", "ax_media_controls.cc", "ax_media_controls.h", + "ax_media_element.cc", + "ax_media_element.h", "ax_menu_list.cc", "ax_menu_list.h", "ax_menu_list_option.cc",
diff --git a/third_party/blink/renderer/modules/accessibility/ax_media_controls.cc b/third_party/blink/renderer/modules/accessibility/ax_media_controls.cc index bcb6d24..2cd919c9 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_media_controls.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_media_controls.cc
@@ -60,7 +60,6 @@ case kMediaSliderThumb: case kMediaTimelineContainer: - case kMediaOverflowList: return MakeGarbageCollected<AccessibilityMediaControl>(layout_object, ax_object_cache); // Removed as a part of the a11y tree rewrite https://crbug/836549. @@ -103,7 +102,6 @@ switch (ControlType()) { case kMediaSliderThumb: case kMediaTimelineContainer: - case kMediaOverflowList: return QueryString(WebLocalizedString::kAXMediaDefault); case kMediaSlider: // Removed as a part of the a11y tree rewrite https://crbug/836549. @@ -123,7 +121,6 @@ switch (ControlType()) { case kMediaSliderThumb: case kMediaTimelineContainer: - case kMediaOverflowList: return QueryString(WebLocalizedString::kAXMediaDefault); case kMediaSlider: // Removed as a part of the a11y tree rewrite https://crbug/836549. @@ -149,7 +146,6 @@ ax::mojom::Role AccessibilityMediaControl::RoleValue() const { switch (ControlType()) { case kMediaTimelineContainer: - case kMediaOverflowList: return ax::mojom::Role::kGroup; case kMediaSliderThumb:
diff --git a/third_party/blink/renderer/modules/accessibility/ax_media_element.cc b/third_party/blink/renderer/modules/accessibility/ax_media_element.cc new file mode 100644 index 0000000..93b3356 --- /dev/null +++ b/third_party/blink/renderer/modules/accessibility/ax_media_element.cc
@@ -0,0 +1,62 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/modules/accessibility/ax_media_element.h" + +#include "third_party/blink/renderer/core/html/media/html_media_element.h" +#include "third_party/blink/renderer/core/layout/layout_object.h" +#include "third_party/blink/renderer/platform/text/platform_locale.h" + +namespace blink { + +using blink::WebLocalizedString; + +AXObject* AccessibilityMediaElement::Create( + LayoutObject* layout_object, + AXObjectCacheImpl& ax_object_cache) { + DCHECK(layout_object->GetNode()); + return MakeGarbageCollected<AccessibilityMediaElement>(layout_object, + ax_object_cache); +} + +AccessibilityMediaElement::AccessibilityMediaElement( + LayoutObject* layout_object, + AXObjectCacheImpl& ax_object_cache) + : AXLayoutObject(layout_object, ax_object_cache) {} + +String AccessibilityMediaElement::TextAlternative( + bool recursive, + bool in_aria_labelled_by_traversal, + AXObjectSet& visited, + ax::mojom::NameFrom& name_from, + AXRelatedObjectVector* related_objects, + NameSources* name_sources) const { + if (IsUnplayable()) { + HTMLMediaElement* element = + static_cast<HTMLMediaElement*>(layout_object_->GetNode()); + return element->GetLocale().QueryString( + WebLocalizedString::kAXMediaPlaybackError); + } + return AXLayoutObject::TextAlternative( + recursive, in_aria_labelled_by_traversal, visited, name_from, + related_objects, name_sources); +} + +AXRestriction AccessibilityMediaElement::Restriction() const { + if (IsUnplayable()) + return kRestrictionDisabled; + + return AXNodeObject::Restriction(); +} + +bool AccessibilityMediaElement::IsUnplayable() const { + HTMLMediaElement* element = + static_cast<HTMLMediaElement*>(layout_object_->GetNode()); + HTMLMediaElement::NetworkState network_state = element->getNetworkState(); + return (element->error() || + network_state == HTMLMediaElement::kNetworkEmpty || + network_state == HTMLMediaElement::kNetworkNoSource); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/accessibility/ax_media_element.h b/third_party/blink/renderer/modules/accessibility/ax_media_element.h new file mode 100644 index 0000000..a6f6d2b --- /dev/null +++ b/third_party/blink/renderer/modules/accessibility/ax_media_element.h
@@ -0,0 +1,42 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_ACCESSIBILITY_AX_MEDIA_ELEMENT_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_ACCESSIBILITY_AX_MEDIA_ELEMENT_H_ + +#include "base/macros.h" +#include "third_party/blink/renderer/core/html/media/html_media_element.h" +#include "third_party/blink/renderer/modules/accessibility/ax_layout_object.h" + +namespace blink { + +class AXObjectCacheImpl; + +class AccessibilityMediaElement : public AXLayoutObject { + public: + static AXObject* Create(LayoutObject*, AXObjectCacheImpl&); + + AccessibilityMediaElement(LayoutObject*, AXObjectCacheImpl&); + ~AccessibilityMediaElement() override = default; + + // AXLayoutObject overrides. + String TextAlternative(bool recursive, + bool in_aria_labelled_by_traversal, + AXObjectSet& visited, + ax::mojom::NameFrom&, + AXRelatedObjectVector*, + NameSources*) const override; + + // AXNodeObject overrides. + AXRestriction Restriction() const override; + + protected: + bool IsUnplayable() const; + + DISALLOW_COPY_AND_ASSIGN(AccessibilityMediaElement); +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_ACCESSIBILITY_AX_MEDIA_ELEMENT_H_
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc index 92cb9423..e70cfc2 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc
@@ -74,6 +74,7 @@ #include "third_party/blink/renderer/modules/accessibility/ax_list_box.h" #include "third_party/blink/renderer/modules/accessibility/ax_list_box_option.h" #include "third_party/blink/renderer/modules/accessibility/ax_media_controls.h" +#include "third_party/blink/renderer/modules/accessibility/ax_media_element.h" #include "third_party/blink/renderer/modules/accessibility/ax_menu_list.h" #include "third_party/blink/renderer/modules/accessibility/ax_menu_list_option.h" #include "third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.h" @@ -332,6 +333,10 @@ IsHTMLDListElement(node)))) return AXList::Create(layout_object, *this); + // media element + if (node && node->IsMediaElement()) + return AccessibilityMediaElement::Create(layout_object, *this); + // media controls // TODO(836549): Remove for the rest of the controls. if (node && node->IsMediaControlElement() && @@ -962,6 +967,14 @@ ToAXRadioInput(first_obj)->RequestUpdateToNextNode(true); } +void AXObjectCacheImpl::ImageLoaded(LayoutObject* layout_object) { + AXObject* obj = GetOrCreate(layout_object); + if (!obj) + return; + + MarkAXObjectDirty(obj, false); +} + void AXObjectCacheImpl::HandleLayoutComplete(LayoutObject* layout_object) { if (!layout_object) return;
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h index 5a71550dd..1959e6f 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h +++ b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h
@@ -85,6 +85,7 @@ void ListboxActiveIndexChanged(HTMLSelectElement*) override; void LocationChanged(LayoutObject*) override; void RadiobuttonRemovedFromGroup(HTMLInputElement*) override; + void ImageLoaded(LayoutObject*) override; void Remove(AccessibleNode*) override; void Remove(LayoutObject*) override;
diff --git a/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc b/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc index 6112320..42c34be 100644 --- a/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc +++ b/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc
@@ -628,14 +628,15 @@ std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl& cache) const { // Walk up parents until an AXObject can be found. - Node* parent_node = inspected_dom_node.IsShadowRoot() - ? &ToShadowRoot(inspected_dom_node).host() + auto* shadow_root = DynamicTo<ShadowRoot>(inspected_dom_node); + Node* parent_node = shadow_root + ? &shadow_root->host() : FlatTreeTraversal::Parent(inspected_dom_node); AXObject* parent_ax_object = cache.GetOrCreate(parent_node); while (parent_node && !parent_ax_object) { - parent_node = parent_node->IsShadowRoot() - ? &ToShadowRoot(parent_node)->host() - : FlatTreeTraversal::Parent(*parent_node); + shadow_root = DynamicTo<ShadowRoot>(parent_node); + parent_node = shadow_root ? &shadow_root->host() + : FlatTreeTraversal::Parent(*parent_node); parent_ax_object = cache.GetOrCreate(parent_node); }
diff --git a/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client.cc b/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client.cc index 8d3c03c0..c26fe1b 100644 --- a/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client.cc +++ b/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client.cc
@@ -169,15 +169,19 @@ global_scope->UpdateAnimatorsList(*input); } - // Assume animators are stateful. - // TODO(https://crbug.com/914918): Implement filter for detecting stateless - // and stateful animators. Call mutate on stateful and stateless global - // scopes with appropriate predicates. AnimationWorkletGlobalScope* stateful_global_scope = SelectStatefulGlobalScope(); DCHECK(stateful_global_scope); - stateful_global_scope->UpdateAnimators(*input, output.get(), - [](Animator*) { return true; }); + stateful_global_scope->UpdateAnimators( + *input, output.get(), + [](Animator* animator) { return animator->IsStateful(); }); + + AnimationWorkletGlobalScope* stateless_global_scope = + SelectStatelessGlobalScope(); + DCHECK(stateless_global_scope); + stateless_global_scope->UpdateAnimators( + *input, output.get(), + [](Animator* animator) { return !animator->IsStateful(); }); UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES( "Animation.AnimationWorklet.MutateDuration", timer.Elapsed(),
diff --git a/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client_test.cc b/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client_test.cc index 85f36ab..1fc3b46 100644 --- a/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client_test.cc +++ b/third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client_test.cc
@@ -11,6 +11,7 @@ #include "base/test/test_simple_task_runner.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h" #include "third_party/blink/renderer/core/testing/core_unit_test_helper.h" #include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h" #include "third_party/blink/renderer/modules/worklet/worklet_thread_test_common.h" @@ -24,8 +25,6 @@ std::unique_ptr<AnimationWorkletMutatorDispatcherImpl>); void SetMutationUpdate(std::unique_ptr<AnimationWorkletOutput>) override {} - void NotifyAnimationsPending() override {} - void NotifyAnimationsReady() override {} MOCK_METHOD1(SynchronizeAnimatorName, void(const String&)); std::unique_ptr<AnimationWorkletMutatorDispatcherImpl> mutator_; @@ -61,6 +60,111 @@ waitable_event->Signal(); } + // Returns false when a script evaluation error happens. + bool EvaluateScriptModule(AnimationWorkletGlobalScope* global_scope, + const String& source_code) { + ScriptState* script_state = + global_scope->ScriptController()->GetScriptState(); + EXPECT_TRUE(script_state); + ScriptState::Scope scope(script_state); + + const KURL js_url("https://example.com/worklet.js"); + ScriptModule module = ScriptModule::Compile( + script_state->GetIsolate(), source_code, js_url, js_url, + ScriptFetchOptions(), TextPosition::MinimumPosition(), + ASSERT_NO_EXCEPTION); + EXPECT_FALSE(module.IsNull()); + ScriptValue exception = module.Instantiate(script_state); + EXPECT_TRUE(exception.IsEmpty()); + ScriptValue value = module.Evaluate(script_state); + return value.IsEmpty(); + } + + using TestCallback = + void (AnimationWorkletProxyClientTest::*)(WorkerThread*, + AnimationWorkletProxyClient*, + base::WaitableEvent*); + void RunTestOnWorkletThread(TestCallback callback) { + std::unique_ptr<WorkerThread> worklet = + CreateAnimationAndPaintWorkletThread( + &GetDocument(), reporting_proxy_.get(), proxy_client_); + + base::WaitableEvent waitable_event; + PostCrossThreadTask( + *worklet->GetTaskRunner(TaskType::kInternalTest), FROM_HERE, + CrossThreadBind( + callback, CrossThreadUnretained(this), + CrossThreadUnretained(worklet.get()), + CrossThreadPersistent<AnimationWorkletProxyClient>(proxy_client_), + CrossThreadUnretained(&waitable_event))); + waitable_event.Wait(); + waitable_event.Reset(); + + worklet->Terminate(); + worklet->WaitForShutdownForTesting(); + } + + void RunMutateCorrectAnimatorOnWorklet( + WorkerThread* thread, + AnimationWorkletProxyClient* proxy_client, + base::WaitableEvent* waitable_event) { + String source_code = + R"JS( + class Stateful { + animate () {} + state () {} + } + + class Stateless { + animate () {} + } + + registerAnimator('stateful_animator', Stateful); + registerAnimator('stateless_animator', Stateless); + )JS"; + + auto* global_scope = To<AnimationWorkletGlobalScope>(thread->GlobalScope()); + ASSERT_TRUE(EvaluateScriptModule(global_scope, source_code)); + + std::unique_ptr<AnimationWorkletInput> state = + std::make_unique<AnimationWorkletInput>(); + cc::WorkletAnimationId first_animation_id = {1, 1}; + cc::WorkletAnimationId second_animation_id = {1, 2}; + cc::WorkletAnimationId third_animation_id = {1, 3}; + cc::WorkletAnimationId forth_animation_id = {1, 4}; + state->added_and_updated_animations.emplace_back( + first_animation_id, // animation id + "stateless_animator", // name associated with the animation + 5000, // animation's current time + nullptr, // options + 1 // number of keyframe effects + ); + state->added_and_updated_animations.emplace_back( + second_animation_id, "stateful_animator", 5000, nullptr, 1); + state->added_and_updated_animations.emplace_back( + third_animation_id, "stateful_animator", 5000, nullptr, 1); + state->added_and_updated_animations.emplace_back( + forth_animation_id, "stateless_animator", 5000, nullptr, 1); + + std::unique_ptr<AnimationWorkletOutput> output = + proxy_client->Mutate(std::move(state)); + EXPECT_EQ(4u, output->animations.size()); + + auto has_id = [&](WorkletAnimationId id) { + auto found = + std::find_if(output->animations.begin(), output->animations.end(), + [&](auto& it) { return it.worklet_animation_id == id; }); + return found != output->animations.end(); + }; + + EXPECT_TRUE(has_id(first_animation_id)); + EXPECT_TRUE(has_id(second_animation_id)); + EXPECT_TRUE(has_id(third_animation_id)); + EXPECT_TRUE(has_id(forth_animation_id)); + + waitable_event->Signal(); + } + Persistent<AnimationWorkletProxyClient> proxy_client_; std::unique_ptr<MockMutatorClient> mutator_client_; scoped_refptr<base::TestSimpleTaskRunner> mutator_task_runner_; @@ -180,4 +284,9 @@ second_worklet->WaitForShutdownForTesting(); } +TEST_F(AnimationWorkletProxyClientTest, MutateCorrectAnimator) { + RunTestOnWorkletThread( + &AnimationWorkletProxyClientTest::RunMutateCorrectAnimatorOnWorklet); +} + } // namespace blink
diff --git a/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_test.cc b/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_test.cc index 80c2000..df81522 100644 --- a/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_test.cc +++ b/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_test.cc
@@ -290,7 +290,7 @@ is_accelerated_(hint != kPreferNoAcceleration) {} ~FakeCanvasResourceProvider() override = default; bool IsAccelerated() const override { return is_accelerated_; } - scoped_refptr<CanvasResource> ProduceFrame() override { + scoped_refptr<CanvasResource> ProduceCanvasResource() override { return scoped_refptr<CanvasResource>(); } bool SupportsDirectCompositing() const override { return false; } @@ -1254,13 +1254,13 @@ auto frame1_resource = CanvasElement() .GetOrCreateCanvasResourceProvider(kPreferNoAcceleration) - ->ProduceFrame(); + ->ProduceCanvasResource(); EXPECT_TRUE(!!frame1_resource); DrawSomething(); auto frame2_resource = CanvasElement() .GetOrCreateCanvasResourceProvider(kPreferNoAcceleration) - ->ProduceFrame(); + ->ProduceCanvasResource(); EXPECT_TRUE(!!frame2_resource); EXPECT_EQ(frame1_resource.get(), frame2_resource.get()); }
diff --git a/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc b/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc index 67358cd7..5701d2e7 100644 --- a/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc +++ b/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc
@@ -55,7 +55,7 @@ // TODO(fserb): consolidate this with PushFrame SkIRect damage_rect(dirty_rect_for_commit_); dirty_rect_for_commit_.setEmpty(); - Host()->Commit(ProduceFrame(), damage_rect); + Host()->Commit(ProduceCanvasResource(), damage_rect); } // BaseRenderingContext2D implementation @@ -95,11 +95,11 @@ } scoped_refptr<CanvasResource> -OffscreenCanvasRenderingContext2D::ProduceFrame() { +OffscreenCanvasRenderingContext2D::ProduceCanvasResource() { if (!CanCreateCanvas2dResourceProvider()) return nullptr; scoped_refptr<CanvasResource> frame = - GetCanvasResourceProvider()->ProduceFrame(); + GetCanvasResourceProvider()->ProduceCanvasResource(); if (!frame) return nullptr; @@ -112,7 +112,7 @@ return; SkIRect damage_rect(dirty_rect_for_commit_); - Host()->PushFrame(ProduceFrame(), damage_rect); + Host()->PushFrame(ProduceCanvasResource(), damage_rect); dirty_rect_for_commit_.setEmpty(); }
diff --git a/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.h b/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.h index 4046019..1815f0c 100644 --- a/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.h +++ b/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.h
@@ -142,7 +142,7 @@ double* max_width = nullptr); const Font& AccessFont(); - scoped_refptr<CanvasResource> ProduceFrame(); + scoped_refptr<CanvasResource> ProduceCanvasResource(); String ColorSpaceAsString() const override; CanvasPixelFormat PixelFormat() const override;
diff --git a/third_party/blink/renderer/modules/credentialmanager/authenticator_attestation_response.idl b/third_party/blink/renderer/modules/credentialmanager/authenticator_attestation_response.idl index 980b705..6e883b1a 100644 --- a/third_party/blink/renderer/modules/credentialmanager/authenticator_attestation_response.idl +++ b/third_party/blink/renderer/modules/credentialmanager/authenticator_attestation_response.idl
@@ -10,5 +10,5 @@ Exposed=Window ] interface AuthenticatorAttestationResponse : AuthenticatorResponse { [SameObject] readonly attribute ArrayBuffer attestationObject; - [RuntimeEnabled=WebAuthGetTransports] sequence<AuthenticatorTransport> getTransports(); + sequence<AuthenticatorTransport> getTransports(); };
diff --git a/third_party/blink/renderer/modules/csspaint/css_paint_definition.cc b/third_party/blink/renderer/modules/csspaint/css_paint_definition.cc index 444a6279..c961997 100644 --- a/third_party/blink/renderer/modules/csspaint/css_paint_definition.cc +++ b/third_party/blink/renderer/modules/csspaint/css_paint_definition.cc
@@ -5,7 +5,10 @@ #include "third_party/blink/renderer/modules/csspaint/css_paint_definition.h" #include <memory> + #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" +#include "third_party/blink/renderer/bindings/core/v8/v8_no_argument_constructor.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_paint_callback.h" #include "third_party/blink/renderer/core/css/css_computed_style_declaration.h" #include "third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" @@ -14,7 +17,6 @@ #include "third_party/blink/renderer/modules/csspaint/paint_size.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/bindings/v8_binding_macros.h" -#include "third_party/blink/renderer/platform/bindings/v8_object_constructor.h" #include "third_party/blink/renderer/platform/graphics/paint_generated_image.h" namespace blink { @@ -33,8 +35,8 @@ CSSPaintDefinition* CSSPaintDefinition::Create( ScriptState* script_state, - v8::Local<v8::Function> constructor, - v8::Local<v8::Function> paint, + V8NoArgumentConstructor* constructor, + V8PaintCallback* paint, const Vector<CSSPropertyID>& native_invalidation_properties, const Vector<AtomicString>& custom_invalidation_properties, const Vector<CSSSyntaxDescriptor>& input_argument_types, @@ -46,15 +48,15 @@ CSSPaintDefinition::CSSPaintDefinition( ScriptState* script_state, - v8::Local<v8::Function> constructor, - v8::Local<v8::Function> paint, + V8NoArgumentConstructor* constructor, + V8PaintCallback* paint, const Vector<CSSPropertyID>& native_invalidation_properties, const Vector<AtomicString>& custom_invalidation_properties, const Vector<CSSSyntaxDescriptor>& input_argument_types, const PaintRenderingContext2DSettings* context_settings) : script_state_(script_state), - constructor_(script_state->GetIsolate(), constructor), - paint_(script_state->GetIsolate(), paint), + constructor_(constructor), + paint_(paint), did_call_constructor_(false), context_settings_(context_settings) { native_invalidation_properties_ = native_invalidation_properties; @@ -77,14 +79,12 @@ ScriptState::Scope scope(script_state_); MaybeCreatePaintInstance(); + // We may have failed to create an instance, in which case produce an + // invalid image. + if (instance_.IsEmpty()) + return nullptr; v8::Isolate* isolate = script_state_->GetIsolate(); - v8::Local<v8::Value> instance = instance_.NewLocal(isolate); - - // We may have failed to create an instance class, in which case produce an - // invalid image. - if (IsUndefinedOrNull(instance)) - return nullptr; DCHECK(layout_object.GetNode()); CanvasColorParams color_params; @@ -102,31 +102,19 @@ layout_object.GetNode(), native_invalidation_properties_, custom_invalidation_properties_); - Vector<v8::Local<v8::Value>, 4> argv; - if (paint_arguments) { - argv = { - ToV8(rendering_context, script_state_->GetContext()->Global(), isolate), - ToV8(paint_size, script_state_->GetContext()->Global(), isolate), - ToV8(style_map, script_state_->GetContext()->Global(), isolate), - ToV8(*paint_arguments, script_state_->GetContext()->Global(), isolate)}; - } else { - argv = { - ToV8(rendering_context, script_state_->GetContext()->Global(), isolate), - ToV8(paint_size, script_state_->GetContext()->Global(), isolate), - ToV8(style_map, script_state_->GetContext()->Global(), isolate)}; - } + CSSStyleValueVector empty_paint_arguments; + if (!paint_arguments) + paint_arguments = &empty_paint_arguments; - v8::Local<v8::Function> paint = paint_.NewLocal(isolate); - - v8::TryCatch block(isolate); - block.SetVerbose(true); - - V8ScriptRunner::CallFunction(paint, ExecutionContext::From(script_state_), - instance, argv.size(), argv.data(), isolate); + v8::TryCatch try_catch(isolate); + try_catch.SetVerbose(true); // The paint function may have produced an error, in which case produce an // invalid image. - if (block.HasCaught()) { + if (paint_ + ->Invoke(instance_.NewLocal(isolate), rendering_context, paint_size, + style_map, *paint_arguments) + .IsNothing()) { return nullptr; } @@ -137,20 +125,15 @@ void CSSPaintDefinition::MaybeCreatePaintInstance() { if (did_call_constructor_) return; + did_call_constructor_ = true; DCHECK(instance_.IsEmpty()); - v8::Isolate* isolate = script_state_->GetIsolate(); - v8::Local<v8::Function> constructor = constructor_.NewLocal(isolate); - DCHECK(!IsUndefinedOrNull(constructor)); + ScriptValue paint_instance; + if (!constructor_->Construct().To(&paint_instance)) + return; - v8::Local<v8::Value> paint_instance; - if (V8ScriptRunner::CallAsConstructor( - isolate, constructor, ExecutionContext::From(script_state_), 0, {}) - .ToLocal(&paint_instance)) - instance_.Set(isolate, paint_instance); - - did_call_constructor_ = true; + instance_.Set(constructor_->GetIsolate(), paint_instance.V8Value()); } void CSSPaintDefinition::Trace(Visitor* visitor) {
diff --git a/third_party/blink/renderer/modules/csspaint/css_paint_definition.h b/third_party/blink/renderer/modules/csspaint/css_paint_definition.h index c282c56..fb8a9fd2 100644 --- a/third_party/blink/renderer/modules/csspaint/css_paint_definition.h +++ b/third_party/blink/renderer/modules/csspaint/css_paint_definition.h
@@ -12,6 +12,7 @@ #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/platform/bindings/name_client.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" +#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h" #include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h" #include "third_party/blink/renderer/platform/geometry/float_size.h" #include "third_party/blink/renderer/platform/heap/handle.h" @@ -20,8 +21,10 @@ namespace blink { class Image; -class ScriptState; class ImageResourceObserver; +class ScriptState; +class V8NoArgumentConstructor; +class V8PaintCallback; // Represents a javascript class registered on the PaintWorkletGlobalScope by // the author. It will store the properties for invalidation and input argument @@ -32,8 +35,8 @@ public: static CSSPaintDefinition* Create( ScriptState*, - v8::Local<v8::Function> constructor, - v8::Local<v8::Function> paint, + V8NoArgumentConstructor* constructor, + V8PaintCallback* paint, const Vector<CSSPropertyID>&, const Vector<AtomicString>& custom_invalidation_properties, const Vector<CSSSyntaxDescriptor>& input_argument_types, @@ -41,8 +44,8 @@ CSSPaintDefinition( ScriptState*, - v8::Local<v8::Function> constructor, - v8::Local<v8::Function> paint, + V8NoArgumentConstructor* constructor, + V8PaintCallback* paint, const Vector<CSSPropertyID>& native_invalidation_properties, const Vector<AtomicString>& custom_invalidation_properties, const Vector<CSSSyntaxDescriptor>& input_argument_types, @@ -76,13 +79,6 @@ ScriptState* GetScriptState() const { return script_state_; } - v8::Local<v8::Function> ConstructorForTesting(v8::Isolate* isolate) { - return constructor_.NewLocal(isolate); - } - v8::Local<v8::Function> PaintFunctionForTesting(v8::Isolate* isolate) { - return paint_.NewLocal(isolate); - } - virtual void Trace(blink::Visitor* visitor); const char* NameInHeapSnapshot() const override { return "CSSPaintDefinition"; @@ -96,8 +92,8 @@ // This object keeps the class instance object, constructor function and // paint function alive. It participates in wrapper tracing as it holds onto // V8 wrappers. - TraceWrapperV8Reference<v8::Function> constructor_; - TraceWrapperV8Reference<v8::Function> paint_; + TraceWrapperMember<V8NoArgumentConstructor> constructor_; + TraceWrapperMember<V8PaintCallback> paint_; // At the moment there is only ever one instance of a paint class per type. TraceWrapperV8Reference<v8::Value> instance_;
diff --git a/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.cc b/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.cc index bf74acd..64aec736 100644 --- a/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.cc +++ b/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.cc
@@ -6,8 +6,10 @@ #include "third_party/blink/renderer/bindings/core/v8/idl_types.h" #include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h" +#include "third_party/blink/renderer/bindings/core/v8/v8_no_argument_constructor.h" #include "third_party/blink/renderer/bindings/core/v8/v8_object_parser.h" #include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_paint_callback.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_paint_rendering_context_2d_settings.h" #include "third_party/blink/renderer/core/css/css_property_names.h" #include "third_party/blink/renderer/core/css/css_syntax_descriptor.h" @@ -23,6 +25,7 @@ #include "third_party/blink/renderer/modules/csspaint/css_paint_worklet.h" #include "third_party/blink/renderer/modules/csspaint/paint_worklet.h" #include "third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.h" +#include "third_party/blink/renderer/platform/bindings/callback_method_retriever.h" #include "third_party/blink/renderer/platform/bindings/v8_binding_macros.h" namespace blink { @@ -30,7 +33,7 @@ namespace { bool ParseInputArguments(v8::Local<v8::Context> context, - v8::Local<v8::Function> constructor, + v8::Local<v8::Object> constructor, Vector<CSSSyntaxDescriptor>* input_argument_types, ExceptionState* exception_state) { v8::Isolate* isolate = context->GetIsolate(); @@ -67,7 +70,7 @@ PaintRenderingContext2DSettings* ParsePaintRenderingContext2DSettings( v8::Local<v8::Context> context, - v8::Local<v8::Function> constructor, + v8::Local<v8::Object> constructor, ExceptionState* exception_state) { v8::Isolate* isolate = context->GetIsolate(); v8::TryCatch block(isolate); @@ -149,10 +152,11 @@ WorkletGlobalScope::Dispose(); } -void PaintWorkletGlobalScope::registerPaint( - const String& name, - const ScriptValue& constructor_value, - ExceptionState& exception_state) { +void PaintWorkletGlobalScope::registerPaint(const String& name, + V8NoArgumentConstructor* paint_ctor, + ExceptionState& exception_state) { + // https://drafts.css-houdini.org/css-paint-api/#dom-paintworkletglobalscope-registerpaint + RegisterWithProxyClientIfNeeded(); if (name.IsEmpty()) { @@ -162,22 +166,20 @@ if (paint_definitions_.Contains(name)) { exception_state.ThrowDOMException( - DOMExceptionCode::kNotSupportedError, + DOMExceptionCode::kInvalidModificationError, "A class with name:'" + name + "' is already registered."); return; } v8::Local<v8::Context> context = ScriptController()->GetContext(); - DCHECK(constructor_value.V8Value()->IsFunction()); - v8::Local<v8::Function> constructor = - v8::Local<v8::Function>::Cast(constructor_value.V8Value()); + v8::Local<v8::Object> v8_paint_ctor = paint_ctor->CallbackObject(); Vector<CSSPropertyID> native_invalidation_properties; Vector<AtomicString> custom_invalidation_properties; if (!V8ObjectParser::ParseCSSPropertyList( - context, constructor, "inputProperties", + context, v8_paint_ctor, "inputProperties", &native_invalidation_properties, &custom_invalidation_properties, &exception_state)) return; @@ -185,33 +187,35 @@ // Get input argument types. Parse the argument type values only when // cssPaintAPIArguments is enabled. Vector<CSSSyntaxDescriptor> input_argument_types; - if (!ParseInputArguments(context, constructor, &input_argument_types, + if (!ParseInputArguments(context, v8_paint_ctor, &input_argument_types, &exception_state)) return; PaintRenderingContext2DSettings* context_settings = - ParsePaintRenderingContext2DSettings(context, constructor, + ParsePaintRenderingContext2DSettings(context, v8_paint_ctor, &exception_state); if (!context_settings) return; - v8::Local<v8::Object> prototype; - if (!V8ObjectParser::ParsePrototype(context, constructor, &prototype, - &exception_state)) + CallbackMethodRetriever retriever(paint_ctor); + + retriever.GetPrototypeObject(exception_state); + if (exception_state.HadException()) return; - v8::Local<v8::Function> paint; - if (!V8ObjectParser::ParseFunction(context, prototype, "paint", &paint, - &exception_state)) + v8::Local<v8::Function> v8_paint = + retriever.GetMethodOrThrow("paint", exception_state); + if (exception_state.HadException()) return; + V8PaintCallback* paint = V8PaintCallback::Create(v8_paint); CSSPaintDefinition* definition = CSSPaintDefinition::Create( - ScriptController()->GetScriptState(), constructor, paint, + ScriptController()->GetScriptState(), paint_ctor, paint, native_invalidation_properties, custom_invalidation_properties, input_argument_types, context_settings); paint_definitions_.Set(name, definition); - // TODO(xidachen): the following steps should be done with a postTask when + // TODO(xidachen): the following steps should be done with a PostTask when // we move PaintWorklet off main thread. if (!RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled()) { PaintWorklet* paint_worklet =
diff --git a/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.h b/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.h index 958840f..6efb35b 100644 --- a/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.h +++ b/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.h
@@ -17,6 +17,7 @@ class CSSPaintDefinition; class ExceptionState; +class V8NoArgumentConstructor; class WorkerReportingProxy; class MODULES_EXPORT PaintWorkletGlobalScope final : public WorkletGlobalScope { @@ -48,7 +49,7 @@ bool IsPaintWorkletGlobalScope() const final { return true; } void registerPaint(const String& name, - const ScriptValue& constructor_value, + V8NoArgumentConstructor* paint_ctor, ExceptionState&); CSSPaintDefinition* FindDefinition(const String& name);
diff --git a/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.idl b/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.idl index fa669fad..bc86a89 100644 --- a/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.idl +++ b/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.idl
@@ -9,7 +9,9 @@ Global=(Worklet,PaintWorklet) ] interface PaintWorkletGlobalScope : WorkletGlobalScope { [Measure] readonly attribute unrestricted double devicePixelRatio; - // TODO(yukishiino): |paintCtor| should be of callback function type - // (should be: callback T = any ()). - [Measure, RaisesException] void registerPaint(DOMString name, CallbackFunctionTreatedAsScriptValue paintCtor); + [Measure, RaisesException] void registerPaint(DOMString name, NoArgumentConstructor paintCtor); }; + +// Blink-specific type for paint function +// https://drafts.css-houdini.org/css-paint-api/#paint-definition-paint-function +callback PaintCallback = void (PaintRenderingContext2D renderingContext, PaintSize paintSize, StylePropertyMapReadOnly styleMap, sequence<CSSStyleValue> inputArguments);
diff --git a/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_test.cc b/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_test.cc index 5c5740c..c0e952f0 100644 --- a/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_test.cc +++ b/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_test.cc
@@ -138,9 +138,6 @@ CSSPaintDefinition* definition = global_scope->FindDefinition("test"); ASSERT_TRUE(definition); - - EXPECT_TRUE(definition->ConstructorForTesting(isolate)->IsFunction()); - EXPECT_TRUE(definition->PaintFunctionForTesting(isolate)->IsFunction()); } {
diff --git a/third_party/blink/renderer/modules/filesystem/data_transfer_item_file_system.cc b/third_party/blink/renderer/modules/filesystem/data_transfer_item_file_system.cc index a92d715..4a2b0fd6 100644 --- a/third_party/blink/renderer/modules/filesystem/data_transfer_item_file_system.cc +++ b/third_party/blink/renderer/modules/filesystem/data_transfer_item_file_system.cc
@@ -58,7 +58,7 @@ // The clipboard may not be in a readable state. if (!file) return nullptr; - DCHECK(file->IsFile()); + DCHECK(IsA<File>(file)); DOMFileSystem* dom_file_system = DraggedIsolatedFileSystemImpl::GetDOMFileSystem( @@ -71,12 +71,12 @@ // The dropped entries are mapped as top-level entries in the isolated // filesystem. - String virtual_path = DOMFilePath::Append("/", ToFile(file)->name()); + String virtual_path = DOMFilePath::Append("/", To<File>(file)->name()); // FIXME: This involves synchronous file operation. Consider passing file type // data when we dispatch drag event. FileMetadata metadata; - if (!GetFileMetadata(ToFile(file)->GetPath(), metadata)) + if (!GetFileMetadata(To<File>(file)->GetPath(), metadata)) return nullptr; if (metadata.type == FileMetadata::kTypeDirectory)
diff --git a/third_party/blink/renderer/modules/indexeddb/idb_database_error.h b/third_party/blink/renderer/modules/indexeddb/idb_database_error.h index fed841d..a1d390f9 100644 --- a/third_party/blink/renderer/modules/indexeddb/idb_database_error.h +++ b/third_party/blink/renderer/modules/indexeddb/idb_database_error.h
@@ -35,10 +35,13 @@ namespace blink { class IDBDatabaseError { + // The code refers to the DOMException error names table here: + // https://heycam.github.io/webidl/#idl-DOMException-error-names + // TODO(dmurph): Make |code| a DOMExceptionCode public: - explicit IDBDatabaseError(unsigned short code) : code_(code) {} + explicit IDBDatabaseError(int32_t code) : code_(code) {} - IDBDatabaseError(unsigned short code, String message) + IDBDatabaseError(int32_t code, String message) : code_(code), message_(std::move(message)) {} IDBDatabaseError(const IDBDatabaseError& error) = default; @@ -47,11 +50,11 @@ IDBDatabaseError& operator=(const IDBDatabaseError& error) = default; - unsigned short Code() const { return code_; } + int32_t Code() const { return code_; } const String& Message() const { return message_; } private: - unsigned short code_; + int32_t code_; String message_; };
diff --git a/third_party/blink/renderer/modules/media_controls/elements/media_control_element_type.h b/third_party/blink/renderer/modules/media_controls/elements/media_control_element_type.h index e1773e2..fa8ad0a5e 100644 --- a/third_party/blink/renderer/modules/media_controls/elements/media_control_element_type.h +++ b/third_party/blink/renderer/modules/media_controls/elements/media_control_element_type.h
@@ -12,7 +12,6 @@ kMediaSlider, kMediaSliderThumb, kMediaTimelineContainer, - kMediaOverflowList, kMediaIgnore };
diff --git a/third_party/blink/renderer/modules/media_controls/elements/media_control_input_element.cc b/third_party/blink/renderer/modules/media_controls/elements/media_control_input_element.cc index 4ad03e4..d8cce8a 100644 --- a/third_party/blink/renderer/modules/media_controls/elements/media_control_input_element.cc +++ b/third_party/blink/renderer/modules/media_controls/elements/media_control_input_element.cc
@@ -64,6 +64,7 @@ HTMLLabelElement* element = HTMLLabelElement::Create(GetDocument()); element->SetShadowPseudoId( AtomicString("-internal-media-controls-overflow-menu-list-item")); + element->setAttribute(html_names::kRoleAttr, "menuitem"); // Appending a button to a label element ensures that clicks on the label // are passed down to the button, performing the action we'd expect. element->ParserAppendChild(button);
diff --git a/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_list_element.cc b/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_list_element.cc index 710ecb6..1251590 100644 --- a/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_list_element.cc +++ b/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_list_element.cc
@@ -18,9 +18,10 @@ MediaControlOverflowMenuListElement::MediaControlOverflowMenuListElement( MediaControlsImpl& media_controls) - : MediaControlPopupMenuElement(media_controls, kMediaOverflowList) { + : MediaControlPopupMenuElement(media_controls) { SetShadowPseudoId( AtomicString("-internal-media-controls-overflow-menu-list")); + setAttribute(html_names::kRoleAttr, "menu"); CloseOverflowMenu(); }
diff --git a/third_party/blink/renderer/modules/media_controls/elements/media_control_popup_menu_element.cc b/third_party/blink/renderer/modules/media_controls/elements/media_control_popup_menu_element.cc index 0c58255..2c7b671d 100644 --- a/third_party/blink/renderer/modules/media_controls/elements/media_control_popup_menu_element.cc +++ b/third_party/blink/renderer/modules/media_controls/elements/media_control_popup_menu_element.cc
@@ -171,9 +171,8 @@ } MediaControlPopupMenuElement::MediaControlPopupMenuElement( - MediaControlsImpl& media_controls, - MediaControlElementType type) - : MediaControlDivElement(media_controls, type) { + MediaControlsImpl& media_controls) + : MediaControlDivElement(media_controls, kMediaIgnore) { SetIsWanted(false); }
diff --git a/third_party/blink/renderer/modules/media_controls/elements/media_control_popup_menu_element.h b/third_party/blink/renderer/modules/media_controls/elements/media_control_popup_menu_element.h index 4e9d228a..126b011 100644 --- a/third_party/blink/renderer/modules/media_controls/elements/media_control_popup_menu_element.h +++ b/third_party/blink/renderer/modules/media_controls/elements/media_control_popup_menu_element.h
@@ -39,7 +39,7 @@ bool SupportsFocus() const override { return true; } protected: - MediaControlPopupMenuElement(MediaControlsImpl&, MediaControlElementType); + MediaControlPopupMenuElement(MediaControlsImpl&); void SetPosition();
diff --git a/third_party/blink/renderer/modules/media_controls/elements/media_control_text_track_list_element.cc b/third_party/blink/renderer/modules/media_controls/elements/media_control_text_track_list_element.cc index 4b91143..62c635e 100644 --- a/third_party/blink/renderer/modules/media_controls/elements/media_control_text_track_list_element.cc +++ b/third_party/blink/renderer/modules/media_controls/elements/media_control_text_track_list_element.cc
@@ -51,7 +51,7 @@ MediaControlTextTrackListElement::MediaControlTextTrackListElement( MediaControlsImpl& media_controls) - : MediaControlPopupMenuElement(media_controls, kMediaIgnore) { + : MediaControlPopupMenuElement(media_controls) { setAttribute(html_names::kRoleAttr, "menu"); setAttribute(html_names::kAriaLabelAttr, WTF::AtomicString(GetLocale().QueryString(
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc index 9dda85f..288bf4515 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc
@@ -122,11 +122,11 @@ return handler_->Ordered(); } -unsigned short RTCDataChannel::maxRetransmitTime() const { +uint16_t RTCDataChannel::maxRetransmitTime() const { return handler_->MaxRetransmitTime(); } -unsigned short RTCDataChannel::maxRetransmits() const { +uint16_t RTCDataChannel::maxRetransmits() const { return handler_->MaxRetransmits(); } @@ -138,7 +138,7 @@ return handler_->Negotiated(); } -unsigned short RTCDataChannel::id() const { +uint16_t RTCDataChannel::id() const { return handler_->Id(); }
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h index a1e779a7..58fa90d 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h +++ b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h
@@ -76,11 +76,11 @@ bool reliable() const; bool ordered() const; - unsigned short maxRetransmitTime() const; - unsigned short maxRetransmits() const; + uint16_t maxRetransmitTime() const; + uint16_t maxRetransmits() const; String protocol() const; bool negotiated() const; - unsigned short id() const; + uint16_t id() const; String readyState() const; unsigned bufferedAmount() const;
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc index 75a50bd5..c304fd8 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc
@@ -33,11 +33,11 @@ } WebString Label() override { return WebString(""); } bool Ordered() const override { return true; } - unsigned short MaxRetransmitTime() const override { return 0; } - unsigned short MaxRetransmits() const override { return 0; } + uint16_t MaxRetransmitTime() const override { return 0; } + uint16_t MaxRetransmits() const override { return 0; } WebString Protocol() const override { return WebString(""); } bool Negotiated() const override { return false; } - unsigned short Id() const override { return 0; } + uint16_t Id() const override { return 0; } WebRTCDataChannelHandlerClient::ReadyState GetState() const override { return state_;
diff --git a/third_party/blink/renderer/modules/service_worker/thread_safe_script_container_test.cc b/third_party/blink/renderer/modules/service_worker/thread_safe_script_container_test.cc index 50a8368..d321c13 100644 --- a/third_party/blink/renderer/modules/service_worker/thread_safe_script_container_test.cc +++ b/third_party/blink/renderer/modules/service_worker/thread_safe_script_container_test.cc
@@ -6,12 +6,12 @@ #include <memory> +#include "base/synchronization/waitable_event.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/platform/cross_thread_functional.h" #include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h" #include "third_party/blink/renderer/platform/scheduler/public/thread.h" -#include "third_party/blink/renderer/platform/waitable_event.h" #include "third_party/blink/renderer/platform/wtf/functional.h" namespace blink { @@ -29,17 +29,23 @@ reader_thread_(Platform::Current()->CreateThread( ThreadCreationParams(WebThreadType::kTestThread) .SetThreadNameForTest("reader_thread"))), + writer_waiter_(std::make_unique<base::WaitableEvent>( + base::WaitableEvent::ResetPolicy::AUTOMATIC, + base::WaitableEvent::InitialState::NOT_SIGNALED)), + reader_waiter_(std::make_unique<base::WaitableEvent>( + base::WaitableEvent::ResetPolicy::AUTOMATIC, + base::WaitableEvent::InitialState::NOT_SIGNALED)), container_(base::MakeRefCounted<ThreadSafeScriptContainer>()) {} protected: - WaitableEvent* AddOnWriterThread( + base::WaitableEvent* AddOnWriterThread( ThreadSafeScriptContainer::RawScriptData** out_data) { PostCrossThreadTask( *writer_thread_->GetTaskRunner(), FROM_HERE, CrossThreadBind( [](scoped_refptr<ThreadSafeScriptContainer> container, ThreadSafeScriptContainer::RawScriptData** out_data, - WaitableEvent* waiter) { + base::WaitableEvent* waiter) { auto data = ThreadSafeScriptContainer::RawScriptData::Create( String::FromUTF8("utf-8") /* encoding */, Vector<Vector<char>>() /* script_text */, @@ -49,74 +55,74 @@ waiter->Signal(); }, container_, CrossThreadUnretained(out_data), - CrossThreadUnretained(&writer_waiter_))); - return &writer_waiter_; + CrossThreadUnretained(writer_waiter_.get()))); + return writer_waiter_.get(); } - WaitableEvent* OnAllDataAddedOnWriterThread() { + base::WaitableEvent* OnAllDataAddedOnWriterThread() { PostCrossThreadTask( *writer_thread_->GetTaskRunner(), FROM_HERE, CrossThreadBind( [](scoped_refptr<ThreadSafeScriptContainer> container, - WaitableEvent* waiter) { + base::WaitableEvent* waiter) { container->OnAllDataAddedOnIOThread(); waiter->Signal(); }, - container_, CrossThreadUnretained(&writer_waiter_))); - return &writer_waiter_; + container_, CrossThreadUnretained(writer_waiter_.get()))); + return writer_waiter_.get(); } - WaitableEvent* GetStatusOnReaderThread(ScriptStatus* out_status) { + base::WaitableEvent* GetStatusOnReaderThread(ScriptStatus* out_status) { PostCrossThreadTask( *reader_thread_->GetTaskRunner(), FROM_HERE, CrossThreadBind( [](scoped_refptr<ThreadSafeScriptContainer> container, - ScriptStatus* out_status, WaitableEvent* waiter) { + ScriptStatus* out_status, base::WaitableEvent* waiter) { *out_status = container->GetStatusOnWorkerThread(KURL(kKeyUrl)); waiter->Signal(); }, container_, CrossThreadUnretained(out_status), - CrossThreadUnretained(&reader_waiter_))); - return &reader_waiter_; + CrossThreadUnretained(reader_waiter_.get()))); + return reader_waiter_.get(); } - WaitableEvent* WaitOnReaderThread(bool* out_exists) { + base::WaitableEvent* WaitOnReaderThread(bool* out_exists) { PostCrossThreadTask( *reader_thread_->GetTaskRunner(), FROM_HERE, CrossThreadBind( [](scoped_refptr<ThreadSafeScriptContainer> container, - bool* out_exists, WaitableEvent* waiter) { + bool* out_exists, base::WaitableEvent* waiter) { *out_exists = container->WaitOnWorkerThread(KURL(kKeyUrl)); waiter->Signal(); }, container_, CrossThreadUnretained(out_exists), - CrossThreadUnretained(&reader_waiter_))); - return &reader_waiter_; + CrossThreadUnretained(reader_waiter_.get()))); + return reader_waiter_.get(); } - WaitableEvent* TakeOnReaderThread( + base::WaitableEvent* TakeOnReaderThread( ThreadSafeScriptContainer::RawScriptData** out_data) { PostCrossThreadTask( *reader_thread_->GetTaskRunner(), FROM_HERE, CrossThreadBind( [](scoped_refptr<ThreadSafeScriptContainer> container, ThreadSafeScriptContainer::RawScriptData** out_data, - WaitableEvent* waiter) { + base::WaitableEvent* waiter) { auto data = container->TakeOnWorkerThread(KURL(kKeyUrl)); *out_data = data.get(); waiter->Signal(); }, container_, CrossThreadUnretained(out_data), - CrossThreadUnretained(&reader_waiter_))); - return &reader_waiter_; + CrossThreadUnretained(reader_waiter_.get()))); + return reader_waiter_.get(); } private: std::unique_ptr<Thread> writer_thread_; std::unique_ptr<Thread> reader_thread_; - WaitableEvent writer_waiter_; - WaitableEvent reader_waiter_; + std::unique_ptr<base::WaitableEvent> writer_waiter_; + std::unique_ptr<base::WaitableEvent> reader_waiter_; scoped_refptr<ThreadSafeScriptContainer> container_; }; @@ -131,10 +137,10 @@ ThreadSafeScriptContainer::RawScriptData* added_data; { bool result = false; - WaitableEvent* pending_wait = WaitOnReaderThread(&result); + base::WaitableEvent* pending_wait = WaitOnReaderThread(&result); // This should not be signaled until data is added. EXPECT_FALSE(pending_wait->IsSignaled()); - WaitableEvent* pending_write = AddOnWriterThread(&added_data); + base::WaitableEvent* pending_write = AddOnWriterThread(&added_data); pending_wait->Wait(); pending_write->Wait(); EXPECT_TRUE(result); @@ -196,10 +202,11 @@ { bool result = true; - WaitableEvent* pending_wait = WaitOnReaderThread(&result); + base::WaitableEvent* pending_wait = WaitOnReaderThread(&result); // This should not be signaled until OnAllDataAdded is called. EXPECT_FALSE(pending_wait->IsSignaled()); - WaitableEvent* pending_on_all_data_added = OnAllDataAddedOnWriterThread(); + base::WaitableEvent* pending_on_all_data_added = + OnAllDataAddedOnWriterThread(); pending_wait->Wait(); pending_on_all_data_added->Wait(); // Aborted wait should return false.
diff --git a/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc b/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc index 80b2d9b..a7a2c9f 100644 --- a/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc +++ b/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc
@@ -765,7 +765,7 @@ if (PaintRenderingResultsToCanvas(kBackBuffer)) { if (Host()->GetOrCreateCanvasResourceProvider(kPreferAcceleration)) { - Host()->Commit(Host()->ResourceProvider()->ProduceFrame(), + Host()->Commit(Host()->ResourceProvider()->ProduceCanvasResource(), SkIRect::MakeWH(width, height)); } } @@ -1388,7 +1388,7 @@ int height = GetDrawingBuffer()->Size().Height(); if (PaintRenderingResultsToCanvas(kBackBuffer)) { if (Host()->GetOrCreateCanvasResourceProvider(kPreferAcceleration)) { - Host()->PushFrame(Host()->ResourceProvider()->ProduceFrame(), + Host()->PushFrame(Host()->ResourceProvider()->ProduceCanvasResource(), SkIRect::MakeWH(width, height)); } }
diff --git a/third_party/blink/renderer/platform/BUILD.gn b/third_party/blink/renderer/platform/BUILD.gn index 95c652e..89bf1b27 100644 --- a/third_party/blink/renderer/platform/BUILD.gn +++ b/third_party/blink/renderer/platform/BUILD.gn
@@ -485,7 +485,6 @@ "content_setting_callbacks.cc", "content_setting_callbacks.h", "cpu/mips/common_macros_msa.h", - "cross_origin_attribute_value.h", "cross_thread_copier.cc", "cross_thread_copier.h", "cross_thread_functional.h", @@ -498,8 +497,6 @@ "data_resource_helper.h", "date_components.cc", "date_components.h", - "drag_image.cc", - "drag_image.h", "exported/file_path_conversion.cc", "exported/interface_registry.cc", "exported/mediastream/media_stream_audio_source.cc", @@ -1214,6 +1211,9 @@ "mhtml/mhtml_archive.h", "mhtml/mhtml_parser.cc", "mhtml/mhtml_parser.h", + "mhtml/serialized_resource.h", + "mhtml/shared_buffer_chunk_reader.cc", + "mhtml/shared_buffer_chunk_reader.h", "mojo/big_string_mojom_traits.cc", "mojo/big_string_mojom_traits.h", "mojo/bluetooth_struct_traits.cc", @@ -1255,11 +1255,8 @@ "scroll/scroll_alignment.h", "scroll/scroll_snap_data.h", "scroll/scroll_types.h", - "serialized_resource.h", "shared_buffer.cc", "shared_buffer.h", - "shared_buffer_chunk_reader.cc", - "shared_buffer_chunk_reader.h", "speech/platform_speech_synthesis_utterance.cc", "speech/platform_speech_synthesis_utterance.h", "speech/platform_speech_synthesis_voice.cc", @@ -1366,8 +1363,6 @@ "transforms/translate_transform_operation.h", "uuid.cc", "uuid.h", - "waitable_event.cc", - "waitable_event.h", "web_gesture_event.cc", "web_icon_sizes_parser.cc", "web_mouse_event.cc", @@ -1674,7 +1669,6 @@ "audio/vector_math_test.cc", "bindings/parkable_string_test.cc", "bindings/runtime_call_stats_test.cc", - "drag_image_test.cc", "exported/file_path_conversion_test.cc", "exported/notification_data_conversions_test.cc", "exported/web_canonical_cookie_test.cc",
diff --git a/third_party/blink/renderer/platform/bindings/parkable_string_test.cc b/third_party/blink/renderer/platform/bindings/parkable_string_test.cc index 809f1d7..6bc9a1f 100644 --- a/third_party/blink/renderer/platform/bindings/parkable_string_test.cc +++ b/third_party/blink/renderer/platform/bindings/parkable_string_test.cc
@@ -548,7 +548,7 @@ ParkableString parkable(MakeLargeString().ReleaseImpl()); EXPECT_TRUE(parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways)); // A main thread task is posted once compression is done. - while (!scoped_task_environment_.MainThreadHasPendingTask()) { + while (scoped_task_environment_.GetPendingMainThreadTaskCount() == 0) { parkable.Lock(); parkable.ToString(); parkable.Unlock(); @@ -735,7 +735,7 @@ protected: void WaitForAging() { - ASSERT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_GT(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); scoped_task_environment_.FastForwardBy(base::TimeDelta::FromSeconds( ParkableStringManager::kAgingIntervalInSeconds)); RunPostedTasks(); @@ -748,8 +748,9 @@ } void TearDown() override { - while (scoped_task_environment_.MainThreadHasPendingTask()) + while (scoped_task_environment_.GetPendingMainThreadTaskCount() != 0) { WaitForAging(); + } ParkableStringTestBase::TearDown(); } @@ -811,9 +812,9 @@ TEST_F(ParkableStringForegroundParkingTest, AgingTicksStopsAndRestarts) { ParkableString parkable(MakeLargeString().ReleaseImpl()); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_GT(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); WaitForAging(); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_GT(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); WaitForAging(); // Nothing more to do, the tick is not re-scheduled. WaitForAging(); @@ -821,7 +822,7 @@ // Unparking, the tick restarts. parkable.ToString(); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_GT(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); WaitForAging(); WaitForAging(); // And stops again. 2 ticks to park the string (age, then park), and one @@ -840,18 +841,18 @@ ParkableString parkable(MakeLargeString().ReleaseImpl()); String retained = parkable.ToString(); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_GT(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); WaitForAging(); // The only string is referenced externally, nothing aging can change. CheckOnlyCpuCostTaskRemains(); ParkableString parkable2(MakeLargeString().ReleaseImpl()); WaitForAging(); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_GT(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); WaitForAging(); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_GT(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); EXPECT_TRUE(parkable2.Impl()->is_parked()); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_GT(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); WaitForAging(); // Once |parkable2| has been parked, back to the case where the only // remaining strings are referenced externally. @@ -872,7 +873,7 @@ parkable1.ToString(); parkable2.ToString(); - EXPECT_TRUE(scoped_task_environment_.MainThreadHasPendingTask()); + EXPECT_GT(scoped_task_environment_.GetPendingMainThreadTaskCount(), 0u); // Aging task + stats. EXPECT_EQ(2u, scoped_task_environment_.GetPendingMainThreadTaskCount()); }
diff --git a/third_party/blink/renderer/platform/exported/notification_data_conversions.cc b/third_party/blink/renderer/platform/exported/notification_data_conversions.cc index d5d3613..e8931a41 100644 --- a/third_party/blink/renderer/platform/exported/notification_data_conversions.cc +++ b/third_party/blink/renderer/platform/exported/notification_data_conversions.cc
@@ -18,18 +18,7 @@ const PlatformNotificationData& platform_data) { WebNotificationData web_data; web_data.title = WebString::FromUTF16(platform_data.title); - switch (platform_data.direction) { - case PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT: - web_data.direction = mojom::NotificationDirection::LEFT_TO_RIGHT; - break; - case PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT: - web_data.direction = mojom::NotificationDirection::RIGHT_TO_LEFT; - break; - case PlatformNotificationData::DIRECTION_AUTO: - web_data.direction = mojom::NotificationDirection::AUTO; - break; - } - + web_data.direction = platform_data.direction; web_data.lang = WebString::FromUTF8(platform_data.lang); web_data.body = WebString::FromUTF16(platform_data.body); web_data.tag = WebString::FromUTF8(platform_data.tag);
diff --git a/third_party/blink/renderer/platform/exported/notification_data_conversions_test.cc b/third_party/blink/renderer/platform/exported/notification_data_conversions_test.cc index dc422ef..4aae5ca 100644 --- a/third_party/blink/renderer/platform/exported/notification_data_conversions_test.cc +++ b/third_party/blink/renderer/platform/exported/notification_data_conversions_test.cc
@@ -48,7 +48,7 @@ PlatformNotificationData platform_data; platform_data.title = base::ASCIIToUTF16(kNotificationTitle); - platform_data.direction = PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT; + platform_data.direction = mojom::NotificationDirection::LEFT_TO_RIGHT; platform_data.lang = kNotificationLang; platform_data.body = base::ASCIIToUTF16(kNotificationBody); platform_data.tag = kNotificationTag;
diff --git a/third_party/blink/renderer/platform/exported/web_runtime_features.cc b/third_party/blink/renderer/platform/exported/web_runtime_features.cc index 6efbdf93..ad41e3e 100644 --- a/third_party/blink/renderer/platform/exported/web_runtime_features.cc +++ b/third_party/blink/renderer/platform/exported/web_runtime_features.cc
@@ -564,10 +564,6 @@ RuntimeEnabledFeatures::SetWebAuthEnabled(enable); } -void WebRuntimeFeatures::EnableWebAuthGetTransports(bool enable) { - RuntimeEnabledFeatures::SetWebAuthGetTransportsEnabled(enable); -} - void WebRuntimeFeatures::EnableClientPlaceholdersForServerLoFi(bool enable) { RuntimeEnabledFeatures::SetClientPlaceholdersForServerLoFiEnabled(enable); }
diff --git a/third_party/blink/renderer/platform/graphics/DEPS b/third_party/blink/renderer/platform/graphics/DEPS index a5db764..46c6bdc 100644 --- a/third_party/blink/renderer/platform/graphics/DEPS +++ b/third_party/blink/renderer/platform/graphics/DEPS
@@ -9,6 +9,7 @@ "+base/threading/sequenced_task_runner_handle.h", "+base/threading/thread_restrictions.h", "+base/barrier_closure.h", + "+base/callback_helpers.h", "+cc", "+components/viz/client", "+components/viz/common", @@ -30,7 +31,6 @@ "+services/ws/public/cpp/gpu/context_provider_command_buffer.h", "+third_party/blink/renderer/platform/cpu/mips/common_macros_msa.h", "+third_party/blink/renderer/platform/cross_thread_functional.h", - "+third_party/blink/renderer/platform/drag_image.h", "+third_party/blink/renderer/platform/fonts", "+third_party/blink/renderer/platform/geometry", "+third_party/blink/renderer/platform/heap",
diff --git a/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.cc b/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.cc index 2c08c50..aa011e9 100644 --- a/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.cc +++ b/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.cc
@@ -5,6 +5,7 @@ #include "third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.h" #include "base/barrier_closure.h" +#include "base/callback_helpers.h" #include "base/metrics/histogram_macros.h" #include "base/synchronization/waitable_event.h" #include "base/timer/elapsed_timer.h" @@ -266,23 +267,30 @@ scoped_refptr<base::SingleThreadTaskRunner> worklet_queue = pair.value; int worklet_id = mutator->GetWorkletId(); DCHECK(!worklet_queue->BelongsToCurrentThread()); + + // Wrap the barrier closure in a ScopedClosureRunner to guarantee it runs + // even if the posted task does not run. + auto on_done_runner = + std::make_unique<base::ScopedClosureRunner>(on_mutator_done); + auto it = mutator_input_map_.find(worklet_id); if (it == mutator_input_map_.end()) { - // No input to process. - on_mutator_done.Run(); + // Here the on_done_runner goes out of scope which causes the barrier + // closure to run. continue; } + PostCrossThreadTask( *worklet_queue, FROM_HERE, CrossThreadBind( [](AnimationWorkletMutator* mutator, std::unique_ptr<AnimationWorkletInput> input, scoped_refptr<OutputVectorRef> outputs, int index, - WTF::CrossThreadClosure on_mutator_done) { + std::unique_ptr<base::ScopedClosureRunner> on_done_runner) { std::unique_ptr<AnimationWorkletOutput> output = mutator ? mutator->Mutate(std::move(input)) : nullptr; outputs->get()[index] = std::move(output); - on_mutator_done.Run(); + on_done_runner->RunAndReset(); }, // The mutator is created and destroyed on the worklet thread. WrapCrossThreadWeakPersistent(mutator), @@ -292,7 +300,7 @@ // on the host thread. It can outlive the dispatcher during shutdown // of a process with a running animation. outputs_, next_request_index++, - WTF::Passed(WTF::CrossThreadClosure(on_mutator_done)))); + WTF::Passed(std::move(on_done_runner)))); } }
diff --git a/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl_test.cc b/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl_test.cc index d77bd6fe..50193ea 100644 --- a/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl_test.cc +++ b/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl_test.cc
@@ -323,6 +323,28 @@ Mock::VerifyAndClearExpectations(client_.get()); } +TEST_F(AnimationWorkletMutatorDispatcherImplTest, + DispatcherShouldNotHangWhenMutatorGoesAway) { + // Create a thread to run mutator tasks. + std::unique_ptr<Thread> first_thread = CreateThread("FirstAnimationThread"); + MockAnimationWorkletMutator* first_mutator = + MakeGarbageCollected<MockAnimationWorkletMutator>( + first_thread->GetTaskRunner()); + + mutator_->RegisterAnimationWorkletMutator(first_mutator, + first_thread->GetTaskRunner()); + + EXPECT_CALL(*first_mutator, GetWorkletId()).WillRepeatedly(Return(11)); + EXPECT_CALL(*client_, SetMutationUpdateRef(_)).Times(0); + + // Shutdown the thread so its task runner no longer executes tasks. + first_thread.reset(); + + mutator_->MutateSynchronously(CreateTestMutatorInput()); + + Mock::VerifyAndClearExpectations(client_.get()); +} + // ----------------------------------------------------------------------- // Asynchronous version of tests.
diff --git a/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc b/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc index 6f5e4f3d..3e55322 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc
@@ -585,7 +585,8 @@ if (!GetOrCreateResourceProvider()) return false; - scoped_refptr<CanvasResource> frame = ResourceProvider()->ProduceFrame(); + scoped_refptr<CanvasResource> frame = + ResourceProvider()->ProduceCanvasResource(); if (!frame || !frame->IsValid()) return false;
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher_test.cc b/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher_test.cc index 7520d04f..a5f8f71 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher_test.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher_test.cc
@@ -57,7 +57,7 @@ public ::testing::WithParamInterface<TestParams> { public: void DispatchOneFrame() { - dispatcher_->DispatchFrame(resource_provider_->ProduceFrame(), + dispatcher_->DispatchFrame(resource_provider_->ProduceCanvasResource(), base::TimeTicks(), SkIRect::MakeEmpty(), false /* needs_vertical_flip */, false /* is-opaque */);
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc index 67baebc1..00f6a7c 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc
@@ -64,8 +64,9 @@ } protected: - scoped_refptr<CanvasResource> ProduceFrame() override { - TRACE_EVENT0("blink", "CanvasResourceProviderTexture::ProduceFrame"); + scoped_refptr<CanvasResource> ProduceCanvasResource() override { + TRACE_EVENT0("blink", + "CanvasResourceProviderTexture::ProduceCanvasResource"); DCHECK(GetSkSurface()); if (IsGpuContextLost()) @@ -174,9 +175,10 @@ FilterQuality(), is_accelerated); } - scoped_refptr<CanvasResource> ProduceFrame() final { - TRACE_EVENT0("blink", - "CanvasResourceProviderTextureGpuMemoreBuffer::ProduceFrame"); + scoped_refptr<CanvasResource> ProduceCanvasResource() final { + TRACE_EVENT0( + "blink", + "CanvasResourceProviderTextureGpuMemoreBuffer::ProduceCanvasResource"); DCHECK(GetSkSurface()); if (IsGpuContextLost()) @@ -185,7 +187,7 @@ scoped_refptr<CanvasResource> output_resource = NewOrRecycledResource(); if (!output_resource) { // GpuMemoryBuffer creation failed, fallback to Texture resource - return CanvasResourceProviderTexture::ProduceFrame(); + return CanvasResourceProviderTexture::ProduceCanvasResource(); } auto paint_image = MakeImageSnapshot(); @@ -233,7 +235,7 @@ bool SupportsDirectCompositing() const override { return false; } private: - scoped_refptr<CanvasResource> ProduceFrame() override { + scoped_refptr<CanvasResource> ProduceCanvasResource() override { return nullptr; // Does not support direct compositing } @@ -286,9 +288,10 @@ FilterQuality(), is_accelerated); } - scoped_refptr<CanvasResource> ProduceFrame() final { - TRACE_EVENT0("blink", - "CanvasResourceProviderBitmapGpuMemoryBuffer::ProduceFrame"); + scoped_refptr<CanvasResource> ProduceCanvasResource() final { + TRACE_EVENT0( + "blink", + "CanvasResourceProviderBitmapGpuMemoryBuffer::ProduceCanvasResource"); DCHECK(GetSkSurface()); @@ -341,7 +344,7 @@ CreateWeakPtr(), FilterQuality()); } - scoped_refptr<CanvasResource> ProduceFrame() final { + scoped_refptr<CanvasResource> ProduceCanvasResource() final { DCHECK(GetSkSurface()); scoped_refptr<CanvasResource> output_resource = NewOrRecycledResource(); if (!output_resource) @@ -401,9 +404,10 @@ return resource_; } - scoped_refptr<CanvasResource> ProduceFrame() final { - TRACE_EVENT0("blink", - "CanvasResourceProviderDirectGpuMemoryBuffer::ProduceFrame"); + scoped_refptr<CanvasResource> ProduceCanvasResource() final { + TRACE_EVENT0( + "blink", + "CanvasResourceProviderDirectGpuMemoryBuffer::ProduceCanvasResource"); if (IsGpuContextLost()) return nullptr; FlushSkia(); @@ -495,8 +499,9 @@ } protected: - scoped_refptr<CanvasResource> ProduceFrame() override { - TRACE_EVENT0("blink", "CanvasResourceProviderSharedImage::ProduceFrame"); + scoped_refptr<CanvasResource> ProduceCanvasResource() override { + TRACE_EVENT0("blink", + "CanvasResourceProviderSharedImage::ProduceCanvasResource"); scoped_refptr<CanvasResource> resource_snapshot = resource_; @@ -549,10 +554,10 @@ scoped_refptr<CanvasResource> resource_; }; -// This class does nothing except answering to ProduceFrame() by piping it to -// NewOrRecycledResource(). This ResourceProvider is meant to be used with an -// imported external CanvasResource, and all drawing and lifetime logic must be -// kept at a higher level. +// This class does nothing except answering to ProduceCanvasResource() by piping +// it to NewOrRecycledResource(). This ResourceProvider is meant to be used +// with an imported external CanvasResource, and all drawing and lifetime logic +// must be kept at a higher level. class CanvasResourceProviderPassThrough final : public CanvasResourceProvider { public: CanvasResourceProviderPassThrough( @@ -580,7 +585,7 @@ return nullptr; } - scoped_refptr<CanvasResource> ProduceFrame() final { + scoped_refptr<CanvasResource> ProduceCanvasResource() final { return NewOrRecycledResource(); }
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h index 4659d39..b574c3d8 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h
@@ -89,8 +89,8 @@ // Use Snapshot() for capturing a frame that is intended to be displayed via // the compositor. Cases that are destined to be transferred via a - // TransferableResource should call ProduceFrame() instead. - virtual scoped_refptr<CanvasResource> ProduceFrame() = 0; + // TransferableResource should call ProduceCanvasResource() instead. + virtual scoped_refptr<CanvasResource> ProduceCanvasResource() = 0; virtual scoped_refptr<StaticBitmapImage> Snapshot() = 0; // WebGraphicsContext3DProvider::DestructionObserver implementation. @@ -112,11 +112,12 @@ } // Indicates that the compositing path is single buffered, meaning that - // ProduceFrame() return a reference to the same resource each time, which - // implies that Producing an animation frame may overwrite the resource used - // by the previous frame. This results in graphics updates skipping the queue, - // thus reducing latency, but with the possible side effects of tearing (in - // cases where the resource is scanned out directly) and irregular frame rate. + // ProduceCanvasResource() return a reference to the same resource each time, + // which implies that Producing an animation frame may overwrite the resource + // used by the previous frame. This results in graphics updates skipping the + // queue, thus reducing latency, but with the possible side effects of tearing + // (in cases where the resource is scanned out directly) and irregular frame + // rate. bool IsSingleBuffered() { return !resource_recycling_enabled_; } // Attempt to enable single buffering mode on this resource provider. May
diff --git a/third_party/blink/renderer/platform/graphics/compositor_mutator_client.h b/third_party/blink/renderer/platform/graphics/compositor_mutator_client.h index b6fb0b0..9445cc7 100644 --- a/third_party/blink/renderer/platform/graphics/compositor_mutator_client.h +++ b/third_party/blink/renderer/platform/graphics/compositor_mutator_client.h
@@ -23,9 +23,6 @@ void SynchronizeAnimatorName(const String& animator_name) override {} void SetMutationUpdate(std::unique_ptr<cc::MutatorOutputState>) override; - // TODO(http://crbug.com/791280): Plumb notifications through to cc scheduler. - void NotifyAnimationsPending() override {} - void NotifyAnimationsReady() override {} // cc::LayerTreeMutator void SetClient(cc::LayerTreeMutatorClient*) override;
diff --git a/third_party/blink/renderer/platform/graphics/graphics_layer.cc b/third_party/blink/renderer/platform/graphics/graphics_layer.cc index 5d55a5e..a3e0f56 100644 --- a/third_party/blink/renderer/platform/graphics/graphics_layer.cc +++ b/third_party/blink/renderer/platform/graphics/graphics_layer.cc
@@ -41,7 +41,6 @@ #include "third_party/blink/public/platform/web_float_rect.h" #include "third_party/blink/public/platform/web_point.h" #include "third_party/blink/public/platform/web_size.h" -#include "third_party/blink/renderer/platform/drag_image.h" #include "third_party/blink/renderer/platform/geometry/float_rect.h" #include "third_party/blink/renderer/platform/geometry/layout_rect.h" #include "third_party/blink/renderer/platform/geometry/region.h" @@ -139,7 +138,7 @@ } void GraphicsLayer::SetSnapContainerData( - base::Optional<SnapContainerData> data) { + base::Optional<cc::SnapContainerData> data) { CcLayer()->SetSnapContainerData(std::move(data)); }
diff --git a/third_party/blink/renderer/platform/graphics/image.cc b/third_party/blink/renderer/platform/graphics/image.cc index 31aab16..d9c1604 100644 --- a/third_party/blink/renderer/platform/graphics/image.cc +++ b/third_party/blink/renderer/platform/graphics/image.cc
@@ -31,7 +31,6 @@ #include "cc/tiles/software_image_decode_cache.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_data.h" -#include "third_party/blink/renderer/platform/drag_image.h" #include "third_party/blink/renderer/platform/geometry/float_point.h" #include "third_party/blink/renderer/platform/geometry/float_rect.h" #include "third_party/blink/renderer/platform/geometry/float_size.h" @@ -48,7 +47,9 @@ #include "third_party/blink/renderer/platform/shared_buffer.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" +#include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkImage.h" +#include "third_party/skia/include/core/SkSurface.h" #include <math.h> #include <tuple> @@ -123,6 +124,57 @@ return image; } +// static +PaintImage Image::ResizeAndOrientImage( + const PaintImage& image, + ImageOrientation orientation, + FloatSize image_scale, + float opacity, + InterpolationQuality interpolation_quality) { + IntSize size(image.width(), image.height()); + size.Scale(image_scale.Width(), image_scale.Height()); + AffineTransform transform; + if (orientation != kDefaultImageOrientation) { + if (orientation.UsesWidthAsHeight()) + size = size.TransposedSize(); + transform *= orientation.TransformFromDefault(FloatSize(size)); + } + transform.ScaleNonUniform(image_scale.Width(), image_scale.Height()); + + if (size.IsEmpty()) + return PaintImage(); + + if (transform.IsIdentity() && opacity == 1) { + // Nothing to adjust, just use the original. + DCHECK_EQ(image.width(), size.Width()); + DCHECK_EQ(image.height(), size.Height()); + return image; + } + + const SkImageInfo info = + SkImageInfo::MakeN32(size.Width(), size.Height(), kPremul_SkAlphaType, + SkColorSpace::MakeSRGB()); + sk_sp<SkSurface> surface = SkSurface::MakeRaster(info); + if (!surface) + return PaintImage(); + + SkPaint paint; + DCHECK_GE(opacity, 0); + DCHECK_LE(opacity, 1); + paint.setAlpha(opacity * 255); + paint.setFilterQuality(interpolation_quality == kInterpolationNone + ? kNone_SkFilterQuality + : kHigh_SkFilterQuality); + + SkCanvas* canvas = surface->getCanvas(); + canvas->concat(AffineTransformToSkMatrix(transform)); + canvas->drawImage(image.GetSkImage(), 0, 0, &paint); + + return PaintImageBuilder::WithProperties(std::move(image)) + .set_image(surface->makeImageSnapshot(), PaintImage::GetNextContentId()) + .TakePaintImage(); +} + Image::SizeAvailability Image::SetData(scoped_refptr<SharedBuffer> data, bool all_data_received) { encoded_image_data_ = std::move(data); @@ -307,7 +359,7 @@ IsBitmapImage()) { ImageOrientation orientation = ToBitmapImage(this)->CurrentFrameOrientation(); - paint_image = DragImage::ResizeAndOrientImage(paint_image, orientation); + paint_image = ResizeAndOrientImage(paint_image, orientation); if (!paint_image) return {}; }
diff --git a/third_party/blink/renderer/platform/graphics/image.h b/third_party/blink/renderer/platform/graphics/image.h index af180fe..eb96eac 100644 --- a/third_party/blink/renderer/platform/graphics/image.h +++ b/third_party/blink/renderer/platform/graphics/image.h
@@ -30,6 +30,7 @@ #include "base/macros.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" +#include "third_party/blink/renderer/platform/geometry/float_size.h" #include "third_party/blink/renderer/platform/geometry/int_rect.h" #include "third_party/blink/renderer/platform/graphics/canvas_color_params.h" #include "third_party/blink/renderer/platform/graphics/graphics_types.h" @@ -58,7 +59,6 @@ class FloatPoint; class FloatRect; -class FloatSize; class GraphicsContext; class Image; class KURL; @@ -80,6 +80,13 @@ static scoped_refptr<Image> LoadPlatformResource(const char* name); + static PaintImage ResizeAndOrientImage( + const PaintImage&, + ImageOrientation, + FloatSize image_scale = FloatSize(1, 1), + float opacity = 1.0, + InterpolationQuality = kInterpolationNone); + virtual bool IsSVGImage() const { return false; } virtual bool IsBitmapImage() const { return false; } virtual bool IsStaticBitmapImage() const { return false; }
diff --git a/third_party/blink/renderer/platform/graphics/main_thread_mutator_client.h b/third_party/blink/renderer/platform/graphics/main_thread_mutator_client.h index f776791..a008984 100644 --- a/third_party/blink/renderer/platform/graphics/main_thread_mutator_client.h +++ b/third_party/blink/renderer/platform/graphics/main_thread_mutator_client.h
@@ -22,8 +22,6 @@ void SynchronizeAnimatorName(const String& animator_name) override; void SetMutationUpdate(std::unique_ptr<AnimationWorkletOutput>) override; - void NotifyAnimationsPending() override {} - void NotifyAnimationsReady() override {} void SetDelegate(MutatorClient* client); AnimationWorkletMutatorDispatcherImpl* Mutator() { return mutator_.get(); }
diff --git a/third_party/blink/renderer/platform/graphics/mutator_client.h b/third_party/blink/renderer/platform/graphics/mutator_client.h index e83018e..7247c27 100644 --- a/third_party/blink/renderer/platform/graphics/mutator_client.h +++ b/third_party/blink/renderer/platform/graphics/mutator_client.h
@@ -17,10 +17,6 @@ virtual void SynchronizeAnimatorName(const String& animator_name) = 0; virtual void SetMutationUpdate(std::unique_ptr<AnimationWorkletOutput>) = 0; - - virtual void NotifyAnimationsPending() = 0; - - virtual void NotifyAnimationsReady() = 0; }; } // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/paint/scroll_paint_property_node.h b/third_party/blink/renderer/platform/graphics/paint/scroll_paint_property_node.h index 35f8337..1fdf708f 100644 --- a/third_party/blink/renderer/platform/graphics/paint/scroll_paint_property_node.h +++ b/third_party/blink/renderer/platform/graphics/paint/scroll_paint_property_node.h
@@ -6,6 +6,7 @@ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_SCROLL_PAINT_PROPERTY_NODE_H_ #include "base/optional.h" +#include "cc/input/scroll_snap_data.h" #include "third_party/blink/renderer/platform/geometry/float_point.h" #include "third_party/blink/renderer/platform/geometry/float_size.h" #include "third_party/blink/renderer/platform/geometry/int_rect.h" @@ -52,7 +53,7 @@ CompositorElementId compositor_element_id; OverscrollBehavior overscroll_behavior = blink::OverscrollBehavior( blink::OverscrollBehavior::kOverscrollBehaviorTypeAuto); - base::Optional<SnapContainerData> snap_container_data; + base::Optional<cc::SnapContainerData> snap_container_data; bool operator==(const State& o) const { return container_rect == o.container_rect && @@ -105,7 +106,7 @@ return state_.overscroll_behavior.y; } - base::Optional<SnapContainerData> GetSnapContainerData() const { + base::Optional<cc::SnapContainerData> GetSnapContainerData() const { return state_.snap_container_data; }
diff --git a/third_party/blink/renderer/platform/loader/BUILD.gn b/third_party/blink/renderer/platform/loader/BUILD.gn index 4da8750..be56961b 100644 --- a/third_party/blink/renderer/platform/loader/BUILD.gn +++ b/third_party/blink/renderer/platform/loader/BUILD.gn
@@ -33,6 +33,7 @@ "fetch/client_hints_preferences.cc", "fetch/client_hints_preferences.h", "fetch/console_logger.h", + "fetch/cross_origin_attribute_value.h", "fetch/data_pipe_bytes_consumer.cc", "fetch/data_pipe_bytes_consumer.h", "fetch/fetch_client_settings_object.h",
diff --git a/third_party/blink/renderer/platform/loader/DEPS b/third_party/blink/renderer/platform/loader/DEPS index 7108dfe..db14b64 100644 --- a/third_party/blink/renderer/platform/loader/DEPS +++ b/third_party/blink/renderer/platform/loader/DEPS
@@ -15,7 +15,6 @@ "+third_party/blink/renderer/platform/bindings/script_forbidden_scope.h", "+third_party/blink/renderer/platform/bindings/trace_wrapper_member.h", "+third_party/blink/renderer/platform/blob/blob_data.h", - "+third_party/blink/renderer/platform/cross_origin_attribute_value.h", "+third_party/blink/renderer/platform/cross_thread_copier.h", "+third_party/blink/renderer/platform/cross_thread_functional.h", "+third_party/blink/renderer/platform/crypto.h", @@ -25,6 +24,7 @@ "+third_party/blink/renderer/platform/instance_counters.h", "+third_party/blink/renderer/platform/instrumentation", "+third_party/blink/renderer/platform/language.h", + "+third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h", "+third_party/blink/renderer/platform/memory_pressure_listener.h", "+third_party/blink/renderer/platform/mhtml", "+third_party/blink/renderer/platform/network",
diff --git a/third_party/blink/renderer/platform/cross_origin_attribute_value.h b/third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h similarity index 66% rename from third_party/blink/renderer/platform/cross_origin_attribute_value.h rename to third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h index 0f59a05c..2da56da 100644 --- a/third_party/blink/renderer/platform/cross_origin_attribute_value.h +++ b/third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_CROSS_ORIGIN_ATTRIBUTE_VALUE_H_ -#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_CROSS_ORIGIN_ATTRIBUTE_VALUE_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_CROSS_ORIGIN_ATTRIBUTE_VALUE_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_CROSS_ORIGIN_ATTRIBUTE_VALUE_H_ namespace blink {
diff --git a/third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h b/third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h index db64c54..7badd8cb 100644 --- a/third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h +++ b/third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h
@@ -27,8 +27,8 @@ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_FETCH_PARAMETERS_H_ #include "third_party/blink/public/platform/web_url_request.h" -#include "third_party/blink/renderer/platform/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.h" +#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/loader/fetch/integrity_metadata.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
diff --git a/third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h b/third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h index eb620cc..d47fdb6 100644 --- a/third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h +++ b/third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h
@@ -7,7 +7,7 @@ #include "services/network/public/mojom/referrer_policy.mojom-shared.h" #include "third_party/blink/public/platform/web_url_request.h" -#include "third_party/blink/renderer/platform/cross_origin_attribute_value.h" +#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h" #include "third_party/blink/renderer/platform/loader/fetch/integrity_metadata.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
diff --git a/third_party/blink/renderer/platform/mhtml/mhtml_archive.cc b/third_party/blink/renderer/platform/mhtml/mhtml_archive.cc index 7b140b4..4628ae1 100644 --- a/third_party/blink/renderer/platform/mhtml/mhtml_archive.cc +++ b/third_party/blink/renderer/platform/mhtml/mhtml_archive.cc
@@ -36,8 +36,8 @@ #include "third_party/blink/renderer/platform/date_components.h" #include "third_party/blink/renderer/platform/mhtml/archive_resource.h" #include "third_party/blink/renderer/platform/mhtml/mhtml_parser.h" +#include "third_party/blink/renderer/platform/mhtml/serialized_resource.h" #include "third_party/blink/renderer/platform/network/mime/mime_type_registry.h" -#include "third_party/blink/renderer/platform/serialized_resource.h" #include "third_party/blink/renderer/platform/shared_buffer.h" #include "third_party/blink/renderer/platform/weborigin/scheme_registry.h" #include "third_party/blink/renderer/platform/wtf/ascii_ctype.h"
diff --git a/third_party/blink/renderer/platform/mhtml/mhtml_parser.h b/third_party/blink/renderer/platform/mhtml/mhtml_parser.h index e6e3bbac..732085a0 100644 --- a/third_party/blink/renderer/platform/mhtml/mhtml_parser.h +++ b/third_party/blink/renderer/platform/mhtml/mhtml_parser.h
@@ -34,7 +34,7 @@ #include "base/memory/scoped_refptr.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/heap/member.h" -#include "third_party/blink/renderer/platform/shared_buffer_chunk_reader.h" +#include "third_party/blink/renderer/platform/mhtml/shared_buffer_chunk_reader.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/wtf/time.h" #include "third_party/blink/renderer/platform/wtf/vector.h"
diff --git a/third_party/blink/renderer/platform/serialized_resource.h b/third_party/blink/renderer/platform/mhtml/serialized_resource.h similarity index 90% rename from third_party/blink/renderer/platform/serialized_resource.h rename to third_party/blink/renderer/platform/mhtml/serialized_resource.h index f2fac29..37ed5a0 100644 --- a/third_party/blink/renderer/platform/serialized_resource.h +++ b/third_party/blink/renderer/platform/mhtml/serialized_resource.h
@@ -28,8 +28,8 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SERIALIZED_RESOURCE_H_ -#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SERIALIZED_RESOURCE_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_MHTML_SERIALIZED_RESOURCE_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_MHTML_SERIALIZED_RESOURCE_H_ #include "third_party/blink/renderer/platform/shared_buffer.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" @@ -52,4 +52,4 @@ } // namespace blink -#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SERIALIZED_RESOURCE_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MHTML_SERIALIZED_RESOURCE_H_
diff --git a/third_party/blink/renderer/platform/shared_buffer_chunk_reader.cc b/third_party/blink/renderer/platform/mhtml/shared_buffer_chunk_reader.cc similarity index 98% rename from third_party/blink/renderer/platform/shared_buffer_chunk_reader.cc rename to third_party/blink/renderer/platform/mhtml/shared_buffer_chunk_reader.cc index 6383440..732afac 100644 --- a/third_party/blink/renderer/platform/shared_buffer_chunk_reader.cc +++ b/third_party/blink/renderer/platform/mhtml/shared_buffer_chunk_reader.cc
@@ -28,7 +28,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "third_party/blink/renderer/platform/shared_buffer_chunk_reader.h" +#include "third_party/blink/renderer/platform/mhtml/shared_buffer_chunk_reader.h" #include "third_party/blink/renderer/platform/shared_buffer.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
diff --git a/third_party/blink/renderer/platform/shared_buffer_chunk_reader.h b/third_party/blink/renderer/platform/mhtml/shared_buffer_chunk_reader.h similarity index 91% rename from third_party/blink/renderer/platform/shared_buffer_chunk_reader.h rename to third_party/blink/renderer/platform/mhtml/shared_buffer_chunk_reader.h index a74b33a..8653387 100644 --- a/third_party/blink/renderer/platform/shared_buffer_chunk_reader.h +++ b/third_party/blink/renderer/platform/mhtml/shared_buffer_chunk_reader.h
@@ -28,11 +28,10 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SHARED_BUFFER_CHUNK_READER_H_ -#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SHARED_BUFFER_CHUNK_READER_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_MHTML_SHARED_BUFFER_CHUNK_READER_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_MHTML_SHARED_BUFFER_CHUNK_READER_H_ #include "base/macros.h" -#include "third_party/blink/renderer/platform/platform_export.h" #include "third_party/blink/renderer/platform/wtf/allocator.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/vector.h" @@ -41,7 +40,7 @@ class SharedBuffer; -class PLATFORM_EXPORT SharedBufferChunkReader final { +class SharedBufferChunkReader final { DISALLOW_NEW(); public: @@ -82,4 +81,4 @@ } // namespace blink -#endif +#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MHTML_SHARED_BUFFER_CHUNK_READER_H_
diff --git a/third_party/blink/renderer/platform/network/DEPS b/third_party/blink/renderer/platform/network/DEPS index e31a6fc2..17d7eb3 100644 --- a/third_party/blink/renderer/platform/network/DEPS +++ b/third_party/blink/renderer/platform/network/DEPS
@@ -17,7 +17,6 @@ "+net/url_request/url_request_data_job.h", "+third_party/blink/renderer/platform/blob/blob_data.h", - "+third_party/blink/renderer/platform/cross_origin_attribute_value.h", "+third_party/blink/renderer/platform/cross_thread_copier.h", "+third_party/blink/renderer/platform/cross_thread_functional.h", "+third_party/blink/renderer/platform/crypto.h",
diff --git a/third_party/blink/renderer/platform/network/network_hints.h b/third_party/blink/renderer/platform/network/network_hints.h index 9316ad5..5b6aae7 100644 --- a/third_party/blink/renderer/platform/network/network_hints.h +++ b/third_party/blink/renderer/platform/network/network_hints.h
@@ -27,7 +27,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_NETWORK_NETWORK_HINTS_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_NETWORK_NETWORK_HINTS_H_ -#include "third_party/blink/renderer/platform/cross_origin_attribute_value.h" +#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h" #include "third_party/blink/renderer/platform/platform_export.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/wtf/forward.h"
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index af2bca9..20d28e95 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -175,6 +175,7 @@ }, { name: "BlockingDownloadsInSandboxWithoutUserActivation", + status: "test", }, { name: "BlockMetaSetCookie", @@ -1428,10 +1429,6 @@ name: "WebAuth", status: "experimental", }, - { - name: "WebAuthGetTransports", - status: "experimental", - }, // WebBluetooth is enabled by default on Android, ChromeOS and Mac. // It is also supported in Windows 10 which is handled in runtime_features.cc {
diff --git a/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy_unittest.cc b/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy_unittest.cc index 471d9d1..11463ad 100644 --- a/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy_unittest.cc +++ b/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy_unittest.cc
@@ -5,6 +5,7 @@ #include "third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy.h" #include "base/bind.h" #include "base/run_loop.h" +#include "base/synchronization/waitable_event.h" #include "base/task/sequence_manager/test/sequence_manager_for_test.h" #include "base/test/scoped_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" @@ -15,7 +16,6 @@ #include "third_party/blink/renderer/platform/scheduler/public/worker_scheduler.h" #include "third_party/blink/renderer/platform/scheduler/worker/worker_thread.h" #include "third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h" -#include "third_party/blink/renderer/platform/waitable_event.h" namespace blink { namespace scheduler { @@ -27,7 +27,7 @@ WorkerThreadSchedulerForTest( std::unique_ptr<base::sequence_manager::SequenceManager> manager, WorkerSchedulerProxy* proxy, - WaitableEvent* throtting_state_changed) + base::WaitableEvent* throtting_state_changed) : WorkerThreadScheduler(WebThreadType::kTestThread, std::move(manager), proxy), @@ -43,13 +43,13 @@ using WorkerThreadScheduler::lifecycle_state; private: - WaitableEvent* throtting_state_changed_; + base::WaitableEvent* throtting_state_changed_; }; class WorkerThreadForTest : public WorkerThread { public: WorkerThreadForTest(FrameScheduler* frame_scheduler, - WaitableEvent* throtting_state_changed) + base::WaitableEvent* throtting_state_changed) : WorkerThread(ThreadCreationParams(WebThreadType::kTestThread) .SetFrameOrWorkerScheduler(frame_scheduler)), throtting_state_changed_(throtting_state_changed) {} @@ -90,14 +90,14 @@ WorkerThreadSchedulerForTest* GetWorkerScheduler() { return scheduler_; } private: - WaitableEvent* throtting_state_changed_; // NOT OWNED + base::WaitableEvent* throtting_state_changed_; // NOT OWNED WorkerThreadSchedulerForTest* scheduler_ = nullptr; // NOT OWNED std::unique_ptr<WorkerScheduler> worker_scheduler_ = nullptr; }; std::unique_ptr<WorkerThreadForTest> CreateWorkerThread( FrameScheduler* frame_scheduler, - WaitableEvent* throtting_state_changed) { + base::WaitableEvent* throtting_state_changed) { auto thread = std::make_unique<WorkerThreadForTest>(frame_scheduler, throtting_state_changed); thread->Init(); @@ -144,7 +144,9 @@ }; TEST_F(WorkerSchedulerProxyTest, VisibilitySignalReceived) { - WaitableEvent throtting_state_changed; + base::WaitableEvent throtting_state_changed( + base::WaitableEvent::ResetPolicy::AUTOMATIC, + base::WaitableEvent::InitialState::NOT_SIGNALED); auto worker_thread = CreateWorkerThread(frame_scheduler_.get(), &throtting_state_changed); @@ -174,7 +176,9 @@ // Tests below check that no crashes occur during different shutdown sequences. TEST_F(WorkerSchedulerProxyTest, FrameSchedulerDestroyed) { - WaitableEvent throtting_state_changed; + base::WaitableEvent throtting_state_changed( + base::WaitableEvent::ResetPolicy::AUTOMATIC, + base::WaitableEvent::InitialState::NOT_SIGNALED); auto worker_thread = CreateWorkerThread(frame_scheduler_.get(), &throtting_state_changed); @@ -195,7 +199,9 @@ } TEST_F(WorkerSchedulerProxyTest, ThreadDestroyed) { - WaitableEvent throtting_state_changed; + base::WaitableEvent throtting_state_changed( + base::WaitableEvent::ResetPolicy::AUTOMATIC, + base::WaitableEvent::InitialState::NOT_SIGNALED); auto worker_thread = CreateWorkerThread(frame_scheduler_.get(), &throtting_state_changed);
diff --git a/third_party/blink/renderer/platform/scheduler/worker/worker_thread_unittest.cc b/third_party/blink/renderer/platform/scheduler/worker/worker_thread_unittest.cc index 72ab7d8..76af09c 100644 --- a/third_party/blink/renderer/platform/scheduler/worker/worker_thread_unittest.cc +++ b/third_party/blink/renderer/platform/scheduler/worker/worker_thread_unittest.cc
@@ -119,7 +119,12 @@ completion.Wait(); } -TEST_F(WorkerThreadTest, TestTaskExecutedBeforeThreadDeletion) { +#if defined(OS_LINUX) +#define MAYBE_TestTaskExecutedBeforeThreadDeletion DISABLED_TestTaskExecutedBeforeThreadDeletion +#else +#define MAYBE_TestTaskExecutedBeforeThreadDeletion TestTaskExecutedBeforeThreadDeletion +#endif +TEST_F(WorkerThreadTest, MAYBE_TestTaskExecutedBeforeThreadDeletion) { MockTask task; base::WaitableEvent completion( base::WaitableEvent::ResetPolicy::AUTOMATIC,
diff --git a/third_party/blink/renderer/platform/scroll/scroll_snap_data.h b/third_party/blink/renderer/platform/scroll/scroll_snap_data.h index e5b8f71e..bd99828 100644 --- a/third_party/blink/renderer/platform/scroll/scroll_snap_data.h +++ b/third_party/blink/renderer/platform/scroll/scroll_snap_data.h
@@ -14,11 +14,6 @@ namespace blink { using SearchAxis = cc::SearchAxis; -using SnapSelectionStrategy = cc::SnapSelectionStrategy; -using ScrollSnapType = cc::ScrollSnapType; -using ScrollSnapAlign = cc::ScrollSnapAlign; -using SnapAreaData = cc::SnapAreaData; -using SnapContainerData = cc::SnapContainerData; using SnapFlingController = cc::SnapFlingController; using SnapFlingClient = cc::SnapFlingClient;
diff --git a/third_party/blink/renderer/platform/waitable_event.cc b/third_party/blink/renderer/platform/waitable_event.cc deleted file mode 100644 index c564f71..0000000 --- a/third_party/blink/renderer/platform/waitable_event.cc +++ /dev/null
@@ -1,52 +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 "third_party/blink/renderer/platform/waitable_event.h" - -#include <vector> -#include "base/optional.h" -#include "base/synchronization/waitable_event.h" -#include "third_party/blink/renderer/platform/heap/thread_state.h" - -namespace blink { - -WaitableEvent::WaitableEvent(ResetPolicy policy, InitialState state) { - impl_ = std::make_unique<base::WaitableEvent>( - policy == ResetPolicy::kManual - ? base::WaitableEvent::ResetPolicy::MANUAL - : base::WaitableEvent::ResetPolicy::AUTOMATIC, - state == InitialState::kSignaled - ? base::WaitableEvent::InitialState::SIGNALED - : base::WaitableEvent::InitialState::NOT_SIGNALED); -} - -WaitableEvent::~WaitableEvent() = default; - -void WaitableEvent::Reset() { - impl_->Reset(); -} - -void WaitableEvent::Wait() { - impl_->Wait(); -} - -void WaitableEvent::Signal() { - impl_->Signal(); -} - -bool WaitableEvent::IsSignaled() { - return impl_->IsSignaled(); -} - -size_t WaitableEvent::WaitMultiple(const WTF::Vector<WaitableEvent*>& events) { - std::vector<base::WaitableEvent*> base_events; - for (WaitableEvent* event : events) - base_events.push_back(event->impl_.get()); - size_t idx = - base::WaitableEvent::WaitMany(base_events.data(), base_events.size()); - DCHECK_LT(idx, events.size()); - return idx; -} - -} // namespace blink
diff --git a/third_party/blink/renderer/platform/waitable_event.h b/third_party/blink/renderer/platform/waitable_event.h deleted file mode 100644 index b2a4cd2..0000000 --- a/third_party/blink/renderer/platform/waitable_event.h +++ /dev/null
@@ -1,94 +0,0 @@ -/* - * Copyright (C) 2014 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_WAITABLE_EVENT_H_ -#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WAITABLE_EVENT_H_ - -#include <memory> -#include "third_party/blink/renderer/platform/platform_export.h" -#include "third_party/blink/renderer/platform/wtf/vector.h" - -namespace base { -class WaitableEvent; -} // namespace base - -namespace blink { - -// DEPRECATED, use base::WaitableEvent instead of blink::WaitableEvent. -// -// Provides a thread synchronization that can be used to allow one thread to -// wait until another thread to finish some work. -// TODO(crbug.com/796799): Remove this class in favor of base::WaitableEvent. -class PLATFORM_EXPORT WaitableEvent { - public: - // If ResetPolicy::Manual is specified on creation, to set the event state - // to non-signaled, a consumer must call reset(). Otherwise, the system - // automatically resets the event state to non-signaled after a single - // waiting thread has been released. - enum class ResetPolicy { kAuto, kManual }; - - // Specify the initial state on creation. - enum class InitialState { kNonSignaled, kSignaled }; - - explicit WaitableEvent(ResetPolicy = ResetPolicy::kAuto, - InitialState = InitialState::kNonSignaled); - - ~WaitableEvent(); - - // Puts the event in the un-signaled state. - void Reset(); - - // Waits indefinitely for the event to be signaled. - void Wait(); - - // Puts the event in the signaled state. Causing any thread blocked on Wait - // to be woken up. The event state is reset to non-signaled after - // a waiting thread has been released. - void Signal(); - - // Returns true if the event is in the signaled state, else false. If this - // is not a manual reset event, then this test will cause a reset. - bool IsSignaled(); - - // Waits on multiple events and returns the index of the object that - // has been signaled. Any event objects given to this method must - // not deleted while this wait is happening. - static size_t WaitMultiple(const WTF::Vector<WaitableEvent*>& events); - - private: - WaitableEvent(const WaitableEvent&) = delete; - void operator=(const WaitableEvent&) = delete; - - std::unique_ptr<base::WaitableEvent> impl_; -}; - -} // namespace blink - -#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WAITABLE_EVENT_H_
diff --git a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py index 7e9fe23..51a23a9 100755 --- a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py +++ b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py
@@ -180,6 +180,8 @@ # cc painting types. 'cc::PaintCanvas', 'cc::PaintFlags', + 'cc::NodeHolder', + 'cc::TextHolder', # Chromium geometry types. 'gfx::Point', @@ -230,10 +232,15 @@ 'cc::AnimationHost', # Scrolling + 'cc::ScrollSnapAlign', + 'cc::ScrollSnapType', 'cc::ScrollOffsetAnimationCurve', 'cc::ScrollStateData', 'cc::SnapAlignment', + 'cc::SnapAreaData', 'cc::SnapAxis', + 'cc::SnapContainerData', + 'cc::SnapSelectionStrategy', 'cc::SnapStrictness', 'gfx::RectToSkRect', 'gfx::ScrollOffset',
diff --git a/third_party/blink/tools/blinkpy/style/checker.py b/third_party/blink/tools/blinkpy/style/checker.py index 37a3afd..6c0bcfc 100644 --- a/third_party/blink/tools/blinkpy/style/checker.py +++ b/third_party/blink/tools/blinkpy/style/checker.py
@@ -226,22 +226,22 @@ return categories -def _check_webkit_style_defaults(): +def _check_blink_style_defaults(): """Return the default command-line options for check_blink_style.py.""" return DefaultCommandOptionValues(min_confidence=_DEFAULT_MIN_CONFIDENCE, output_format=_DEFAULT_OUTPUT_FORMAT) # This function assists in optparser not having to import from checker. -def check_webkit_style_parser(): +def check_blink_style_parser(): all_categories = _all_categories() - default_options = _check_webkit_style_defaults() + default_options = _check_blink_style_defaults() return ArgumentParser(all_categories=all_categories, base_filter_rules=_BASE_FILTER_RULES, default_options=default_options) -def check_webkit_style_configuration(options): +def check_blink_style_configuration(options): """Return a StyleProcessorConfiguration instance for check_blink_style.py. Args:
diff --git a/third_party/blink/tools/blinkpy/style/checker_unittest.py b/third_party/blink/tools/blinkpy/style/checker_unittest.py index 2de9211d..ba36947 100644 --- a/third_party/blink/tools/blinkpy/style/checker_unittest.py +++ b/third_party/blink/tools/blinkpy/style/checker_unittest.py
@@ -44,8 +44,8 @@ from blinkpy.style.checker import _BASE_FILTER_RULES from blinkpy.style.checker import _MAX_REPORTS_PER_CATEGORY from blinkpy.style.checker import _PATH_RULES_SPECIFIER as PATH_RULES_SPECIFIER -from blinkpy.style.checker import check_webkit_style_configuration -from blinkpy.style.checker import check_webkit_style_parser +from blinkpy.style.checker import check_blink_style_configuration +from blinkpy.style.checker import check_blink_style_parser from blinkpy.style.checker import CheckerDispatcher from blinkpy.style.checker import configure_logging from blinkpy.style.checker import StyleProcessor @@ -155,9 +155,11 @@ return _all_categories() def defaults(self): - return style._check_webkit_style_defaults() + # Access to a protected member _check_blink_style_defaults + # pylint: disable=W0212 + return style._check_blink_style_defaults() - def test_webkit_base_filter_rules(self): + def test_blink_base_filter_rules(self): base_filter_rules = _BASE_FILTER_RULES already_seen = [] validate_filter_rules(base_filter_rules, self._all_categories()) @@ -224,18 +226,18 @@ 'Key "%s" is not a category' % category) -class CheckWebKitStyleFunctionTest(unittest.TestCase): +class CheckBlinkStyleFunctionTest(unittest.TestCase): - """Tests the functions with names of the form check_webkit_style_*.""" + """Tests the functions with names of the form check_blink_style_*.""" - def test_check_webkit_style_configuration(self): + def test_check_blink_style_configuration(self): # Exercise the code path to make sure the function does not error out. option_values = CommandOptionValues() - check_webkit_style_configuration(option_values) + check_blink_style_configuration(option_values) - def test_check_webkit_style_parser(self): + def test_check_blink_style_parser(self): # Exercise the code path to make sure the function does not error out. - check_webkit_style_parser() + check_blink_style_parser() class CheckerDispatcherSkipTest(unittest.TestCase):
diff --git a/third_party/blink/tools/blinkpy/style/main.py b/third_party/blink/tools/blinkpy/style/main.py index cb21027..28a5e3d 100644 --- a/third_party/blink/tools/blinkpy/style/main.py +++ b/third_party/blink/tools/blinkpy/style/main.py
@@ -100,8 +100,7 @@ return paths -# TODO(tkent): Replace "WebKit" with "Blink" in code. -class CheckWebKitStyle(object): +class CheckBlinkStyle(object): def _engage_awesome_stderr_hacks(self): # Change stderr to write with replacement characters so we don't die @@ -129,17 +128,17 @@ stderr = self._engage_awesome_stderr_hacks() - # Checking for the verbose flag before calling check_webkit_style_parser() + # Checking for the verbose flag before calling check_blink_style_parser() # lets us enable verbose logging earlier. is_verbose = '-v' in args or '--verbose' in args checker.configure_logging(stream=stderr, is_verbose=is_verbose) _log.debug('Verbose logging enabled.') - parser = checker.check_webkit_style_parser() + parser = checker.check_blink_style_parser() (paths, options) = parser.parse(args) - configuration = checker.check_webkit_style_configuration(options) + configuration = checker.check_blink_style_configuration(options) paths = change_directory(host.filesystem, checkout_root=host.git().checkout_root, paths=paths)
diff --git a/third_party/blink/tools/blinkpy/web_tests/port/linux.py b/third_party/blink/tools/blinkpy/web_tests/port/linux.py index 1942b5752..a14f0a0f 100644 --- a/third_party/blink/tools/blinkpy/web_tests/port/linux.py +++ b/third_party/blink/tools/blinkpy/web_tests/port/linux.py
@@ -211,6 +211,8 @@ """Tries to find a free X display, looping if necessary.""" # The "xvfb-run" command uses :99 by default. for display_number in range(99, 120): + if self.host.filesystem.exists('/tmp/.X%d-lock' % display_number): + continue display = ':%d' % display_number exit_code = self.host.executive.run_command( ['xdpyinfo', '-display', display], return_exit_code=True)
diff --git a/third_party/blink/tools/check_blink_style.py b/third_party/blink/tools/check_blink_style.py index b51b140..78c72aa 100755 --- a/third_party/blink/tools/check_blink_style.py +++ b/third_party/blink/tools/check_blink_style.py
@@ -40,8 +40,8 @@ import sys from blinkpy.common import version_check # pylint: disable=unused-import -from blinkpy.style.main import CheckWebKitStyle +from blinkpy.style.main import CheckBlinkStyle if __name__ == "__main__": - sys.exit(CheckWebKitStyle().main()) + sys.exit(CheckBlinkStyle().main())
diff --git a/third_party/blink/web_tests/SlowTests b/third_party/blink/web_tests/SlowTests index 41a925f0..3f1358b4 100644 --- a/third_party/blink/web_tests/SlowTests +++ b/third_party/blink/web_tests/SlowTests
@@ -1575,3 +1575,5 @@ crbug.com/933550 external/wpt/service-workers/service-worker/interfaces-window.https.html [ Slow ] crbug.com/933550 external/wpt/webusb/idlharness.https.any.worker.html [ Slow ] + +crbug.com/927183 [ Mac10.13 ] external/wpt/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_navigation_download_allow_downloads_without_user_activation.sub.tentative.html [ Slow ]
diff --git a/third_party/blink/web_tests/SmokeTests b/third_party/blink/web_tests/SmokeTests index 3f3390c2..89432f8 100644 --- a/third_party/blink/web_tests/SmokeTests +++ b/third_party/blink/web_tests/SmokeTests
@@ -316,7 +316,7 @@ external/wpt/web-animations/interfaces/KeyframeEffect/spacing.html external/wpt/web-animations/timing-model/animation-effects/active-time.html external/wpt/web-animations/timing-model/animations/finishing-an-animation.html -external/wpt/web-animations/timing-model/animations/set-the-animation-start-time.html +external/wpt/web-animations/timing-model/animations/setting-the-start-time-of-an-animation.html external/wpt/web-animations/timing-model/time-transformations/transformed-progress.html external/wpt/webaudio/the-audio-api/the-audiobuffersourcenode-interface/audiobuffersource-ended.html external/wpt/webaudio/the-audio-api/the-audiobuffersourcenode-interface/audiobuffersource-playbackrate-zero.html
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 0526118..794e898e 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -641,9 +641,6 @@ crbug.com/591099 external/wpt/css/filter-effects/filtered-inline-applies-to-float.html [ Failure ] crbug.com/591099 tables/mozilla/bugs/bug14159-1.html [ Failure ] -### virtual/layout_ng/external/wpt/css/CSS2/abspos -crbug.com/591099 virtual/layout_ng/external/wpt/css/CSS2/abspos/abspos-in-block-in-inline-in-relpos-inline.html [ Failure ] - ### virtual/layout_ng/external/wpt/css/CSS2/floats crbug.com/711704 virtual/layout_ng/external/wpt/css/CSS2/floats/floats-rule3-outside-left-002.xht [ Failure ] crbug.com/711704 virtual/layout_ng/external/wpt/css/CSS2/floats/floats-rule3-outside-right-002.xht [ Failure ] @@ -861,8 +858,6 @@ crbug.com/591099 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-basic-008.xht [ Failure ] crbug.com/776051 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-block-no-clip-001.xht [ Failure ] crbug.com/776051 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-block-no-clip-002.xht [ Failure ] -crbug.com/874506 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-break-000.xht [ Failure ] -crbug.com/874506 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-break-001.xht [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-breaking-000.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-breaking-001.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-breaking-002.html [ Failure ] @@ -963,7 +958,6 @@ crbug.com/591099 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-span-all-001.xht [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-span-all-002.xht [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-span-all-003.xht [ Failure ] -crbug.com/829028 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-span-all-004.html [ Failure ] crbug.com/829028 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-span-all-005.html [ Failure ] crbug.com/829028 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-span-all-006.html [ Failure Crash ] crbug.com/829028 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-span-all-007.html [ Failure ] @@ -1105,7 +1099,6 @@ crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/float-moved-by-child-line-and-unbreakable.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/float-paginate-empty-lines.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/float-paginate.html [ Failure ] -crbug.com/714962 virtual/layout_ng_experimental/fast/multicol/float-truncation.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/float-with-margin-moved-by-child-block-and-unbreakable.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/float-with-margin-moved-by-child-block.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/float-with-margin-moved-by-child-line-and-unbreakable.html [ Failure ] @@ -1299,7 +1292,6 @@ crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/vertical-lr/float-content-break.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/vertical-lr/float-edge.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/vertical-lr/float-paginate.html [ Failure ] -crbug.com/714962 virtual/layout_ng_experimental/fast/multicol/vertical-lr/float-truncation.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/vertical-lr/image-inside-nested-blocks-with-border.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/vertical-lr/nested-columns.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/vertical-lr/offset-top-and-left-at-boundaries.html [ Failure ] @@ -1324,7 +1316,6 @@ crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/vertical-rl/float-content-break.html [ Crash Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/vertical-rl/float-edge.html [ Crash Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/vertical-rl/float-paginate.html [ Crash Failure ] -crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/vertical-rl/float-truncation.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/vertical-rl/image-inside-nested-blocks-with-border.html [ Failure ] crbug.com/467477 virtual/layout_ng_experimental/fast/multicol/vertical-rl/nested-columns.html [ Crash Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/vertical-rl/offset-top-and-left-at-boundaries.html [ Failure ] @@ -1377,7 +1368,6 @@ crbug.com/591099 virtual/layout_ng_experimental/fragmentation/change-fragmentainer-height-block-float.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fragmentation/change-fragmentainer-height-inline-float.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fragmentation/change-fragmentainer-height-line-float.html [ Failure ] -crbug.com/591099 virtual/layout_ng_experimental/fragmentation/column-fill-auto-child.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fragmentation/float-after-forced-break.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fragmentation/float-margin-top.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fragmentation/float-pushed-to-next-fragmentainer-by-floats.html [ Failure ] @@ -1416,7 +1406,6 @@ crbug.com/591099 virtual/layout_ng_experimental/fragmentation/single-line-cells-multiple-tables-caption-repeating-thead-tfoot-with-border-spacing-at-top-of-row-3.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fragmentation/single-line-cells-multiple-tables-caption-repeating-thead-tfoot-with-border-spacing-at-top-of-row-4.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fragmentation/single-line-cells-multiple-tables-caption-repeating-thead-tfoot-with-border-spacing-at-top-of-row.html [ Failure ] -crbug.com/714962 virtual/layout_ng_experimental/fragmentation/single-line-cells-multiple-tables-repeating-thead-with-border-spacing-at-top-of-row.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fragmentation/single-line-cells-nested-repeating-thead-2.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fragmentation/single-line-cells-nested-repeating-thead-3.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fragmentation/single-line-cells-nested-repeating-thead-4.html [ Failure ] @@ -1553,7 +1542,6 @@ crbug.com/591099 virtual/layout_ng_experimental/css3/flexbox/nested-stretch.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/css3/flexbox/order-painting.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/css3/flexbox/orthogonal-writing-modes-and-intrinsic-sizing.html [ Failure ] -crbug.com/591099 virtual/layout_ng_experimental/css3/flexbox/overflow-and-padding.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/css3/flexbox/overflow-auto-resizes-correctly.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/css3/flexbox/overflow-keep-scrollpos.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/css3/flexbox/percentage-height-replaced-element.html [ Failure ] @@ -3056,7 +3044,6 @@ 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 ] -crbug.com/626703 [ Linux ] virtual/layout_ng/external/wpt/css/CSS2/abspos/abspos-containing-block-initial-001.xht [ Crash ] crbug.com/626703 [ Retina ] virtual/feature-policy-permissions/external/wpt/mediacapture-streams/GUM-non-applicable-constraint.https.html [ Timeout ] crbug.com/626703 [ Linux ] virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/clients-matchall.https.html [ Crash ] crbug.com/626703 [ Retina ] virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/skip-waiting.https.html [ Timeout ] @@ -3072,7 +3059,6 @@ crbug.com/626703 [ Retina ] virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/navigation-preload/get-state.https.html [ Timeout ] crbug.com/626703 [ Linux ] virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/fetch-request-css-images.https.html [ Crash ] crbug.com/626703 [ Retina ] virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/fetch-event-referrer-policy.https.html [ Timeout ] -crbug.com/626703 [ Linux ] virtual/layout_ng/external/wpt/css/CSS2/linebox/vertical-align-004.xht [ Crash ] crbug.com/626703 [ Retina ] virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/clients-get-cross-origin.https.html [ Timeout ] crbug.com/626703 [ Retina ] virtual/feature-policy-permissions/external/wpt/mediacapture-streams/MediaStream-audio-only.https.html [ Timeout ] crbug.com/626703 crbug.com/930297 [ Linux ] external/wpt/html/infrastructure/urls/resolving-urls/query-encoding/windows-1251.html [ Timeout Pass Failure Crash ] @@ -3200,7 +3186,7 @@ crbug.com/626703 [ Retina ] virtual/unified-autoplay/external/wpt/feature-policy/picture-in-picture-default-feature-policy.https.sub.html [ Crash ] crbug.com/626703 [ Mac10.13 ] external/wpt/media-source/mediasource-detach.html [ Crash ] crbug.com/626703 [ Retina ] external/wpt/media-source/mediasource-detach.html [ Crash ] -crbug.com/626703 external/wpt/infrastructure/testdriver/actions/pause.html [ Timeout ] +crbug.com/626703 [ Mac ] external/wpt/infrastructure/testdriver/actions/pause.html [ Pass Timeout ] crbug.com/626703 external/wpt/infrastructure/testdriver/actions/eventOrder.html [ Timeout ] crbug.com/626703 external/wpt/css/css-text/writing-system/writing-system-segment-break-001.html [ Failure ] crbug.com/626703 external/wpt/css/css-text/writing-system/writing-system-line-break-001.html [ Failure ] @@ -5930,8 +5916,6 @@ crbug.com/922951 virtual/video-surface-layer/media/controls/overflow-menu-hide-on-click-panel.html [ Skip ] crbug.com/922951 virtual/video-surface-layer/media/controls/overflow-menu-toggle-class-for-animation.html [ Skip ] -crbug.com/927866 external/wpt/longtask-timing/longtask-in-sibling-iframe.html [ Pass Failure ] - # Race: The RTCIceConnectionState can become "connected" before getStats() # returns candidate-pair whose state is "succeeded", this sounds like a # contradiction. @@ -5991,7 +5975,6 @@ crbug.com/929678 [ Mac ] virtual/feature-policy-for-sandbox/http/tests/security/inactive-document-with-empty-security-origin.html [ Pass Failure ] # Sheriff 2019-02-06 -crbug.com/929122 [ Linux ] external/wpt/html/dom/interfaces.worker.html [ Timeout Failure ] crbug.com/929435 [ Mac ] external/wpt/webaudio/the-audio-api/the-audiobuffersourcenode-interface/sub-sample-buffer-stitching.html [ Pass Failure ] # Sheriff 2019-02-11 @@ -6015,3 +5998,14 @@ # Sheriff 2019-02-19 crbug.com/933346 [ Debug ] external/wpt/orientation-sensor/RelativeOrientationSensor.https.html [ Failure Timeout Pass ] + +# Sheriff 2019-02-21 +crbug.com/934278 [ Mac ] virtual/video-surface-layer/media/video-object-fit.html [ Failure Pass ] + +# Sheriff 2019-02-22 +crbug.com/934636 http/tests/security/cross-origin-indexeddb-allowed.html [ Crash Pass ] +crbug.com/934636 virtual/feature-policy-for-sandbox/http/tests/security/cross-origin-indexeddb-allowed.html [ Crash Pass ] +crbug.com/934636 virtual/outofblink-cors/http/tests/security/cross-origin-indexeddb-allowed.html [ Crash Pass ] +crbug.com/934636 virtual/outofblink-cors-ns/http/tests/security/cross-origin-indexeddb-allowed.html [ Crash Pass ] +crbug.com/934768 [ Mac ] http/tests/devtools/tracing/worker-events.js [ Failure Pass ] +crbug.com/934768 [ Mac ] virtual/threaded/http/tests/devtools/tracing/worker-events.js [ Failure Pass ]
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites index e37cfd5..e344f2e 100644 --- a/third_party/blink/web_tests/VirtualTestSuites +++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -633,18 +633,6 @@ "args": ["--enable-features=NetworkService"] }, { - "prefix": "sxg-origin-trial", - "base": "http/tests/loading/sxg", - "args": ["--stable-release-mode", - "--enable-features=SignedHTTPExchangeOriginTrial"] - }, - { - "prefix": "sxg-origin-trial-with-network-service", - "base": "http/tests/loading/sxg", - "args": ["--stable-release-mode", - "--enable-features=SignedHTTPExchangeOriginTrial,NetworkService"] - }, - { "prefix": "disabled-service-worker-servicification", "base": "http/tests/serviceworker", "args": ["--disable-features=ServiceWorkerServicification,NetworkService"]
diff --git a/third_party/blink/web_tests/accessibility/animated-image-loaded-events.html b/third_party/blink/web_tests/accessibility/animated-image-loaded-events.html new file mode 100644 index 0000000..9531d27 --- /dev/null +++ b/third_party/blink/web_tests/accessibility/animated-image-loaded-events.html
@@ -0,0 +1,26 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<img id="img"> + +<script> +async_test(function(t) { + var img = document.getElementById("img"); + var axImg = accessibilityController.accessibleElementById("img"); + var count = 0; + axImg.addNotificationListener((notification) => { + if (notification == "MarkDirty") { + count++; + // We should only get at most one notification. + assert_equals(1, count); + } + }); + img.src = "../images/resources/animated2.gif"; + + setTimeout(() => { + assert_equals(1, count); + t.done(); + }, 300); +}, "When loading an animated image, a notification is only received once."); +</script>
diff --git a/third_party/blink/web_tests/accessibility/background-image-loaded-events.html b/third_party/blink/web_tests/accessibility/background-image-loaded-events.html new file mode 100644 index 0000000..462c8792 --- /dev/null +++ b/third_party/blink/web_tests/accessibility/background-image-loaded-events.html
@@ -0,0 +1,27 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<style> +.imgparent div { + width: 100px; + height: 100px; + background-image: url('resources/cake.png'); +} +</style> +<div id="outer"> + <div id="img"></div> +</div> + +<script> +async_test(function(t) { + var outer = document.getElementById("outer"); + var img = document.getElementById("img"); + var axImg = accessibilityController.accessibleElementById("img"); + axImg.addNotificationListener((notification) => { + if (notification == "MarkDirty") + t.done(); + }); + outer.className = "imgparent"; +}, "A notification is received when a background image loads."); +</script>
diff --git a/third_party/blink/web_tests/accessibility/image-loaded-events.html b/third_party/blink/web_tests/accessibility/image-loaded-events.html new file mode 100644 index 0000000..7c43cac47 --- /dev/null +++ b/third_party/blink/web_tests/accessibility/image-loaded-events.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<img id="img"> + +<script> +async_test(function(t) { + var img = document.getElementById("img"); + var axImg = accessibilityController.accessibleElementById("img"); + axImg.addNotificationListener((notification) => { + if (notification == "MarkDirty") + t.done(); + }); + img.src = "resources/cake.png"; +}, "A notification is received when an image is loaded on an img element."); +</script>
diff --git a/third_party/blink/web_tests/editing/input/caret-at-the-edge-of-contenteditable.html b/third_party/blink/web_tests/editing/input/caret-at-the-edge-of-contenteditable.html index a7f7ebf..83c425b 100644 --- a/third_party/blink/web_tests/editing/input/caret-at-the-edge-of-contenteditable.html +++ b/third_party/blink/web_tests/editing/input/caret-at-the-edge-of-contenteditable.html
@@ -2,7 +2,7 @@ <head> </head> <body> -<div>When the caret reaches the edge of the input box or content editable div, on the next input if must jump to the center of the control.</div> +<div>When the caret reaches the edge of the input box or content editable div, on the next input it must stay at the edge of the control.</div> <span style="position:absolute; visibility:hidden" id="single-digit">0</span> <div style="border:thin solid black; white-space:nowrap; overflow:hidden" contenteditable="true" id="input-contenteditable">012345678901234567890123456789</div> <script>
diff --git a/third_party/blink/web_tests/editing/input/caret-at-the-edge-of-input.html b/third_party/blink/web_tests/editing/input/caret-at-the-edge-of-input.html index 0a5ef59c..ced7aef 100644 --- a/third_party/blink/web_tests/editing/input/caret-at-the-edge-of-input.html +++ b/third_party/blink/web_tests/editing/input/caret-at-the-edge-of-input.html
@@ -2,7 +2,7 @@ <head> </head> <body> -<div>When the caret reaches the edge of the input box, on the next input if must jump to the center of the control.</div> +<div>When the caret reaches the edge of the input box, on the next input if must stay at the edge of the control.</div> <input type="text" name="input-edit" id="input-edit" size="10" value="012345678901234567890123456789" /> <script>
diff --git a/third_party/blink/web_tests/editing/input/resources/reveal-utilities.js b/third_party/blink/web_tests/editing/input/resources/reveal-utilities.js index 127853f..c4fd6e59 100644 --- a/third_party/blink/web_tests/editing/input/resources/reveal-utilities.js +++ b/third_party/blink/web_tests/editing/input/resources/reveal-utilities.js
@@ -3,6 +3,12 @@ return element.getClientRects()[0].top; } +function offsetFromViewportBottom(element) +{ + var rect = element.getClientRects()[0]; + return window.innerHeight - rect.top - rect.height; +} + function offsetOfMiddleFromViewportTop(element) { return element.getClientRects()[0].top + Math.round(element.getClientRects()[0].height / 2); @@ -28,6 +34,15 @@ return result; } +function assertInputIsInTheBottomEdgeOfViewport() +{ + var offsetOfInput = offsetFromViewportBottom(document.getElementById("input")); + document.getElementById("results").innerHTML += "ScrollVertically: " + + (Math.abs(offsetOfInput) <= 3 ? + "PASS" : + "FAIL<br>offsetOfInput: " + offsetOfInput); +} + function assertInputIsInTheMiddleOfViewport() { var viewportMiddle = Math.round(window.innerHeight / 2);
diff --git a/third_party/blink/web_tests/editing/input/reveal-caret-of-multiline-contenteditable.html b/third_party/blink/web_tests/editing/input/reveal-caret-of-multiline-contenteditable.html index 4e01426d..8686ca4 100644 --- a/third_party/blink/web_tests/editing/input/reveal-caret-of-multiline-contenteditable.html +++ b/third_party/blink/web_tests/editing/input/reveal-caret-of-multiline-contenteditable.html
@@ -3,7 +3,7 @@ <script type="text/javascript" src="resources/reveal-utilities.js"></script> </head> <body> -<div>When the caret is scrolled out, on starting typing it must be brought to the center of the control.</div> +<div>When the caret is scrolled out, on starting typing it must be brought to the edge of the control.</div> <span style="position:absolute; visibility:hidden" id="single-digit">0</span> <div style="border:thin solid black; overflow:scroll" contenteditable="true" id="input-contenteditable"></div> <script>
diff --git a/third_party/blink/web_tests/editing/input/reveal-caret-of-multiline-input.html b/third_party/blink/web_tests/editing/input/reveal-caret-of-multiline-input.html index d5e5ba2..c74b424 100644 --- a/third_party/blink/web_tests/editing/input/reveal-caret-of-multiline-input.html +++ b/third_party/blink/web_tests/editing/input/reveal-caret-of-multiline-input.html
@@ -3,7 +3,7 @@ <script type="text/javascript" src="resources/reveal-utilities.js"></script> </head> <body> -<div>When the caret is scrolled out, on starting typing it must be brought to the center of the control.</div> +<div>When the caret is scrolled out, on starting typing it must be brought to the edge of the control.</div> <textarea name="textarea" id="textarea" rows="10" cols="10"></textarea> <script>
diff --git a/third_party/blink/web_tests/editing/input/reveal-contenteditable-on-input-vertically-expected.txt b/third_party/blink/web_tests/editing/input/reveal-contenteditable-on-input-vertically-expected.txt index 35077988..9a80251 100644 --- a/third_party/blink/web_tests/editing/input/reveal-contenteditable-on-input-vertically-expected.txt +++ b/third_party/blink/web_tests/editing/input/reveal-contenteditable-on-input-vertically-expected.txt
@@ -1,4 +1,4 @@ -After starting typing in a scrolled out of view editor control, the control is to be brought in the center of the view -To test manually, scroll the page up to the top, then start typing. Input box should be scrolled into the middle of the view. +After starting typing in a scrolled out of view editor control, the control is to be brought to the edge of the view +To test manually, scroll the page up to the top, then start typing. Input box should be scrolled into the edge of the view. a ScrollVertically: PASS
diff --git a/third_party/blink/web_tests/editing/input/reveal-contenteditable-on-input-vertically.html b/third_party/blink/web_tests/editing/input/reveal-contenteditable-on-input-vertically.html index fe0dd03..99b88748 100644 --- a/third_party/blink/web_tests/editing/input/reveal-contenteditable-on-input-vertically.html +++ b/third_party/blink/web_tests/editing/input/reveal-contenteditable-on-input-vertically.html
@@ -8,9 +8,9 @@ </style> </head> <body> -<div>After starting typing in a scrolled out of view editor control, the control is to be brought in the center of the view</div> +<div>After starting typing in a scrolled out of view editor control, the control is to be brought to the edge of the view</div> <div style="height:200%"></div> -<div>To test manually, scroll the page up to the top, then start typing. Input box should be scrolled into the middle of the view.</div> +<div>To test manually, scroll the page up to the top, then start typing. Input box should be scrolled into the edge of the view.</div> <div style="width:150px; border:thin solid black" contenteditable="true" id="input"></div> <div style="height:200%"></div> <div id="results"></div> @@ -21,7 +21,7 @@ if (window.internals) internals.settings.setScrollAnimatorEnabled(false); performVerticalScrollingInputTest(); -assertInputIsInTheMiddleOfViewport(); +assertInputIsInTheBottomEdgeOfViewport(); </script> </body>
diff --git a/third_party/blink/web_tests/editing/input/reveal-edit-on-input-vertically-expected.txt b/third_party/blink/web_tests/editing/input/reveal-edit-on-input-vertically-expected.txt index f388660b..f9da4337 100644 --- a/third_party/blink/web_tests/editing/input/reveal-edit-on-input-vertically-expected.txt +++ b/third_party/blink/web_tests/editing/input/reveal-edit-on-input-vertically-expected.txt
@@ -1,3 +1,3 @@ -After starting typing in a scrolled out of view editor control, the control is to be brought in the center of the view -To test manually, scroll the page up to the top, then start typing. Input box should be scrolled into the middle of the view. +After starting typing in a scrolled out of view editor control, the control is to be brought to the edge of the view +To test manually, scroll the page up to the top, then start typing. Input box should be scrolled into the edge of the view. ScrollVertically: PASS
diff --git a/third_party/blink/web_tests/editing/input/reveal-edit-on-input-vertically.html b/third_party/blink/web_tests/editing/input/reveal-edit-on-input-vertically.html index f5c461dd..a3d95013 100644 --- a/third_party/blink/web_tests/editing/input/reveal-edit-on-input-vertically.html +++ b/third_party/blink/web_tests/editing/input/reveal-edit-on-input-vertically.html
@@ -8,9 +8,9 @@ </style> </head> <body> -<div>After starting typing in a scrolled out of view editor control, the control is to be brought in the center of the view</div> +<div>After starting typing in a scrolled out of view editor control, the control is to be brought to the edge of the view</div> <div style="height:200%"></div> -<div>To test manually, scroll the page up to the top, then start typing. Input box should be scrolled into the middle of the view.</div> +<div>To test manually, scroll the page up to the top, then start typing. Input box should be scrolled into the edge of the view.</div> <input type="text" name="input" id="input" /> <div style="height:200%"></div> <div id="results"></div> @@ -21,7 +21,7 @@ if (window.internals) internals.settings.setScrollAnimatorEnabled(false); performVerticalScrollingInputTest(); -assertInputIsInTheMiddleOfViewport(); +assertInputIsInTheBottomEdgeOfViewport(); </script> </body>
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 f0873e4..e0a8a9c2 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
@@ -157025,6 +157025,11 @@ {} ] ], + "custom-elements/HTMLElement-attachInternals-expected.txt": [ + [ + {} + ] + ], "custom-elements/HTMLElement-constructor-expected.txt": [ [ {} @@ -171255,6 +171260,11 @@ {} ] ], + "html/semantics/embedded-content/the-iframe-element/support/download_stash.py": [ + [ + {} + ] + ], "html/semantics/embedded-content/the-iframe-element/support/iframe-that-checks-contentDocument.html": [ [ {} @@ -171415,6 +171425,11 @@ {} ] ], + "html/semantics/embedded-content/the-iframe-element/support/iframe_sandbox_download_helper.js": [ + [ + {} + ] + ], "html/semantics/embedded-content/the-iframe-element/support/load-into-the-iframe.html": [ [ {} @@ -187965,6 +187980,21 @@ {} ] ], + "trusted-types/trusted-types-report-only.tentative.https.html.headers": [ + [ + {} + ] + ], + "trusted-types/trusted-types-reporting-check-report.https.html.sub.headers": [ + [ + {} + ] + ], + "trusted-types/trusted-types-reporting.tentative.https.html.headers": [ + [ + {} + ] + ], "uievents/META.yml": [ [ {} @@ -223105,6 +223135,12 @@ {} ] ], + "custom-elements/HTMLElement-attachInternals.html": [ + [ + "/custom-elements/HTMLElement-attachInternals.html", + {} + ] + ], "custom-elements/HTMLElement-constructor.html": [ [ "/custom-elements/HTMLElement-constructor.html", @@ -244009,6 +244045,18 @@ {} ] ], + "html/semantics/embedded-content/the-iframe-element/iframe_sandbox_anchor_download_allow_downloads_without_user_activation.sub.tentative.html": [ + [ + "/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_anchor_download_allow_downloads_without_user_activation.sub.tentative.html", + {} + ] + ], + "html/semantics/embedded-content/the-iframe-element/iframe_sandbox_anchor_download_block_downloads_without_user_activation.sub.tentative.html": [ + [ + "/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_anchor_download_block_downloads_without_user_activation.sub.tentative.html", + {} + ] + ], "html/semantics/embedded-content/the-iframe-element/iframe_sandbox_block_modals-1.html": [ [ "/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_block_modals-1.html", @@ -244057,6 +244105,18 @@ {} ] ], + "html/semantics/embedded-content/the-iframe-element/iframe_sandbox_navigation_download_allow_downloads_without_user_activation.sub.tentative.html": [ + [ + "/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_navigation_download_allow_downloads_without_user_activation.sub.tentative.html", + {} + ] + ], + "html/semantics/embedded-content/the-iframe-element/iframe_sandbox_navigation_download_block_downloads_without_user_activation.sub.tentative.html": [ + [ + "/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_navigation_download_block_downloads_without_user_activation.sub.tentative.html", + {} + ] + ], "html/semantics/embedded-content/the-iframe-element/iframe_sandbox_popups_escaping-1.html": [ [ "/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_popups_escaping-1.html", @@ -280155,6 +280215,18 @@ {} ] ], + "signed-exchange/reporting/sxg-reporting-navigation-ok.tentative.html": [ + [ + "/signed-exchange/reporting/sxg-reporting-navigation-ok.tentative.html", + {} + ] + ], + "signed-exchange/reporting/sxg-reporting-prefetch-ok.tentative.html": [ + [ + "/signed-exchange/reporting/sxg-reporting-prefetch-ok.tentative.html", + {} + ] + ], "signed-exchange/sxg-double-prefetch.tentative.html": [ [ "/signed-exchange/sxg-double-prefetch.tentative.html", @@ -282153,6 +282225,18 @@ {} ] ], + "svg/geometry/svg-image-intrinsic-size-with-cssstyle-auto-dynamic-image-change.html": [ + [ + "/svg/geometry/svg-image-intrinsic-size-with-cssstyle-auto-dynamic-image-change.html", + {} + ] + ], + "svg/geometry/svg-image-intrinsic-size-with-cssstyle-auto.html": [ + [ + "/svg/geometry/svg-image-intrinsic-size-with-cssstyle-auto.html", + {} + ] + ], "svg/historical.html": [ [ "/svg/historical.html", @@ -283353,6 +283437,24 @@ {} ] ], + "trusted-types/trusted-types-report-only.tentative.https.html": [ + [ + "/trusted-types/trusted-types-report-only.tentative.https.html", + {} + ] + ], + "trusted-types/trusted-types-reporting-check-report.https.html": [ + [ + "/trusted-types/trusted-types-reporting-check-report.https.html", + {} + ] + ], + "trusted-types/trusted-types-reporting.tentative.https.html": [ + [ + "/trusted-types/trusted-types-reporting.tentative.https.html", + {} + ] + ], "uievents/click/auxclick_event.html": [ [ "/uievents/click/auxclick_event.html", @@ -392844,6 +392946,14 @@ "32613c47e241078fae04ecdd7ee9e5b0236819fc", "testharness" ], + "custom-elements/HTMLElement-attachInternals-expected.txt": [ + "9101726756df003f5600183501f471ce24157c14", + "support" + ], + "custom-elements/HTMLElement-attachInternals.html": [ + "e537983059054eb6193434bfbeb700226e3c5fb7", + "testharness" + ], "custom-elements/HTMLElement-constructor-expected.txt": [ "ca5b35f6cd8057907dc8e9bd209d961f067f76fd", "support" @@ -406257,7 +406367,7 @@ "testharness" ], "html/dom/interfaces.https_exclude=(Document_Window_HTML._)-expected.txt": [ - "d9a59c802f3368cc0d818e3f221e9e1e60e545e0", + "84ed1fbde617c5619932dcb5630adfdd3cfae218", "support" ], "html/dom/interfaces.https_include=(Document_Window)-expected.txt": [ @@ -406265,11 +406375,11 @@ "support" ], "html/dom/interfaces.https_include=HTML._-expected.txt": [ - "826eb52dc05bf982b7cdfc4106cc6d7b396e72cd", + "1d5d27d4f9cef5103c7cd0678f8a95b6ad601c56", "support" ], "html/dom/interfaces.worker-expected.txt": [ - "e00efd48545cc2325bdae4e89772d2a4f42169e2", + "421fe46ceea51e655fc42599ffd797000277574c", "support" ], "html/dom/interfaces.worker.js": [ @@ -414408,6 +414518,14 @@ "042851bbb492365e9d176aff8d678feb645f1d18", "testharness" ], + "html/semantics/embedded-content/the-iframe-element/iframe_sandbox_anchor_download_allow_downloads_without_user_activation.sub.tentative.html": [ + "32409f220f0a273f165741e2d79ca60846d61648", + "testharness" + ], + "html/semantics/embedded-content/the-iframe-element/iframe_sandbox_anchor_download_block_downloads_without_user_activation.sub.tentative.html": [ + "abd4d7c5e0d76d04cd678b00a153d5a8f10bddf7", + "testharness" + ], "html/semantics/embedded-content/the-iframe-element/iframe_sandbox_block_modals-1.html": [ "ce171bfb8e10f90ed581fbcdc0b4e0605d150b88", "testharness" @@ -414440,6 +414558,14 @@ "12c4e0ca50236caacae89c76da3b81effd7b44be", "testharness" ], + "html/semantics/embedded-content/the-iframe-element/iframe_sandbox_navigation_download_allow_downloads_without_user_activation.sub.tentative.html": [ + "4fee27f9ba92482b85ecbcb7e1abe541fbfe83b9", + "testharness" + ], + "html/semantics/embedded-content/the-iframe-element/iframe_sandbox_navigation_download_block_downloads_without_user_activation.sub.tentative.html": [ + "9b9246c393ec9b4ee3b9762d6d06ea65ff0ff5d1", + "testharness" + ], "html/semantics/embedded-content/the-iframe-element/iframe_sandbox_popups_escaping-1.html": [ "342d422036426655457bb5e886871a310bb1dd3a", "testharness" @@ -414648,6 +414774,10 @@ "18ecdcb795c33d6ab7bbb43f647947defca5634d", "support" ], + "html/semantics/embedded-content/the-iframe-element/support/download_stash.py": [ + "24e1dfd58f760e1fa99846e0fac063a32a258e58", + "support" + ], "html/semantics/embedded-content/the-iframe-element/support/iframe-that-checks-contentDocument.html": [ "bc35a977e8b27360f75a901d44fedf47ad496e37", "support" @@ -414776,6 +414906,10 @@ "67733d8101b94e788f670393f624b35b7a9c7876", "support" ], + "html/semantics/embedded-content/the-iframe-element/support/iframe_sandbox_download_helper.js": [ + "7090e7662ca8e2f5cd0e732a8ea3c386abc273b1", + "support" + ], "html/semantics/embedded-content/the-iframe-element/support/load-into-the-iframe.html": [ "05a80be73745465ddcd65bc5745a674824974590", "support" @@ -422665,7 +422799,7 @@ "support" ], "interfaces/html.idl": [ - "f530f3559b68af565fc07f4372a1444d5036eac2", + "641213d1bb6fd47d3cb66f84661b8d658e76b641", "support" ], "interfaces/image-capture.idl": [ @@ -422733,7 +422867,7 @@ "support" ], "interfaces/netinfo.idl": [ - "a4876c9991069b48ff037e8105f05ebbd31202b1", + "729678396884a19874239468075bfd587c621305", "support" ], "interfaces/notifications.idl": [ @@ -422913,7 +423047,7 @@ "support" ], "interfaces/web-nfc.idl": [ - "913d1fe808adf50f66fa621eb62d12b1b41a3a05", + "11a36cde6eb7d2d287310635e867f2fe65f4a4fa", "support" ], "interfaces/web-share.idl": [ @@ -423433,7 +423567,7 @@ "testharness" ], "longtask-timing/longtask-in-sibling-iframe.html": [ - "b8a4270163a1ef4de3a0dfd4aaf82f9404497882", + "16f0998c2234f39257694817436b6e6178632433", "testharness" ], "longtask-timing/longtask-tojson.html": [ @@ -428325,7 +428459,7 @@ "support" ], "network-error-logging/support/nel.sub.js": [ - "759d0337fa677da751c93146f057b05c53f9fa57", + "16aebd54a97cdcd9329c42eba6b4116c40993ca0", "support" ], "network-error-logging/support/no-policy-pass.png": [ @@ -428345,7 +428479,7 @@ "support" ], "network-error-logging/support/report.py": [ - "49af9fe34ccac87f3dffa7c9da9b4486eb140764", + "4bb7e3d248bbff52c042eee6ada3f6df079fb5b6", "support" ], "network-error-logging/support/subdomains-pass.png": [ @@ -451568,6 +451702,14 @@ "f1167f919ab39a85e38778c39fc64305eecd4921", "testharness" ], + "signed-exchange/reporting/sxg-reporting-navigation-ok.tentative.html": [ + "ee9a50966d8f5581084b3518757ff74a6abed692", + "testharness" + ], + "signed-exchange/reporting/sxg-reporting-prefetch-ok.tentative.html": [ + "fb5fb58c9f7063c2abd45130ec4bfdf4b6bcc8cb", + "testharness" + ], "signed-exchange/resources/127.0.0.1.sxg.ext": [ "8cdc25a9a7f36f3313813e967eb9e68f5e546ff6", "support" @@ -451613,7 +451755,7 @@ "support" ], "signed-exchange/resources/sxg-util.js": [ - "67439c8a6e4f111d0095519a77dc0e6ffd380e2c", + "7abb3cf2079087092ac4a7f7332ecf72f9cabd75", "support" ], "signed-exchange/resources/sxg-version1b2.sxg": [ @@ -452868,6 +453010,14 @@ "c2ca49341c5ec5d4d96d1541999893053146eecd", "reftest" ], + "svg/geometry/svg-image-intrinsic-size-with-cssstyle-auto-dynamic-image-change.html": [ + "8d5e2e982e82bd73e45cf86688e637a65f5d6535", + "testharness" + ], + "svg/geometry/svg-image-intrinsic-size-with-cssstyle-auto.html": [ + "6b49f62296433892913e74d0cc9c6bed7567fe31", + "testharness" + ], "svg/historical.html": [ "1b73ca8d2236c7afdb9b331c532c84b6083f2968", "testharness" @@ -454592,6 +454742,30 @@ "4079f7e9c7933cf9ee195fe0e7a54e0f56f184ab", "support" ], + "trusted-types/trusted-types-report-only.tentative.https.html": [ + "f33183b4906975f03ebb3f3a21adb63839c89adb", + "testharness" + ], + "trusted-types/trusted-types-report-only.tentative.https.html.headers": [ + "b38cfae2cb209eec5b8c9e8b0c774262694c1aec", + "support" + ], + "trusted-types/trusted-types-reporting-check-report.https.html": [ + "111907788d279a722aced631dc19b20afb6f0285", + "testharness" + ], + "trusted-types/trusted-types-reporting-check-report.https.html.sub.headers": [ + "5830239f5ca4c45ff97f8fa9f53daba82e0e9685", + "support" + ], + "trusted-types/trusted-types-reporting.tentative.https.html": [ + "3074895ba13f7f734d00898e723b4b604234a9cb", + "testharness" + ], + "trusted-types/trusted-types-reporting.tentative.https.html.headers": [ + "8093b8474d686fd665c6e835c6d0ed8f337cf2cd", + "support" + ], "uievents/META.yml": [ "2f1ec58efec10e0dd6374aac05cb926c8cffa3f1", "support" @@ -456849,7 +457023,7 @@ "support" ], "web-nfc/idlharness.https.window-expected.txt": [ - "87dabc03edd4804a38b57c7884de8e5865c77e01", + "436eaadb9861e4e81270b0c80e1dac33dc668177", "support" ], "web-nfc/idlharness.https.window.js": [ @@ -461789,7 +461963,7 @@ "reftest" ], "webvtt/rendering/cues-with-video/processing-model/2_tracks-ref.html": [ - "9bc6d9278ae2ce4f2a7d94b06f362c04acd1fa37", + "1a46c4d83f8dab463739d1928c4fd87d4975f2bb", "support" ], "webvtt/rendering/cues-with-video/processing-model/2_tracks.html": [ @@ -461797,7 +461971,7 @@ "reftest" ], "webvtt/rendering/cues-with-video/processing-model/3_tracks-ref.html": [ - "46f861579ac0c4753fd0cd67a41b3cc085bf9d86", + "bec3c0557ca557457f113c95a79cc3132899c373", "support" ], "webvtt/rendering/cues-with-video/processing-model/3_tracks.html": [
diff --git a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-002.https.html b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-002.https.html index 6fc16c7..b1b50e0 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-002.https.html +++ b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-002.https.html
@@ -25,7 +25,8 @@ } }); } catch(ex) { - if (ex.name == "TypeError" && ex.message == "Failed to execute 'registerPaint' on 'PaintWorkletGlobalScope': The provided value cannot be converted to a sequence.") + // 'inputArguments' property is a string, not a sequence. + if (ex.name == 'TypeError') testsPassed = true; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-003.https.html b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-003.https.html index 44fd850..3b1b0014 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-003.https.html +++ b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-003.https.html
@@ -25,7 +25,8 @@ } }); } catch(ex) { - if (ex.name == "TypeError" && ex.message == "Failed to execute 'registerPaint' on 'PaintWorkletGlobalScope': Invalid argument types.") + // 'non-sense-type' is not a proper name of CSS properties. + if (ex.name == 'TypeError') testsPassed = true; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-005.https.html b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-005.https.html index c12e00c..0c5e539 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-005.https.html +++ b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-005.https.html
@@ -22,7 +22,8 @@ registerPaint('foo', class { paint() { } }); registerPaint('foo', class { paint() { } }); } catch(ex) { - if (ex.name == "NotSupportedError" && ex.message == "Failed to execute 'registerPaint' on 'PaintWorkletGlobalScope': A class with name:'foo' is already registered.") + // 'foo' gets registered twice. + if (ex.name == 'InvalidModificationError') testsPassed = true; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-006.https.html b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-006.https.html index 664b7a8c..e99ab05 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-006.https.html +++ b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-006.https.html
@@ -21,7 +21,8 @@ try { registerPaint('', class { }); } catch(ex) { - if (ex.name == 'TypeError' && ex.message == "Failed to execute 'registerPaint' on 'PaintWorkletGlobalScope': The empty string is not a valid name.") + // The empty string is not a valid name. + if (ex.name == 'TypeError') testsPassed = true; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-008.https.html b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-008.https.html index 1914e3c..e6b863c64 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-008.https.html +++ b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-008.https.html
@@ -25,7 +25,8 @@ } }); } catch(ex) { - if (ex.name == 'TypeError' && ex.message == "Failed to execute 'registerPaint' on 'PaintWorkletGlobalScope': The provided value cannot be converted to a sequence.") + // 'inputProperties' property is 42, not a sequence<DOMString>. + if (ex.name == 'TypeError') testsPassed = true; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-009.https.html b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-009.https.html index 21d004d..b23191a 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-009.https.html +++ b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-009.https.html
@@ -23,7 +23,8 @@ a.prototype = undefined; registerPaint('foo5', a); } catch(ex) { - if (ex.name == 'TypeError' && ex.message == "Failed to execute 'registerPaint' on 'PaintWorkletGlobalScope': The 'prototype' object on the class does not exist.") + // The prototype object is undefined, not an object. + if (ex.name == 'TypeError') testsPassed = true; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-010.https.html b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-010.https.html index d923479e..e98b4316 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-010.https.html +++ b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-010.https.html
@@ -23,7 +23,8 @@ b.prototype = 42; registerPaint('foo6', b); } catch(ex) { - if (ex.name == 'TypeError' && ex.message == "Failed to execute 'registerPaint' on 'PaintWorkletGlobalScope': The 'prototype' property on the class is not an object.") + // The prototype object is 42, not an object. + if (ex.name == 'TypeError') testsPassed = true; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-011.https.html b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-011.https.html index 6cea438f..b9d54bf 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-011.https.html +++ b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-011.https.html
@@ -21,7 +21,8 @@ try { registerPaint('foo7', class { }); } catch(ex) { - if (ex.name == 'TypeError' && ex.message == "Failed to execute 'registerPaint' on 'PaintWorkletGlobalScope': The 'paint' property on the prototype does not exist.") + // 'paint' property doesn't exist on the prototype chain. + if (ex.name == 'TypeError') testsPassed = true; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-012.https.html b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-012.https.html index 938150a..14eebeb 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-012.https.html +++ b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-012.https.html
@@ -25,7 +25,8 @@ } }); } catch(ex) { - if (ex.name == 'TypeError' && ex.message == "Failed to execute 'registerPaint' on 'PaintWorkletGlobalScope': The 'paint' property on the prototype is not a function.") + // 'paint' property's value is 42, not a function. + if (ex.name == 'TypeError') testsPassed = true; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-016.https.html b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-016.https.html index 8c9d05d..31cca45f 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-016.https.html +++ b/third_party/blink/web_tests/external/wpt/css/css-paint-api/parse-input-arguments-016.https.html
@@ -25,7 +25,8 @@ } }); } catch(ex) { - if (ex.name == "TypeError" && ex.message == "Failed to execute 'registerPaint' on 'PaintWorkletGlobalScope': cannot convert to dictionary.") + // 'contextOptions' property is 42, not a dictionary. + if (ex.name == 'TypeError') testsPassed = true; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-001.html b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-001.html new file mode 100644 index 0000000..d6f8ed4 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-001.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<link rel="help" href="https://drafts.csswg.org/css2/visudet.html#abs-non-replaced-width" /> +<link rel="match" href="../../reference/ref-filled-green-100px-square-only.html"> +<meta name="assert" content="Tests the static position of inline-level absolute-positioned elements, with combinations of float, direction, and text-align." /> +<style> +#container { position: relative; background: red; width: 100px; height: 100px; } +#container > div { background: green; } +#inflow { height: 50px; } +#float { float: left; width: 50px; height: 50px; } +#abs { display: inline; position: absolute; width: 50px; height: 50px; } +</style> +<p>Test passes if there is a filled green square.</p> +<div id=container style="direction: ltr; text-align: left;"> + <div id=inflow></div> + <div id=float style="float: left;"></div> + <div id=abs style="transform: translateX(0%);"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-002.html b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-002.html new file mode 100644 index 0000000..9b0f5c2 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-002.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<link rel="help" href="https://drafts.csswg.org/css2/visudet.html#abs-non-replaced-width" /> +<link rel="match" href="../../reference/ref-filled-green-100px-square-only.html"> +<meta name="assert" content="Tests the static position of inline-level absolute-positioned elements, with combinations of float, direction, and text-align." /> +<style> +#container { position: relative; background: red; width: 100px; height: 100px; } +#container > div { background: green; } +#inflow { height: 50px; } +#float { float: left; width: 50px; height: 50px; } +#abs { display: inline; position: absolute; width: 50px; height: 50px; } +</style> +<p>Test passes if there is a filled green square.</p> +<div id=container style="direction: ltr; text-align: center;"> + <div id=inflow></div> + <div id=float style="float: left;"></div> + <div id=abs style="transform: translateX(-50%);"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-003.html b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-003.html new file mode 100644 index 0000000..90db2d4f80 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-003.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<link rel="help" href="https://drafts.csswg.org/css2/visudet.html#abs-non-replaced-width" /> +<link rel="match" href="../../reference/ref-filled-green-100px-square-only.html"> +<meta name="assert" content="Tests the static position of inline-level absolute-positioned elements, with combinations of float, direction, and text-align." /> +<style> +#container { position: relative; background: red; width: 100px; height: 100px; } +#container > div { background: green; } +#inflow { height: 50px; } +#float { float: left; width: 50px; height: 50px; } +#abs { display: inline; position: absolute; width: 50px; height: 50px; } +</style> +<p>Test passes if there is a filled green square.</p> +<div id=container style="direction: ltr; text-align: right;"> + <div id=inflow></div> + <div id=float style="float: left;"></div> + <div id=abs style="transform: translateX(-100%);"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-004.html b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-004.html new file mode 100644 index 0000000..a6b13b2 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-004.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<link rel="help" href="https://drafts.csswg.org/css2/visudet.html#abs-non-replaced-width" /> +<link rel="match" href="../../reference/ref-filled-green-100px-square-only.html"> +<meta name="assert" content="Tests the static position of inline-level absolute-positioned elements, with combinations of float, direction, and text-align." /> +<style> +#container { position: relative; background: red; width: 100px; height: 100px; } +#container > div { background: green; } +#inflow { height: 50px; } +#float { float: left; width: 50px; height: 50px; } +#abs { display: inline; position: absolute; width: 50px; height: 50px; } +</style> +<p>Test passes if there is a filled green square.</p> +<div id=container style="direction: ltr; text-align: left;"> + <div id=inflow></div> + <div id=float style="float: right;"></div> + <div id=abs style="transform: translateX(0%);"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-005.html b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-005.html new file mode 100644 index 0000000..481c83a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-005.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<link rel="help" href="https://drafts.csswg.org/css2/visudet.html#abs-non-replaced-width" /> +<link rel="match" href="../../reference/ref-filled-green-100px-square-only.html"> +<meta name="assert" content="Tests the static position of inline-level absolute-positioned elements, with combinations of float, direction, and text-align." /> +<style> +#container { position: relative; background: red; width: 100px; height: 100px; } +#container > div { background: green; } +#inflow { height: 50px; } +#float { float: left; width: 50px; height: 50px; } +#abs { display: inline; position: absolute; width: 50px; height: 50px; } +</style> +<p>Test passes if there is a filled green square.</p> +<div id=container style="direction: ltr; text-align: center;"> + <div id=inflow></div> + <div id=float style="float: right;"></div> + <div id=abs style="transform: translateX(-50%);"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-006.html b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-006.html new file mode 100644 index 0000000..de5322f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-006.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<link rel="help" href="https://drafts.csswg.org/css2/visudet.html#abs-non-replaced-width" /> +<link rel="match" href="../../reference/ref-filled-green-100px-square-only.html"> +<meta name="assert" content="Tests the static position of inline-level absolute-positioned elements, with combinations of float, direction, and text-align." /> +<style> +#container { position: relative; background: red; width: 100px; height: 100px; } +#container > div { background: green; } +#inflow { height: 50px; } +#float { float: left; width: 50px; height: 50px; } +#abs { display: inline; position: absolute; width: 50px; height: 50px; } +</style> +<p>Test passes if there is a filled green square.</p> +<div id=container style="direction: ltr; text-align: right;"> + <div id=inflow></div> + <div id=float style="float: right;"></div> + <div id=abs style="transform: translateX(-100%);"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-007.html b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-007.html new file mode 100644 index 0000000..1168b1d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-007.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<link rel="help" href="https://drafts.csswg.org/css2/visudet.html#abs-non-replaced-width" /> +<link rel="match" href="../../reference/ref-filled-green-100px-square-only.html"> +<meta name="assert" content="Tests the static position of inline-level absolute-positioned elements, with combinations of float, direction, and text-align." /> +<style> +#container { position: relative; background: red; width: 100px; height: 100px; } +#container > div { background: green; } +#inflow { height: 50px; } +#float { float: left; width: 50px; height: 50px; } +#abs { display: inline; position: absolute; width: 50px; height: 50px; } +</style> +<p>Test passes if there is a filled green square.</p> +<div id=container style="direction: rtl; text-align: right;"> + <div id=inflow></div> + <div id=float style="float: left;"></div> + <div id=abs style="transform: translateX(0%);"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-008.html b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-008.html new file mode 100644 index 0000000..e10a7e1 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-008.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<link rel="help" href="https://drafts.csswg.org/css2/visudet.html#abs-non-replaced-width" /> +<link rel="match" href="../../reference/ref-filled-green-100px-square-only.html"> +<meta name="assert" content="Tests the static position of inline-level absolute-positioned elements, with combinations of float, direction, and text-align." /> +<style> +#container { position: relative; background: red; width: 100px; height: 100px; } +#container > div { background: green; } +#inflow { height: 50px; } +#float { float: left; width: 50px; height: 50px; } +#abs { display: inline; position: absolute; width: 50px; height: 50px; } +</style> +<p>Test passes if there is a filled green square.</p> +<div id=container style="direction: rtl; text-align: center;"> + <div id=inflow></div> + <div id=float style="float: left;"></div> + <div id=abs style="transform: translateX(50%);"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-009.html b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-009.html new file mode 100644 index 0000000..86102fa --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-009.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<link rel="help" href="https://drafts.csswg.org/css2/visudet.html#abs-non-replaced-width" /> +<link rel="match" href="../../reference/ref-filled-green-100px-square-only.html"> +<meta name="assert" content="Tests the static position of inline-level absolute-positioned elements, with combinations of float, direction, and text-align." /> +<style> +#container { position: relative; background: red; width: 100px; height: 100px; } +#container > div { background: green; } +#inflow { height: 50px; } +#float { float: left; width: 50px; height: 50px; } +#abs { display: inline; position: absolute; width: 50px; height: 50px; } +</style> +<p>Test passes if there is a filled green square.</p> +<div id=container style="direction: rtl; text-align: left;"> + <div id=inflow></div> + <div id=float style="float: left;"></div> + <div id=abs style="transform: translateX(100%);"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-010.html b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-010.html new file mode 100644 index 0000000..95d43b9c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-010.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<link rel="help" href="https://drafts.csswg.org/css2/visudet.html#abs-non-replaced-width" /> +<link rel="match" href="../../reference/ref-filled-green-100px-square-only.html"> +<meta name="assert" content="Tests the static position of inline-level absolute-positioned elements, with combinations of float, direction, and text-align." /> +<style> +#container { position: relative; background: red; width: 100px; height: 100px; } +#container > div { background: green; } +#inflow { height: 50px; } +#float { float: left; width: 50px; height: 50px; } +#abs { display: inline; position: absolute; width: 50px; height: 50px; } +</style> +<p>Test passes if there is a filled green square.</p> +<div id=container style="direction: rtl; text-align: right;"> + <div id=inflow></div> + <div id=float style="float: right;"></div> + <div id=abs style="transform: translateX(0%);"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-011.html b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-011.html new file mode 100644 index 0000000..3755663 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-011.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<link rel="help" href="https://drafts.csswg.org/css2/visudet.html#abs-non-replaced-width" /> +<link rel="match" href="../../reference/ref-filled-green-100px-square-only.html"> +<meta name="assert" content="Tests the static position of inline-level absolute-positioned elements, with combinations of float, direction, and text-align." /> +<style> +#container { position: relative; background: red; width: 100px; height: 100px; } +#container > div { background: green; } +#inflow { height: 50px; } +#float { float: left; width: 50px; height: 50px; } +#abs { display: inline; position: absolute; width: 50px; height: 50px; } +</style> +<p>Test passes if there is a filled green square.</p> +<div id=container style="direction: rtl; text-align: center;"> + <div id=inflow></div> + <div id=float style="float: right;"></div> + <div id=abs style="transform: translateX(50%);"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-012.html b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-012.html new file mode 100644 index 0000000..1972317 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-012.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<link rel="help" href="https://drafts.csswg.org/css2/visudet.html#abs-non-replaced-width" /> +<link rel="match" href="../../reference/ref-filled-green-100px-square-only.html"> +<meta name="assert" content="Tests the static position of inline-level absolute-positioned elements, with combinations of float, direction, and text-align." /> +<style> +#container { position: relative; background: red; width: 100px; height: 100px; } +#container > div { background: green; } +#inflow { height: 50px; } +#float { float: left; width: 50px; height: 50px; } +#abs { display: inline; position: absolute; width: 50px; height: 50px; } +</style> +<p>Test passes if there is a filled green square.</p> +<div id=container style="direction: rtl; text-align: left;"> + <div id=inflow></div> + <div id=float style="float: right;"></div> + <div id=abs style="transform: translateX(100%);"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-scroll-snap/scroll-snap-stop-always.html b/third_party/blink/web_tests/external/wpt/css/css-scroll-snap/scroll-snap-stop-always.html new file mode 100644 index 0000000..62446f5 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-scroll-snap/scroll-snap-stop-always.html
@@ -0,0 +1,71 @@ +<!DOCTYPE html> +<link rel="help" href="https://drafts.csswg.org/css-scroll-snap/#scroll-snap-stop" /> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<style> +div { + position: absolute; +} +#scroller { + width: 400px; + height: 400px; + overflow: scroll; + scroll-snap-type: both mandatory; +} +#space { + left: 0px; + top: 0px; + width: 2100px; + height: 2100px; +} +.target { + width: 50px; + height: 50px; + scroll-snap-align: start; +} +.origin { + left: 0px; + top: 0px; +} +.always-stop { + left: 100px; + top: 0px; + scroll-snap-stop: always; +} +.closer { + left: 200px; + top: 0px; +} +</style> + +<div id="scroller"> + <div id="space"></div> + <div class="target origin"></div> + <div class="target always-stop"></div> + <div class="target closer"></div> +</div> + +<script> +var scroller = document.getElementById("scroller"); +test(() => { + scroller.scrollTo(0, 0); + assert_equals(scroller.scrollLeft, 0); + assert_equals(scroller.scrollTop, 0); + + scroller.scrollBy(300, 0); + assert_equals(scroller.scrollLeft, 100); + assert_equals(scroller.scrollTop, 0); +}, "A scroll with intended direction and end position should not pass a snap " + + "area with scroll-snap-stop: always.") + +test(() => { + scroller.scrollTo(0, 0); + assert_equals(scroller.scrollLeft, 0); + assert_equals(scroller.scrollTop, 0); + + scroller.scrollTo(300, 0); + assert_equals(scroller.scrollLeft, 200); + assert_equals(scroller.scrollTop, 0); +}, "A scroll with intended end position should always choose the closest snap " + + "position regardless of the scroll-snap-stop value.") +</script>
diff --git a/third_party/blink/web_tests/external/wpt/custom-elements/HTMLElement-attachInternals-expected.txt b/third_party/blink/web_tests/external/wpt/custom-elements/HTMLElement-attachInternals-expected.txt new file mode 100644 index 0000000..9101726 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/custom-elements/HTMLElement-attachInternals-expected.txt
@@ -0,0 +1,9 @@ +This is a testharness.js-based test. +PASS Successful attachInternals() and the second call. +FAIL attachInternals() throws a NotSupportedError if it is called for a customized built-in element assert_throws: function "() => { customizedBuiltin.attachInternals() }" threw object "InvalidStateError: Failed to execute 'attachInternals' on 'HTMLElement': Unable to attach ElementInternals to non-custom elements." that is not a DOMException NotSupportedError: property "code" is equal to 11, expected 9 +PASS If a custom element definition for the local name of the element doesn't exist, throw an InvalidStateError +FAIL If a custom element definition for the local name of the element has disable internals flag, throw a NotSupportedError assert_throws: function "() => { + (new MyElement2).attachInternals(); + }" threw object "InvalidStateError: Failed to execute 'attachInternals' on 'HTMLElement': ElementInternals is disabled by disabledFeature static field." that is not a DOMException NotSupportedError: property "code" is equal to 11, expected 9 +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/custom-elements/HTMLElement-attachInternals.html b/third_party/blink/web_tests/external/wpt/custom-elements/HTMLElement-attachInternals.html new file mode 100644 index 0000000..e5379830 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/custom-elements/HTMLElement-attachInternals.html
@@ -0,0 +1,82 @@ +<!DOCTYPE html> +<body> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<link rel="help" content="https://html.spec.whatwg.org/multipage/custom-elements.html#dom-attachinternals"> +<div id="container"></div> +<script> +test(() => { + class MyElement1 extends HTMLElement { + } + customElements.define('my-element1', MyElement1); + const container = document.querySelector('#container'); + + let element = new MyElement1(); + assert_true(element.attachInternals() instanceof ElementInternals, + 'New - 1st call'); + assert_throws('InvalidStateError', () => { element.attachInternals(); }, + 'New - 2nd call'); + + element = document.createElement('my-element1'); + assert_true(element.attachInternals() instanceof ElementInternals, + 'createElement - 1st call'); + assert_throws('InvalidStateError', () => { element.attachInternals(); }, + 'createElement - 2nd call'); + + container.innerHTML = '<my-element1></my-element1>'; + assert_true(container.firstChild.attachInternals() instanceof ElementInternals, + 'Parser - 1st call'); + assert_throws('InvalidStateError', () => { + container.firstChild.attachInternals(); + }, 'Parser - 2nd call'); +}, 'Successful attachInternals() and the second call.'); + +test(() => { + class MyDiv extends HTMLDivElement {} + customElements.define('my-div', MyDiv, { extends: 'div' }); + const customizedBuiltin = document.createElement('div', { is: 'my-div'}); + assert_throws('NotSupportedError', () => { customizedBuiltin.attachInternals() }); +}, 'attachInternals() throws a NotSupportedError if it is called for ' + + 'a customized built-in element'); + +test(() => { + const builtin = document.createElement('div'); + assert_throws('InvalidStateError', () => { builtin.attachInternals() }); + + const doc = document.implementation.createDocument('foo', null); + const span = doc.appendChild(doc.createElementNS('http://www.w3.org/1999/xhtml', 'html:span')); + assert_true(span instanceof HTMLElement); + assert_throws('InvalidStateError', () => { span.attachInternals(); }); + + const undefinedCustom = document.createElement('undefined-element'); + assert_throws('InvalidStateError', () => { undefinedCustom.attachInternals() }); +}, 'If a custom element definition for the local name of the element doesn\'t' + + ' exist, throw an InvalidStateError'); + +test(() => { + class MyElement2 extends HTMLElement { + static get disabledFeatures() { return ['internals']; } + } + customElements.define('my-element2', MyElement2); + const container = document.querySelector('#container'); + + assert_throws('NotSupportedError', () => { + (new MyElement2).attachInternals(); + }); + assert_throws('NotSupportedError', () => { + document.createElement('my-element2').attachInternals(); + }); + assert_throws('NotSupportedError', () => { + container.innerHTML = '<my-element2></my-element2>'; + container.firstChild.attachInternals(); + }); + + class MyElement3 extends HTMLElement { + static get disabledFeatures() { return ['INTERNALS']; } + } + customElements.define('my-element3', MyElement3); + assert_true((new MyElement3).attachInternals() instanceof ElementInternals); +}, 'If a custom element definition for the local name of the element has ' + + 'disable internals flag, throw a NotSupportedError'); +</script> +</body>
diff --git "a/third_party/blink/web_tests/external/wpt/html/dom/interfaces.https_exclude=\050Document_Window_HTML._\051-expected.txt" "b/third_party/blink/web_tests/external/wpt/html/dom/interfaces.https_exclude=\050Document_Window_HTML._\051-expected.txt" index d9a59c8..84ed1fbd 100644 --- "a/third_party/blink/web_tests/external/wpt/html/dom/interfaces.https_exclude=\050Document_Window_HTML._\051-expected.txt" +++ "b/third_party/blink/web_tests/external/wpt/html/dom/interfaces.https_exclude=\050Document_Window_HTML._\051-expected.txt"
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 1148 tests; 1131 PASS, 17 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 1154 tests; 1137 PASS, 17 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 @@ -643,6 +643,12 @@ PASS CustomElementRegistry interface: operation get(DOMString) PASS CustomElementRegistry interface: operation whenDefined(DOMString) PASS CustomElementRegistry interface: operation upgrade(Node) +PASS ElementInternals interface: existence and properties of interface object +PASS ElementInternals interface object length +PASS ElementInternals interface object name +PASS ElementInternals interface: existence and properties of interface prototype object +PASS ElementInternals interface: existence and properties of interface prototype object's "constructor" property +PASS ElementInternals interface: existence and properties of interface prototype object's @@unscopables property PASS DataTransfer interface: existence and properties of interface object PASS DataTransfer interface object length PASS DataTransfer interface object name
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 826eb52..1d5d27d 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 3593 tests; 3546 PASS, 47 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 3595 tests; 3548 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 @@ -100,6 +100,7 @@ PASS HTMLElement interface: attribute spellcheck PASS HTMLElement interface: attribute autocapitalize PASS HTMLElement interface: attribute innerText +PASS HTMLElement interface: operation attachInternals() PASS HTMLElement interface: attribute onabort PASS HTMLElement interface: attribute onauxclick PASS HTMLElement interface: attribute onblur @@ -189,6 +190,7 @@ PASS HTMLElement interface: document.createElement("noscript") must inherit property "spellcheck" with the proper type PASS HTMLElement interface: document.createElement("noscript") must inherit property "autocapitalize" with the proper type PASS HTMLElement interface: document.createElement("noscript") must inherit property "innerText" with the proper type +PASS HTMLElement interface: document.createElement("noscript") must inherit property "attachInternals()" with the proper type PASS HTMLElement interface: document.createElement("noscript") must inherit property "onabort" with the proper type PASS HTMLElement interface: document.createElement("noscript") must inherit property "onauxclick" with the proper type PASS HTMLElement interface: document.createElement("noscript") must inherit property "onblur" with the proper type
diff --git a/third_party/blink/web_tests/external/wpt/html/dom/interfaces.worker-expected.txt b/third_party/blink/web_tests/external/wpt/html/dom/interfaces.worker-expected.txt index e00efd4..421fe46 100644 --- a/third_party/blink/web_tests/external/wpt/html/dom/interfaces.worker-expected.txt +++ b/third_party/blink/web_tests/external/wpt/html/dom/interfaces.worker-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 652 tests; 611 PASS, 41 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 653 tests; 612 PASS, 41 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 @@ -278,6 +278,7 @@ PASS OffscreenCanvasRenderingContext2D interface: operation arc(unrestricted double, unrestricted double, unrestricted double, unrestricted double, unrestricted double, boolean) PASS OffscreenCanvasRenderingContext2D interface: operation ellipse(unrestricted double, unrestricted double, unrestricted double, unrestricted double, unrestricted double, unrestricted double, unrestricted double, boolean) PASS CustomElementRegistry interface: existence and properties of interface object +PASS ElementInternals interface: existence and properties of interface object PASS DataTransfer interface: existence and properties of interface object PASS DataTransferItemList interface: existence and properties of interface object PASS DataTransferItem interface: existence and properties of interface object
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_anchor_download_allow_downloads_without_user_activation.sub.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_anchor_download_allow_downloads_without_user_activation.sub.tentative.html new file mode 100644 index 0000000..32409f2 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_anchor_download_allow_downloads_without_user_activation.sub.tentative.html
@@ -0,0 +1,31 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title><a download> triggered download in sandbox is allowed by allow-downloads-without-user-activation.</title> +<link rel="help" href="https://html.spec.whatwg.org/multipage/#attr-iframe-sandbox"> +<link rel="help" href="https://html.spec.whatwg.org/multipage/#the-iframe-element"> +<script src="/resources/testharness.js"></script> +<script src='/resources/testharnessreport.js'></script> +<script src="support/iframe_sandbox_download_helper.js"></script> +<body> +<script> +"use strict"; + +async_test(t => { + const token = "{{$id:uuid()}}"; + var iframe = document.createElement("iframe"); + iframe.srcdoc = "<a>Download</a>"; + iframe.sandbox = "allow-same-origin allow-downloads-without-user-activation"; + iframe.onload = t.step_func(function () { + iframe.contentWindow.addEventListener( + "unload", t.unreached_func("Unexpected navigation.")); + var anchor = iframe.contentDocument.getElementsByTagName('a')[0]; + anchor.href = "support/download_stash.py?token=" + token; + anchor.download = null; + anchor.click(); + AssertDownloadSuccess(t, token, DownloadVerifyDelay()); + }); + + document.body.appendChild(iframe); +}, "<a download> triggered download in sandbox is allowed by allow-downloads-without-user-activation."); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_anchor_download_block_downloads_without_user_activation.sub.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_anchor_download_block_downloads_without_user_activation.sub.tentative.html new file mode 100644 index 0000000..abd4d7c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_anchor_download_block_downloads_without_user_activation.sub.tentative.html
@@ -0,0 +1,31 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title><a download> triggered download in sandbox is blocked.</title> +<link rel="help" href="https://html.spec.whatwg.org/multipage/#attr-iframe-sandbox"> +<link rel="help" href="https://html.spec.whatwg.org/multipage/#the-iframe-element"> +<script src="/resources/testharness.js"></script> +<script src='/resources/testharnessreport.js'></script> +<script src="support/iframe_sandbox_download_helper.js"></script> +<body> +<script> +"use strict"; + +async_test(t => { + const token = "{{$id:uuid()}}"; + var iframe = document.createElement("iframe"); + iframe.srcdoc = "<a>Download</a>"; + iframe.sandbox = "allow-same-origin"; + iframe.onload = t.step_func(function () { + iframe.contentWindow.addEventListener( + "unload", t.unreached_func("Unexpected navigation.")); + var anchor = iframe.contentDocument.getElementsByTagName('a')[0]; + anchor.href = "support/download_stash.py?token=" + token; + anchor.download = null; + anchor.click(); + AssertDownloadFailure(t, token, DownloadVerifyDelay()); + }); + + document.body.appendChild(iframe); +}, "<a download> triggered download in sandbox is blocked."); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_navigation_download_allow_downloads_without_user_activation.sub.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_navigation_download_allow_downloads_without_user_activation.sub.tentative.html new file mode 100644 index 0000000..4fee27f9 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_navigation_download_allow_downloads_without_user_activation.sub.tentative.html
@@ -0,0 +1,33 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Navigation resulted download in sandbox is allowed by allow-downloads-without-user-activation.</title> +<link rel="help" href="https://html.spec.whatwg.org/multipage/#attr-iframe-sandbox"> +<link rel="help" href="https://html.spec.whatwg.org/multipage/#the-iframe-element"> +<script src="/resources/testharness.js"></script> +<script src='/resources/testharnessreport.js'></script> +<script src="support/iframe_sandbox_download_helper.js"></script> +<body> +<script> +"use strict"; + +async_test(t => { + const token = "{{$id:uuid()}}"; + var iframe = document.createElement("iframe"); + iframe.srcdoc = "<a>Download</a>"; + iframe.sandbox = "allow-same-origin allow-downloads-without-user-activation"; + iframe.onload = t.step_func(function () { + iframe.contentWindow.addEventListener( + "unload", t.unreached_func("Unexpected navigation.")); + var anchor = iframe.contentDocument.getElementsByTagName('a')[0]; + // Set |finish-delay| to let the server stream a response over a period + // of time, so it's able to catch potential download cancellation by + // detecting a socket close. + anchor.href = "support/download_stash.py?token=" + token + "&finish-delay=" + StreamDownloadFinishDelay(); + anchor.click(); + AssertDownloadSuccess(t, token, StreamDownloadFinishDelay() + DownloadVerifyDelay()); + }); + + document.body.appendChild(iframe); +}, "Navigation resulted download in sandbox is allowed by allow-downloads-without-user-activation."); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_navigation_download_block_downloads_without_user_activation.sub.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_navigation_download_block_downloads_without_user_activation.sub.tentative.html new file mode 100644 index 0000000..9b9246c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_navigation_download_block_downloads_without_user_activation.sub.tentative.html
@@ -0,0 +1,33 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Navigation resulted download in sandbox is blocked.</title> +<link rel="help" href="https://html.spec.whatwg.org/multipage/#attr-iframe-sandbox"> +<link rel="help" href="https://html.spec.whatwg.org/multipage/#the-iframe-element"> +<script src="/resources/testharness.js"></script> +<script src='/resources/testharnessreport.js'></script> +<script src="support/iframe_sandbox_download_helper.js"></script> +<body> +<script> +"use strict"; + +async_test(t => { + const token = "{{$id:uuid()}}"; + var iframe = document.createElement("iframe"); + iframe.srcdoc = "<a>Download</a>"; + iframe.sandbox = "allow-same-origin"; + iframe.onload = t.step_func(function () { + iframe.contentWindow.addEventListener( + "unload", t.unreached_func("Unexpected navigation.")); + var anchor = iframe.contentDocument.getElementsByTagName('a')[0]; + // Set |finish-delay| to let the server stream a response over a period + // of time, so it's able to catch potential download cancellation by + // detecting a socket close. + anchor.href = "support/download_stash.py?token=" + token + "&finish-delay=" + StreamDownloadFinishDelay(); + anchor.click(); + AssertDownloadFailure(t, token, StreamDownloadFinishDelay() + DownloadVerifyDelay()); + }); + + document.body.appendChild(iframe); +}, "Navigation resulted download in sandbox is blocked."); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/support/download_stash.py b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/support/download_stash.py new file mode 100644 index 0000000..24e1dfd --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/support/download_stash.py
@@ -0,0 +1,28 @@ +import time + +def main(request, response): + token = request.GET["token"] + response.status = 200 + response.headers.append("Content-Type", "text/html") + if "verify-token" in request.GET: + if request.server.stash.take(token): + return 'TOKEN_SET' + return 'TOKEN_NOT_SET' + + if "finish-delay" not in request.GET: + # <a download> + request.server.stash.put(token, True) + return + + # navigation to download + response.headers.append("Content-Disposition", "attachment") + response.write_status_headers() + finish_delay = float(request.GET["finish-delay"]) / 1E3 + count = 10 + single_delay = finish_delay / count + for i in range(count): # pylint: disable=unused-variable + time.sleep(single_delay) + response.writer.write_content("\n") + if not response.writer.flush(): + return + request.server.stash.put(token, True)
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/support/iframe_sandbox_download_helper.js b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/support/iframe_sandbox_download_helper.js new file mode 100644 index 0000000..7090e76 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-iframe-element/support/iframe_sandbox_download_helper.js
@@ -0,0 +1,37 @@ +function StreamDownloadFinishDelay() { + return 1000; +} + +function DownloadVerifyDelay() { + return 1000; +} + +function VerifyDownload(test_obj, token, timeout, expect_download) { + var verify_token = test_obj.step_func(function () { + var xhr = new XMLHttpRequest(); + xhr.open('GET', 'support/download_stash.py?verify-token&token=' + token); + xhr.onload = test_obj.step_func(function(e) { + if (expect_download) { + if (xhr.response != "TOKEN_SET") { + // Always retry, and rely on the test timeout to conclude that + // download didn't happen and to fail the test. + test_obj.step_timeout(verify_token, DownloadVerifyDelay()); + return; + } + } else { + assert_equals(xhr.response, "TOKEN_NOT_SET", "Expect no download to happen, but got one."); + } + test_obj.done(); + }); + xhr.send(); + }); + test_obj.step_timeout(verify_token, timeout); +} + +function AssertDownloadSuccess(test_obj, token, timeout) { + VerifyDownload(test_obj, token, timeout, true); +} + +function AssertDownloadFailure(test_obj, token, timeout) { + VerifyDownload(test_obj, token, timeout, false); +}
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 f530f355..641213d 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/html.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/html.idl
@@ -114,6 +114,8 @@ [CEReactions] attribute DOMString autocapitalize; [CEReactions] attribute [TreatNullAs=EmptyString] DOMString innerText; + + ElementInternals attachInternals(); }; HTMLElement includes GlobalEventHandlers; @@ -1410,6 +1412,11 @@ DOMString extends; }; +[Exposed=Window] +interface ElementInternals { + +}; + dictionary FocusOptions { boolean preventScroll = false; };
diff --git a/third_party/blink/web_tests/external/wpt/interfaces/netinfo.idl b/third_party/blink/web_tests/external/wpt/interfaces/netinfo.idl index a4876c9..7296783 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/netinfo.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/netinfo.idl
@@ -23,7 +23,7 @@ }; interface mixin NavigatorNetworkInformation { - readonly attribute NetworkInformation connection; + [SameObject] readonly attribute NetworkInformation connection; }; Navigator includes NavigatorNetworkInformation;
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 913d1fe8..11a36cd 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
@@ -3,20 +3,20 @@ // (https://github.com/tidoust/reffy-reports) // Source: Web NFC API (https://w3c.github.io/web-nfc/) -dictionary NFCMessage { - sequence<NFCRecord> records; +dictionary NDEFMessage { + sequence<NDEFRecord> records; USVString url; }; -typedef (DOMString or unrestricted double or ArrayBuffer or Dictionary) NFCRecordData; +typedef (DOMString or unrestricted double or ArrayBuffer or Dictionary) NDEFRecordData; -dictionary NFCRecord { - NFCRecordType recordType; +dictionary NDEFRecord { + NDEFRecordType recordType; USVString mediaType; - NFCRecordData data; + NDEFRecordData data; }; -enum NFCRecordType { +enum NDEFRecordType { "empty", "text", "url", @@ -24,11 +24,11 @@ "opaque" }; -typedef (DOMString or ArrayBuffer or NFCMessage) NFCMessageSource; +typedef (DOMString or ArrayBuffer or NDEFMessage) NDEFMessageSource; [Constructor(), SecureContext, Exposed=Window] interface NFCWriter { - Promise<void> push(NFCMessageSource message, optional NFCPushOptions options); + Promise<void> push(NDEFMessageSource message, optional NFCPushOptions options); }; [Constructor(optional NFCReaderOptions options), SecureContext, Exposed=Window] @@ -42,11 +42,11 @@ [Constructor(DOMString type, NFCReadingEventInit readingEventInitDict), SecureContext, Exposed=Window] interface NFCReadingEvent : Event { - readonly attribute NFCMessage message; + readonly attribute NDEFMessage message; }; dictionary NFCReadingEventInit : EventInit { - required NFCMessage message; + required NDEFMessage message; }; [Constructor(DOMString type, NFCErrorEventInit errorEventInitDict), SecureContext, Exposed=Window] @@ -58,11 +58,18 @@ required DOMException error; }; +enum NDEFCompatibility { + "nfc-forum", + "vendor", + "any" +}; + dictionary NFCPushOptions { NFCPushTarget target = "any"; unrestricted double timeout = Infinity; boolean ignoreRead = true; AbortSignal? signal; + NDEFCompatibility compatibility = "nfc-forum"; }; enum NFCPushTarget { @@ -73,6 +80,7 @@ dictionary NFCReaderOptions { USVString url = ""; - NFCRecordType recordType; + NDEFRecordType recordType; USVString mediaType = ""; + NDEFCompatibility compatibility = "nfc-forum"; };
diff --git a/third_party/blink/web_tests/external/wpt/longtask-timing/longtask-in-sibling-iframe.html b/third_party/blink/web_tests/external/wpt/longtask-timing/longtask-in-sibling-iframe.html index b8a42701..16f0998 100644 --- a/third_party/blink/web_tests/external/wpt/longtask-timing/longtask-in-sibling-iframe.html +++ b/third_party/blink/web_tests/external/wpt/longtask-timing/longtask-in-sibling-iframe.html
@@ -14,6 +14,10 @@ } window.addEventListener('message', t.step_func(e => { assert_equals(e.data['entryType'], 'longtask'); + // Ignore any long task that may be produced by the top-level frame. + if (e.data['frame-attribution'] === 'same-origin-ancestor') + return; + assert_equals(e.data['frame-attribution'], 'same-origin'); assert_equals(e.data['task-attribution'], 'unknown'); assert_equals(e.data['containerId'], 'longtask-iframe-id');
diff --git a/third_party/blink/web_tests/external/wpt/network-error-logging/support/nel.sub.js b/third_party/blink/web_tests/external/wpt/network-error-logging/support/nel.sub.js index 16aebd5..8fa8350 100644 --- a/third_party/blink/web_tests/external/wpt/network-error-logging/support/nel.sub.js +++ b/third_party/blink/web_tests/external/wpt/network-error-logging/support/nel.sub.js
@@ -55,7 +55,7 @@ */ function getURLForResourceWithBasicPolicy(subdomain) { - return _getNELResourceURL(subdomain, "pass.png?id="+reportID); + return _getNELResourceURL(subdomain, "pass.png?id="+reportID+"&success_fraction=1.0"); } function fetchResourceWithBasicPolicy(subdomain) { @@ -63,6 +63,11 @@ return fetch(url, {mode: "no-cors"}); } +function fetchResourceWithZeroSuccessFractionPolicy(subdomain) { + const url = _getNELResourceURL(subdomain, "pass.png?id="+reportID+"&success_fraction=0.0"); + return fetch(url, {mode: "no-cors"}); +} + /* * Fetches a resource whose headers define an include_subdomains NEL policy. */
diff --git a/third_party/blink/web_tests/external/wpt/network-error-logging/support/pass.png.sub.headers b/third_party/blink/web_tests/external/wpt/network-error-logging/support/pass.png.sub.headers index 70796e9..15d246d 100644 --- a/third_party/blink/web_tests/external/wpt/network-error-logging/support/pass.png.sub.headers +++ b/third_party/blink/web_tests/external/wpt/network-error-logging/support/pass.png.sub.headers
@@ -3,4 +3,4 @@ Cache-Control: post-check=0, pre-check=0, false Pragma: no-cache Report-To: { "group": "nel-group", "max_age": 10886400, "endpoints": [{ "url": "https://{{hosts[][www]}}:{{ports[https][0]}}/network-error-logging/support/report.py?op=put&reportID={{GET[id]}}" }] } -NEL: {"report_to": "nel-group", "max_age": 10886400, "success_fraction": 1.0} +NEL: {"report_to": "nel-group", "max_age": 10886400, "success_fraction": {{GET[success_fraction]}}}
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_fetch_error-downgraded.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_fetch_error-downgraded.tentative.html new file mode 100644 index 0000000..845b7e01 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_fetch_error-downgraded.tentative.html
@@ -0,0 +1,64 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.failed downgraded from sxg.cert_fetch_error for navigation</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; +const test_origin = get_host_info().HTTPS_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + '/signed-exchange/resources/sxg/sxg-cert-not-found.sxg?navigation'; + const cert_url = test_origin + '/signed-exchange/resources/not_found_certfile.cbor'; + const message = await openSXGInIframeAndWaitForMessage(t, sxg_url); + assert_equals(message.location, + innerURLOrigin() + '/signed-exchange/resources/inner-url.html'); + assert_true(message.is_fallback); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + // The origin of this SXG's certURL is different from the reporting + // origin. So the report must be downgraded. + type: "sxg.failed", + elapsed_time: 0, + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.failed downgraded from sxg.cert_fetch_error for' + + ' navigation.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_fetch_error.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_fetch_error.tentative.html new file mode 100644 index 0000000..476af82 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_fetch_error.tentative.html
@@ -0,0 +1,76 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.cert_fetch_error for navigation</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-cert-not-found-on-alt-origin.sxg?navigation'; + const cert_url = + alt_origin + '/signed-exchange/resources/not_found_certfile.cbor'; + const message = await openSXGInIframeAndWaitForMessage(t, sxg_url); + assert_equals(message.location, + innerURLOrigin() + '/signed-exchange/resources/inner-url.html'); + assert_true(message.is_fallback); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + // The origin of this SXG's certURL is same as the reporting origin. So + // the report must not be downgraded. + type: "sxg.cert_fetch_error", + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: cert_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "http.error", + status_code: 404, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.cert_fetch_error for navigation.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_parse_error-downgraded.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_parse_error-downgraded.tentative.html new file mode 100644 index 0000000..d962b88 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_parse_error-downgraded.tentative.html
@@ -0,0 +1,65 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.failed downgraded from sxg.cert_parse_error for navigation</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; +const test_origin = get_host_info().HTTPS_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-invalid-cert-format.sxg?navigation'; + const cert_url = + test_origin + '/signed-exchange/resources/invalid-cert-format.cbor'; + const message = await openSXGInIframeAndWaitForMessage(t, sxg_url); + assert_equals(message.location, + innerURLOrigin() + '/signed-exchange/resources/inner-url.html'); + assert_true(message.is_fallback); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + // The origin of this SXG's certURL is different from the reporting + // origin. So the report must be downgraded. + type: "sxg.failed", + elapsed_time: 0, + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.failed downgraded from sxg.cert_parse_error for navigation.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_parse_error.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_parse_error.tentative.html new file mode 100644 index 0000000..11dc4141 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_parse_error.tentative.html
@@ -0,0 +1,76 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.cert_parse_error for navigation</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-invalid-cert-format-on-alt-origin.sxg?navigation'; + const cert_url = + alt_origin + '/signed-exchange/resources/invalid-cert-format.cbor'; + const message = await openSXGInIframeAndWaitForMessage(t, sxg_url); + assert_equals(message.location, + innerURLOrigin() + '/signed-exchange/resources/inner-url.html'); + assert_true(message.is_fallback); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + // The origin of this SXG's certURL is same as the reporting origin. So + // the report must not be downgraded. + type: "sxg.cert_parse_error", + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: cert_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.cert_parse_error for navigation.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_verification_error-downgraded.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_verification_error-downgraded.tentative.html new file mode 100644 index 0000000..a1358e75 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_verification_error-downgraded.tentative.html
@@ -0,0 +1,65 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.failed downgraded from sxg.cert_verification_error for navigation</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; +const test_origin = get_host_info().HTTPS_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-validity-period-too-long.sxg?navigation'; + const cert_url = test_origin + '/signed-exchange/resources/127.0.0.1.sxg.pem.cbor'; + const message = await openSXGInIframeAndWaitForMessage(t, sxg_url); + assert_equals(message.location, + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', 'location'); + assert_true(message.is_fallback, 'is_fallback'); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + // The origin of this SXG's certURL is different from the reporting + // origin. So the report must be downgraded. + type: "sxg.failed", + elapsed_time: 0, + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.failed downgraded from ' + + 'sxg.cert_verification_error for navigation.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_verification_error.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_verification_error.tentative.html new file mode 100644 index 0000000..81520f9d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-cert_verification_error.tentative.html
@@ -0,0 +1,60 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.cert_verification_error for navigation</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-validity-period-too-long-cert-on-alt-origin.sxg?navigation'; + const cert_url = alt_origin + '/signed-exchange/resources/127.0.0.1.sxg.pem.cbor'; + const message = await openSXGInIframeAndWaitForMessage(t, sxg_url); + assert_equals(message.location, + innerURLOrigin() + '/signed-exchange/resources/inner-url.html'); + assert_true(message.is_fallback); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + type: "sxg.cert_verification_error", + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.cert_verification_error for navigation.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-failed-zero-success-fraction.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-failed-zero-success-fraction.tentative.html new file mode 100644 index 0000000..c0e06c8 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-failed-zero-success-fraction.tentative.html
@@ -0,0 +1,69 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.failed for navigation (zero success fraction)</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; +const test_origin = get_host_info().HTTPS_ORIGIN; + +nel_test(async t => { + await fetchResourceWithZeroSuccessFractionPolicy(); + const sxg_url = + alt_origin + '/signed-exchange/resources/sxg/sxg-cert-not-found.sxg?navigation'; + const cert_url = test_origin + '/signed-exchange/resources/not_found_certfile.cbor'; + const message = await openSXGInIframeAndWaitForMessage(t, sxg_url); + assert_equals(message.location, + innerURLOrigin() + '/signed-exchange/resources/inner-url.html'); + assert_true(message.is_fallback); + assert_true(await reportExists( + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + // The origin of this SXG's certURL is different from the reporting + // origin. So the report must be downgraded. + type: "sxg.failed", + elapsed_time: 0, + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: cert_url + } + }, + metadata: { + content_type: "application/reports+json", + }, + } + ), 'SXG error reporting must be downgraded when the cert URL is different ' + + 'from the reporting origin'); + assert_false(await reportExists( + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + } + ), 'Succeeded normal NEL report should not be sent when success fraction ' + + 'is zero.'); +}, 'SXG error report must be downgraded when the cert URL is different from ' + + 'the reporting origin. And succeeded normal NEL report should not be sent ' + + ' when success fraction is zero.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-invalid_integrity_header.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-invalid_integrity_header.tentative.html new file mode 100644 index 0000000..aaad0c8 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-invalid_integrity_header.tentative.html
@@ -0,0 +1,61 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.invalid_integrity_header for navigation</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; +const test_origin = get_host_info().HTTPS_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-invalid-integrity-header.sxg?navigation'; + const cert_url = test_origin + '/signed-exchange/resources/127.0.0.1.sxg.pem.cbor'; + const message = await openSXGInIframeAndWaitForMessage(t, sxg_url); + assert_equals(message.location, + innerURLOrigin() + '/signed-exchange/resources/inner-url.html'); + assert_true(message.is_fallback); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + type: "sxg.invalid_integrity_header", + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.invalid_integrity_header for navigation.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-mi_error.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-mi_error.tentative.html new file mode 100644 index 0000000..40d1ae0 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-mi_error.tentative.html
@@ -0,0 +1,67 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.mi_error for navigation</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; +const test_origin = get_host_info().HTTPS_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-merkle-integrity-error.sxg?navigation'; + const cert_url = test_origin + '/signed-exchange/resources/127.0.0.1.sxg.pem.cbor'; + try { + const message = await openSXGInIframeAndWaitForMessage(t, sxg_url); + if (message.is_fallback) { + assert_unreached('Fallback redirect should not have happened'); + } else { + assert_unreached('SXG should not have loaded'); + } + } catch (e) { + assert_equals(e, 'timeout'); + } + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + type: "sxg.mi_error", + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + } + ])); +}, 'SXG reporting test of sxg.mi_error for navigation.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-parse_error.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-parse_error.tentative.html new file mode 100644 index 0000000..aaaa387 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-parse_error.tentative.html
@@ -0,0 +1,64 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.parse_error for navigation</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-invalid-format.sxg?navigation'; + try { + const message = await openSXGInIframeAndWaitForMessage(t, sxg_url); + if (message.is_fallback) { + assert_unreached('Fallback redirect should not have happened'); + } else { + assert_unreached('SXG should not have loaded'); + } + } catch (e) { + assert_equals(e, 'timeout'); + } + + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + type: "sxg.parse_error", + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + cert_url: [] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.parse_error for navigation.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-signature_verification_error-downgraded.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-signature_verification_error-downgraded.tentative.html new file mode 100644 index 0000000..87bbc36 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-signature_verification_error-downgraded.tentative.html
@@ -0,0 +1,65 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.failed downgraded from sxg.signature_verification_error for navigation</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; +const test_origin = get_host_info().HTTPS_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-invalid-cert-sha256.sxg?navigation'; + const cert_url = test_origin + '/signed-exchange/resources/127.0.0.1.sxg.pem.cbor'; + const message = await openSXGInIframeAndWaitForMessage(t, sxg_url); + assert_equals(message.location, + innerURLOrigin() + '/signed-exchange/resources/inner-url.html'); + assert_true(message.is_fallback); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + // The origin of this SXG's certURL is different from the reporting + // origin. So the report must be downgraded. + type: "sxg.failed", + elapsed_time: 0, + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.failed downgraded from ' + + 'sxg.signature_verification_error for navigation.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-signature_verification_error.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-signature_verification_error.tentative.html new file mode 100644 index 0000000..f57fd4d5 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-navigation-signature_verification_error.tentative.html
@@ -0,0 +1,60 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.signature_verification_error for navigation</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-invalid-cert-sha256-cert-on-alt-origin.sxg?navigation'; + const cert_url = alt_origin + '/signed-exchange/resources/127.0.0.1.sxg.pem.cbor'; + const message = await openSXGInIframeAndWaitForMessage(t, sxg_url); + assert_equals(message.location, + innerURLOrigin() + '/signed-exchange/resources/inner-url.html'); + assert_true(message.is_fallback); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + type: "sxg.signature_verification_error", + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.signature_verification_error for navigation.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_fetch_error-downgraded.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_fetch_error-downgraded.tentative.html new file mode 100644 index 0000000..f663f35c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_fetch_error-downgraded.tentative.html
@@ -0,0 +1,62 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.failed downgraded from sxg.cert_fetch_error for prefetch</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; +const test_origin = get_host_info().HTTPS_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + '/signed-exchange/resources/sxg/sxg-cert-not-found.sxg?prefetch'; + const cert_url = + test_origin + '/signed-exchange/resources/not_found_certfile.cbor'; + addPrefetch(sxg_url); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + // The origin of this SXG's certURL is different from the reporting + // origin. So the report must be downgraded. + type: "sxg.failed", + elapsed_time: 0, + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.failed downgraded from ' + + 'sxg.cert_fetch_error for prefetch.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_fetch_error.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_fetch_error.tentative.html new file mode 100644 index 0000000..c17fc5c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_fetch_error.tentative.html
@@ -0,0 +1,73 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.cert_fetch_error for prefetch</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-cert-not-found-on-alt-origin.sxg?prefetch'; + const cert_url = + alt_origin + '/signed-exchange/resources/not_found_certfile.cbor'; + addPrefetch(sxg_url); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + // The origin of this SXG's certURL is same as the reporting origin. So + // the report must not be downgraded. + type: "sxg.cert_fetch_error", + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: cert_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "http.error", + status_code: 404, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.cert_fetch_error for prefetch.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_parse_error-downgraded.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_parse_error-downgraded.tentative.html new file mode 100644 index 0000000..f1a5eb17 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_parse_error-downgraded.tentative.html
@@ -0,0 +1,63 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.failed downgraded from sxg.cert_parse_error for prefetch</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; +const test_origin = get_host_info().HTTPS_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-invalid-cert-format.sxg?prefetch'; + const cert_url = + test_origin + '/signed-exchange/resources/invalid-cert-format.cbor'; + addPrefetch(sxg_url); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + // The origin of this SXG's certURL is different from the reporting + // origin. So the report must be downgraded. + type: "sxg.failed", + elapsed_time: 0, + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.failed downgraded from sxg.cert_parse_error for' + + ' prefetch.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_parse_error.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_parse_error.tentative.html new file mode 100644 index 0000000..00f41c0 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_parse_error.tentative.html
@@ -0,0 +1,73 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.cert_parse_error for prefetch</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-invalid-cert-format-on-alt-origin.sxg?prefetch'; + const cert_url = + alt_origin + '/signed-exchange/resources/invalid-cert-format.cbor'; + addPrefetch(sxg_url); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + // The origin of this SXG's certURL is same as the reporting origin. So + // the report must not be downgraded. + type: "sxg.cert_parse_error", + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: cert_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.cert_parse_error for prefetch.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_verification_error-downgraded.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_verification_error-downgraded.tentative.html new file mode 100644 index 0000000..4836dc1b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_verification_error-downgraded.tentative.html
@@ -0,0 +1,62 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.failed downgraded from sxg.cert_verification_error for prefetch</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; +const test_origin = get_host_info().HTTPS_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-validity-period-too-long.sxg?prefetch'; + const cert_url = test_origin + '/signed-exchange/resources/127.0.0.1.sxg.pem.cbor'; + addPrefetch(sxg_url); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + // The origin of this SXG's certURL is different from the reporting + // origin. So the report must be downgraded. + type: "sxg.failed", + elapsed_time: 0, + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.failed downgraded from ' + + 'sxg.cert_verification_error for prefetch.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_verification_error.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_verification_error.tentative.html new file mode 100644 index 0000000..441a17af --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-cert_verification_error.tentative.html
@@ -0,0 +1,57 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.cert_verification_error for prefetch</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-validity-period-too-long-cert-on-alt-origin.sxg?prefetch'; + const cert_url = alt_origin + '/signed-exchange/resources/127.0.0.1.sxg.pem.cbor'; + addPrefetch(sxg_url); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + type: "sxg.cert_verification_error", + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.cert_verification_error for prefetch.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-failed-zero-success-feaction.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-failed-zero-success-feaction.tentative.html new file mode 100644 index 0000000..b0f71030 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-failed-zero-success-feaction.tentative.html
@@ -0,0 +1,67 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.failed for prefetch (zero success fraction)</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; +const test_origin = get_host_info().HTTPS_ORIGIN; + +nel_test(async t => { + await fetchResourceWithZeroSuccessFractionPolicy(); + const sxg_url = + alt_origin + '/signed-exchange/resources/sxg/sxg-cert-not-found.sxg?prefetch'; + const cert_url = + test_origin + '/signed-exchange/resources/not_found_certfile.cbor'; + addPrefetch(sxg_url); + assert_true(await reportExists( + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + // The origin of this SXG's certURL is different from the reporting + // origin. So the report must be downgraded. + type: "sxg.failed", + elapsed_time: 0, + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ), 'SXG error reporting must be downgraded when the cert URL is different ' + + 'from the reporting origin'); + assert_false(await reportExists( + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + } + ), 'Succeeded normal NEL report should not be sent when success fraction ' + + 'is zero.'); +}, 'SXG error report must be downgraded when the cert URL is different from ' + + 'the reporting origin. And succeeded normal NEL report should not be sent ' + + ' when success fraction is zero.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-invalid_integrity_header.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-invalid_integrity_header.tentative.html new file mode 100644 index 0000000..1fd431c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-invalid_integrity_header.tentative.html
@@ -0,0 +1,58 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.invalid_integrity_header for prefetch</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; +const test_origin = get_host_info().HTTPS_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-invalid-integrity-header.sxg?prefetch'; + const cert_url = test_origin + '/signed-exchange/resources/127.0.0.1.sxg.pem.cbor'; + addPrefetch(sxg_url); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + type: "sxg.invalid_integrity_header", + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.invalid_integrity_header for prefetch.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-mi_error.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-mi_error.tentative.html new file mode 100644 index 0000000..2bbf0e8f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-mi_error.tentative.html
@@ -0,0 +1,58 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.mi_error for prefetch</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; +const test_origin = get_host_info().HTTPS_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-merkle-integrity-error.sxg?prefetch'; + const cert_url = test_origin + '/signed-exchange/resources/127.0.0.1.sxg.pem.cbor'; + addPrefetch(sxg_url); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + type: "sxg.mi_error", + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + } + ])); +}, 'SXG reporting test of sxg.mi_error for prefetch.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-parse_error.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-parse_error.tentative.html new file mode 100644 index 0000000..171baf1 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-parse_error.tentative.html
@@ -0,0 +1,54 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.parse_error for prefetch</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-invalid-format.sxg?prefetch'; + addPrefetch(sxg_url); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + type: "sxg.parse_error", + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + cert_url: [] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.parse_error for prefetch.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-signature_verification_error-downgraded.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-signature_verification_error-downgraded.tentative.html new file mode 100644 index 0000000..7340b75 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-signature_verification_error-downgraded.tentative.html
@@ -0,0 +1,62 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.failed downgraded from sxg.signature_verification_error for prefetch</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; +const test_origin = get_host_info().HTTPS_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-invalid-cert-sha256.sxg?prefetch'; + const cert_url = test_origin + '/signed-exchange/resources/127.0.0.1.sxg.pem.cbor'; + addPrefetch(sxg_url); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + // The origin of this SXG's certURL is different from the reporting + // origin. So the report must be downgraded. + type: "sxg.failed", + elapsed_time: 0, + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.failed downgraded from ' + + 'sxg.signature_verification_error for prefetch.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-signature_verification_error.tentative.html b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-signature_verification_error.tentative.html new file mode 100644 index 0000000..d552c4a8 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/reporting/sxg-reporting-prefetch-signature_verification_error.tentative.html
@@ -0,0 +1,57 @@ +<!DOCTYPE html> +<title>SXG reporting test of sxg.signature_verification_error for prefetch</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="/network-error-logging/support/nel.sub.js"></script> +<script src="../resources/sxg-util.js"></script> +<body> +<script> +const alt_origin = get_host_info().HTTPS_NOTSAMESITE_ORIGIN; + +nel_test(async t => { + await fetchResourceWithBasicPolicy(); + const sxg_url = + alt_origin + + '/signed-exchange/resources/sxg/sxg-invalid-cert-sha256-cert-on-alt-origin.sxg?prefetch'; + const cert_url = alt_origin + '/signed-exchange/resources/127.0.0.1.sxg.pem.cbor'; + addPrefetch(sxg_url); + assert_true(await reportsExist([ + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "sxg", + type: "sxg.signature_verification_error", + status_code: 200, + referrer: location.href, + sxg: { + outer_url: sxg_url, + inner_url: + innerURLOrigin() + '/signed-exchange/resources/inner-url.html', + cert_url: [cert_url] + } + }, + metadata: { + content_type: "application/reports+json", + }, + }, + { + url: sxg_url, + user_agent: navigator.userAgent, + type: "network-error", + body: { + phase: "application", + type: "ok", + status_code: 200, + referrer: location.href, + }, + metadata: { + content_type: "application/reports+json", + }, + }, + ])); +}, 'SXG reporting test of sxg.signature_verification_error for prefetch.'); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/generate-test-sxgs.sh b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/generate-test-sxgs.sh index bb95df8..bae4ce0ea 100755 --- a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/generate-test-sxgs.sh +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/generate-test-sxgs.sh
@@ -7,6 +7,7 @@ # the fly. wpt_test_origin=https://web-platform.test:8444 wpt_test_remote_origin=https://www1.web-platform.test:8444 +wpt_test_alt_origin=https://not-web-platform.test:8444 cert_url_origin=$wpt_test_origin sxg_content_type='content-type: application/signed-exchange;v=b3' @@ -40,6 +41,22 @@ -o sxg/sxg-location.sxg \ -miRecordSize 100 +# A valid Signed Exchange. The origin of certUrl is the "alt" origin where NEL +# policy is installed in reporting tests. +gen-signedexchange \ + -version $sxg_version \ + -uri $inner_url_origin/signed-exchange/resources/inner-url.html \ + -status 200 \ + -content sxg-location.html \ + -certificate $certfile \ + -certUrl $wpt_test_alt_origin/signed-exchange/resources/$certfile.cbor \ + -validityUrl $inner_url_origin/signed-exchange/resources/resource.validity.msg \ + -privateKey $keyfile \ + -date 2018-04-01T00:00:00Z \ + -expire 168h \ + -o sxg/sxg-location-cert-on-alt-origin.sxg \ + -miRecordSize 100 + # A signed exchange of unsupported version. gen-signedexchange \ -version 1b2 \ @@ -154,6 +171,38 @@ -miRecordSize 100 \ -ignoreErrors true +# certUrl is 404 and the origin of certUrl is different from the "alt" origin +# where NEL policy is installed in reporting tests. +gen-signedexchange \ + -version $sxg_version \ + -uri $inner_url_origin/signed-exchange/resources/inner-url.html \ + -status 200 \ + -content sxg-location.html \ + -certificate $certfile \ + -certUrl $cert_url_origin/signed-exchange/resources/not_found_certfile.cbor \ + -validityUrl $inner_url_origin/signed-exchange/resources/resource.validity.msg \ + -privateKey $keyfile \ + -date 2018-04-01T00:00:00Z \ + -expire 168h \ + -o sxg/sxg-cert-not-found.sxg \ + -miRecordSize 100 + +# certUrl is 404 and the origin of certUrl is the "alt" origin where NEL policy +# is installed in reporting tests. +gen-signedexchange \ + -version $sxg_version \ + -uri $inner_url_origin/signed-exchange/resources/inner-url.html \ + -status 200 \ + -content sxg-location.html \ + -certificate $certfile \ + -certUrl $wpt_test_alt_origin/signed-exchange/resources/not_found_certfile.cbor \ + -validityUrl $inner_url_origin/signed-exchange/resources/resource.validity.msg \ + -privateKey $keyfile \ + -date 2018-04-01T00:00:00Z \ + -expire 168h \ + -o sxg/sxg-cert-not-found-on-alt-origin.sxg \ + -miRecordSize 100 + # certUrl is 404 and fallback URL is another signed exchange. gen-signedexchange \ -version $sxg_version \ @@ -170,6 +219,38 @@ -miRecordSize 100 \ -ignoreErrors true +# certUrl is an invalid cert and the origin of certUrl is different from the +# "alt" origin where NEL policy is installed in reporting tests. +gen-signedexchange \ + -version $sxg_version \ + -uri $inner_url_origin/signed-exchange/resources/inner-url.html \ + -status 200 \ + -content sxg-location.html \ + -certificate $certfile \ + -certUrl $cert_url_origin/signed-exchange/resources/invalid-cert-format.cbor \ + -validityUrl $inner_url_origin/signed-exchange/resources/resource.validity.msg \ + -privateKey $keyfile \ + -date 2018-04-01T00:00:00Z \ + -expire 168h \ + -o sxg/sxg-invalid-cert-format.sxg \ + -miRecordSize 100 + +# certUrl is an invalid cert and the origin of certUrl is the "alt" origin where +# NEL policy is installed in reporting tests. +gen-signedexchange \ + -version $sxg_version \ + -uri $inner_url_origin/signed-exchange/resources/inner-url.html \ + -status 200 \ + -content sxg-location.html \ + -certificate $certfile \ + -certUrl $wpt_test_alt_origin/signed-exchange/resources/invalid-cert-format.cbor \ + -validityUrl $inner_url_origin/signed-exchange/resources/resource.validity.msg \ + -privateKey $keyfile \ + -date 2018-04-01T00:00:00Z \ + -expire 168h \ + -o sxg/sxg-invalid-cert-format-on-alt-origin.sxg \ + -miRecordSize 100 + # Nested signed exchange. gen-signedexchange \ -version $sxg_version \ @@ -272,7 +353,56 @@ -miRecordSize 100 \ -ignoreErrors true + + # Signed Exchange with payload integrity error. echo 'garbage' | cat sxg/sxg-location.sxg - >sxg/sxg-merkle-integrity-error.sxg +# An invalid signed exchange which integrity header is invalid. +cat sxg/sxg-location.sxg | + sed 's/digest\/mi-sha256-03/digest\/mi-sha256-xx/' \ + > sxg/sxg-invalid-integrity-header.sxg + +# An invalid signed exchange which cert-sha256 is invalid. +dummy_sha256=`echo "dummy" | openssl dgst -binary -sha256 | base64` +cat sxg/sxg-location.sxg | + sed "s/cert-sha256=\*[^*]*\*;/cert-sha256=*$dummy_sha256*;/" \ + > sxg/sxg-invalid-cert-sha256.sxg +cat sxg/sxg-location-cert-on-alt-origin.sxg | + sed "s/cert-sha256=\*[^*]*\*;/cert-sha256=*$dummy_sha256*;/" \ + > sxg/sxg-invalid-cert-sha256-cert-on-alt-origin.sxg + +# An invalid signed exchange which validity period is too long. +gen-signedexchange \ + -version $sxg_version \ + -uri $inner_url_origin/signed-exchange/resources/inner-url.html \ + -status 200 \ + -content sxg-location.html \ + -certificate $certfile \ + -certUrl $cert_url_origin/signed-exchange/resources/$certfile.cbor \ + -validityUrl $inner_url_origin/signed-exchange/resources/resource.validity.msg \ + -privateKey $keyfile \ + -date 2018-04-01T00:00:00Z \ + -expire 300h \ + -o sxg/sxg-validity-period-too-long.sxg \ + -miRecordSize 100 \ + -ignoreErrors true + +# An invalid signed exchange which validity period is too long. The origin of +# certUrl is the "alt" origin where NEL policy is installed in reporting tests. +gen-signedexchange \ + -version $sxg_version \ + -uri $inner_url_origin/signed-exchange/resources/inner-url.html \ + -status 200 \ + -content sxg-location.html \ + -certificate $certfile \ + -certUrl $wpt_test_alt_origin/signed-exchange/resources/$certfile.cbor \ + -validityUrl $inner_url_origin/signed-exchange/resources/resource.validity.msg \ + -privateKey $keyfile \ + -date 2018-04-01T00:00:00Z \ + -expire 300h \ + -o sxg/sxg-validity-period-too-long-cert-on-alt-origin.sxg \ + -miRecordSize 100 \ + -ignoreErrors true + rm -fr $tmpdir
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/invalid-cert-format.cbor b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/invalid-cert-format.cbor new file mode 100644 index 0000000..82f15ff9 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/invalid-cert-format.cbor
@@ -0,0 +1 @@ +This is an invalid certificate file.
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/invalid-cert-format.cbor.headers b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/invalid-cert-format.cbor.headers new file mode 100644 index 0000000..d581d598 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/invalid-cert-format.cbor.headers
@@ -0,0 +1 @@ +Content-Type: application/cert-chain+cbor
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-cert-not-found-on-alt-origin.sxg b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-cert-not-found-on-alt-origin.sxg new file mode 100644 index 0000000..2a7dbf6 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-cert-not-found-on-alt-origin.sxg Binary files differ
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-cert-not-found.sxg b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-cert-not-found.sxg new file mode 100644 index 0000000..07212540 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-cert-not-found.sxg Binary files differ
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-cert-format-on-alt-origin.sxg b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-cert-format-on-alt-origin.sxg new file mode 100644 index 0000000..62acedd --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-cert-format-on-alt-origin.sxg Binary files differ
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-cert-format.sxg b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-cert-format.sxg new file mode 100644 index 0000000..30e4fcd9 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-cert-format.sxg Binary files differ
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-cert-sha256-cert-on-alt-origin.sxg b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-cert-sha256-cert-on-alt-origin.sxg new file mode 100644 index 0000000..066a3cc --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-cert-sha256-cert-on-alt-origin.sxg Binary files differ
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-cert-sha256.sxg b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-cert-sha256.sxg new file mode 100644 index 0000000..46d2bb1 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-cert-sha256.sxg Binary files differ
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-format.sxg b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-format.sxg new file mode 100644 index 0000000..3fbb151 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-format.sxg
@@ -0,0 +1 @@ +This is an invalid Signed Exchange.
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-integrity-header.sxg b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-integrity-header.sxg new file mode 100644 index 0000000..95d35824 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-invalid-integrity-header.sxg Binary files differ
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-location-cert-on-alt-origin.sxg b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-location-cert-on-alt-origin.sxg new file mode 100644 index 0000000..a2ddc77 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-location-cert-on-alt-origin.sxg Binary files differ
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-validity-period-too-long-cert-on-alt-origin.sxg b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-validity-period-too-long-cert-on-alt-origin.sxg new file mode 100644 index 0000000..294f97b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-validity-period-too-long-cert-on-alt-origin.sxg Binary files differ
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-validity-period-too-long.sxg b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-validity-period-too-long.sxg new file mode 100644 index 0000000..e90d9bc6 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/sxg/sxg-validity-period-too-long.sxg Binary files differ
diff --git a/third_party/blink/web_tests/external/wpt/web-animations/README.md b/third_party/blink/web_tests/external/wpt/web-animations/README.md index f6efbf9..75493ce5 100644 --- a/third_party/blink/web_tests/external/wpt/web-animations/README.md +++ b/third_party/blink/web_tests/external/wpt/web-animations/README.md
@@ -19,7 +19,7 @@ Instead, try something like: - > * `/web-animations/timing-model/animations/set-the-animation-start-time.html`<br> + > * `/web-animations/timing-model/animations/setting-the-start-time-of-an-animation.html`<br> > Tests all the branches and inputs to the procedure as defined in the > spec (using the `Animation.startTime` API). > * `/web-animations/interfaces/Animation/startTime.html`<br>
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/idlharness.https.window-expected.txt b/third_party/blink/web_tests/external/wpt/web-nfc/idlharness.https.window-expected.txt index 87dabc03..436eaad 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/idlharness.https.window-expected.txt +++ b/third_party/blink/web_tests/external/wpt/web-nfc/idlharness.https.window-expected.txt
@@ -6,7 +6,7 @@ FAIL NFCWriter interface: existence and properties of interface prototype object assert_own_property: self does not have own property "NFCWriter" expected property "NFCWriter" missing FAIL NFCWriter interface: existence and properties of interface prototype object's "constructor" property assert_own_property: self does not have own property "NFCWriter" expected property "NFCWriter" missing FAIL NFCWriter interface: existence and properties of interface prototype object's @@unscopables property assert_own_property: self does not have own property "NFCWriter" expected property "NFCWriter" missing -FAIL NFCWriter interface: operation push(NFCMessageSource, NFCPushOptions) assert_own_property: self does not have own property "NFCWriter" expected property "NFCWriter" missing +FAIL NFCWriter interface: operation push(NDEFMessageSource, NFCPushOptions) assert_own_property: self does not have own property "NFCWriter" expected property "NFCWriter" missing FAIL NFCReader interface: existence and properties of interface object assert_own_property: self does not have own property "NFCReader" expected property "NFCReader" missing FAIL NFCReader interface object length assert_own_property: self does not have own property "NFCReader" expected property "NFCReader" missing FAIL NFCReader interface object name assert_own_property: self does not have own property "NFCReader" expected property "NFCReader" missing
diff --git a/third_party/blink/web_tests/external/wpt_automation/pointerevents/pointerevent_common_input.js b/third_party/blink/web_tests/external/wpt_automation/pointerevents/pointerevent_common_input.js index 545c881..f2e2d3ed 100644 --- a/third_party/blink/web_tests/external/wpt_automation/pointerevents/pointerevent_common_input.js +++ b/third_party/blink/web_tests/external/wpt_automation/pointerevents/pointerevent_common_input.js
@@ -311,7 +311,7 @@ { name: 'pointerDown', x: xPosition1, y: yPosition1 }, { name: 'pointerMove', x: xPosition2, y: yPosition2 }, { name: 'pointerMove', x: xPosition3, y: yPosition3 }, - { name: 'pause', duration: 0.1 }, + { name: 'pause', duration: 100 }, { name: 'pointerUp' } ]}, {source: pointerType, @@ -319,7 +319,7 @@ { name: 'pointerDown', x: xPosition1 + boundaryOffset, y: yPosition1 }, { name: 'pointerMove', x: xPosition2 + boundaryOffset, y: yPosition2 }, { name: 'pointerMove', x: xPosition3 + boundaryOffset, y: yPosition3 }, - { name: 'pause', duration: 0.1 }, + { name: 'pause', duration: 100 }, { name: 'pointerUp' } ]}], resolve); } else { @@ -365,7 +365,7 @@ { name: 'pointerDown', x: xPosition1, y: yPosition1 }, { name: 'pointerMove', x: xPosition2, y: yPosition2 }, { name: 'pointerMove', x: xPosition3, y: yPosition3 }, - { name: 'pause', duration: 0.1 }, + { name: 'pause', duration: 100 }, { name: 'pointerUp' } ]}], resolve); });
diff --git a/third_party/blink/web_tests/fast/events/no-fake-mousemove.html b/third_party/blink/web_tests/fast/events/no-fake-mousemove.html index 64bf1eb..eaa498b1 100644 --- a/third_party/blink/web_tests/fast/events/no-fake-mousemove.html +++ b/third_party/blink/web_tests/fast/events/no-fake-mousemove.html
@@ -48,7 +48,7 @@ [{source: "mouse", actions: [ { name: "pointerMove", x: x, y: y }, - { name: 'pause', duration: 1 }]}]; + { name: 'pause', duration: 1000 }]}]; chrome.gpuBenchmarking.pointerActionSequence(pointerActions, callbackValidMouseMove); } }
diff --git a/third_party/blink/web_tests/fast/events/resources/middleClickAutoscroll.js b/third_party/blink/web_tests/fast/events/resources/middleClickAutoscroll.js index eca0e88..113200a 100644 --- a/third_party/blink/web_tests/fast/events/resources/middleClickAutoscroll.js +++ b/third_party/blink/web_tests/fast/events/resources/middleClickAutoscroll.js
@@ -1,5 +1,5 @@ var middleClickAutoscrollRadius = 15; // from FrameView::noPanScrollRadius -var waitTimeBeforeMoveInSeconds = 0.1; +var waitTimeBeforeMoveInMilliseconds = 100; var scrollable; var scrolledObject; var startX; @@ -43,7 +43,7 @@ } else { assert_equals('drag', autoscrollParam.clickOrDrag); mouseDragAndDrop(startX, startY, endX, endY, middleButton, - waitTimeBeforeMoveInSeconds); + waitTimeBeforeMoveInMilliseconds); } // Wait for some scrolling, then end the autoscroll.
diff --git a/third_party/blink/web_tests/fast/frames/location-redirect-user-gesture-expected.txt b/third_party/blink/web_tests/fast/frames/location-redirect-user-gesture-expected.txt index 3c2a4d16..34fe5331 100644 --- a/third_party/blink/web_tests/fast/frames/location-redirect-user-gesture-expected.txt +++ b/third_party/blink/web_tests/fast/frames/location-redirect-user-gesture-expected.txt
@@ -1,3 +1,2 @@ -Frame with user gesture "false" - in didStartProvisionalLoadForFrame -Frame with user gesture "false" - in didStartProvisionalLoadForFrame +Frame with user gesture "false" - in DidStartNavigation SUCCESS
diff --git a/third_party/blink/web_tests/fast/frames/meta-refresh-user-gesture-expected.txt b/third_party/blink/web_tests/fast/frames/meta-refresh-user-gesture-expected.txt index 52cfe9a4..547279b 100644 --- a/third_party/blink/web_tests/fast/frames/meta-refresh-user-gesture-expected.txt +++ b/third_party/blink/web_tests/fast/frames/meta-refresh-user-gesture-expected.txt
@@ -1,3 +1,2 @@ -Frame with user gesture "false" - in didStartProvisionalLoadForFrame -Frame with user gesture "false" - in didStartProvisionalLoadForFrame +Frame with user gesture "false" - in DidStartNavigation
diff --git a/third_party/blink/web_tests/fast/loader/subframe-removes-itself-expected.txt b/third_party/blink/web_tests/fast/loader/subframe-removes-itself-expected.txt index 6baef90..8fb7b90 100644 --- a/third_party/blink/web_tests/fast/loader/subframe-removes-itself-expected.txt +++ b/third_party/blink/web_tests/fast/loader/subframe-removes-itself-expected.txt
@@ -1,8 +1,8 @@ frame "<!--framePath //<!--frame0-->-->" - didReceiveTitle: -frame "<!--framePath //<!--frame0-->-->" - didStartProvisionalLoadForFrame +frame "<!--framePath //<!--frame0-->-->" - DidStartNavigation main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame -frame "<!--framePath //<!--frame0-->-->" - didStartProvisionalLoadForFrame +frame "<!--framePath //<!--frame0-->-->" - ReadyToCommitNavigation frame "<!--framePath //<!--frame0-->-->" - didCommitLoadForFrame frame "<!--framePath //<!--frame0-->-->" - didFailLoadWithError main frame - didHandleOnloadEventsForFrame
diff --git a/third_party/blink/web_tests/fast/scroll-snap/snaps-after-scrollbar-scrolling.html b/third_party/blink/web_tests/fast/scroll-snap/snaps-after-scrollbar-scrolling.html index 9bc46e47d..d0727f2 100644 --- a/third_party/blink/web_tests/fast/scroll-snap/snaps-after-scrollbar-scrolling.html +++ b/third_party/blink/web_tests/fast/scroll-snap/snaps-after-scrollbar-scrolling.html
@@ -43,7 +43,7 @@ promise_test (async () => { scroller.scrollTo(0, 0); - await mousePressOn(398, 350, 1); + await mousePressOn(398, 350, 1000); await waitForAnimationEnd(scrollTop, 500, 5); await waitFor( () => { return scroller.scrollTop == 400; @@ -52,7 +52,7 @@ promise_test (async () => { scroller.scrollTo(0, 0); - await mousePressOn(350, 398, 1); + await mousePressOn(350, 398, 1000); await waitForAnimationEnd(scrollLeft, 500, 5); await waitFor( () => { return scroller.scrollLeft == 400;
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/http/tests/loading/nested_bad_objects-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/http/tests/loading/nested_bad_objects-expected.txt deleted file mode 100644 index 8c50b52..0000000 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/http/tests/loading/nested_bad_objects-expected.txt +++ /dev/null
@@ -1,7 +0,0 @@ -main frame - didStartProvisionalLoadForFrame -main frame - didCommitLoadForFrame -main frame - didReceiveTitle: -main frame - didFinishDocumentLoadForFrame -main frame - didHandleOnloadEventsForFrame -main frame - didFinishLoadForFrame - PASS - nested image objects with bad mimetype do not cause a crash.
diff --git a/third_party/blink/web_tests/http/tests/devtools/console/console-format-broken-unicode.js b/third_party/blink/web_tests/http/tests/devtools/console/console-format-broken-unicode.js index d0b3019..bb71f17f 100644 --- a/third_party/blink/web_tests/http/tests/devtools/console/console-format-broken-unicode.js +++ b/third_party/blink/web_tests/http/tests/devtools/console/console-format-broken-unicode.js
@@ -40,6 +40,11 @@ function step5(result) { var text = result; TestRunner.assertEquals(15, text.length, 'text length'); + // It's important that this last character in |text| is an unbalanced UTF16 + // low surrogate (|text| is invalid UTF16, allowed by Javascript), as + // opposed to some replacement character that came from transcoding to UTF8 + // and back to valid UTF16. + TestRunner.assertEquals('\uD835', text[text.length - 1]); TestRunner.assertEquals(8, countTextNodes(text), 'nodes count'); TestRunner.assertEquals(1, countTextNodes('"' + text + '"'), 'nodes with quoted text count'); TestRunner.addResult('PASS: Found all nodes with the broken text');
diff --git a/third_party/blink/web_tests/http/tests/loading/307-after-303-after-post-expected.txt b/third_party/blink/web_tests/http/tests/loading/307-after-303-after-post-expected.txt index 93155c1..c67c95f 100644 --- a/third_party/blink/web_tests/http/tests/loading/307-after-303-after-post-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/307-after-303-after-post-expected.txt
@@ -1,12 +1,13 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame +main frame - DidStartNavigation http://127.0.0.1:8000/loading/resources/post-to-303-target.php - willSendRequest <NSURLRequest URL http://127.0.0.1:8000/loading/resources/post-to-303-target.php, main document URL http://127.0.0.1:8000/loading/resources/post-to-303-target.php, http method POST> -main frame - didStartProvisionalLoadForFrame -main frame - didStartProvisionalLoadForFrame +main frame - ReadyToCommitNavigation http://127.0.0.1:8000/loading/resources/307-post-output-target.php - didReceiveResponse <NSURLResponse http://127.0.0.1:8000/loading/resources/307-post-output-target.php, http status code 200> main frame - didCommitLoadForFrame main frame - didReceiveTitle:
diff --git a/third_party/blink/web_tests/http/tests/loading/bad-scheme-subframe-expected.txt b/third_party/blink/web_tests/http/tests/loading/bad-scheme-subframe-expected.txt index cf6b2f90..c763b17 100644 --- a/third_party/blink/web_tests/http/tests/loading/bad-scheme-subframe-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/bad-scheme-subframe-expected.txt
@@ -1,9 +1,10 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame frame "f1" - didReceiveTitle: -frame "f1" - didStartProvisionalLoadForFrame +frame "f1" - DidStartNavigation main frame - didHandleOnloadEventsForFrame frame "f1" - didFailProvisionalLoadWithError main frame - didFinishLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/bad-server-subframe-expected.txt b/third_party/blink/web_tests/http/tests/loading/bad-server-subframe-expected.txt index ac8966b2..4aad07b 100644 --- a/third_party/blink/web_tests/http/tests/loading/bad-server-subframe-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/bad-server-subframe-expected.txt
@@ -1,11 +1,13 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame frame "f1" - didReceiveTitle: -frame "f1" - didStartProvisionalLoadForFrame +frame "f1" - DidStartNavigation main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame frame "f1" - didFailProvisionalLoadWithError -frame "f1" - didStartProvisionalLoadForFrame +frame "f1" - DidStartNavigation +frame "f1" - ReadyToCommitNavigation frame "f1" - didCommitLoadForFrame frame "f1" - didReceiveTitle: Error frame "f1" - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/basic-expected.txt b/third_party/blink/web_tests/http/tests/loading/basic-expected.txt index 868aa22d..6801f5b4 100644 --- a/third_party/blink/web_tests/http/tests/loading/basic-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/basic-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/dont-preload-non-img-srcset-expected.txt b/third_party/blink/web_tests/http/tests/loading/dont-preload-non-img-srcset-expected.txt index 0ed7d56..8d230d60 100644 --- a/third_party/blink/web_tests/http/tests/loading/dont-preload-non-img-srcset-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/dont-preload-non-img-srcset-expected.txt
@@ -1,7 +1,9 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame frame "<!--framePath //<!--frame0-->-->" - didReceiveTitle: -frame "<!--framePath //<!--frame0-->-->" - didStartProvisionalLoadForFrame +frame "<!--framePath //<!--frame0-->-->" - DidStartNavigation +frame "<!--framePath //<!--frame0-->-->" - ReadyToCommitNavigation frame "<!--framePath //<!--frame0-->-->" - didCommitLoadForFrame frame "<!--framePath //<!--frame0-->-->" - didReceiveTitle: frame "<!--framePath //<!--frame0-->-->" - didFinishDocumentLoadForFrame @@ -11,11 +13,12 @@ main frame - didFinishDocumentLoadForFrame main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame -main frame - didStartProvisionalLoadForFrame -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame frame "<!--framePath //<!--frame0-->-->" - didReceiveTitle: -frame "<!--framePath //<!--frame0-->-->" - didStartProvisionalLoadForFrame +frame "<!--framePath //<!--frame0-->-->" - DidStartNavigation +frame "<!--framePath //<!--frame0-->-->" - ReadyToCommitNavigation frame "<!--framePath //<!--frame0-->-->" - didCommitLoadForFrame frame "<!--framePath //<!--frame0-->-->" - didReceiveTitle: frame "<!--framePath //<!--frame0-->-->" - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/empty-subframe-expected.txt b/third_party/blink/web_tests/http/tests/loading/empty-subframe-expected.txt index c91610e..ab5d22f4 100644 --- a/third_party/blink/web_tests/http/tests/loading/empty-subframe-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/empty-subframe-expected.txt
@@ -1,7 +1,9 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame frame "f1" - didReceiveTitle: -frame "f1" - didStartProvisionalLoadForFrame +frame "f1" - DidStartNavigation +frame "f1" - ReadyToCommitNavigation frame "f1" - didCommitLoadForFrame frame "f1" - didReceiveTitle: frame "f1" - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/fire-error-event-empty-404-script-expected.txt b/third_party/blink/web_tests/http/tests/loading/fire-error-event-empty-404-script-expected.txt index 1e069ec..76cda0b 100644 --- a/third_party/blink/web_tests/http/tests/loading/fire-error-event-empty-404-script-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/fire-error-event-empty-404-script-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/fire-error-event-script-no-content-type-expected.txt b/third_party/blink/web_tests/http/tests/loading/fire-error-event-script-no-content-type-expected.txt index d7b552c4..ef885557 100644 --- a/third_party/blink/web_tests/http/tests/loading/fire-error-event-script-no-content-type-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/fire-error-event-script-no-content-type-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/link-preload-image-sizes-2x-expected.txt b/third_party/blink/web_tests/http/tests/loading/link-preload-image-sizes-2x-expected.txt index f693d37..1afa143 100644 --- a/third_party/blink/web_tests/http/tests/loading/link-preload-image-sizes-2x-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/link-preload-image-sizes-2x-expected.txt
@@ -1,11 +1,12 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame -main frame - didStartProvisionalLoadForFrame -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/link-preload-image-sizes-expected.txt b/third_party/blink/web_tests/http/tests/loading/link-preload-image-sizes-expected.txt index edb53d1..44e9d01 100644 --- a/third_party/blink/web_tests/http/tests/loading/link-preload-image-sizes-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/link-preload-image-sizes-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/link-preload-image-srcset-2x-expected.txt b/third_party/blink/web_tests/http/tests/loading/link-preload-image-srcset-2x-expected.txt index 42c3fc9..accd792 100644 --- a/third_party/blink/web_tests/http/tests/loading/link-preload-image-srcset-2x-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/link-preload-image-srcset-2x-expected.txt
@@ -1,11 +1,12 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame -main frame - didStartProvisionalLoadForFrame -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/link-preload-image-srcset-expected.txt b/third_party/blink/web_tests/http/tests/loading/link-preload-image-srcset-expected.txt index e40ff034..734caa0 100644 --- a/third_party/blink/web_tests/http/tests/loading/link-preload-image-srcset-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/link-preload-image-srcset-expected.txt
@@ -1,11 +1,12 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame -main frame - didStartProvisionalLoadForFrame -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/load-javascript-after-many-xhrs-expected.txt b/third_party/blink/web_tests/http/tests/loading/load-javascript-after-many-xhrs-expected.txt index 637c4a1..5edc18d 100644 --- a/third_party/blink/web_tests/http/tests/loading/load-javascript-after-many-xhrs-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/load-javascript-after-many-xhrs-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/location-hash-reload-cycle-expected.txt b/third_party/blink/web_tests/http/tests/loading/location-hash-reload-cycle-expected.txt index 032a21dd..0fd9419b 100644 --- a/third_party/blink/web_tests/http/tests/loading/location-hash-reload-cycle-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/location-hash-reload-cycle-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/module-script-wrong-mime-expected.txt b/third_party/blink/web_tests/http/tests/loading/module-script-wrong-mime-expected.txt index 665ff33..d6d313e 100644 --- a/third_party/blink/web_tests/http/tests/loading/module-script-wrong-mime-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/module-script-wrong-mime-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame CONSOLE ERROR: Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec. main frame - didReceiveTitle:
diff --git a/third_party/blink/web_tests/http/tests/loading/nested_bad_objects-expected.txt b/third_party/blink/web_tests/http/tests/loading/nested_bad_objects-expected.txt index 8c50b52..6cbb434 100644 --- a/third_party/blink/web_tests/http/tests/loading/nested_bad_objects-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/nested_bad_objects-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/onbeforeunload-detach-expected.txt b/third_party/blink/web_tests/http/tests/loading/onbeforeunload-detach-expected.txt index 9b771ff..6b8125b 100644 --- a/third_party/blink/web_tests/http/tests/loading/onbeforeunload-detach-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/onbeforeunload-detach-expected.txt
@@ -1,10 +1,11 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame frame "iframe" - didReceiveTitle: -frame "iframe" - didStartProvisionalLoadForFrame +frame "iframe" - DidStartNavigation main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame -frame "iframe" - didStartProvisionalLoadForFrame +frame "iframe" - ReadyToCommitNavigation frame "iframe" - didCommitLoadForFrame CONSOLE MESSAGE: line 12: iframe: clicking CONSOLE MESSAGE: line 5: iframe: onbeforeunload
diff --git a/third_party/blink/web_tests/http/tests/loading/onload-vs-immediate-refresh-expected.txt b/third_party/blink/web_tests/http/tests/loading/onload-vs-immediate-refresh-expected.txt index 1893c44a..7b4f834 100644 --- a/third_party/blink/web_tests/http/tests/loading/onload-vs-immediate-refresh-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/onload-vs-immediate-refresh-expected.txt
@@ -1,12 +1,13 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame ALERT: SUCCESS main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame -main frame - didStartProvisionalLoadForFrame -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/onreadystatechange-detach-expected.txt b/third_party/blink/web_tests/http/tests/loading/onreadystatechange-detach-expected.txt index a9c30a5..f6862843 100644 --- a/third_party/blink/web_tests/http/tests/loading/onreadystatechange-detach-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/onreadystatechange-detach-expected.txt
@@ -1,12 +1,14 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame frame "iframe" - didReceiveTitle: -frame "iframe" - didStartProvisionalLoadForFrame +frame "iframe" - DidStartNavigation main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame -frame "iframe" - didStartProvisionalLoadForFrame +frame "iframe" - ReadyToCommitNavigation frame "iframe" - didCommitLoadForFrame CONSOLE MESSAGE: line 12: iframe: clicking +frame "iframe" - DidStartNavigation CONSOLE MESSAGE: line 5: iframe: onreadystatechange frame "iframe" - didFailLoadWithError main frame - didHandleOnloadEventsForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/pdf-commit-load-callbacks-expected.txt b/third_party/blink/web_tests/http/tests/loading/pdf-commit-load-callbacks-expected.txt index 743c297..62dde80 100644 --- a/third_party/blink/web_tests/http/tests/loading/pdf-commit-load-callbacks-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/pdf-commit-load-callbacks-expected.txt
@@ -1,7 +1,8 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame frame "<!--framePath //<!--frame0-->-->" - didReceiveTitle: -frame "<!--framePath //<!--frame0-->-->" - didStartProvisionalLoadForFrame +frame "<!--framePath //<!--frame0-->-->" - DidStartNavigation main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame frame "<!--framePath //<!--frame0-->-->" - didFailProvisionalLoadWithError
diff --git a/third_party/blink/web_tests/http/tests/loading/pending-script-leak-expected.txt b/third_party/blink/web_tests/http/tests/loading/pending-script-leak-expected.txt index b6bba1e..1a368692c 100644 --- a/third_party/blink/web_tests/http/tests/loading/pending-script-leak-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/pending-script-leak-expected.txt
@@ -1,7 +1,9 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame frame "<!--framePath //<!--frame0-->-->" - didReceiveTitle: -frame "<!--framePath //<!--frame0-->-->" - didStartProvisionalLoadForFrame +frame "<!--framePath //<!--frame0-->-->" - DidStartNavigation +frame "<!--framePath //<!--frame0-->-->" - ReadyToCommitNavigation frame "<!--framePath //<!--frame0-->-->" - didCommitLoadForFrame frame "<!--framePath //<!--frame0-->-->" - didReceiveTitle: frame "<!--framePath //<!--frame0-->-->" - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-append-scan-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-append-scan-expected.txt index fdda6d3e..8eb7717 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-append-scan-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-append-scan-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-css-test-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-css-test-expected.txt index f201d25..9a3c875 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-css-test-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-css-test-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-ignore-invalid-base-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-ignore-invalid-base-expected.txt index 42fd5ea2..7f26759 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-ignore-invalid-base-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-ignore-invalid-base-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-image-sizes-2x-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-image-sizes-2x-expected.txt index c6cdbad7..a7448ee 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-image-sizes-2x-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-image-sizes-2x-expected.txt
@@ -1,11 +1,12 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame -main frame - didStartProvisionalLoadForFrame -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-image-sizes-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-image-sizes-expected.txt index d1b1e06..31306b7b 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-image-sizes-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-image-sizes-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-image-src-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-image-src-expected.txt index 2b166a4..6e99454 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-image-src-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-image-src-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-2x-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-2x-expected.txt index 9c5d6aac..1a02c9e7 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-2x-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-2x-expected.txt
@@ -1,11 +1,12 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame -main frame - didStartProvisionalLoadForFrame -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-duplicate-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-duplicate-expected.txt index c464360..7f70ae1 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-duplicate-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-duplicate-expected.txt
@@ -1,11 +1,12 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame -main frame - didStartProvisionalLoadForFrame -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-expected.txt index c4e8cfb..35a9a83 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-expected.txt
@@ -1,11 +1,12 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame -main frame - didStartProvisionalLoadForFrame -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-reverse-order-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-reverse-order-expected.txt index e421b7405..2a008fe 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-reverse-order-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-reverse-order-expected.txt
@@ -1,11 +1,12 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame -main frame - didStartProvisionalLoadForFrame -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-src-preloaded-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-src-preloaded-expected.txt index 5e165ad..df9ed07a 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-src-preloaded-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-src-preloaded-expected.txt
@@ -1,11 +1,12 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame -main frame - didStartProvisionalLoadForFrame -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-src-preloaded-reverse-order-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-src-preloaded-reverse-order-expected.txt index 22cff36..7ac6716 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-src-preloaded-reverse-order-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-image-srcset-src-preloaded-reverse-order-expected.txt
@@ -1,11 +1,12 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame -main frame - didStartProvisionalLoadForFrame -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-picture-invalid-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-picture-invalid-expected.txt index e7a84ae..8e93797 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-picture-invalid-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-picture-invalid-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-picture-nested-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-picture-nested-expected.txt index 1af0247..770d2799 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-picture-nested-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-picture-nested-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-picture-sizes-2x-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-picture-sizes-2x-expected.txt index 0377fcf..0e0d220a 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-picture-sizes-2x-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-picture-sizes-2x-expected.txt
@@ -1,12 +1,13 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame CONSOLE WARNING: <source src> with a <picture> parent is invalid and therefore ignored. Please use <source srcset> instead. main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame -main frame - didStartProvisionalLoadForFrame -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame CONSOLE WARNING: <source src> with a <picture> parent is invalid and therefore ignored. Please use <source srcset> instead. main frame - didReceiveTitle:
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-picture-sizes-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-picture-sizes-expected.txt index 7d9fa94..d7b10483 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-picture-sizes-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-picture-sizes-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame CONSOLE WARNING: <source src> with a <picture> parent is invalid and therefore ignored. Please use <source srcset> instead. main frame - didReceiveTitle:
diff --git a/third_party/blink/web_tests/http/tests/loading/preload-video-poster-expected.txt b/third_party/blink/web_tests/http/tests/loading/preload-video-poster-expected.txt index 35e0b00c..d0898b2 100644 --- a/third_party/blink/web_tests/http/tests/loading/preload-video-poster-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/preload-video-poster-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/redirect-methods-expected.txt b/third_party/blink/web_tests/http/tests/loading/redirect-methods-expected.txt index 6b627ca..469a5cd 100644 --- a/third_party/blink/web_tests/http/tests/loading/redirect-methods-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/redirect-methods-expected.txt
@@ -1,34 +1,37 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame frame "0" - didReceiveTitle: -frame "0" - didStartProvisionalLoadForFrame +frame "0" - DidStartNavigation +frame "0" - ReadyToCommitNavigation frame "0" - didCommitLoadForFrame frame "0" - didReceiveTitle: frame "0" - didFinishDocumentLoadForFrame frame "0" - didHandleOnloadEventsForFrame frame "0" - didFinishLoadForFrame +frame "0" - DidStartNavigation http://127.0.0.1:8000/loading/resources/redirect-methods-form.html - willSendRequest <NSURLRequest URL http://127.0.0.1:8000/loading/resources/redirect-methods-form.html, main document URL http://127.0.0.1:8000/loading/redirect-methods.html, http method GET> -frame "0" - didStartProvisionalLoadForFrame -frame "0" - didStartProvisionalLoadForFrame +frame "0" - ReadyToCommitNavigation http://127.0.0.1:8000/loading/resources/redirect-methods-form.html - didReceiveResponse <NSURLResponse http://127.0.0.1:8000/loading/resources/redirect-methods-form.html, http status code 200> frame "0" - didCommitLoadForFrame frame "0" - didReceiveTitle: frame "0" - didFinishDocumentLoadForFrame frame "0" - didHandleOnloadEventsForFrame frame "0" - didFinishLoadForFrame +frame "0" - DidStartNavigation http://127.0.0.1:8000/loading/resources/redirect-methods-result.php - willSendRequest <NSURLRequest URL http://127.0.0.1:8000/loading/resources/redirect-methods-result.php, main document URL http://127.0.0.1:8000/loading/redirect-methods.html, http method POST> -frame "0" - didStartProvisionalLoadForFrame -frame "0" - didStartProvisionalLoadForFrame +frame "0" - ReadyToCommitNavigation http://127.0.0.1:8000/loading/resources/redirect-methods-result.php?redirected=true - didReceiveResponse <NSURLResponse http://127.0.0.1:8000/loading/resources/redirect-methods-result.php?redirected=true, http status code 200> frame "0" - didCommitLoadForFrame frame "0" - didReceiveTitle: frame "0" - didFinishDocumentLoadForFrame frame "1" - didReceiveTitle: -frame "1" - didStartProvisionalLoadForFrame +frame "1" - DidStartNavigation +frame "1" - ReadyToCommitNavigation frame "1" - didCommitLoadForFrame frame "1" - didReceiveTitle: frame "1" - didFinishDocumentLoadForFrame @@ -36,24 +39,25 @@ frame "1" - didFinishLoadForFrame frame "0" - didHandleOnloadEventsForFrame frame "0" - didFinishLoadForFrame +frame "1" - DidStartNavigation http://127.0.0.1:8000/loading/resources/redirect-methods-form.html - willSendRequest <NSURLRequest URL http://127.0.0.1:8000/loading/resources/redirect-methods-form.html, main document URL http://127.0.0.1:8000/loading/redirect-methods.html, http method GET> -frame "1" - didStartProvisionalLoadForFrame -frame "1" - didStartProvisionalLoadForFrame +frame "1" - ReadyToCommitNavigation http://127.0.0.1:8000/loading/resources/redirect-methods-form.html - didReceiveResponse <NSURLResponse http://127.0.0.1:8000/loading/resources/redirect-methods-form.html, http status code 200> frame "1" - didCommitLoadForFrame frame "1" - didReceiveTitle: frame "1" - didFinishDocumentLoadForFrame frame "1" - didHandleOnloadEventsForFrame frame "1" - didFinishLoadForFrame +frame "1" - DidStartNavigation http://127.0.0.1:8000/loading/resources/redirect-methods-result.php - willSendRequest <NSURLRequest URL http://127.0.0.1:8000/loading/resources/redirect-methods-result.php, main document URL http://127.0.0.1:8000/loading/redirect-methods.html, http method POST> -frame "1" - didStartProvisionalLoadForFrame -frame "1" - didStartProvisionalLoadForFrame +frame "1" - ReadyToCommitNavigation http://127.0.0.1:8000/loading/resources/redirect-methods-result.php?redirected=true - didReceiveResponse <NSURLResponse http://127.0.0.1:8000/loading/resources/redirect-methods-result.php?redirected=true, http status code 200> frame "1" - didCommitLoadForFrame frame "1" - didReceiveTitle: frame "1" - didFinishDocumentLoadForFrame frame "2" - didReceiveTitle: -frame "2" - didStartProvisionalLoadForFrame +frame "2" - DidStartNavigation +frame "2" - ReadyToCommitNavigation frame "2" - didCommitLoadForFrame frame "2" - didReceiveTitle: frame "2" - didFinishDocumentLoadForFrame @@ -61,24 +65,25 @@ frame "2" - didFinishLoadForFrame frame "1" - didHandleOnloadEventsForFrame frame "1" - didFinishLoadForFrame +frame "2" - DidStartNavigation http://127.0.0.1:8000/loading/resources/redirect-methods-form.html - willSendRequest <NSURLRequest URL http://127.0.0.1:8000/loading/resources/redirect-methods-form.html, main document URL http://127.0.0.1:8000/loading/redirect-methods.html, http method GET> -frame "2" - didStartProvisionalLoadForFrame -frame "2" - didStartProvisionalLoadForFrame +frame "2" - ReadyToCommitNavigation http://127.0.0.1:8000/loading/resources/redirect-methods-form.html - didReceiveResponse <NSURLResponse http://127.0.0.1:8000/loading/resources/redirect-methods-form.html, http status code 200> frame "2" - didCommitLoadForFrame frame "2" - didReceiveTitle: frame "2" - didFinishDocumentLoadForFrame frame "2" - didHandleOnloadEventsForFrame frame "2" - didFinishLoadForFrame +frame "2" - DidStartNavigation http://127.0.0.1:8000/loading/resources/redirect-methods-result.php - willSendRequest <NSURLRequest URL http://127.0.0.1:8000/loading/resources/redirect-methods-result.php, main document URL http://127.0.0.1:8000/loading/redirect-methods.html, http method POST> -frame "2" - didStartProvisionalLoadForFrame -frame "2" - didStartProvisionalLoadForFrame +frame "2" - ReadyToCommitNavigation http://127.0.0.1:8000/loading/resources/redirect-methods-result.php?redirected=true - didReceiveResponse <NSURLResponse http://127.0.0.1:8000/loading/resources/redirect-methods-result.php?redirected=true, http status code 200> frame "2" - didCommitLoadForFrame frame "2" - didReceiveTitle: frame "2" - didFinishDocumentLoadForFrame frame "3" - didReceiveTitle: -frame "3" - didStartProvisionalLoadForFrame +frame "3" - DidStartNavigation +frame "3" - ReadyToCommitNavigation frame "3" - didCommitLoadForFrame frame "3" - didReceiveTitle: frame "3" - didFinishDocumentLoadForFrame @@ -86,18 +91,18 @@ frame "3" - didFinishLoadForFrame frame "2" - didHandleOnloadEventsForFrame frame "2" - didFinishLoadForFrame +frame "3" - DidStartNavigation http://127.0.0.1:8000/loading/resources/redirect-methods-form.html - willSendRequest <NSURLRequest URL http://127.0.0.1:8000/loading/resources/redirect-methods-form.html, main document URL http://127.0.0.1:8000/loading/redirect-methods.html, http method GET> -frame "3" - didStartProvisionalLoadForFrame -frame "3" - didStartProvisionalLoadForFrame +frame "3" - ReadyToCommitNavigation http://127.0.0.1:8000/loading/resources/redirect-methods-form.html - didReceiveResponse <NSURLResponse http://127.0.0.1:8000/loading/resources/redirect-methods-form.html, http status code 200> frame "3" - didCommitLoadForFrame frame "3" - didReceiveTitle: frame "3" - didFinishDocumentLoadForFrame frame "3" - didHandleOnloadEventsForFrame frame "3" - didFinishLoadForFrame +frame "3" - DidStartNavigation http://127.0.0.1:8000/loading/resources/redirect-methods-result.php - willSendRequest <NSURLRequest URL http://127.0.0.1:8000/loading/resources/redirect-methods-result.php, main document URL http://127.0.0.1:8000/loading/redirect-methods.html, http method POST> -frame "3" - didStartProvisionalLoadForFrame -frame "3" - didStartProvisionalLoadForFrame +frame "3" - ReadyToCommitNavigation http://127.0.0.1:8000/loading/resources/redirect-methods-result.php?redirected=true - didReceiveResponse <NSURLResponse http://127.0.0.1:8000/loading/resources/redirect-methods-result.php?redirected=true, http status code 200> frame "3" - didCommitLoadForFrame frame "3" - didReceiveTitle:
diff --git a/third_party/blink/web_tests/http/tests/loading/redirect-with-no-location-crash-expected.txt b/third_party/blink/web_tests/http/tests/loading/redirect-with-no-location-crash-expected.txt index bd0c3c71..884c935c 100644 --- a/third_party/blink/web_tests/http/tests/loading/redirect-with-no-location-crash-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/redirect-with-no-location-crash-expected.txt
@@ -1,10 +1,11 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: Test for https://bugs.webkit.org/show_bug.cgi?id=29293 frame "<!--framePath //<!--frame0-->-->" - didReceiveTitle: -frame "<!--framePath //<!--frame0-->-->" - didStartProvisionalLoadForFrame +frame "<!--framePath //<!--frame0-->-->" - DidStartNavigation main frame - didFinishDocumentLoadForFrame -frame "<!--framePath //<!--frame0-->-->" - didStartProvisionalLoadForFrame +frame "<!--framePath //<!--frame0-->-->" - ReadyToCommitNavigation frame "<!--framePath //<!--frame0-->-->" - didCommitLoadForFrame frame "<!--framePath //<!--frame0-->-->" - didReceiveTitle: frame "<!--framePath //<!--frame0-->-->" - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/remove-child-triggers-parser-expected.txt b/third_party/blink/web_tests/http/tests/loading/remove-child-triggers-parser-expected.txt index 1dac025..4048f6d 100644 --- a/third_party/blink/web_tests/http/tests/loading/remove-child-triggers-parser-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/remove-child-triggers-parser-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/simple-subframe-expected.txt b/third_party/blink/web_tests/http/tests/loading/simple-subframe-expected.txt index 7fbc7e8..2d92bb7 100644 --- a/third_party/blink/web_tests/http/tests/loading/simple-subframe-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/simple-subframe-expected.txt
@@ -1,10 +1,11 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame frame "f1" - didReceiveTitle: -frame "f1" - didStartProvisionalLoadForFrame +frame "f1" - DidStartNavigation main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame -frame "f1" - didStartProvisionalLoadForFrame +frame "f1" - ReadyToCommitNavigation frame "f1" - didCommitLoadForFrame frame "f1" - didReceiveTitle: frame "f1" - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/slow-parsing-subframe-expected.txt b/third_party/blink/web_tests/http/tests/loading/slow-parsing-subframe-expected.txt index 200bf469..caf4b7a9 100644 --- a/third_party/blink/web_tests/http/tests/loading/slow-parsing-subframe-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/slow-parsing-subframe-expected.txt
@@ -1,10 +1,11 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame frame "f1" - didReceiveTitle: -frame "f1" - didStartProvisionalLoadForFrame +frame "f1" - DidStartNavigation main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame -frame "f1" - didStartProvisionalLoadForFrame +frame "f1" - ReadyToCommitNavigation frame "f1" - didCommitLoadForFrame frame "f1" - didReceiveTitle: frame "f1" - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/state-object-security-exception-expected.txt b/third_party/blink/web_tests/http/tests/loading/state-object-security-exception-expected.txt index 76a2bea..e547d577 100644 --- a/third_party/blink/web_tests/http/tests/loading/state-object-security-exception-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/state-object-security-exception-expected.txt
@@ -1,4 +1,5 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/stop-load-at-commit-expected.txt b/third_party/blink/web_tests/http/tests/loading/stop-load-at-commit-expected.txt index da44157..dc9a22c 100644 --- a/third_party/blink/web_tests/http/tests/loading/stop-load-at-commit-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/stop-load-at-commit-expected.txt
@@ -1,11 +1,12 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame -main frame - didStartProvisionalLoadForFrame -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/loading/sxg/resources/sxg-location-origin-trial.php b/third_party/blink/web_tests/http/tests/loading/sxg/resources/sxg-location-origin-trial.php deleted file mode 100644 index 1f0b7dfa..0000000 --- a/third_party/blink/web_tests/http/tests/loading/sxg/resources/sxg-location-origin-trial.php +++ /dev/null
@@ -1,10 +0,0 @@ -<?php -header('HTTP/1.0 200 OK'); -// generate_token.py http://127.0.0.1:8000 SignedHTTPExchangeOriginTrial --expire-timestamp=2000000000 -header("Origin-Trial: AqVs+066F+i9lgx2N0bCs5B31heTh9PJOfVM00yDS34V3FqBzWCuI3VKOpHPDeeujnaqJRVPHG8q+jBXjPNoLwkAAABleyJvcmlnaW4iOiAiaHR0cDovLzEyNy4wLjAuMTo4MDAwIiwgImZlYXR1cmUiOiAiU2lnbmVkSFRUUEV4Y2hhbmdlT3JpZ2luVHJpYWwiLCAiZXhwaXJ5IjogMjAwMDAwMDAwMH0="); -header("Content-Type: application/signed-exchange;v=b3"); -$name = 'sxg-location.sxg'; -$fp = fopen($name, 'rb'); -header("Content-Length: " . filesize($name)); -fpassthru($fp); -?>
diff --git a/third_party/blink/web_tests/http/tests/loading/sxg/sxg-location-origin-trial-redirect.html b/third_party/blink/web_tests/http/tests/loading/sxg/sxg-location-origin-trial-redirect.html deleted file mode 100644 index 9a32bd3..0000000 --- a/third_party/blink/web_tests/http/tests/loading/sxg/sxg-location-origin-trial-redirect.html +++ /dev/null
@@ -1,19 +0,0 @@ -<!DOCTYPE html> -<title>Location of SignedHTTPExchange with Origin-Trial header after redirect</title> -<script src="../../resources/testharness.js"></script> -<script src="../../resources/testharnessreport.js"></script> -<script src="./resources/sxg-util.js"></script> -<body> -<script> -promise_test(async (t) => { - await waitUntilDidFinishLoadForFrame; - const url = - 'http://localhost:8000/resources/redirect.php?url=' + - encodeURIComponent( - 'http://127.0.0.1:8000/loading/sxg/resources/sxg-location-origin-trial.php'); - const message = await openSXGInIframeAndWaitForMessage(t, url); - assert_equals(message.location, 'https://127.0.0.1:8443/loading/sxg/resources/inner-url.html'); - assert_false(message.is_fallback); -}, 'Location of SignedHTTPExchange with Origin-Trial header after redirect'); -</script> -</body>
diff --git a/third_party/blink/web_tests/http/tests/loading/sxg/sxg-location-origin-trial.html b/third_party/blink/web_tests/http/tests/loading/sxg/sxg-location-origin-trial.html deleted file mode 100644 index 4ef3fb43..0000000 --- a/third_party/blink/web_tests/http/tests/loading/sxg/sxg-location-origin-trial.html +++ /dev/null
@@ -1,16 +0,0 @@ -<!DOCTYPE html> -<title>Location of SignedHTTPExchange with Origin-Trial header</title> -<script src="../../resources/testharness.js"></script> -<script src="../../resources/testharnessreport.js"></script> -<script src="./resources/sxg-util.js"></script> -<body> -<script> -promise_test(async (t) => { - await waitUntilDidFinishLoadForFrame; - - const message = await openSXGInIframeAndWaitForMessage(t, 'resources/sxg-location-origin-trial.php'); - assert_equals(message.location, 'https://127.0.0.1:8443/loading/sxg/resources/inner-url.html'); - assert_false(message.is_fallback); -}, 'Location of SignedHTTPExchange with Origin-Trial header'); -</script> -</body>
diff --git a/third_party/blink/web_tests/http/tests/loading/text-content-type-with-binary-extension-expected.txt b/third_party/blink/web_tests/http/tests/loading/text-content-type-with-binary-extension-expected.txt index 0dcc4b7..a7731b1f 100644 --- a/third_party/blink/web_tests/http/tests/loading/text-content-type-with-binary-extension-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/text-content-type-with-binary-extension-expected.txt
@@ -1,7 +1,8 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame frame "iframe" - didReceiveTitle: -frame "iframe" - didStartProvisionalLoadForFrame +frame "iframe" - DidStartNavigation main frame - didReceiveTitle: main frame - didFinishDocumentLoadForFrame frame "iframe" - didFailProvisionalLoadWithError
diff --git a/third_party/blink/web_tests/http/tests/loading/window-open-onblur-reentrancy-expected.txt b/third_party/blink/web_tests/http/tests/loading/window-open-onblur-reentrancy-expected.txt index 6563535..1a28e0f 100644 --- a/third_party/blink/web_tests/http/tests/loading/window-open-onblur-reentrancy-expected.txt +++ b/third_party/blink/web_tests/http/tests/loading/window-open-onblur-reentrancy-expected.txt
@@ -1,7 +1,9 @@ -main frame - didStartProvisionalLoadForFrame +main frame - DidStartNavigation +main frame - ReadyToCommitNavigation main frame - didCommitLoadForFrame frame "i" - didReceiveTitle: -frame "i" - didStartProvisionalLoadForFrame +frame "i" - DidStartNavigation +frame "i" - ReadyToCommitNavigation frame "i" - didCommitLoadForFrame frame "i" - didReceiveTitle: frame "i" - didFinishDocumentLoadForFrame
diff --git a/third_party/blink/web_tests/http/tests/misc/resources/iframe-initiating-gesture.html b/third_party/blink/web_tests/http/tests/misc/resources/iframe-initiating-gesture.html index bcf2271..fc014b0 100644 --- a/third_party/blink/web_tests/http/tests/misc/resources/iframe-initiating-gesture.html +++ b/third_party/blink/web_tests/http/tests/misc/resources/iframe-initiating-gesture.html
@@ -13,12 +13,6 @@ <script> -// TODO(931723): Synthetic gesture completion callbacks are broken over OOPIFs. -// We'll wait for a scroll event to work around this. -var didScroll = new Promise((resolve) => { - document.addEventListener('scroll', resolve, { once: true }); -}); - window.addEventListener('message', async (e) => { var framePosition = e.data.framePosition; var x = framePosition.x + window.innerWidth / 2; @@ -29,7 +23,6 @@ try { await smoothScroll( 100, x, y, GestureSourceType.DEFAULT_INPUT, 'down', SPEED_INSTANT); - await didScroll; var scrollYAfter = window.scrollY; e.source.postMessage((scrollYAfter > scrollYBefore) ? 'pass' : 'fail', '*'); } catch (error) {
diff --git a/third_party/blink/web_tests/http/tests/security/mixedContent/insecure-iframe-with-hsts.https-expected.txt b/third_party/blink/web_tests/http/tests/security/mixedContent/insecure-iframe-with-hsts.https-expected.txt index 121dc87..752ae76 100644 --- a/third_party/blink/web_tests/http/tests/security/mixedContent/insecure-iframe-with-hsts.https-expected.txt +++ b/third_party/blink/web_tests/http/tests/security/mixedContent/insecure-iframe-with-hsts.https-expected.txt
@@ -3,7 +3,7 @@ main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame frame "<!--framePath //<!--frame0-->-->" - didReceiveTitle: -frame "<!--framePath //<!--frame0-->-->" - didStartProvisionalLoadForFrame +frame "<!--framePath //<!--frame0-->-->" - DidStartNavigation CONSOLE ERROR: line 18: Mixed Content: The page at 'https://127.0.0.1:8443/security/mixedContent/insecure-iframe-with-hsts.https.html' was loaded over HTTPS, but requested an insecure resource 'http://hsts-example.test:8443/security/resources/hsts.php'. This request has been blocked; the content must be served over HTTPS. frame "<!--framePath //<!--frame0-->-->" - didFailProvisionalLoadWithError This is a testharness.js-based test.
diff --git a/third_party/blink/web_tests/http/tests/xmlviewer/ns-node-prev-sibling-expected.png b/third_party/blink/web_tests/http/tests/xmlviewer/ns-node-prev-sibling-expected.png new file mode 100644 index 0000000..b5daa85 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/xmlviewer/ns-node-prev-sibling-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/http/tests/xmlviewer/ns-node-prev-sibling.html b/third_party/blink/web_tests/http/tests/xmlviewer/ns-node-prev-sibling.html new file mode 100644 index 0000000..e778ddf --- /dev/null +++ b/third_party/blink/web_tests/http/tests/xmlviewer/ns-node-prev-sibling.html
@@ -0,0 +1,2 @@ +<?xml-stylesheet type="text/xsl" href="resources/number-key-ns.xsl"?> +<top xmlns:type_confusion="aaaaaaaabbbbbbbbccccccccddddddddeeeeeeeeffffffh" />
diff --git a/third_party/blink/web_tests/http/tests/xmlviewer/resources/number-key-ns.xsl b/third_party/blink/web_tests/http/tests/xmlviewer/resources/number-key-ns.xsl new file mode 100644 index 0000000..d8d6158 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/xmlviewer/resources/number-key-ns.xsl
@@ -0,0 +1,8 @@ +<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> + <xsl:key name="aaa" match="/bbb" use="./ccc"/> + <xsl:template match="//child::node()"> + <xsl:for-each select="namespace::*[position()=2]"> + <xsl:number from="key('e','f')"/> + </xsl:for-each> + </xsl:template> +</xsl:stylesheet>
diff --git a/third_party/blink/web_tests/inspector-protocol/page/pageDomContentBeforeLoadEventFired-expected.txt b/third_party/blink/web_tests/inspector-protocol/page/pageDomContentBeforeLoadEventFired-expected.txt new file mode 100644 index 0000000..1f3fe36f --- /dev/null +++ b/third_party/blink/web_tests/inspector-protocol/page/pageDomContentBeforeLoadEventFired-expected.txt
@@ -0,0 +1,16 @@ +Tests Page.domContentEventFired is triggered before Page.loadEventFired for a non-blank page +{ + method : Page.domContentEventFired + params : { + timestamp : <number> + } + sessionId : <string> +} +{ + method : Page.loadEventFired + params : { + timestamp : <number> + } + sessionId : <string> +} +
diff --git a/third_party/blink/web_tests/inspector-protocol/page/pageDomContentBeforeLoadEventFired.js b/third_party/blink/web_tests/inspector-protocol/page/pageDomContentBeforeLoadEventFired.js new file mode 100644 index 0000000..8e734e7 --- /dev/null +++ b/third_party/blink/web_tests/inspector-protocol/page/pageDomContentBeforeLoadEventFired.js
@@ -0,0 +1,15 @@ +(async function (testRunner) { + const { page, session, dp } = await testRunner.startBlank( + 'Tests Page.domContentEventFired is triggered before Page.loadEventFired for a non-blank page'); + + await dp.Page.enable(); + + const htmlPage = testRunner.url('../resources/dom-snapshot.html'); + dp.Page.navigate({ url: htmlPage }); + const domContentEvent = await dp.Page.onceDomContentEventFired(); + testRunner.log(domContentEvent); + const loadEvent = await dp.Page.onceLoadEventFired(); + testRunner.log(loadEvent); + + testRunner.completeTest(); +})
diff --git a/third_party/blink/web_tests/inspector-protocol/page/pageLoadBeforeDomContentEventFired-expected.txt b/third_party/blink/web_tests/inspector-protocol/page/pageLoadBeforeDomContentEventFired-expected.txt new file mode 100644 index 0000000..96748fe --- /dev/null +++ b/third_party/blink/web_tests/inspector-protocol/page/pageLoadBeforeDomContentEventFired-expected.txt
@@ -0,0 +1,16 @@ +Tests Page.loadEventFired is triggered before Page.domContentEventFired for a blank page +{ + method : Page.loadEventFired + params : { + timestamp : <number> + } + sessionId : <string> +} +{ + method : Page.domContentEventFired + params : { + timestamp : <number> + } + sessionId : <string> +} +
diff --git a/third_party/blink/web_tests/inspector-protocol/page/pageLoadBeforeDomContentEventFired.js b/third_party/blink/web_tests/inspector-protocol/page/pageLoadBeforeDomContentEventFired.js new file mode 100644 index 0000000..5eb1820 --- /dev/null +++ b/third_party/blink/web_tests/inspector-protocol/page/pageLoadBeforeDomContentEventFired.js
@@ -0,0 +1,15 @@ +(async function (testRunner) { + const { page, session, dp } = await testRunner.startBlank( + 'Tests Page.loadEventFired is triggered before Page.domContentEventFired for a blank page'); + + await dp.Page.enable(); + + const htmlPage = testRunner.url('../resources/blank.html'); + dp.Page.navigate({ url: htmlPage }); + const loadEvent = await dp.Page.onceLoadEventFired(); + testRunner.log(loadEvent); + const domContentEvent = await dp.Page.onceDomContentEventFired(); + testRunner.log(domContentEvent); + + testRunner.completeTest(); +})
diff --git a/third_party/blink/web_tests/media/alpha-video-playback-expected.png b/third_party/blink/web_tests/media/alpha-video-playback-expected.png new file mode 100644 index 0000000..e2872f31 --- /dev/null +++ b/third_party/blink/web_tests/media/alpha-video-playback-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/media/alpha-video-playback.html b/third_party/blink/web_tests/media/alpha-video-playback.html new file mode 100644 index 0000000..71aa824 --- /dev/null +++ b/third_party/blink/web_tests/media/alpha-video-playback.html
@@ -0,0 +1,33 @@ +<!doctype html> +<title>Verify VP9+Alpha video playback and canvas interact correctly.</title> +<style> + body { background: white; } + video, canvas { background: pink; } +</style> +<script> + if (window.testRunner) + testRunner.waitUntilDone(); + + function startTest() { + var video = document.querySelector('video'); + + video.oncanplaythrough = function() { + var canvas = document.querySelector('canvas'); + var ctx = canvas.getContext('2d'); + + // This will squish the video a bit, but it doesn't matter for this test. + ctx.clearRect(0, 0, canvas.width, canvas.height); + ctx.drawImage(video, 0, 0, canvas.width, canvas.height); + + // Wait for request animation frame to ensure the video frame is drawn. + if (window.testRunner) + window.requestAnimationFrame(_ => { testRunner.notifyDone(); }); + } + + video.src = "resources/white-square-vp9a.webm"; + } +</script> +<body onload="startTest();"> + <video width="320" height="240"></video> + <canvas width="320" height="240"></canvas> +</body>
diff --git a/third_party/blink/web_tests/media/controls/modern/scrubbing.html b/third_party/blink/web_tests/media/controls/modern/scrubbing.html index d0251af..1bddb1fb5 100644 --- a/third_party/blink/web_tests/media/controls/modern/scrubbing.html +++ b/third_party/blink/web_tests/media/controls/modern/scrubbing.html
@@ -37,7 +37,7 @@ { name: 'pointerMove', x: c[0], y: c[1] }, { name: 'pointerDown', x: c[0], y: c[1], button: leftButton }, { name: 'pointerMove', x: c2[0], y: c2[1]}, - { name: 'pause', duration: 5 }, + { name: 'pause', duration: 5000 }, { name: 'pointerUp', button: leftButton } ] }
diff --git a/third_party/blink/web_tests/media/media-controls.js b/third_party/blink/web_tests/media/media-controls.js index 87ba2f5..f62950f 100644 --- a/third_party/blink/web_tests/media/media-controls.js +++ b/third_party/blink/web_tests/media/media-controls.js
@@ -544,7 +544,7 @@ actions: [ { name: 'pointerDown', x: x, y: y }, { name: 'pointerUp' }, - { name: 'pause', duration: timeout / 1000 }, + { name: 'pause', duration: timeout }, { name: 'pointerDown', x: x, y: y }, { name: 'pointerUp' } ] @@ -610,7 +610,7 @@ actions: [ { name: 'pointerDown', x: x, y: y }, { name: 'pointerUp' }, - { name: 'pause', duration: timeout / 1000 }, + { name: 'pause', duration: timeout }, { name: 'pointerDown', x: x, y: y }, { name: 'pointerUp' } ]
diff --git a/third_party/blink/web_tests/media/resources/white-square-vp9a.webm b/third_party/blink/web_tests/media/resources/white-square-vp9a.webm new file mode 100644 index 0000000..e3d85fb --- /dev/null +++ b/third_party/blink/web_tests/media/resources/white-square-vp9a.webm Binary files differ
diff --git a/third_party/blink/web_tests/mojo/document-interface-broker-override.html b/third_party/blink/web_tests/mojo/document-interface-broker-override.html index 8e1da98b..561b034a 100644 --- a/third_party/blink/web_tests/mojo/document-interface-broker-override.html +++ b/third_party/blink/web_tests/mojo/document-interface-broker-override.html
@@ -18,14 +18,8 @@ Mojo.getDocumentInterfaceBrokerHandle()); const testInterfaceProxyBeforeOverride = new blink.mojom.FrameHostTestInterfaceProxy; - console.log("proxy" + typeof(testInterfaceProxyBeforeOverride)); brokerProxy.getFrameHostTestInterface(testInterfaceProxyBeforeOverride.$.createRequest()); - // Verify that RenderFrameHostImpl's implementation gets called without an override - testInterfaceProxyBeforeOverride.getName().then(reply => { - assert_equals(reply.name, 'RenderFrameHostImpl'); - }); - setDocumentInterfaceBrokerOverrides({ getFrameHostTestInterface: request => { frameHostTestImpl.bindHandle(request.handle); }}); @@ -33,10 +27,13 @@ const testInterfaceProxyAfterOverride = new blink.mojom.FrameHostTestInterfaceProxy; brokerProxy.getFrameHostTestInterface(testInterfaceProxyAfterOverride.$.createRequest()); + // Verify that RenderFrameHostImpl's implementation gets called without an override + let reply = await testInterfaceProxyBeforeOverride.getName(); + assert_equals(reply.name, 'RenderFrameHostImpl'); + // Verify that the test implementation gets called after the override - return testInterfaceProxyAfterOverride.getName().then(reply => { - assert_equals(reply.name, 'TestFrameHostTestImpl'); - }); + reply = await testInterfaceProxyAfterOverride.getName(); + assert_equals(reply.name, 'TestFrameHostTestImpl'); }, 'Appropriate DocumentInterfaceBroker implementations are called before and after overriding');
diff --git a/third_party/blink/web_tests/platform/android/external/wpt/web-animations/timing-model/animations/set-the-animation-start-time-expected.txt b/third_party/blink/web_tests/platform/android/external/wpt/web-animations/timing-model/animations/set-the-animation-start-time-expected.txt deleted file mode 100644 index cc38ff5..0000000 --- a/third_party/blink/web_tests/platform/android/external/wpt/web-animations/timing-model/animations/set-the-animation-start-time-expected.txt +++ /dev/null
@@ -1,10 +0,0 @@ -This is a testharness.js-based test. -FAIL Setting the start time of an animation without an active timeline assert_equals: Setting the start time clears the current time expected (object) null but got (number) -463.4576666666703 -FAIL Setting an unresolved start time an animation without an active timeline does not clear the current time assert_equals: Start time remains unresolved expected (object) null but got (number) 0 -PASS Setting the start time clears the hold time -FAIL Setting an unresolved start time sets the hold time assert_approx_equals: Hold time is set after start time is made unresolved expected 1000 +/- 0.0005 but got 536.5423333333297 -FAIL Setting the start time resolves a pending ready promise assert_true: Animation is in play-pending state expected true got undefined -FAIL Setting the start time resolves a pending pause task assert_true: Animation is in pause-pending state expected true got undefined -FAIL Setting the start time updates the finished state assert_greater_than: Setting the start time updated the finished state with the 'did seek' flag set to true expected a number greater than 100000 but got 100000 -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/linux/editing/input/caret-at-the-edge-of-contenteditable-expected.png b/third_party/blink/web_tests/platform/linux/editing/input/caret-at-the-edge-of-contenteditable-expected.png index b89a131e..f604dbf3 100644 --- a/third_party/blink/web_tests/platform/linux/editing/input/caret-at-the-edge-of-contenteditable-expected.png +++ b/third_party/blink/web_tests/platform/linux/editing/input/caret-at-the-edge-of-contenteditable-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/editing/input/caret-at-the-edge-of-input-expected.png b/third_party/blink/web_tests/platform/linux/editing/input/caret-at-the-edge-of-input-expected.png index 8b64592..089a034 100644 --- a/third_party/blink/web_tests/platform/linux/editing/input/caret-at-the-edge-of-input-expected.png +++ b/third_party/blink/web_tests/platform/linux/editing/input/caret-at-the-edge-of-input-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/editing/input/reveal-caret-of-multiline-contenteditable-expected.png b/third_party/blink/web_tests/platform/linux/editing/input/reveal-caret-of-multiline-contenteditable-expected.png index 61cea4a..051687a 100644 --- a/third_party/blink/web_tests/platform/linux/editing/input/reveal-caret-of-multiline-contenteditable-expected.png +++ b/third_party/blink/web_tests/platform/linux/editing/input/reveal-caret-of-multiline-contenteditable-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/editing/input/reveal-caret-of-multiline-input-expected.png b/third_party/blink/web_tests/platform/linux/editing/input/reveal-caret-of-multiline-input-expected.png index 1a5194c..3b4a6d1c 100644 --- a/third_party/blink/web_tests/platform/linux/editing/input/reveal-caret-of-multiline-input-expected.png +++ b/third_party/blink/web_tests/platform/linux/editing/input/reveal-caret-of-multiline-input-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/forms/text/input-text-scroll-left-on-blur-expected.png b/third_party/blink/web_tests/platform/linux/fast/forms/text/input-text-scroll-left-on-blur-expected.png index 4c1770a..f09c4d3 100644 --- a/third_party/blink/web_tests/platform/linux/fast/forms/text/input-text-scroll-left-on-blur-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/forms/text/input-text-scroll-left-on-blur-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/media/alpha-video-playback-expected.png b/third_party/blink/web_tests/platform/linux/media/alpha-video-playback-expected.png new file mode 100644 index 0000000..e2872f31 --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/media/alpha-video-playback-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.10/editing/input/caret-at-the-edge-of-input-expected.png b/third_party/blink/web_tests/platform/mac-mac10.10/editing/input/caret-at-the-edge-of-input-expected.png index 933207e..ca0ddc9 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.10/editing/input/caret-at-the-edge-of-input-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.10/editing/input/caret-at-the-edge-of-input-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.10/editing/input/reveal-caret-of-multiline-input-expected.png b/third_party/blink/web_tests/platform/mac-mac10.10/editing/input/reveal-caret-of-multiline-input-expected.png index 75aa2693..22d7c8b 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.10/editing/input/reveal-caret-of-multiline-input-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.10/editing/input/reveal-caret-of-multiline-input-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.10/fast/forms/text/input-text-scroll-left-on-blur-expected.png b/third_party/blink/web_tests/platform/mac-mac10.10/fast/forms/text/input-text-scroll-left-on-blur-expected.png index 8f81f6d..7420fa2b 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.10/fast/forms/text/input-text-scroll-left-on-blur-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.10/fast/forms/text/input-text-scroll-left-on-blur-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.11/editing/input/caret-at-the-edge-of-input-expected.png b/third_party/blink/web_tests/platform/mac-mac10.11/editing/input/caret-at-the-edge-of-input-expected.png index dabafa8e..3924808 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.11/editing/input/caret-at-the-edge-of-input-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.11/editing/input/caret-at-the-edge-of-input-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.11/editing/input/reveal-caret-of-multiline-input-expected.png b/third_party/blink/web_tests/platform/mac-mac10.11/editing/input/reveal-caret-of-multiline-input-expected.png index 27d1a11..a7ea9fa2 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.11/editing/input/reveal-caret-of-multiline-input-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.11/editing/input/reveal-caret-of-multiline-input-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.11/fast/forms/text/input-text-scroll-left-on-blur-expected.png b/third_party/blink/web_tests/platform/mac-mac10.11/fast/forms/text/input-text-scroll-left-on-blur-expected.png index 55b9bf0f..f8b5a9bee 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.11/fast/forms/text/input-text-scroll-left-on-blur-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.11/fast/forms/text/input-text-scroll-left-on-blur-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.12/editing/input/reveal-caret-of-multiline-input-expected.png b/third_party/blink/web_tests/platform/mac-mac10.12/editing/input/reveal-caret-of-multiline-input-expected.png index 552271bd..7491a35 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.12/editing/input/reveal-caret-of-multiline-input-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.12/editing/input/reveal-caret-of-multiline-input-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/editing/input/caret-at-the-edge-of-contenteditable-expected.png b/third_party/blink/web_tests/platform/mac/editing/input/caret-at-the-edge-of-contenteditable-expected.png index 7c95804..d7d31e9e 100644 --- a/third_party/blink/web_tests/platform/mac/editing/input/caret-at-the-edge-of-contenteditable-expected.png +++ b/third_party/blink/web_tests/platform/mac/editing/input/caret-at-the-edge-of-contenteditable-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/editing/input/caret-at-the-edge-of-input-expected.png b/third_party/blink/web_tests/platform/mac/editing/input/caret-at-the-edge-of-input-expected.png index 61b1dcd..8576c7f5 100644 --- a/third_party/blink/web_tests/platform/mac/editing/input/caret-at-the-edge-of-input-expected.png +++ b/third_party/blink/web_tests/platform/mac/editing/input/caret-at-the-edge-of-input-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/editing/input/reveal-caret-of-multiline-contenteditable-expected.png b/third_party/blink/web_tests/platform/mac/editing/input/reveal-caret-of-multiline-contenteditable-expected.png index 7130b82..e47cec0 100644 --- a/third_party/blink/web_tests/platform/mac/editing/input/reveal-caret-of-multiline-contenteditable-expected.png +++ b/third_party/blink/web_tests/platform/mac/editing/input/reveal-caret-of-multiline-contenteditable-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/editing/input/reveal-caret-of-multiline-input-expected.png b/third_party/blink/web_tests/platform/mac/editing/input/reveal-caret-of-multiline-input-expected.png index da270d5..1c959ae 100644 --- a/third_party/blink/web_tests/platform/mac/editing/input/reveal-caret-of-multiline-input-expected.png +++ b/third_party/blink/web_tests/platform/mac/editing/input/reveal-caret-of-multiline-input-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/forms/text/input-text-scroll-left-on-blur-expected.png b/third_party/blink/web_tests/platform/mac/fast/forms/text/input-text-scroll-left-on-blur-expected.png index 498ebcb..c7449ab6 100644 --- a/third_party/blink/web_tests/platform/mac/fast/forms/text/input-text-scroll-left-on-blur-expected.png +++ b/third_party/blink/web_tests/platform/mac/fast/forms/text/input-text-scroll-left-on-blur-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/editing/input/caret-at-the-edge-of-contenteditable-expected.png b/third_party/blink/web_tests/platform/win/editing/input/caret-at-the-edge-of-contenteditable-expected.png index a05ffc146..64e80a97 100644 --- a/third_party/blink/web_tests/platform/win/editing/input/caret-at-the-edge-of-contenteditable-expected.png +++ b/third_party/blink/web_tests/platform/win/editing/input/caret-at-the-edge-of-contenteditable-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/editing/input/caret-at-the-edge-of-input-expected.png b/third_party/blink/web_tests/platform/win/editing/input/caret-at-the-edge-of-input-expected.png index 0cc638fa..de5405f 100644 --- a/third_party/blink/web_tests/platform/win/editing/input/caret-at-the-edge-of-input-expected.png +++ b/third_party/blink/web_tests/platform/win/editing/input/caret-at-the-edge-of-input-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/editing/input/reveal-caret-of-multiline-contenteditable-expected.png b/third_party/blink/web_tests/platform/win/editing/input/reveal-caret-of-multiline-contenteditable-expected.png index 7d1891c..8d261bd 100644 --- a/third_party/blink/web_tests/platform/win/editing/input/reveal-caret-of-multiline-contenteditable-expected.png +++ b/third_party/blink/web_tests/platform/win/editing/input/reveal-caret-of-multiline-contenteditable-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/editing/input/reveal-caret-of-multiline-input-expected.png b/third_party/blink/web_tests/platform/win/editing/input/reveal-caret-of-multiline-input-expected.png index aee6df72..2a86a15 100644 --- a/third_party/blink/web_tests/platform/win/editing/input/reveal-caret-of-multiline-input-expected.png +++ b/third_party/blink/web_tests/platform/win/editing/input/reveal-caret-of-multiline-input-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/forms/text/input-text-scroll-left-on-blur-expected.png b/third_party/blink/web_tests/platform/win/fast/forms/text/input-text-scroll-left-on-blur-expected.png index 949e0fb..92461294 100644 --- a/third_party/blink/web_tests/platform/win/fast/forms/text/input-text-scroll-left-on-blur-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/forms/text/input-text-scroll-left-on-blur-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/media/alpha-video-playback-expected.png b/third_party/blink/web_tests/platform/win/media/alpha-video-playback-expected.png new file mode 100644 index 0000000..806797b --- /dev/null +++ b/third_party/blink/web_tests/platform/win/media/alpha-video-playback-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/resources/gesture-util.js b/third_party/blink/web_tests/resources/gesture-util.js index e4399c7..c885e13 100644 --- a/third_party/blink/web_tests/resources/gesture-util.js +++ b/third_party/blink/web_tests/resources/gesture-util.js
@@ -338,7 +338,7 @@ function doubleTapAt(xPosition, yPosition) { // This comes from config constants in gesture_detector.cc. - const DOUBLE_TAP_MINIMUM_DURATION_S = 0.04; + const DOUBLE_TAP_MINIMUM_DURATION_MS = 40; return new Promise(function(resolve, reject) { if (!window.chrome || !chrome.gpuBenchmarking) { @@ -351,7 +351,7 @@ actions: [ { name: 'pointerDown', x: xPosition, y: yPosition }, { name: 'pointerUp' }, - { name: 'pause', duration: DOUBLE_TAP_MINIMUM_DURATION_S }, + { name: 'pause', duration: DOUBLE_TAP_MINIMUM_DURATION_MS }, { name: 'pointerDown', x: xPosition, y: yPosition }, { name: 'pointerUp' } ]
diff --git a/third_party/blink/web_tests/virtual/scroll_customization/fast/scroll-behavior/scroll-customization/scroll-customization-property.html b/third_party/blink/web_tests/virtual/scroll_customization/fast/scroll-behavior/scroll-customization/scroll-customization-property.html index d2d082d..c44e9524 100644 --- a/third_party/blink/web_tests/virtual/scroll_customization/fast/scroll-behavior/scroll-customization/scroll-customization-property.html +++ b/third_party/blink/web_tests/virtual/scroll_customization/fast/scroll-behavior/scroll-customization/scroll-customization-property.html
@@ -181,7 +181,7 @@ // this when and if it becomes possible to create gesture scroll without the // delay (https://crbug.com/803168). // Necessary to avoid getting a fling instead. Cannot be too small. - var pauseSeconds = 0.05; + var pauseMilliseconds = 100; return new Promise((resolve) => { chrome.gpuBenchmarking.pointerActionSequence([{ source: 'touch', @@ -189,7 +189,7 @@ { name: 'pointerDown', x: startingX, y: startingY }, { name: 'pointerMove', x: (startingX + deltaX), y: (startingY + deltaY)}, - { name: 'pause', duration: pauseSeconds}, + { name: 'pause', duration: pauseMilliseconds}, { name: 'pointerUp'} ] }], resolve);
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 fbc7e2d..77532a9 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
@@ -223,6 +223,7 @@ attribute @@toStringTag getter attestationObject method constructor + method getTransports interface AuthenticatorResponse attribute @@toStringTag getter clientDataJSON
diff --git a/third_party/blink/web_tests/virtual/sxg-origin-trial-with-network-service/http/tests/loading/sxg/README.txt b/third_party/blink/web_tests/virtual/sxg-origin-trial-with-network-service/http/tests/loading/sxg/README.txt deleted file mode 100644 index 291cb01b..0000000 --- a/third_party/blink/web_tests/virtual/sxg-origin-trial-with-network-service/http/tests/loading/sxg/README.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This directory is for testing the SignedHTTPExchangeOriginTrial feature. - -This suite runs the tests with --stable-release-mode, with which we -run tests with only stable feature (no experiments).
diff --git a/third_party/blink/web_tests/virtual/sxg-origin-trial/http/tests/loading/sxg/README.txt b/third_party/blink/web_tests/virtual/sxg-origin-trial/http/tests/loading/sxg/README.txt deleted file mode 100644 index 291cb01b..0000000 --- a/third_party/blink/web_tests/virtual/sxg-origin-trial/http/tests/loading/sxg/README.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This directory is for testing the SignedHTTPExchangeOriginTrial feature. - -This suite runs the tests with --stable-release-mode, with which we -run tests with only stable feature (no experiments).
diff --git a/third_party/closure_compiler/externs/file_manager_private.js b/third_party/closure_compiler/externs/file_manager_private.js index df9d8e4..09402b0a 100644 --- a/third_party/closure_compiler/externs/file_manager_private.js +++ b/third_party/closure_compiler/externs/file_manager_private.js
@@ -517,8 +517,8 @@ * Gets the list of tasks that can be performed over selected files. |entries| * Array of selected entries |callback| * @param {!Array<!Entry>} entries - * @param {function((!Array<!chrome.fileManagerPrivate.FileTask>|undefined))} callback |tasks| The list of - * matched file entries for this task. + * @param {function((!Array<!chrome.fileManagerPrivate.FileTask>|undefined))} + * callback |tasks| The list of matched file entries for this task. */ chrome.fileManagerPrivate.getFileTasks = function(entries, callback) {}; @@ -598,9 +598,9 @@ * |callback| * @param {!Array<!Entry>} entries * @param {!Array<string>} names - * @param {function((!Array<!chrome.fileManagerPrivate.EntryProperties>|undefined))} callback - * |entryProperties| A dictionary containing properties of the requested - * entries. + * @param {function((!Array<!chrome.fileManagerPrivate.EntryProperties>|undefined))} + * callback |entryProperties| A dictionary containing properties of the + * requested entries. */ chrome.fileManagerPrivate.getEntryProperties = function(entries, names, callback) {}; @@ -671,9 +671,9 @@ /** * Get the list of mounted volumes. |callback| - * @param {function((!Array<!chrome.fileManagerPrivate.VolumeMetadata>|undefined))} callback Callback with - * the list of chrome.fileManagerPrivate.VolumeMetadata representing mounted - * volumes. + * @param {function((!Array<!chrome.fileManagerPrivate.VolumeMetadata>|undefined))} + * callback Callback with the list of + * chrome.fileManagerPrivate.VolumeMetadata representing mounted volumes. */ chrome.fileManagerPrivate.getVolumeMetadataList = function(callback) {}; @@ -711,8 +711,9 @@ * Retrieves total and remaining size of a mount point. |volumeId| ID of the * volume to be checked. |callback| * @param {string} volumeId - * @param {function((!chrome.fileManagerPrivate.MountPointSizeStats|undefined))} callback Name/value pairs - * of size stats. Will be undefined if stats could not be determined. + * @param {function((!chrome.fileManagerPrivate.MountPointSizeStats|undefined))} + * callback Name/value pairs of size stats. Will be undefined if stats could + * not be determined. */ chrome.fileManagerPrivate.getSizeStats = function(volumeId, callback) {}; @@ -732,7 +733,8 @@ /** * Retrieves file manager preferences. |callback| - * @param {function((!chrome.fileManagerPrivate.Preferences|undefined))} callback + * @param {function((!chrome.fileManagerPrivate.Preferences|undefined))} + * callback */ chrome.fileManagerPrivate.getPreferences = function(callback) {}; @@ -754,7 +756,8 @@ /** * Performs drive metadata search. |searchParams| |callback| * @param {chrome.fileManagerPrivate.SearchMetadataParams} searchParams - * @param {function((!Array<!chrome.fileManagerPrivate.SearchResult>|undefined))} callback + * @param {function((!Array<!chrome.fileManagerPrivate.SearchResult>|undefined))} + * callback */ chrome.fileManagerPrivate.searchDriveMetadata = function(searchParams, callback) {}; @@ -810,7 +813,7 @@ /** * Requests a Drive API OAuth2 access token. |refresh| Whether the token should - * be refetched instead of using the cached one. |callback| + * be refetched instead of using the cached one. |callback| * @param {boolean} refresh * @param {function((string|undefined))} callback |accessToken| OAuth2 access * token, or an empty string if failed to fetch. @@ -842,10 +845,11 @@ /** * Obtains a list of profiles that are logged-in. - * @param {function((!Array<!chrome.fileManagerPrivate.ProfileInfo>|undefined), (string|undefined), - * (string|undefined))} callback Callback with list of profile information, - * |runningProfile| ID of the profile that runs the application instance. - * |showingProfile| ID of the profile that shows the application window. + * @param {function((!Array<!chrome.fileManagerPrivate.ProfileInfo>|undefined), + * (string|undefined), (string|undefined))} callback Callback with list of + * profile information, |runningProfile| ID of the profile that runs the + * application instance. |showingProfile| ID of the profile that shows the + * application window. */ chrome.fileManagerPrivate.getProfiles = function(callback) {}; @@ -894,7 +898,8 @@ /** * Returns list of available providers. - * @param {function((!Array<!chrome.fileManagerPrivate.Provider>|undefined))} callback + * @param {function((!Array<!chrome.fileManagerPrivate.Provider>|undefined))} + * callback */ chrome.fileManagerPrivate.getProviders = function(callback) {}; @@ -919,7 +924,8 @@ * Requests fetching list of actions for the specified set of entries. If not * possible, then returns an error via chrome.runtime.lastError. * @param {!Array<!Entry>} entries - * @param {function((!Array<!chrome.fileSystemProvider.Action>|undefined))} callback + * @param {function((!Array<!chrome.fileSystemProvider.Action>|undefined))} + * callback */ chrome.fileManagerPrivate.getCustomActions = function(entries, callback) {};
diff --git a/third_party/crashpad/README.chromium b/third_party/crashpad/README.chromium index 37877073..19dadd7 100644 --- a/third_party/crashpad/README.chromium +++ b/third_party/crashpad/README.chromium
@@ -2,7 +2,7 @@ Short Name: crashpad URL: https://crashpad.chromium.org/ Version: unknown -Revision: bba9d0819c12a4bf39bebafb6233e000aa8a446c +Revision: 39e458b331b7ea09a20b1efbc001dee82b203bf2 License: Apache 2.0 License File: crashpad/LICENSE Security Critical: yes
diff --git a/third_party/crashpad/crashpad/minidump/minidump_extensions.h b/third_party/crashpad/crashpad/minidump/minidump_extensions.h index bdaaa48..6715744 100644 --- a/third_party/crashpad/crashpad/minidump/minidump_extensions.h +++ b/third_party/crashpad/crashpad/minidump/minidump_extensions.h
@@ -30,7 +30,7 @@ // compiler is buggy and only supports disabling it with a pragma, so we can't // disable it with other silly warnings in build/common.gypi. See: // https://connect.microsoft.com/VisualStudio/feedback/details/1114440 -MSVC_PUSH_DISABLE_WARNING(4200); +MSVC_PUSH_DISABLE_WARNING(4200) #if defined(COMPILER_MSVC) #define PACKED @@ -501,7 +501,7 @@ #endif // COMPILER_MSVC #undef PACKED -MSVC_POP_WARNING(); // C4200 +MSVC_POP_WARNING() // C4200 } // namespace crashpad
diff --git a/third_party/crashpad/crashpad/snapshot/crashpad_info_client_options.cc b/third_party/crashpad/crashpad/snapshot/crashpad_info_client_options.cc index 4a89d84..fe3b0b3 100644 --- a/third_party/crashpad/crashpad/snapshot/crashpad_info_client_options.cc +++ b/third_party/crashpad/crashpad/snapshot/crashpad_info_client_options.cc
@@ -39,7 +39,8 @@ CrashpadInfoClientOptions::CrashpadInfoClientOptions() : crashpad_handler_behavior(TriState::kUnset), system_crash_reporter_forwarding(TriState::kUnset), - gather_indirectly_referenced_memory(TriState::kUnset) { + gather_indirectly_referenced_memory(TriState::kUnset), + indirectly_referenced_memory_cap(0) { } } // namespace crashpad
diff --git a/third_party/crashpad/crashpad/util/misc/capture_context_test.cc b/third_party/crashpad/crashpad/util/misc/capture_context_test.cc index 7137a31..42ce6ea 100644 --- a/third_party/crashpad/crashpad/util/misc/capture_context_test.cc +++ b/third_party/crashpad/crashpad/util/misc/capture_context_test.cc
@@ -55,7 +55,7 @@ const uintptr_t kReferencePC = reinterpret_cast<uintptr_t>(TestCaptureContext); EXPECT_PRED2([](uintptr_t actual, - uintptr_t reference) { return actual - reference < 64u; }, + uintptr_t reference) { return actual - reference < 128u; }, pc, kReferencePC); #endif // !defined(ADDRESS_SANITIZER)
diff --git a/third_party/crashpad/crashpad/util/process/process_memory_mac.cc b/third_party/crashpad/crashpad/util/process/process_memory_mac.cc index eba1f20..29357f3 100644 --- a/third_party/crashpad/crashpad/util/process/process_memory_mac.cc +++ b/third_party/crashpad/crashpad/util/process/process_memory_mac.cc
@@ -94,8 +94,16 @@ "mach_vm_read(0x%llx, 0x%llx)", region_address, region_size); return std::unique_ptr<MappedMemory>(); } + if (region_count != region_size) { + LOG(ERROR) << base::StringPrintf( + "mach_vm_read() unexpected read: 0x%x != 0x%llx bytes", + region_count, + region_size); + if (region_count) + vm_deallocate(mach_task_self(), region, region_count); + return std::unique_ptr<MappedMemory>(); + } - DCHECK_EQ(region_count, region_size); return std::unique_ptr<MappedMemory>( new MappedMemory(region, region_size, address - region_address, size)); }
diff --git a/third_party/espresso/OWNERS b/third_party/espresso/OWNERS index 6f9a49c1..e44d585 100644 --- a/third_party/espresso/OWNERS +++ b/third_party/espresso/OWNERS
@@ -1,2 +1 @@ jbudorick@chromium.org -aluo@chromium.org
diff --git a/third_party/flatbuffers/BUILD.gn b/third_party/flatbuffers/BUILD.gn index 03f5652..eb247f9 100644 --- a/third_party/flatbuffers/BUILD.gn +++ b/third_party/flatbuffers/BUILD.gn
@@ -56,12 +56,13 @@ "src/src/idl_gen_general.cpp", "src/src/idl_gen_go.cpp", "src/src/idl_gen_grpc.cpp", - "src/src/idl_gen_js.cpp", + "src/src/idl_gen_js_ts.cpp", "src/src/idl_gen_json_schema.cpp", "src/src/idl_gen_lobster.cpp", "src/src/idl_gen_lua.cpp", "src/src/idl_gen_php.cpp", "src/src/idl_gen_python.cpp", + "src/src/idl_gen_rust.cpp", "src/src/idl_gen_text.cpp", "src/src/idl_parser.cpp", "src/src/reflection.cpp", @@ -83,6 +84,8 @@ ":compiler_files", ":flatbuffers", ] + configs -= [ "//build/config/compiler:chromium_code" ] + configs += [ "//build/config/compiler:no_chromium_code" ] } # The following is just for testing. @@ -102,6 +105,8 @@ test("flatbuffers_unittest") { sources = [ "src/tests/test.cpp", + "src/tests/test_assert.cpp", + "src/tests/test_builder.cpp", ] deps = [ ":compiler_files", @@ -112,9 +117,8 @@ "src/tests/", ] - if (is_win) { - # Suppress "object allocated on the heap may not be aligned 16". - cflags = [ "/wd4316" ] - } - defines = [ "FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE" ] + defines = [ + "FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE", + "FLATBUFFERS_TEST_PATH_PREFIX=third_party/flatbuffers/src/", + ] }
diff --git a/third_party/flatbuffers/README.chromium b/third_party/flatbuffers/README.chromium index 1e7f3309..7905758 100644 --- a/third_party/flatbuffers/README.chromium +++ b/third_party/flatbuffers/README.chromium
@@ -1,8 +1,8 @@ Name: FlatBuffers Short Name: flatbuffers URL: https://github.com/google/flatbuffers -Version: 5d3648b88a91e8a5d67db83df2d08bb9e8702ae8 -Date: 2018-07-24 +Version: 4f32cbf268a8ad469974b9453924a3582dbf2f30 +Date: 2019-02-20 License: Apache 2.0 License File: LICENSE Security Critical: yes
diff --git a/third_party/glslang/README.chromium b/third_party/glslang/README.chromium index 6bc5852b..f22f536 100644 --- a/third_party/glslang/README.chromium +++ b/third_party/glslang/README.chromium
@@ -1,6 +1,6 @@ -Name: Google fork of Khronos reference front-end for GLSL and ESSL +Name: Khronos reference front-end for GLSL and ESSL Short Name: glslang -URL: https://github.com/google/glslang +URL: https://github.com/KhronosGroup/glslang Version: Unknown Security Critical: yes License: MIT @@ -12,4 +12,4 @@ Local Modifications: Added OWNERS, README.chromium. Ported build rules from CMake to GN. -5/13/2016 - Updated GN build rules to include new files added in repository. \ No newline at end of file +5/13/2016 - Updated GN build rules to include new files added in repository.
diff --git a/third_party/google-truth/OWNERS b/third_party/google-truth/OWNERS index e0f85ce..31731969 100644 --- a/third_party/google-truth/OWNERS +++ b/third_party/google-truth/OWNERS
@@ -1,3 +1,2 @@ -aluo@chromium.org fgorski@chromium.org jbudorick@chromium.org
diff --git a/third_party/grpc/BUILD.gn b/third_party/grpc/BUILD.gn index 217793d0..a7583bf 100644 --- a/third_party/grpc/BUILD.gn +++ b/third_party/grpc/BUILD.gn
@@ -269,7 +269,6 @@ "src/src/core/lib/gpr/tmpfile_msys.cc", "src/src/core/lib/gpr/tmpfile_posix.cc", "src/src/core/lib/gpr/tmpfile_windows.cc", - "src/src/core/lib/gpr/wrap_memcpy.cc", "src/src/core/lib/gprpp/fork.cc", "src/src/core/lib/gprpp/thd_posix.cc", "src/src/core/lib/gprpp/thd_windows.cc", @@ -568,7 +567,9 @@ additional_configs = [ ":grpc_config", ":grpc_internal_config", + "//build/config/compiler:no_chromium_code", ] + suppressed_configs = [ "//build/config/compiler:chromium_code" ] seed_corpus = "src/test/core/security/corpus/alts_credentials_corpus" } @@ -584,7 +585,9 @@ additional_configs = [ ":grpc_config", ":grpc_internal_config", + "//build/config/compiler:no_chromium_code", ] + suppressed_configs = [ "//build/config/compiler:chromium_code" ] seed_corpus = "src/test/core/end2end/fuzzers/api_fuzzer_corpus" dict = "src/test/core/end2end/fuzzers/api_fuzzer.dictionary" } @@ -601,7 +604,9 @@ additional_configs = [ ":grpc_config", ":grpc_internal_config", + "//build/config/compiler:no_chromium_code", ] + suppressed_configs = [ "//build/config/compiler:chromium_code" ] seed_corpus = "src/test/core/end2end/fuzzers/client_fuzzer_corpus" dict = "src/test/core/end2end/fuzzers/hpack.dictionary" } @@ -618,7 +623,9 @@ additional_configs = [ ":grpc_config", ":grpc_internal_config", + "//build/config/compiler:no_chromium_code", ] + suppressed_configs = [ "//build/config/compiler:chromium_code" ] seed_corpus = "src/test/core/transport/chttp2/hpack_parser_corpus" } @@ -634,7 +641,9 @@ additional_configs = [ ":grpc_config", ":grpc_internal_config", + "//build/config/compiler:no_chromium_code", ] + suppressed_configs = [ "//build/config/compiler:chromium_code" ] seed_corpus = "src/test/core/http/request_corpus" } @@ -650,7 +659,9 @@ additional_configs = [ ":grpc_config", ":grpc_internal_config", + "//build/config/compiler:no_chromium_code", ] + suppressed_configs = [ "//build/config/compiler:chromium_code" ] seed_corpus = "src/test/core/http/response_corpus" } @@ -666,7 +677,9 @@ additional_configs = [ ":grpc_config", ":grpc_internal_config", + "//build/config/compiler:no_chromium_code", ] + suppressed_configs = [ "//build/config/compiler:chromium_code" ] seed_corpus = "src/test/core/json/corpus" } @@ -682,7 +695,9 @@ additional_configs = [ ":grpc_config", ":grpc_internal_config", + "//build/config/compiler:no_chromium_code", ] + suppressed_configs = [ "//build/config/compiler:chromium_code" ] seed_corpus = "src/test/core/nanopb/corpus_response" } @@ -698,7 +713,9 @@ additional_configs = [ ":grpc_config", ":grpc_internal_config", + "//build/config/compiler:no_chromium_code", ] + suppressed_configs = [ "//build/config/compiler:chromium_code" ] seed_corpus = "src/test/core/nanopb/corpus_serverlist" } @@ -714,7 +731,9 @@ additional_configs = [ ":grpc_config", ":grpc_internal_config", + "//build/config/compiler:no_chromium_code", ] + suppressed_configs = [ "//build/config/compiler:chromium_code" ] seed_corpus = "src/test/core/slice/percent_decode_corpus" } @@ -730,7 +749,9 @@ additional_configs = [ ":grpc_config", ":grpc_internal_config", + "//build/config/compiler:no_chromium_code", ] + suppressed_configs = [ "//build/config/compiler:chromium_code" ] seed_corpus = "src/test/core/slice/percent_encode_corpus" } @@ -746,7 +767,9 @@ additional_configs = [ ":grpc_config", ":grpc_internal_config", + "//build/config/compiler:no_chromium_code", ] + suppressed_configs = [ "//build/config/compiler:chromium_code" ] seed_corpus = "src/test/core/end2end/fuzzers/server_fuzzer_corpus" } @@ -762,7 +785,9 @@ additional_configs = [ ":grpc_config", ":grpc_internal_config", + "//build/config/compiler:no_chromium_code", ] + suppressed_configs = [ "//build/config/compiler:chromium_code" ] seed_corpus = "src/test/core/security/corpus/ssl_server_corpus" } @@ -778,6 +803,8 @@ additional_configs = [ ":grpc_config", ":grpc_internal_config", + "//build/config/compiler:no_chromium_code", ] + suppressed_configs = [ "//build/config/compiler:chromium_code" ] seed_corpus = "src/test/core/client_channel/uri_corpus" }
diff --git a/third_party/libaom/cmake_update.sh b/third_party/libaom/cmake_update.sh index c4a881f..c6c05ea 100755 --- a/third_party/libaom/cmake_update.sh +++ b/third_party/libaom/cmake_update.sh
@@ -127,6 +127,7 @@ reset_dirs linux/ia32 gen_config_files linux/ia32 "${toolchain}/x86-linux.cmake ${all_platforms} \ + -DCONFIG_PIC=1 \ -DAOM_RTCD_FLAGS=--require-mmx;--require-sse;--require-sse2" reset_dirs linux/x64
diff --git a/third_party/libaom/source/config/linux/ia32/config/aom_config.asm b/third_party/libaom/source/config/linux/ia32/config/aom_config.asm index 4076e8c5..3740e59 100644 --- a/third_party/libaom/source/config/linux/ia32/config/aom_config.asm +++ b/third_party/libaom/source/config/linux/ia32/config/aom_config.asm
@@ -35,7 +35,7 @@ %define CONFIG_NORMAL_TILE_MODE 1 %define CONFIG_ONE_PASS_SVM 0 %define CONFIG_OS_SUPPORT 1 -%define CONFIG_PIC 0 +%define CONFIG_PIC 1 %define CONFIG_RD_DEBUG 0 %define CONFIG_RUNTIME_CPU_DETECT 1 %define CONFIG_SHARED 0
diff --git a/third_party/libaom/source/config/linux/ia32/config/aom_config.c b/third_party/libaom/source/config/linux/ia32/config/aom_config.c index 64458d8..1a09cdbb 100644 --- a/third_party/libaom/source/config/linux/ia32/config/aom_config.c +++ b/third_party/libaom/source/config/linux/ia32/config/aom_config.c
@@ -9,5 +9,5 @@ * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include "aom/aom_codec.h" -static const char* const cfg = "cmake ../source/libaom -G \"Unix Makefiles\" -DCMAKE_TOOLCHAIN_FILE=\"../source/libaom/build/cmake/toolchains/x86-linux.cmake\" -DAOM_RTCD_FLAGS=--require-mmx;--require-sse;--require-sse2 -DCONFIG_AV1_ENCODER=0 -DCONFIG_LOWBITDEPTH=1 -DCONFIG_MAX_DECODE_PROFILE=0 -DCONFIG_NORMAL_TILE_MODE=1 -DCONFIG_SIZE_LIMIT=1 -DDECODE_HEIGHT_LIMIT=16384 -DDECODE_WIDTH_LIMIT=16384"; +static const char* const cfg = "cmake ../source/libaom -G \"Unix Makefiles\" -DCMAKE_TOOLCHAIN_FILE=\"../source/libaom/build/cmake/toolchains/x86-linux.cmake\" -DAOM_RTCD_FLAGS=--require-mmx;--require-sse;--require-sse2 -DCONFIG_AV1_ENCODER=0 -DCONFIG_PIC=1 -DCONFIG_LOWBITDEPTH=1 -DCONFIG_MAX_DECODE_PROFILE=0 -DCONFIG_NORMAL_TILE_MODE=1 -DCONFIG_SIZE_LIMIT=1 -DDECODE_HEIGHT_LIMIT=16384 -DDECODE_WIDTH_LIMIT=16384"; const char *aom_codec_build_config(void) {return cfg;}
diff --git a/third_party/libaom/source/config/linux/ia32/config/aom_config.h b/third_party/libaom/source/config/linux/ia32/config/aom_config.h index 9bf1f6fb..229cdf1 100644 --- a/third_party/libaom/source/config/linux/ia32/config/aom_config.h +++ b/third_party/libaom/source/config/linux/ia32/config/aom_config.h
@@ -47,7 +47,7 @@ #define CONFIG_NORMAL_TILE_MODE 1 #define CONFIG_ONE_PASS_SVM 0 #define CONFIG_OS_SUPPORT 1 -#define CONFIG_PIC 0 +#define CONFIG_PIC 1 #define CONFIG_RD_DEBUG 0 #define CONFIG_RUNTIME_CPU_DETECT 1 #define CONFIG_SHARED 0
diff --git a/third_party/libaom/source/config/win/ia32/config/aom_config.asm b/third_party/libaom/source/config/win/ia32/config/aom_config.asm index 762283c..c2ffac7 100644 --- a/third_party/libaom/source/config/win/ia32/config/aom_config.asm +++ b/third_party/libaom/source/config/win/ia32/config/aom_config.asm
@@ -35,7 +35,7 @@ %define CONFIG_NORMAL_TILE_MODE 1 %define CONFIG_ONE_PASS_SVM 0 %define CONFIG_OS_SUPPORT 1 -%define CONFIG_PIC 0 +%define CONFIG_PIC 1 %define CONFIG_RD_DEBUG 0 %define CONFIG_RUNTIME_CPU_DETECT 1 %define CONFIG_SHARED 0
diff --git a/third_party/libaom/source/config/win/ia32/config/aom_config.c b/third_party/libaom/source/config/win/ia32/config/aom_config.c index 64458d8..1a09cdbb 100644 --- a/third_party/libaom/source/config/win/ia32/config/aom_config.c +++ b/third_party/libaom/source/config/win/ia32/config/aom_config.c
@@ -9,5 +9,5 @@ * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include "aom/aom_codec.h" -static const char* const cfg = "cmake ../source/libaom -G \"Unix Makefiles\" -DCMAKE_TOOLCHAIN_FILE=\"../source/libaom/build/cmake/toolchains/x86-linux.cmake\" -DAOM_RTCD_FLAGS=--require-mmx;--require-sse;--require-sse2 -DCONFIG_AV1_ENCODER=0 -DCONFIG_LOWBITDEPTH=1 -DCONFIG_MAX_DECODE_PROFILE=0 -DCONFIG_NORMAL_TILE_MODE=1 -DCONFIG_SIZE_LIMIT=1 -DDECODE_HEIGHT_LIMIT=16384 -DDECODE_WIDTH_LIMIT=16384"; +static const char* const cfg = "cmake ../source/libaom -G \"Unix Makefiles\" -DCMAKE_TOOLCHAIN_FILE=\"../source/libaom/build/cmake/toolchains/x86-linux.cmake\" -DAOM_RTCD_FLAGS=--require-mmx;--require-sse;--require-sse2 -DCONFIG_AV1_ENCODER=0 -DCONFIG_PIC=1 -DCONFIG_LOWBITDEPTH=1 -DCONFIG_MAX_DECODE_PROFILE=0 -DCONFIG_NORMAL_TILE_MODE=1 -DCONFIG_SIZE_LIMIT=1 -DDECODE_HEIGHT_LIMIT=16384 -DDECODE_WIDTH_LIMIT=16384"; const char *aom_codec_build_config(void) {return cfg;}
diff --git a/third_party/libaom/source/config/win/ia32/config/aom_config.h b/third_party/libaom/source/config/win/ia32/config/aom_config.h index 7f1e956..dea81bc4 100644 --- a/third_party/libaom/source/config/win/ia32/config/aom_config.h +++ b/third_party/libaom/source/config/win/ia32/config/aom_config.h
@@ -47,7 +47,7 @@ #define CONFIG_NORMAL_TILE_MODE 1 #define CONFIG_ONE_PASS_SVM 0 #define CONFIG_OS_SUPPORT 1 -#define CONFIG_PIC 0 +#define CONFIG_PIC 1 #define CONFIG_RD_DEBUG 0 #define CONFIG_RUNTIME_CPU_DETECT 1 #define CONFIG_SHARED 0
diff --git a/third_party/libjingle_xmpp/xmpp/jid.h b/third_party/libjingle_xmpp/xmpp/jid.h index fb24426..bb77a6c 100644 --- a/third_party/libjingle_xmpp/xmpp/jid.h +++ b/third_party/libjingle_xmpp/xmpp/jid.h
@@ -50,8 +50,8 @@ bool operator==(const Jid& other) const; bool operator!=(const Jid& other) const { return !operator==(other); } - bool operator<(const Jid& other) const { return Compare(other) < 0; }; - bool operator>(const Jid& other) const { return Compare(other) > 0; }; + bool operator<(const Jid& other) const { return Compare(other) < 0; } + bool operator>(const Jid& other) const { return Compare(other) > 0; } int Compare(const Jid & other) const;
diff --git a/third_party/libvpx/README.chromium b/third_party/libvpx/README.chromium index 6bb4842..1c20d7a 100644 --- a/third_party/libvpx/README.chromium +++ b/third_party/libvpx/README.chromium
@@ -5,9 +5,9 @@ License File: source/libvpx/LICENSE Security Critical: yes -Date: Tuesday February 12 2019 +Date: Wednesday February 20 2019 Branch: master -Commit: e2381829e984c58e54a7ad0580c168cb7432ef92 +Commit: 986b2bef7f475543a441cf9aa5a3ca55dd57ccae Description: Contains the sources used to compile libvpx binaries used by Google Chrome and
diff --git a/third_party/libvpx/source/config/vpx_version.h b/third_party/libvpx/source/config/vpx_version.h index dff0bbf..13973ca 100644 --- a/third_party/libvpx/source/config/vpx_version.h +++ b/third_party/libvpx/source/config/vpx_version.h
@@ -2,7 +2,7 @@ #define VERSION_MAJOR 1 #define VERSION_MINOR 8 #define VERSION_PATCH 0 -#define VERSION_EXTRA "161-ge2381829e9" +#define VERSION_EXTRA "173-g986b2bef7f" #define VERSION_PACKED ((VERSION_MAJOR<<16)|(VERSION_MINOR<<8)|(VERSION_PATCH)) -#define VERSION_STRING_NOSP "v1.8.0-161-ge2381829e9" -#define VERSION_STRING " v1.8.0-161-ge2381829e9" +#define VERSION_STRING_NOSP "v1.8.0-173-g986b2bef7f" +#define VERSION_STRING " v1.8.0-173-g986b2bef7f"
diff --git a/third_party/libxml/README.chromium b/third_party/libxml/README.chromium index 8a8e6ce..c77276c 100644 --- a/third_party/libxml/README.chromium +++ b/third_party/libxml/README.chromium
@@ -1,6 +1,6 @@ Name: libxml URL: http://xmlsoft.org -Version: 7a1bd7f6497ac33a9023d556f6f47a48f01deac0 +Version: 6a6fb8560e75c3b9c15744ef20df9fce9fcd8c6e License: MIT License File: src/Copyright Security Critical: yes
diff --git a/third_party/libxml/chromium/roll.py b/third_party/libxml/chromium/roll.py index 704e207..5dadf62 100755 --- a/third_party/libxml/chromium/roll.py +++ b/third_party/libxml/chromium/roll.py
@@ -28,13 +28,10 @@ # Prerequisites: # # 1. Check out Chromium somewhere on Linux, Mac and Windows. -# 2. On each machine, add the experimental remote named 'wip': -# git remote add -f wip \ -# https://chromium.googlesource.com/experimental/chromium/src -# 3. On Linux: +# 2. On Linux: # a. sudo apt-get install libicu-dev -# b. git clone git://git.gnome.org/libxml2 somewhere -# 4. On Mac, install these MacPorts: +# b. git clone https://github.com/GNOME/libxml2.git somewhere +# 3. On Mac, install these MacPorts: # autoconf automake libtool pkgconfig icu # # Procedure: @@ -54,22 +51,19 @@ # head; modify the patch files, this script, and # README.chromium; then commit the result and run it again. # -# b. git push -f wip HEAD:refs/wip/$USER/roll_libxml +# b. Upload a CL, but do not Start Review. # # 2. On Windows, in the Chromium src directory: -# a. git fetch wip refs/wip/$USER/roll_libxml -# b. git checkout FETCH_HEAD -# c. third_party\libxml\chromium\roll.py --win32 -# d. git push -f wip HEAD:refs/wip/$USER/roll_libxml +# a. git cl patch <Gerrit Issue ID> +# b. third_party\libxml\chromium\roll.py --win32 +# c. git cl upload # # 3. On Mac, in the Chromium src directory: -# a. git fetch wip refs/wip/$USER/roll_libxml -# b. git checkout -b roll_libxml_nnnn FETCH_HEAD -# c. git branch --set-upstream-to origin/master -# d. third_party/libxml/chromium/roll.py --mac -# e. Make and commit any final changes to README.chromium, BUILD.gn, etc. -# f. Complete the code review process as usual: git cl upload -d; -# git cl try-results; etc. +# a. git cl patch <Gerrit Issue ID> +# b. third_party/libxml/chromium/roll.py --mac +# c. Make and commit any final changes to README.chromium, BUILD.gn, etc. +# d. git cl upload +# e. Complete the review as usual PATCHES = [ 'chromium-issue-599427.patch',
diff --git a/third_party/libxml/linux/config.h b/third_party/libxml/linux/config.h index a39eb31..7d273f6 100644 --- a/third_party/libxml/linux/config.h +++ b/third_party/libxml/linux/config.h
@@ -267,7 +267,7 @@ #define VA_LIST_IS_ARRAY 1 /* Version number of package */ -#define VERSION "2.9.8" +#define VERSION "2.9.9" /* Determine what socket length (socklen_t) data type is */ #define XML_SOCKLEN_T socklen_t
diff --git a/third_party/libxml/linux/include/libxml/xmlversion.h b/third_party/libxml/linux/include/libxml/xmlversion.h index d20bb87..59cc485 100644 --- a/third_party/libxml/linux/include/libxml/xmlversion.h +++ b/third_party/libxml/linux/include/libxml/xmlversion.h
@@ -29,21 +29,21 @@ * * the version string like "1.2.3" */ -#define LIBXML_DOTTED_VERSION "2.9.8" +#define LIBXML_DOTTED_VERSION "2.9.9" /** * LIBXML_VERSION: * * the version number: 1.2.3 value is 10203 */ -#define LIBXML_VERSION 20908 +#define LIBXML_VERSION 20909 /** * LIBXML_VERSION_STRING: * * the version number string, 1.2.3 value is "10203" */ -#define LIBXML_VERSION_STRING "20908" +#define LIBXML_VERSION_STRING "20909" /** * LIBXML_VERSION_EXTRA: @@ -58,7 +58,7 @@ * Macro to check that the libxml version in use is compatible with * the version the software has been compiled against */ -#define LIBXML_TEST_VERSION xmlCheckVersion(20908); +#define LIBXML_TEST_VERSION xmlCheckVersion(20909); #ifndef VMS #if 0 @@ -291,7 +291,7 @@ * * Whether ISO-8859-* support is made available in case iconv is not */ -#if 1 +#if 0 #define LIBXML_ISO8859X_ENABLED #endif
diff --git a/third_party/libxml/linux/xml2-config b/third_party/libxml/linux/xml2-config index 9e140ed..9ae2109 100755 --- a/third_party/libxml/linux/xml2-config +++ b/third_party/libxml/linux/xml2-config
@@ -58,7 +58,7 @@ ;; --version) - echo 2.9.8 + echo 2.9.9 exit 0 ;;
diff --git a/third_party/libxml/mac/config.h b/third_party/libxml/mac/config.h index 78a0a26..047e066 100644 --- a/third_party/libxml/mac/config.h +++ b/third_party/libxml/mac/config.h
@@ -267,7 +267,7 @@ #define VA_LIST_IS_ARRAY 1 /* Version number of package */ -#define VERSION "2.9.8" +#define VERSION "2.9.9" /* Determine what socket length (socklen_t) data type is */ #define XML_SOCKLEN_T socklen_t
diff --git a/third_party/libxml/mac/include/libxml/xmlversion.h b/third_party/libxml/mac/include/libxml/xmlversion.h index d20bb87..59cc485 100644 --- a/third_party/libxml/mac/include/libxml/xmlversion.h +++ b/third_party/libxml/mac/include/libxml/xmlversion.h
@@ -29,21 +29,21 @@ * * the version string like "1.2.3" */ -#define LIBXML_DOTTED_VERSION "2.9.8" +#define LIBXML_DOTTED_VERSION "2.9.9" /** * LIBXML_VERSION: * * the version number: 1.2.3 value is 10203 */ -#define LIBXML_VERSION 20908 +#define LIBXML_VERSION 20909 /** * LIBXML_VERSION_STRING: * * the version number string, 1.2.3 value is "10203" */ -#define LIBXML_VERSION_STRING "20908" +#define LIBXML_VERSION_STRING "20909" /** * LIBXML_VERSION_EXTRA: @@ -58,7 +58,7 @@ * Macro to check that the libxml version in use is compatible with * the version the software has been compiled against */ -#define LIBXML_TEST_VERSION xmlCheckVersion(20908); +#define LIBXML_TEST_VERSION xmlCheckVersion(20909); #ifndef VMS #if 0 @@ -291,7 +291,7 @@ * * Whether ISO-8859-* support is made available in case iconv is not */ -#if 1 +#if 0 #define LIBXML_ISO8859X_ENABLED #endif
diff --git a/third_party/libxml/src/HTMLparser.c b/third_party/libxml/src/HTMLparser.c index 7e243e6..9e60e27e 100644 --- a/third_party/libxml/src/HTMLparser.c +++ b/third_party/libxml/src/HTMLparser.c
@@ -1084,7 +1084,7 @@ "menu", "p", "head", "ul", NULL, "p", "p", "head", "h1", "h2", "h3", "h4", "h5", "h6", FONTSTYLE, NULL, "div", "p", "head", NULL, -"noscript", "p", NULL, +"noscript", "script", NULL, "center", "font", "b", "i", "p", "head", NULL, "a", "a", "head", NULL, "caption", "p", NULL, @@ -3636,12 +3636,12 @@ processed = ctxt->input->cur - ctxt->input->base; xmlBufShrink(ctxt->input->buf->buffer, processed); nbchars = xmlCharEncInput(ctxt->input->buf, 1); + xmlBufResetInput(ctxt->input->buf->buffer, ctxt->input); if (nbchars < 0) { htmlParseErr(ctxt, XML_ERR_INVALID_ENCODING, "htmlCheckEncoding: encoder error\n", NULL, NULL); } - xmlBufResetInput(ctxt->input->buf->buffer, ctxt->input); } } }
diff --git a/third_party/libxml/src/HTMLtree.c b/third_party/libxml/src/HTMLtree.c index 2fd0c9c5..21cfcfe5 100644 --- a/third_party/libxml/src/HTMLtree.c +++ b/third_party/libxml/src/HTMLtree.c
@@ -502,17 +502,17 @@ if (handler == NULL) htmlSaveErr(XML_SAVE_UNKNOWN_ENCODING, NULL, encoding); } + } else { + /* + * Fallback to HTML or ASCII when the encoding is unspecified + */ + if (handler == NULL) + handler = xmlFindCharEncodingHandler("HTML"); + if (handler == NULL) + handler = xmlFindCharEncodingHandler("ascii"); } /* - * Fallback to HTML or ASCII when the encoding is unspecified - */ - if (handler == NULL) - handler = xmlFindCharEncodingHandler("HTML"); - if (handler == NULL) - handler = xmlFindCharEncodingHandler("ascii"); - - /* * save the content to a temp buffer. */ buf = xmlOutputBufferCreateFile(out, handler); @@ -570,33 +570,22 @@ xmlCharEncoding enc; enc = xmlParseCharEncoding(encoding); - if (enc != cur->charset) { - if (cur->charset != XML_CHAR_ENCODING_UTF8) { - /* - * Not supported yet - */ - *mem = NULL; - *size = 0; - return; - } - + if (enc != XML_CHAR_ENCODING_UTF8) { handler = xmlFindCharEncodingHandler(encoding); if (handler == NULL) htmlSaveErr(XML_SAVE_UNKNOWN_ENCODING, NULL, encoding); - } else { - handler = xmlFindCharEncodingHandler(encoding); } + } else { + /* + * Fallback to HTML or ASCII when the encoding is unspecified + */ + if (handler == NULL) + handler = xmlFindCharEncodingHandler("HTML"); + if (handler == NULL) + handler = xmlFindCharEncodingHandler("ascii"); } - /* - * Fallback to HTML or ASCII when the encoding is unspecified - */ - if (handler == NULL) - handler = xmlFindCharEncodingHandler("HTML"); - if (handler == NULL) - handler = xmlFindCharEncodingHandler("ascii"); - buf = xmlAllocOutputBufferInternal(handler); if (buf == NULL) { *mem = NULL; @@ -1101,30 +1090,21 @@ xmlCharEncoding enc; enc = xmlParseCharEncoding(encoding); - if (enc != cur->charset) { - if (cur->charset != XML_CHAR_ENCODING_UTF8) { - /* - * Not supported yet - */ - return(-1); - } - + if (enc != XML_CHAR_ENCODING_UTF8) { handler = xmlFindCharEncodingHandler(encoding); if (handler == NULL) htmlSaveErr(XML_SAVE_UNKNOWN_ENCODING, NULL, encoding); - } else { - handler = xmlFindCharEncodingHandler(encoding); } + } else { + /* + * Fallback to HTML or ASCII when the encoding is unspecified + */ + if (handler == NULL) + handler = xmlFindCharEncodingHandler("HTML"); + if (handler == NULL) + handler = xmlFindCharEncodingHandler("ascii"); } - /* - * Fallback to HTML or ASCII when the encoding is unspecified - */ - if (handler == NULL) - handler = xmlFindCharEncodingHandler("HTML"); - if (handler == NULL) - handler = xmlFindCharEncodingHandler("ascii"); - buf = xmlOutputBufferCreateFile(f, handler); if (buf == NULL) return(-1); htmlDocContentDumpOutput(buf, cur, NULL); @@ -1160,29 +1140,22 @@ xmlCharEncoding enc; enc = xmlParseCharEncoding(encoding); - if (enc != cur->charset) { - if (cur->charset != XML_CHAR_ENCODING_UTF8) { - /* - * Not supported yet - */ - return(-1); - } - + if (enc != XML_CHAR_ENCODING_UTF8) { handler = xmlFindCharEncodingHandler(encoding); if (handler == NULL) htmlSaveErr(XML_SAVE_UNKNOWN_ENCODING, NULL, encoding); } + } else { + /* + * Fallback to HTML or ASCII when the encoding is unspecified + */ + if (handler == NULL) + handler = xmlFindCharEncodingHandler("HTML"); + if (handler == NULL) + handler = xmlFindCharEncodingHandler("ascii"); } /* - * Fallback to HTML or ASCII when the encoding is unspecified - */ - if (handler == NULL) - handler = xmlFindCharEncodingHandler("HTML"); - if (handler == NULL) - handler = xmlFindCharEncodingHandler("ascii"); - - /* * save the content to a temp buffer. */ buf = xmlOutputBufferCreateFilename(filename, handler, cur->compression); @@ -1221,14 +1194,7 @@ xmlCharEncoding enc; enc = xmlParseCharEncoding(encoding); - if (enc != cur->charset) { - if (cur->charset != XML_CHAR_ENCODING_UTF8) { - /* - * Not supported yet - */ - return(-1); - } - + if (enc != XML_CHAR_ENCODING_UTF8) { handler = xmlFindCharEncodingHandler(encoding); if (handler == NULL) htmlSaveErr(XML_SAVE_UNKNOWN_ENCODING, NULL, encoding); @@ -1236,15 +1202,15 @@ htmlSetMetaEncoding(cur, (const xmlChar *) encoding); } else { htmlSetMetaEncoding(cur, (const xmlChar *) "UTF-8"); - } - /* - * Fallback to HTML or ASCII when the encoding is unspecified - */ - if (handler == NULL) - handler = xmlFindCharEncodingHandler("HTML"); - if (handler == NULL) - handler = xmlFindCharEncodingHandler("ascii"); + /* + * Fallback to HTML or ASCII when the encoding is unspecified + */ + if (handler == NULL) + handler = xmlFindCharEncodingHandler("HTML"); + if (handler == NULL) + handler = xmlFindCharEncodingHandler("ascii"); + } /* * save the content to a temp buffer.
diff --git a/third_party/libxml/src/Makefile.am b/third_party/libxml/src/Makefile.am index 9c630be4..174b984 100644 --- a/third_party/libxml/src/Makefile.am +++ b/third_party/libxml/src/Makefile.am
@@ -126,11 +126,7 @@ testC14N_DEPENDENCIES = $(DEPS) testC14N_LDADD= $(LDADDS) -if THREADS_W32 -testThreads_SOURCES = testThreadsWin32.c -else testThreads_SOURCES = testThreads.c -endif testThreads_LDFLAGS = testThreads_DEPENDENCIES = $(DEPS) testThreads_LDADD= $(BASE_THREAD_LIBS) $(LDADDS) @@ -1253,7 +1249,7 @@ libxml2-config.cmake.in autogen.sh \ trionan.c trionan.h triostr.c triostr.h trio.c trio.h \ triop.h triodef.h libxml.h elfgcchack.h xzlib.h buf.h \ - enc.h save.h testThreadsWin32.c genUnicode.py TODO_SCHEMAS \ + enc.h save.h genUnicode.py TODO_SCHEMAS \ dbgen.pl dbgenattr.pl regressions.py regressions.xml \ README.tests Makefile.tests libxml2.syms timsort.h \ README.zOS \
diff --git a/third_party/libxml/src/NEWS b/third_party/libxml/src/NEWS index d248c69..5504bed 100644 --- a/third_party/libxml/src/NEWS +++ b/third_party/libxml/src/NEWS
@@ -8,8 +8,451 @@ ChangeLog.html describes the recents commits to the GIT at -http://git.gnome.org/browse/libxml2/ +https://gitlab.gnome.org/GNOME/libxml2 code base.Here is the list of public releases: +v2.9.9: Jan 03 2019: + - Security: + CVE-2018-9251 CVE-2018-14567 Fix infinite loop in LZMA decompression (Nick Wellnhofer), + CVE-2018-14404 Fix nullptr deref with XPath logic ops (Nick Wellnhofer), + + - Documentation: + reader: Fix documentation comment (Mohammed Sadiq) + + - Portability: + Fix MSVC build with lzma (Nick Wellnhofer), + Variables need 'extern' in static lib on Cygwin (Michael Haubenwallner), + Really declare dllexport/dllimport for Cygwin (Michael Haubenwallner), + Merge branch 'patch-2' into 'master' (Nick Wellnhofer), + Change dir to $THEDIR after ACLOCAL_PATH check autoreconf creates aclocal.m4 in $srcdir (Vitaly Buka), + Improve error message if pkg.m4 couldn't be found (Nick Wellnhofer), + NaN and Inf fixes for pre-C99 compilers (Nick Wellnhofer) + + - Bug Fixes: + Revert "Support xmlTextReaderNextSibling w/o preparsed doc" (Nick Wellnhofer), + Fix building relative URIs (Thomas Holder), + Problem with data in interleave in RelaxNG validation (Nikolai Weibull), + Fix memory leak in xmlSwitchInputEncodingInt error path (Nick Wellnhofer), + Set doc on element obtained from freeElems (Nick Wellnhofer), + Fix HTML serialization with UTF-8 encoding (Nick Wellnhofer), + Use actual doc in xmlTextReaderRead*Xml (Nick Wellnhofer), + Unlink node before freeing it in xmlSAX2StartElement (Nick Wellnhofer), + Check return value of nodePush in xmlSAX2StartElement (Nick Wellnhofer), + Free input buffer in xmlHaltParser (Nick Wellnhofer), + Reset HTML parser input pointers on encoding failure (Nick Wellnhofer), + Don't run icu_parse_test if EUC-JP is unsupported (Nick Wellnhofer), + Fix xmlSchemaValidCtxtPtr reuse memory leak (Greg Hildstrom), + Fix xmlTextReaderNext with preparsed document (Felix Bünemann), + Remove stray character from comment (Nick Wellnhofer), + Remove a misleading line from xmlCharEncOutput (Andrey Bienkowski), + HTML noscript should not close p (Daniel Veillard), + Don't change context node in xmlXPathRoot (Nick Wellnhofer), + Stop using XPATH_OP_RESET (Nick Wellnhofer), + Revert "Change calls to xmlCharEncInput to set flush false" (Nick Wellnhofer) + + - Improvements: + Fix "Problem with data in interleave in RelaxNG validation" (Nikolai Weibull), + cleanup: remove some unreachable code (Thomas Holder), + add --relative to testURI (Thomas Holder), + Remove redefined starts and defines inside include elements (Nikolai Weibull), + Allow choice within choice in nameClass in RELAX NG (Nikolai Weibull), + Look inside divs for starts and defines inside include (Nikolai Weibull), + Add compile and libxml2-config.cmake to .gitignore (Nikolai Weibull), + Stop using doc->charset outside parser code (Nick Wellnhofer), + Add newlines to 'xmllint --xpath' output (Nick Wellnhofer), + Don't include SAX.h from globals.h (Nick Wellnhofer), + Support xmlTextReaderNextSibling w/o preparsed doc (Felix Bünemann), + Don't instruct user to run make when autogen.sh failed (林博仁(Buo-ren Lin)), + Run Travis ASan tests with "sudo: required" (Nick Wellnhofer), + Improve restoring of context size and position (Nick Wellnhofer), + Simplify and harden nodeset filtering (Nick Wellnhofer), + Avoid unnecessary backups of the context node (Nick Wellnhofer), + Fix inconsistency in xmlXPathIsInf (Nick Wellnhofer) + + - Cleanups: + + + +v2.9.8: Mar 05 2018: + - Portability: + python: remove single use of _PyVerify_fd (Patrick Welche), + Build more test executables on Windows/MSVC (Nick Wellnhofer), + Stop including ansidecl.h (Nick Wellnhofer), + Fix libz and liblzma detection (Nick Wellnhofer), + Revert "Compile testapi with -Wno-unused-function" (Nick Wellnhofer) + + - Bug Fixes: + Fix xmlParserEntityCheck (Nick Wellnhofer), + Halt parser in case of encoding error (Nick Wellnhofer), + Clear entity content in case of errors (Nick Wellnhofer), + Change calls to xmlCharEncInput to set flush false when not final call. Having flush incorrectly set to true causes errors for ICU. (Joel Hockey), + Fix buffer over-read in xmlParseNCNameComplex (Nick Wellnhofer), + Fix ICU library filenames on Windows/MSVC (Nick Wellnhofer), + Fix xmlXPathIsNaN broken by recent commit (Nick Wellnhofer), + Fix -Wenum-compare warnings (Nick Wellnhofer), + Fix callback signature in testapi.c (Nick Wellnhofer), + Fix unused parameter warning without ICU (Nick Wellnhofer), + Fix IO callback signatures (Nick Wellnhofer), + Fix misc callback signatures (Nick Wellnhofer), + Fix list callback signatures (Nick Wellnhofer), + Fix hash callback signatures (Nick Wellnhofer), + Refactor name and type signature for xmlNop (Vlad Tsyrklevich), + Fixed ICU to set flush correctly and provide pivot buffer. (Joel Hockey), + Skip EBCDIC tests if EBCDIC isn't supported (Nick Wellnhofer) + + - Improvements: + Disable pointer-overflow UBSan checks under Travis (Nick Wellnhofer), + Improve handling of context input_id (Daniel Veillard), + Add resource file to Windows DLL (ccpaging), + Run Travis tests with -Werror (Nick Wellnhofer), + Build with "-Wall -Wextra" (Nick Wellnhofer), + Fix -Wtautological-pointer-compare warnings (Nick Wellnhofer), + Remove unused AC_CHECKs (Nick Wellnhofer), + Update information about contributing (Nick Wellnhofer), + Fix -Wmisleading-indentation warnings (Nick Wellnhofer), + Don't touch CFLAGS in configure.ac (Nick Wellnhofer), + Ignore function pointer cast warnings (Nick Wellnhofer), + Simplify XPath NaN, inf and -0 handling (Nick Wellnhofer), + Introduce xmlPosixStrdup and update xmlMemStrdup (Nick Wellnhofer), + Add test for ICU flush and pivot buffer (Nick Wellnhofer), + Compile testapi with -Wno-unused-function (Nick Wellnhofer) + + + +2.9.7: Nov 02 2017: + - Documentation: + xmlcatalog: refresh man page wrt. quering system catalog easily (Jan Pokorný) + + - Portability: + Fix deprecated Travis compiler flag (Nick Wellnhofer), + Add declaration for DllMain (J. Peter Mugaas), + Fix preprocessor conditional in threads.h (J. Peter Mugaas), + Fix pointer comparison warnings on 64-bit Windows (J. Peter Mugaas), + Fix macro redefinition warning (J. Peter Mugaas), + Default to native threads on MinGW-w64 (Nick Wellnhofer), + Simplify Windows IO functions (Nick Wellnhofer), + Fix runtest on Windows (Nick Wellnhofer), + socklen_t is always int on Windows (Nick Wellnhofer), + Don't redefine socket error codes on Windows (Nick Wellnhofer), + Fix pointer/int cast warnings on 64-bit Windows (Nick Wellnhofer), + Fix Windows compiler warnings in xmlCanonicPath (Nick Wellnhofer) + + - Bug Fixes: + xmlcatalog: restore ability to query system catalog easily (Jan Pokorný), + Fix comparison of nodesets to strings (Nick Wellnhofer) + + - Improvements: + Add Makefile rules to rebuild HTML man pages (Nick Wellnhofer), + Fix mixed decls and code in timsort.h (Nick Wellnhofer), + Rework handling of return values in thread tests (Nick Wellnhofer), + Fix unused variable warnings in testrecurse (Nick Wellnhofer), + Fix -Wimplicit-fallthrough warnings (J. Peter Mugaas), + Upgrade timsort.h to latest revision (Nick Wellnhofer), + Increase warning level to /W3 under MSVC (Nick Wellnhofer), + Fix a couple of warnings in dict.c and threads.c (Nick Wellnhofer), + Update .gitignore for Windows (Nick Wellnhofer), + Fix unused variable warnings in nanohttp.c (Nick Wellnhofer), + Fix the Windows header mess (Nick Wellnhofer), + Don't include winsock2.h in xmllint.c (Nick Wellnhofer), + Remove generated file python/setup.py from version control (Nick Wellnhofer), + Use __linux__ macro in generated code (Nick Wellnhofer) + + + +v2.9.6: Oct 06 2017: + - Portability: + Change preprocessor OS tests to __linux__ (Nick Wellnhofer) + + - Bug Fixes: + Fix XPath stack frame logic (Nick Wellnhofer), + Report undefined XPath variable error message (Nick Wellnhofer), + Fix regression with librsvg (Nick Wellnhofer), + Handle more invalid entity values in recovery mode (Nick Wellnhofer), + Fix structured validation errors (Nick Wellnhofer), + Fix memory leak in LZMA decompressor (Nick Wellnhofer), + Set memory limit for LZMA decompression (Nick Wellnhofer), + Handle illegal entity values in recovery mode (Nick Wellnhofer), + Fix debug dump of streaming XPath expressions (Nick Wellnhofer), + Fix memory leak in nanoftp (Nick Wellnhofer), + Fix memory leaks in SAX1 parser (Nick Wellnhofer) + + + +v2.9.5: Sep 04 2017: + - Security: + Detect infinite recursion in parameter entities (Nick Wellnhofer), + Fix handling of parameter-entity references (Nick Wellnhofer), + Disallow namespace nodes in XPointer ranges (Nick Wellnhofer), + Fix XPointer paths beginning with range-to (Nick Wellnhofer) + + - Documentation: + Documentation fixes (Nick Wellnhofer), + Spelling and grammar fixes (Nick Wellnhofer) + + - Portability: + Adding README.zOS to list of extra files for the release (Daniel Veillard), + Description of work needed to compile on zOS (Stéphane Michaut), + Porting libxml2 on zOS encoding of code (Stéphane Michaut), + small changes for OS/400 (Patrick Monnerat), + relaxng.c, xmlschemas.c: Fix build on pre-C99 compilers (Chun-wei Fan) + + - Bug Fixes: + Problem resolving relative URIs (Daniel Veillard), + Fix unwanted warnings when switching encodings (Nick Wellnhofer), + Fix signature of xmlSchemaAugmentImportedIDC (Daniel Veillard), + Heap-buffer-overflow read of size 1 in xmlFAParsePosCharGroup (David Kilzer), + Fix NULL pointer deref in xmlFAParseCharClassEsc (Nick Wellnhofer), + Fix infinite loops with push parser in recovery mode (Nick Wellnhofer), + Send xmllint usage error to stderr (Nick Wellnhofer), + Fix NULL deref in xmlParseExternalEntityPrivate (Nick Wellnhofer), + Make sure not to call IS_BLANK_CH when parsing the DTD (Nick Wellnhofer), + Fix xmlHaltParser (Nick Wellnhofer), + Fix pathological performance when outputting charrefs (Nick Wellnhofer), + Fix invalid-source-encoding warnings in testWriter.c (Nick Wellnhofer), + Fix duplicate SAX callbacks for entity content (David Kilzer), + Treat URIs with scheme as absolute in C14N (Nick Wellnhofer), + Fix copy-paste errors in error messages (Nick Wellnhofer), + Fix sanity check in htmlParseNameComplex (Nick Wellnhofer), + Fix potential infinite loop in xmlStringLenDecodeEntities (Nick Wellnhofer), + Reset parser input pointers on encoding failure (Nick Wellnhofer), + Fix memory leak in xmlParseEntityDecl error path (Nick Wellnhofer), + Fix xmlBuildRelativeURI for URIs starting with './' (Nick Wellnhofer), + Fix type confusion in xmlValidateOneNamespace (Nick Wellnhofer), + Fix memory leak in xmlStringLenGetNodeList (Nick Wellnhofer), + Fix NULL pointer deref in xmlDumpElementContent (Daniel Veillard), + Fix memory leak in xmlBufAttrSerializeTxtContent (Nick Wellnhofer), + Stop parser on unsupported encodings (Nick Wellnhofer), + Check for integer overflow in memory debug code (Nick Wellnhofer), + Fix buffer size checks in xmlSnprintfElementContent (Nick Wellnhofer), + Avoid reparsing in xmlParseStartTag2 (Nick Wellnhofer), + Fix undefined behavior in xmlRegExecPushStringInternal (Nick Wellnhofer), + Check XPath exponents for overflow (Nick Wellnhofer), + Check for overflow in xmlXPathIsPositionalPredicate (Nick Wellnhofer), + Fix spurious error message (Nick Wellnhofer), + Fix memory leak in xmlCanonicPath (Nick Wellnhofer), + Fix memory leak in xmlXPathCompareNodeSetValue (Nick Wellnhofer), + Fix memory leak in pattern error path (Nick Wellnhofer), + Fix memory leak in parser error path (Nick Wellnhofer), + Fix memory leaks in XPointer error paths (Nick Wellnhofer), + Fix memory leak in xmlXPathNodeSetMergeAndClear (Nick Wellnhofer), + Fix memory leak in XPath filter optimizations (Nick Wellnhofer), + Fix memory leaks in XPath error paths (Nick Wellnhofer), + Do not leak the new CData node if adding fails (David Tardon), + Prevent unwanted external entity reference (Neel Mehta), + Increase buffer space for port in HTTP redirect support (Daniel Veillard), + Fix more NULL pointer derefs in xpointer.c (Nick Wellnhofer), + Avoid function/data pointer conversion in xpath.c (Nick Wellnhofer), + Fix format string warnings (Nick Wellnhofer), + Disallow namespace nodes in XPointer points (Nick Wellnhofer), + Fix comparison with root node in xmlXPathCmpNodes (Nick Wellnhofer), + Fix attribute decoding during XML schema validation (Alex Henrie), + Fix NULL pointer deref in XPointer range-to (Nick Wellnhofer) + + - Improvements: + Updating the spec file to reflect Fedora 24 (Daniel Veillard), + Add const in five places to move 1 KiB to .rdata (Bruce Dawson), + Fix missing part of comment for function xmlXPathEvalExpression() (Daniel Veillard), + Get rid of "blanks wrapper" for parameter entities (Nick Wellnhofer), + Simplify handling of parameter entity references (Nick Wellnhofer), + Deduplicate code in encoding.c (Nick Wellnhofer), + Make HTML parser functions take const pointers (Nick Wellnhofer), + Build test programs only when needed (Nick Wellnhofer), + Fix doc/examples/index.py (Nick Wellnhofer), + Fix compiler warnings in threads.c (Nick Wellnhofer), + Fix empty-body warning in nanohttp.c (Nick Wellnhofer), + Fix cast-align warnings (Nick Wellnhofer), + Fix unused-parameter warnings (Nick Wellnhofer), + Rework entity boundary checks (Nick Wellnhofer), + Don't switch encoding for internal parameter entities (Nick Wellnhofer), + Merge duplicate code paths handling PE references (Nick Wellnhofer), + Test SAX2 callbacks with entity substitution (Nick Wellnhofer), + Support catalog and threads tests under --without-sax1 (Nick Wellnhofer), + Misc fixes for 'make tests' (Nick Wellnhofer), + Initialize keepBlanks in HTML parser (Nick Wellnhofer), + Add test cases for bug 758518 (David Kilzer), + Fix compiler warning in htmlParseElementInternal (Nick Wellnhofer), + Remove useless check in xmlParseAttributeListDecl (Nick Wellnhofer), + Allow zero sized memory input buffers (Nick Wellnhofer), + Add TODO comment in xmlSwitchEncoding (Nick Wellnhofer), + Check for integer overflow in xmlXPathFormatNumber (Nick Wellnhofer), + Make Travis print UBSan stacktraces (Nick Wellnhofer), + Add .travis.yml (Nick Wellnhofer), + Fix expected error output in Python tests (Nick Wellnhofer), + Simplify control flow in xmlParseStartTag2 (Nick Wellnhofer), + Disable LeakSanitizer when running API tests (Nick Wellnhofer), + Avoid out-of-bound array access in API tests (Nick Wellnhofer), + Avoid spurious UBSan errors in parser.c (Nick Wellnhofer), + Parse small XPath numbers more accurately (Nick Wellnhofer), + Rework XPath rounding functions (Nick Wellnhofer), + Fix white space in test output (Nick Wellnhofer), + Fix axis traversal from attribute and namespace nodes (Nick Wellnhofer), + Check for trailing characters in XPath expressions earlier (Nick Wellnhofer), + Rework final handling of XPath results (Nick Wellnhofer), + Make xmlXPathEvalExpression call xmlXPathEval (Nick Wellnhofer), + Remove unused variables (Nick Wellnhofer), + Don't print generic error messages in XPath tests (Nick Wellnhofer) + + - Cleanups: + Fix a couple of misleading indentation errors (Daniel Veillard), + Remove unnecessary calls to xmlPopInput (Nick Wellnhofer) + + + +2.9.4: May 23 2016: + - Security: + More format string warnings with possible format string vulnerability (David Kilzer), + Avoid building recursive entities (Daniel Veillard), + Heap-based buffer overread in htmlCurrentChar (Pranjal Jumde), + Heap-based buffer-underreads due to xmlParseName (David Kilzer), + Heap use-after-free in xmlSAX2AttributeNs (Pranjal Jumde), + Heap use-after-free in htmlParsePubidLiteral and htmlParseSystemiteral (Pranjal Jumde), + Fix some format string warnings with possible format string vulnerability (David Kilzer), + Detect change of encoding when parsing HTML names (Hugh Davenport), + Fix inappropriate fetch of entities content (Daniel Veillard), + Bug 759398: Heap use-after-free in xmlDictComputeFastKey <https://bugzilla.gnome.org/show_bug.cgi?id=759398> (Pranjal Jumde), + Bug 758605: Heap-based buffer overread in xmlDictAddString <https://bugzilla.gnome.org/show_bug.cgi?id=758605> (Pranjal Jumde), + Bug 758588: Heap-based buffer overread in xmlParserPrintFileContextInternal <https://bugzilla.gnome.org/show_bug.cgi?id=758588> (David Kilzer), + Bug 757711: heap-buffer-overflow in xmlFAParsePosCharGroup <https://bugzilla.gnome.org/show_bug.cgi?id=757711> (Pranjal Jumde), + Add missing increments of recursion depth counter to XML parser. (Peter Simons) + + - Documentation: + Fix typo: s{ ec -> cr }cipt (Jan Pokorný), + Fix typos: dictio{ nn -> n }ar{y,ies} (Jan Pokorný), + Fix typos: PATH_{ SEAPARATOR -> SEPARATOR } (Jan Pokorný), + Correct a typo. (Shlomi Fish) + + - Portability: + Correct the usage of LDFLAGS (Mattias Hansson), + Revert the use of SAVE_LDFLAGS in configure.ac (Mattias Hansson), + libxml2 hardcodes -L/lib in zlib/lzma tests which breaks cross-compiles (Mike Frysinger), + Fix apibuild for a recently added construct (Daniel Veillard), + Use pkg-config to locate zlib when possible (Stewart Brodie), + Use pkg-config to locate ICU when possible (Stewart Brodie), + Portability to non C99 compliant compilers (Patrick Monnerat), + dict.h: Move xmlDictPtr definition before includes to allow direct inclusion. (Patrick Monnerat), + os400: tell about xmllint and xmlcatalog in README400. (Patrick Monnerat), + os400: properly process SGML add in XMLCATALOG command. (Patrick Monnerat), + os400: implement CL command XMLCATALOG. (Patrick Monnerat), + os400: compile and install program xmlcatalog (qshell-only). (Patrick Monnerat), + os400: expand tabs in sources, strip trailing blanks. (Patrick Monnerat), + os400: implement CL command XMLLINT. (Patrick Monnerat), + os400: compile and install program xmllint (qshell-only). (Patrick Monnerat), + os400: initscript make_module(): Use options instead of positional parameters. (Patrick Monnerat), + os400: c14n.rpgle: allow *omit for nullable reference parameters. (Patrick Monnerat), + os400: use like() for double type. (Patrick Monnerat), + os400: use like() for int type. (Patrick Monnerat), + os400: use like() for unsigned int type. (Patrick Monnerat), + os400: use like() for enum types. (Patrick Monnerat), + Add xz to xml2-config --libs output (Baruch Siach), + Bug 760190: configure.ac should be able to build --with-icu without icu-config tool <https://bugzilla.gnome.org/show_bug.cgi?id=760190> (David Kilzer), + win32\VC10\config.h and VS 2015 (Bruce Dawson), + Add configure maintainer mode (orzen) + + - Bug Fixes: + Avoid an out of bound access when serializing malformed strings (Daniel Veillard), + Unsigned addition may overflow in xmlMallocAtomicLoc() (David Kilzer), + Integer signed/unsigned type mismatch in xmlParserInputGrow() (David Kilzer), + Bug 763071: heap-buffer-overflow in xmlStrncat <https://bugzilla.gnome.org/show_bug.cgi?id=763071> (Pranjal Jumde), + Integer overflow parsing port number in URI (Michael Paddon), + Fix an error with regexp on nullable counted char transition (Daniel Veillard), + Fix memory leak with XPath namespace nodes (Nick Wellnhofer), + Fix namespace axis traversal (Nick Wellnhofer), + Fix null pointer deref in docs with no root element (Hugh Davenport), + Fix XSD validation of URIs with ampersands (Alex Henrie), + xmlschemastypes.c: accept endOfDayFrag Times set to "24:00:00" mean "end of day" and should not cause an error. (Patrick Monnerat), + xmlcatalog: flush stdout before interactive shell input. (Patrick Monnerat), + xmllint: flush stdout before interactive shell input. (Patrick Monnerat), + Don't recurse into OP_VALUEs in xmlXPathOptimizeExpression (Nick Wellnhofer), + Fix namespace::node() XPath expression (Nick Wellnhofer), + Fix OOB write in xmlXPathEmptyNodeSet (Nick Wellnhofer), + Fix parsing of NCNames in XPath (Nick Wellnhofer), + Fix OOB read with invalid UTF-8 in xmlUTF8Strsize (Nick Wellnhofer), + Do normalize string-based datatype value in RelaxNG facet checking (Audric Schiltknecht), + Bug 760921: REGRESSION (8eb55d78): doc/examples/io1 test fails after fix for "xmlSaveUri() incorrectly recomposes URIs with rootless paths" <https://bugzilla.gnome.org/show_bug.cgi?id=760921> (David Kilzer), + Bug 760861: REGRESSION (bf9c1dad): Missing results for test/schemas/regexp-char-ref_[01].xsd <https://bugzilla.gnome.org/show_bug.cgi?id=760861> (David Kilzer), + error.c: *input->cur == 0 does not mean no error (Pavel Raiskup), + Add missing RNG test files (David Kilzer), + Bug 760183: REGRESSION (v2.9.3): XML push parser fails with bogus UTF-8 encoding error when multi-byte character in large CDATA section is split across buffer <https://bugzilla.gnome.org/show_bug.cgi?id=760183> (David Kilzer), + Bug 758572: ASAN crash in make check <https://bugzilla.gnome.org/show_bug.cgi?id=758572> (David Kilzer), + Bug 721158: Missing ICU string when doing --version on xmllint <https://bugzilla.gnome.org/show_bug.cgi?id=721158> (David Kilzer), + python 3: libxml2.c wrappers create Unicode str already (Michael Stahl), + Add autogen.sh to distrib (orzen), + Heap-based buffer overread in xmlNextChar (Daniel Veillard) + + - Improvements: + Add more debugging info to runtest (Daniel Veillard), + Implement "runtest -u" mode (David Kilzer), + Add a make rule to rebuild for ASAN (Daniel Veillard) + + + +v2.9.3: Nov 20 2015: + - Security: + CVE-2015-8242 Buffer overead with HTML parser in push mode (Hugh Davenport), + CVE-2015-7500 Fix memory access error due to incorrect entities boundaries (Daniel Veillard), + CVE-2015-7499-2 Detect incoherency on GROW (Daniel Veillard), + CVE-2015-7499-1 Add xmlHaltParser() to stop the parser (Daniel Veillard), + CVE-2015-5312 Another entity expansion issue (David Drysdale), + CVE-2015-7497 Avoid an heap buffer overflow in xmlDictComputeFastQKey (David Drysdale), + CVE-2015-7498 Avoid processing entities after encoding conversion failures (Daniel Veillard), + CVE-2015-8035 Fix XZ compression support loop (Daniel Veillard), + CVE-2015-7942-2 Fix an error in previous Conditional section patch (Daniel Veillard), + CVE-2015-7942 Another variation of overflow in Conditional sections (Daniel Veillard), + CVE-2015-1819 Enforce the reader to run in constant memory (Daniel Veillard) + CVE-2015-7941_2 Cleanup conditional section error handling (Daniel Veillard), + CVE-2015-7941_1 Stop parsing on entities boundaries errors (Daniel Veillard), + + - Documentation: + Correct spelling of "calling" (Alex Henrie), + Fix a small error in xmllint --format description (Fabien Degomme), + Avoid XSS on the search of xmlsoft.org (Daniel Veillard) + + - Portability: + threads: use forward declarations only for glibc (Michael Heimpold), + Update Win32 configure.js to search for configure.ac (Daniel Veillard) + + - Bug Fixes: + Bug on creating new stream from entity (Daniel Veillard), + Fix some loop issues embedding NEXT (Daniel Veillard), + Do not print error context when there is none (Daniel Veillard), + Avoid extra processing of MarkupDecl when EOF (Hugh Davenport), + Fix parsing short unclosed comment uninitialized access (Daniel Veillard), + Add missing Null check in xmlParseExternalEntityPrivate (Gaurav Gupta), + Fix a bug in CData error handling in the push parser (Daniel Veillard), + Fix a bug on name parsing at the end of current input buffer (Daniel Veillard), + Fix the spurious ID already defined error (Daniel Veillard), + Fix previous change to node sort order (Nick Wellnhofer), + Fix a self assignment issue raised by clang (Scott Graham), + Fail parsing early on if encoding conversion failed (Daniel Veillard), + Do not process encoding values if the declaration if broken (Daniel Veillard), + Silence clang's -Wunknown-attribute (Michael Catanzaro), + xmlMemUsed is not thread-safe (Martin von Gagern), + Fix support for except in nameclasses (Daniel Veillard), + Fix order of root nodes (Nick Wellnhofer), + Allow attributes on descendant-or-self axis (Nick Wellnhofer), + Fix the fix to Windows locking (Steve Nairn), + Fix timsort invariant loop re: Envisage article (Christopher Swenson), + Don't add IDs in xmlSetTreeDoc (Nick Wellnhofer), + Account for ID attributes in xmlSetTreeDoc (Nick Wellnhofer), + Remove various unused value assignments (Philip Withnall), + Fix missing entities after CVE-2014-3660 fix (Daniel Veillard), + Revert "Missing initialization for the catalog module" (Daniel Veillard) + + - Improvements: + Reuse xmlHaltParser() where it makes sense (Daniel Veillard), + xmlStopParser reset errNo (Daniel Veillard), + Reenable xz support by default (Daniel Veillard), + Recover unescaped less-than character in HTML recovery parsing (Daniel Veillard), + Allow HTML serializer to output HTML5 DOCTYPE (Shaun McCance), + Regression test for bug #695699 (Nick Wellnhofer), + Add a couple of XPath tests (Nick Wellnhofer), + Add Python 3 rpm subpackage (Tomas Radej), + libxml2-config.cmake.in: update include directories (Samuel Martin), + Adding example from bugs 738805 to regression tests (Daniel Veillard) + + - Cleanups: + + + 2.9.2: Oct 16 2014: - Security: Fix for CVE-2014-3660 billion laugh variant (Daniel Veillard), @@ -845,7 +1288,7 @@ - Improvement: switch parser to XML-1.0 5th edition, add parsing flags for old versions, switch URI parsing to RFC 3986, add xmlSchemaValidCtxtGetParserCtxt (Holger Kaelberer), - new hashing functions for dictionaries (based on Stefan Behnel work), + new hashing functions for dictionnaries (based on Stefan Behnel work), improve handling of misplaced html/head/body in HTML parser, better regression test tools and code coverage display, better algorithms to detect various versions of the billion laughts attacks, make @@ -1231,7 +1674,7 @@ Bakefile support (Francesco Montorsi), Windows compilation (Joel Reed), some gcc4 fixes, HP-UX portability fixes (Rick Jones). - bug fixes: xmlSchemaElementDump namespace (Kasimier Buchcik), push and - xmlreader stopping on non-fatal errors, thread support for dictionaries + xmlreader stopping on non-fatal errors, thread support for dictionnaries reference counting (Gary Coady), internal subset and push problem, URL saved in xmlCopyDoc, various schemas bug fixes (Kasimier), Python paths fixup (Stephane Bidoul), xmlGetNodePath and namespaces, xmlSetNsProp fix @@ -1482,7 +1925,7 @@ William) reported by Yuuichi Teranishi - bugfixes: make test and path issues, xmlWriter attribute serialization (William Brack), xmlWriter indentation (William), schemas validation - (Eric Haszlakiewicz), XInclude dictionaries issues (William and Oleg + (Eric Haszlakiewicz), XInclude dictionnaries issues (William and Oleg Paraschenko), XInclude empty fallback (William), HTML warnings (William), XPointer in XInclude (William), Python namespace serialization, isolat1ToUTF8 bound error (Alfred Mickautsch), output of parameter @@ -1503,7 +1946,7 @@ 2.6.5: Jan 25 2004: - - Bugfixes: dictionaries for schemas (William Brack), regexp segfault + - Bugfixes: dictionnaries for schemas (William Brack), regexp segfault (William), xs:all problem (William), a number of XPointer bugfixes (William), xmllint error go to stderr, DTD validation problem with namespace, memory leak (William), SAX1 cleanup and minimal options fixes
diff --git a/third_party/libxml/src/SAX2.c b/third_party/libxml/src/SAX2.c index 0f261b7..fee66b7fb 100644 --- a/third_party/libxml/src/SAX2.c +++ b/third_party/libxml/src/SAX2.c
@@ -1665,7 +1665,13 @@ #ifdef DEBUG_SAX_TREE xmlGenericError(xmlGenericErrorContext, "pushing(%s)\n", name); #endif - nodePush(ctxt, ret); + if (nodePush(ctxt, ret) < 0) { + xmlUnlinkNode(ret); + xmlFreeNode(ret); + if (prefix != NULL) + xmlFree(prefix); + return; + } /* * Link the child element @@ -2257,6 +2263,7 @@ ctxt->freeElems = ret->next; ctxt->freeElemsNr--; memset(ret, 0, sizeof(xmlNode)); + ret->doc = ctxt->myDoc; ret->type = XML_ELEMENT_NODE; if (ctxt->dictNames) @@ -2336,7 +2343,11 @@ /* * We are parsing a new node. */ - nodePush(ctxt, ret); + if (nodePush(ctxt, ret) < 0) { + xmlUnlinkNode(ret); + xmlFreeNode(ret); + return; + } /* * Link the child element
diff --git a/third_party/libxml/src/configure.ac b/third_party/libxml/src/configure.ac index 370e2de..9cae50c 100644 --- a/third_party/libxml/src/configure.ac +++ b/third_party/libxml/src/configure.ac
@@ -9,7 +9,7 @@ LIBXML_MAJOR_VERSION=2 LIBXML_MINOR_VERSION=9 -LIBXML_MICRO_VERSION=8 +LIBXML_MICRO_VERSION=9 LIBXML_MICRO_VERSION_SUFFIX= LIBXML_VERSION=$LIBXML_MAJOR_VERSION.$LIBXML_MINOR_VERSION.$LIBXML_MICRO_VERSION$LIBXML_MICRO_VERSION_SUFFIX LIBXML_VERSION_INFO=`expr $LIBXML_MAJOR_VERSION + $LIBXML_MINOR_VERSION`:$LIBXML_MICRO_VERSION:$LIBXML_MINOR_VERSION @@ -1620,7 +1620,14 @@ WIN32_EXTRA_LDFLAGS="-no-undefined" if test "${PYTHON}" != "" then - WIN32_EXTRA_PYTHON_LIBADD="-L${pythondir}/../../libs -lpython$(echo ${PYTHON_VERSION} | tr -d .)" + case "$host" in + *-w64-mingw*) + WIN32_EXTRA_PYTHON_LIBADD="-shrext .pyd -L${pythondir}/../../lib -lpython${PYTHON_VERSION}" + ;; + *) + WIN32_EXTRA_PYTHON_LIBADD="-L${pythondir}/../../libs -lpython$(echo ${PYTHON_VERSION} | tr -d .)" + ;; + esac fi ;; *-*-cygwin*)
diff --git a/third_party/libxml/src/encoding.c b/third_party/libxml/src/encoding.c index de7b511..a3aaf10e 100644 --- a/third_party/libxml/src/encoding.c +++ b/third_party/libxml/src/encoding.c
@@ -2460,8 +2460,6 @@ ret = -3; } - if (ret >= 0) output += ret; - /* * Attempt to handle error cases */
diff --git a/third_party/libxml/src/error.c b/third_party/libxml/src/error.c index 50e9e6f8..9d39f79 100644 --- a/third_party/libxml/src/error.c +++ b/third_party/libxml/src/error.c
@@ -631,7 +631,7 @@ (channel == xmlParserValidityError) || (channel == xmlParserValidityWarning)) xmlReportError(to, ctxt, str, NULL, NULL); - else if ((channel == (xmlGenericErrorFunc) fprintf) || + else if (((void(*)(void)) channel == (void(*)(void)) fprintf) || (channel == xmlGenericErrorDefaultFunc)) xmlReportError(to, ctxt, str, channel, data); else
diff --git a/third_party/libxml/src/gentest.py b/third_party/libxml/src/gentest.py index e4a8932..b76330047f 100755 --- a/third_party/libxml/src/gentest.py +++ b/third_party/libxml/src/gentest.py
@@ -399,14 +399,20 @@ known_param_types = [] -def is_known_param_type(name, rtype): - global test +def is_known_param_type(name): for type in known_param_types: if type == name: return 1 + return name[-3:] == 'Ptr' or name[-4:] == '_ptr' + +def generate_param_type(name, rtype): + global test + for type in known_param_types: + if type == name: + return for type in generated_param_types: if type == name: - return 1 + return if name[-3:] == 'Ptr' or name[-4:] == '_ptr': if rtype[0:6] == 'const ': @@ -429,9 +435,6 @@ if define == 1: test.write("#endif\n\n") add_generated_param_type(name) - return 1 - - return 0 # # Provide the type destructors for the return values @@ -546,7 +549,7 @@ continue; define = 0 - if argtypes.has_key(name) and is_known_param_type(name, name) == 0: + if argtypes.has_key(name) and is_known_param_type(name) == 0: values = ctxt.xpathEval("/api/symbols/enum[@type='%s']" % name) i = 0 vals = [] @@ -689,7 +692,7 @@ info = arg.xpathEval("string(@info)") nam = arg.xpathEval("string(@name)") type = type_convert(rtype, nam, info, module, name, n) - if is_known_param_type(type, rtype) == 0: + if is_known_param_type(type) == 0: add_missing_type(type, name); no_gen = 1 if (type[-3:] == 'Ptr' or type[-4:] == '_ptr') and \ @@ -716,6 +719,11 @@ t_ret = (type, rtype, info) break + if no_gen == 0: + for t_arg in t_args: + (nam, type, rtype, crtype, info) = t_arg + generate_param_type(type, rtype) + test.write(""" static int test_%s(void) {
diff --git a/third_party/libxml/src/include/libxml/globals.h b/third_party/libxml/src/include/libxml/globals.h index a9305aa..5e41b7b 100644 --- a/third_party/libxml/src/include/libxml/globals.h +++ b/third_party/libxml/src/include/libxml/globals.h
@@ -17,7 +17,6 @@ #include <libxml/xmlversion.h> #include <libxml/parser.h> #include <libxml/xmlerror.h> -#include <libxml/SAX.h> #include <libxml/SAX2.h> #include <libxml/xmlmemory.h>
diff --git a/third_party/libxml/src/include/libxml/tree.h b/third_party/libxml/src/include/libxml/tree.h index 4a9b3bc..626ed6a 100644 --- a/third_party/libxml/src/include/libxml/tree.h +++ b/third_party/libxml/src/include/libxml/tree.h
@@ -575,7 +575,7 @@ void *ids; /* Hash table for ID attributes if any */ void *refs; /* Hash table for IDREFs attributes if any */ const xmlChar *URL; /* The URI for that document */ - int charset; /* encoding of the in-memory content + int charset; /* Internal flag for charset handling, actually an xmlCharEncoding */ struct _xmlDict *dict; /* dict used to allocate names or NULL */ void *psvi; /* for type/PSVI informations */
diff --git a/third_party/libxml/src/include/libxml/xmlexports.h b/third_party/libxml/src/include/libxml/xmlexports.h index 2c79f814..31ab8a1 100644 --- a/third_party/libxml/src/include/libxml/xmlexports.h +++ b/third_party/libxml/src/include/libxml/xmlexports.h
@@ -131,8 +131,8 @@ #endif #endif -/* Cygwin platform, GNU compiler */ -#if defined(_WIN32) && defined(__CYGWIN__) +/* Cygwin platform (does not define _WIN32), GNU compiler */ +#if defined(__CYGWIN__) #undef XMLPUBFUN #undef XMLPUBVAR #undef XMLCALL @@ -145,7 +145,7 @@ #if !defined(LIBXML_STATIC) #define XMLPUBVAR __declspec(dllimport) extern #else - #define XMLPUBVAR + #define XMLPUBVAR extern #endif #endif #define XMLCALL __cdecl
diff --git a/third_party/libxml/src/include/wsockcompat.h b/third_party/libxml/src/include/wsockcompat.h index 0484ee3..e57ca8e 100644 --- a/third_party/libxml/src/include/wsockcompat.h +++ b/third_party/libxml/src/include/wsockcompat.h
@@ -11,6 +11,11 @@ #include <errno.h> #include <winsock2.h> +/* Fix for old MinGW. */ +#ifndef _WINSOCKAPI_ +#define _WINSOCKAPI_ +#endif + /* the following is a workaround a problem for 'inline' keyword in said header when compiled with Borland C++ 6 */ #if defined(__BORLANDC__) && !defined(__cplusplus)
diff --git a/third_party/libxml/src/libxml2.spec b/third_party/libxml/src/libxml2.spec index 46bba32..52cbeb83 100644 --- a/third_party/libxml/src/libxml2.spec +++ b/third_party/libxml/src/libxml2.spec
@@ -2,7 +2,7 @@ Summary: Library providing XML and HTML support Name: libxml2 -Version: 2.9.8 +Version: 2.9.9 Release: 1%{?dist}%{?extra_release} License: MIT Group: Development/Libraries @@ -203,6 +203,6 @@ %endif # with_python3 %changelog -* Tue Mar 27 2018 Daniel Veillard <veillard@redhat.com> -- upstream release 2.9.8 see http://xmlsoft.org/news.html +* Tue Feb 19 2019 Daniel Veillard <veillard@redhat.com> +- upstream release 2.9.9 see http://xmlsoft.org/news.html
diff --git a/third_party/libxml/src/parser.c b/third_party/libxml/src/parser.c index 4264445a..3a8a0d7 100644 --- a/third_party/libxml/src/parser.c +++ b/third_party/libxml/src/parser.c
@@ -7015,7 +7015,7 @@ */ if (NXT(1) == '#') { int i = 0; - xmlChar out[10]; + xmlChar out[16]; int hex = NXT(2); int value = xmlParseCharRef(ctxt); @@ -9264,7 +9264,8 @@ xmlErrMemory(ctxt, "dictionary allocation failure"); if ((attvalue != NULL) && (alloc != 0)) xmlFree(attvalue); - return(NULL); + localname = NULL; + goto done; } if (*URL != 0) { uri = xmlParseURI((const char *) URL); @@ -9514,7 +9515,8 @@ if ((atts == NULL) || (nbatts + 5 > maxatts)) { if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) { - return(NULL); + localname = NULL; + goto done; } maxatts = ctxt->maxatts; atts = ctxt->atts; @@ -12479,7 +12481,12 @@ ctxt->input->free((xmlChar *) ctxt->input->base); ctxt->input->free = NULL; } + if (ctxt->input->buf != NULL) { + xmlFreeParserInputBuffer(ctxt->input->buf); + ctxt->input->buf = NULL; + } ctxt->input->cur = BAD_CAST""; + ctxt->input->length = 0; ctxt->input->base = ctxt->input->cur; ctxt->input->end = ctxt->input->cur; }
diff --git a/third_party/libxml/src/parserInternals.c b/third_party/libxml/src/parserInternals.c index 9d45e5ca..265223b 100644 --- a/third_party/libxml/src/parserInternals.c +++ b/third_party/libxml/src/parserInternals.c
@@ -1240,8 +1240,18 @@ * size to be able to convert the buffer. */ xmlErrInternal(ctxt, "switching encoding : no input\n", NULL); + /* + * Callers assume that the input buffer takes ownership of the + * encoding handler. xmlCharEncCloseFunc frees unregistered + * handlers and avoids a memory leak. + */ + xmlCharEncCloseFunc(handler); return (-1); } + /* + * We should actually raise an error here, see issue #34. + */ + xmlCharEncCloseFunc(handler); return (0); }
diff --git a/third_party/libxml/src/runsuite.c b/third_party/libxml/src/runsuite.c index aaab13e..767455bd0 100644 --- a/third_party/libxml/src/runsuite.c +++ b/third_party/libxml/src/runsuite.c
@@ -327,10 +327,8 @@ } xmlNodeDump(buf, test->doc, test, 0, 0); pctxt = xmlRelaxNGNewMemParserCtxt((const char *)buf->content, buf->use); - xmlRelaxNGSetParserErrors(pctxt, - (xmlRelaxNGValidityErrorFunc) testErrorHandler, - (xmlRelaxNGValidityWarningFunc) testErrorHandler, - pctxt); + xmlRelaxNGSetParserErrors(pctxt, testErrorHandler, testErrorHandler, + pctxt); rng = xmlRelaxNGParse(pctxt); xmlRelaxNGFreeParserCtxt(pctxt); if (rng != NULL) { @@ -462,10 +460,8 @@ } xmlNodeDump(buf, test->doc, test, 0, 0); pctxt = xmlRelaxNGNewMemParserCtxt((const char *)buf->content, buf->use); - xmlRelaxNGSetParserErrors(pctxt, - (xmlRelaxNGValidityErrorFunc) testErrorHandler, - (xmlRelaxNGValidityWarningFunc) testErrorHandler, - pctxt); + xmlRelaxNGSetParserErrors(pctxt, testErrorHandler, testErrorHandler, + pctxt); rng = xmlRelaxNGParse(pctxt); xmlRelaxNGFreeParserCtxt(pctxt); if (extraMemoryFromResolver) @@ -510,9 +506,7 @@ nb_tests++; ctxt = xmlRelaxNGNewValidCtxt(rng); xmlRelaxNGSetValidErrors(ctxt, - (xmlRelaxNGValidityErrorFunc) testErrorHandler, - (xmlRelaxNGValidityWarningFunc) testErrorHandler, - ctxt); + testErrorHandler, testErrorHandler, ctxt); ret = xmlRelaxNGValidateDoc(ctxt, doc); xmlRelaxNGFreeValidCtxt(ctxt); if (ret > 0) { @@ -567,9 +561,7 @@ nb_tests++; ctxt = xmlRelaxNGNewValidCtxt(rng); xmlRelaxNGSetValidErrors(ctxt, - (xmlRelaxNGValidityErrorFunc) testErrorHandler, - (xmlRelaxNGValidityWarningFunc) testErrorHandler, - ctxt); + testErrorHandler, testErrorHandler, ctxt); ret = xmlRelaxNGValidateDoc(ctxt, doc); xmlRelaxNGFreeValidCtxt(ctxt); if (ret == 0) { @@ -825,10 +817,7 @@ } ctxt = xmlSchemaNewValidCtxt(schemas); - xmlSchemaSetValidErrors(ctxt, - (xmlSchemaValidityErrorFunc) testErrorHandler, - (xmlSchemaValidityWarningFunc) testErrorHandler, - ctxt); + xmlSchemaSetValidErrors(ctxt, testErrorHandler, testErrorHandler, ctxt); ret = xmlSchemaValidateDoc(ctxt, doc); if (xmlStrEqual(validity, BAD_CAST "valid")) { @@ -916,10 +905,8 @@ if (xmlStrEqual(validity, BAD_CAST "valid")) { nb_schematas++; ctxt = xmlSchemaNewParserCtxt((const char *) path); - xmlSchemaSetParserErrors(ctxt, - (xmlSchemaValidityErrorFunc) testErrorHandler, - (xmlSchemaValidityWarningFunc) testErrorHandler, - ctxt); + xmlSchemaSetParserErrors(ctxt, testErrorHandler, testErrorHandler, + ctxt); schemas = xmlSchemaParse(ctxt); xmlSchemaFreeParserCtxt(ctxt); if (schemas == NULL) { @@ -952,10 +939,8 @@ } else if (xmlStrEqual(validity, BAD_CAST "invalid")) { nb_schematas++; ctxt = xmlSchemaNewParserCtxt((const char *) path); - xmlSchemaSetParserErrors(ctxt, - (xmlSchemaValidityErrorFunc) testErrorHandler, - (xmlSchemaValidityWarningFunc) testErrorHandler, - ctxt); + xmlSchemaSetParserErrors(ctxt, testErrorHandler, testErrorHandler, + ctxt); schemas = xmlSchemaParse(ctxt); xmlSchemaFreeParserCtxt(ctxt); if (schemas != NULL) {
diff --git a/third_party/libxml/src/runtest.c b/third_party/libxml/src/runtest.c index 605c1d1a..b1c30d8 100644 --- a/third_party/libxml/src/runtest.c +++ b/third_party/libxml/src/runtest.c
@@ -587,8 +587,8 @@ suffixbuff[0]='_'; #endif - snprintf(res, 499, "%s%s%s", out, base, suffixbuff); - res[499] = 0; + if (snprintf(res, 499, "%s%s%s", out, base, suffixbuff) >= 499) + res[499] = 0; return(strdup(res)); } @@ -2501,13 +2501,17 @@ return(-1); } - snprintf(pattern, 499, "./test/XPath/tests/%s*", baseFilename(filename)); - pattern[499] = 0; + res = snprintf(pattern, 499, "./test/XPath/tests/%s*", + baseFilename(filename)); + if (res >= 499) + pattern[499] = 0; globbuf.gl_offs = 0; glob(pattern, GLOB_DOOFFS, NULL, &globbuf); for (i = 0;i < globbuf.gl_pathc;i++) { - snprintf(result, 499, "result/XPath/tests/%s", + res = snprintf(result, 499, "result/XPath/tests/%s", baseFilename(globbuf.gl_pathv[i])); + if (res >= 499) + result[499] = 0; res = xpathCommonTest(globbuf.gl_pathv[i], &result[0], 0, 0); if (res != 0) ret = res; @@ -2549,13 +2553,17 @@ return(-1); } - snprintf(pattern, 499, "./test/XPath/xptr/%s*", baseFilename(filename)); - pattern[499] = 0; + res = snprintf(pattern, 499, "./test/XPath/xptr/%s*", + baseFilename(filename)); + if (res >= 499) + pattern[499] = 0; globbuf.gl_offs = 0; glob(pattern, GLOB_DOOFFS, NULL, &globbuf); for (i = 0;i < globbuf.gl_pathc;i++) { - snprintf(result, 499, "result/XPath/xptr/%s", + res = snprintf(result, 499, "result/XPath/xptr/%s", baseFilename(globbuf.gl_pathv[i])); + if (res >= 499) + result[499] = 0; res = xpathCommonTest(globbuf.gl_pathv[i], &result[0], 1, 0); if (res != 0) ret = res; @@ -3011,10 +3019,7 @@ } ctxt = xmlSchemaNewValidCtxt(schemas); - xmlSchemaSetValidErrors(ctxt, - (xmlSchemaValidityErrorFunc) testErrorHandler, - (xmlSchemaValidityWarningFunc) testErrorHandler, - ctxt); + xmlSchemaSetValidErrors(ctxt, testErrorHandler, testErrorHandler, ctxt); validResult = xmlSchemaValidateDoc(ctxt, doc); if (validResult == 0) { fprintf(schemasOutput, "%s validates\n", filename); @@ -3079,10 +3084,7 @@ /* first compile the schemas if possible */ ctxt = xmlSchemaNewParserCtxt(filename); - xmlSchemaSetParserErrors(ctxt, - (xmlSchemaValidityErrorFunc) testErrorHandler, - (xmlSchemaValidityWarningFunc) testErrorHandler, - ctxt); + xmlSchemaSetParserErrors(ctxt, testErrorHandler, testErrorHandler, ctxt); schemas = xmlSchemaParse(ctxt); xmlSchemaFreeParserCtxt(ctxt); @@ -3104,8 +3106,8 @@ memcpy(prefix, base, len); prefix[len] = 0; - snprintf(pattern, 499, "./test/schemas/%s_?.xml", prefix); - pattern[499] = 0; + if (snprintf(pattern, 499, "./test/schemas/%s_?.xml", prefix) >= 499) + pattern[499] = 0; if (base[len] == '_') { len += 2; @@ -3123,12 +3125,14 @@ len = strlen(base2); if ((len > 6) && (base2[len - 6] == '_')) { count = base2[len - 5]; - snprintf(result, 499, "result/schemas/%s_%c", + ret = snprintf(result, 499, "result/schemas/%s_%c", prefix, count); - result[499] = 0; - snprintf(err, 499, "result/schemas/%s_%c.err", + if (ret >= 499) + result[499] = 0; + ret = snprintf(err, 499, "result/schemas/%s_%c.err", prefix, count); - err[499] = 0; + if (ret >= 499) + err[499] = 0; } else { fprintf(stderr, "don't know how to process %s\n", instance); continue; @@ -3186,10 +3190,7 @@ } ctxt = xmlRelaxNGNewValidCtxt(schemas); - xmlRelaxNGSetValidErrors(ctxt, - (xmlRelaxNGValidityErrorFunc) testErrorHandler, - (xmlRelaxNGValidityWarningFunc) testErrorHandler, - ctxt); + xmlRelaxNGSetValidErrors(ctxt, testErrorHandler, testErrorHandler, ctxt); ret = xmlRelaxNGValidateDoc(ctxt, doc); if (ret == 0) { testErrorHandler(NULL, "%s validates\n", filename); @@ -3256,10 +3257,7 @@ /* first compile the schemas if possible */ ctxt = xmlRelaxNGNewParserCtxt(filename); - xmlRelaxNGSetParserErrors(ctxt, - (xmlRelaxNGValidityErrorFunc) testErrorHandler, - (xmlRelaxNGValidityWarningFunc) testErrorHandler, - ctxt); + xmlRelaxNGSetParserErrors(ctxt, testErrorHandler, testErrorHandler, ctxt); schemas = xmlRelaxNGParse(ctxt); xmlRelaxNGFreeParserCtxt(ctxt); @@ -3275,8 +3273,8 @@ memcpy(prefix, base, len); prefix[len] = 0; - snprintf(pattern, 499, "./test/relaxng/%s_?.xml", prefix); - pattern[499] = 0; + if (snprintf(pattern, 499, "./test/relaxng/%s_?.xml", prefix) >= 499) + pattern[499] = 0; globbuf.gl_offs = 0; glob(pattern, GLOB_DOOFFS, NULL, &globbuf); @@ -3288,12 +3286,14 @@ len = strlen(base2); if ((len > 6) && (base2[len - 6] == '_')) { count = base2[len - 5]; - snprintf(result, 499, "result/relaxng/%s_%c", + res = snprintf(result, 499, "result/relaxng/%s_%c", prefix, count); - result[499] = 0; - snprintf(err, 499, "result/relaxng/%s_%c.err", + if (res >= 499) + result[499] = 0; + res = snprintf(err, 499, "result/relaxng/%s_%c.err", prefix, count); - err[499] = 0; + if (res >= 499) + err[499] = 0; } else { fprintf(stderr, "don't know how to process %s\n", instance); continue; @@ -3301,7 +3301,7 @@ if (schemas == NULL) { } else { nb_tests++; - ret = rngOneTest(filename, instance, result, err, + res = rngOneTest(filename, instance, result, err, options, schemas); if (res != 0) ret = res; @@ -3364,8 +3364,8 @@ (!strcmp(prefix, "tutor8_2"))) disable_err = 1; - snprintf(pattern, 499, "./test/relaxng/%s_?.xml", prefix); - pattern[499] = 0; + if (snprintf(pattern, 499, "./test/relaxng/%s_?.xml", prefix) >= 499) + pattern[499] = 0; globbuf.gl_offs = 0; glob(pattern, GLOB_DOOFFS, NULL, &globbuf); @@ -3377,12 +3377,14 @@ len = strlen(base2); if ((len > 6) && (base2[len - 6] == '_')) { count = base2[len - 5]; - snprintf(result, 499, "result/relaxng/%s_%c", + ret = snprintf(result, 499, "result/relaxng/%s_%c", prefix, count); - result[499] = 0; - snprintf(err, 499, "result/relaxng/%s_%c.err", + if (ret >= 499) + result[499] = 0; + ret = snprintf(err, 499, "result/relaxng/%s_%c.err", prefix, count); - err[499] = 0; + if (ret >= 499) + err[499] = 0; } else { fprintf(stderr, "don't know how to process %s\n", instance); continue; @@ -3507,8 +3509,8 @@ len -= 4; memcpy(xml, filename, len); xml[len] = 0; - snprintf(result, 499, "result/pattern/%s", baseFilename(xml)); - result[499] = 0; + if (snprintf(result, 499, "result/pattern/%s", baseFilename(xml)) >= 499) + result[499] = 0; memcpy(xml + len, ".xml", 5); if (!checkTestFile(xml) && !update_results) { @@ -3885,17 +3887,20 @@ memcpy(prefix, base, len); prefix[len] = 0; - snprintf(buf, 499, "result/c14n/%s/%s", subdir,prefix); + if (snprintf(buf, 499, "result/c14n/%s/%s", subdir, prefix) >= 499) + buf[499] = 0; if (!checkTestFile(buf) && !update_results) { fprintf(stderr, "Missing result file %s", buf); return(-1); } result = strdup(buf); - snprintf(buf, 499, "test/c14n/%s/%s.xpath", subdir,prefix); + if (snprintf(buf, 499, "test/c14n/%s/%s.xpath", subdir, prefix) >= 499) + buf[499] = 0; if (checkTestFile(buf)) { xpath = strdup(buf); } - snprintf(buf, 499, "test/c14n/%s/%s.ns", subdir,prefix); + if (snprintf(buf, 499, "test/c14n/%s/%s.ns", subdir, prefix) >= 499) + buf[499] = 0; if (checkTestFile(buf)) { ns = strdup(buf); } @@ -4413,9 +4418,10 @@ char *result; char *error; int mem; - xmlCharEncodingHandlerPtr ebcdicHandler; + xmlCharEncodingHandlerPtr ebcdicHandler, eucJpHandler; ebcdicHandler = xmlGetCharEncodingHandler(XML_CHAR_ENCODING_EBCDIC); + eucJpHandler = xmlGetCharEncodingHandler(XML_CHAR_ENCODING_EUC_JP); if (tst == NULL) return(-1); if (tst->in != NULL) { @@ -4426,8 +4432,10 @@ for (i = 0;i < globbuf.gl_pathc;i++) { if (!checkTestFile(globbuf.gl_pathv[i])) continue; - if ((ebcdicHandler == NULL) && - (strstr(globbuf.gl_pathv[i], "ebcdic") != NULL)) + if (((ebcdicHandler == NULL) && + (strstr(globbuf.gl_pathv[i], "ebcdic") != NULL)) || + ((eucJpHandler == NULL) && + (strstr(globbuf.gl_pathv[i], "icu_parse_test") != NULL))) continue; if (tst->suffix != NULL) { result = resultFilename(globbuf.gl_pathv[i], tst->out, @@ -4496,6 +4504,7 @@ } xmlCharEncCloseFunc(ebcdicHandler); + xmlCharEncCloseFunc(eucJpHandler); return(err); }
diff --git a/third_party/libxml/src/testC14N.c b/third_party/libxml/src/testC14N.c index 86e58f27..addc800 100644 --- a/third_party/libxml/src/testC14N.c +++ b/third_party/libxml/src/testC14N.c
@@ -18,6 +18,9 @@ #define STDOUT_FILENO fileno(stdout) #endif /* HAVE_UNISTD_H */ #endif +#ifdef _WIN32 +#include <io.h> +#endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif
diff --git a/third_party/libxml/src/testRelax.c b/third_party/libxml/src/testRelax.c index 8e94a7a8..3549f93 100644 --- a/third_party/libxml/src/testRelax.c +++ b/third_party/libxml/src/testRelax.c
@@ -101,9 +101,7 @@ ctxt = xmlRelaxNGNewMemParserCtxt((char *)base,info.st_size); xmlRelaxNGSetParserErrors(ctxt, - (xmlRelaxNGValidityErrorFunc) fprintf, - (xmlRelaxNGValidityWarningFunc) fprintf, - stderr); + xmlGenericError, xmlGenericError, NULL); schema = xmlRelaxNGParse(ctxt); xmlRelaxNGFreeParserCtxt(ctxt); munmap((char *) base, info.st_size); @@ -112,9 +110,7 @@ { ctxt = xmlRelaxNGNewParserCtxt(argv[i]); xmlRelaxNGSetParserErrors(ctxt, - (xmlRelaxNGValidityErrorFunc) fprintf, - (xmlRelaxNGValidityWarningFunc) fprintf, - stderr); + xmlGenericError, xmlGenericError, NULL); schema = xmlRelaxNGParse(ctxt); xmlRelaxNGFreeParserCtxt(ctxt); } @@ -144,9 +140,7 @@ ctxt = xmlRelaxNGNewValidCtxt(schema); xmlRelaxNGSetValidErrors(ctxt, - (xmlRelaxNGValidityErrorFunc) fprintf, - (xmlRelaxNGValidityWarningFunc) fprintf, - stderr); + xmlGenericError, xmlGenericError, NULL); ret = xmlRelaxNGValidateDoc(ctxt, doc); if (ret == 0) { printf("%s validates\n", argv[i]);
diff --git a/third_party/libxml/src/testSchemas.c b/third_party/libxml/src/testSchemas.c index b98e631..fc39862c 100644 --- a/third_party/libxml/src/testSchemas.c +++ b/third_party/libxml/src/testSchemas.c
@@ -97,9 +97,7 @@ ctxt = xmlSchemaNewMemParserCtxt((char *)base,info.st_size); xmlSchemaSetParserErrors(ctxt, - (xmlSchemaValidityErrorFunc) fprintf, - (xmlSchemaValidityWarningFunc) fprintf, - stderr); + xmlGenericError, xmlGenericError, NULL); schema = xmlSchemaParse(ctxt); xmlSchemaFreeParserCtxt(ctxt); munmap((char *) base, info.st_size); @@ -108,9 +106,7 @@ { ctxt = xmlSchemaNewParserCtxt(argv[i]); xmlSchemaSetParserErrors(ctxt, - (xmlSchemaValidityErrorFunc) fprintf, - (xmlSchemaValidityWarningFunc) fprintf, - stderr); + xmlGenericError, xmlGenericError, NULL); schema = xmlSchemaParse(ctxt); xmlSchemaFreeParserCtxt(ctxt); } @@ -135,9 +131,7 @@ ctxt = xmlSchemaNewValidCtxt(schema); xmlSchemaSetValidErrors(ctxt, - (xmlSchemaValidityErrorFunc) fprintf, - (xmlSchemaValidityWarningFunc) fprintf, - stderr); + xmlGenericError, xmlGenericError, NULL); ret = xmlSchemaValidateDoc(ctxt, doc); if (ret == 0) { printf("%s validates\n", argv[i]);
diff --git a/third_party/libxml/src/testThreads.c b/third_party/libxml/src/testThreads.c index 2ef70a7..bef65377 100644 --- a/third_party/libxml/src/testThreads.c +++ b/third_party/libxml/src/testThreads.c
@@ -10,6 +10,8 @@ #include <libxml/catalog.h> #ifdef HAVE_PTHREAD_H #include <pthread.h> +#elif defined HAVE_WIN32_THREADS +#include <windows.h> #elif defined HAVE_BEOS_THREADS #include <OS.h> #endif @@ -20,25 +22,32 @@ #include <assert.h> #define MAX_ARGC 20 +#define TEST_REPEAT_COUNT 500 #ifdef HAVE_PTHREAD_H static pthread_t tid[MAX_ARGC]; +#elif defined HAVE_WIN32_THREADS +static HANDLE tid[MAX_ARGC]; #elif defined HAVE_BEOS_THREADS static thread_id tid[MAX_ARGC]; #endif -static const char *catalog = "test/threads/complex.xml"; -static const char *testfiles[] = { - "test/threads/abc.xml", - "test/threads/acb.xml", - "test/threads/bac.xml", - "test/threads/bca.xml", - "test/threads/cab.xml", - "test/threads/cba.xml", - "test/threads/invalid.xml", -}; +typedef struct { + const char *filename; + int okay; +} xmlThreadParams; -static const char *Okay = "OK"; -static const char *Failed = "Failed"; +static const char *catalog = "test/threads/complex.xml"; +static xmlThreadParams threadParams[] = { + { "test/threads/abc.xml", 0 }, + { "test/threads/acb.xml", 0 }, + { "test/threads/bac.xml", 0 }, + { "test/threads/bca.xml", 0 }, + { "test/threads/cab.xml", 0 }, + { "test/threads/cba.xml", 0 }, + { "test/threads/invalid.xml", 0 } +}; +static const unsigned int num_threads = sizeof(threadParams) / + sizeof(threadParams[0]); #ifndef xmlDoValidityCheckingDefaultValue #error xmlDoValidityCheckingDefaultValue is not a macro @@ -51,7 +60,8 @@ thread_specific_data(void *private_data) { xmlDocPtr myDoc; - const char *filename = (const char *) private_data; + xmlThreadParams *params = (xmlThreadParams *) private_data; + const char *filename = params->filename; int okay = 1; if (!strcmp(filename, "test/threads/invalid.xml")) { @@ -91,9 +101,8 @@ okay = 0; } } - if (okay == 0) - return((void *) Failed); - return ((void *) Okay); + params->okay = okay; + return(NULL); } #ifdef HAVE_PTHREAD_H @@ -101,27 +110,25 @@ main(void) { unsigned int i, repeat; - unsigned int num_threads = sizeof(testfiles) / sizeof(testfiles[0]); - void *results[MAX_ARGC]; int ret; xmlInitParser(); - for (repeat = 0;repeat < 500;repeat++) { + for (repeat = 0;repeat < TEST_REPEAT_COUNT;repeat++) { xmlLoadCatalog(catalog); - memset(results, 0, sizeof(*results)*num_threads); memset(tid, 0xff, sizeof(*tid)*num_threads); for (i = 0; i < num_threads; i++) { ret = pthread_create(&tid[i], NULL, thread_specific_data, - (void *) testfiles[i]); + (void *) &threadParams[i]); if (ret != 0) { perror("pthread_create"); exit(1); } } for (i = 0; i < num_threads; i++) { - ret = pthread_join(tid[i], &results[i]); + void *result; + ret = pthread_join(tid[i], &result); if (ret != 0) { perror("pthread_join"); exit(1); @@ -130,35 +137,97 @@ xmlCatalogCleanup(); for (i = 0; i < num_threads; i++) - if (results[i] != (void *) Okay) - printf("Thread %d handling %s failed\n", i, testfiles[i]); + if (threadParams[i].okay == 0) + printf("Thread %d handling %s failed\n", i, + threadParams[i].filename); } xmlCleanupParser(); xmlMemoryDump(); return (0); } +#elif defined HAVE_WIN32_THREADS +static DWORD WINAPI +win32_thread_specific_data(void *private_data) +{ + thread_specific_data(private_data); + return(0); +} + +int +main(void) +{ + unsigned int i, repeat; + BOOL ret; + + xmlInitParser(); + for (repeat = 0;repeat < TEST_REPEAT_COUNT;repeat++) + { + xmlLoadCatalog(catalog); + + for (i = 0; i < num_threads; i++) + { + tid[i] = (HANDLE) -1; + } + + for (i = 0; i < num_threads; i++) + { + DWORD useless; + tid[i] = CreateThread(NULL, 0, + win32_thread_specific_data, &threadParams[i], 0, &useless); + if (tid[i] == NULL) + { + perror("CreateThread"); + exit(1); + } + } + + if (WaitForMultipleObjects (num_threads, tid, TRUE, INFINITE) == WAIT_FAILED) + perror ("WaitForMultipleObjects failed"); + + for (i = 0; i < num_threads; i++) + { + DWORD exitCode; + ret = GetExitCodeThread (tid[i], &exitCode); + if (ret == 0) + { + perror("GetExitCodeThread"); + exit(1); + } + CloseHandle (tid[i]); + } + + xmlCatalogCleanup(); + for (i = 0; i < num_threads; i++) { + if (threadParams[i].okay == 0) + printf("Thread %d handling %s failed\n", i, + threadParams[i].filename); + } + } + + xmlCleanupParser(); + xmlMemoryDump(); + + return (0); +} #elif defined HAVE_BEOS_THREADS int main(void) { unsigned int i, repeat; - unsigned int num_threads = sizeof(testfiles) / sizeof(testfiles[0]); - void *results[MAX_ARGC]; status_t ret; xmlInitParser(); printf("Parser initialized\n"); - for (repeat = 0;repeat < 500;repeat++) { + for (repeat = 0;repeat < TEST_REPEAT_COUNT;repeat++) { printf("repeat: %d\n",repeat); xmlLoadCatalog(catalog); printf("loaded catalog: %s\n", catalog); for (i = 0; i < num_threads; i++) { - results[i] = NULL; tid[i] = (thread_id) -1; } printf("cleaned threads\n"); for (i = 0; i < num_threads; i++) { - tid[i] = spawn_thread(thread_specific_data, "xmlTestThread", B_NORMAL_PRIORITY, (void *) testfiles[i]); + tid[i] = spawn_thread(thread_specific_data, "xmlTestThread", B_NORMAL_PRIORITY, (void *) &threadParams[i]); if (tid[i] < B_OK) { perror("beos_thread_create"); exit(1); @@ -166,7 +235,8 @@ printf("beos_thread_create %d -> %d\n", i, tid[i]); } for (i = 0; i < num_threads; i++) { - ret = wait_for_thread(tid[i], &results[i]); + void *result; + ret = wait_for_thread(tid[i], &result); printf("beos_thread_wait %d -> %d\n", i, ret); if (ret != B_OK) { perror("beos_thread_wait"); @@ -177,8 +247,9 @@ xmlCatalogCleanup(); ret = B_OK; for (i = 0; i < num_threads; i++) - if (results[i] != (void *) Okay) { - printf("Thread %d handling %s failed\n", i, testfiles[i]); + if (threadParams[i].okay == 0) { + printf("Thread %d handling %s failed\n", i, + threadParams[i].filename); ret = B_ERROR; } }
diff --git a/third_party/libxml/src/testThreadsWin32.c b/third_party/libxml/src/testThreadsWin32.c deleted file mode 100644 index 3d1a5ba..0000000 --- a/third_party/libxml/src/testThreadsWin32.c +++ /dev/null
@@ -1,150 +0,0 @@ -#include "libxml.h" -#include <stdlib.h> -#include <stdio.h> - -#if defined(LIBXML_THREAD_ENABLED) && defined(LIBXML_CATALOG_ENABLED) -#include <libxml/globals.h> -#include <libxml/threads.h> -#include <libxml/parser.h> -#include <libxml/catalog.h> -#include <windows.h> -#include <string.h> -#include <assert.h> - -#define MAX_ARGC 20 -#define TEST_REPEAT_COUNT 500 - -static HANDLE tid[MAX_ARGC]; - -static const char *catalog = "test/threads/complex.xml"; -static char *testfiles[] = { - "test/threads/abc.xml", - "test/threads/acb.xml", - "test/threads/bac.xml", - "test/threads/bca.xml", - "test/threads/cab.xml", - "test/threads/cba.xml", - "test/threads/invalid.xml", -}; - -const char *Okay = "OK"; -const char *Failed = "Failed"; - -#ifndef xmlDoValidityCheckingDefaultValue -#error xmlDoValidityCheckingDefaultValue is not a macro -#endif -#ifndef xmlGenericErrorContext -#error xmlGenericErrorContext is not a macro -#endif - -static DWORD WINAPI -thread_specific_data(void *private_data) -{ - xmlDocPtr myDoc; - const char *filename = (const char *) private_data; - int okay = 1; - - if (!strcmp(filename, "test/threads/invalid.xml")) { - xmlDoValidityCheckingDefaultValue = 0; - xmlGenericErrorContext = stdout; - } else { - xmlDoValidityCheckingDefaultValue = 1; - xmlGenericErrorContext = stderr; - } - myDoc = xmlParseFile(filename); - if (myDoc) { - xmlFreeDoc(myDoc); - } else { - printf("parse failed\n"); - okay = 0; - } - if (!strcmp(filename, "test/threads/invalid.xml")) { - if (xmlDoValidityCheckingDefaultValue != 0) { - printf("ValidityCheckingDefaultValue override failed\n"); - okay = 0; - } - if (xmlGenericErrorContext != stdout) { - printf("xmlGenericErrorContext override failed\n"); - okay = 0; - } - } else { - if (xmlDoValidityCheckingDefaultValue != 1) { - printf("ValidityCheckingDefaultValue override failed\n"); - okay = 0; - } - if (xmlGenericErrorContext != stderr) { - printf("xmlGenericErrorContext override failed\n"); - okay = 0; - } - } - if (okay == 0) - return ((DWORD) Failed); - return ((DWORD) Okay); -} - -int -main() -{ - unsigned int i, repeat; - unsigned int num_threads = sizeof(testfiles) / sizeof(testfiles[0]); - DWORD results[MAX_ARGC]; - BOOL ret; - - xmlInitParser(); - for (repeat = 0;repeat < TEST_REPEAT_COUNT;repeat++) - { - xmlLoadCatalog(catalog); - - for (i = 0; i < num_threads; i++) - { - results[i] = 0; - tid[i] = (HANDLE) -1; - } - - for (i = 0; i < num_threads; i++) - { - DWORD useless; - tid[i] = CreateThread(NULL, 0, - thread_specific_data, testfiles[i], 0, &useless); - if (tid[i] == NULL) - { - perror("CreateThread"); - exit(1); - } - } - - if (WaitForMultipleObjects (num_threads, tid, TRUE, INFINITE) == WAIT_FAILED) - perror ("WaitForMultipleObjects failed"); - - for (i = 0; i < num_threads; i++) - { - ret = GetExitCodeThread (tid[i], &results[i]); - if (ret == 0) - { - perror("GetExitCodeThread"); - exit(1); - } - CloseHandle (tid[i]); - } - - xmlCatalogCleanup(); - for (i = 0; i < num_threads; i++) { - if (results[i] != (DWORD) Okay) - printf("Thread %d handling %s failed\n", i, testfiles[i]); - } - } - - xmlCleanupParser(); - xmlMemoryDump(); - - return (0); -} - -#else /* !LIBXML_THREADS_ENABLED */ -int -main() -{ - fprintf(stderr, "libxml was not compiled with thread or catalog support\n"); - return (0); -} -#endif
diff --git a/third_party/libxml/src/testURI.c b/third_party/libxml/src/testURI.c index d20989d..0043b203 100644 --- a/third_party/libxml/src/testURI.c +++ b/third_party/libxml/src/testURI.c
@@ -19,6 +19,7 @@ static const char *base = NULL; static int escape = 0; static int debug = 0; +static int relative = 0; static void handleURI(const char *str) { int ret; @@ -57,7 +58,12 @@ } } } else { - res = xmlBuildURI((xmlChar *)str, (xmlChar *) base); + if (relative) { + res = xmlBuildRelativeURI((xmlChar *)str, (xmlChar *) base); + } else { + res = xmlBuildURI((xmlChar *)str, (xmlChar *) base); + } + if (res != NULL) { printf("%s\n", (char *) res); } @@ -75,6 +81,11 @@ int i, arg = 1; if ((argc > arg) && (argv[arg] != NULL) && + (!strcmp(argv[arg], "--relative"))) { + arg++; + relative++; + } + if ((argc > arg) && (argv[arg] != NULL) && ((!strcmp(argv[arg], "-base")) || (!strcmp(argv[arg], "--base")))) { arg++; base = argv[arg];
diff --git a/third_party/libxml/src/testapi.c b/third_party/libxml/src/testapi.c index 4a751e20..980d7fb5 100644 --- a/third_party/libxml/src/testapi.c +++ b/third_party/libxml/src/testapi.c
@@ -7511,13 +7511,6 @@ } -#define gen_nb_char_ptr 1 -static char * gen_char_ptr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { - return(NULL); -} -static void des_char_ptr(int no ATTRIBUTE_UNUSED, char * val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { -} - static int test_xmlShell(void) { int test_ret = 0; @@ -7528,6 +7521,13 @@ } +#define gen_nb_char_ptr 1 +static char * gen_char_ptr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { + return(NULL); +} +static void des_char_ptr(int no ATTRIBUTE_UNUSED, char * val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { +} + static int test_xmlShellBase(void) { int test_ret = 0; @@ -9334,13 +9334,6 @@ } -#define gen_nb_xmlEntitiesTablePtr 1 -static xmlEntitiesTablePtr gen_xmlEntitiesTablePtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { - return(NULL); -} -static void des_xmlEntitiesTablePtr(int no ATTRIBUTE_UNUSED, xmlEntitiesTablePtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { -} - static int test_xmlCopyEntitiesTable(void) { int test_ret = 0; @@ -9361,6 +9354,13 @@ } +#define gen_nb_xmlEntitiesTablePtr 1 +static xmlEntitiesTablePtr gen_xmlEntitiesTablePtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { + return(NULL); +} +static void des_xmlEntitiesTablePtr(int no ATTRIBUTE_UNUSED, xmlEntitiesTablePtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { +} + static int test_xmlDumpEntitiesTable(void) { int test_ret = 0; @@ -18145,16 +18145,6 @@ return(test_ret); } -#ifdef LIBXML_SCHEMATRON_ENABLED - -#define gen_nb_xmlSchematronPtr 1 -static xmlSchematronPtr gen_xmlSchematronPtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { - return(NULL); -} -static void des_xmlSchematronPtr(int no ATTRIBUTE_UNUSED, xmlSchematronPtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { -} -#endif - static int test_xmlSchematronNewValidCtxt(void) { @@ -18165,16 +18155,6 @@ return(test_ret); } -#ifdef LIBXML_SCHEMATRON_ENABLED - -#define gen_nb_xmlSchematronParserCtxtPtr 1 -static xmlSchematronParserCtxtPtr gen_xmlSchematronParserCtxtPtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { - return(NULL); -} -static void des_xmlSchematronParserCtxtPtr(int no ATTRIBUTE_UNUSED, xmlSchematronParserCtxtPtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { -} -#endif - static int test_xmlSchematronParse(void) { @@ -18185,6 +18165,16 @@ return(test_ret); } + +static int +test_xmlSchematronSetValidStructuredErrors(void) { + int test_ret = 0; + + + /* missing type support */ + return(test_ret); +} + #ifdef LIBXML_SCHEMATRON_ENABLED #define gen_nb_xmlSchematronValidCtxtPtr 1 @@ -18197,16 +18187,6 @@ static int -test_xmlSchematronSetValidStructuredErrors(void) { - int test_ret = 0; - - - /* missing type support */ - return(test_ret); -} - - -static int test_xmlSchematronValidateDoc(void) { int test_ret = 0; @@ -18665,13 +18645,6 @@ } -#define gen_nb_const_xmlBufPtr 1 -static xmlBufPtr gen_const_xmlBufPtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { - return(NULL); -} -static void des_const_xmlBufPtr(int no ATTRIBUTE_UNUSED, const xmlBufPtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { -} - static int test_xmlBufUse(void) { int test_ret = 0; @@ -25100,13 +25073,6 @@ } -#define gen_nb_xmlAttributeTablePtr 1 -static xmlAttributeTablePtr gen_xmlAttributeTablePtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { - return(NULL); -} -static void des_xmlAttributeTablePtr(int no ATTRIBUTE_UNUSED, xmlAttributeTablePtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { -} - static int test_xmlCopyAttributeTable(void) { int test_ret = 0; @@ -25188,13 +25154,6 @@ } -#define gen_nb_xmlElementTablePtr 1 -static xmlElementTablePtr gen_xmlElementTablePtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { - return(NULL); -} -static void des_xmlElementTablePtr(int no ATTRIBUTE_UNUSED, xmlElementTablePtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { -} - static int test_xmlCopyElementTable(void) { int test_ret = 0; @@ -25215,13 +25174,6 @@ } -#define gen_nb_xmlNotationTablePtr 1 -static xmlNotationTablePtr gen_xmlNotationTablePtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { - return(NULL); -} -static void des_xmlNotationTablePtr(int no ATTRIBUTE_UNUSED, xmlNotationTablePtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { -} - static int test_xmlCopyNotationTable(void) { int test_ret = 0; @@ -25288,6 +25240,13 @@ } +#define gen_nb_xmlAttributeTablePtr 1 +static xmlAttributeTablePtr gen_xmlAttributeTablePtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { + return(NULL); +} +static void des_xmlAttributeTablePtr(int no ATTRIBUTE_UNUSED, xmlAttributeTablePtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { +} + static int test_xmlDumpAttributeTable(void) { int test_ret = 0; @@ -25373,6 +25332,13 @@ } +#define gen_nb_xmlElementTablePtr 1 +static xmlElementTablePtr gen_xmlElementTablePtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { + return(NULL); +} +static void des_xmlElementTablePtr(int no ATTRIBUTE_UNUSED, xmlElementTablePtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { +} + static int test_xmlDumpElementTable(void) { int test_ret = 0; @@ -25458,6 +25424,13 @@ } +#define gen_nb_xmlNotationTablePtr 1 +static xmlNotationTablePtr gen_xmlNotationTablePtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { + return(NULL); +} +static void des_xmlNotationTablePtr(int no ATTRIBUTE_UNUSED, xmlNotationTablePtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { +} + static int test_xmlDumpNotationTable(void) { int test_ret = 0; @@ -29389,16 +29362,6 @@ printf("Module xmlIO: %d errors\n", test_ret); return(test_ret); } -#ifdef LIBXML_AUTOMATA_ENABLED - -#define gen_nb_xmlAutomataPtr 1 -static xmlAutomataPtr gen_xmlAutomataPtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { - return(NULL); -} -static void des_xmlAutomataPtr(int no ATTRIBUTE_UNUSED, xmlAutomataPtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { -} -#endif - static int test_xmlAutomataCompile(void) { @@ -29419,6 +29382,16 @@ return(test_ret); } +#ifdef LIBXML_AUTOMATA_ENABLED + +#define gen_nb_xmlAutomataPtr 1 +static xmlAutomataPtr gen_xmlAutomataPtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { + return(NULL); +} +static void des_xmlAutomataPtr(int no ATTRIBUTE_UNUSED, xmlAutomataPtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { +} +#endif + static int test_xmlAutomataIsDeterminist(void) { @@ -29453,16 +29426,6 @@ return(test_ret); } -#ifdef LIBXML_AUTOMATA_ENABLED - -#define gen_nb_xmlAutomataStatePtr 1 -static xmlAutomataStatePtr gen_xmlAutomataStatePtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { - return(NULL); -} -static void des_xmlAutomataStatePtr(int no ATTRIBUTE_UNUSED, xmlAutomataStatePtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { -} -#endif - static int test_xmlAutomataNewAllTrans(void) { @@ -29631,6 +29594,16 @@ return(test_ret); } +#ifdef LIBXML_AUTOMATA_ENABLED + +#define gen_nb_xmlAutomataStatePtr 1 +static xmlAutomataStatePtr gen_xmlAutomataStatePtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { + return(NULL); +} +static void des_xmlAutomataStatePtr(int no ATTRIBUTE_UNUSED, xmlAutomataStatePtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { +} +#endif + static int test_xmlAutomataSetFinalState(void) { @@ -33908,16 +33881,6 @@ return(test_ret); } -#ifdef LIBXML_REGEXP_ENABLED - -#define gen_nb_xmlRegexpPtr 1 -static xmlRegexpPtr gen_xmlRegexpPtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { - return(NULL); -} -static void des_xmlRegexpPtr(int no ATTRIBUTE_UNUSED, xmlRegexpPtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { -} -#endif - static int test_xmlRegNewExecCtxt(void) { @@ -33938,6 +33901,16 @@ return(test_ret); } +#ifdef LIBXML_REGEXP_ENABLED + +#define gen_nb_xmlRegexpPtr 1 +static xmlRegexpPtr gen_xmlRegexpPtr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { + return(NULL); +} +static void des_xmlRegexpPtr(int no ATTRIBUTE_UNUSED, xmlRegexpPtr val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { +} +#endif + static int test_xmlRegexpExec(void) { @@ -34662,16 +34635,6 @@ return(test_ret); } -#ifdef LIBXML_SCHEMAS_ENABLED - -#define gen_nb_xmlSAXHandlerPtr_ptr 1 -static xmlSAXHandlerPtr * gen_xmlSAXHandlerPtr_ptr(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { - return(NULL); -} -static void des_xmlSAXHandlerPtr_ptr(int no ATTRIBUTE_UNUSED, xmlSAXHandlerPtr * val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { -} -#endif - static int test_xmlSchemaSAXPlug(void) {
diff --git a/third_party/libxml/src/testrecurse.c b/third_party/libxml/src/testrecurse.c index f95ae1c..64b9cd0 100644 --- a/third_party/libxml/src/testrecurse.c +++ b/third_party/libxml/src/testrecurse.c
@@ -632,8 +632,8 @@ suffixbuff[0]='_'; #endif - snprintf(res, 499, "%s%s%s", out, base, suffixbuff); - res[499] = 0; + if (snprintf(res, 499, "%s%s%s", out, base, suffixbuff) >= 499) + res[499] = 0; return(strdup(res)); }
diff --git a/third_party/libxml/src/uri.c b/third_party/libxml/src/uri.c index ebbca67..d4f0f5e 100644 --- a/third_party/libxml/src/uri.c +++ b/third_party/libxml/src/uri.c
@@ -2236,25 +2236,8 @@ * First we take care of the special case where either of the * two path components may be missing (bug 316224) */ - if (bas->path == NULL) { - if (ref->path != NULL) { - uptr = (xmlChar *) ref->path; - if (*uptr == '/') - uptr++; - /* exception characters from xmlSaveUri */ - val = xmlURIEscapeStr(uptr, BAD_CAST "/;&=+$,"); - } - goto done; - } bptr = (xmlChar *)bas->path; - if (ref->path == NULL) { - for (ix = 0; bptr[ix] != 0; ix++) { - if (bptr[ix] == '/') - nbslash++; - } - uptr = NULL; - len = 1; /* this is for a string terminator only */ - } else { + { xmlChar *rptr = (xmlChar *) ref->path; int pos = 0; @@ -2280,30 +2263,28 @@ * beginning of the "unique" suffix of URI */ ix = pos; - if ((rptr[ix] == '/') && (ix > 0)) - ix--; - else if ((rptr[ix] == 0) && (ix > 1) && (rptr[ix - 1] == '/')) - ix -= 2; for (; ix > 0; ix--) { - if (rptr[ix] == '/') + if (rptr[ix - 1] == '/') break; } - if (ix == 0) { - uptr = (xmlChar *)rptr; - } else { - ix++; - uptr = (xmlChar *)&rptr[ix]; - } + uptr = (xmlChar *)&rptr[ix]; /* * In base, count the number of '/' from the differing point */ - if (bptr[pos] != rptr[pos]) {/* check for trivial URI == base */ - for (; bptr[ix] != 0; ix++) { - if (bptr[ix] == '/') - nbslash++; - } + for (; bptr[ix] != 0; ix++) { + if (bptr[ix] == '/') + nbslash++; } + + /* + * e.g: URI="foo/" base="foo/bar" -> "./" + */ + if (nbslash == 0 && !uptr[0]) { + val = xmlStrdup(BAD_CAST "./"); + goto done; + } + len = xmlStrlen (uptr) + 1; }
diff --git a/third_party/libxml/src/win32/Makefile.bcb b/third_party/libxml/src/win32/Makefile.bcb index 41002da5..d326fb9 100644 --- a/third_party/libxml/src/win32/Makefile.bcb +++ b/third_party/libxml/src/win32/Makefile.bcb
@@ -225,9 +225,7 @@ $(BINDIR)\testlimits.exe -!if "$(WITH_THREADS)" == "yes" || "$(WITH_THREADS)" == "ctls" || "$(WITH_THREADS)" == "native" -UTILS = $(UTILS) $(BINDIR)\testThreadsWin32.exe -!else if "$(WITH_THREADS)" == "posix" +!if "$(WITH_THREADS)" != "no" UTILS = $(UTILS) $(BINDIR)\testThreads.exe !endif
diff --git a/third_party/libxml/src/win32/Makefile.mingw b/third_party/libxml/src/win32/Makefile.mingw index 3d4cb888..9dfa4ab 100644 --- a/third_party/libxml/src/win32/Makefile.mingw +++ b/third_party/libxml/src/win32/Makefile.mingw
@@ -220,16 +220,7 @@ $(BINDIR)/testapi.exe\ $(BINDIR)/testlimits.exe -ifeq ($(WITH_THREADS),yes) -UTILS += $(BINDIR)/testThreadsWin32.exe -endif -ifeq ($(WITH_THREADS),ctls) -UTILS += $(BINDIR)/testThreadsWin32.exe -endif -ifeq ($(WITH_THREADS),native) -UTILS += $(BINDIR)/testThreadsWin32.exe -endif -ifeq ($(WITH_THREADS),posix) +ifneq ($(WITH_THREADS),no) UTILS += $(BINDIR)/testThreads.exe endif
diff --git a/third_party/libxml/src/win32/Makefile.msvc b/third_party/libxml/src/win32/Makefile.msvc index 491dc880..f6a0182 100644 --- a/third_party/libxml/src/win32/Makefile.msvc +++ b/third_party/libxml/src/win32/Makefile.msvc
@@ -244,6 +244,12 @@ $(XML_INTDIR_A_DLL)\xpointer.obj\ $(XML_INTDIR_A_DLL)\xmlstring.obj +!if "$(WITH_LZMA)" == "1" +XML_OBJS = $(XML_OBJS) $(XML_INTDIR)\xzlib.obj +XML_OBJS_A = $(XML_OBJS_A) $(XML_INTDIR_A)\xzlib.obj +XML_OBJS_A_DLL = $(XML_OBJS_A_DLL) $(XML_INTDIR_A_DLL)\xzlib.obj +!endif + # Xmllint and friends executables. UTILS = $(BINDIR)\xmllint.exe\ $(BINDIR)\xmlcatalog.exe\ @@ -268,9 +274,7 @@ $(BINDIR)\testlimits.exe\ $(BINDIR)\testrecurse.exe -!if "$(WITH_THREADS)" == "yes" || "$(WITH_THREADS)" == "ctls" || "$(WITH_THREADS)" == "native" -UTILS = $(UTILS) $(BINDIR)\testThreadsWin32.exe -!else if "$(WITH_THREADS)" == "posix" +!if "$(WITH_THREADS)" != "no" UTILS = $(UTILS) $(BINDIR)\testThreads.exe !endif
diff --git a/third_party/libxml/src/xmlreader.c b/third_party/libxml/src/xmlreader.c index 4053269..1f6d8f6 100644 --- a/third_party/libxml/src/xmlreader.c +++ b/third_party/libxml/src/xmlreader.c
@@ -32,6 +32,7 @@ #include <libxml/xmlIO.h> #include <libxml/xmlreader.h> #include <libxml/parserInternals.h> + #ifdef LIBXML_SCHEMAS_ENABLED #include <libxml/relaxng.h> #include <libxml/xmlschemas.h> @@ -238,6 +239,8 @@ if (id->value != NULL) DICT_FREE(id->value) + if (id->name != NULL) + DICT_FREE(id->name) xmlFree(id); } @@ -271,6 +274,7 @@ return(-1); } id->name = attr->name; + attr->name = NULL; id->attr = NULL; return(0); } @@ -1112,11 +1116,11 @@ continue; } else { /* - * The error has probably be raised already. + * The error has probably been raised already. */ if (node == oldnode) break; - node = node->next; + goto skip_children; } #ifdef LIBXML_REGEXP_ENABLED } else if (node->type == XML_ELEMENT_NODE) { @@ -1138,6 +1142,7 @@ } else if (node->type == XML_ELEMENT_NODE) { xmlTextReaderValidatePop(reader); } +skip_children: if (node->next != NULL) { node = node->next; continue; @@ -1711,10 +1716,11 @@ if (xmlTextReaderExpand(reader) == NULL) { return NULL; } - doc = reader->doc; + doc = reader->node->doc; buff = xmlBufferCreate(); for (cur_node = reader->node->children; cur_node != NULL; cur_node = cur_node->next) { + /* XXX: Why is the node copied? */ node = xmlDocCopyNode(cur_node, doc, 1); buff2 = xmlBufferCreate(); if (xmlNodeDump(buff2, doc, node, 0, 0) == -1) { @@ -1755,10 +1761,11 @@ xmlDocPtr doc; node = reader->node; - doc = reader->doc; + doc = node->doc; if (xmlTextReaderExpand(reader) == NULL) { return NULL; } + /* XXX: Why is the node copied? */ if (node->type == XML_DTD_NODE) { node = (xmlNodePtr) xmlCopyDtd((xmlDtdPtr) node); } else { @@ -1917,12 +1924,9 @@ /* if reader->node->next is NULL mean no subtree for current node, so need to move to sibling of parent node if present */ - if ((reader->node->type == XML_ELEMENT_NODE) || - (reader->node->type == XML_ATTRIBUTE_NODE)) { - reader->state = XML_TEXTREADER_BACKTRACK; - /* This will move to parent if present */ - xmlTextReaderRead(reader); - } + reader->state = XML_TEXTREADER_BACKTRACK; + /* This will move to parent if present */ + xmlTextReaderRead(reader); } if (reader->node->next != 0) { @@ -2263,17 +2267,21 @@ if (reader->ctxt != NULL) { if (reader->dict == reader->ctxt->dict) reader->dict = NULL; +#ifdef LIBXML_REGEXP_ENABLED + if ((reader->ctxt->vctxt.vstateTab != NULL) && + (reader->ctxt->vctxt.vstateMax > 0)){ + while (reader->ctxt->vctxt.vstateNr > 0) + xmlValidatePopElement(&reader->ctxt->vctxt, NULL, NULL, NULL); + xmlFree(reader->ctxt->vctxt.vstateTab); + reader->ctxt->vctxt.vstateTab = NULL; + reader->ctxt->vctxt.vstateMax = 0; + } +#endif if (reader->ctxt->myDoc != NULL) { if (reader->preserve == 0) xmlTextReaderFreeDoc(reader, reader->ctxt->myDoc); reader->ctxt->myDoc = NULL; } - if ((reader->ctxt->vctxt.vstateTab != NULL) && - (reader->ctxt->vctxt.vstateMax > 0)){ - xmlFree(reader->ctxt->vctxt.vstateTab); - reader->ctxt->vctxt.vstateTab = NULL; - reader->ctxt->vctxt.vstateMax = 0; - } if (reader->allocs & XML_TEXTREADER_CTXT) xmlFreeParserCtxt(reader->ctxt); } @@ -3006,7 +3014,7 @@ * Reference: * http://www.gnu.org/software/dotgnu/pnetlib-doc/System/Xml/XmlNodeType.html * - * Returns the xmlNodeType of the current node or -1 in case of error + * Returns the xmlReaderTypes of the current node or -1 in case of error */ int xmlTextReaderNodeType(xmlTextReaderPtr reader) {
diff --git a/third_party/libxml/src/xmlsave.c b/third_party/libxml/src/xmlsave.c index 6c7418e..7a05d83 100644 --- a/third_party/libxml/src/xmlsave.c +++ b/third_party/libxml/src/xmlsave.c
@@ -1123,9 +1123,6 @@ cur->encoding = BAD_CAST ctxt->encoding; } else if (cur->encoding != NULL) { encoding = cur->encoding; - } else if (cur->charset != XML_CHAR_ENCODING_UTF8) { - encoding = (const xmlChar *) - xmlGetCharEncodingName((xmlCharEncoding) cur->charset); } if (((cur->type == XML_HTML_DOCUMENT_NODE) &&
diff --git a/third_party/libxml/src/xpath.c b/third_party/libxml/src/xpath.c index af9c0b4b..59f2e102 100644 --- a/third_party/libxml/src/xpath.c +++ b/third_party/libxml/src/xpath.c
@@ -2,7 +2,7 @@ * xpath.c: XML Path Language implementation * XPath is a language for addressing parts of an XML document, * designed to be used by both XSLT and XPointer - *f + * * Reference: W3C Recommendation 16 November 1999 * http://www.w3.org/TR/1999/REC-xpath-19991116 * Public reference: @@ -527,9 +527,9 @@ #ifdef isinf return isinf(val) ? (val > 0 ? 1 : -1) : 0; #else - if (val >= HUGE_VAL) + if (val >= INFINITY) return 1; - if (val <= -HUGE_VAL) + if (val <= -INFINITY) return -1; return 0; #endif @@ -868,15 +868,14 @@ XPATH_OP_UNION, XPATH_OP_ROOT, XPATH_OP_NODE, - XPATH_OP_RESET, /* 10 */ XPATH_OP_COLLECT, - XPATH_OP_VALUE, /* 12 */ + XPATH_OP_VALUE, /* 11 */ XPATH_OP_VARIABLE, XPATH_OP_FUNCTION, XPATH_OP_ARG, XPATH_OP_PREDICATE, - XPATH_OP_FILTER, /* 17 */ - XPATH_OP_SORT /* 18 */ + XPATH_OP_FILTER, /* 16 */ + XPATH_OP_SORT /* 17 */ #ifdef LIBXML_XPTR_ENABLED ,XPATH_OP_RANGETO #endif @@ -1526,8 +1525,6 @@ fprintf(output, "ROOT"); break; case XPATH_OP_NODE: fprintf(output, "NODE"); break; - case XPATH_OP_RESET: - fprintf(output, "RESET"); break; case XPATH_OP_SORT: fprintf(output, "SORT"); break; case XPATH_OP_COLLECT: { @@ -8480,9 +8477,8 @@ xmlXPathRoot(xmlXPathParserContextPtr ctxt) { if ((ctxt == NULL) || (ctxt->context == NULL)) return; - ctxt->context->node = (xmlNodePtr) ctxt->context->doc; valuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt->context, - ctxt->context->node)); + (xmlNodePtr) ctxt->context->doc)); } /************************************************************************ @@ -10735,7 +10731,6 @@ PUSH_LONG_EXPR(XPATH_OP_COLLECT, AXIS_DESCENDANT_OR_SELF, NODE_TEST_TYPE, NODE_TYPE_NODE, NULL, NULL); - PUSH_UNARY_EXPR(XPATH_OP_RESET, ctxt->comp->last, 1, 0); xmlXPathCompRelativeLocationPath(ctxt); } else if (CUR == '/') { @@ -11666,6 +11661,7 @@ xmlXPathContextPtr xpctxt = ctxt->context; xmlNodePtr contextNode, oldContextNode; xmlDocPtr oldContextDoc; + int oldcs, oldpp; int i, res, contextPos = 0, newContextSize; xmlXPathStepOpPtr exprOp; xmlXPathObjectPtr contextObj = NULL, exprRes = NULL; @@ -11702,6 +11698,8 @@ */ oldContextNode = xpctxt->node; oldContextDoc = xpctxt->doc; + oldcs = xpctxt->contextSize; + oldpp = xpctxt->proximityPosition; /* * Get the expression of this predicate. */ @@ -11788,8 +11786,8 @@ */ xpctxt->node = oldContextNode; xpctxt->doc = oldContextDoc; - xpctxt->contextSize = -1; - xpctxt->proximityPosition = -1; + xpctxt->contextSize = oldcs; + xpctxt->proximityPosition = oldpp; return(newContextSize); } return(contextSize); @@ -11832,6 +11830,7 @@ return (contextSize); } else { xmlDocPtr oldContextDoc; + int oldcs, oldpp; int i, pos = 0, newContextSize = 0, contextPos = 0, res; xmlXPathStepOpPtr exprOp; xmlXPathObjectPtr contextObj = NULL, exprRes = NULL; @@ -11852,6 +11851,8 @@ */ oldContextNode = xpctxt->node; oldContextDoc = xpctxt->doc; + oldcs = xpctxt->contextSize; + oldpp = xpctxt->proximityPosition; /* * Get the expression of this predicate. */ @@ -11988,8 +11989,8 @@ */ xpctxt->node = oldContextNode; xpctxt->doc = oldContextDoc; - xpctxt->contextSize = -1; - xpctxt->proximityPosition = -1; + xpctxt->contextSize = oldcs; + xpctxt->proximityPosition = oldpp; return(newContextSize); } return(contextSize); @@ -12779,15 +12780,6 @@ valuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node)); return (total); - case XPATH_OP_RESET: - if (op->ch1 != -1) - total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); - CHECK_ERROR0; - if (op->ch2 != -1) - total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); - CHECK_ERROR0; - ctxt->context->node = NULL; - return (total); case XPATH_OP_COLLECT:{ if (op->ch1 == -1) return (total); @@ -12843,10 +12835,6 @@ int total = 0, cur; xmlXPathCompExprPtr comp; xmlXPathObjectPtr arg1, arg2; - xmlNodePtr bak; - xmlDocPtr bakd; - int pp; - int cs; CHECK_ERROR0; comp = ctxt->comp; @@ -12854,10 +12842,6 @@ case XPATH_OP_END: return (0); case XPATH_OP_UNION: - bakd = ctxt->context->doc; - bak = ctxt->context->node; - pp = ctxt->context->proximityPosition; - cs = ctxt->context->contextSize; total = xmlXPathCompOpEvalLast(ctxt, &comp->steps[op->ch1], last); CHECK_ERROR0; @@ -12875,10 +12859,6 @@ nodesetval->nodeNr - 1]; } - ctxt->context->doc = bakd; - ctxt->context->node = bak; - ctxt->context->proximityPosition = pp; - ctxt->context->contextSize = cs; cur = xmlXPathCompOpEvalLast(ctxt, &comp->steps[op->ch2], last); CHECK_ERROR0; @@ -12918,15 +12898,6 @@ valuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node)); return (total); - case XPATH_OP_RESET: - if (op->ch1 != -1) - total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); - CHECK_ERROR0; - if (op->ch2 != -1) - total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); - CHECK_ERROR0; - ctxt->context->node = NULL; - return (total); case XPATH_OP_COLLECT:{ if (op->ch1 == -1) return (0); @@ -12971,6 +12942,7 @@ xmlNodeSetPtr oldset; xmlNodePtr oldnode; xmlDocPtr oldDoc; + int oldcs, oldpp; int i; CHECK_ERROR0; @@ -13022,7 +12994,6 @@ return (total); #ifdef LIBXML_XPTR_ENABLED - oldnode = ctxt->context->node; /* * Hum are we filtering the result of an XPointer expression */ @@ -13037,23 +13008,17 @@ * up a new locset. */ CHECK_TYPE0(XPATH_LOCATIONSET); + + if ((ctxt->value->user == NULL) || + (((xmlLocationSetPtr) ctxt->value->user)->locNr == 0)) + return (total); + obj = valuePop(ctxt); oldlocset = obj->user; - ctxt->context->node = NULL; + oldnode = ctxt->context->node; + oldcs = ctxt->context->contextSize; + oldpp = ctxt->context->proximityPosition; - if ((oldlocset == NULL) || (oldlocset->locNr == 0)) { - ctxt->context->contextSize = 0; - ctxt->context->proximityPosition = 0; - if (op->ch2 != -1) - total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); - res = valuePop(ctxt); - if (res != NULL) { - xmlXPathReleaseObject(ctxt->context, res); - } - valuePush(ctxt, obj); - CHECK_ERROR0; - return (total); - } newlocset = xmlXPtrLocationSetCreate(NULL); for (i = 0; i < oldlocset->locNr; i++) { @@ -13077,8 +13042,8 @@ if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { - xmlXPathFreeObject(obj); - return(0); + xmlXPtrFreeLocationSet(newlocset); + goto xptr_error; } /* * The result of the evaluation need to be tested to @@ -13106,7 +13071,6 @@ /* OLD: xmlXPathFreeObject(res); */ } else tmp = NULL; - ctxt->context->node = NULL; /* * Only put the first node in the result, then leave. */ @@ -13121,12 +13085,12 @@ /* * The result is used as the new evaluation locset. */ - xmlXPathReleaseObject(ctxt->context, obj); - ctxt->context->node = NULL; - ctxt->context->contextSize = -1; - ctxt->context->proximityPosition = -1; valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset)); +xptr_error: + xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = oldnode; + ctxt->context->contextSize = oldcs; + ctxt->context->proximityPosition = oldpp; return (total); } #endif /* LIBXML_XPTR_ENABLED */ @@ -13137,32 +13101,19 @@ * up a new set. */ CHECK_TYPE0(XPATH_NODESET); - obj = valuePop(ctxt); - oldset = obj->nodesetval; - oldnode = ctxt->context->node; - oldDoc = ctxt->context->doc; - ctxt->context->node = NULL; - - if ((oldset == NULL) || (oldset->nodeNr == 0)) { - ctxt->context->contextSize = 0; - ctxt->context->proximityPosition = 0; - /* QUESTION TODO: Why was this code commented out? - if (op->ch2 != -1) - total += - xmlXPathCompOpEval(ctxt, - &comp->steps[op->ch2]); - CHECK_ERROR0; - res = valuePop(ctxt); - if (res != NULL) - xmlXPathFreeObject(res); - */ - valuePush(ctxt, obj); - ctxt->context->node = oldnode; - CHECK_ERROR0; - } else { + if ((ctxt->value->nodesetval != NULL) && + (ctxt->value->nodesetval->nodeNr != 0)) { xmlNodeSetPtr newset; xmlXPathObjectPtr tmp = NULL; + + obj = valuePop(ctxt); + oldset = obj->nodesetval; + oldnode = ctxt->context->node; + oldDoc = ctxt->context->doc; + oldcs = ctxt->context->contextSize; + oldpp = ctxt->context->proximityPosition; + /* * Initialize the new set. * Also set the xpath document in case things like @@ -13196,8 +13147,7 @@ total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeNodeSet(newset); - xmlXPathFreeObject(obj); - return(0); + goto error; } /* * The result of the evaluation needs to be tested to @@ -13224,7 +13174,6 @@ xmlXPathNodeSetClear(tmp->nodesetval, 1); } else tmp = NULL; - ctxt->context->node = NULL; /* * Only put the first node in the result, then leave. */ @@ -13239,15 +13188,14 @@ /* * The result is used as the new evaluation set. */ - xmlXPathReleaseObject(ctxt->context, obj); - ctxt->context->node = NULL; - ctxt->context->contextSize = -1; - ctxt->context->proximityPosition = -1; - /* may want to move this past the '}' later */ - ctxt->context->doc = oldDoc; valuePush(ctxt, xmlXPathCacheWrapNodeSet(ctxt->context, newset)); +error: + xmlXPathReleaseObject(ctxt->context, obj); + ctxt->context->node = oldnode; + ctxt->context->doc = oldDoc; + ctxt->context->contextSize = oldcs; + ctxt->context->proximityPosition = oldpp; } - ctxt->context->node = oldnode; return(total); } #endif /* XP_OPTIMIZED_FILTER_FIRST */ @@ -13267,10 +13215,6 @@ int equal, ret; xmlXPathCompExprPtr comp; xmlXPathObjectPtr arg1, arg2; - xmlNodePtr bak; - xmlDocPtr bakd; - int pp; - int cs; CHECK_ERROR0; comp = ctxt->comp; @@ -13278,68 +13222,42 @@ case XPATH_OP_END: return (0); case XPATH_OP_AND: - bakd = ctxt->context->doc; - bak = ctxt->context->node; - pp = ctxt->context->proximityPosition; - cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; xmlXPathBooleanFunction(ctxt, 1); if ((ctxt->value == NULL) || (ctxt->value->boolval == 0)) return (total); arg2 = valuePop(ctxt); - ctxt->context->doc = bakd; - ctxt->context->node = bak; - ctxt->context->proximityPosition = pp; - ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error) { xmlXPathFreeObject(arg2); return(0); } xmlXPathBooleanFunction(ctxt, 1); - arg1 = valuePop(ctxt); - arg1->boolval &= arg2->boolval; - valuePush(ctxt, arg1); + if (ctxt->value != NULL) + ctxt->value->boolval &= arg2->boolval; xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_OR: - bakd = ctxt->context->doc; - bak = ctxt->context->node; - pp = ctxt->context->proximityPosition; - cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; xmlXPathBooleanFunction(ctxt, 1); if ((ctxt->value == NULL) || (ctxt->value->boolval == 1)) return (total); arg2 = valuePop(ctxt); - ctxt->context->doc = bakd; - ctxt->context->node = bak; - ctxt->context->proximityPosition = pp; - ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error) { xmlXPathFreeObject(arg2); return(0); } xmlXPathBooleanFunction(ctxt, 1); - arg1 = valuePop(ctxt); - arg1->boolval |= arg2->boolval; - valuePush(ctxt, arg1); + if (ctxt->value != NULL) + ctxt->value->boolval |= arg2->boolval; xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_EQUAL: - bakd = ctxt->context->doc; - bak = ctxt->context->node; - pp = ctxt->context->proximityPosition; - cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; - ctxt->context->doc = bakd; - ctxt->context->node = bak; - ctxt->context->proximityPosition = pp; - ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; if (op->value) @@ -13349,33 +13267,17 @@ valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, equal)); return (total); case XPATH_OP_CMP: - bakd = ctxt->context->doc; - bak = ctxt->context->node; - pp = ctxt->context->proximityPosition; - cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; - ctxt->context->doc = bakd; - ctxt->context->node = bak; - ctxt->context->proximityPosition = pp; - ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; ret = xmlXPathCompareValues(ctxt, op->value, op->value2); valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, ret)); return (total); case XPATH_OP_PLUS: - bakd = ctxt->context->doc; - bak = ctxt->context->node; - pp = ctxt->context->proximityPosition; - cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 != -1) { - ctxt->context->doc = bakd; - ctxt->context->node = bak; - ctxt->context->proximityPosition = pp; - ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); } CHECK_ERROR0; @@ -13391,16 +13293,8 @@ } return (total); case XPATH_OP_MULT: - bakd = ctxt->context->doc; - bak = ctxt->context->node; - pp = ctxt->context->proximityPosition; - cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; - ctxt->context->doc = bakd; - ctxt->context->node = bak; - ctxt->context->proximityPosition = pp; - ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; if (op->value == 0) @@ -13411,16 +13305,8 @@ xmlXPathModValues(ctxt); return (total); case XPATH_OP_UNION: - bakd = ctxt->context->doc; - bak = ctxt->context->node; - pp = ctxt->context->proximityPosition; - cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; - ctxt->context->doc = bakd; - ctxt->context->node = bak; - ctxt->context->proximityPosition = pp; - ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; @@ -13457,15 +13343,6 @@ valuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node)); return (total); - case XPATH_OP_RESET: - if (op->ch1 != -1) - total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); - CHECK_ERROR0; - if (op->ch2 != -1) - total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); - CHECK_ERROR0; - ctxt->context->node = NULL; - return (total); case XPATH_OP_COLLECT:{ if (op->ch1 == -1) return (total); @@ -13584,24 +13461,12 @@ return (total); } case XPATH_OP_ARG: - bakd = ctxt->context->doc; - bak = ctxt->context->node; - pp = ctxt->context->proximityPosition; - cs = ctxt->context->contextSize; if (op->ch1 != -1) { total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); - ctxt->context->contextSize = cs; - ctxt->context->proximityPosition = pp; - ctxt->context->node = bak; - ctxt->context->doc = bakd; CHECK_ERROR0; } if (op->ch2 != -1) { total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); - ctxt->context->contextSize = cs; - ctxt->context->proximityPosition = pp; - ctxt->context->node = bak; - ctxt->context->doc = bakd; CHECK_ERROR0; } return (total); @@ -13613,6 +13478,7 @@ xmlNodeSetPtr oldset; xmlNodePtr oldnode; xmlDocPtr oldDoc; + int oldcs, oldpp; int i; /* @@ -13715,8 +13581,6 @@ if (ctxt->value == NULL) return (total); - oldnode = ctxt->context->node; - #ifdef LIBXML_XPTR_ENABLED /* * Hum are we filtering the result of an XPointer expression @@ -13731,25 +13595,17 @@ * up a new locset. */ CHECK_TYPE0(XPATH_LOCATIONSET); + + if ((ctxt->value->user == NULL) || + (((xmlLocationSetPtr) ctxt->value->user)->locNr == 0)) + return (total); + obj = valuePop(ctxt); oldlocset = obj->user; - ctxt->context->node = NULL; + oldnode = ctxt->context->node; + oldcs = ctxt->context->contextSize; + oldpp = ctxt->context->proximityPosition; - if ((oldlocset == NULL) || (oldlocset->locNr == 0)) { - ctxt->context->contextSize = 0; - ctxt->context->proximityPosition = 0; - if (op->ch2 != -1) - total += - xmlXPathCompOpEval(ctxt, - &comp->steps[op->ch2]); - res = valuePop(ctxt); - if (res != NULL) { - xmlXPathReleaseObject(ctxt->context, res); - } - valuePush(ctxt, obj); - CHECK_ERROR0; - return (total); - } newlocset = xmlXPtrLocationSetCreate(NULL); for (i = 0; i < oldlocset->locNr; i++) { @@ -13769,8 +13625,8 @@ xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { - xmlXPathFreeObject(obj); - return(0); + xmlXPtrFreeLocationSet(newlocset); + goto filter_xptr_error; } /* @@ -13794,19 +13650,17 @@ res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } - - ctxt->context->node = NULL; } /* * The result is used as the new evaluation locset. */ - xmlXPathReleaseObject(ctxt->context, obj); - ctxt->context->node = NULL; - ctxt->context->contextSize = -1; - ctxt->context->proximityPosition = -1; valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset)); +filter_xptr_error: + xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = oldnode; + ctxt->context->contextSize = oldcs; + ctxt->context->proximityPosition = oldpp; return (total); } #endif /* LIBXML_XPTR_ENABLED */ @@ -13817,30 +13671,15 @@ * up a new set. */ CHECK_TYPE0(XPATH_NODESET); - obj = valuePop(ctxt); - oldset = obj->nodesetval; - oldnode = ctxt->context->node; - oldDoc = ctxt->context->doc; - ctxt->context->node = NULL; - - if ((oldset == NULL) || (oldset->nodeNr == 0)) { - ctxt->context->contextSize = 0; - ctxt->context->proximityPosition = 0; -/* - if (op->ch2 != -1) - total += - xmlXPathCompOpEval(ctxt, - &comp->steps[op->ch2]); - CHECK_ERROR0; - res = valuePop(ctxt); - if (res != NULL) - xmlXPathFreeObject(res); -*/ - valuePush(ctxt, obj); - ctxt->context->node = oldnode; - CHECK_ERROR0; - } else { + if ((ctxt->value->nodesetval != NULL) && + (ctxt->value->nodesetval->nodeNr != 0)) { + obj = valuePop(ctxt); + oldset = obj->nodesetval; + oldnode = ctxt->context->node; + oldDoc = ctxt->context->doc; + oldcs = ctxt->context->contextSize; + oldpp = ctxt->context->proximityPosition; tmp = NULL; /* * Initialize the new set. @@ -13906,8 +13745,7 @@ &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeNodeSet(newset); - xmlXPathFreeObject(obj); - return(0); + goto filter_error; } /* @@ -13941,23 +13779,21 @@ */ } else tmp = NULL; - ctxt->context->node = NULL; } if (tmp != NULL) xmlXPathReleaseObject(ctxt->context, tmp); /* * The result is used as the new evaluation set. */ - xmlXPathReleaseObject(ctxt->context, obj); - ctxt->context->node = NULL; - ctxt->context->contextSize = -1; - ctxt->context->proximityPosition = -1; - /* may want to move this past the '}' later */ - ctxt->context->doc = oldDoc; valuePush(ctxt, xmlXPathCacheWrapNodeSet(ctxt->context, newset)); +filter_error: + xmlXPathReleaseObject(ctxt->context, obj); + ctxt->context->node = oldnode; + ctxt->context->doc = oldDoc; + ctxt->context->contextSize = oldcs; + ctxt->context->proximityPosition = oldpp; } - ctxt->context->node = oldnode; return (total); } case XPATH_OP_SORT: @@ -13980,6 +13816,9 @@ xmlLocationSetPtr newlocset = NULL; xmlLocationSetPtr oldlocset; xmlNodeSetPtr oldset; + xmlNodePtr oldnode = ctxt->context->node; + int oldcs = ctxt->context->contextSize; + int oldpp = ctxt->context->proximityPosition; int i, j; if (op->ch1 != -1) { @@ -14000,22 +13839,14 @@ * up a new locset. */ CHECK_TYPE0(XPATH_LOCATIONSET); + + if ((ctxt->value->user == NULL) || + (((xmlLocationSetPtr) ctxt->value->user)->locNr == 0)) + return (total); + obj = valuePop(ctxt); oldlocset = obj->user; - if ((oldlocset == NULL) || (oldlocset->locNr == 0)) { - ctxt->context->node = NULL; - ctxt->context->contextSize = 0; - ctxt->context->proximityPosition = 0; - total += xmlXPathCompOpEval(ctxt,&comp->steps[op->ch2]); - res = valuePop(ctxt); - if (res != NULL) { - xmlXPathReleaseObject(ctxt->context, res); - } - valuePush(ctxt, obj); - CHECK_ERROR0; - return (total); - } newlocset = xmlXPtrLocationSetCreate(NULL); for (i = 0; i < oldlocset->locNr; i++) { @@ -14035,8 +13866,8 @@ xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { - xmlXPathFreeObject(obj); - return(0); + xmlXPtrFreeLocationSet(newlocset); + goto rangeto_error; } res = valuePop(ctxt); @@ -14071,14 +13902,11 @@ res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } - - ctxt->context->node = NULL; } } else { /* Not a location set */ CHECK_TYPE0(XPATH_NODESET); obj = valuePop(ctxt); oldset = obj->nodesetval; - ctxt->context->node = NULL; newlocset = xmlXPtrLocationSetCreate(NULL); @@ -14101,8 +13929,8 @@ xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { - xmlXPathFreeObject(obj); - return(0); + xmlXPtrFreeLocationSet(newlocset); + goto rangeto_error; } res = valuePop(ctxt); @@ -14123,8 +13951,6 @@ res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } - - ctxt->context->node = NULL; } } } @@ -14132,11 +13958,12 @@ /* * The result is used as the new evaluation set. */ - xmlXPathReleaseObject(ctxt->context, obj); - ctxt->context->node = NULL; - ctxt->context->contextSize = -1; - ctxt->context->proximityPosition = -1; valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset)); +rangeto_error: + xmlXPathReleaseObject(ctxt->context, obj); + ctxt->context->node = oldnode; + ctxt->context->contextSize = oldcs; + ctxt->context->proximityPosition = oldpp; return (total); } #endif /* LIBXML_XPTR_ENABLED */
diff --git a/third_party/libxml/win32/include/libxml/xmlversion.h b/third_party/libxml/win32/include/libxml/xmlversion.h index e73e434..23989a56 100644 --- a/third_party/libxml/win32/include/libxml/xmlversion.h +++ b/third_party/libxml/win32/include/libxml/xmlversion.h
@@ -29,21 +29,21 @@ * * the version string like "1.2.3" */ -#define LIBXML_DOTTED_VERSION "2.9.8" +#define LIBXML_DOTTED_VERSION "2.9.9" /** * LIBXML_VERSION: * * the version number: 1.2.3 value is 10203 */ -#define LIBXML_VERSION 20908 +#define LIBXML_VERSION 20909 /** * LIBXML_VERSION_STRING: * * the version number string, 1.2.3 value is "10203" */ -#define LIBXML_VERSION_STRING "20908" +#define LIBXML_VERSION_STRING "20909" /** * LIBXML_VERSION_EXTRA: @@ -58,7 +58,7 @@ * Macro to check that the libxml version in use is compatible with * the version the software has been compiled against */ -#define LIBXML_TEST_VERSION xmlCheckVersion(20908); +#define LIBXML_TEST_VERSION xmlCheckVersion(20909); #ifndef VMS #if 0 @@ -388,7 +388,7 @@ * * the string suffix used by dynamic modules (usually shared libraries) */ -#define LIBXML_MODULE_EXTENSION ".dll" +#define LIBXML_MODULE_EXTENSION ".dll" #endif /**
diff --git a/third_party/libxslt/README.chromium b/third_party/libxslt/README.chromium index ab21800..4a5ebe3 100644 --- a/third_party/libxslt/README.chromium +++ b/third_party/libxslt/README.chromium
@@ -1,6 +1,6 @@ Name: libxslt URL: http://xmlsoft.org/XSLT -Version: 840c8e2b6ab33a02374d7a097868649e492da768 +Version: d1a26a3ff708f3f477bc3f6ef35691fb96be7520 Security Critical: yes License: MIT License File: src/Copyright
diff --git a/third_party/libxslt/chromium/roll.py b/third_party/libxslt/chromium/roll.py index 0f97d85..352bbd6 100755 --- a/third_party/libxslt/chromium/roll.py +++ b/third_party/libxslt/chromium/roll.py
@@ -27,13 +27,10 @@ # Prerequisites: # # 1. Check out Chromium somewhere on Linux, Mac and Windows. -# 2. On each machine, add the experimental remote named 'wip': -# git remote add -f wip \ -# https://chromium.googlesource.com/experimental/chromium/src -# 3. On Linux: +# 2. On Linux: # a. sudo apt-get install libicu-dev -# b. git clone git://git.gnome.org/libxslt somewhere -# 4. On Mac, install these MacPorts: +# b. git clone https://gitlab.gnome.org/GNOME/libxslt.git somewhere +# 3. On Mac, install these MacPorts: # autoconf automake libtool pkgconfig icu # # Procedure: @@ -53,21 +50,18 @@ # head; modify the patch files, this script, and # README.chromium; then commit the result and run it again. # -# b. git push -f wip HEAD:refs/wip/$USER/roll_libxslt +# b. Upload a Cl but do not start review # # 2. On Windows, in the Chromium src directory: -# a. git fetch wip refs/wip/$USER/roll_libxslt -# b. git checkout FETCH_HEAD -# c. third_party\libxslt\chromium\roll.py --win32 -# d. git push -f wip HEAD:refs/wip/$USER/roll_libxslt +# a. git cl patch <Gerrit Issue ID> +# b. third_party\libxslt\chromium\roll.py --win32 +# c. git cl upload # # 3. On Mac, in the Chromium src directory: -# a. git fetch wip refs/wip/$USER/roll_libxslt -# b. git checkout -b roll_libxslt_nnnn FETCH_HEAD -# c. git branch --set-upstream-to origin/master -# d. third_party/libxslt/chromium/roll.py --mac -# e. Make and commit any final changes to README.chromium, BUILD.gn, etc. -# f. Complete the code review process as usual: git cl upload -d; +# a. git cl patch <Gerrit Issue ID> +# b. third_party/libxslt/chromium/roll.py --mac +# c. Make and commit any final changes to README.chromium, BUILD.gn, etc. +# d. Complete the code review process as usual: git cl upload -d; # git cl try-results; etc. PATCHES = [ @@ -88,6 +82,7 @@ ('--without-debugger', 'debugger=no'), ('--without-mem-debug', 'mem_debug=no'), ('--without-plugins', 'modules=no'), + ('--without-crypto', 'crypto=no'), ] # These options are only available in configure.ac for Linux and Mac.
diff --git a/third_party/libxslt/linux/config.h b/third_party/libxslt/linux/config.h index 1e2ec15..bdd8fef 100644 --- a/third_party/libxslt/linux/config.h +++ b/third_party/libxslt/linux/config.h
@@ -32,7 +32,7 @@ #define HAVE_FTIME 1 /* Define if gcrypt library is available. */ -#define HAVE_GCRYPT 1 +/* #undef HAVE_GCRYPT */ /* Define to 1 if you have the `gettimeofday' function. */ #define HAVE_GETTIMEOFDAY 1 @@ -161,7 +161,7 @@ #define PACKAGE_NAME "libxslt" /* Define to the full name and version of this package. */ -#define PACKAGE_STRING "libxslt 1.1.32" +#define PACKAGE_STRING "libxslt 1.1.33" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "libxslt" @@ -170,7 +170,7 @@ #define PACKAGE_URL "" /* Define to the version of this package. */ -#define PACKAGE_VERSION "1.1.32" +#define PACKAGE_VERSION "1.1.33" /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 @@ -198,7 +198,7 @@ /* Version number of package */ -#define VERSION "1.1.32" +#define VERSION "1.1.33" /* Define if debugging support is enabled */ /* #undef WITH_DEBUGGER */ @@ -212,12 +212,3 @@ /* Define to 1 if you need to in order for `stat' and other things to work. */ /* #undef _POSIX_SOURCE */ - -/* Using the Win32 Socket implementation */ -/* #undef _WINSOCKAPI_ */ - -/* Win32 Std C name mangling work-around */ -/* #undef snprintf */ - -/* Win32 Std C name mangling work-around */ -/* #undef vsnprintf */
diff --git a/third_party/libxslt/linux/libexslt/exsltconfig.h b/third_party/libxslt/linux/libexslt/exsltconfig.h index d1745c4..443ee094 100644 --- a/third_party/libxslt/linux/libexslt/exsltconfig.h +++ b/third_party/libxslt/linux/libexslt/exsltconfig.h
@@ -18,7 +18,7 @@ * * the version string like "1.2.3" */ -#define LIBEXSLT_DOTTED_VERSION "1.1.32" +#define LIBEXSLT_DOTTED_VERSION "1.1.33" /** * LIBEXSLT_VERSION: @@ -46,7 +46,7 @@ * * Whether crypto support is configured into exslt */ -#if 1 +#if 0 #define EXSLT_CRYPTO_ENABLED #endif
diff --git a/third_party/libxslt/linux/libxslt/xsltwin32config.h b/third_party/libxslt/linux/libxslt/xsltwin32config.h index 3feb1fd..ceccadc 100644 --- a/third_party/libxslt/linux/libxslt/xsltwin32config.h +++ b/third_party/libxslt/linux/libxslt/xsltwin32config.h
@@ -23,21 +23,21 @@ * * the version string like "1.2.3" */ -#define LIBXSLT_DOTTED_VERSION "1.1.32" +#define LIBXSLT_DOTTED_VERSION "1.1.33" /** * LIBXSLT_VERSION: * * the version number: 1.2.3 value is 1002003 */ -#define LIBXSLT_VERSION 10132 +#define LIBXSLT_VERSION 10133 /** * LIBXSLT_VERSION_STRING: * * the version number string, 1.2.3 value is "1002003" */ -#define LIBXSLT_VERSION_STRING "10132" +#define LIBXSLT_VERSION_STRING "10133" /** * LIBXSLT_VERSION_EXTRA:
diff --git a/third_party/libxslt/mac/config.h b/third_party/libxslt/mac/config.h index 5bd3ea6..04d8185 100644 --- a/third_party/libxslt/mac/config.h +++ b/third_party/libxslt/mac/config.h
@@ -1,5 +1,5 @@ /* config.h. Generated from config.h.in by configure. */ -/* config.h.in. Generated from configure.in by autoheader. */ +/* config.h.in. Generated from configure.ac by autoheader. */ /* Define to 1 if you have the <ansidecl.h> header file. */ /* #undef HAVE_ANSIDECL_H */ @@ -161,7 +161,7 @@ #define PACKAGE_NAME "libxslt" /* Define to the full name and version of this package. */ -#define PACKAGE_STRING "libxslt 1.1.32" +#define PACKAGE_STRING "libxslt 1.1.33" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "libxslt" @@ -170,7 +170,7 @@ #define PACKAGE_URL "" /* Define to the version of this package. */ -#define PACKAGE_VERSION "1.1.32" +#define PACKAGE_VERSION "1.1.33" /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 @@ -198,7 +198,7 @@ /* Version number of package */ -#define VERSION "1.1.32" +#define VERSION "1.1.33" /* Define if debugging support is enabled */ /* #undef WITH_DEBUGGER */ @@ -212,12 +212,3 @@ /* Define to 1 if you need to in order for `stat' and other things to work. */ /* #undef _POSIX_SOURCE */ - -/* Using the Win32 Socket implementation */ -/* #undef _WINSOCKAPI_ */ - -/* Win32 Std C name mangling work-around */ -/* #undef snprintf */ - -/* Win32 Std C name mangling work-around */ -/* #undef vsnprintf */
diff --git a/third_party/libxslt/src/config.h.in b/third_party/libxslt/src/config.h.in index 86162f8..62d5ce6 100644 --- a/third_party/libxslt/src/config.h.in +++ b/third_party/libxslt/src/config.h.in
@@ -1,4 +1,4 @@ -/* config.h.in. Generated from configure.in by autoheader. */ +/* config.h.in. Generated from configure.ac by autoheader. */ /* Define to 1 if you have the <ansidecl.h> header file. */ #undef HAVE_ANSIDECL_H @@ -211,12 +211,3 @@ /* Define to 1 if you need to in order for `stat' and other things to work. */ #undef _POSIX_SOURCE - -/* Using the Win32 Socket implementation */ -#undef _WINSOCKAPI_ - -/* Win32 Std C name mangling work-around */ -#undef snprintf - -/* Win32 Std C name mangling work-around */ -#undef vsnprintf
diff --git a/third_party/libxslt/src/configure.ac b/third_party/libxslt/src/configure.ac index 9f40d9aa..60c3ba0 100644 --- a/third_party/libxslt/src/configure.ac +++ b/third_party/libxslt/src/configure.ac
@@ -3,7 +3,7 @@ m4_define([MAJOR_VERSION], [1]) m4_define([MINOR_VERSION], [1]) -m4_define([MICRO_VERSION], [32]) +m4_define([MICRO_VERSION], [33]) AC_INIT([libxslt], [MAJOR_VERSION.MINOR_VERSION.MICRO_VERSION]) AC_CONFIG_SRCDIR([libxslt/xslt.c]) @@ -579,22 +579,11 @@ LIBXSLT_DEFAULT_PLUGINS_PATH="$expanded_libdir/libxslt-plugins" AC_SUBST(LIBXSLT_DEFAULT_PLUGINS_PATH) -WIN32_EXTRA_LIBADD= -WIN32_EXTRA_LDFLAGS= case "$host" in - *-*-cygwin*) - WIN32_EXTRA_LDFLAGS="-no-undefined" - ;; - *-*-mingw*) - WIN32_EXTRA_LIBADD="-lwsock32" - WIN32_EXTRA_LDFLAGS="-no-undefined" - AC_DEFINE([_WINSOCKAPI_],1,[Using the Win32 Socket implementation]) - AC_DEFINE([snprintf],[_snprintf],[Win32 Std C name mangling work-around]) - AC_DEFINE([vsnprintf],[_vsnprintf],[Win32 Std C name mangling work-around]) + *-*-cygwin*|*-*-mingw*) + LDFLAGS="$LDFLAGS -no-undefined" ;; esac -AC_SUBST(WIN32_EXTRA_LIBADD) -AC_SUBST(WIN32_EXTRA_LDFLAGS) AC_SUBST(XSLTPROCDV) @@ -670,7 +659,6 @@ tests/exslt/strings/Makefile tests/exslt/date/Makefile tests/exslt/dynamic/Makefile -tests/exslt/crypto/Makefile tests/plugins/Makefile doc/Makefile xslt-config
diff --git a/third_party/libxslt/src/libexslt/Makefile.am b/third_party/libxslt/src/libexslt/Makefile.am index 5449524..de1104c 100644 --- a/third_party/libxslt/src/libexslt/Makefile.am +++ b/third_party/libxslt/src/libexslt/Makefile.am
@@ -28,7 +28,7 @@ dynamic.c libexslt_la_LIBADD = $(top_builddir)/libxslt/libxslt.la $(EXTRA_LIBS) $(LIBGCRYPT_LIBS) $(M_LIBS) -libexslt_la_LDFLAGS = $(WIN32_EXTRA_LDFLAGS) -version-info $(LIBEXSLT_VERSION_INFO) +libexslt_la_LDFLAGS = -version-info $(LIBEXSLT_VERSION_INFO) man_MANS = libexslt.3
diff --git a/third_party/libxslt/src/libexslt/exsltexports.h b/third_party/libxslt/src/libexslt/exsltexports.h index bead915..eee8222 100644 --- a/third_party/libxslt/src/libexslt/exsltexports.h +++ b/third_party/libxslt/src/libexslt/exsltexports.h
@@ -111,8 +111,8 @@ #endif #endif -/* Cygwin platform, GNU compiler */ -#if defined(_WIN32) && defined(__CYGWIN__) +/* Cygwin platform (does not define _WIN32), GNU compiler */ +#if defined(__CYGWIN__) #undef EXSLTPUBFUN #undef EXSLTPUBVAR #undef EXSLTCALL @@ -124,7 +124,7 @@ #if !defined(LIBEXSLT_STATIC) #define EXSLTPUBVAR __declspec(dllimport) extern #else - #define EXSLTPUBVAR + #define EXSLTPUBVAR extern #endif #endif #define EXSLTCALL __cdecl
diff --git a/third_party/libxslt/src/libexslt/functions.c b/third_party/libxslt/src/libexslt/functions.c index 74dea1a..41d37493 100644 --- a/third_party/libxslt/src/libexslt/functions.c +++ b/third_party/libxslt/src/libexslt/functions.c
@@ -34,6 +34,7 @@ struct _exsltFuncData { xmlHashTablePtr funcs; /* pointer to the stylesheet module data */ xmlXPathObjectPtr result; /* returned by func:result */ + xsltStackElemPtr ctxtVar; /* context variable */ int error; /* did an error occur? */ }; @@ -290,8 +291,9 @@ xmlXPathObjectPtr oldResult, ret; exsltFuncData *data; exsltFuncFunctionData *func; - xmlNodePtr paramNode, oldInsert, fake; + xmlNodePtr paramNode, oldInsert, oldXPNode, fake; int oldBase; + void *oldCtxtVar; xsltStackElemPtr params = NULL, param; xsltTransformContextPtr tctxt = xsltXPathGetTransformContext(ctxt); int i, notSet; @@ -358,6 +360,9 @@ } tctxt->depth++; + /* Evaluating templates can change the XPath context node. */ + oldXPNode = tctxt->xpathCtxt->node; + /* * We have a problem with the evaluation of function parameters. * The original library code did not evaluate XPath expressions until @@ -425,19 +430,26 @@ } } /* - * actual processing + * Actual processing. The context variable is cleared and restored + * when func:result is evaluated. */ fake = xmlNewDocNode(tctxt->output, NULL, (const xmlChar *)"fake", NULL); oldInsert = tctxt->insert; + oldCtxtVar = data->ctxtVar; + data->ctxtVar = tctxt->contextVariable; tctxt->insert = fake; + tctxt->contextVariable = NULL; xsltApplyOneTemplate (tctxt, tctxt->node, func->content, NULL, NULL); xsltLocalVariablePop(tctxt, tctxt->varsBase, -2); tctxt->insert = oldInsert; + tctxt->contextVariable = data->ctxtVar; tctxt->varsBase = oldBase; /* restore original scope */ + data->ctxtVar = oldCtxtVar; if (params != NULL) xsltFreeStackElemList(params); + tctxt->xpathCtxt->node = oldXPNode; if (data->error != 0) goto error; @@ -468,6 +480,7 @@ "executing a function\n", ctxt->context->functionURI, ctxt->context->function); xmlFreeNode(fake); + xmlXPathFreeObject(ret); goto error; } xmlFreeNode(fake); @@ -703,6 +716,11 @@ return; } /* + * Restore context variable, so that it will receive the function + * result RVTs. + */ + ctxt->contextVariable = data->ctxtVar; + /* * Processing */ if (comp->select != NULL) { @@ -762,6 +780,7 @@ return; } /* Mark as function result. */ + xsltRegisterLocalRVT(ctxt, container); container->psvi = XSLT_RVT_FUNC_RESULT; oldInsert = ctxt->insert;
diff --git a/third_party/libxslt/src/libxslt.spec b/third_party/libxslt/src/libxslt.spec index 1610143..f2d797b2 100644 --- a/third_party/libxslt/src/libxslt.spec +++ b/third_party/libxslt/src/libxslt.spec
@@ -1,6 +1,6 @@ Summary: Library providing the GNOME XSLT engine Name: libxslt -Version: 1.1.32 +Version: 1.1.33 Release: 1%{?dist}%{?extra_release} License: MIT Group: Development/Libraries @@ -129,5 +129,5 @@ %doc python/tests/*.xsl %changelog -* Fri Dec 15 2017 Daniel Veillard <veillard@redhat.com> -- upstream release 1.1.32 see http://xmlsoft.org/XSLT/news.html +* Wed Feb 20 2019 Daniel Veillard <veillard@redhat.com> +- upstream release 1.1.33 see http://xmlsoft.org/XSLT/news.html
diff --git a/third_party/libxslt/src/libxslt/Makefile.am b/third_party/libxslt/src/libxslt/Makefile.am index ef2de24..22dbdef 100644 --- a/third_party/libxslt/src/libxslt/Makefile.am +++ b/third_party/libxslt/src/libxslt/Makefile.am
@@ -64,7 +64,6 @@ libxslt_la_LIBADD = $(LIBXML_LIBS) $(EXTRA_LIBS) $(M_LIBS) libxslt_la_LDFLAGS = \ - $(WIN32_EXTRA_LDFLAGS) \ $(LIBXSLT_VERSION_SCRIPT) \ -version-info $(LIBXSLT_VERSION_INFO)
diff --git a/third_party/libxslt/src/libxslt/numbers.c b/third_party/libxslt/src/libxslt/numbers.c index 0d34740..89e1f668 100644 --- a/third_party/libxslt/src/libxslt/numbers.c +++ b/third_party/libxslt/src/libxslt/numbers.c
@@ -646,42 +646,51 @@ { int amount = 0; int cnt; + xmlNodePtr oldCtxtNode; xmlNodePtr ancestor; xmlNodePtr preceding; xmlXPathParserContextPtr parser; - context->xpathCtxt->node = node; + oldCtxtNode = context->xpathCtxt->node; parser = xmlXPathNewParserContext(NULL, context->xpathCtxt); if (parser) { /* ancestor-or-self::*[count] */ - for (ancestor = node; - (ancestor != NULL) && (ancestor->type != XML_DOCUMENT_NODE); - ancestor = xmlXPathNextAncestor(parser, ancestor)) { - + ancestor = node; + while ((ancestor != NULL) && (ancestor->type != XML_DOCUMENT_NODE)) { if ((fromPat != NULL) && xsltTestCompMatchList(context, ancestor, fromPat)) break; /* for */ + /* + * The xmlXPathNext* iterators require that the context node is + * set to the start node. Calls to xsltTestCompMatch* may also + * leave the context node in an undefined state, so make sure + * that the context node is reset before each iterator invocation. + */ + if (xsltTestCompMatchCount(context, ancestor, countPat, node)) { /* count(preceding-sibling::*) */ cnt = 1; - for (preceding = - xmlXPathNextPrecedingSibling(parser, ancestor); - preceding != NULL; - preceding = - xmlXPathNextPrecedingSibling(parser, preceding)) { - + context->xpathCtxt->node = ancestor; + preceding = xmlXPathNextPrecedingSibling(parser, ancestor); + while (preceding != NULL) { if (xsltTestCompMatchCount(context, preceding, countPat, node)) cnt++; + context->xpathCtxt->node = ancestor; + preceding = + xmlXPathNextPrecedingSibling(parser, preceding); } array[amount++] = (double)cnt; if (amount >= max) break; /* for */ } + context->xpathCtxt->node = node; + ancestor = xmlXPathNextAncestor(parser, ancestor); } xmlXPathFreeParserContext(parser); } + context->xpathCtxt->node = oldCtxtNode; return amount; }
diff --git a/third_party/libxslt/src/libxslt/pattern.c b/third_party/libxslt/src/libxslt/pattern.c index 07f11f9b..7d66019 100644 --- a/third_party/libxslt/src/libxslt/pattern.c +++ b/third_party/libxslt/src/libxslt/pattern.c
@@ -113,6 +113,7 @@ xmlNsPtr *nsList; /* the namespaces in scope */ int nsNr; /* the number of namespaces in scope */ xsltStepOpPtr steps; /* ops for computation */ + int novar; /* doesn't contain variables */ }; typedef struct _xsltParserContext xsltParserContext; @@ -594,7 +595,8 @@ } ix = 0; - if ((parent == NULL) || (node->doc == NULL) || isRVT) + if ((parent == NULL) || (node->doc == NULL) || isRVT || + (comp->novar == 0)) nocache = 1; if (nocache == 0) { @@ -1970,6 +1972,7 @@ j++; } element->nsNr = j; + element->novar = novar; #ifdef WITH_XSLT_DEBUG_PATTERN
diff --git a/third_party/libxslt/src/libxslt/security.c b/third_party/libxslt/src/libxslt/security.c index 7d4bda2..8e47d4b 100644 --- a/third_party/libxslt/src/libxslt/security.c +++ b/third_party/libxslt/src/libxslt/security.c
@@ -385,16 +385,18 @@ (xmlStrEqual(BAD_CAST uri->scheme, BAD_CAST "file"))) { #if defined(_WIN32) && !defined(__CYGWIN__) - if ((uri->path)&&(uri->path[0]=='/')&& - (uri->path[1]!='\0')&&(uri->path[2]==':')) - ret = xsltCheckWritePath(sec, ctxt, uri->path+1); - else + if ((uri->path)&&(uri->path[0]=='/')&& + (uri->path[1]!='\0')&&(uri->path[2]==':')) + ret = xsltCheckWritePath(sec, ctxt, uri->path+1); + else #endif + { + /* + * Check if we are allowed to write this file + */ + ret = xsltCheckWritePath(sec, ctxt, uri->path); + } - /* - * Check if we are allowed to write this file - */ - ret = xsltCheckWritePath(sec, ctxt, uri->path); if (ret <= 0) { xmlFreeURI(uri); return(ret);
diff --git a/third_party/libxslt/src/libxslt/templates.c b/third_party/libxslt/src/libxslt/templates.c index 42559210..88547ed8 100644 --- a/third_party/libxslt/src/libxslt/templates.c +++ b/third_party/libxslt/src/libxslt/templates.c
@@ -645,11 +645,12 @@ xsltAttrListTemplateProcess(xsltTransformContextPtr ctxt, xmlNodePtr target, xmlAttrPtr attrs) { - xmlAttrPtr attr, copy, last; + xmlAttrPtr attr, copy, last = NULL; xmlNodePtr oldInsert, text; xmlNsPtr origNs = NULL, copyNs = NULL; const xmlChar *value; xmlChar *valueAVT; + int hasAttr = 0; if ((ctxt == NULL) || (target == NULL) || (attrs == NULL) || (target->type != XML_ELEMENT_NODE)) @@ -659,15 +660,34 @@ ctxt->insert = target; /* + * Apply attribute-sets. + */ + attr = attrs; + do { +#ifdef XSLT_REFACTORED + if ((attr->psvi == xsltXSLTAttrMarker) && + xmlStrEqual(attr->name, (const xmlChar *)"use-attribute-sets")) + { + xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL); + } +#else + if ((attr->ns != NULL) && + xmlStrEqual(attr->name, (const xmlChar *)"use-attribute-sets") && + xmlStrEqual(attr->ns->href, XSLT_NAMESPACE)) + { + xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL); + } +#endif + attr = attr->next; + } while (attr != NULL); + + if (target->properties != NULL) { + hasAttr = 1; + } + + /* * Instantiate LRE-attributes. */ - if (target->properties) { - last = target->properties; - while (last->next != NULL) - last = last->next; - } else { - last = NULL; - } attr = attrs; do { /* @@ -703,35 +723,7 @@ value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0); /* - * Create a new attribute. - */ - copy = xmlNewDocProp(target->doc, attr->name, NULL); - if (copy == NULL) { - if (attr->ns) { - xsltTransformError(ctxt, NULL, attr->parent, - "Internal error: Failed to create attribute '{%s}%s'.\n", - attr->ns->href, attr->name); - } else { - xsltTransformError(ctxt, NULL, attr->parent, - "Internal error: Failed to create attribute '%s'.\n", - attr->name); - } - goto error; - } - /* - * Attach it to the target element. - */ - copy->parent = target; - if (last == NULL) { - target->properties = copy; - last = copy; - } else { - last->next = copy; - copy->prev = last; - last = copy; - } - /* - * Set the namespace. Avoid lookups of same namespaces. + * Get the namespace. Avoid lookups of same namespaces. */ if (attr->ns != origNs) { origNs = attr->ns; @@ -748,7 +740,47 @@ } else copyNs = NULL; } - copy->ns = copyNs; + /* + * Create a new attribute. + */ + if (hasAttr) { + copy = xmlSetNsProp(target, copyNs, attr->name, NULL); + } else { + /* + * Avoid checking for duplicate attributes if there aren't + * any attribute sets. + */ + copy = xmlNewDocProp(target->doc, attr->name, NULL); + + if (copy != NULL) { + copy->ns = copyNs; + + /* + * Attach it to the target element. + */ + copy->parent = target; + if (last == NULL) { + target->properties = copy; + last = copy; + } else { + last->next = copy; + copy->prev = last; + last = copy; + } + } + } + if (copy == NULL) { + if (attr->ns) { + xsltTransformError(ctxt, NULL, attr->parent, + "Internal error: Failed to create attribute '{%s}%s'.\n", + attr->ns->href, attr->name); + } else { + xsltTransformError(ctxt, NULL, attr->parent, + "Internal error: Failed to create attribute '%s'.\n", + attr->name); + } + goto error; + } /* * Set the value. @@ -803,30 +835,6 @@ attr = attr->next; } while (attr != NULL); - /* - * Apply attribute-sets. - * The creation of such attributes will not overwrite any existing - * attribute. - */ - attr = attrs; - do { -#ifdef XSLT_REFACTORED - if ((attr->psvi == xsltXSLTAttrMarker) && - xmlStrEqual(attr->name, (const xmlChar *)"use-attribute-sets")) - { - xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL); - } -#else - if ((attr->ns != NULL) && - xmlStrEqual(attr->name, (const xmlChar *)"use-attribute-sets") && - xmlStrEqual(attr->ns->href, XSLT_NAMESPACE)) - { - xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL); - } -#endif - attr = attr->next; - } while (attr != NULL); - ctxt->insert = oldInsert; return(target->properties);
diff --git a/third_party/libxslt/src/libxslt/transform.c b/third_party/libxslt/src/libxslt/transform.c index 90d2731..1379391 100644 --- a/third_party/libxslt/src/libxslt/transform.c +++ b/third_party/libxslt/src/libxslt/transform.c
@@ -2301,6 +2301,11 @@ if (cur->prev != NULL) xsltTransformError(ctxt, NULL, NULL, "localRVT not head of list\n"); + /* Reset localRVT early because some RVTs might be registered again. */ + ctxt->localRVT = base; + if (base != NULL) + base->prev = NULL; + do { tmp = cur; cur = (xmlDocPtr) cur->next; @@ -2308,16 +2313,19 @@ xsltReleaseRVT(ctxt, tmp); } else if (tmp->psvi == XSLT_RVT_GLOBAL) { xsltRegisterPersistRVT(ctxt, tmp); - } else if (tmp->psvi != XSLT_RVT_FUNC_RESULT) { + } else if (tmp->psvi == XSLT_RVT_FUNC_RESULT) { + /* + * This will either register the RVT again or move it to the + * context variable. + */ + xsltRegisterLocalRVT(ctxt, tmp); + tmp->psvi = XSLT_RVT_FUNC_RESULT; + } else { xmlGenericError(xmlGenericErrorContext, "xsltReleaseLocalRVTs: Unexpected RVT flag %p\n", tmp->psvi); } } while (cur != base); - - if (base != NULL) - base->prev = NULL; - ctxt->localRVT = base; } /** @@ -6003,6 +6011,13 @@ res->encoding = xmlStrdup(encoding); variables = style->variables; + ctxt->node = (xmlNodePtr) doc; + ctxt->output = res; + + ctxt->xpathCtxt->contextSize = 1; + ctxt->xpathCtxt->proximityPosition = 1; + ctxt->xpathCtxt->node = NULL; /* TODO: Set the context node here? */ + /* * Start the evaluation, evaluate the params, the stylesheets globals * and start by processing the top node. @@ -6012,7 +6027,6 @@ /* * Evaluate global params and user-provided params. */ - ctxt->node = (xmlNodePtr) doc; if (ctxt->globalVars == NULL) ctxt->globalVars = xmlHashCreate(20); if (params != NULL) { @@ -6027,14 +6041,9 @@ /* Clean up any unused RVTs. */ xsltReleaseLocalRVTs(ctxt, NULL); - ctxt->node = (xmlNodePtr) doc; - ctxt->output = res; ctxt->insert = (xmlNodePtr) res; ctxt->varsBase = ctxt->varsNr - 1; - ctxt->xpathCtxt->contextSize = 1; - ctxt->xpathCtxt->proximityPosition = 1; - ctxt->xpathCtxt->node = NULL; /* TODO: Set the context node here? */ /* * Start processing the source tree ----------------------------------- */
diff --git a/third_party/libxslt/src/libxslt/variables.c b/third_party/libxslt/src/libxslt/variables.c index fe6f299c..8f88e57 100644 --- a/third_party/libxslt/src/libxslt/variables.c +++ b/third_party/libxslt/src/libxslt/variables.c
@@ -123,7 +123,7 @@ return(-1); RVT->prev = NULL; - RVT->psvi = XSLT_RVT_VARIABLE; + RVT->psvi = XSLT_RVT_LOCAL; /* * We'll restrict the lifetime of user-created fragments @@ -163,6 +163,7 @@ return(-1); RVT->prev = NULL; + RVT->psvi = XSLT_RVT_LOCAL; /* * When evaluating "select" expressions of xsl:variable @@ -173,7 +174,6 @@ if ((ctxt->contextVariable != NULL) && (XSLT_TCTXT_VARIABLE(ctxt)->flags & XSLT_VAR_IN_SELECT)) { - RVT->psvi = XSLT_RVT_VARIABLE; RVT->next = (xmlNodePtr) XSLT_TCTXT_VARIABLE(ctxt)->fragment; XSLT_TCTXT_VARIABLE(ctxt)->fragment = RVT; return(0); @@ -183,7 +183,6 @@ * If not reference by a returning instruction (like EXSLT's function), * then this fragment will be freed, when the instruction exits. */ - RVT->psvi = XSLT_RVT_LOCAL; RVT->next = (xmlNodePtr) ctxt->localRVT; if (ctxt->localRVT != NULL) ctxt->localRVT->prev = (xmlNodePtr) RVT; @@ -314,14 +313,8 @@ #endif if (val == XSLT_RVT_LOCAL) { - if (doc->psvi != XSLT_RVT_FUNC_RESULT) { - xmlGenericError(xmlGenericErrorContext, - "xsltFlagRVTs: Invalid transition %p => LOCAL\n", - doc->psvi); - return(-1); - } - - xsltRegisterLocalRVT(ctxt, doc); + if (doc->psvi == XSLT_RVT_FUNC_RESULT) + doc->psvi = XSLT_RVT_LOCAL; } else if (val == XSLT_RVT_GLOBAL) { if (doc->psvi != XSLT_RVT_LOCAL) { xmlGenericError(xmlGenericErrorContext, @@ -585,10 +578,12 @@ cur = elem->fragment; elem->fragment = (xmlDocPtr) cur->next; - if (cur->psvi == XSLT_RVT_VARIABLE) { - xsltReleaseRVT((xsltTransformContextPtr) elem->context, - cur); - } else if (cur->psvi != XSLT_RVT_FUNC_RESULT) { + if (cur->psvi == XSLT_RVT_LOCAL) { + xsltReleaseRVT(elem->context, cur); + } else if (cur->psvi == XSLT_RVT_FUNC_RESULT) { + xsltRegisterLocalRVT(elem->context, cur); + cur->psvi = XSLT_RVT_FUNC_RESULT; + } else { xmlGenericError(xmlGenericErrorContext, "xsltFreeStackElem: Unexpected RVT flag %p\n", cur->psvi); @@ -992,7 +987,7 @@ * the Result Tree Fragment. */ variable->fragment = container; - container->psvi = XSLT_RVT_VARIABLE; + container->psvi = XSLT_RVT_LOCAL; oldOutput = ctxt->output; oldInsert = ctxt->insert;
diff --git a/third_party/libxslt/src/libxslt/variables.h b/third_party/libxslt/src/libxslt/variables.h index 24acf8d..039288fb 100644 --- a/third_party/libxslt/src/libxslt/variables.h +++ b/third_party/libxslt/src/libxslt/variables.h
@@ -46,28 +46,20 @@ #define XSLT_RVT_LOCAL ((void *)1) /** - * XSLT_RVT_VARIABLE: - * - * RVT is part of a local variable and destroyed after the variable goes out - * of scope. - */ -#define XSLT_RVT_VARIABLE ((void *)2) - -/** * XSLT_RVT_FUNC_RESULT: * * RVT is part of results returned with func:result. The RVT won't be * destroyed after exiting a template and will be reset to XSLT_RVT_LOCAL or * XSLT_RVT_VARIABLE in the template that receives the return value. */ -#define XSLT_RVT_FUNC_RESULT ((void *)3) +#define XSLT_RVT_FUNC_RESULT ((void *)2) /** * XSLT_RVT_GLOBAL: * * RVT is part of a global variable. */ -#define XSLT_RVT_GLOBAL ((void *)4) +#define XSLT_RVT_GLOBAL ((void *)3) /* * Interfaces for the variable module.
diff --git a/third_party/libxslt/src/libxslt/xsltconfig.h b/third_party/libxslt/src/libxslt/xsltconfig.h index 3c87617..42a99dcd 100644 --- a/third_party/libxslt/src/libxslt/xsltconfig.h +++ b/third_party/libxslt/src/libxslt/xsltconfig.h
@@ -20,21 +20,21 @@ * * the version string like "1.2.3" */ -#define LIBXSLT_DOTTED_VERSION "1.1.32" +#define LIBXSLT_DOTTED_VERSION "1.1.33" /** * LIBXSLT_VERSION: * * the version number: 1.2.3 value is 10203 */ -#define LIBXSLT_VERSION 10132 +#define LIBXSLT_VERSION 10133 /** * LIBXSLT_VERSION_STRING: * * the version number string, 1.2.3 value is "10203" */ -#define LIBXSLT_VERSION_STRING "10132" +#define LIBXSLT_VERSION_STRING "10133" /** * LIBXSLT_VERSION_EXTRA: @@ -120,7 +120,7 @@ #ifndef WITH_MODULES #define WITH_MODULES #endif -#define LIBXSLT_DEFAULT_PLUGINS_PATH() "/usr/local/lib/libxslt-plugins" +#define LIBXSLT_DEFAULT_PLUGINS_PATH() "NULL" #endif /**
diff --git a/third_party/libxslt/src/libxslt/xsltexports.h b/third_party/libxslt/src/libxslt/xsltexports.h index 825c122..99b6ac3 100644 --- a/third_party/libxslt/src/libxslt/xsltexports.h +++ b/third_party/libxslt/src/libxslt/xsltexports.h
@@ -113,8 +113,8 @@ #endif #endif -/* Cygwin platform, GNU compiler */ -#if defined(_WIN32) && defined(__CYGWIN__) +/* Cygwin platform (does not define _WIN32), GNU compiler */ +#if defined(__CYGWIN__) #undef XSLTPUBFUN #undef XSLTPUBVAR #undef XSLTCALL @@ -126,7 +126,7 @@ #if !defined(LIBXSLT_STATIC) #define XSLTPUBVAR __declspec(dllimport) extern #else - #define XSLTPUBVAR + #define XSLTPUBVAR extern #endif #endif #define XSLTCALL __cdecl
diff --git a/third_party/libxslt/src/win32/Makefile.mingw b/third_party/libxslt/src/win32/Makefile.mingw index 4fc42fe..ad6ecdf 100644 --- a/third_party/libxslt/src/win32/Makefile.mingw +++ b/third_party/libxslt/src/win32/Makefile.mingw
@@ -55,7 +55,7 @@ # The linker and its options. LD = gcc.exe LDFLAGS += -Wl,-L,$(BINDIR) -Wl,-L,$(LIBPREFIX) -LIBS = -lwsock32 +LIBS = # The archiver and its options. AR = ar.exe
diff --git a/third_party/libxslt/src/win32/Makefile.msvc b/third_party/libxslt/src/win32/Makefile.msvc index a6d57a1..2e4742b 100644 --- a/third_party/libxslt/src/win32/Makefile.msvc +++ b/third_party/libxslt/src/win32/Makefile.msvc
@@ -59,7 +59,7 @@ LD = link.exe LDFLAGS = /nologo LDFLAGS = $(LDFLAGS) /LIBPATH:$(BINDIR) /LIBPATH:$(LIBPREFIX) -LIBS = wsock32.lib +LIBS = # The archiver and its options. AR = lib.exe
diff --git a/third_party/libxslt/src/win32/libxslt/libxslt.def b/third_party/libxslt/src/win32/libxslt/libxslt.def index a1dad624..dc6f1a0 100644 --- a/third_party/libxslt/src/win32/libxslt/libxslt.def +++ b/third_party/libxslt/src/win32/libxslt/libxslt.def
@@ -1,149 +1,149 @@ - -LIBRARY libxslt -EXPORTS - - xsltNewStylesheet - xsltParseStylesheetFile - xsltFreeStylesheet - xsltIsBlank - xsltFreeStackElemList - xsltDecimalFormatGetByName - xsltParseStylesheetProcess - xsltParseStylesheetOutput - xsltParseStylesheetDoc - xsltNumberFormat - xsltFormatNumberConversion - xsltProfileStylesheet - - xsltParseStylesheetAttributeSet - xsltFreeAttributeSetsHashes - xsltApplyAttributeSet - - xsltNewDocument - xsltLoadDocument - xsltFreeDocuments - xsltLoadStyleDocument - xsltNewStyleDocument - xsltFreeStyleDocuments - - - xsltRegisterExtPrefix - xsltCheckExtPrefix - xsltRegisterExtFunction - xsltRegisterExtElement - xsltFreeCtxtExts - xsltFreeExts - xsltUnregisterAllExtModules - xsltGetExtData - xsltShutdownCtxtExts - xsltXPathGetTransformContext - xsltUnregisterExtModule - xsltRegisterExtModule - - - xsltDocumentFunction - xsltKeyFunction - xsltUnparsedEntityURIFunction - xsltFormatNumberFunction - xsltGenerateIdFunction - xsltSystemPropertyFunction - xsltElementAvailableFunction - xsltFunctionAvailableFunction - xsltRegisterAllFunctions - - xsltParseStylesheetImport - xsltParseStylesheetInclude - xsltNextImport - xsltFindElemSpaceHandling - xsltFindTemplate - - xsltAddKey - xsltGetKey - xsltInitCtxtKeys - xsltFreeKeys - xsltFreeDocumentKeys - - xsltNamespaceAlias - xsltGetNamespace - xsltGetSpecialNamespace - xsltCopyNamespaceList - xsltCopyNamespaceList - xsltFreeNamespaceAliasHashes - - xsltCompilePattern - xsltFreeCompMatchList - xsltTestCompMatchList - xsltAddTemplate - xsltGetTemplate - xsltFreeTemplateHashes - xsltCleanupTemplates - - xsltStylePreCompute - xsltFreeStylePreComps - - xsltEvalXPathPredicate - xsltEvalTemplateString - xsltEvalAttrValueTemplate - xsltEvalStaticAttrValueTemplate - xsltEvalXPathString - xsltTemplateProcess - xsltAttrListTemplateProcess - xsltAttrTemplateProcess - xsltAttrTemplateValueProcess - - xsltApplyStylesheet - xsltApplyOneTemplate - xsltDocumentElem - xsltSort - xsltCopy - xsltText - xsltElement - xsltComment - xsltAttribute - xsltProcessingInstruction - xsltCopyOf - xsltValueOf - xsltNumber - xsltApplyImports - xsltCallTemplate - xsltApplyTemplates - xsltChoose - xsltIf - xsltForEach - - xsltEvalGlobalVariables - xsltEvalUserParams - xsltParseGlobalVariable - xsltParseGlobalParam - xsltParseStylesheetVariable - xsltParseStylesheetParam - xsltParseStylesheetCallerParam - xsltAddStackElemList - xsltFreeGlobalVariables - xsltVariableLookup - xsltXPathVariableLookup - - xsltMessage - xsltSetGenericErrorFunc - xsltSetGenericDebugFunc - xsltDocumentSortFunction - xsltDoSortFunction - xsltSaveResultTo - xsltSaveResultToFilename - xsltSaveResultToFile - xsltSaveResultToFd - - xsltMaxDepth - xsltMaxVars - xsltSetXIncludeDefault - xsltLibxmlVersion - xsltLibxsltVersion - xsltEngineVersion - - xsltRunStylesheet - xsltLoadStylesheetPI - xsltRegisterAllElement - - - - + +LIBRARY libxslt +EXPORTS + + xsltNewStylesheet + xsltParseStylesheetFile + xsltFreeStylesheet + xsltIsBlank + xsltFreeStackElemList + xsltDecimalFormatGetByName + xsltParseStylesheetProcess + xsltParseStylesheetOutput + xsltParseStylesheetDoc + xsltNumberFormat + xsltFormatNumberConversion + xsltProfileStylesheet + + xsltParseStylesheetAttributeSet + xsltFreeAttributeSetsHashes + xsltApplyAttributeSet + + xsltNewDocument + xsltLoadDocument + xsltFreeDocuments + xsltLoadStyleDocument + xsltNewStyleDocument + xsltFreeStyleDocuments + + + xsltRegisterExtPrefix + xsltCheckExtPrefix + xsltRegisterExtFunction + xsltRegisterExtElement + xsltFreeCtxtExts + xsltFreeExts + xsltUnregisterAllExtModules + xsltGetExtData + xsltShutdownCtxtExts + xsltXPathGetTransformContext + xsltUnregisterExtModule + xsltRegisterExtModule + + + xsltDocumentFunction + xsltKeyFunction + xsltUnparsedEntityURIFunction + xsltFormatNumberFunction + xsltGenerateIdFunction + xsltSystemPropertyFunction + xsltElementAvailableFunction + xsltFunctionAvailableFunction + xsltRegisterAllFunctions + + xsltParseStylesheetImport + xsltParseStylesheetInclude + xsltNextImport + xsltFindElemSpaceHandling + xsltFindTemplate + + xsltAddKey + xsltGetKey + xsltInitCtxtKeys + xsltFreeKeys + xsltFreeDocumentKeys + + xsltNamespaceAlias + xsltGetNamespace + xsltGetSpecialNamespace + xsltCopyNamespaceList + xsltCopyNamespaceList + xsltFreeNamespaceAliasHashes + + xsltCompilePattern + xsltFreeCompMatchList + xsltTestCompMatchList + xsltAddTemplate + xsltGetTemplate + xsltFreeTemplateHashes + xsltCleanupTemplates + + xsltStylePreCompute + xsltFreeStylePreComps + + xsltEvalXPathPredicate + xsltEvalTemplateString + xsltEvalAttrValueTemplate + xsltEvalStaticAttrValueTemplate + xsltEvalXPathString + xsltTemplateProcess + xsltAttrListTemplateProcess + xsltAttrTemplateProcess + xsltAttrTemplateValueProcess + + xsltApplyStylesheet + xsltApplyOneTemplate + xsltDocumentElem + xsltSort + xsltCopy + xsltText + xsltElement + xsltComment + xsltAttribute + xsltProcessingInstruction + xsltCopyOf + xsltValueOf + xsltNumber + xsltApplyImports + xsltCallTemplate + xsltApplyTemplates + xsltChoose + xsltIf + xsltForEach + + xsltEvalGlobalVariables + xsltEvalUserParams + xsltParseGlobalVariable + xsltParseGlobalParam + xsltParseStylesheetVariable + xsltParseStylesheetParam + xsltParseStylesheetCallerParam + xsltAddStackElemList + xsltFreeGlobalVariables + xsltVariableLookup + xsltXPathVariableLookup + + xsltMessage + xsltSetGenericErrorFunc + xsltSetGenericDebugFunc + xsltDocumentSortFunction + xsltDoSortFunction + xsltSaveResultTo + xsltSaveResultToFilename + xsltSaveResultToFile + xsltSaveResultToFd + + xsltMaxDepth + xsltMaxVars + xsltSetXIncludeDefault + xsltLibxmlVersion + xsltLibxsltVersion + xsltEngineVersion + + xsltRunStylesheet + xsltLoadStylesheetPI + xsltRegisterAllElement + + + +
diff --git a/third_party/libxslt/src/win32/libxslt/libxslt.dsw b/third_party/libxslt/src/win32/libxslt/libxslt.dsw index 3685bcc..b8a53e2 100644 --- a/third_party/libxslt/src/win32/libxslt/libxslt.dsw +++ b/third_party/libxslt/src/win32/libxslt/libxslt.dsw
@@ -1,44 +1,44 @@ -Microsoft Developer Studio Workspace File, Format Version 6.00 -# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! - -############################################################################### - -Project: "libxslt_so"=.\libxslt_so.dsp - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ -}}} - -############################################################################### - -Project: "xsltproc"=.\xsltproc.dsp - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ - Begin Project Dependency - Project_Dep_Name libxslt_so - End Project Dependency -}}} - -############################################################################### - -Global: - -Package=<5> -{{{ -}}} - -Package=<3> -{{{ -}}} - -############################################################################### - +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "libxslt_so"=.\libxslt_so.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "xsltproc"=.\xsltproc.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libxslt_so + End Project Dependency +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### +
diff --git a/third_party/libxslt/src/win32/libxslt/libxslt_so.dsp b/third_party/libxslt/src/win32/libxslt/libxslt_so.dsp index d8b9065..4bc6cad 100644 --- a/third_party/libxslt/src/win32/libxslt/libxslt_so.dsp +++ b/third_party/libxslt/src/win32/libxslt/libxslt_so.dsp
@@ -1,247 +1,247 @@ -# Microsoft Developer Studio Project File - Name="libxslt_so" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 - -CFG=libxslt_so - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "libxslt_so.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "libxslt_so.mak" CFG="libxslt_so - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "libxslt_so - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") -!MESSAGE "libxslt_so - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -MTL=midl.exe -RSC=rc.exe - -!IF "$(CFG)" == "libxslt_so - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBXSLT_SO_EXPORTS" /Yu"stdafx.h" /FD /c -# ADD CPP /nologo /MT /W3 /GX /O2 /I "..\..\..\gnome-xml" /I "..\..\..\gnome-xml\include" /I "..\.." /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBXSLT_SO_EXPORTS" /FD /c -# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 -# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 -# ADD LINK32 ..\..\..\gnome-xml\win32\libxml2\release_so\libxml2.lib /nologo /dll /machine:I386 /out:"Release/libxslt.dll" - -!ELSEIF "$(CFG)" == "libxslt_so - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBXSLT_SO_EXPORTS" /Yu"stdafx.h" /FD /GZ /c -# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "..\..\..\gnome-xml\include" /I "..\..\..\gnome-xml" /I "..\.." /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBXSLT_SO_EXPORTS" /FD /GZ /c -# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 -# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept -# ADD LINK32 ..\..\..\gnome-xml\win32\libxml2\debug_so\libxml2.lib /nologo /dll /debug /machine:I386 /out:"Debug/libxslt.dll" /pdbtype:sept - -!ENDIF - -# Begin Target - -# Name "libxslt_so - Win32 Release" -# Name "libxslt_so - Win32 Debug" -# Begin Group "Source Files" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Source File - -SOURCE=..\..\libxslt\attributes.c -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\documents.c -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\extensions.c -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\extra.c -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\functions.c -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\imports.c -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\keys.c -# End Source File -# Begin Source File - -SOURCE=.\libxslt.def -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\namespaces.c -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\numbers.c -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\pattern.c -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\preproc.c -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\templates.c -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\transform.c -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\variables.c -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\xslt.c -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\xsltutils.c -# End Source File -# End Group -# Begin Group "Header Files" - -# PROP Default_Filter "h;hpp;hxx;hm;inl" -# Begin Source File - -SOURCE=..\..\libxslt\attributes.h -# End Source File -# Begin Source File - -SOURCE=..\..\config.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\documents.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\extensions.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\extra.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\functions.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\imports.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\keys.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\namespaces.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\numbersInternals.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\pattern.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\preproc.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\templates.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\transform.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\variables.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\xslt.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\xsltconfig.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\xsltInternals.h -# End Source File -# Begin Source File - -SOURCE=..\..\libxslt\xsltutils.h -# End Source File -# End Group -# Begin Group "Resource Files" - -# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" -# End Group -# End Target -# End Project +# Microsoft Developer Studio Project File - Name="libxslt_so" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 + +CFG=libxslt_so - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "libxslt_so.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "libxslt_so.mak" CFG="libxslt_so - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "libxslt_so - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE "libxslt_so - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "libxslt_so - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBXSLT_SO_EXPORTS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MT /W3 /GX /O2 /I "..\..\..\gnome-xml" /I "..\..\..\gnome-xml\include" /I "..\.." /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBXSLT_SO_EXPORTS" /FD /c +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 +# ADD LINK32 ..\..\..\gnome-xml\win32\libxml2\release_so\libxml2.lib /nologo /dll /machine:I386 /out:"Release/libxslt.dll" + +!ELSEIF "$(CFG)" == "libxslt_so - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBXSLT_SO_EXPORTS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "..\..\..\gnome-xml\include" /I "..\..\..\gnome-xml" /I "..\.." /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBXSLT_SO_EXPORTS" /FD /GZ /c +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\..\gnome-xml\win32\libxml2\debug_so\libxml2.lib /nologo /dll /debug /machine:I386 /out:"Debug/libxslt.dll" /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "libxslt_so - Win32 Release" +# Name "libxslt_so - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=..\..\libxslt\attributes.c +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\documents.c +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\extensions.c +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\extra.c +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\functions.c +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\imports.c +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\keys.c +# End Source File +# Begin Source File + +SOURCE=.\libxslt.def +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\namespaces.c +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\numbers.c +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\pattern.c +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\preproc.c +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\templates.c +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\transform.c +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\variables.c +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\xslt.c +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\xsltutils.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=..\..\libxslt\attributes.h +# End Source File +# Begin Source File + +SOURCE=..\..\config.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\documents.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\extensions.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\extra.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\functions.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\imports.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\keys.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\namespaces.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\numbersInternals.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\pattern.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\preproc.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\templates.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\transform.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\variables.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\xslt.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\xsltconfig.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\xsltInternals.h +# End Source File +# Begin Source File + +SOURCE=..\..\libxslt\xsltutils.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project
diff --git a/third_party/libxslt/src/win32/libxslt/xsltproc.dsp b/third_party/libxslt/src/win32/libxslt/xsltproc.dsp index 096d96ff..92938412 100644 --- a/third_party/libxslt/src/win32/libxslt/xsltproc.dsp +++ b/third_party/libxslt/src/win32/libxslt/xsltproc.dsp
@@ -1,102 +1,102 @@ -# Microsoft Developer Studio Project File - Name="xsltproc" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Console Application" 0x0103 - -CFG=xsltproc - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "xsltproc.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "xsltproc.mak" CFG="xsltproc - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "xsltproc - Win32 Release" (based on "Win32 (x86) Console Application") -!MESSAGE "xsltproc - Win32 Debug" (based on "Win32 (x86) Console Application") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "xsltproc - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /GX /O2 /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /W3 /GX /O2 /I "..\..\..\gnome-xml\include" /I "..\..\..\gnome-xml" /I "..\.." /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 -# ADD LINK32 ..\..\..\gnome-xml\win32\libxml2\release_so\libxml2.lib Release/libxslt.lib /nologo /subsystem:console /machine:I386 - -!ELSEIF "$(CFG)" == "xsltproc - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "..\..\..\gnome-xml\include" /I "..\..\..\gnome-xml" /I "..\.." /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept -# ADD LINK32 ..\..\..\gnome-xml\win32\libxml2\debug_so\libxml2.lib Debug/libxslt.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept - -!ENDIF - -# Begin Target - -# Name "xsltproc - Win32 Release" -# Name "xsltproc - Win32 Debug" -# Begin Group "Source Files" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Source File - -SOURCE=..\..\libxslt\xsltproc.c -# End Source File -# End Group -# Begin Group "Header Files" - -# PROP Default_Filter "h;hpp;hxx;hm;inl" -# End Group -# Begin Group "Resource Files" - -# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" -# End Group -# End Target -# End Project +# Microsoft Developer Studio Project File - Name="xsltproc" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=xsltproc - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "xsltproc.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "xsltproc.mak" CFG="xsltproc - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "xsltproc - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "xsltproc - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "xsltproc - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /I "..\..\..\gnome-xml\include" /I "..\..\..\gnome-xml" /I "..\.." /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 ..\..\..\gnome-xml\win32\libxml2\release_so\libxml2.lib Release/libxslt.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "xsltproc - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "..\..\..\gnome-xml\include" /I "..\..\..\gnome-xml" /I "..\.." /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ..\..\..\gnome-xml\win32\libxml2\debug_so\libxml2.lib Debug/libxslt.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "xsltproc - Win32 Release" +# Name "xsltproc - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=..\..\libxslt\xsltproc.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project
diff --git a/third_party/metrics_proto/README.chromium b/third_party/metrics_proto/README.chromium index 9cd2897..e904fb8c 100644 --- a/third_party/metrics_proto/README.chromium +++ b/third_party/metrics_proto/README.chromium
@@ -1,8 +1,8 @@ Name: Metrics Protos Short Name: metrics_proto URL: This is the canonical public repository -Version: 233608850 -Date: 2019/02/12 UTC +Version: 234842562 +Date: 2019/02/20 UTC License: BSD Security Critical: Yes
diff --git a/third_party/metrics_proto/sampled_profile.proto b/third_party/metrics_proto/sampled_profile.proto index ea29b73..5cf5650 100644 --- a/third_party/metrics_proto/sampled_profile.proto +++ b/third_party/metrics_proto/sampled_profile.proto
@@ -11,15 +11,15 @@ package metrics; +import "call_stack_profile.proto"; import "execution_context.proto"; import "perf_data.proto"; import "perf_stat.proto"; -import "call_stack_profile.proto"; // Protocol buffer for collected sample-based profiling data. // Contains the parameters and data from a single profile collection event. -// Next tag: 13 +// Next tag: 15 message SampledProfile { // Indicates the event that triggered this collection. enum TriggerEvent { @@ -60,6 +60,20 @@ // The thread in which the profile was collected. optional Thread thread = 12; + // Map of Chrome PIDs running on the system when the profile was collected. + // Each Chrome PID is mapped to its process type. + // This field and the below thread_types field assume that the PID/TID + // information are collected in a short duration for a single session such + // that, the PID/TID reuse is highly unlikely. + // The information from these two fields is used to map chrome samples + // collected for a specific PID/TID to the corresponding process type and + // thread type. + map<uint32, Process> process_types = 13; + + // Map of Chrome TIDs running on the system when the profile was collected. + // Each Chrome TID is mapped to its thread type. + map<uint32, Thread> thread_types = 14; + // Fields 2-3: Time durations are given in ticks, and represent system uptime // rather than wall time.
diff --git a/third_party/protobuf/patches/0025-once-only.patch b/third_party/protobuf/patches/0025-once-only.patch index fb716b0..f8a82ba 100644 --- a/third_party/protobuf/patches/0025-once-only.patch +++ b/third_party/protobuf/patches/0025-once-only.patch
@@ -308,7 +308,7 @@ + } + +#define GOOGLE_PROTOBUF_FORWARD_ONCE(NAME) \ -+ ::google::protobuf::ProtobufOnceType& get_once_##NAME(); ++ ::google::protobuf::ProtobufOnceType& get_once_##NAME() + +#define GOOGLE_PROTOBUF_GET_ONCE(NAME) (get_once_##NAME())
diff --git a/third_party/protobuf/src/google/protobuf/stubs/once.h b/third_party/protobuf/src/google/protobuf/stubs/once.h index d481bdf..c6a6d8a 100644 --- a/third_party/protobuf/src/google/protobuf/stubs/once.h +++ b/third_party/protobuf/src/google/protobuf/stubs/once.h
@@ -126,7 +126,7 @@ } #define GOOGLE_PROTOBUF_FORWARD_ONCE(NAME) \ - ::google::protobuf::ProtobufOnceType& get_once_##NAME(); + ::google::protobuf::ProtobufOnceType& get_once_##NAME() #define GOOGLE_PROTOBUF_GET_ONCE(NAME) (get_once_##NAME())
diff --git a/third_party/unrar/README.chromium b/third_party/unrar/README.chromium index b5b3e9df..8ef4d71 100644 --- a/third_party/unrar/README.chromium +++ b/third_party/unrar/README.chromium
@@ -21,7 +21,7 @@ Notable changes from upstream: - Use CHROMIUM_UNRAR macro to guard Chromium-specific changes. - Rewrite WinNT() in isnt.cpp to use the new Windows APIs. -- Explicit use of parentheses to fix linter errors. +- Explicit use of parentheses to fix linter errors (001_linter.patch) - Replace exceptions with terminating the current process. Guarded with the macro UNRAR_NO_EXCEPTIONS. - Pass a file handle to the rar file, instead of trying to open the rar file @@ -31,4 +31,5 @@ - Pass a file handle to a temporary file with write permission, so the archive can be extracted inside the sandbox for analysis. - Put all symbols into a namespace third_party_unrar to avoid polluting global - namespace. (Apply add_namespaces.patch) + namespace (add_namespaces.patch) +- Remove unnecessary semicolons from header files (semicolons.patch)
diff --git a/third_party/unrar/patches/semicolons.patch b/third_party/unrar/patches/semicolons.patch new file mode 100644 index 0000000..33b8f7c --- /dev/null +++ b/third_party/unrar/patches/semicolons.patch
@@ -0,0 +1,80 @@ +diff --git a/third_party/unrar/src/archive.hpp b/third_party/unrar/src/archive.hpp +index c2dec52041a9..9c1456830413 100644 +--- a/third_party/unrar/src/archive.hpp ++++ b/third_party/unrar/src/archive.hpp +@@ -94,7 +94,7 @@ class Archive:public File + void AddSubData(byte *SrcData,uint64 DataSize,File *SrcFile, + const wchar *Name,uint Flags); + bool ReadSubData(Array<byte> *UnpData,File *DestFile); +- HEADER_TYPE GetHeaderType() {return CurHeaderType;}; ++ HEADER_TYPE GetHeaderType() {return CurHeaderType;} + RAROptions* GetRAROptions() {return Cmd;} + void SetSilentOpen(bool Mode) {SilentOpen=Mode;} + #if 0 +diff --git a/third_party/unrar/src/errhnd.hpp b/third_party/unrar/src/errhnd.hpp +index 3dff399b16bb..b3f728e48122 100644 +--- a/third_party/unrar/src/errhnd.hpp ++++ b/third_party/unrar/src/errhnd.hpp +@@ -57,7 +57,7 @@ class ErrorHandler + uint GetErrorCount() {return ErrCount;} + void SetSignalHandlers(bool Enable); + void Throw(RAR_EXIT Code); +- void SetSilent(bool Mode) {Silent=Mode;}; ++ void SetSilent(bool Mode) {Silent=Mode;} + bool GetSysErrMsg(wchar *Msg,size_t Size); + void SysErrMsg(); + int GetSystemErrorCode(); +diff --git a/third_party/unrar/src/file.hpp b/third_party/unrar/src/file.hpp +index 4b3b637ad832..9cc7807b0fde 100644 +--- a/third_party/unrar/src/file.hpp ++++ b/third_party/unrar/src/file.hpp +@@ -105,7 +105,7 @@ class File + void SetCloseFileTime(RarTime *ftm,RarTime *fta=NULL); + static void SetCloseFileTimeByName(const wchar *Name,RarTime *ftm,RarTime *fta); + void GetOpenFileTime(RarTime *ft); +- virtual bool IsOpened() {return hFile!=FILE_BAD_HANDLE;}; // 'virtual' for MultiFile class. ++ virtual bool IsOpened() {return hFile!=FILE_BAD_HANDLE;} // 'virtual' for MultiFile class. + int64 FileLength(); + void SetHandleType(FILE_HANDLETYPE Type) {HandleType=Type;} + FILE_HANDLETYPE GetHandleType() {return HandleType;} +diff --git a/third_party/unrar/src/scantree.hpp b/third_party/unrar/src/scantree.hpp +index 73354ab9429f..9edcb24527aa 100644 +--- a/third_party/unrar/src/scantree.hpp ++++ b/third_party/unrar/src/scantree.hpp +@@ -66,8 +66,8 @@ class ScanTree + ScanTree(StringList *FileMasks,RECURSE_MODE Recurse,bool GetLinks,SCAN_DIRS GetDirs); + ~ScanTree(); + SCAN_CODE GetNext(FindData *FindData); +- size_t GetSpecPathLength() {return SpecPathLength;}; +- int GetErrors() {return Errors;}; ++ size_t GetSpecPathLength() {return SpecPathLength;} ++ int GetErrors() {return Errors;} + void SetErrArcName(const wchar *Name) {wcsncpyz(ErrArcName,Name,ASIZE(ErrArcName));} + void SetCommandData(CommandData *Cmd) {ScanTree::Cmd=Cmd;} + void SetErrDirList(StringList *List,Array<uint> *Lengths) +diff --git a/third_party/unrar/src/strlist.hpp b/third_party/unrar/src/strlist.hpp +index 55108dd9b10a..2c16b68f18eb 100644 +--- a/third_party/unrar/src/strlist.hpp ++++ b/third_party/unrar/src/strlist.hpp +@@ -23,7 +23,7 @@ class StringList + wchar* GetString(); + bool GetString(wchar **Str); + void Rewind(); +- size_t ItemsCount() {return StringsCount;}; ++ size_t ItemsCount() {return StringsCount;} + size_t GetCharCount() {return StringData.Size();} + bool Search(const wchar *Str,bool CaseSensitive); + void SavePosition(); +diff --git a/third_party/unrar/src/suballoc.hpp b/third_party/unrar/src/suballoc.hpp +index 17af204eb6c1..98ba2dea73ff 100644 +--- a/third_party/unrar/src/suballoc.hpp ++++ b/third_party/unrar/src/suballoc.hpp +@@ -79,7 +79,7 @@ class SubAllocator + inline void* ExpandUnits(void* ptr,int OldNU); + inline void* ShrinkUnits(void* ptr,int OldNU,int NewNU); + inline void FreeUnits(void* ptr,int OldNU); +- long GetAllocatedMemory() {return(SubAllocatorSize);}; ++ long GetAllocatedMemory() {return(SubAllocatorSize);} + + byte *pText, *UnitsStart,*HeapEnd,*FakeUnitsStart; + };
diff --git a/third_party/unrar/src/archive.hpp b/third_party/unrar/src/archive.hpp index c2dec52..9c14568 100644 --- a/third_party/unrar/src/archive.hpp +++ b/third_party/unrar/src/archive.hpp
@@ -94,7 +94,7 @@ void AddSubData(byte *SrcData,uint64 DataSize,File *SrcFile, const wchar *Name,uint Flags); bool ReadSubData(Array<byte> *UnpData,File *DestFile); - HEADER_TYPE GetHeaderType() {return CurHeaderType;}; + HEADER_TYPE GetHeaderType() {return CurHeaderType;} RAROptions* GetRAROptions() {return Cmd;} void SetSilentOpen(bool Mode) {SilentOpen=Mode;} #if 0
diff --git a/third_party/unrar/src/errhnd.hpp b/third_party/unrar/src/errhnd.hpp index 3dff399..b3f728e 100644 --- a/third_party/unrar/src/errhnd.hpp +++ b/third_party/unrar/src/errhnd.hpp
@@ -57,7 +57,7 @@ uint GetErrorCount() {return ErrCount;} void SetSignalHandlers(bool Enable); void Throw(RAR_EXIT Code); - void SetSilent(bool Mode) {Silent=Mode;}; + void SetSilent(bool Mode) {Silent=Mode;} bool GetSysErrMsg(wchar *Msg,size_t Size); void SysErrMsg(); int GetSystemErrorCode();
diff --git a/third_party/unrar/src/file.hpp b/third_party/unrar/src/file.hpp index 4b3b637a..9cc7807 100644 --- a/third_party/unrar/src/file.hpp +++ b/third_party/unrar/src/file.hpp
@@ -105,7 +105,7 @@ void SetCloseFileTime(RarTime *ftm,RarTime *fta=NULL); static void SetCloseFileTimeByName(const wchar *Name,RarTime *ftm,RarTime *fta); void GetOpenFileTime(RarTime *ft); - virtual bool IsOpened() {return hFile!=FILE_BAD_HANDLE;}; // 'virtual' for MultiFile class. + virtual bool IsOpened() {return hFile!=FILE_BAD_HANDLE;} // 'virtual' for MultiFile class. int64 FileLength(); void SetHandleType(FILE_HANDLETYPE Type) {HandleType=Type;} FILE_HANDLETYPE GetHandleType() {return HandleType;}
diff --git a/third_party/unrar/src/scantree.hpp b/third_party/unrar/src/scantree.hpp index 73354ab..9edcb24 100644 --- a/third_party/unrar/src/scantree.hpp +++ b/third_party/unrar/src/scantree.hpp
@@ -66,8 +66,8 @@ ScanTree(StringList *FileMasks,RECURSE_MODE Recurse,bool GetLinks,SCAN_DIRS GetDirs); ~ScanTree(); SCAN_CODE GetNext(FindData *FindData); - size_t GetSpecPathLength() {return SpecPathLength;}; - int GetErrors() {return Errors;}; + size_t GetSpecPathLength() {return SpecPathLength;} + int GetErrors() {return Errors;} void SetErrArcName(const wchar *Name) {wcsncpyz(ErrArcName,Name,ASIZE(ErrArcName));} void SetCommandData(CommandData *Cmd) {ScanTree::Cmd=Cmd;} void SetErrDirList(StringList *List,Array<uint> *Lengths)
diff --git a/third_party/unrar/src/strlist.hpp b/third_party/unrar/src/strlist.hpp index 55108dd9..2c16b68 100644 --- a/third_party/unrar/src/strlist.hpp +++ b/third_party/unrar/src/strlist.hpp
@@ -23,7 +23,7 @@ wchar* GetString(); bool GetString(wchar **Str); void Rewind(); - size_t ItemsCount() {return StringsCount;}; + size_t ItemsCount() {return StringsCount;} size_t GetCharCount() {return StringData.Size();} bool Search(const wchar *Str,bool CaseSensitive); void SavePosition();
diff --git a/third_party/unrar/src/suballoc.hpp b/third_party/unrar/src/suballoc.hpp index 17af204..98ba2dea 100644 --- a/third_party/unrar/src/suballoc.hpp +++ b/third_party/unrar/src/suballoc.hpp
@@ -79,7 +79,7 @@ inline void* ExpandUnits(void* ptr,int OldNU); inline void* ShrinkUnits(void* ptr,int OldNU,int NewNU); inline void FreeUnits(void* ptr,int OldNU); - long GetAllocatedMemory() {return(SubAllocatorSize);}; + long GetAllocatedMemory() {return(SubAllocatorSize);} byte *pText, *UnitsStart,*HeapEnd,*FakeUnitsStart; };
diff --git a/third_party/webrtc_overrides/task_queue_factory.cc b/third_party/webrtc_overrides/task_queue_factory.cc index 55df38a..48169f65 100644 --- a/third_party/webrtc_overrides/task_queue_factory.cc +++ b/third_party/webrtc_overrides/task_queue_factory.cc
@@ -32,8 +32,9 @@ private: ~WebrtcTaskQueue() override = default; - void RunTask(scoped_refptr<base::RefCountedData<bool>> is_active, - std::unique_ptr<webrtc::QueuedTask> task); + static void RunTask(WebrtcTaskQueue* task_queue, + scoped_refptr<base::RefCountedData<bool>> is_active, + std::unique_ptr<webrtc::QueuedTask> task); const scoped_refptr<base::SequencedTaskRunner> task_runner_; // Value of |is_active_| is checked and set on |task_runner_|. @@ -57,12 +58,13 @@ } void WebrtcTaskQueue::RunTask( + WebrtcTaskQueue* task_queue, scoped_refptr<base::RefCountedData<bool>> is_active, std::unique_ptr<webrtc::QueuedTask> task) { if (!is_active->data) return; - CurrentTaskQueueSetter set_current(this); + CurrentTaskQueueSetter set_current(task_queue); webrtc::QueuedTask* task_ptr = task.release(); if (task_ptr->Run()) { // Delete task_ptr before CurrentTaskQueueSetter clears state that this code
diff --git a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/arm64/gaia_credential_provider.tlb b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/arm64/gaia_credential_provider.tlb index 58a88cd..0d764da 100644 --- a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/arm64/gaia_credential_provider.tlb +++ b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/arm64/gaia_credential_provider.tlb Binary files differ
diff --git a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/arm64/gaia_credential_provider_i.c b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/arm64/gaia_credential_provider_i.c index a225804..39db520 100644 --- a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/arm64/gaia_credential_provider_i.c +++ b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/arm64/gaia_credential_provider_i.c
@@ -70,9 +70,6 @@ MIDL_DEFINE_GUID(IID, IID_IGaiaCredentialProvider,0xCEC9EF6C,0xB2E6,0x4BB6,0x8F,0x1E,0x17,0x47,0xBA,0x4F,0x71,0x38); -MIDL_DEFINE_GUID(IID, IID_IGaiaCredentialProviderForTesting,0x224CE2FB,0x2977,0x4585,0xBD,0x46,0x1B,0xAE,0x8D,0x79,0x64,0xDE); - - MIDL_DEFINE_GUID(IID, IID_IGaiaCredential,0xE5BF88DF,0x9966,0x465B,0xB2,0x33,0xC1,0xCA,0xC7,0x51,0x0A,0x59);
diff --git a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/arm64/gaia_credential_provider_i.h b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/arm64/gaia_credential_provider_i.h index 0b59836..a5542cb 100644 --- a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/arm64/gaia_credential_provider_i.h +++ b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/arm64/gaia_credential_provider_i.h
@@ -52,13 +52,6 @@ #endif /* __IGaiaCredentialProvider_FWD_DEFINED__ */ -#ifndef __IGaiaCredentialProviderForTesting_FWD_DEFINED__ -#define __IGaiaCredentialProviderForTesting_FWD_DEFINED__ -typedef interface IGaiaCredentialProviderForTesting IGaiaCredentialProviderForTesting; - -#endif /* __IGaiaCredentialProviderForTesting_FWD_DEFINED__ */ - - #ifndef __IGaiaCredential_FWD_DEFINED__ #define __IGaiaCredential_FWD_DEFINED__ typedef interface IGaiaCredential IGaiaCredential; @@ -119,8 +112,6 @@ /* [in] */ BSTR sid, /* [in] */ BOOL fire_credentials_changed) = 0; - virtual HRESULT STDMETHODCALLTYPE HasInternetConnection( void) = 0; - }; @@ -154,9 +145,6 @@ /* [in] */ BSTR sid, /* [in] */ BOOL fire_credentials_changed); - HRESULT ( STDMETHODCALLTYPE *HasInternetConnection )( - IGaiaCredentialProvider * This); - END_INTERFACE } IGaiaCredentialProviderVtbl; @@ -186,9 +174,6 @@ #define IGaiaCredentialProvider_OnUserAuthenticated(This,credential,username,password,sid,fire_credentials_changed) \ ( (This)->lpVtbl -> OnUserAuthenticated(This,credential,username,password,sid,fire_credentials_changed) ) -#define IGaiaCredentialProvider_HasInternetConnection(This) \ - ( (This)->lpVtbl -> HasInternetConnection(This) ) - #endif /* COBJMACROS */ @@ -200,102 +185,6 @@ #endif /* __IGaiaCredentialProvider_INTERFACE_DEFINED__ */ -/* interface __MIDL_itf_gaia_credential_provider_0000_0001 */ -/* [local] */ - -typedef /* [public][public] */ -enum __MIDL___MIDL_itf_gaia_credential_provider_0000_0001_0001 - { - kHicForceYes = 0, - kHicForceNo = ( kHicForceYes + 1 ) , - kHicCheckAlways = ( kHicForceNo + 1 ) - } HasInternetConnectionCheckType; - - - -extern RPC_IF_HANDLE __MIDL_itf_gaia_credential_provider_0000_0001_v0_0_c_ifspec; -extern RPC_IF_HANDLE __MIDL_itf_gaia_credential_provider_0000_0001_v0_0_s_ifspec; - -#ifndef __IGaiaCredentialProviderForTesting_INTERFACE_DEFINED__ -#define __IGaiaCredentialProviderForTesting_INTERFACE_DEFINED__ - -/* interface IGaiaCredentialProviderForTesting */ -/* [unique][uuid][object] */ - - -EXTERN_C const IID IID_IGaiaCredentialProviderForTesting; - -#if defined(__cplusplus) && !defined(CINTERFACE) - - MIDL_INTERFACE("224CE2FB-2977-4585-BD46-1BAE8D7964DE") - IGaiaCredentialProviderForTesting : public IUnknown - { - public: - virtual HRESULT STDMETHODCALLTYPE SetHasInternetConnection( - /* [in] */ HasInternetConnectionCheckType hic) = 0; - - }; - - -#else /* C style interface */ - - typedef struct IGaiaCredentialProviderForTestingVtbl - { - BEGIN_INTERFACE - - HRESULT ( STDMETHODCALLTYPE *QueryInterface )( - IGaiaCredentialProviderForTesting * This, - /* [in] */ REFIID riid, - /* [annotation][iid_is][out] */ - _COM_Outptr_ void **ppvObject); - - ULONG ( STDMETHODCALLTYPE *AddRef )( - IGaiaCredentialProviderForTesting * This); - - ULONG ( STDMETHODCALLTYPE *Release )( - IGaiaCredentialProviderForTesting * This); - - HRESULT ( STDMETHODCALLTYPE *SetHasInternetConnection )( - IGaiaCredentialProviderForTesting * This, - /* [in] */ HasInternetConnectionCheckType hic); - - END_INTERFACE - } IGaiaCredentialProviderForTestingVtbl; - - interface IGaiaCredentialProviderForTesting - { - CONST_VTBL struct IGaiaCredentialProviderForTestingVtbl *lpVtbl; - }; - - - -#ifdef COBJMACROS - - -#define IGaiaCredentialProviderForTesting_QueryInterface(This,riid,ppvObject) \ - ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) - -#define IGaiaCredentialProviderForTesting_AddRef(This) \ - ( (This)->lpVtbl -> AddRef(This) ) - -#define IGaiaCredentialProviderForTesting_Release(This) \ - ( (This)->lpVtbl -> Release(This) ) - - -#define IGaiaCredentialProviderForTesting_SetHasInternetConnection(This,hic) \ - ( (This)->lpVtbl -> SetHasInternetConnection(This,hic) ) - -#endif /* COBJMACROS */ - - -#endif /* C style interface */ - - - - -#endif /* __IGaiaCredentialProviderForTesting_INTERFACE_DEFINED__ */ - - #ifndef __IGaiaCredential_INTERFACE_DEFINED__ #define __IGaiaCredential_INTERFACE_DEFINED__
diff --git a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/arm64/gaia_credential_provider_p.c b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/arm64/gaia_credential_provider_p.c index aa33de1..d8cd3c7 100644 --- a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/arm64/gaia_credential_provider_p.c +++ b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/arm64/gaia_credential_provider_p.c
@@ -47,7 +47,7 @@ #include "gaia_credential_provider_i.h" #define TYPE_FORMAT_STRING_SIZE 97 -#define PROC_FORMAT_STRING_SIZE 467 +#define PROC_FORMAT_STRING_SIZE 391 #define EXPR_FORMAT_STRING_SIZE 1 #define TRANSMIT_AS_TABLE_SIZE 0 #define WIRE_MARSHAL_TABLE_SIZE 1 @@ -90,13 +90,6 @@ extern const MIDL_STUB_DESC Object_StubDesc; -extern const MIDL_SERVER_INFO IGaiaCredentialProviderForTesting_ServerInfo; -extern const MIDL_STUBLESS_PROXY_INFO IGaiaCredentialProviderForTesting_ProxyInfo; - - -extern const MIDL_STUB_DESC Object_StubDesc; - - extern const MIDL_SERVER_INFO IGaiaCredential_ServerInfo; extern const MIDL_STUBLESS_PROXY_INFO IGaiaCredential_ProxyInfo; @@ -219,305 +212,242 @@ /* 110 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ - /* Procedure HasInternetConnection */ + /* Procedure Initialize */ /* 112 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ /* 114 */ NdrFcLong( 0x0 ), /* 0 */ -/* 118 */ NdrFcShort( 0x5 ), /* 5 */ -/* 120 */ NdrFcShort( 0x10 ), /* ARM64 Stack size/offset = 16 */ +/* 118 */ NdrFcShort( 0x3 ), /* 3 */ +/* 120 */ NdrFcShort( 0x18 ), /* ARM64 Stack size/offset = 24 */ /* 122 */ NdrFcShort( 0x0 ), /* 0 */ /* 124 */ NdrFcShort( 0x8 ), /* 8 */ -/* 126 */ 0x44, /* Oi2 Flags: has return, has ext, */ - 0x1, /* 1 */ -/* 128 */ 0xc, /* 12 */ +/* 126 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ + 0x2, /* 2 */ +/* 128 */ 0xe, /* 14 */ 0x1, /* Ext Flags: new corr desc, */ /* 130 */ NdrFcShort( 0x0 ), /* 0 */ /* 132 */ NdrFcShort( 0x0 ), /* 0 */ /* 134 */ NdrFcShort( 0x0 ), /* 0 */ -/* 136 */ NdrFcShort( 0x1 ), /* 1 */ -/* 138 */ 0x1, /* 1 */ +/* 136 */ NdrFcShort( 0x2 ), /* 2 */ +/* 138 */ 0x2, /* 2 */ 0x80, /* 128 */ - - /* Return value */ - -/* 140 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 142 */ NdrFcShort( 0x8 ), /* ARM64 Stack size/offset = 8 */ -/* 144 */ 0x8, /* FC_LONG */ - 0x0, /* 0 */ - - /* Procedure SetHasInternetConnection */ - -/* 146 */ 0x33, /* FC_AUTO_HANDLE */ - 0x6c, /* Old Flags: object, Oi2 */ -/* 148 */ NdrFcLong( 0x0 ), /* 0 */ -/* 152 */ NdrFcShort( 0x3 ), /* 3 */ -/* 154 */ NdrFcShort( 0x18 ), /* ARM64 Stack size/offset = 24 */ -/* 156 */ NdrFcShort( 0x6 ), /* 6 */ -/* 158 */ NdrFcShort( 0x8 ), /* 8 */ -/* 160 */ 0x44, /* Oi2 Flags: has return, has ext, */ - 0x2, /* 2 */ -/* 162 */ 0xe, /* 14 */ - 0x1, /* Ext Flags: new corr desc, */ -/* 164 */ NdrFcShort( 0x0 ), /* 0 */ -/* 166 */ NdrFcShort( 0x0 ), /* 0 */ -/* 168 */ NdrFcShort( 0x0 ), /* 0 */ -/* 170 */ NdrFcShort( 0x2 ), /* 2 */ -/* 172 */ 0x2, /* 2 */ - 0x80, /* 128 */ -/* 174 */ 0x81, /* 129 */ - 0x0, /* 0 */ - - /* Parameter hic */ - -/* 176 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ -/* 178 */ NdrFcShort( 0x8 ), /* ARM64 Stack size/offset = 8 */ -/* 180 */ 0xd, /* FC_ENUM16 */ - 0x0, /* 0 */ - - /* Return value */ - -/* 182 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 184 */ NdrFcShort( 0x10 ), /* ARM64 Stack size/offset = 16 */ -/* 186 */ 0x8, /* FC_LONG */ - 0x0, /* 0 */ - - /* Procedure Initialize */ - -/* 188 */ 0x33, /* FC_AUTO_HANDLE */ - 0x6c, /* Old Flags: object, Oi2 */ -/* 190 */ NdrFcLong( 0x0 ), /* 0 */ -/* 194 */ NdrFcShort( 0x3 ), /* 3 */ -/* 196 */ NdrFcShort( 0x18 ), /* ARM64 Stack size/offset = 24 */ -/* 198 */ NdrFcShort( 0x0 ), /* 0 */ -/* 200 */ NdrFcShort( 0x8 ), /* 8 */ -/* 202 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ - 0x2, /* 2 */ -/* 204 */ 0xe, /* 14 */ - 0x1, /* Ext Flags: new corr desc, */ -/* 206 */ NdrFcShort( 0x0 ), /* 0 */ -/* 208 */ NdrFcShort( 0x0 ), /* 0 */ -/* 210 */ NdrFcShort( 0x0 ), /* 0 */ -/* 212 */ NdrFcShort( 0x2 ), /* 2 */ -/* 214 */ 0x2, /* 2 */ - 0x80, /* 128 */ -/* 216 */ 0x81, /* 129 */ +/* 140 */ 0x81, /* 129 */ 0x0, /* 0 */ /* Parameter provider */ -/* 218 */ NdrFcShort( 0xb ), /* Flags: must size, must free, in, */ -/* 220 */ NdrFcShort( 0x8 ), /* ARM64 Stack size/offset = 8 */ -/* 222 */ NdrFcShort( 0x3c ), /* Type Offset=60 */ +/* 142 */ NdrFcShort( 0xb ), /* Flags: must size, must free, in, */ +/* 144 */ NdrFcShort( 0x8 ), /* ARM64 Stack size/offset = 8 */ +/* 146 */ NdrFcShort( 0x3c ), /* Type Offset=60 */ /* Return value */ -/* 224 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 226 */ NdrFcShort( 0x10 ), /* ARM64 Stack size/offset = 16 */ -/* 228 */ 0x8, /* FC_LONG */ +/* 148 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 150 */ NdrFcShort( 0x10 ), /* ARM64 Stack size/offset = 16 */ +/* 152 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure Terminate */ -/* 230 */ 0x33, /* FC_AUTO_HANDLE */ +/* 154 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ -/* 232 */ NdrFcLong( 0x0 ), /* 0 */ -/* 236 */ NdrFcShort( 0x4 ), /* 4 */ -/* 238 */ NdrFcShort( 0x10 ), /* ARM64 Stack size/offset = 16 */ -/* 240 */ NdrFcShort( 0x0 ), /* 0 */ -/* 242 */ NdrFcShort( 0x8 ), /* 8 */ -/* 244 */ 0x44, /* Oi2 Flags: has return, has ext, */ +/* 156 */ NdrFcLong( 0x0 ), /* 0 */ +/* 160 */ NdrFcShort( 0x4 ), /* 4 */ +/* 162 */ NdrFcShort( 0x10 ), /* ARM64 Stack size/offset = 16 */ +/* 164 */ NdrFcShort( 0x0 ), /* 0 */ +/* 166 */ NdrFcShort( 0x8 ), /* 8 */ +/* 168 */ 0x44, /* Oi2 Flags: has return, has ext, */ 0x1, /* 1 */ -/* 246 */ 0xc, /* 12 */ +/* 170 */ 0xc, /* 12 */ 0x1, /* Ext Flags: new corr desc, */ -/* 248 */ NdrFcShort( 0x0 ), /* 0 */ -/* 250 */ NdrFcShort( 0x0 ), /* 0 */ -/* 252 */ NdrFcShort( 0x0 ), /* 0 */ -/* 254 */ NdrFcShort( 0x1 ), /* 1 */ -/* 256 */ 0x1, /* 1 */ +/* 172 */ NdrFcShort( 0x0 ), /* 0 */ +/* 174 */ NdrFcShort( 0x0 ), /* 0 */ +/* 176 */ NdrFcShort( 0x0 ), /* 0 */ +/* 178 */ NdrFcShort( 0x1 ), /* 1 */ +/* 180 */ 0x1, /* 1 */ 0x80, /* 128 */ /* Return value */ -/* 258 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 260 */ NdrFcShort( 0x8 ), /* ARM64 Stack size/offset = 8 */ -/* 262 */ 0x8, /* FC_LONG */ +/* 182 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 184 */ NdrFcShort( 0x8 ), /* ARM64 Stack size/offset = 8 */ +/* 186 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure OnUserAuthenticated */ -/* 264 */ 0x33, /* FC_AUTO_HANDLE */ +/* 188 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ -/* 266 */ NdrFcLong( 0x0 ), /* 0 */ -/* 270 */ NdrFcShort( 0x5 ), /* 5 */ -/* 272 */ NdrFcShort( 0x20 ), /* ARM64 Stack size/offset = 32 */ -/* 274 */ NdrFcShort( 0x0 ), /* 0 */ -/* 276 */ NdrFcShort( 0x8 ), /* 8 */ -/* 278 */ 0x47, /* Oi2 Flags: srv must size, clt must size, has return, has ext, */ +/* 190 */ NdrFcLong( 0x0 ), /* 0 */ +/* 194 */ NdrFcShort( 0x5 ), /* 5 */ +/* 196 */ NdrFcShort( 0x20 ), /* ARM64 Stack size/offset = 32 */ +/* 198 */ NdrFcShort( 0x0 ), /* 0 */ +/* 200 */ NdrFcShort( 0x8 ), /* 8 */ +/* 202 */ 0x47, /* Oi2 Flags: srv must size, clt must size, has return, has ext, */ 0x3, /* 3 */ -/* 280 */ 0xe, /* 14 */ +/* 204 */ 0xe, /* 14 */ 0x7, /* Ext Flags: new corr desc, clt corr check, srv corr check, */ -/* 282 */ NdrFcShort( 0x1 ), /* 1 */ -/* 284 */ NdrFcShort( 0x1 ), /* 1 */ -/* 286 */ NdrFcShort( 0x0 ), /* 0 */ -/* 288 */ NdrFcShort( 0x3 ), /* 3 */ -/* 290 */ 0x3, /* 3 */ +/* 206 */ NdrFcShort( 0x1 ), /* 1 */ +/* 208 */ NdrFcShort( 0x1 ), /* 1 */ +/* 210 */ NdrFcShort( 0x0 ), /* 0 */ +/* 212 */ NdrFcShort( 0x3 ), /* 3 */ +/* 214 */ 0x3, /* 3 */ 0x80, /* 128 */ -/* 292 */ 0x81, /* 129 */ +/* 216 */ 0x81, /* 129 */ 0x82, /* 130 */ /* Parameter authentication_info */ -/* 294 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 296 */ NdrFcShort( 0x8 ), /* ARM64 Stack size/offset = 8 */ -/* 298 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 218 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 220 */ NdrFcShort( 0x8 ), /* ARM64 Stack size/offset = 8 */ +/* 222 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Parameter status_text */ -/* 300 */ NdrFcShort( 0x2113 ), /* Flags: must size, must free, out, simple ref, srv alloc size=8 */ -/* 302 */ NdrFcShort( 0x10 ), /* ARM64 Stack size/offset = 16 */ -/* 304 */ NdrFcShort( 0x56 ), /* Type Offset=86 */ +/* 224 */ NdrFcShort( 0x2113 ), /* Flags: must size, must free, out, simple ref, srv alloc size=8 */ +/* 226 */ NdrFcShort( 0x10 ), /* ARM64 Stack size/offset = 16 */ +/* 228 */ NdrFcShort( 0x56 ), /* Type Offset=86 */ /* Return value */ -/* 306 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 308 */ NdrFcShort( 0x18 ), /* ARM64 Stack size/offset = 24 */ -/* 310 */ 0x8, /* FC_LONG */ +/* 230 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 232 */ NdrFcShort( 0x18 ), /* ARM64 Stack size/offset = 24 */ +/* 234 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure ReportError */ -/* 312 */ 0x33, /* FC_AUTO_HANDLE */ +/* 236 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ -/* 314 */ NdrFcLong( 0x0 ), /* 0 */ -/* 318 */ NdrFcShort( 0x6 ), /* 6 */ -/* 320 */ NdrFcShort( 0x28 ), /* ARM64 Stack size/offset = 40 */ -/* 322 */ NdrFcShort( 0x10 ), /* 16 */ -/* 324 */ NdrFcShort( 0x8 ), /* 8 */ -/* 326 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ +/* 238 */ NdrFcLong( 0x0 ), /* 0 */ +/* 242 */ NdrFcShort( 0x6 ), /* 6 */ +/* 244 */ NdrFcShort( 0x28 ), /* ARM64 Stack size/offset = 40 */ +/* 246 */ NdrFcShort( 0x10 ), /* 16 */ +/* 248 */ NdrFcShort( 0x8 ), /* 8 */ +/* 250 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ 0x4, /* 4 */ -/* 328 */ 0x10, /* 16 */ +/* 252 */ 0x10, /* 16 */ 0x5, /* Ext Flags: new corr desc, srv corr check, */ -/* 330 */ NdrFcShort( 0x0 ), /* 0 */ -/* 332 */ NdrFcShort( 0x1 ), /* 1 */ -/* 334 */ NdrFcShort( 0x0 ), /* 0 */ -/* 336 */ NdrFcShort( 0x4 ), /* 4 */ -/* 338 */ 0x4, /* 4 */ +/* 254 */ NdrFcShort( 0x0 ), /* 0 */ +/* 256 */ NdrFcShort( 0x1 ), /* 1 */ +/* 258 */ NdrFcShort( 0x0 ), /* 0 */ +/* 260 */ NdrFcShort( 0x4 ), /* 4 */ +/* 262 */ 0x4, /* 4 */ 0x80, /* 128 */ -/* 340 */ 0x81, /* 129 */ +/* 264 */ 0x81, /* 129 */ 0x82, /* 130 */ -/* 342 */ 0x83, /* 131 */ +/* 266 */ 0x83, /* 131 */ 0x0, /* 0 */ /* Parameter status */ -/* 344 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ -/* 346 */ NdrFcShort( 0x8 ), /* ARM64 Stack size/offset = 8 */ -/* 348 */ 0x8, /* FC_LONG */ +/* 268 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 270 */ NdrFcShort( 0x8 ), /* ARM64 Stack size/offset = 8 */ +/* 272 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Parameter substatus */ -/* 350 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ -/* 352 */ NdrFcShort( 0x10 ), /* ARM64 Stack size/offset = 16 */ -/* 354 */ 0x8, /* FC_LONG */ +/* 274 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 276 */ NdrFcShort( 0x10 ), /* ARM64 Stack size/offset = 16 */ +/* 278 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Parameter status_text */ -/* 356 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 358 */ NdrFcShort( 0x18 ), /* ARM64 Stack size/offset = 24 */ -/* 360 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 280 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 282 */ NdrFcShort( 0x18 ), /* ARM64 Stack size/offset = 24 */ +/* 284 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Return value */ -/* 362 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 364 */ NdrFcShort( 0x20 ), /* ARM64 Stack size/offset = 32 */ -/* 366 */ 0x8, /* FC_LONG */ +/* 286 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 288 */ NdrFcShort( 0x20 ), /* ARM64 Stack size/offset = 32 */ +/* 290 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure SetEmailForReauth */ -/* 368 */ 0x33, /* FC_AUTO_HANDLE */ +/* 292 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ -/* 370 */ NdrFcLong( 0x0 ), /* 0 */ -/* 374 */ NdrFcShort( 0x3 ), /* 3 */ -/* 376 */ NdrFcShort( 0x18 ), /* ARM64 Stack size/offset = 24 */ -/* 378 */ NdrFcShort( 0x0 ), /* 0 */ -/* 380 */ NdrFcShort( 0x8 ), /* 8 */ -/* 382 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ +/* 294 */ NdrFcLong( 0x0 ), /* 0 */ +/* 298 */ NdrFcShort( 0x3 ), /* 3 */ +/* 300 */ NdrFcShort( 0x18 ), /* ARM64 Stack size/offset = 24 */ +/* 302 */ NdrFcShort( 0x0 ), /* 0 */ +/* 304 */ NdrFcShort( 0x8 ), /* 8 */ +/* 306 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ 0x2, /* 2 */ -/* 384 */ 0xe, /* 14 */ +/* 308 */ 0xe, /* 14 */ 0x5, /* Ext Flags: new corr desc, srv corr check, */ -/* 386 */ NdrFcShort( 0x0 ), /* 0 */ -/* 388 */ NdrFcShort( 0x1 ), /* 1 */ -/* 390 */ NdrFcShort( 0x0 ), /* 0 */ -/* 392 */ NdrFcShort( 0x2 ), /* 2 */ -/* 394 */ 0x2, /* 2 */ +/* 310 */ NdrFcShort( 0x0 ), /* 0 */ +/* 312 */ NdrFcShort( 0x1 ), /* 1 */ +/* 314 */ NdrFcShort( 0x0 ), /* 0 */ +/* 316 */ NdrFcShort( 0x2 ), /* 2 */ +/* 318 */ 0x2, /* 2 */ 0x80, /* 128 */ -/* 396 */ 0x81, /* 129 */ +/* 320 */ 0x81, /* 129 */ 0x0, /* 0 */ /* Parameter email */ -/* 398 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 400 */ NdrFcShort( 0x8 ), /* ARM64 Stack size/offset = 8 */ -/* 402 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 322 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 324 */ NdrFcShort( 0x8 ), /* ARM64 Stack size/offset = 8 */ +/* 326 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Return value */ -/* 404 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 406 */ NdrFcShort( 0x10 ), /* ARM64 Stack size/offset = 16 */ -/* 408 */ 0x8, /* FC_LONG */ +/* 328 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 330 */ NdrFcShort( 0x10 ), /* ARM64 Stack size/offset = 16 */ +/* 332 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure SetOSUserInfo */ -/* 410 */ 0x33, /* FC_AUTO_HANDLE */ +/* 334 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ -/* 412 */ NdrFcLong( 0x0 ), /* 0 */ -/* 416 */ NdrFcShort( 0x4 ), /* 4 */ -/* 418 */ NdrFcShort( 0x28 ), /* ARM64 Stack size/offset = 40 */ -/* 420 */ NdrFcShort( 0x0 ), /* 0 */ -/* 422 */ NdrFcShort( 0x8 ), /* 8 */ -/* 424 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ +/* 336 */ NdrFcLong( 0x0 ), /* 0 */ +/* 340 */ NdrFcShort( 0x4 ), /* 4 */ +/* 342 */ NdrFcShort( 0x28 ), /* ARM64 Stack size/offset = 40 */ +/* 344 */ NdrFcShort( 0x0 ), /* 0 */ +/* 346 */ NdrFcShort( 0x8 ), /* 8 */ +/* 348 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ 0x4, /* 4 */ -/* 426 */ 0x10, /* 16 */ +/* 350 */ 0x10, /* 16 */ 0x5, /* Ext Flags: new corr desc, srv corr check, */ -/* 428 */ NdrFcShort( 0x0 ), /* 0 */ -/* 430 */ NdrFcShort( 0x1 ), /* 1 */ -/* 432 */ NdrFcShort( 0x0 ), /* 0 */ -/* 434 */ NdrFcShort( 0x4 ), /* 4 */ -/* 436 */ 0x4, /* 4 */ +/* 352 */ NdrFcShort( 0x0 ), /* 0 */ +/* 354 */ NdrFcShort( 0x1 ), /* 1 */ +/* 356 */ NdrFcShort( 0x0 ), /* 0 */ +/* 358 */ NdrFcShort( 0x4 ), /* 4 */ +/* 360 */ 0x4, /* 4 */ 0x80, /* 128 */ -/* 438 */ 0x81, /* 129 */ +/* 362 */ 0x81, /* 129 */ 0x82, /* 130 */ -/* 440 */ 0x83, /* 131 */ +/* 364 */ 0x83, /* 131 */ 0x0, /* 0 */ /* Parameter sid */ -/* 442 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 444 */ NdrFcShort( 0x8 ), /* ARM64 Stack size/offset = 8 */ -/* 446 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 366 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 368 */ NdrFcShort( 0x8 ), /* ARM64 Stack size/offset = 8 */ +/* 370 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Parameter domain */ -/* 448 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 450 */ NdrFcShort( 0x10 ), /* ARM64 Stack size/offset = 16 */ -/* 452 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 372 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 374 */ NdrFcShort( 0x10 ), /* ARM64 Stack size/offset = 16 */ +/* 376 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Parameter username */ -/* 454 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 456 */ NdrFcShort( 0x18 ), /* ARM64 Stack size/offset = 24 */ -/* 458 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 378 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 380 */ NdrFcShort( 0x18 ), /* ARM64 Stack size/offset = 24 */ +/* 382 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Return value */ -/* 460 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 462 */ NdrFcShort( 0x20 ), /* ARM64 Stack size/offset = 32 */ -/* 464 */ 0x8, /* FC_LONG */ +/* 384 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 386 */ NdrFcShort( 0x20 ), /* ARM64 Stack size/offset = 32 */ +/* 388 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ 0x0 @@ -631,8 +561,7 @@ static const unsigned short IGaiaCredentialProvider_FormatStringOffsetTable[] = { 0, - 42, - 112 + 42 }; static const MIDL_STUBLESS_PROXY_INFO IGaiaCredentialProvider_ProxyInfo = @@ -656,7 +585,7 @@ 0, 0, 0}; -CINTERFACE_PROXY_VTABLE(6) _IGaiaCredentialProviderProxyVtbl = +CINTERFACE_PROXY_VTABLE(5) _IGaiaCredentialProviderProxyVtbl = { &IGaiaCredentialProvider_ProxyInfo, &IID_IGaiaCredentialProvider, @@ -664,69 +593,14 @@ IUnknown_AddRef_Proxy, IUnknown_Release_Proxy , (void *) (INT_PTR) -1 /* IGaiaCredentialProvider::GetUsageScenario */ , - (void *) (INT_PTR) -1 /* IGaiaCredentialProvider::OnUserAuthenticated */ , - (void *) (INT_PTR) -1 /* IGaiaCredentialProvider::HasInternetConnection */ + (void *) (INT_PTR) -1 /* IGaiaCredentialProvider::OnUserAuthenticated */ }; const CInterfaceStubVtbl _IGaiaCredentialProviderStubVtbl = { &IID_IGaiaCredentialProvider, &IGaiaCredentialProvider_ServerInfo, - 6, - 0, /* pure interpreted */ - CStdStubBuffer_METHODS -}; - - -/* Standard interface: __MIDL_itf_gaia_credential_provider_0000_0001, ver. 0.0, - GUID={0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}} */ - - -/* Object interface: IGaiaCredentialProviderForTesting, ver. 0.0, - GUID={0x224CE2FB,0x2977,0x4585,{0xBD,0x46,0x1B,0xAE,0x8D,0x79,0x64,0xDE}} */ - -#pragma code_seg(".orpc") -static const unsigned short IGaiaCredentialProviderForTesting_FormatStringOffsetTable[] = - { - 146 - }; - -static const MIDL_STUBLESS_PROXY_INFO IGaiaCredentialProviderForTesting_ProxyInfo = - { - &Object_StubDesc, - gaia_credential_provider__MIDL_ProcFormatString.Format, - &IGaiaCredentialProviderForTesting_FormatStringOffsetTable[-3], - 0, - 0, - 0 - }; - - -static const MIDL_SERVER_INFO IGaiaCredentialProviderForTesting_ServerInfo = - { - &Object_StubDesc, - 0, - gaia_credential_provider__MIDL_ProcFormatString.Format, - &IGaiaCredentialProviderForTesting_FormatStringOffsetTable[-3], - 0, - 0, - 0, - 0}; -CINTERFACE_PROXY_VTABLE(4) _IGaiaCredentialProviderForTestingProxyVtbl = -{ - &IGaiaCredentialProviderForTesting_ProxyInfo, - &IID_IGaiaCredentialProviderForTesting, - IUnknown_QueryInterface_Proxy, - IUnknown_AddRef_Proxy, - IUnknown_Release_Proxy , - (void *) (INT_PTR) -1 /* IGaiaCredentialProviderForTesting::SetHasInternetConnection */ -}; - -const CInterfaceStubVtbl _IGaiaCredentialProviderForTestingStubVtbl = -{ - &IID_IGaiaCredentialProviderForTesting, - &IGaiaCredentialProviderForTesting_ServerInfo, - 4, + 5, 0, /* pure interpreted */ CStdStubBuffer_METHODS }; @@ -738,10 +612,10 @@ #pragma code_seg(".orpc") static const unsigned short IGaiaCredential_FormatStringOffsetTable[] = { + 112, + 154, 188, - 230, - 264, - 312 + 236 }; static const MIDL_STUBLESS_PROXY_INFO IGaiaCredential_ProxyInfo = @@ -794,8 +668,8 @@ #pragma code_seg(".orpc") static const unsigned short IReauthCredential_FormatStringOffsetTable[] = { - 368, - 410 + 292, + 334 }; static const MIDL_STUBLESS_PROXY_INFO IReauthCredential_ProxyInfo = @@ -868,7 +742,6 @@ ( CInterfaceProxyVtbl *) &_IGaiaCredentialProviderProxyVtbl, ( CInterfaceProxyVtbl *) &_IGaiaCredentialProxyVtbl, ( CInterfaceProxyVtbl *) &_IReauthCredentialProxyVtbl, - ( CInterfaceProxyVtbl *) &_IGaiaCredentialProviderForTestingProxyVtbl, 0 }; @@ -877,7 +750,6 @@ ( CInterfaceStubVtbl *) &_IGaiaCredentialProviderStubVtbl, ( CInterfaceStubVtbl *) &_IGaiaCredentialStubVtbl, ( CInterfaceStubVtbl *) &_IReauthCredentialStubVtbl, - ( CInterfaceStubVtbl *) &_IGaiaCredentialProviderForTestingStubVtbl, 0 }; @@ -886,7 +758,6 @@ "IGaiaCredentialProvider", "IGaiaCredential", "IReauthCredential", - "IGaiaCredentialProviderForTesting", 0 }; @@ -897,9 +768,9 @@ { IID_BS_LOOKUP_SETUP - IID_BS_LOOKUP_INITIAL_TEST( _gaia_credential_provider, 4, 2 ) + IID_BS_LOOKUP_INITIAL_TEST( _gaia_credential_provider, 3, 2 ) IID_BS_LOOKUP_NEXT_TEST( _gaia_credential_provider, 1 ) - IID_BS_LOOKUP_RETURN_RESULT( _gaia_credential_provider, 4, *pIndex ) + IID_BS_LOOKUP_RETURN_RESULT( _gaia_credential_provider, 3, *pIndex ) } @@ -910,7 +781,7 @@ (const PCInterfaceName * ) & _gaia_credential_provider_InterfaceNamesList, 0, /* no delegation */ & _gaia_credential_provider_IID_Lookup, - 4, + 3, 2, 0, /* table of [async_uuid] interfaces */ 0, /* Filler1 */
diff --git a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x64/gaia_credential_provider.tlb b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x64/gaia_credential_provider.tlb index 58a88cd..0d764da 100644 --- a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x64/gaia_credential_provider.tlb +++ b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x64/gaia_credential_provider.tlb Binary files differ
diff --git a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x64/gaia_credential_provider_i.c b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x64/gaia_credential_provider_i.c index fdcf5eeb..dd728df 100644 --- a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x64/gaia_credential_provider_i.c +++ b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x64/gaia_credential_provider_i.c
@@ -70,9 +70,6 @@ MIDL_DEFINE_GUID(IID, IID_IGaiaCredentialProvider,0xCEC9EF6C,0xB2E6,0x4BB6,0x8F,0x1E,0x17,0x47,0xBA,0x4F,0x71,0x38); -MIDL_DEFINE_GUID(IID, IID_IGaiaCredentialProviderForTesting,0x224CE2FB,0x2977,0x4585,0xBD,0x46,0x1B,0xAE,0x8D,0x79,0x64,0xDE); - - MIDL_DEFINE_GUID(IID, IID_IGaiaCredential,0xE5BF88DF,0x9966,0x465B,0xB2,0x33,0xC1,0xCA,0xC7,0x51,0x0A,0x59);
diff --git a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x64/gaia_credential_provider_i.h b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x64/gaia_credential_provider_i.h index 67e22f0..8e07bab 100644 --- a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x64/gaia_credential_provider_i.h +++ b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x64/gaia_credential_provider_i.h
@@ -52,13 +52,6 @@ #endif /* __IGaiaCredentialProvider_FWD_DEFINED__ */ -#ifndef __IGaiaCredentialProviderForTesting_FWD_DEFINED__ -#define __IGaiaCredentialProviderForTesting_FWD_DEFINED__ -typedef interface IGaiaCredentialProviderForTesting IGaiaCredentialProviderForTesting; - -#endif /* __IGaiaCredentialProviderForTesting_FWD_DEFINED__ */ - - #ifndef __IGaiaCredential_FWD_DEFINED__ #define __IGaiaCredential_FWD_DEFINED__ typedef interface IGaiaCredential IGaiaCredential; @@ -119,8 +112,6 @@ /* [in] */ BSTR sid, /* [in] */ BOOL fire_credentials_changed) = 0; - virtual HRESULT STDMETHODCALLTYPE HasInternetConnection( void) = 0; - }; @@ -154,9 +145,6 @@ /* [in] */ BSTR sid, /* [in] */ BOOL fire_credentials_changed); - HRESULT ( STDMETHODCALLTYPE *HasInternetConnection )( - IGaiaCredentialProvider * This); - END_INTERFACE } IGaiaCredentialProviderVtbl; @@ -186,9 +174,6 @@ #define IGaiaCredentialProvider_OnUserAuthenticated(This,credential,username,password,sid,fire_credentials_changed) \ ( (This)->lpVtbl -> OnUserAuthenticated(This,credential,username,password,sid,fire_credentials_changed) ) -#define IGaiaCredentialProvider_HasInternetConnection(This) \ - ( (This)->lpVtbl -> HasInternetConnection(This) ) - #endif /* COBJMACROS */ @@ -200,102 +185,6 @@ #endif /* __IGaiaCredentialProvider_INTERFACE_DEFINED__ */ -/* interface __MIDL_itf_gaia_credential_provider_0000_0001 */ -/* [local] */ - -typedef /* [public][public] */ -enum __MIDL___MIDL_itf_gaia_credential_provider_0000_0001_0001 - { - kHicForceYes = 0, - kHicForceNo = ( kHicForceYes + 1 ) , - kHicCheckAlways = ( kHicForceNo + 1 ) - } HasInternetConnectionCheckType; - - - -extern RPC_IF_HANDLE __MIDL_itf_gaia_credential_provider_0000_0001_v0_0_c_ifspec; -extern RPC_IF_HANDLE __MIDL_itf_gaia_credential_provider_0000_0001_v0_0_s_ifspec; - -#ifndef __IGaiaCredentialProviderForTesting_INTERFACE_DEFINED__ -#define __IGaiaCredentialProviderForTesting_INTERFACE_DEFINED__ - -/* interface IGaiaCredentialProviderForTesting */ -/* [unique][uuid][object] */ - - -EXTERN_C const IID IID_IGaiaCredentialProviderForTesting; - -#if defined(__cplusplus) && !defined(CINTERFACE) - - MIDL_INTERFACE("224CE2FB-2977-4585-BD46-1BAE8D7964DE") - IGaiaCredentialProviderForTesting : public IUnknown - { - public: - virtual HRESULT STDMETHODCALLTYPE SetHasInternetConnection( - /* [in] */ HasInternetConnectionCheckType hic) = 0; - - }; - - -#else /* C style interface */ - - typedef struct IGaiaCredentialProviderForTestingVtbl - { - BEGIN_INTERFACE - - HRESULT ( STDMETHODCALLTYPE *QueryInterface )( - IGaiaCredentialProviderForTesting * This, - /* [in] */ REFIID riid, - /* [annotation][iid_is][out] */ - _COM_Outptr_ void **ppvObject); - - ULONG ( STDMETHODCALLTYPE *AddRef )( - IGaiaCredentialProviderForTesting * This); - - ULONG ( STDMETHODCALLTYPE *Release )( - IGaiaCredentialProviderForTesting * This); - - HRESULT ( STDMETHODCALLTYPE *SetHasInternetConnection )( - IGaiaCredentialProviderForTesting * This, - /* [in] */ HasInternetConnectionCheckType hic); - - END_INTERFACE - } IGaiaCredentialProviderForTestingVtbl; - - interface IGaiaCredentialProviderForTesting - { - CONST_VTBL struct IGaiaCredentialProviderForTestingVtbl *lpVtbl; - }; - - - -#ifdef COBJMACROS - - -#define IGaiaCredentialProviderForTesting_QueryInterface(This,riid,ppvObject) \ - ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) - -#define IGaiaCredentialProviderForTesting_AddRef(This) \ - ( (This)->lpVtbl -> AddRef(This) ) - -#define IGaiaCredentialProviderForTesting_Release(This) \ - ( (This)->lpVtbl -> Release(This) ) - - -#define IGaiaCredentialProviderForTesting_SetHasInternetConnection(This,hic) \ - ( (This)->lpVtbl -> SetHasInternetConnection(This,hic) ) - -#endif /* COBJMACROS */ - - -#endif /* C style interface */ - - - - -#endif /* __IGaiaCredentialProviderForTesting_INTERFACE_DEFINED__ */ - - #ifndef __IGaiaCredential_INTERFACE_DEFINED__ #define __IGaiaCredential_INTERFACE_DEFINED__
diff --git a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x64/gaia_credential_provider_p.c b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x64/gaia_credential_provider_p.c index 924e563..18a8c05 100644 --- a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x64/gaia_credential_provider_p.c +++ b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x64/gaia_credential_provider_p.c
@@ -47,7 +47,7 @@ #include "gaia_credential_provider_i.h" #define TYPE_FORMAT_STRING_SIZE 97 -#define PROC_FORMAT_STRING_SIZE 423 +#define PROC_FORMAT_STRING_SIZE 353 #define EXPR_FORMAT_STRING_SIZE 1 #define TRANSMIT_AS_TABLE_SIZE 0 #define WIRE_MARSHAL_TABLE_SIZE 1 @@ -90,13 +90,6 @@ extern const MIDL_STUB_DESC Object_StubDesc; -extern const MIDL_SERVER_INFO IGaiaCredentialProviderForTesting_ServerInfo; -extern const MIDL_STUBLESS_PROXY_INFO IGaiaCredentialProviderForTesting_ProxyInfo; - - -extern const MIDL_STUB_DESC Object_StubDesc; - - extern const MIDL_SERVER_INFO IGaiaCredential_ServerInfo; extern const MIDL_STUBLESS_PROXY_INFO IGaiaCredential_ProxyInfo; @@ -207,17 +200,17 @@ /* 98 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ - /* Procedure HasInternetConnection */ + /* Procedure Initialize */ /* 100 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ /* 102 */ NdrFcLong( 0x0 ), /* 0 */ -/* 106 */ NdrFcShort( 0x5 ), /* 5 */ -/* 108 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 106 */ NdrFcShort( 0x3 ), /* 3 */ +/* 108 */ NdrFcShort( 0x18 ), /* X64 Stack size/offset = 24 */ /* 110 */ NdrFcShort( 0x0 ), /* 0 */ /* 112 */ NdrFcShort( 0x8 ), /* 8 */ -/* 114 */ 0x44, /* Oi2 Flags: has return, has ext, */ - 0x1, /* 1 */ +/* 114 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ + 0x2, /* 2 */ /* 116 */ 0xa, /* 10 */ 0x1, /* Ext Flags: new corr desc, */ /* 118 */ NdrFcShort( 0x0 ), /* 0 */ @@ -225,255 +218,198 @@ /* 122 */ NdrFcShort( 0x0 ), /* 0 */ /* 124 */ NdrFcShort( 0x0 ), /* 0 */ - /* Return value */ - -/* 126 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 128 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ -/* 130 */ 0x8, /* FC_LONG */ - 0x0, /* 0 */ - - /* Procedure SetHasInternetConnection */ - -/* 132 */ 0x33, /* FC_AUTO_HANDLE */ - 0x6c, /* Old Flags: object, Oi2 */ -/* 134 */ NdrFcLong( 0x0 ), /* 0 */ -/* 138 */ NdrFcShort( 0x3 ), /* 3 */ -/* 140 */ NdrFcShort( 0x18 ), /* X64 Stack size/offset = 24 */ -/* 142 */ NdrFcShort( 0x6 ), /* 6 */ -/* 144 */ NdrFcShort( 0x8 ), /* 8 */ -/* 146 */ 0x44, /* Oi2 Flags: has return, has ext, */ - 0x2, /* 2 */ -/* 148 */ 0xa, /* 10 */ - 0x1, /* Ext Flags: new corr desc, */ -/* 150 */ NdrFcShort( 0x0 ), /* 0 */ -/* 152 */ NdrFcShort( 0x0 ), /* 0 */ -/* 154 */ NdrFcShort( 0x0 ), /* 0 */ -/* 156 */ NdrFcShort( 0x0 ), /* 0 */ - - /* Parameter hic */ - -/* 158 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ -/* 160 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ -/* 162 */ 0xd, /* FC_ENUM16 */ - 0x0, /* 0 */ - - /* Return value */ - -/* 164 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 166 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ -/* 168 */ 0x8, /* FC_LONG */ - 0x0, /* 0 */ - - /* Procedure Initialize */ - -/* 170 */ 0x33, /* FC_AUTO_HANDLE */ - 0x6c, /* Old Flags: object, Oi2 */ -/* 172 */ NdrFcLong( 0x0 ), /* 0 */ -/* 176 */ NdrFcShort( 0x3 ), /* 3 */ -/* 178 */ NdrFcShort( 0x18 ), /* X64 Stack size/offset = 24 */ -/* 180 */ NdrFcShort( 0x0 ), /* 0 */ -/* 182 */ NdrFcShort( 0x8 ), /* 8 */ -/* 184 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ - 0x2, /* 2 */ -/* 186 */ 0xa, /* 10 */ - 0x1, /* Ext Flags: new corr desc, */ -/* 188 */ NdrFcShort( 0x0 ), /* 0 */ -/* 190 */ NdrFcShort( 0x0 ), /* 0 */ -/* 192 */ NdrFcShort( 0x0 ), /* 0 */ -/* 194 */ NdrFcShort( 0x0 ), /* 0 */ - /* Parameter provider */ -/* 196 */ NdrFcShort( 0xb ), /* Flags: must size, must free, in, */ -/* 198 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ -/* 200 */ NdrFcShort( 0x3c ), /* Type Offset=60 */ +/* 126 */ NdrFcShort( 0xb ), /* Flags: must size, must free, in, */ +/* 128 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 130 */ NdrFcShort( 0x3c ), /* Type Offset=60 */ /* Return value */ -/* 202 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 204 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ -/* 206 */ 0x8, /* FC_LONG */ +/* 132 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 134 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 136 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure Terminate */ -/* 208 */ 0x33, /* FC_AUTO_HANDLE */ +/* 138 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ -/* 210 */ NdrFcLong( 0x0 ), /* 0 */ -/* 214 */ NdrFcShort( 0x4 ), /* 4 */ -/* 216 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ -/* 218 */ NdrFcShort( 0x0 ), /* 0 */ -/* 220 */ NdrFcShort( 0x8 ), /* 8 */ -/* 222 */ 0x44, /* Oi2 Flags: has return, has ext, */ +/* 140 */ NdrFcLong( 0x0 ), /* 0 */ +/* 144 */ NdrFcShort( 0x4 ), /* 4 */ +/* 146 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 148 */ NdrFcShort( 0x0 ), /* 0 */ +/* 150 */ NdrFcShort( 0x8 ), /* 8 */ +/* 152 */ 0x44, /* Oi2 Flags: has return, has ext, */ 0x1, /* 1 */ -/* 224 */ 0xa, /* 10 */ +/* 154 */ 0xa, /* 10 */ 0x1, /* Ext Flags: new corr desc, */ -/* 226 */ NdrFcShort( 0x0 ), /* 0 */ -/* 228 */ NdrFcShort( 0x0 ), /* 0 */ -/* 230 */ NdrFcShort( 0x0 ), /* 0 */ -/* 232 */ NdrFcShort( 0x0 ), /* 0 */ +/* 156 */ NdrFcShort( 0x0 ), /* 0 */ +/* 158 */ NdrFcShort( 0x0 ), /* 0 */ +/* 160 */ NdrFcShort( 0x0 ), /* 0 */ +/* 162 */ NdrFcShort( 0x0 ), /* 0 */ /* Return value */ -/* 234 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 236 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ -/* 238 */ 0x8, /* FC_LONG */ +/* 164 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 166 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 168 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure OnUserAuthenticated */ -/* 240 */ 0x33, /* FC_AUTO_HANDLE */ +/* 170 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ -/* 242 */ NdrFcLong( 0x0 ), /* 0 */ -/* 246 */ NdrFcShort( 0x5 ), /* 5 */ -/* 248 */ NdrFcShort( 0x20 ), /* X64 Stack size/offset = 32 */ -/* 250 */ NdrFcShort( 0x0 ), /* 0 */ -/* 252 */ NdrFcShort( 0x8 ), /* 8 */ -/* 254 */ 0x47, /* Oi2 Flags: srv must size, clt must size, has return, has ext, */ +/* 172 */ NdrFcLong( 0x0 ), /* 0 */ +/* 176 */ NdrFcShort( 0x5 ), /* 5 */ +/* 178 */ NdrFcShort( 0x20 ), /* X64 Stack size/offset = 32 */ +/* 180 */ NdrFcShort( 0x0 ), /* 0 */ +/* 182 */ NdrFcShort( 0x8 ), /* 8 */ +/* 184 */ 0x47, /* Oi2 Flags: srv must size, clt must size, has return, has ext, */ 0x3, /* 3 */ -/* 256 */ 0xa, /* 10 */ +/* 186 */ 0xa, /* 10 */ 0x7, /* Ext Flags: new corr desc, clt corr check, srv corr check, */ -/* 258 */ NdrFcShort( 0x1 ), /* 1 */ -/* 260 */ NdrFcShort( 0x1 ), /* 1 */ -/* 262 */ NdrFcShort( 0x0 ), /* 0 */ -/* 264 */ NdrFcShort( 0x0 ), /* 0 */ +/* 188 */ NdrFcShort( 0x1 ), /* 1 */ +/* 190 */ NdrFcShort( 0x1 ), /* 1 */ +/* 192 */ NdrFcShort( 0x0 ), /* 0 */ +/* 194 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter authentication_info */ -/* 266 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 268 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ -/* 270 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 196 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 198 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 200 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Parameter status_text */ -/* 272 */ NdrFcShort( 0x2113 ), /* Flags: must size, must free, out, simple ref, srv alloc size=8 */ -/* 274 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ -/* 276 */ NdrFcShort( 0x56 ), /* Type Offset=86 */ +/* 202 */ NdrFcShort( 0x2113 ), /* Flags: must size, must free, out, simple ref, srv alloc size=8 */ +/* 204 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 206 */ NdrFcShort( 0x56 ), /* Type Offset=86 */ /* Return value */ -/* 278 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 280 */ NdrFcShort( 0x18 ), /* X64 Stack size/offset = 24 */ -/* 282 */ 0x8, /* FC_LONG */ +/* 208 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 210 */ NdrFcShort( 0x18 ), /* X64 Stack size/offset = 24 */ +/* 212 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure ReportError */ -/* 284 */ 0x33, /* FC_AUTO_HANDLE */ +/* 214 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ -/* 286 */ NdrFcLong( 0x0 ), /* 0 */ -/* 290 */ NdrFcShort( 0x6 ), /* 6 */ -/* 292 */ NdrFcShort( 0x28 ), /* X64 Stack size/offset = 40 */ -/* 294 */ NdrFcShort( 0x10 ), /* 16 */ -/* 296 */ NdrFcShort( 0x8 ), /* 8 */ -/* 298 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ +/* 216 */ NdrFcLong( 0x0 ), /* 0 */ +/* 220 */ NdrFcShort( 0x6 ), /* 6 */ +/* 222 */ NdrFcShort( 0x28 ), /* X64 Stack size/offset = 40 */ +/* 224 */ NdrFcShort( 0x10 ), /* 16 */ +/* 226 */ NdrFcShort( 0x8 ), /* 8 */ +/* 228 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ 0x4, /* 4 */ -/* 300 */ 0xa, /* 10 */ +/* 230 */ 0xa, /* 10 */ 0x5, /* Ext Flags: new corr desc, srv corr check, */ -/* 302 */ NdrFcShort( 0x0 ), /* 0 */ -/* 304 */ NdrFcShort( 0x1 ), /* 1 */ -/* 306 */ NdrFcShort( 0x0 ), /* 0 */ -/* 308 */ NdrFcShort( 0x0 ), /* 0 */ +/* 232 */ NdrFcShort( 0x0 ), /* 0 */ +/* 234 */ NdrFcShort( 0x1 ), /* 1 */ +/* 236 */ NdrFcShort( 0x0 ), /* 0 */ +/* 238 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter status */ -/* 310 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ -/* 312 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ -/* 314 */ 0x8, /* FC_LONG */ +/* 240 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 242 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 244 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Parameter substatus */ -/* 316 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ -/* 318 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ -/* 320 */ 0x8, /* FC_LONG */ +/* 246 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 248 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 250 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Parameter status_text */ -/* 322 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 324 */ NdrFcShort( 0x18 ), /* X64 Stack size/offset = 24 */ -/* 326 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 252 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 254 */ NdrFcShort( 0x18 ), /* X64 Stack size/offset = 24 */ +/* 256 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Return value */ -/* 328 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 330 */ NdrFcShort( 0x20 ), /* X64 Stack size/offset = 32 */ -/* 332 */ 0x8, /* FC_LONG */ +/* 258 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 260 */ NdrFcShort( 0x20 ), /* X64 Stack size/offset = 32 */ +/* 262 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure SetEmailForReauth */ -/* 334 */ 0x33, /* FC_AUTO_HANDLE */ +/* 264 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ -/* 336 */ NdrFcLong( 0x0 ), /* 0 */ -/* 340 */ NdrFcShort( 0x3 ), /* 3 */ -/* 342 */ NdrFcShort( 0x18 ), /* X64 Stack size/offset = 24 */ -/* 344 */ NdrFcShort( 0x0 ), /* 0 */ -/* 346 */ NdrFcShort( 0x8 ), /* 8 */ -/* 348 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ +/* 266 */ NdrFcLong( 0x0 ), /* 0 */ +/* 270 */ NdrFcShort( 0x3 ), /* 3 */ +/* 272 */ NdrFcShort( 0x18 ), /* X64 Stack size/offset = 24 */ +/* 274 */ NdrFcShort( 0x0 ), /* 0 */ +/* 276 */ NdrFcShort( 0x8 ), /* 8 */ +/* 278 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ 0x2, /* 2 */ -/* 350 */ 0xa, /* 10 */ +/* 280 */ 0xa, /* 10 */ 0x5, /* Ext Flags: new corr desc, srv corr check, */ -/* 352 */ NdrFcShort( 0x0 ), /* 0 */ -/* 354 */ NdrFcShort( 0x1 ), /* 1 */ -/* 356 */ NdrFcShort( 0x0 ), /* 0 */ -/* 358 */ NdrFcShort( 0x0 ), /* 0 */ +/* 282 */ NdrFcShort( 0x0 ), /* 0 */ +/* 284 */ NdrFcShort( 0x1 ), /* 1 */ +/* 286 */ NdrFcShort( 0x0 ), /* 0 */ +/* 288 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter email */ -/* 360 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 362 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ -/* 364 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 290 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 292 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 294 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Return value */ -/* 366 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 368 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ -/* 370 */ 0x8, /* FC_LONG */ +/* 296 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 298 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 300 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure SetOSUserInfo */ -/* 372 */ 0x33, /* FC_AUTO_HANDLE */ +/* 302 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ -/* 374 */ NdrFcLong( 0x0 ), /* 0 */ -/* 378 */ NdrFcShort( 0x4 ), /* 4 */ -/* 380 */ NdrFcShort( 0x28 ), /* X64 Stack size/offset = 40 */ -/* 382 */ NdrFcShort( 0x0 ), /* 0 */ -/* 384 */ NdrFcShort( 0x8 ), /* 8 */ -/* 386 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ +/* 304 */ NdrFcLong( 0x0 ), /* 0 */ +/* 308 */ NdrFcShort( 0x4 ), /* 4 */ +/* 310 */ NdrFcShort( 0x28 ), /* X64 Stack size/offset = 40 */ +/* 312 */ NdrFcShort( 0x0 ), /* 0 */ +/* 314 */ NdrFcShort( 0x8 ), /* 8 */ +/* 316 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ 0x4, /* 4 */ -/* 388 */ 0xa, /* 10 */ +/* 318 */ 0xa, /* 10 */ 0x5, /* Ext Flags: new corr desc, srv corr check, */ -/* 390 */ NdrFcShort( 0x0 ), /* 0 */ -/* 392 */ NdrFcShort( 0x1 ), /* 1 */ -/* 394 */ NdrFcShort( 0x0 ), /* 0 */ -/* 396 */ NdrFcShort( 0x0 ), /* 0 */ +/* 320 */ NdrFcShort( 0x0 ), /* 0 */ +/* 322 */ NdrFcShort( 0x1 ), /* 1 */ +/* 324 */ NdrFcShort( 0x0 ), /* 0 */ +/* 326 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter sid */ -/* 398 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 400 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ -/* 402 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 328 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 330 */ NdrFcShort( 0x8 ), /* X64 Stack size/offset = 8 */ +/* 332 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Parameter domain */ -/* 404 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 406 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ -/* 408 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 334 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 336 */ NdrFcShort( 0x10 ), /* X64 Stack size/offset = 16 */ +/* 338 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Parameter username */ -/* 410 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 412 */ NdrFcShort( 0x18 ), /* X64 Stack size/offset = 24 */ -/* 414 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 340 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 342 */ NdrFcShort( 0x18 ), /* X64 Stack size/offset = 24 */ +/* 344 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Return value */ -/* 416 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 418 */ NdrFcShort( 0x20 ), /* X64 Stack size/offset = 32 */ -/* 420 */ 0x8, /* FC_LONG */ +/* 346 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 348 */ NdrFcShort( 0x20 ), /* X64 Stack size/offset = 32 */ +/* 350 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ 0x0 @@ -587,8 +523,7 @@ static const unsigned short IGaiaCredentialProvider_FormatStringOffsetTable[] = { 0, - 38, - 100 + 38 }; static const MIDL_STUBLESS_PROXY_INFO IGaiaCredentialProvider_ProxyInfo = @@ -612,7 +547,7 @@ 0, 0, 0}; -CINTERFACE_PROXY_VTABLE(6) _IGaiaCredentialProviderProxyVtbl = +CINTERFACE_PROXY_VTABLE(5) _IGaiaCredentialProviderProxyVtbl = { &IGaiaCredentialProvider_ProxyInfo, &IID_IGaiaCredentialProvider, @@ -620,69 +555,14 @@ IUnknown_AddRef_Proxy, IUnknown_Release_Proxy , (void *) (INT_PTR) -1 /* IGaiaCredentialProvider::GetUsageScenario */ , - (void *) (INT_PTR) -1 /* IGaiaCredentialProvider::OnUserAuthenticated */ , - (void *) (INT_PTR) -1 /* IGaiaCredentialProvider::HasInternetConnection */ + (void *) (INT_PTR) -1 /* IGaiaCredentialProvider::OnUserAuthenticated */ }; const CInterfaceStubVtbl _IGaiaCredentialProviderStubVtbl = { &IID_IGaiaCredentialProvider, &IGaiaCredentialProvider_ServerInfo, - 6, - 0, /* pure interpreted */ - CStdStubBuffer_METHODS -}; - - -/* Standard interface: __MIDL_itf_gaia_credential_provider_0000_0001, ver. 0.0, - GUID={0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}} */ - - -/* Object interface: IGaiaCredentialProviderForTesting, ver. 0.0, - GUID={0x224CE2FB,0x2977,0x4585,{0xBD,0x46,0x1B,0xAE,0x8D,0x79,0x64,0xDE}} */ - -#pragma code_seg(".orpc") -static const unsigned short IGaiaCredentialProviderForTesting_FormatStringOffsetTable[] = - { - 132 - }; - -static const MIDL_STUBLESS_PROXY_INFO IGaiaCredentialProviderForTesting_ProxyInfo = - { - &Object_StubDesc, - gaia_credential_provider__MIDL_ProcFormatString.Format, - &IGaiaCredentialProviderForTesting_FormatStringOffsetTable[-3], - 0, - 0, - 0 - }; - - -static const MIDL_SERVER_INFO IGaiaCredentialProviderForTesting_ServerInfo = - { - &Object_StubDesc, - 0, - gaia_credential_provider__MIDL_ProcFormatString.Format, - &IGaiaCredentialProviderForTesting_FormatStringOffsetTable[-3], - 0, - 0, - 0, - 0}; -CINTERFACE_PROXY_VTABLE(4) _IGaiaCredentialProviderForTestingProxyVtbl = -{ - &IGaiaCredentialProviderForTesting_ProxyInfo, - &IID_IGaiaCredentialProviderForTesting, - IUnknown_QueryInterface_Proxy, - IUnknown_AddRef_Proxy, - IUnknown_Release_Proxy , - (void *) (INT_PTR) -1 /* IGaiaCredentialProviderForTesting::SetHasInternetConnection */ -}; - -const CInterfaceStubVtbl _IGaiaCredentialProviderForTestingStubVtbl = -{ - &IID_IGaiaCredentialProviderForTesting, - &IGaiaCredentialProviderForTesting_ServerInfo, - 4, + 5, 0, /* pure interpreted */ CStdStubBuffer_METHODS }; @@ -694,10 +574,10 @@ #pragma code_seg(".orpc") static const unsigned short IGaiaCredential_FormatStringOffsetTable[] = { + 100, + 138, 170, - 208, - 240, - 284 + 214 }; static const MIDL_STUBLESS_PROXY_INFO IGaiaCredential_ProxyInfo = @@ -750,8 +630,8 @@ #pragma code_seg(".orpc") static const unsigned short IReauthCredential_FormatStringOffsetTable[] = { - 334, - 372 + 264, + 302 }; static const MIDL_STUBLESS_PROXY_INFO IReauthCredential_ProxyInfo = @@ -824,7 +704,6 @@ ( CInterfaceProxyVtbl *) &_IGaiaCredentialProviderProxyVtbl, ( CInterfaceProxyVtbl *) &_IGaiaCredentialProxyVtbl, ( CInterfaceProxyVtbl *) &_IReauthCredentialProxyVtbl, - ( CInterfaceProxyVtbl *) &_IGaiaCredentialProviderForTestingProxyVtbl, 0 }; @@ -833,7 +712,6 @@ ( CInterfaceStubVtbl *) &_IGaiaCredentialProviderStubVtbl, ( CInterfaceStubVtbl *) &_IGaiaCredentialStubVtbl, ( CInterfaceStubVtbl *) &_IReauthCredentialStubVtbl, - ( CInterfaceStubVtbl *) &_IGaiaCredentialProviderForTestingStubVtbl, 0 }; @@ -842,7 +720,6 @@ "IGaiaCredentialProvider", "IGaiaCredential", "IReauthCredential", - "IGaiaCredentialProviderForTesting", 0 }; @@ -853,9 +730,9 @@ { IID_BS_LOOKUP_SETUP - IID_BS_LOOKUP_INITIAL_TEST( _gaia_credential_provider, 4, 2 ) + IID_BS_LOOKUP_INITIAL_TEST( _gaia_credential_provider, 3, 2 ) IID_BS_LOOKUP_NEXT_TEST( _gaia_credential_provider, 1 ) - IID_BS_LOOKUP_RETURN_RESULT( _gaia_credential_provider, 4, *pIndex ) + IID_BS_LOOKUP_RETURN_RESULT( _gaia_credential_provider, 3, *pIndex ) } @@ -866,7 +743,7 @@ (const PCInterfaceName * ) & _gaia_credential_provider_InterfaceNamesList, 0, /* no delegation */ & _gaia_credential_provider_IID_Lookup, - 4, + 3, 2, 0, /* table of [async_uuid] interfaces */ 0, /* Filler1 */
diff --git a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x86/gaia_credential_provider.tlb b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x86/gaia_credential_provider.tlb index 72de774..2a4ba66 100644 --- a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x86/gaia_credential_provider.tlb +++ b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x86/gaia_credential_provider.tlb Binary files differ
diff --git a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x86/gaia_credential_provider_i.c b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x86/gaia_credential_provider_i.c index 3584b52..3a57962 100644 --- a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x86/gaia_credential_provider_i.c +++ b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x86/gaia_credential_provider_i.c
@@ -70,9 +70,6 @@ MIDL_DEFINE_GUID(IID, IID_IGaiaCredentialProvider,0xCEC9EF6C,0xB2E6,0x4BB6,0x8F,0x1E,0x17,0x47,0xBA,0x4F,0x71,0x38); -MIDL_DEFINE_GUID(IID, IID_IGaiaCredentialProviderForTesting,0x224CE2FB,0x2977,0x4585,0xBD,0x46,0x1B,0xAE,0x8D,0x79,0x64,0xDE); - - MIDL_DEFINE_GUID(IID, IID_IGaiaCredential,0xE5BF88DF,0x9966,0x465B,0xB2,0x33,0xC1,0xCA,0xC7,0x51,0x0A,0x59);
diff --git a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x86/gaia_credential_provider_i.h b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x86/gaia_credential_provider_i.h index 974e870..b16af3a 100644 --- a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x86/gaia_credential_provider_i.h +++ b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x86/gaia_credential_provider_i.h
@@ -52,13 +52,6 @@ #endif /* __IGaiaCredentialProvider_FWD_DEFINED__ */ -#ifndef __IGaiaCredentialProviderForTesting_FWD_DEFINED__ -#define __IGaiaCredentialProviderForTesting_FWD_DEFINED__ -typedef interface IGaiaCredentialProviderForTesting IGaiaCredentialProviderForTesting; - -#endif /* __IGaiaCredentialProviderForTesting_FWD_DEFINED__ */ - - #ifndef __IGaiaCredential_FWD_DEFINED__ #define __IGaiaCredential_FWD_DEFINED__ typedef interface IGaiaCredential IGaiaCredential; @@ -119,8 +112,6 @@ /* [in] */ BSTR sid, /* [in] */ BOOL fire_credentials_changed) = 0; - virtual HRESULT STDMETHODCALLTYPE HasInternetConnection( void) = 0; - }; @@ -154,9 +145,6 @@ /* [in] */ BSTR sid, /* [in] */ BOOL fire_credentials_changed); - HRESULT ( STDMETHODCALLTYPE *HasInternetConnection )( - IGaiaCredentialProvider * This); - END_INTERFACE } IGaiaCredentialProviderVtbl; @@ -186,9 +174,6 @@ #define IGaiaCredentialProvider_OnUserAuthenticated(This,credential,username,password,sid,fire_credentials_changed) \ ( (This)->lpVtbl -> OnUserAuthenticated(This,credential,username,password,sid,fire_credentials_changed) ) -#define IGaiaCredentialProvider_HasInternetConnection(This) \ - ( (This)->lpVtbl -> HasInternetConnection(This) ) - #endif /* COBJMACROS */ @@ -200,102 +185,6 @@ #endif /* __IGaiaCredentialProvider_INTERFACE_DEFINED__ */ -/* interface __MIDL_itf_gaia_credential_provider_0000_0001 */ -/* [local] */ - -typedef /* [public][public] */ -enum __MIDL___MIDL_itf_gaia_credential_provider_0000_0001_0001 - { - kHicForceYes = 0, - kHicForceNo = ( kHicForceYes + 1 ) , - kHicCheckAlways = ( kHicForceNo + 1 ) - } HasInternetConnectionCheckType; - - - -extern RPC_IF_HANDLE __MIDL_itf_gaia_credential_provider_0000_0001_v0_0_c_ifspec; -extern RPC_IF_HANDLE __MIDL_itf_gaia_credential_provider_0000_0001_v0_0_s_ifspec; - -#ifndef __IGaiaCredentialProviderForTesting_INTERFACE_DEFINED__ -#define __IGaiaCredentialProviderForTesting_INTERFACE_DEFINED__ - -/* interface IGaiaCredentialProviderForTesting */ -/* [unique][uuid][object] */ - - -EXTERN_C const IID IID_IGaiaCredentialProviderForTesting; - -#if defined(__cplusplus) && !defined(CINTERFACE) - - MIDL_INTERFACE("224CE2FB-2977-4585-BD46-1BAE8D7964DE") - IGaiaCredentialProviderForTesting : public IUnknown - { - public: - virtual HRESULT STDMETHODCALLTYPE SetHasInternetConnection( - /* [in] */ HasInternetConnectionCheckType hic) = 0; - - }; - - -#else /* C style interface */ - - typedef struct IGaiaCredentialProviderForTestingVtbl - { - BEGIN_INTERFACE - - HRESULT ( STDMETHODCALLTYPE *QueryInterface )( - IGaiaCredentialProviderForTesting * This, - /* [in] */ REFIID riid, - /* [annotation][iid_is][out] */ - _COM_Outptr_ void **ppvObject); - - ULONG ( STDMETHODCALLTYPE *AddRef )( - IGaiaCredentialProviderForTesting * This); - - ULONG ( STDMETHODCALLTYPE *Release )( - IGaiaCredentialProviderForTesting * This); - - HRESULT ( STDMETHODCALLTYPE *SetHasInternetConnection )( - IGaiaCredentialProviderForTesting * This, - /* [in] */ HasInternetConnectionCheckType hic); - - END_INTERFACE - } IGaiaCredentialProviderForTestingVtbl; - - interface IGaiaCredentialProviderForTesting - { - CONST_VTBL struct IGaiaCredentialProviderForTestingVtbl *lpVtbl; - }; - - - -#ifdef COBJMACROS - - -#define IGaiaCredentialProviderForTesting_QueryInterface(This,riid,ppvObject) \ - ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) - -#define IGaiaCredentialProviderForTesting_AddRef(This) \ - ( (This)->lpVtbl -> AddRef(This) ) - -#define IGaiaCredentialProviderForTesting_Release(This) \ - ( (This)->lpVtbl -> Release(This) ) - - -#define IGaiaCredentialProviderForTesting_SetHasInternetConnection(This,hic) \ - ( (This)->lpVtbl -> SetHasInternetConnection(This,hic) ) - -#endif /* COBJMACROS */ - - -#endif /* C style interface */ - - - - -#endif /* __IGaiaCredentialProviderForTesting_INTERFACE_DEFINED__ */ - - #ifndef __IGaiaCredential_INTERFACE_DEFINED__ #define __IGaiaCredential_INTERFACE_DEFINED__
diff --git a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x86/gaia_credential_provider_p.c b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x86/gaia_credential_provider_p.c index 0864b871..554701e 100644 --- a/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x86/gaia_credential_provider_p.c +++ b/third_party/win_build_output/midl/chrome/credential_provider/gaiacp/x86/gaia_credential_provider_p.c
@@ -50,7 +50,7 @@ #include "gaia_credential_provider_i.h" #define TYPE_FORMAT_STRING_SIZE 97 -#define PROC_FORMAT_STRING_SIZE 403 +#define PROC_FORMAT_STRING_SIZE 337 #define EXPR_FORMAT_STRING_SIZE 1 #define TRANSMIT_AS_TABLE_SIZE 0 #define WIRE_MARSHAL_TABLE_SIZE 1 @@ -93,13 +93,6 @@ extern const MIDL_STUB_DESC Object_StubDesc; -extern const MIDL_SERVER_INFO IGaiaCredentialProviderForTesting_ServerInfo; -extern const MIDL_STUBLESS_PROXY_INFO IGaiaCredentialProviderForTesting_ProxyInfo; - - -extern const MIDL_STUB_DESC Object_StubDesc; - - extern const MIDL_SERVER_INFO IGaiaCredential_ServerInfo; extern const MIDL_STUBLESS_PROXY_INFO IGaiaCredential_ProxyInfo; @@ -216,265 +209,210 @@ /* 94 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ - /* Procedure HasInternetConnection */ + /* Procedure Initialize */ /* 96 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ /* 98 */ NdrFcLong( 0x0 ), /* 0 */ -/* 102 */ NdrFcShort( 0x5 ), /* 5 */ -/* 104 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ +/* 102 */ NdrFcShort( 0x3 ), /* 3 */ +/* 104 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ /* 106 */ NdrFcShort( 0x0 ), /* 0 */ /* 108 */ NdrFcShort( 0x8 ), /* 8 */ -/* 110 */ 0x44, /* Oi2 Flags: has return, has ext, */ - 0x1, /* 1 */ +/* 110 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ + 0x2, /* 2 */ /* 112 */ 0x8, /* 8 */ 0x1, /* Ext Flags: new corr desc, */ /* 114 */ NdrFcShort( 0x0 ), /* 0 */ /* 116 */ NdrFcShort( 0x0 ), /* 0 */ /* 118 */ NdrFcShort( 0x0 ), /* 0 */ - /* Return value */ - -/* 120 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 122 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ -/* 124 */ 0x8, /* FC_LONG */ - 0x0, /* 0 */ - - /* Procedure SetHasInternetConnection */ - -/* 126 */ 0x33, /* FC_AUTO_HANDLE */ - 0x6c, /* Old Flags: object, Oi2 */ -/* 128 */ NdrFcLong( 0x0 ), /* 0 */ -/* 132 */ NdrFcShort( 0x3 ), /* 3 */ -/* 134 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ -/* 136 */ NdrFcShort( 0x6 ), /* 6 */ -/* 138 */ NdrFcShort( 0x8 ), /* 8 */ -/* 140 */ 0x44, /* Oi2 Flags: has return, has ext, */ - 0x2, /* 2 */ -/* 142 */ 0x8, /* 8 */ - 0x1, /* Ext Flags: new corr desc, */ -/* 144 */ NdrFcShort( 0x0 ), /* 0 */ -/* 146 */ NdrFcShort( 0x0 ), /* 0 */ -/* 148 */ NdrFcShort( 0x0 ), /* 0 */ - - /* Parameter hic */ - -/* 150 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ -/* 152 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ -/* 154 */ 0xd, /* FC_ENUM16 */ - 0x0, /* 0 */ - - /* Return value */ - -/* 156 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 158 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ -/* 160 */ 0x8, /* FC_LONG */ - 0x0, /* 0 */ - - /* Procedure Initialize */ - -/* 162 */ 0x33, /* FC_AUTO_HANDLE */ - 0x6c, /* Old Flags: object, Oi2 */ -/* 164 */ NdrFcLong( 0x0 ), /* 0 */ -/* 168 */ NdrFcShort( 0x3 ), /* 3 */ -/* 170 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ -/* 172 */ NdrFcShort( 0x0 ), /* 0 */ -/* 174 */ NdrFcShort( 0x8 ), /* 8 */ -/* 176 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ - 0x2, /* 2 */ -/* 178 */ 0x8, /* 8 */ - 0x1, /* Ext Flags: new corr desc, */ -/* 180 */ NdrFcShort( 0x0 ), /* 0 */ -/* 182 */ NdrFcShort( 0x0 ), /* 0 */ -/* 184 */ NdrFcShort( 0x0 ), /* 0 */ - /* Parameter provider */ -/* 186 */ NdrFcShort( 0xb ), /* Flags: must size, must free, in, */ -/* 188 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ -/* 190 */ NdrFcShort( 0x3c ), /* Type Offset=60 */ +/* 120 */ NdrFcShort( 0xb ), /* Flags: must size, must free, in, */ +/* 122 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ +/* 124 */ NdrFcShort( 0x3c ), /* Type Offset=60 */ /* Return value */ -/* 192 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 194 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ -/* 196 */ 0x8, /* FC_LONG */ +/* 126 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 128 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ +/* 130 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure Terminate */ -/* 198 */ 0x33, /* FC_AUTO_HANDLE */ +/* 132 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ -/* 200 */ NdrFcLong( 0x0 ), /* 0 */ -/* 204 */ NdrFcShort( 0x4 ), /* 4 */ -/* 206 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ -/* 208 */ NdrFcShort( 0x0 ), /* 0 */ -/* 210 */ NdrFcShort( 0x8 ), /* 8 */ -/* 212 */ 0x44, /* Oi2 Flags: has return, has ext, */ +/* 134 */ NdrFcLong( 0x0 ), /* 0 */ +/* 138 */ NdrFcShort( 0x4 ), /* 4 */ +/* 140 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ +/* 142 */ NdrFcShort( 0x0 ), /* 0 */ +/* 144 */ NdrFcShort( 0x8 ), /* 8 */ +/* 146 */ 0x44, /* Oi2 Flags: has return, has ext, */ 0x1, /* 1 */ -/* 214 */ 0x8, /* 8 */ +/* 148 */ 0x8, /* 8 */ 0x1, /* Ext Flags: new corr desc, */ -/* 216 */ NdrFcShort( 0x0 ), /* 0 */ -/* 218 */ NdrFcShort( 0x0 ), /* 0 */ -/* 220 */ NdrFcShort( 0x0 ), /* 0 */ +/* 150 */ NdrFcShort( 0x0 ), /* 0 */ +/* 152 */ NdrFcShort( 0x0 ), /* 0 */ +/* 154 */ NdrFcShort( 0x0 ), /* 0 */ /* Return value */ -/* 222 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 224 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ -/* 226 */ 0x8, /* FC_LONG */ +/* 156 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 158 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ +/* 160 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure OnUserAuthenticated */ -/* 228 */ 0x33, /* FC_AUTO_HANDLE */ +/* 162 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ -/* 230 */ NdrFcLong( 0x0 ), /* 0 */ -/* 234 */ NdrFcShort( 0x5 ), /* 5 */ -/* 236 */ NdrFcShort( 0x10 ), /* x86 Stack size/offset = 16 */ -/* 238 */ NdrFcShort( 0x0 ), /* 0 */ -/* 240 */ NdrFcShort( 0x8 ), /* 8 */ -/* 242 */ 0x47, /* Oi2 Flags: srv must size, clt must size, has return, has ext, */ +/* 164 */ NdrFcLong( 0x0 ), /* 0 */ +/* 168 */ NdrFcShort( 0x5 ), /* 5 */ +/* 170 */ NdrFcShort( 0x10 ), /* x86 Stack size/offset = 16 */ +/* 172 */ NdrFcShort( 0x0 ), /* 0 */ +/* 174 */ NdrFcShort( 0x8 ), /* 8 */ +/* 176 */ 0x47, /* Oi2 Flags: srv must size, clt must size, has return, has ext, */ 0x3, /* 3 */ -/* 244 */ 0x8, /* 8 */ +/* 178 */ 0x8, /* 8 */ 0x7, /* Ext Flags: new corr desc, clt corr check, srv corr check, */ -/* 246 */ NdrFcShort( 0x1 ), /* 1 */ -/* 248 */ NdrFcShort( 0x1 ), /* 1 */ -/* 250 */ NdrFcShort( 0x0 ), /* 0 */ +/* 180 */ NdrFcShort( 0x1 ), /* 1 */ +/* 182 */ NdrFcShort( 0x1 ), /* 1 */ +/* 184 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter authentication_info */ -/* 252 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 254 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ -/* 256 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 186 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 188 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ +/* 190 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Parameter status_text */ -/* 258 */ NdrFcShort( 0x2113 ), /* Flags: must size, must free, out, simple ref, srv alloc size=8 */ -/* 260 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ -/* 262 */ NdrFcShort( 0x56 ), /* Type Offset=86 */ +/* 192 */ NdrFcShort( 0x2113 ), /* Flags: must size, must free, out, simple ref, srv alloc size=8 */ +/* 194 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ +/* 196 */ NdrFcShort( 0x56 ), /* Type Offset=86 */ /* Return value */ -/* 264 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 266 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ -/* 268 */ 0x8, /* FC_LONG */ +/* 198 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 200 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ +/* 202 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure ReportError */ -/* 270 */ 0x33, /* FC_AUTO_HANDLE */ +/* 204 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ -/* 272 */ NdrFcLong( 0x0 ), /* 0 */ -/* 276 */ NdrFcShort( 0x6 ), /* 6 */ -/* 278 */ NdrFcShort( 0x14 ), /* x86 Stack size/offset = 20 */ -/* 280 */ NdrFcShort( 0x10 ), /* 16 */ -/* 282 */ NdrFcShort( 0x8 ), /* 8 */ -/* 284 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ +/* 206 */ NdrFcLong( 0x0 ), /* 0 */ +/* 210 */ NdrFcShort( 0x6 ), /* 6 */ +/* 212 */ NdrFcShort( 0x14 ), /* x86 Stack size/offset = 20 */ +/* 214 */ NdrFcShort( 0x10 ), /* 16 */ +/* 216 */ NdrFcShort( 0x8 ), /* 8 */ +/* 218 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ 0x4, /* 4 */ -/* 286 */ 0x8, /* 8 */ +/* 220 */ 0x8, /* 8 */ 0x5, /* Ext Flags: new corr desc, srv corr check, */ -/* 288 */ NdrFcShort( 0x0 ), /* 0 */ -/* 290 */ NdrFcShort( 0x1 ), /* 1 */ -/* 292 */ NdrFcShort( 0x0 ), /* 0 */ +/* 222 */ NdrFcShort( 0x0 ), /* 0 */ +/* 224 */ NdrFcShort( 0x1 ), /* 1 */ +/* 226 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter status */ -/* 294 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ -/* 296 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ -/* 298 */ 0x8, /* FC_LONG */ +/* 228 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 230 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ +/* 232 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Parameter substatus */ -/* 300 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ -/* 302 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ -/* 304 */ 0x8, /* FC_LONG */ +/* 234 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ +/* 236 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ +/* 238 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Parameter status_text */ -/* 306 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 308 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ -/* 310 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 240 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 242 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ +/* 244 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Return value */ -/* 312 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 314 */ NdrFcShort( 0x10 ), /* x86 Stack size/offset = 16 */ -/* 316 */ 0x8, /* FC_LONG */ +/* 246 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 248 */ NdrFcShort( 0x10 ), /* x86 Stack size/offset = 16 */ +/* 250 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure SetEmailForReauth */ -/* 318 */ 0x33, /* FC_AUTO_HANDLE */ +/* 252 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ -/* 320 */ NdrFcLong( 0x0 ), /* 0 */ -/* 324 */ NdrFcShort( 0x3 ), /* 3 */ -/* 326 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ -/* 328 */ NdrFcShort( 0x0 ), /* 0 */ -/* 330 */ NdrFcShort( 0x8 ), /* 8 */ -/* 332 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ +/* 254 */ NdrFcLong( 0x0 ), /* 0 */ +/* 258 */ NdrFcShort( 0x3 ), /* 3 */ +/* 260 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ +/* 262 */ NdrFcShort( 0x0 ), /* 0 */ +/* 264 */ NdrFcShort( 0x8 ), /* 8 */ +/* 266 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ 0x2, /* 2 */ -/* 334 */ 0x8, /* 8 */ +/* 268 */ 0x8, /* 8 */ 0x5, /* Ext Flags: new corr desc, srv corr check, */ -/* 336 */ NdrFcShort( 0x0 ), /* 0 */ -/* 338 */ NdrFcShort( 0x1 ), /* 1 */ -/* 340 */ NdrFcShort( 0x0 ), /* 0 */ +/* 270 */ NdrFcShort( 0x0 ), /* 0 */ +/* 272 */ NdrFcShort( 0x1 ), /* 1 */ +/* 274 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter email */ -/* 342 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 344 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ -/* 346 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 276 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 278 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ +/* 280 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Return value */ -/* 348 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 350 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ -/* 352 */ 0x8, /* FC_LONG */ +/* 282 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 284 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ +/* 286 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure SetOSUserInfo */ -/* 354 */ 0x33, /* FC_AUTO_HANDLE */ +/* 288 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ -/* 356 */ NdrFcLong( 0x0 ), /* 0 */ -/* 360 */ NdrFcShort( 0x4 ), /* 4 */ -/* 362 */ NdrFcShort( 0x14 ), /* x86 Stack size/offset = 20 */ -/* 364 */ NdrFcShort( 0x0 ), /* 0 */ -/* 366 */ NdrFcShort( 0x8 ), /* 8 */ -/* 368 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ +/* 290 */ NdrFcLong( 0x0 ), /* 0 */ +/* 294 */ NdrFcShort( 0x4 ), /* 4 */ +/* 296 */ NdrFcShort( 0x14 ), /* x86 Stack size/offset = 20 */ +/* 298 */ NdrFcShort( 0x0 ), /* 0 */ +/* 300 */ NdrFcShort( 0x8 ), /* 8 */ +/* 302 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ 0x4, /* 4 */ -/* 370 */ 0x8, /* 8 */ +/* 304 */ 0x8, /* 8 */ 0x5, /* Ext Flags: new corr desc, srv corr check, */ -/* 372 */ NdrFcShort( 0x0 ), /* 0 */ -/* 374 */ NdrFcShort( 0x1 ), /* 1 */ -/* 376 */ NdrFcShort( 0x0 ), /* 0 */ +/* 306 */ NdrFcShort( 0x0 ), /* 0 */ +/* 308 */ NdrFcShort( 0x1 ), /* 1 */ +/* 310 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter sid */ -/* 378 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 380 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ -/* 382 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 312 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 314 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ +/* 316 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Parameter domain */ -/* 384 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 386 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ -/* 388 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 318 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 320 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ +/* 322 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Parameter username */ -/* 390 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ -/* 392 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ -/* 394 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ +/* 324 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ +/* 326 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ +/* 328 */ NdrFcShort( 0x32 ), /* Type Offset=50 */ /* Return value */ -/* 396 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ -/* 398 */ NdrFcShort( 0x10 ), /* x86 Stack size/offset = 16 */ -/* 400 */ 0x8, /* FC_LONG */ +/* 330 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ +/* 332 */ NdrFcShort( 0x10 ), /* x86 Stack size/offset = 16 */ +/* 334 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ 0x0 @@ -588,8 +526,7 @@ static const unsigned short IGaiaCredentialProvider_FormatStringOffsetTable[] = { 0, - 36, - 96 + 36 }; static const MIDL_STUBLESS_PROXY_INFO IGaiaCredentialProvider_ProxyInfo = @@ -613,7 +550,7 @@ 0, 0, 0}; -CINTERFACE_PROXY_VTABLE(6) _IGaiaCredentialProviderProxyVtbl = +CINTERFACE_PROXY_VTABLE(5) _IGaiaCredentialProviderProxyVtbl = { &IGaiaCredentialProvider_ProxyInfo, &IID_IGaiaCredentialProvider, @@ -621,69 +558,14 @@ IUnknown_AddRef_Proxy, IUnknown_Release_Proxy , (void *) (INT_PTR) -1 /* IGaiaCredentialProvider::GetUsageScenario */ , - (void *) (INT_PTR) -1 /* IGaiaCredentialProvider::OnUserAuthenticated */ , - (void *) (INT_PTR) -1 /* IGaiaCredentialProvider::HasInternetConnection */ + (void *) (INT_PTR) -1 /* IGaiaCredentialProvider::OnUserAuthenticated */ }; const CInterfaceStubVtbl _IGaiaCredentialProviderStubVtbl = { &IID_IGaiaCredentialProvider, &IGaiaCredentialProvider_ServerInfo, - 6, - 0, /* pure interpreted */ - CStdStubBuffer_METHODS -}; - - -/* Standard interface: __MIDL_itf_gaia_credential_provider_0000_0001, ver. 0.0, - GUID={0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}} */ - - -/* Object interface: IGaiaCredentialProviderForTesting, ver. 0.0, - GUID={0x224CE2FB,0x2977,0x4585,{0xBD,0x46,0x1B,0xAE,0x8D,0x79,0x64,0xDE}} */ - -#pragma code_seg(".orpc") -static const unsigned short IGaiaCredentialProviderForTesting_FormatStringOffsetTable[] = - { - 126 - }; - -static const MIDL_STUBLESS_PROXY_INFO IGaiaCredentialProviderForTesting_ProxyInfo = - { - &Object_StubDesc, - gaia_credential_provider__MIDL_ProcFormatString.Format, - &IGaiaCredentialProviderForTesting_FormatStringOffsetTable[-3], - 0, - 0, - 0 - }; - - -static const MIDL_SERVER_INFO IGaiaCredentialProviderForTesting_ServerInfo = - { - &Object_StubDesc, - 0, - gaia_credential_provider__MIDL_ProcFormatString.Format, - &IGaiaCredentialProviderForTesting_FormatStringOffsetTable[-3], - 0, - 0, - 0, - 0}; -CINTERFACE_PROXY_VTABLE(4) _IGaiaCredentialProviderForTestingProxyVtbl = -{ - &IGaiaCredentialProviderForTesting_ProxyInfo, - &IID_IGaiaCredentialProviderForTesting, - IUnknown_QueryInterface_Proxy, - IUnknown_AddRef_Proxy, - IUnknown_Release_Proxy , - (void *) (INT_PTR) -1 /* IGaiaCredentialProviderForTesting::SetHasInternetConnection */ -}; - -const CInterfaceStubVtbl _IGaiaCredentialProviderForTestingStubVtbl = -{ - &IID_IGaiaCredentialProviderForTesting, - &IGaiaCredentialProviderForTesting_ServerInfo, - 4, + 5, 0, /* pure interpreted */ CStdStubBuffer_METHODS }; @@ -695,10 +577,10 @@ #pragma code_seg(".orpc") static const unsigned short IGaiaCredential_FormatStringOffsetTable[] = { + 96, + 132, 162, - 198, - 228, - 270 + 204 }; static const MIDL_STUBLESS_PROXY_INFO IGaiaCredential_ProxyInfo = @@ -751,8 +633,8 @@ #pragma code_seg(".orpc") static const unsigned short IReauthCredential_FormatStringOffsetTable[] = { - 318, - 354 + 252, + 288 }; static const MIDL_STUBLESS_PROXY_INFO IReauthCredential_ProxyInfo = @@ -825,7 +707,6 @@ ( CInterfaceProxyVtbl *) &_IGaiaCredentialProviderProxyVtbl, ( CInterfaceProxyVtbl *) &_IGaiaCredentialProxyVtbl, ( CInterfaceProxyVtbl *) &_IReauthCredentialProxyVtbl, - ( CInterfaceProxyVtbl *) &_IGaiaCredentialProviderForTestingProxyVtbl, 0 }; @@ -834,7 +715,6 @@ ( CInterfaceStubVtbl *) &_IGaiaCredentialProviderStubVtbl, ( CInterfaceStubVtbl *) &_IGaiaCredentialStubVtbl, ( CInterfaceStubVtbl *) &_IReauthCredentialStubVtbl, - ( CInterfaceStubVtbl *) &_IGaiaCredentialProviderForTestingStubVtbl, 0 }; @@ -843,7 +723,6 @@ "IGaiaCredentialProvider", "IGaiaCredential", "IReauthCredential", - "IGaiaCredentialProviderForTesting", 0 }; @@ -854,9 +733,9 @@ { IID_BS_LOOKUP_SETUP - IID_BS_LOOKUP_INITIAL_TEST( _gaia_credential_provider, 4, 2 ) + IID_BS_LOOKUP_INITIAL_TEST( _gaia_credential_provider, 3, 2 ) IID_BS_LOOKUP_NEXT_TEST( _gaia_credential_provider, 1 ) - IID_BS_LOOKUP_RETURN_RESULT( _gaia_credential_provider, 4, *pIndex ) + IID_BS_LOOKUP_RETURN_RESULT( _gaia_credential_provider, 3, *pIndex ) } @@ -867,7 +746,7 @@ (const PCInterfaceName * ) & _gaia_credential_provider_InterfaceNamesList, 0, /* no delegation */ & _gaia_credential_provider_IID_Lookup, - 4, + 3, 2, 0, /* table of [async_uuid] interfaces */ 0, /* Filler1 */
diff --git a/tools/grit/grit/grd_reader.py b/tools/grit/grit/grd_reader.py index 733dc23..e0ccdac 100755 --- a/tools/grit/grit/grd_reader.py +++ b/tools/grit/grit/grd_reader.py
@@ -88,7 +88,7 @@ partname = os.path.join(self.dir, partnode.GetInputPath()) # Check the GRDP file exists. if not os.path.exists(partname): - raise exception.FileNotFound() + raise exception.FileNotFound(partname) # Exceptions propagate to the handler in grd_reader.Parse(). oldsource = self.source try: @@ -110,7 +110,8 @@ self.stack[-1].AppendContent(content) def ignorableWhitespace(self, whitespace): - # TODO(joi) This is not supported by expat. Should use a different XML parser? + # TODO(joi): This is not supported by expat. Should use a different XML + # parser? pass
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 1eda44b..c91352c4 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -2674,6 +2674,19 @@ <int value="4" label="Pause"/> </enum> +<enum name="AutocompleteActionPredictorAction"> + <int value="0" label="PRERENDER"/> + <int value="1" label="PRECONNECT"/> + <int value="2" label="NONE"/> +</enum> + +<enum name="AutocompleteActionPredictorDatabaseAction"> + <int value="0" label="ADD"/> + <int value="1" label="UPDATE"/> + <int value="2" label="DELETE SOME"/> + <int value="3" label="DELETE ALL"/> +</enum> + <enum name="AutocompleteEvents"> <int value="0" label="Suggestions Shown"/> <int value="1" label="Suggestion Selected"/> @@ -15495,6 +15508,7 @@ <int value="524" label="BrowserSwitcherDelay"/> <int value="525" label="PrintingAllowedPinModes"/> <int value="526" label="PrintingPinDefault"/> + <int value="527" label="VoiceInteractionContextEnabled"/> </enum> <enum name="EnterprisePolicyInvalidations"> @@ -21648,6 +21662,7 @@ <int value="2791" label="ClientHintsUAPlatform"/> <int value="2792" label="ClientHintsUAModel"/> <int value="2793" label="AnimationFrameCancelledWithinFrame"/> + <int value="2794" label="SchedulingIsInputPending"/> </enum> <enum name="FeaturePolicyFeature"> @@ -28708,6 +28723,8 @@ <int value="3" label="New Voice Search"/> <int value="4" label="New QR Code Search"/> <int value="5" label="Open URL"/> + <int value="6" label="Search Text"/> + <int value="7" label="Search Image"/> </enum> <enum name="IOSShareExtensionReceivedEntrySource"> @@ -32124,6 +32141,8 @@ <int value="201343576" label="enable-password-change-support:enabled"/> <int value="203239167" label="ImprovedGeoLanguageData:enabled"/> <int value="203776499" label="enable-virtual-keyboard-overscroll"/> + <int value="207907053" + label="OmniboxUIExperimentBlueSearchLoopAndSearchQuery:enabled"/> <int value="212489101" label="AutofillAssistantChromeEntry:enabled"/> <int value="215328738" label="ImprovedGeoLanguageData:disabled"/> <int value="217455219" label="SyncStandaloneTransport:enabled"/> @@ -33139,6 +33158,8 @@ <int value="1913298816" label="OverlayScrollbar:enabled"/> <int value="1913926782" label="ChromeModernAlternateCardLayout:disabled"/> <int value="1915178511" label="disable-blink-features"/> + <int value="1918984253" + label="OmniboxUIExperimentBlueSearchLoopAndSearchQuery:disabled"/> <int value="1919917329" label="ImplicitRootScroller:disabled"/> <int value="1924192543" label="ProactiveTabFreezeAndDiscard:enabled"/> <int value="1925627218" label="FullscreenToolbarReveal:disabled"/> @@ -35909,6 +35930,11 @@ </int> </enum> +<enum name="MountEncryptedEncryptedFsType"> + <int value="0" label="Dm-crypt">Dm-crypt over a sparse backing file.</int> + <int value="1" label="Ext4 Dircrypto">Encrypted ext4 directory.</int> +</enum> + <enum name="MountEncryptedEncryptionKeyStatus"> <int value="0" label="unknown">Key not loaded yet.</int> <int value="1" label="keyfile">Key loaded from encrypted.key file.</int> @@ -43815,7 +43841,9 @@ <int value="0" label="Preview Allowed."/> <int value="1" label="Blacklist not created."/> <int value="2" label="Blacklist data not loaded yet from disk."/> - <int value="3" label="User opted out of a preview recently."/> + <int value="3" + label="User opted out of a preview recently or reloaded on a preview + page recently."/> <int value="4" label="User is blacklisted for all hosts."/> <int value="5" label="User is blacklisted for the specific host."/> <int value="6" label="The network quality estimate is not available."/> @@ -43935,14 +43963,14 @@ <int value="2" label="Subframe navigation"/> <int value="3" label="Server Unavailable"/> <int value="4" label="Infobar hasn't been seen by the user and needs to be"/> - <int value="5" label="Network was not slow"/> + <int value="5" label="(DEPRECATED IN M74) Network was not slow"/> <int value="6" label="User opted out of this preview (pre-s13n only)"/> <int value="7" label="The user has blocked cookies for the original page"/> - <int value="8" label="ECT Unknown"/> + <int value="8" label="(DEPRECATED IN M74) ECT Unknown"/> <int value="9" label="Exceeded maximum number of navigation restarts or a redirect loop was detected"/> - <int value="10" label="Disallowed by PreviewsState"/> + <int value="10" label="(DEPRECATED IN M74) Disallowed by PreviewsState"/> </enum> <enum name="PreviewsServerLitePageServerResponse"> @@ -49207,6 +49235,9 @@ Entries that are read before a write to that entry has finished when read and write request interleave. </int> + <int value="7" label="WriteFailure"> + Entries that could not be written, usually because they're too big. + </int> </enum> <enum name="SiteIsolatedCodeCacheWASMBehaviour"> @@ -49225,6 +49256,9 @@ Entries that are read before a write to that entry has finished when read and write request interleave. </int> + <int value="7" label="WriteFailure"> + Entries that could not be written, usually because they're too big. + </int> </enum> <enum name="SiteIsolationMimeType">
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index db197b3..fa393d5 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -7510,6 +7510,84 @@ </summary> </histogram> +<histogram name="AutocompleteActionPredictor.AccurateCount"> + <owner>tbansal@chromium.org</owner> + <summary> + Every time we calculate the confidence for a URL to determine if it should + be prerendered, we track the URL and confidence calculated. When an Omnibox + navigation happens, if we calculated a confidence for that URL, a count is + incremented for the confidence that was calculated. This histogram is then a + histogram of counts that relates the number of correctly predicted URLs to a + confidence value. By comparing that number to the + AutocompleteActionPredictor.NavigationCount and + Prerender.OmniboxNavigationsUsedPrerenderCount histograms, it's possible to + determine the effect of changing the confidence threshold on the accuracy of + prerendering prediction. + </summary> +</histogram> + +<histogram name="AutocompleteActionPredictor.Action" + enum="AutocompleteActionPredictorAction"> + <owner>tbansal@chromium.org</owner> + <summary> + The distribution of network actions recommended by the + AutocompleteActionPredictor. A network action can be one of the enumerated + AutocompleteActionPredictor::Action values: PRERENDER, PRECONNECT, or NONE. + The AutocompleteActionPredictor recommends one of these based on a + confidence score for a given URL and user-entered text pair. + </summary> +</histogram> + +<histogram name="AutocompleteActionPredictor.Confidence"> + <owner>tbansal@chromium.org</owner> + <summary> + The distribution of confidence ratings. The AutocompleteActionPredictor uses + a heuristic to calculate a confidence score given a URL and user-entered + text pair. It is in the range [0,1] and is mapped on to a recommended + action, one of the enumerated AutocompleteActionPredictor::Action values: + PRERENDER, PRECONNECT or NONE. This is the distribution of those scores + multiplied by 100. + </summary> +</histogram> + +<histogram name="AutocompleteActionPredictor.DatabaseAction" + enum="AutocompleteActionPredictorDatabaseAction"> + <owner>tbansal@chromium.org</owner> + <summary> + Trackes the number of times something is added, removed, or deleted from the + AutocompleteActionPredictor backing database. + </summary> +</histogram> + +<histogram name="AutocompleteActionPredictor.DatabaseRowCount"> + <owner>tbansal@chromium.org</owner> + <summary> + The distribution of row counts for the AutocompleteActionPredictorDatabase. + Each row contains information regarding the user's Omnibox use history. + </summary> +</histogram> + +<histogram name="AutocompleteActionPredictor.MatchIsInDb"> + <owner>tbansal@chromium.org</owner> + <summary> + A boolean that indicates if the autocomplete suggestion under consideration + by the AutocompleteActionPredictor was found in the database. This gives an + upper bound on the fraction of suggestions it is possible to calculate a + confidence for, and thus an upper bound on the fraction of suggestions that + can be prerendered. + </summary> +</histogram> + +<histogram name="AutocompleteActionPredictor.NavigationCount"> + <owner>tbansal@chromium.org</owner> + <summary> + The number of navigations triggered by the Omnibox and seen by the + AutocompleteActionPredictor. This triggers when the Omnibox is showing + Autocomplete results to the user and they select one with the mouse or by + pressing enter. + </summary> +</histogram> + <histogram name="AutodetectEncoding.Attempted" enum="BooleanAttempted"> <obsolete> Deprecated as of 2/2016. @@ -84380,6 +84458,16 @@ </summary> </histogram> +<histogram name="Platform.MountEncrypted.EncryptedFsType" + enum="MountEncryptedEncryptedFsType"> + <owner>gwendal@chromium.org</owner> + <owner>sarthakkukreti@chromium.org</owner> + <summary> + Type of encrypted mount used for the encrypted stateful file system on + Chrome OS. + </summary> +</histogram> + <histogram name="Platform.MountEncrypted.EncryptionKeyStatus" enum="MountEncryptedEncryptionKeyStatus"> <owner>apronin@chromium.org</owner> @@ -134128,7 +134216,7 @@ <suffix name="toBlobCallback" label="Image formats passed to canvas.toBlob (callback)"/> <suffix name="toDataURL" label="Image formats passed to canvas.toDataURL"/> - <affected-histogram name="Canvas.RequestedImageMimeTypes"/> + <affected-histogram name="Blink.Canvas.RequestedImageMimeTypes"/> </histogram_suffixes> <histogram_suffixes name="CertificateTransparencyProtocol" separator=".">
diff --git a/tools/metrics/ukm/ukm.xml b/tools/metrics/ukm/ukm.xml index 8c02128..4b79ffe 100644 --- a/tools/metrics/ukm/ukm.xml +++ b/tools/metrics/ukm/ukm.xml
@@ -3643,6 +3643,11 @@ meaningful input with longest queuing delay per navigation. In ms. </summary> </metric> + <metric name="IsSignedExchangeInnerResponse"> + <summary> + Set to 1 if the main resource is an inner response of a signed exchange. + </summary> + </metric> <metric name="LayoutStability.JankScore"> <summary> Measures the amount of layout jank (bit.ly/lsm-explainer) that has @@ -3827,6 +3832,14 @@ start to the time the parser started, for main frame documents. </summary> </metric> + <metric name="SiteEngagementScore"> + <owner>mcrouse@chromium.org</owner> + <owner>tbansal@chromium.org</owner> + <summary> + Measures the Site Engagement Score for the commited URL rounded to the + nearest 10. + </summary> + </metric> <metric name="WasCached"> <summary> Set to 1 if the main resource was served from cache.
diff --git a/tools/perf/benchmarks/system_health_smoke_test.py b/tools/perf/benchmarks/system_health_smoke_test.py index 4a80b3f..4d2b82c 100644 --- a/tools/perf/benchmarks/system_health_smoke_test.py +++ b/tools/perf/benchmarks/system_health_smoke_test.py
@@ -235,6 +235,11 @@ # all crashes and hence remove the need to enable logging in actual perf # benchmarks. options.browser_options.logging_verbosity = 'non-verbose' + # TODO(sadrul): Remove the check once catapult roll happens. + # https://crbug.com/932409 + if "GetSupportedPlatforms" in dir(benchmark_class): + options.target_platforms = benchmark_class.GetSupportedPlatforms( + benchmark_class.SUPPORTED_PLATFORMS) return options
diff --git a/tools/perf/core/bot_platforms.py b/tools/perf/core/bot_platforms.py index 2d06d36..218a2ce 100644 --- a/tools/perf/core/bot_platforms.py +++ b/tools/perf/core/bot_platforms.py
@@ -138,6 +138,10 @@ num_shards=19, benchmarks_names_to_run=_ANDROID_GO_BENCHMARK_NAMES) +ANDROID_GO_WEBVIEW = PerfPlatform( + 'android-go_webview-perf', 'Android OPM1.171019.021', + num_shards=25, benchmarks_names_to_run=_ANDROID_GO_BENCHMARK_NAMES) + ANDROID_NEXUS_5 = PerfPlatform( 'Android Nexus5 Perf', 'Android KOT49H', num_shards=16) @@ -165,10 +169,6 @@ 'android-pixel2_webview-perf', 'Android OPM1.171019.021', is_fyi=True, num_shards=7) -ANDROID_GO_WEBVIEW = PerfPlatform( - 'android-go_webview-perf', 'Android OPM1.171019.021', is_fyi=True, - num_shards=25, benchmarks_names_to_run=_ANDROID_GO_BENCHMARK_NAMES) - ANDROID_NEXUS5X_PERF_FYI = PerfPlatform( 'android-nexus5x-perf-fyi', 'Android MMB29Q', is_fyi=True, num_shards=4, benchmarks_names_to_run={
diff --git a/tools/perf/core/perf_data_generator.py b/tools/perf/core/perf_data_generator.py index 8e32c97f..ea6f73e5 100755 --- a/tools/perf/core/perf_data_generator.py +++ b/tools/perf/core/perf_data_generator.py
@@ -108,25 +108,6 @@ 'device_os_flavor': 'google', }, }, - 'android-go_webview-perf': { - 'tests': [ - { - 'isolate': 'performance_webview_test_suite', - 'extra_args': [ - '--test-shard-map-filename=android-go_webview-perf_map.json', - ], - 'num_shards': 25 - } - ], - 'platform': 'android-webview-google', - 'dimension': { - 'pool': 'chrome.tests.perf-webview', - 'os': 'Android', - 'device_type': 'gobo', - 'device_os': 'O', - 'device_os_flavor': 'google', - }, - } } } @@ -156,6 +137,25 @@ 'os': 'Android', }, }, + 'android-go_webview-perf': { + 'tests': [ + { + 'isolate': 'performance_webview_test_suite', + 'extra_args': [ + '--test-shard-map-filename=android-go_webview-perf_map.json', + ], + 'num_shards': 25 + } + ], + 'platform': 'android-webview-google', + 'dimension': { + 'pool': 'chrome.tests.perf-webview', + 'os': 'Android', + 'device_type': 'gobo', + 'device_os': 'O', + 'device_os_flavor': 'google', + }, + }, 'android-nexus5x-perf': { 'tests': [ {
diff --git a/tools/perf/core/results_dashboard.py b/tools/perf/core/results_dashboard.py index cb257400..f765c567 100755 --- a/tools/perf/core/results_dashboard.py +++ b/tools/perf/core/results_dashboard.py
@@ -11,8 +11,8 @@ import calendar import datetime import httplib -import json import os +import shutil import subprocess import sys import traceback @@ -69,7 +69,7 @@ This function tries to send the given data to the dashboard. Args: - data: The data to try to send. Must be JSON-serializable. + data: The JSON string to try to send. data_label: string name of the data to be uploaded. This is only used for logging purpose. url: Performance Dashboard URL (including schema). @@ -93,8 +93,6 @@ data_type = ('histogram' if send_as_histograms else 'chartjson') - dashboard_data_str = json.dumps(data) - # When perf dashboard is overloaded, it takes sometimes to spin up new # instance. So sleep before retrying again. ( # For more details, see crbug.com/867379. @@ -105,11 +103,11 @@ print 'Sending %s result of %s to dashboard (attempt %i out of %i).' % ( data_type, data_label, i, num_retries) if send_as_histograms: - _SendHistogramJson(url, dashboard_data_str, + _SendHistogramJson(url, data, service_account_file, token_generator_callback) else: # TODO(eakuefner): Remove this logic once all bots use histograms. - _SendResultsJson(url, dashboard_data_str) + _SendResultsJson(url, data) all_data_uploaded = True break except SendResultsRetryException as e: @@ -139,7 +137,18 @@ test_name, bot, buildername, buildnumber, project, buildbucket, revisions_dict, is_reference_build, - perf_dashboard_machine_group): + perf_dashboard_machine_group, max_bytes=0, + output_path=''): + """Generates strings containing HistogramSet JSON. + + Args: + histograms_file: input filename + output_path: output filename. If empty, a temporary directory will be + created. + max_bytes: If non-zero, tries to produce files no larger than max_bytes. + (May generate a file that is larger than max_bytes if max_bytes is smaller + than a single Histogram.) + """ add_diagnostics_args = [] add_diagnostics_args.extend([ '--benchmarks', test_name, @@ -149,6 +158,9 @@ '--is_reference_build', 'true' if is_reference_build else '', ]) + if max_bytes: + add_diagnostics_args.extend(['--max_bytes', max_bytes]) + stdio_url = _MakeStdioUrl(test_name, buildername, buildnumber) if stdio_url: add_diagnostics_args.extend(['--log_urls_k', 'Buildbot stdio']) @@ -172,21 +184,31 @@ path_util.GetChromiumSrcDir(), 'third_party', 'catapult', 'tracing', 'bin', 'add_reserved_diagnostics') - tf = tempfile.NamedTemporaryFile(delete=False) - tf.close() - temp_histogram_output_file = tf.name + output_dir = None + if not output_path: + output_dir = tempfile.mkdtemp() + output_path = os.path.join(output_dir, 'histograms.json') cmd = ([sys.executable, add_reserved_diagnostics_path] + - add_diagnostics_args + ['--output_path', temp_histogram_output_file]) + add_diagnostics_args + ['--output_path', output_path]) try: + begin_time = time.time() subprocess.check_call(cmd) + end_time = time.time() + print 'Duration of adding diagnostics for %s: %d seconds' % ( + test_name, end_time - begin_time) + # TODO: Handle reference builds - with open(temp_histogram_output_file) as f: - hs = json.load(f) - return hs + + if output_dir: + for basename in os.listdir(output_dir): + yield file(os.path.join(output_dir, basename)).read() + else: + yield file(output_path).read() finally: - os.remove(temp_histogram_output_file) + if output_dir: + shutil.rmtree(output_dir) def MakeListOfPoints(charts, bot, test_name, buildername,
diff --git a/tools/perf/core/upload_results_to_perf_dashboard.py b/tools/perf/core/upload_results_to_perf_dashboard.py index 3afb2b3a..69b6d46 100755 --- a/tools/perf/core/upload_results_to_perf_dashboard.py +++ b/tools/perf/core/upload_results_to_perf_dashboard.py
@@ -12,7 +12,6 @@ import optparse import re import sys -import time import urllib from core import results_dashboard @@ -30,7 +29,7 @@ return int(re.search(r'{#(\d+)}', commit_pos).group(1)) -def _GetDashboardJson(options): +def _GenerateDashboardJSONs(options): main_revision = _GetMainRevision(options.got_revision_cp) revisions = _GetPerfDashboardRevisionsWithProperties( options.got_webrtc_revision, options.got_v8_revision, @@ -57,9 +56,13 @@ options.buildername, options.buildnumber, {}, reference_build, perf_dashboard_machine_group=options.perf_dashboard_machine_group) - return dashboard_json + dashboard_json = json.dumps(dashboard_json, indent=2, separators=(',', ': ')) + if options.output_json_file: + with open(options.output_json_file, 'w') as f: + f.write(dashboard_json) + yield dashboard_json -def _GetDashboardHistogramData(options): +def _GenerateDashboardHistogramJSONs(options, max_bytes=0): revisions = { '--chromium_commit_positions': _GetMainRevision(options.got_revision_cp), '--chromium_revisions': options.git_revision @@ -73,18 +76,14 @@ is_reference_build = 'reference' in options.name stripped_test_name = options.name.replace('.reference', '') - begin_time = time.time() - hs = results_dashboard.MakeHistogramSetWithDiagnostics( + return results_dashboard.MakeHistogramSetWithDiagnostics( histograms_file=options.results_file, test_name=stripped_test_name, bot=options.configuration_name, buildername=options.buildername, - buildnumber=options.buildnumber, + buildnumber=options.buildnumber, max_bytes=max_bytes, + output_path=options.output_json_file, project=options.project, buildbucket=options.buildbucket, revisions_dict=revisions, is_reference_build=is_reference_build, perf_dashboard_machine_group=options.perf_dashboard_machine_group) - end_time = time.time() - print 'Duration of adding diagnostics for %s: %d seconds' % ( - stripped_test_name, end_time - begin_time) - return hs def _CreateParser(): # Parse options @@ -125,16 +124,22 @@ print 'Error: Invalid perf dashboard machine group' return 1 - if not options.send_as_histograms: - dashboard_json = _GetDashboardJson(options) + if options.send_as_histograms: + if options.output_json_file: + _GenerateDashboardHistogramJSONs(options) + # Clear output_json_file so that the next call will use mkdtemp. + options.output_json_file = '' + dashboard_jsons = _GenerateDashboardHistogramJSONs( + options, max_bytes=1<<20) else: - dashboard_json = _GetDashboardHistogramData(options) + dashboard_jsons = _GenerateDashboardJSONs(options) - if options.output_json_file: - json.dump(dashboard_json, options.output_json_file, - indent=4, separators=(',', ': ')) + any_results = False + for dashboard_json in dashboard_jsons: + if not dashboard_json: + continue - if dashboard_json: + any_results = True if options.output_json_dashboard_url: # Dump dashboard url to file. dashboard_url = GetDashboardUrl(options.name, @@ -151,9 +156,11 @@ send_as_histograms=options.send_as_histograms, service_account_file=service_account_file): return 1 - else: + + if not any_results: # The upload didn't fail since there was no data to upload. print 'Warning: No perf dashboard JSON was produced.' + return 0 if __name__ == '__main__':
diff --git a/tools/perf/expectations.config b/tools/perf/expectations.config index 458b1a3..845deaf 100644 --- a/tools/perf/expectations.config +++ b/tools/perf/expectations.config
@@ -15,7 +15,8 @@ crbug.com/910207 [ Nexus_5X ] blink_perf.bindings/structured-clone-json-serialize.html [ Skip ] crbug.com/882881 [ Nexus_5 ] blink_perf.bindings/structured-clone-long-string-deserialize.html [ Skip ] crbug.com/910207 [ Nexus_5X ] blink_perf.bindings/structured-clone-long-string-deserialize.html [ Skip ] -crbug.com/893209 [ Nexus5X_Webview ] blink_perf.bindings/structured-clone-long-string-deserialize.html [ Skip ] +crbug.com/931780 [ Android_Webview ] blink_perf.bindings/structured-clone-long-string-serialize.html [ Skip ] +crbug.com/893209 [ Android_Webview ] blink_perf.bindings/structured-clone-long-string-deserialize.html [ Skip ] crbug.com/882881 [ Nexus_5 ] blink_perf.bindings/structured-clone-long-string-serialize.html [ Skip ] crbug.com/910207 [ Nexus_5X ] blink_perf.bindings/structured-clone-long-string-serialize.html [ Skip ] crbug.com/882881 [ Nexus_5 ] blink_perf.bindings/worker-structured-clone-json-roundtrip.html [ Skip ] @@ -256,7 +257,8 @@ crbug.com/846022 [ Linux ] system_health.common_desktop/browse:social:twitter_infinite_scroll [ Skip ] crbug.com/903417 [ Mac ] system_health.common_desktop/long_running:tools:gmail-foreground [ Skip ] crbug.com/903417 [ Win ] system_health.common_desktop/long_running:tools:gmail-foreground [ Skip ] -crbug.com/911214 [ Win_10 ] system_health.common_desktop/multitab:misc:typical24 [ Skip ] +crbug.com/911214 [ Win ] system_health.common_desktop/multitab:misc:typical24 [ Skip ] +crbug.com/934270 [ Win ] system_health.common_desktop/multitab:misc:typical24:2018 [ Skip ] crbug.com/923106 [ Linux ] system_health.common_desktop/browse:media:tumblr [ Skip ] crbug.com/923106 [ Win ] system_health.common_desktop/browse:media:tumblr [ Skip ] crbug.com/927758 [ Desktop ] system_health.common_desktop/load:games:alphabetty [ Skip ] @@ -392,8 +394,9 @@ crbug.com/910207 [ Nexus_5X ] v8.browsing_mobile/browse:chrome:newtab [ Skip ] crbug.com/853212 [ Android_Webview ] v8.browsing_mobile/browse:media:youtube [ Skip ] crbug.com/853212 [ Android_Webview ] v8.browsing_mobile/browse:news:cnn [ Skip ] -crbug.com/877648 [ Android_Go ] v8.browsing_mobile/browse:news:toi [ Skip ] +crbug.com/877648 [ Android ] v8.browsing_mobile/browse:news:toi [ Skip ] crbug.com/877648 [ Android_Go ] v8.browsing_mobile/browse:news:cnn [ Skip ] +crbug.com/931866 [ Android_Go ] v8.browsing_mobile/browse:news:cnn:2018 [ Skip ] crbug.com/901967 [ Nexus6_Webview ] v8.browsing_mobile/browse:news:toi [ Skip ] crbug.com/923116 [ Android ] v8.browsing_mobile/browse:shopping:avito [ Skip ] crbug.com/923517 [ Android_Go ] v8.browsing_mobile/browse:social:tumblr_infinite_scroll:2018 [ Skip ] @@ -407,7 +410,7 @@ crbug.com/910207 [ Nexus_5X ] v8.browsing_mobile-future/browse:chrome:newtab [ Skip ] crbug.com/799080 [ Nexus_5X Android_Webview ] v8.browsing_mobile-future/browse:social:facebook [ Skip ] crbug.com/799080 [ Nexus_5X Android_Webview ] v8.browsing_mobile-future/browse:social:facebook [ Skip ] -crbug.com/901534 [ Nexus6_Webview ] v8.browsing_mobile-future/browse:news:toi [ Skip ] +crbug.com/901534 [ Android ] v8.browsing_mobile-future/browse:news:toi [ Skip ] crbug.com/865400 [ Pixel_2 ] v8.browsing_mobile-future/browse:shopping:avito [ Skip ] crbug.com/923116 [ Android ] v8.browsing_mobile-future/browse:shopping:avito [ Skip ] crbug.com/906654 [ All ] v8.browsing_mobile-future/browse:tech:discourse_infinite_scroll [ Skip ]
diff --git a/tools/perf/wpr/update_wpr.py b/tools/perf/wpr/update_wpr.py index f72b3cc2..c5a42b6 100644 --- a/tools/perf/wpr/update_wpr.py +++ b/tools/perf/wpr/update_wpr.py
@@ -195,6 +195,22 @@ count = shell(cmd + '| wc -l') cli_helpers.Info(' %-16s%-8s %s' % ('[javascript]:', count, cmd)) + def _UploadArchiveToGoogleStorage(self, archive): + """Uploads specified WPR archive to the GS.""" + cli_helpers.Run([ + 'upload_to_google_storage.py', '--bucket=chrome-partner-telemetry', + archive]) + + def _GitAddArtifactHash(self, archive): + """Stages changes into SHA1 file for commit.""" + archive_sha1 = archive + '.sha1' + if not os.path.exists(archive_sha1): + cli_helpers.Error( + 'Could not find upload artifact: {sha}', sha=archive_sha1) + return False + cli_helpers.Run(['git', 'add', archive_sha1]) + return True + def LiveRun(self): cli_helpers.Step('LIVE RUN: %s' % self.story) out_file = self._RunSystemHealthMemoryBenchmark( @@ -228,6 +244,14 @@ self._PrintRunInfo(out_file) return out_file + def UploadWpr(self): + cli_helpers.Step('UPLOAD WPR: %s' % self.story) + archive = self._ExistingWpr() + if archive is None: + cli_helpers.Error('NO WPR FOUND, use the "record" subcommand') + self._UploadArchiveToGoogleStorage(archive) + return self._GitAddArtifactHash(archive) + def Main(argv): parser = argparse.ArgumentParser() @@ -246,7 +270,7 @@ help='Path to the Chromium/Chrome binary relative to output directory. ' 'Defaults to default Chrome browser installed if not specified.') parser.add_argument( - 'command', choices=['live', 'record', 'replay'], + 'command', choices=['live', 'record', 'replay', 'upload'], help='Mode in which to run this script.') args = parser.parse_args(argv) @@ -258,4 +282,6 @@ updater.RecordWpr() elif args.command == 'replay': updater.ReplayWpr() + elif args.command == 'upload': + updater.UploadWpr() updater.Cleanup()
diff --git a/tools/perf/wpr/update_wpr_unittest.py b/tools/perf/wpr/update_wpr_unittest.py index 5e595468..7c7c715e 100644 --- a/tools/perf/wpr/update_wpr_unittest.py +++ b/tools/perf/wpr/update_wpr_unittest.py
@@ -196,6 +196,15 @@ run_benchmark.assert_called_once_with(log_name='replay', live=False) print_run_info.assert_called_once_with('<out-file>') + def testUploadWPR(self): + mock.patch(WPR_UPDATER + '_ExistingWpr', return_value='<archive>').start() + self.wpr_updater.UploadWpr() + self.assertListEqual(self._run.mock_calls, [ + mock.call(['upload_to_google_storage.py', + '--bucket=chrome-partner-telemetry', '<archive>']), + mock.call(['git', 'add', '<archive>.sha1']) + ]) + if __name__ == "__main__": unittest.main()
diff --git a/tools/traffic_annotation/summary/annotations.xml b/tools/traffic_annotation/summary/annotations.xml index 846c3ece9..1257372 100644 --- a/tools/traffic_annotation/summary/annotations.xml +++ b/tools/traffic_annotation/summary/annotations.xml
@@ -276,7 +276,7 @@ <item id="ui_devtools_server" hash_code="4986170" type="0" content_hash_code="62670263" os_list="linux,windows" file_path="components/ui_devtools/devtools_server.cc"/> <item id="undefined" hash_code="45578882" type="0" reserved="1" os_list="linux,windows" file_path=""/> <item id="unwanted_software_report" hash_code="43759504" type="0" content_hash_code="43217092" os_list="windows" file_path="chrome/chrome_cleaner/logging/reporter_logging_service.cc"/> - <item id="update_client" hash_code="54845618" type="0" content_hash_code="10382647" os_list="linux,windows" file_path="components/update_client/net/network_impl.cc"/> + <item id="update_client" hash_code="54845618" type="0" content_hash_code="33566159" os_list="linux,windows" file_path="components/update_client/net/network_impl.cc"/> <item id="url_fetcher_downloader" hash_code="113231892" type="0" deprecated="2019-02-09" content_hash_code="61085066" file_path=""/> <item id="url_prevision_fetcher" hash_code="118389509" type="0" content_hash_code="66145513" os_list="linux,windows" file_path="content/browser/media/url_provision_fetcher.cc"/> <item id="user_info_fetcher" hash_code="22265491" type="0" content_hash_code="72016232" os_list="linux,windows" file_path="components/policy/core/common/cloud/user_info_fetcher.cc"/>
diff --git a/tools/web_dev_style/resource_checker.py b/tools/web_dev_style/resource_checker.py index 4a74ff4..576095e5c 100644 --- a/tools/web_dev_style/resource_checker.py +++ b/tools/web_dev_style/resource_checker.py
@@ -15,9 +15,13 @@ self.output_api = output_api self.file_filter = file_filter + def DeprecatedMojoBindingsCheck(self, line_number, line): + return regex_check.RegexCheck(self.input_api.re, line_number, line, + '(mojo_bindings\.js)', 'Please use mojo_bindings_lite.js in new code') + def DisallowIncludeCheck(self, msg, line_number, line): return regex_check.RegexCheck(self.input_api.re, line_number, line, - '^\s*(?:\/[\*\/])?\s*(<include)\s*src=', msg) + '^\s*(?:\/[\*\/])?\s*(<include)\s*src=', msg) # This is intentionally not included in RunChecks(). It's an optional check # that can be used from a PRESUBMIT.py in a directory that does not wish to @@ -30,13 +34,17 @@ def SelfClosingIncludeCheck(self, line_number, line): return regex_check.RegexCheck(self.input_api.re, line_number, line, - "(</include>|<include.*/>)", "Closing <include> tags is unnecessary.") + '(</include>|<include.*/>)', 'Closing <include> tags is unnecessary.') def RunChecks(self): - return self._RunCheckOnAffectedFiles( - self.SelfClosingIncludeCheck, 'Found resources style issues in %s') + msg = 'Found resources style issues in %s' + # TODO(crbug.com/931798): is_error for Mojo check when -lite is majority? + return self._RunCheckOnAffectedFiles(self.DeprecatedMojoBindingsCheck, + msg, only_changed_lines=True) + \ + self._RunCheckOnAffectedFiles(self.SelfClosingIncludeCheck, msg) - def _RunCheckOnAffectedFiles(self, check, msg_template, is_error=False): + def _RunCheckOnAffectedFiles(self, check, msg_template, is_error=False, + only_changed_lines=False): """Check for violations of the Chromium web development style guide. See https://chromium.googlesource.com/chromium/src/+/master/styleguide/web/web.md """ @@ -46,8 +54,11 @@ include_deletes=False) for f in affected_files: errors = [] - - for line_number, line in enumerate(f.NewContents(), start=1): + if only_changed_lines: + contents = f.ChangedContents() + else: + contents = enumerate(f.NewContents(), start=1) + for line_number, line in contents: error = check(line_number, line) if error: errors.append(error)
diff --git a/tools/web_dev_style/resource_checker_test.py b/tools/web_dev_style/resource_checker_test.py index da3877a..30093ab 100755 --- a/tools/web_dev_style/resource_checker_test.py +++ b/tools/web_dev_style/resource_checker_test.py
@@ -26,6 +26,57 @@ output_api = self.mox.CreateMockAnything() self.checker = resource_checker.ResourceChecker(input_api, output_api) + def ShouldPassDeprecatedMojoBindingCheck(self, line): + error = self.checker.DeprecatedMojoBindingsCheck(1, line) + self.assertEqual('', error, 'Should not be flagged as error: ' + line) + + def ShouldFailDeprecatedMojoBindingCheck(self, line): + error = self.checker.DeprecatedMojoBindingsCheck(1, line) + self.assertNotEqual('', error, 'Should be flagged as error: ' + line) + self.assertEquals('mojo_bindings.js', test_util.GetHighlight(line, error)) + + def testDeprecatedMojoBindingsCheckPasses(self): + lines = [ + '<script src="chrome://resources/js/mojo_bindings_lite.js">', + "script.src = 'chrome://resources/js/mojo_bindings_lite.js';", + ] + for line in lines: + self.ShouldPassDeprecatedMojoBindingCheck(line) + + def testDeprecatedMojoBindingsCheckFails(self): + lines = [ + '<script src="chrome://resources/js/mojo_bindings.js">', + "script.src = 'chrome://resources/js/mojo_bindings.js';", + ] + for line in lines: + self.ShouldFailDeprecatedMojoBindingCheck(line) + + def ShouldPassDisallowIncludeCheck(self, line): + self.assertEqual('', self.checker.DisallowIncludeCheck('msg', 1, line), + 'Should not be flagged as error') + + def ShouldFailDisallowIncludeCheck(self, line): + error = self.checker.DisallowIncludeCheck('msg', 1, line) + self.assertNotEqual('', error, 'Should be flagged as error: ' + line) + self.assertEquals('<include', test_util.GetHighlight(line, error)) + + def testDisallowIncludesFails(self): + lines = [ + '<include src="blah.js">', + ' // <include src="blah.js">', + ' /* <include src="blah.js"> */ ', + ] + for line in lines: + self.ShouldFailDisallowIncludeCheck(line) + + def testDisallowIncludesPasses(self): + lines = [ + 'if (count < includeCount) {', + '// No <include>s allowed.', + ] + for line in lines: + self.ShouldPassDisallowIncludeCheck(line) + def ShouldFailSelfClosingIncludeCheck(self, line): """Checks that the '</include>' checker flags |line| as a style error.""" error = self.checker.SelfClosingIncludeCheck(1, line) @@ -61,32 +112,6 @@ for line in lines: self.ShouldPassSelfClosingIncludeCheck(line) - def ShouldPassDisallowIncludeCheck(self, line): - self.assertEqual('', self.checker.DisallowIncludeCheck('msg', 1, line), - 'Should not be flagged as error') - - def ShouldFailDisallowIncludeCheck(self, line): - error = self.checker.DisallowIncludeCheck('msg', 1, line) - self.assertNotEqual('', error, 'Should be flagged as error: ' + line) - self.assertEquals('<include', test_util.GetHighlight(line, error)) - - def testDisallowIncludesFails(self): - lines = [ - '<include src="blah.js">', - ' // <include src="blah.js">', - ' /* <include src="blah.js"> */ ', - ] - for line in lines: - self.ShouldFailDisallowIncludeCheck(line) - - def testDisallowIncludesPasses(self): - lines = [ - 'if (count < includeCount) {', - '// No <include>s allowed.', - ] - for line in lines: - self.ShouldPassDisallowIncludeCheck(line) - if __name__ == '__main__': unittest.main()
diff --git a/ui/accessibility/platform/ax_platform_node_auralinux_unittest.cc b/ui/accessibility/platform/ax_platform_node_auralinux_unittest.cc index f275278b..258e7904 100644 --- a/ui/accessibility/platform/ax_platform_node_auralinux_unittest.cc +++ b/ui/accessibility/platform/ax_platform_node_auralinux_unittest.cc
@@ -66,7 +66,7 @@ if (0 == strcmp(attribute_name, attribute->name)) { // Ensure that we only see this attribute once. - ASSERT_FALSE(saw_attribute); + ASSERT_FALSE(saw_attribute) << attribute_name; EXPECT_STREQ(attribute_value, attribute->value); saw_attribute = true; @@ -86,7 +86,7 @@ AtkAttributeSet* current = attributes; while (current) { AtkAttribute* attribute = static_cast<AtkAttribute*>(current->data); - ASSERT_NE(0, strcmp(attribute_name, attribute->name)) << attribute_name; + ASSERT_STRNE(attribute_name, attribute->name) << attribute_name; current = current->next; } atk_attribute_set_free(attributes); @@ -578,7 +578,6 @@ TEST_F(AXPlatformNodeAuraLinuxTest, DISABLED_TestAtkObjectIntAttributes) { AXNodeData root_data; root_data.id = 1; - Init(root_data); AXNode* root_node = GetRootNode();
diff --git a/ui/accessibility/platform/ax_platform_node_delegate_base.cc b/ui/accessibility/platform/ax_platform_node_delegate_base.cc index 4fe9726..8fab20f 100644 --- a/ui/accessibility/platform/ax_platform_node_delegate_base.cc +++ b/ui/accessibility/platform/ax_platform_node_delegate_base.cc
@@ -8,6 +8,7 @@ #include "base/no_destructor.h" #include "ui/accessibility/ax_node_data.h" +#include "ui/accessibility/ax_role_properties.h" #include "ui/accessibility/ax_tree_data.h" namespace ui { @@ -73,23 +74,23 @@ } bool AXPlatformNodeDelegateBase::IsTable() const { - return false; + return ui::IsTableLike(GetData().role); } int AXPlatformNodeDelegateBase::GetTableRowCount() const { - return 0; + return GetData().GetIntAttribute(ax::mojom::IntAttribute::kTableRowCount); } int AXPlatformNodeDelegateBase::GetTableColCount() const { - return 0; + return GetData().GetIntAttribute(ax::mojom::IntAttribute::kTableColumnCount); } int32_t AXPlatformNodeDelegateBase::GetTableAriaColCount() const { - return 0; + return GetData().GetIntAttribute(ax::mojom::IntAttribute::kAriaColumnCount); } int32_t AXPlatformNodeDelegateBase::GetTableAriaRowCount() const { - return 0; + return GetData().GetIntAttribute(ax::mojom::IntAttribute::kAriaRowCount); } int32_t AXPlatformNodeDelegateBase::GetTableCellCount() const { @@ -98,58 +99,61 @@ const std::vector<int32_t> AXPlatformNodeDelegateBase::GetColHeaderNodeIds() const { - return std::vector<int32_t>(); + return {}; } const std::vector<int32_t> AXPlatformNodeDelegateBase::GetColHeaderNodeIds( int32_t col_index) const { - return std::vector<int32_t>(); + return {}; } const std::vector<int32_t> AXPlatformNodeDelegateBase::GetRowHeaderNodeIds() const { - return std::vector<int32_t>(); + return {}; } const std::vector<int32_t> AXPlatformNodeDelegateBase::GetRowHeaderNodeIds( int32_t row_index) const { - return std::vector<int32_t>(); + return {}; } bool AXPlatformNodeDelegateBase::IsTableRow() const { - return false; + return ui::IsTableRow(GetData().role); } int32_t AXPlatformNodeDelegateBase::GetTableRowRowIndex() const { - return 0; + return GetData().GetIntAttribute(ax::mojom::IntAttribute::kTableRowIndex); } bool AXPlatformNodeDelegateBase::IsTableCellOrHeader() const { - return false; + return ui::IsCellOrTableHeader(GetData().role); } int32_t AXPlatformNodeDelegateBase::GetTableCellColIndex() const { - return 0; + return GetData().GetIntAttribute( + ax::mojom::IntAttribute::kTableCellColumnIndex); } int32_t AXPlatformNodeDelegateBase::GetTableCellRowIndex() const { - return 0; + return GetData().GetIntAttribute(ax::mojom::IntAttribute::kTableCellRowIndex); } int32_t AXPlatformNodeDelegateBase::GetTableCellColSpan() const { - return 0; + return GetData().GetIntAttribute( + ax::mojom::IntAttribute::kTableCellColumnSpan); } int32_t AXPlatformNodeDelegateBase::GetTableCellRowSpan() const { - return 0; + return GetData().GetIntAttribute(ax::mojom::IntAttribute::kTableCellRowSpan); } int32_t AXPlatformNodeDelegateBase::GetTableCellAriaColIndex() const { - return 0; + return GetData().GetIntAttribute( + ax::mojom::IntAttribute::kAriaCellColumnIndex); } int32_t AXPlatformNodeDelegateBase::GetTableCellAriaRowIndex() const { - return 0; + return GetData().GetIntAttribute(ax::mojom::IntAttribute::kAriaCellRowIndex); } int32_t AXPlatformNodeDelegateBase::GetCellId(int32_t row_index,
diff --git a/ui/accessibility/platform/ax_platform_node_win.cc b/ui/accessibility/platform/ax_platform_node_win.cc index 4559bc6..57665b56 100644 --- a/ui/accessibility/platform/ax_platform_node_win.cc +++ b/ui/accessibility/platform/ax_platform_node_win.cc
@@ -373,7 +373,6 @@ AXPlatformNodeWin* node_win = static_cast<AXPlatformNodeWin*>(GetDelegate()->GetFromNodeID(node_id)); DCHECK(node_win); - node_win->AddRef(); SafeArrayPutElement(uia_array, &i, static_cast<IRawElementProviderSimple*>(node_win)); ++i; @@ -1868,15 +1867,31 @@ IFACEMETHODIMP AXPlatformNodeWin::GetSelection(SAFEARRAY** result) { UIA_VALIDATE_CALL_1_ARG(result); - int child_count = GetDelegate()->GetChildCount(); - *result = SafeArrayCreateVector(VT_UNKNOWN, 0, child_count); + + std::vector<AXPlatformNodeWin*> selected_children; + LONG child_count = GetDelegate()->GetChildCount(); for (LONG i = 0; i < child_count; ++i) { auto* child = static_cast<AXPlatformNodeWin*>( FromNativeViewAccessible(GetDelegate()->ChildAtIndex(i))); DCHECK(child); - child->AddRef(); - SafeArrayPutElement(*result, &i, - static_cast<IRawElementProviderSimple*>(child)); + if (child->GetData().GetBoolAttribute(ax::mojom::BoolAttribute::kSelected)) + selected_children.push_back(child); + } + + LONG selected_children_count = selected_children.size(); + *result = SafeArrayCreateVector(VT_UNKNOWN, 0, selected_children_count); + if (!*result) + return E_OUTOFMEMORY; + + for (LONG i = 0; i < selected_children_count; ++i) { + HRESULT hr = SafeArrayPutElement( + *result, &i, + static_cast<IRawElementProviderSimple*>(selected_children[i])); + if (FAILED(hr)) { + SafeArrayDestroy(*result); + *result = nullptr; + return hr; + } } return S_OK; } @@ -1889,7 +1904,8 @@ IFACEMETHODIMP AXPlatformNodeWin::get_IsSelectionRequired(BOOL* result) { UIA_VALIDATE_CALL_1_ARG(result); - return E_NOTIMPL; + *result = GetData().HasState(ax::mojom::State::kRequired); + return S_OK; } //
diff --git a/ui/accessibility/platform/ax_platform_node_win_unittest.cc b/ui/accessibility/platform/ax_platform_node_win_unittest.cc index 30fb7185..a966c1f 100644 --- a/ui/accessibility/platform/ax_platform_node_win_unittest.cc +++ b/ui/accessibility/platform/ax_platform_node_win_unittest.cc
@@ -137,7 +137,6 @@ EXPECT_HRESULT_SUCCEEDED( ax_platform_node->GetNativeViewAccessible()->QueryInterface(__uuidof(T), &result)); - return result; } @@ -152,13 +151,7 @@ } ComPtr<IAccessible> AXPlatformNodeWinTest::IAccessibleFromNode(AXNode* node) { - TestAXNodeWrapper* wrapper = - TestAXNodeWrapper::GetOrCreate(tree_.get(), node); - if (!wrapper) - return ComPtr<IAccessible>(); - AXPlatformNode* ax_platform_node = wrapper->ax_platform_node(); - IAccessible* iaccessible = ax_platform_node->GetNativeViewAccessible(); - return ComPtr<IAccessible>(iaccessible); + return QueryInterfaceFromNode<IAccessible>(node); } ComPtr<IAccessible> AXPlatformNodeWinTest::GetRootIAccessible() { @@ -254,6 +247,45 @@ return fragment_root_provider; } +void AXPlatformNodeWinTest::InitListBox( + bool option_1_is_selected, + bool option_2_is_selected, + bool option_3_is_selected, + ax::mojom::State additional_state = ax::mojom::State::kNone) { + AXNodeData listbox; + listbox.id = 0; + listbox.SetName("ListBox"); + listbox.role = ax::mojom::Role::kListBox; + if (additional_state != ax::mojom::State::kNone) + listbox.AddState(additional_state); + + AXNodeData option_1; + option_1.id = 1; + option_1.SetName("Option1"); + option_1.role = ax::mojom::Role::kListBoxOption; + if (option_1_is_selected) + option_1.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); + listbox.child_ids.push_back(option_1.id); + + AXNodeData option_2; + option_2.id = 2; + option_2.SetName("Option2"); + option_2.role = ax::mojom::Role::kListBoxOption; + if (option_2_is_selected) + option_2.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); + listbox.child_ids.push_back(option_2.id); + + AXNodeData option_3; + option_3.id = 3; + option_3.SetName("Option3"); + option_3.role = ax::mojom::Role::kListBoxOption; + if (option_3_is_selected) + option_3.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); + listbox.child_ids.push_back(option_3.id); + + Init(listbox, option_1, option_2, option_3); +} + TEST_F(AXPlatformNodeWinTest, TestIAccessibleDetachedObject) { AXNodeData root; root.id = 1; @@ -3092,12 +3124,12 @@ SAFEARRAY* runtime_id; EXPECT_HRESULT_SUCCEEDED(root_provider->GetRuntimeId(&runtime_id)); - long array_lower_bound; + LONG array_lower_bound; EXPECT_HRESULT_SUCCEEDED( ::SafeArrayGetLBound(runtime_id, 1, &array_lower_bound)); EXPECT_EQ(0, array_lower_bound); - long array_upper_bound; + LONG array_upper_bound; EXPECT_HRESULT_SUCCEEDED( ::SafeArrayGetUBound(runtime_id, 1, &array_upper_bound)); EXPECT_EQ(1, array_upper_bound); @@ -3176,6 +3208,168 @@ nullptr); } +TEST_F(AXPlatformNodeWinTest, TestISelectionProviderCanSelectMultipleDefault) { + InitListBox(/*option_1_is_selected*/ false, + /*option_2_is_selected*/ false, + /*option_3_is_selected*/ false); + + ComPtr<ISelectionProvider> selection_provider( + QueryInterfaceFromNode<ISelectionProvider>(GetRootNode())); + + BOOL multiple = TRUE; + EXPECT_HRESULT_SUCCEEDED( + selection_provider->get_CanSelectMultiple(&multiple)); + EXPECT_FALSE(multiple); +} + +TEST_F(AXPlatformNodeWinTest, TestISelectionProviderCanSelectMultipleTrue) { + InitListBox(/*option_1_is_selected*/ false, + /*option_2_is_selected*/ false, + /*option_3_is_selected*/ false, + /*additional_state*/ ax::mojom::State::kMultiselectable); + + ComPtr<ISelectionProvider> selection_provider( + QueryInterfaceFromNode<ISelectionProvider>(GetRootNode())); + + BOOL multiple = FALSE; + EXPECT_HRESULT_SUCCEEDED( + selection_provider->get_CanSelectMultiple(&multiple)); + EXPECT_TRUE(multiple); +} + +TEST_F(AXPlatformNodeWinTest, + TestISelectionProviderIsSelectionRequiredDefault) { + InitListBox(/*option_1_is_selected*/ false, + /*option_2_is_selected*/ false, + /*option_3_is_selected*/ false); + + ComPtr<ISelectionProvider> selection_provider( + QueryInterfaceFromNode<ISelectionProvider>(GetRootNode())); + + BOOL selection_required = TRUE; + EXPECT_HRESULT_SUCCEEDED( + selection_provider->get_IsSelectionRequired(&selection_required)); + EXPECT_FALSE(selection_required); +} + +TEST_F(AXPlatformNodeWinTest, TestISelectionProviderIsSelectionRequiredTrue) { + InitListBox(/*option_1_is_selected*/ false, + /*option_2_is_selected*/ false, + /*option_3_is_selected*/ false, + /*additional_state*/ ax::mojom::State::kRequired); + + ComPtr<ISelectionProvider> selection_provider( + QueryInterfaceFromNode<ISelectionProvider>(GetRootNode())); + + BOOL selection_required = FALSE; + EXPECT_HRESULT_SUCCEEDED( + selection_provider->get_IsSelectionRequired(&selection_required)); + EXPECT_TRUE(selection_required); +} + +TEST_F(AXPlatformNodeWinTest, TestISelectionProviderGetSelectionNoneSelected) { + InitListBox(/*option_1_is_selected*/ false, + /*option_2_is_selected*/ false, + /*option_3_is_selected*/ false); + + ComPtr<ISelectionProvider> selection_provider( + QueryInterfaceFromNode<ISelectionProvider>(GetRootNode())); + + SAFEARRAY* selected_items; + EXPECT_HRESULT_SUCCEEDED(selection_provider->GetSelection(&selected_items)); + EXPECT_NE(nullptr, selected_items); + + LONG array_lower_bound; + EXPECT_HRESULT_SUCCEEDED( + ::SafeArrayGetLBound(selected_items, 1, &array_lower_bound)); + EXPECT_EQ(0, array_lower_bound); + + LONG array_upper_bound; + EXPECT_HRESULT_SUCCEEDED( + ::SafeArrayGetUBound(selected_items, 1, &array_upper_bound)); + EXPECT_EQ(-1, array_upper_bound); + + EXPECT_HRESULT_SUCCEEDED(::SafeArrayDestroy(selected_items)); +} + +TEST_F(AXPlatformNodeWinTest, + TestISelectionProviderGetSelectionSingleItemSelected) { + InitListBox(/*option_1_is_selected*/ false, + /*option_2_is_selected*/ true, + /*option_3_is_selected*/ false); + + ComPtr<ISelectionProvider> selection_provider( + QueryInterfaceFromNode<ISelectionProvider>(GetRootNode())); + ComPtr<IRawElementProviderSimple> option2_provider( + QueryInterfaceFromNode<IRawElementProviderSimple>( + GetRootNode()->children()[1])); + + SAFEARRAY* selected_items; + EXPECT_HRESULT_SUCCEEDED(selection_provider->GetSelection(&selected_items)); + EXPECT_NE(nullptr, selected_items); + + LONG array_lower_bound; + EXPECT_HRESULT_SUCCEEDED( + ::SafeArrayGetLBound(selected_items, 1, &array_lower_bound)); + EXPECT_EQ(0, array_lower_bound); + + LONG array_upper_bound; + EXPECT_HRESULT_SUCCEEDED( + ::SafeArrayGetUBound(selected_items, 1, &array_upper_bound)); + EXPECT_EQ(0, array_upper_bound); + + IRawElementProviderSimple** array_data; + EXPECT_HRESULT_SUCCEEDED(::SafeArrayAccessData( + selected_items, reinterpret_cast<void**>(&array_data))); + EXPECT_EQ(option2_provider.Get(), array_data[0]); + + EXPECT_HRESULT_SUCCEEDED(::SafeArrayUnaccessData(selected_items)); + EXPECT_HRESULT_SUCCEEDED(::SafeArrayDestroy(selected_items)); +} + +TEST_F(AXPlatformNodeWinTest, + TestISelectionProviderGetSelectionMultipleItemsSelected) { + InitListBox(/*option_1_is_selected*/ true, + /*option_2_is_selected*/ true, + /*option_3_is_selected*/ true); + + ComPtr<ISelectionProvider> selection_provider( + QueryInterfaceFromNode<ISelectionProvider>(GetRootNode())); + ComPtr<IRawElementProviderSimple> option1_provider( + QueryInterfaceFromNode<IRawElementProviderSimple>( + GetRootNode()->children()[0])); + ComPtr<IRawElementProviderSimple> option2_provider( + QueryInterfaceFromNode<IRawElementProviderSimple>( + GetRootNode()->children()[1])); + ComPtr<IRawElementProviderSimple> option3_provider( + QueryInterfaceFromNode<IRawElementProviderSimple>( + GetRootNode()->children()[2])); + + SAFEARRAY* selected_items; + EXPECT_HRESULT_SUCCEEDED(selection_provider->GetSelection(&selected_items)); + EXPECT_NE(nullptr, selected_items); + + LONG array_lower_bound; + EXPECT_HRESULT_SUCCEEDED( + ::SafeArrayGetLBound(selected_items, 1, &array_lower_bound)); + EXPECT_EQ(0, array_lower_bound); + + LONG array_upper_bound; + EXPECT_HRESULT_SUCCEEDED( + ::SafeArrayGetUBound(selected_items, 1, &array_upper_bound)); + EXPECT_EQ(2, array_upper_bound); + + IRawElementProviderSimple** array_data; + EXPECT_HRESULT_SUCCEEDED(::SafeArrayAccessData( + selected_items, reinterpret_cast<void**>(&array_data))); + EXPECT_EQ(option1_provider.Get(), array_data[0]); + EXPECT_EQ(option2_provider.Get(), array_data[1]); + EXPECT_EQ(option3_provider.Get(), array_data[2]); + + EXPECT_HRESULT_SUCCEEDED(::SafeArrayUnaccessData(selected_items)); + EXPECT_HRESULT_SUCCEEDED(::SafeArrayDestroy(selected_items)); +} + TEST_F(AXPlatformNodeWinTest, TestUIAErrorHandling) { AXNodeData root; Init(root);
diff --git a/ui/accessibility/platform/ax_platform_node_win_unittest.h b/ui/accessibility/platform/ax_platform_node_win_unittest.h index caaeaee..98f1360b 100644 --- a/ui/accessibility/platform/ax_platform_node_win_unittest.h +++ b/ui/accessibility/platform/ax_platform_node_win_unittest.h
@@ -59,6 +59,11 @@ void InitFragmentRoot(); Microsoft::WRL::ComPtr<IRawElementProviderFragmentRoot> GetFragmentRoot(); + void InitListBox(bool option_1_is_selected, + bool option_2_is_selected, + bool option_3_is_selected, + ax::mojom::State additional_state); + std::unique_ptr<AXFragmentRootWin> ax_fragment_root_; };
diff --git a/ui/android/java/res/values/attrs.xml b/ui/android/java/res/values/attrs.xml index b9ce9b6..f82f8f00d 100644 --- a/ui/android/java/res/values/attrs.xml +++ b/ui/android/java/res/values/attrs.xml
@@ -3,6 +3,8 @@ Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> <resources> + <attr name="rippleColor" format="color"/> + <declare-styleable name="DualControlLayout"> <attr name="stackedMargin" format="reference"/> <attr name="primaryButtonText" format="reference|string"/> @@ -16,7 +18,7 @@ <declare-styleable name="ButtonCompat"> <attr name="buttonColor" format="color"/> - <attr name="rippleColor" format="color"/> + <attr name="rippleColor"/> <attr name="buttonRaised" format="boolean"/> </declare-styleable> @@ -28,7 +30,7 @@ <attr name="iconHeight" format="reference|dimension"/> <attr name="primaryTextAppearance" format="reference"/> <attr name="secondaryTextAppearance" format="reference"/> - <attr name="rippleColor" format="color"/> + <attr name="rippleColor"/> </declare-styleable> <declare-styleable name="TextViewWithLeading">
diff --git a/ui/aura/mus/mus_lsi_allocator.cc b/ui/aura/mus/mus_lsi_allocator.cc index b224ee99..baa6622d 100644 --- a/ui/aura/mus/mus_lsi_allocator.cc +++ b/ui/aura/mus/mus_lsi_allocator.cc
@@ -222,9 +222,10 @@ } void TopLevelAllocator::NotifyServerOfLocalSurfaceId() { - window_tree_client()->OnWindowTreeHostBoundsWillChange( - static_cast<WindowTreeHostMus*>(GetWindow()->GetHost()), - GetWindow()->GetHost()->GetBoundsInPixels()); + WindowTreeHostMus* host = + static_cast<WindowTreeHostMus*>(GetWindow()->GetHost()); + window_tree_client()->OnWindowTreeHostBoundsWillChange(host, + host->bounds_in_dip()); } // EmbeddedAllocator -----------------------------------------------------------
diff --git a/ui/aura/mus/window_tree_client.cc b/ui/aura/mus/window_tree_client.cc index 8950782..22ced9e 100644 --- a/ui/aura/mus/window_tree_client.cc +++ b/ui/aura/mus/window_tree_client.cc
@@ -716,8 +716,8 @@ void WindowTreeClient::ScheduleInFlightBoundsChange( WindowMus* window, - const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) { + const gfx::Rect& old_bounds_in_dip, + const gfx::Rect& new_bounds_in_dip) { base::Optional<viz::LocalSurfaceIdAllocation> local_surface_id_allocation = window->GetLocalSurfaceIdAllocation(); if (!local_surface_id_allocation->IsValid()) { @@ -736,9 +736,9 @@ } const uint32_t change_id = ScheduleInFlightChange(std::make_unique<InFlightBoundsChange>( - this, window, old_bounds, /* from_server */ false, + this, window, old_bounds_in_dip, /* from_server */ false, local_surface_id_allocation)); - tree_->SetWindowBounds(change_id, window->server_id(), new_bounds, + tree_->SetWindowBounds(change_id, window->server_id(), new_bounds_in_dip, local_surface_id_allocation); }
diff --git a/ui/aura/mus/window_tree_client.h b/ui/aura/mus/window_tree_client.h index 5d863e2..3e2bd45 100644 --- a/ui/aura/mus/window_tree_client.h +++ b/ui/aura/mus/window_tree_client.h
@@ -356,8 +356,8 @@ // Called from OnWindowMusBoundsChanged() and SetRootWindowBounds(). void ScheduleInFlightBoundsChange(WindowMus* window, - const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds); + const gfx::Rect& old_bounds_in_dip, + const gfx::Rect& new_bounds_in_dip); // Following are called from WindowMus. void OnWindowMusCreated(WindowMus* window);
diff --git a/ui/aura/mus/window_tree_host_mus.cc b/ui/aura/mus/window_tree_host_mus.cc index 203712f4..3206b5a 100644 --- a/ui/aura/mus/window_tree_host_mus.cc +++ b/ui/aura/mus/window_tree_host_mus.cc
@@ -188,7 +188,7 @@ } void WindowTreeHostMus::SetBounds( - const gfx::Rect& bounds, + const gfx::Rect& bounds_in_dip, const viz::LocalSurfaceIdAllocation& local_surface_id_allocation) { viz::LocalSurfaceIdAllocation actual_local_surface_id_allocation = local_surface_id_allocation; @@ -199,8 +199,9 @@ // Do not use ConvertRectToPixel, enclosing rects cause problems. In // particular, ConvertRectToPixel's result varies based on the location. const float dsf = ui::GetScaleFactorForNativeView(window()); - const gfx::Rect pixel_bounds(gfx::ScaleToFlooredPoint(bounds.origin(), dsf), - gfx::ScaleToCeiledSize(bounds.size(), dsf)); + const gfx::Rect pixel_bounds( + gfx::ScaleToFlooredPoint(bounds_in_dip.origin(), dsf), + gfx::ScaleToCeiledSize(bounds_in_dip.size(), dsf)); if (!in_set_bounds_from_server_) { // Update the LocalSurfaceIdAllocation here, rather than in WindowTreeHost // as WindowTreeClient (the delegate) needs that information before @@ -212,9 +213,9 @@ actual_local_surface_id_allocation = window()->GetLocalSurfaceIdAllocation(); } - delegate_->OnWindowTreeHostBoundsWillChange(this, bounds); + delegate_->OnWindowTreeHostBoundsWillChange(this, bounds_in_dip); } - bounds_in_dip_ = bounds; + bounds_in_dip_ = bounds_in_dip; WindowTreeHostPlatform::SetBoundsInPixels(pixel_bounds, actual_local_surface_id_allocation); }
diff --git a/ui/aura/mus/window_tree_host_mus.h b/ui/aura/mus/window_tree_host_mus.h index ef03a6d..4d17b48f 100644 --- a/ui/aura/mus/window_tree_host_mus.h +++ b/ui/aura/mus/window_tree_host_mus.h
@@ -41,7 +41,7 @@ static WindowTreeHostMus* ForWindow(aura::Window* window); virtual void SetBounds( - const gfx::Rect& bounds, + const gfx::Rect& bounds_in_dip, const viz::LocalSurfaceIdAllocation& local_surface_id_allocation); void SetBoundsFromServer( const gfx::Rect& bounds,
diff --git a/ui/aura/window_tree_host_platform.cc b/ui/aura/window_tree_host_platform.cc index b21abe04..ede54de7 100644 --- a/ui/aura/window_tree_host_platform.cc +++ b/ui/aura/window_tree_host_platform.cc
@@ -57,7 +57,7 @@ std::unique_ptr<Window> window, const char* trace_environment_name) : WindowTreeHost(std::move(window)) { - bounds_ = properties.bounds; + bounds_in_pixels_ = properties.bounds; CreateCompositor(viz::FrameSinkId(), /* force_software_compositor */ false, /* external_begin_frames_enabled */ nullptr, @@ -200,18 +200,20 @@ void WindowTreeHostPlatform::OnBoundsChanged(const gfx::Rect& new_bounds) { float current_scale = compositor()->device_scale_factor(); float new_scale = ui::GetScaleFactorForNativeView(window()); - gfx::Rect old_bounds = bounds_; - bounds_ = new_bounds; - if (bounds_.origin() != old_bounds.origin()) - OnHostMovedInPixels(bounds_.origin()); + gfx::Rect old_bounds = bounds_in_pixels_; + bounds_in_pixels_ = new_bounds; + if (bounds_in_pixels_.origin() != old_bounds.origin()) + OnHostMovedInPixels(bounds_in_pixels_.origin()); if (pending_local_surface_id_allocation_.IsValid() || - bounds_.size() != old_bounds.size() || current_scale != new_scale) { + bounds_in_pixels_.size() != old_bounds.size() || + current_scale != new_scale) { viz::LocalSurfaceIdAllocation local_surface_id_allocation; - if (bounds_.size() == pending_size_) + if (bounds_in_pixels_.size() == pending_size_) local_surface_id_allocation = pending_local_surface_id_allocation_; pending_local_surface_id_allocation_ = viz::LocalSurfaceIdAllocation(); pending_size_ = gfx::Size(); - OnHostResizedInPixels(bounds_.size(), local_surface_id_allocation); + OnHostResizedInPixels(bounds_in_pixels_.size(), + local_surface_id_allocation); } }
diff --git a/ui/aura/window_tree_host_platform.h b/ui/aura/window_tree_host_platform.h index 354d7be..369c37b 100644 --- a/ui/aura/window_tree_host_platform.h +++ b/ui/aura/window_tree_host_platform.h
@@ -94,7 +94,7 @@ gfx::AcceleratedWidget widget_; std::unique_ptr<ui::PlatformWindow> platform_window_; gfx::NativeCursor current_cursor_; - gfx::Rect bounds_; + gfx::Rect bounds_in_pixels_; std::unique_ptr<ui::KeyboardHook> keyboard_hook_;
diff --git a/ui/chromeos/search_box/search_box_view_base.cc b/ui/chromeos/search_box/search_box_view_base.cc index 6223d89..0c828429 100644 --- a/ui/chromeos/search_box/search_box_view_base.cc +++ b/ui/chromeos/search_box/search_box_view_base.cc
@@ -23,7 +23,6 @@ #include "ui/views/animation/ink_drop_highlight.h" #include "ui/views/animation/ink_drop_impl.h" #include "ui/views/animation/ink_drop_mask.h" -#include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/context_menu_controller.h" #include "ui/views/controls/button/image_button.h" @@ -56,15 +55,17 @@ } // namespace -// A background that paints a solid white rounded rect with a thin grey border. +// A background that paints a solid white rounded rect with a thin grey +// border. class SearchBoxBackground : public views::Background { public: SearchBoxBackground(int corner_radius, SkColor color) - : corner_radius_(corner_radius), color_(color) {} + : corner_radius_(corner_radius) { + SetNativeControlColor(color); + } ~SearchBoxBackground() override {} void set_corner_radius(int corner_radius) { corner_radius_ = corner_radius; } - void set_color(SkColor color) { color_ = color; } private: // views::Background overrides: @@ -73,12 +74,11 @@ cc::PaintFlags flags; flags.setAntiAlias(true); - flags.setColor(color_); + flags.setColor(get_color()); canvas->DrawRoundRect(bounds, corner_radius_, flags); } int corner_radius_; - SkColor color_; DISALLOW_COPY_AND_ASSIGN(SearchBoxBackground); }; @@ -248,7 +248,7 @@ AddChildView(content_container_); content_container_->SetBackground(std::make_unique<SearchBoxBackground>( - kSearchBoxBorderCornerRadius, background_color_)); + kSearchBoxBorderCornerRadius, kSearchBoxBackgroundDefault)); box_layout_ = content_container_->SetLayoutManager(std::make_unique<views::BoxLayout>( @@ -343,7 +343,7 @@ is_search_box_active_ = active; UpdateSearchIcon(); - UpdateBackgroundColor(background_color_); + UpdateBackgroundColor(kSearchBoxBackgroundDefault); search_box_->set_placeholder_text_draw_flags( active ? (base::i18n::IsRTL() ? gfx::Canvas::TEXT_ALIGN_RIGHT : gfx::Canvas::TEXT_ALIGN_LEFT) @@ -472,14 +472,6 @@ delegate_->ActiveChanged(this); } -// TODO(crbug.com/755219): Unify this with UpdateBackgroundColor. -void SearchBoxViewBase::SetBackgroundColor(SkColor light_vibrant) { - background_color_ = - (light_vibrant == SK_ColorTRANSPARENT) - ? kSearchBoxBackgroundDefault - : color_utils::AlphaBlend(SK_ColorWHITE, light_vibrant, 0.9f); -} - void SearchBoxViewBase::SetSearchBoxColor(SkColor color) { search_box_color_ = SK_ColorTRANSPARENT == color ? kDefaultSearchboxColor : color; @@ -533,11 +525,8 @@ } void SearchBoxViewBase::SetSearchBoxBackgroundCornerRadius(int corner_radius) { - GetSearchBoxBackground()->set_corner_radius(corner_radius); -} - -void SearchBoxViewBase::SetSearchBoxBackgroundColor(SkColor color) { - GetSearchBoxBackground()->set_color(color); + static_cast<SearchBoxBackground*>(GetSearchBoxBackground()) + ->set_corner_radius(corner_radius); } void SearchBoxViewBase::SetSearchIconImage(gfx::ImageSkia image) { @@ -570,11 +559,11 @@ void SearchBoxViewBase::UpdateBackgroundColor(SkColor color) { if (is_search_box_active_) color = kSearchBoxBackgroundDefault; - GetSearchBoxBackground()->set_color(color); + GetSearchBoxBackground()->SetNativeControlColor(color); } -SearchBoxBackground* SearchBoxViewBase::GetSearchBoxBackground() const { - return static_cast<SearchBoxBackground*>(content_container_->background()); +views::Background* SearchBoxViewBase::GetSearchBoxBackground() { + return content_container_->background(); } } // namespace search_box
diff --git a/ui/chromeos/search_box/search_box_view_base.h b/ui/chromeos/search_box/search_box_view_base.h index d01a1ae..e4d77a11 100644 --- a/ui/chromeos/search_box/search_box_view_base.h +++ b/ui/chromeos/search_box/search_box_view_base.h
@@ -12,6 +12,7 @@ #include "ui/chromeos/search_box/search_box_constants.h" #include "ui/chromeos/search_box/search_box_export.h" #include "ui/events/event_constants.h" +#include "ui/views/background.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/widget/widget_delegate.h" @@ -30,7 +31,6 @@ namespace search_box { class SearchBoxViewDelegate; -class SearchBoxBackground; class SearchBoxImageButton; // These are used in histograms, do not remove/renumber entries. If you're @@ -133,10 +133,6 @@ // Nofifies the active status change. void NotifyActiveChanged(); - // Sets the background color. - void SetBackgroundColor(SkColor light_vibrant); - SkColor background_color() const { return background_color_; } - // Sets the search box color. void SetSearchBoxColor(SkColor color); SkColor search_box_color() const { return search_box_color_; } @@ -160,7 +156,6 @@ bool is_tablet_mode() const { return is_tablet_mode_; } void SetSearchBoxBackgroundCornerRadius(int corner_radius); - void SetSearchBoxBackgroundColor(SkColor color); void SetSearchIconImage(gfx::ImageSkia image); @@ -173,6 +168,9 @@ // Updates the search box's background color. virtual void UpdateBackgroundColor(SkColor color); + // Gets the search box background. + views::Background* GetSearchBoxBackground(); + private: virtual void ModelChanged() = 0; @@ -196,9 +194,6 @@ // Records in histograms the activation of the searchbox. virtual void RecordSearchBoxActivationHistogram(ui::EventType event_type) {} - // Gets the search box background. - SearchBoxBackground* GetSearchBoxBackground() const; - SearchBoxViewDelegate* delegate_; // Not owned. // Owned by views hierarchy. @@ -221,8 +216,6 @@ bool show_assistant_button_ = false; // Whether tablet mode is active. bool is_tablet_mode_ = false; - // The current background color. - SkColor background_color_ = kSearchBoxBackgroundDefault; // The current search box color. SkColor search_box_color_ = kDefaultSearchboxColor;
diff --git a/ui/events/ozone/evdev/event_device_info.cc b/ui/events/ozone/evdev/event_device_info.cc index 4a001a7..fd279b18 100644 --- a/ui/events/ozone/evdev/event_device_info.cc +++ b/ui/events/ozone/evdev/event_device_info.cc
@@ -118,6 +118,24 @@ memset(&dst[src_len], 0, (dst_len - src_len) * sizeof(unsigned long)); } +bool IsBlacklistedAbsoluteMouseDevice(const input_id& id) { + static constexpr struct { + uint16_t vid; + uint16_t pid; + } kUSBLegacyBlackListedDevices[] = { + {0x222a, 0x0001}, // ILITEK ILITEK-TP + }; + + for (size_t i = 0; i < base::size(kUSBLegacyBlackListedDevices); ++i) { + if (id.vendor == kUSBLegacyBlackListedDevices[i].vid && + id.product == kUSBLegacyBlackListedDevices[i].pid) { + return true; + } + } + + return false; +} + } // namespace EventDeviceInfo::EventDeviceInfo() { @@ -506,7 +524,8 @@ return LegacyAbsoluteDeviceType::TOUCHSCREEN; // ABS_Z mitigation for extra device on some Elo devices. - if (HasKeyEvent(BTN_LEFT) && !HasAbsEvent(ABS_Z)) + if (HasKeyEvent(BTN_LEFT) && !HasAbsEvent(ABS_Z) && + !IsBlacklistedAbsoluteMouseDevice(input_id_)) return LegacyAbsoluteDeviceType::TOUCHSCREEN; return LegacyAbsoluteDeviceType::NONE;
diff --git a/ui/events/ozone/evdev/event_device_info_unittest.cc b/ui/events/ozone/evdev/event_device_info_unittest.cc index 4248eec..3e7c081 100644 --- a/ui/events/ozone/evdev/event_device_info_unittest.cc +++ b/ui/events/ozone/evdev/event_device_info_unittest.cc
@@ -225,4 +225,32 @@ EXPECT_EQ(ui::InputDeviceType::INPUT_DEVICE_INTERNAL, devinfo.device_type()); } +TEST(EventDeviceInfoTest, IllitekTP_Mouse) { + EventDeviceInfo devinfo; + EXPECT_TRUE(CapabilitiesToDeviceInfo(kIlitekTP_Mouse, &devinfo)); + + EXPECT_FALSE(devinfo.HasKeyboard()); + EXPECT_FALSE(devinfo.HasMouse()); + EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_FALSE(devinfo.HasTouchscreen()); + EXPECT_FALSE(devinfo.HasTablet()); + EXPECT_FALSE(devinfo.HasGamepad()); + + EXPECT_EQ(ui::InputDeviceType::INPUT_DEVICE_USB, devinfo.device_type()); +} + +TEST(EventDeviceInfoTest, IllitekTP) { + EventDeviceInfo devinfo; + EXPECT_TRUE(CapabilitiesToDeviceInfo(kIlitekTP, &devinfo)); + + EXPECT_FALSE(devinfo.HasKeyboard()); + EXPECT_FALSE(devinfo.HasMouse()); + EXPECT_FALSE(devinfo.HasTouchpad()); + EXPECT_TRUE(devinfo.HasTouchscreen()); + EXPECT_FALSE(devinfo.HasTablet()); + EXPECT_FALSE(devinfo.HasGamepad()); + + EXPECT_EQ(ui::InputDeviceType::INPUT_DEVICE_USB, devinfo.device_type()); +} + } // namespace ui
diff --git a/ui/events/ozone/evdev/event_device_test_util.cc b/ui/events/ozone/evdev/event_device_test_util.cc index 1172b98..e652ea7 100644 --- a/ui/events/ozone/evdev/event_device_test_util.cc +++ b/ui/events/ozone/evdev/event_device_test_util.cc
@@ -700,6 +700,66 @@ base::size(kHammerTouchpadAbsAxes), }; +// Captured from Logitech Tap touch controller +const DeviceAbsoluteAxis kIlitekTP_Mouse_AbsAxes[] = { + {ABS_X, {0, 0, 16384, 0, 0, 76}}, + {ABS_Y, {0, 0, 9600, 0, 0, 71}}, +}; +const DeviceCapabilities kIlitekTP_Mouse = { + /* path */ + "/sys/devices/pci0000:00/0000:00:14.0/usb1/1-2/1-2.1/1-2.1.1/1-2.1.1.4/" + "1-2.1.1.4.2/1-2.1.1.4.2:1.1/0003:222A:0001.0015/input/input19/event9", + /* name */ "ILITEK ILITEK-TP", + /* phys */ "usb-0000:00:14.0-2.1.1.4.2/input1", + /* uniq */ "", + /* bustype */ "0003", + /* vendor */ "222a", + /* product */ "0001", + /* version */ "0110", + /* prop */ "0", + /* ev */ "1b", + /* key */ "1f0000 0 0 0 0", + /* rel */ "0", + /* abs */ "3", + /* msc */ "10", + /* sw */ "0", + /* led */ "0", + /* ff */ "0", + kIlitekTP_Mouse_AbsAxes, + base::size(kIlitekTP_Mouse_AbsAxes), +}; +const DeviceAbsoluteAxis kIlitekTPAbsAxes[] = { + {ABS_X, {0, 0, 16384, 0, 0, 76}}, + {ABS_Y, {0, 0, 9600, 0, 0, 71}}, + {ABS_MT_SLOT, {0, 0, 9, 0, 0, 0}}, + {ABS_MT_POSITION_X, {0, 0, 16384, 0, 0, 76}}, + {ABS_MT_POSITION_Y, {0, 0, 9600, 0, 0, 71}}, + {ABS_MT_TRACKING_ID, {0, 0, 65535, 0, 0, 0}}, +}; +const DeviceCapabilities kIlitekTP = { + /* path */ + "/sys/devices/pci0000:00/0000:00:14.0/usb1/1-2/1-2.1/1-2.1.1/1-2.1.1.4/" + "1-2.1.1.4.2/1-2.1.1.4.2:1.0/0003:222A:0001.0014/input/input18/event8", + /* name */ "ILITEK ILITEK-TP", + /* phys */ "usb-0000:00:14.0-2.1.1.4.2/input0", + /* uniq */ "", + /* bustype */ "0003", + /* vendor */ "222a", + /* product */ "0001", + /* version */ "0110", + /* prop */ "2", + /* ev */ "1b", + /* key */ "400 0 0 0 0 0", + /* rel */ "0", + /* abs */ "260800000000003", + /* msc */ "20", + /* sw */ "0", + /* led */ "0", + /* ff */ "0", + kIlitekTPAbsAxes, + base::size(kIlitekTPAbsAxes), +}; + // NB: Please use the capture_device_capabilities.py script to add more // test data here. This will help ensure the data matches what the kernel // reports for a real device and is entered correctly.
diff --git a/ui/events/ozone/evdev/event_device_test_util.h b/ui/events/ozone/evdev/event_device_test_util.h index 00eb347..533690f 100644 --- a/ui/events/ozone/evdev/event_device_test_util.h +++ b/ui/events/ozone/evdev/event_device_test_util.h
@@ -79,6 +79,8 @@ extern const DeviceCapabilities kEveStylus; extern const DeviceCapabilities kHammerKeyboard; extern const DeviceCapabilities kHammerTouchpad; +extern const DeviceCapabilities kIlitekTP_Mouse; +extern const DeviceCapabilities kIlitekTP; } // namspace ui
diff --git a/ui/file_manager/audio_player/audio_player.html b/ui/file_manager/audio_player/audio_player.html index 42fa94df..2fdd823 100644 --- a/ui/file_manager/audio_player/audio_player.html +++ b/ui/file_manager/audio_player/audio_player.html
@@ -11,6 +11,7 @@ -- string. Until then, use an invisible non-whitespace character. --> <title></title> + <script src="chrome://resources/polymer/v1_0/html-imports/html-imports.min.js"></script> <link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> <link rel="stylesheet" type="text/css" href="css/audio_player.css">
diff --git a/ui/file_manager/audio_player/js/audio_player.js b/ui/file_manager/audio_player/js/audio_player.js index ef7b2fa..5e23cd7 100644 --- a/ui/file_manager/audio_player/js/audio_player.js +++ b/ui/file_manager/audio_player/js/audio_player.js
@@ -686,7 +686,7 @@ * initializeAudioPlayer: loads the audio player. */ function initializeAudioPlayer() { - AudioPlayer.load(); + window.HTMLImports.whenReady(AudioPlayer.load); } if (document.readyState === 'loading') {
diff --git a/ui/file_manager/audio_player/manifest.json b/ui/file_manager/audio_player/manifest.json index a2f01eaa..0fd230e 100644 --- a/ui/file_manager/audio_player/manifest.json +++ b/ui/file_manager/audio_player/manifest.json
@@ -61,7 +61,7 @@ }, // enhhojjnijigcajfphajepfemndkmdlo is the Dev Media Router component extension ID. // pkedcjkdefgpdelpbcmbmeomcjbeemfm is the Stable Media Router component extension ID. - "content_security_policy": "default-src 'none'; script-src 'self' blob: filesystem: chrome://resources chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj chrome-extension://enhhojjnijigcajfphajepfemndkmdlo chrome-extension://pkedcjkdefgpdelpbcmbmeomcjbeemfm; style-src 'self' blob: filesystem: chrome://resources 'unsafe-inline'; img-src 'self' blob: filesystem: chrome://theme chrome://resources data: https://www.googledrive.com; media-src 'self' blob: filesystem:; object-src 'self' blob: filesystem:; font-src chrome://resources;" + "content_security_policy": "default-src 'none'; script-src 'self' blob: filesystem: chrome://resources chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj chrome-extension://enhhojjnijigcajfphajepfemndkmdlo chrome-extension://pkedcjkdefgpdelpbcmbmeomcjbeemfm; style-src 'self' blob: filesystem: chrome://resources 'unsafe-inline'; img-src 'self' blob: filesystem: chrome://theme chrome://resources data: https://www.googledrive.com; media-src 'self' blob: filesystem:; connect-src chrome://resources ; object-src 'self' blob: filesystem:; font-src chrome://resources;" } }
diff --git a/ui/file_manager/externs/app_window_common.js b/ui/file_manager/externs/app_window_common.js index 84bbdcd13..70073025 100644 --- a/ui/file_manager/externs/app_window_common.js +++ b/ui/file_manager/externs/app_window_common.js
@@ -18,3 +18,15 @@ * @type {function()} */ Window.prototype.reload = function() {}; + +/** + * + * Created by HTML imports polyfill. + * @type {!Object} + */ +Window.prototype.HTMLImports; + +/** + * @type {function(function())} + */ +Window.prototype.HTMLImports.whenReady;
diff --git a/ui/file_manager/file_manager/background/js/volume_manager_impl.js b/ui/file_manager/file_manager/background/js/volume_manager_impl.js index 832e6cf..ef34c84a 100644 --- a/ui/file_manager/file_manager/background/js/volume_manager_impl.js +++ b/ui/file_manager/file_manager/background/js/volume_manager_impl.js
@@ -130,9 +130,9 @@ VolumeManagerImpl.prototype.initialize_ = function(callback) { chrome.fileManagerPrivate.onMountCompleted.addListener( this.onMountCompleted_.bind(this)); - console.debug('Requesting volume list.'); + console.warn('Requesting volume list.'); chrome.fileManagerPrivate.getVolumeMetadataList(volumeMetadataList => { - console.debug( + console.warn( 'Volume list fetched with: ' + volumeMetadataList.length + ' items.'); // We must subscribe to the mount completed event in the callback of // getVolumeMetadataList. crbug.com/330061. @@ -142,15 +142,15 @@ // Create VolumeInfo for each volume. Promise.all( volumeMetadataList.map(volumeMetadata => { - console.debug( + console.warn( 'Initializing volume: ' + volumeMetadata.volumeId); return this.addVolumeMetadata_(volumeMetadata).then( volumeInfo => { - console.debug('Initialized volume: ' + volumeInfo.volumeId); + console.warn('Initialized volume: ' + volumeInfo.volumeId); }); })) .then(() => { - console.debug('Initialized all volumes.'); + console.warn('Initialized all volumes.'); // Call the callback of the initialize function. callback(); // Call the callback of AsyncQueue. Maybe it invokes callbacks @@ -219,7 +219,7 @@ if (event.status === 'success') { this.volumeInfoList.remove(event.volumeMetadata.volumeId); } - console.debug('unmounted volume: ' + volumeId); + console.warn('unmounted volume: ' + volumeId); callback(); break; }
diff --git a/ui/file_manager/file_manager/background/js/volume_manager_util.js b/ui/file_manager/file_manager/background/js/volume_manager_util.js index d2d8b41..9f317f9c 100644 --- a/ui/file_manager/file_manager/background/js/volume_manager_util.js +++ b/ui/file_manager/file_manager/background/js/volume_manager_util.js
@@ -97,7 +97,7 @@ break; } - console.debug( + console.warn( 'Requesting file system: ' + volumeMetadata.volumeType + ' ' + volumeMetadata.volumeId); return util @@ -145,7 +145,7 @@ .then( /** @param {!FileSystem} fileSystem */ fileSystem => { - console.debug('File system obtained: ' + volumeMetadata.volumeId); + console.warn('File system obtained: ' + volumeMetadata.volumeId); if (volumeMetadata.volumeType === VolumeManagerCommon.VolumeType.DRIVE) { // After file system is mounted, we "read" drive grand root
diff --git a/ui/file_manager/file_manager/common/js/util.js b/ui/file_manager/file_manager/common/js/util.js index 7051f96..eb44f0c7 100644 --- a/ui/file_manager/file_manager/common/js/util.js +++ b/ui/file_manager/file_manager/common/js/util.js
@@ -1502,3 +1502,33 @@ return loadTimeData.valueExists('MY_FILES_VOLUME_ENABLED') && loadTimeData.getBoolean('MY_FILES_VOLUME_ENABLED'); }; + +/** + * Used for logs and debugging. It tries to tell what type is the entry, its + * path and URL. + * + * @param {Entry|FilesAppEntry} entry + * @return {string} + */ +util.entryDebugString = (entry) => { + if (entry === null) { + return 'entry is null'; + } + if (entry === undefined) { + return 'entry is undefined'; + } + let typeName = ''; + if (entry.constructor && entry.constructor.name) { + typeName = entry.constructor.name; + } else { + typeName = Object.prototype.toString.call(entry); + } + let entryDescription = '(' + typeName + ') '; + if (entry.fullPath) { + entryDescription = entryDescription + entry.fullPath + ' '; + } + if (entry.toURL) { + entryDescription = entryDescription + entry.toURL(); + } + return entryDescription; +};
diff --git a/ui/file_manager/file_manager/common/js/util_unittest.js b/ui/file_manager/file_manager/common/js/util_unittest.js index 881ea99..968a236 100644 --- a/ui/file_manager/file_manager/common/js/util_unittest.js +++ b/ui/file_manager/file_manager/common/js/util_unittest.js
@@ -124,3 +124,58 @@ assertTrue(util.isDescendantEntry(volumeEntry, fakeEntry)); assertTrue(util.isDescendantEntry(volumeEntry, folder1)); } + +/** + * Tests that it doesn't fail with different types of entries and inputs. + */ +function testEntryDebugString() { + // Check static values. + assertEquals('entry is null', util.entryDebugString(null)); + (/** + * @suppress {checkTypes} Closure doesn't allow passing undefined or {} due + * to type constraints nor casting to {Entry}. + */ + function() { + assertEquals('entry is undefined', util.entryDebugString(undefined)); + assertEquals('(Object) ', util.entryDebugString({})); + })(); + + // Construct some types of entries. + const root = fileSystem.root; + const folder = fileSystem.entries['/dir_a']; + const file = fileSystem.entries['/file_a.txt']; + const fakeEntry = + new FakeEntry('fake-entry-label', VolumeManagerCommon.RootType.CROSTINI); + const entryList = + new EntryList('entry-list-label', VolumeManagerCommon.RootType.MY_FILES); + entryList.addEntry(fakeEntry); + const volumeManager = new MockVolumeManager(); + // Index 1 is Downloads. + assertEquals( + VolumeManagerCommon.VolumeType.DOWNLOADS, + volumeManager.volumeInfoList.item(1).volumeType); + const downloadsVolumeInfo = volumeManager.volumeInfoList.item(1); + const mockFs = /** @type {MockFileSystem} */ (downloadsVolumeInfo.fileSystem); + mockFs.populate(['/folder1/']); + const volumeEntry = new VolumeEntry(downloadsVolumeInfo); + volumeEntry.addEntry(fakeEntry); + + // Mocked values are identified as Object instead of DirectoryEntry and + // FileEntry. + assertEquals( + '(Object) / filesystem:fake-volume/', util.entryDebugString(root)); + assertEquals( + '(Object) /dir_a filesystem:fake-volume/dir_a', + util.entryDebugString(folder)); + assertEquals( + '(Object) /file_a.txt filesystem:fake-volume/file_a.txt', + util.entryDebugString(file)); + // FilesAppEntry types: + assertEquals( + '(FakeEntry) fake-entry://crostini', util.entryDebugString(fakeEntry)); + assertEquals( + '(EntryList) entry-list://my_files', util.entryDebugString(entryList)); + assertEquals( + '(VolumeEntry) / filesystem:downloads/', + util.entryDebugString(volumeEntry)); +}
diff --git a/ui/file_manager/file_manager/foreground/js/file_manager.js b/ui/file_manager/file_manager/foreground/js/file_manager.js index 3a606d5e..4f0a076 100644 --- a/ui/file_manager/file_manager/foreground/js/file_manager.js +++ b/ui/file_manager/file_manager/foreground/js/file_manager.js
@@ -684,6 +684,7 @@ this.enableTouchMode_ = true; } }.bind(this)); + console.warn('Files app sync startup finished.'); }; /** @@ -842,6 +843,7 @@ FileManager.prototype.initGeneral_ = function() { // Initialize the application state. // TODO(mtomasz): Unify window.appState with location.search format. + console.warn('Files app starting up.'); if (window.appState) { var params = {}; for (var name in window.appState) { @@ -1477,14 +1479,20 @@ directoryEntry, opt_selectionEntry, opt_suggestedName) { // Open the directory, and select the selection (if passed). if (directoryEntry) { + const entryDescription = util.entryDebugString(directoryEntry); + console.warn( + 'Files app start up: changing to directory: ' + entryDescription); this.directoryModel_.changeDirectoryEntry(directoryEntry, function() { if (opt_selectionEntry) { this.directoryModel_.selectEntry(opt_selectionEntry); } - + console.warn( + 'Files app start up: finished changing to directory: ' + + entryDescription); this.ui_.addLoadedAttribute(); }.bind(this)); } else { + console.warn('No entry for finishSetupCurrentDirectory_'); this.ui_.addLoadedAttribute(); }
diff --git a/ui/file_manager/file_manager/foreground/js/file_tasks.js b/ui/file_manager/file_manager/foreground/js/file_tasks.js index ebe4fb7..f6c4466b 100644 --- a/ui/file_manager/file_manager/foreground/js/file_tasks.js +++ b/ui/file_manager/file_manager/foreground/js/file_tasks.js
@@ -687,10 +687,9 @@ 'Error sharing with linux to execute: ' + chrome.runtime.lastError.message); } - // Register paths as shared, and now we are ready to execute. - entriesToShare.forEach((entry) => { - this.crostini_.registerSharedPath(entry); - }); + // crbug.com/925973. Do not register non-persisted shared paths since + // we can't be sure at any time that the VM has not restarted and they + // are still shared. callback(); }); };
diff --git a/ui/file_manager/file_manager/foreground/js/file_tasks_unittest.js b/ui/file_manager/file_manager/foreground/js/file_tasks_unittest.js index 78e0a05c..64ae458 100644 --- a/ui/file_manager/file_manager/foreground/js/file_tasks_unittest.js +++ b/ui/file_manager/file_manager/foreground/js/file_tasks_unittest.js
@@ -636,6 +636,8 @@ expect( '2 entries, not shared, same dir', [notShared1, notShared2], true, '', ''); + // Non-persistent shares should not be registered. + assertFalse(crostini.isPathShared(notShared1)); expect( '2 entries, not shared, different dir', [notShared1, otherNotShared],
diff --git a/ui/file_manager/file_manager/foreground/js/ui/multi_menu.js b/ui/file_manager/file_manager/foreground/js/ui/multi_menu.js index 31ea25d..5e61827 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/multi_menu.js +++ b/ui/file_manager/file_manager/foreground/js/ui/multi_menu.js
@@ -130,9 +130,13 @@ style.top = itemRect.top + 'px'; // Size the subMenu to fit inside the height of the viewport const menuEndGap = 18; // padding on cr.menu + 2px + // Always set the maximum height so that expanding the window + // allows the menu height to grow crbug/934207 + style.maxHeight = (viewportHeight - itemRect.top - menuEndGap) + 'px'; if ((itemRect.top + childRect.height + menuEndGap) > viewportHeight) { - style.maxHeight = (viewportHeight - itemRect.top - menuEndGap) + 'px'; style.overflowY = 'scroll'; + } else { + style.overflowY = 'auto'; } },
diff --git a/ui/file_manager/file_manager/foreground/js/ui/multi_menu_unittest.js b/ui/file_manager/file_manager/foreground/js/ui/multi_menu_unittest.js index e14c804..c4b7033a 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/multi_menu_unittest.js +++ b/ui/file_manager/file_manager/foreground/js/ui/multi_menu_unittest.js
@@ -20,11 +20,13 @@ '<style>', ' cr-menu {', ' position: fixed;', + ' padding: 8px;', ' }', ' cr-menu-item {', ' width: 10px;', ' height: 10px;', ' display: block;', + ' background-color: blue;', ' }', '</style>', '<command id="default-task">', @@ -40,6 +42,7 @@ '</cr-menu>', '<cr-menu id="sub-menu" hidden>', ' <cr-menu-item class="custom-appearance"></cr-menu-item>', + ' <cr-menu-item class="custom-appearance"></cr-menu-item>', '</cr-menu>', ].join(''); @@ -190,3 +193,43 @@ assertTrue(topMenu.hasAttribute('hidden')); assertTrue(subMenu.hasAttribute('hidden')); } + +/** + * Tests that shrinking the window height will limit + * the height of the sub-menu. + */ +function testShrinkWindowSizesSubMenu() { + testSelectHostMenuItemAndCallShowSubMenu(); + const subMenuPosition = subMenu.getBoundingClientRect(); + // Reduce window innerHeight so sub-menu won't fit. + window.innerHeight = subMenuPosition.bottom - 10; + // Call the internal hide method, then re-show it + // to force the resizing behavior. + menubutton.hideSubMenu_(); + menubutton.showSubMenu(); + const shrunkPosition = subMenu.getBoundingClientRect(); + assertTrue(shrunkPosition.bottom < window.innerHeight); +} + +/** + * Tests that growing the window height will increase + * the height of the sub-menu. + */ +function testGrowWindowSizesSubMenu() { + // Remember the full size of the sub-menu + testSelectHostMenuItemAndCallShowSubMenu(); + const subMenuPosition = subMenu.getBoundingClientRect(); + // Make sure the sub-menu has been reduced in height. + testShrinkWindowSizesSubMenu(); + // Make the window taller than the sub-menu plus padding. + window.innerHeight = subMenuPosition.bottom + 20; + // Call the internal hide method, then re-show it + // to force the resizing behavior. + menubutton.hideSubMenu_(); + menubutton.showSubMenu(); + const grownPosition = subMenu.getBoundingClientRect(); + // Test that the height of the sub-menu is the same as + // the height at the start of this test (before we + // deliberately shrank it). + assertTrue(grownPosition.bottom === subMenuPosition.bottom); +}
diff --git a/ui/file_manager/file_manager/main.html b/ui/file_manager/file_manager/main.html index 7afa79d56..6c5643f 100644 --- a/ui/file_manager/file_manager/main.html +++ b/ui/file_manager/file_manager/main.html
@@ -9,6 +9,7 @@ <title></title> <meta name="google" value="notranslate"> + <script src="chrome://resources/polymer/v1_0/html-imports/html-imports.min.js"></script> <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="stylesheet" href="chrome://resources/css/action_link.css">
diff --git a/ui/file_manager/file_manager/manifest.json b/ui/file_manager/file_manager/manifest.json index b0d01b9..3803ec0 100644 --- a/ui/file_manager/file_manager/manifest.json +++ b/ui/file_manager/file_manager/manifest.json
@@ -66,8 +66,7 @@ "default_title": "__MSG_MOUNT_ARCHIVE__", "default_icon": "common/images/file_types/200/archive.png", "file_filters": [ - "filesystem:*.rar", - "filesystem:*.zip" + "filesystem:*.rar" ] }, {
diff --git a/ui/file_manager/gallery/gallery.html b/ui/file_manager/gallery/gallery.html index c322dce..1c62b9b0 100644 --- a/ui/file_manager/gallery/gallery.html +++ b/ui/file_manager/gallery/gallery.html
@@ -5,6 +5,7 @@ --> <html i18n-values="dir:textdirection"> <head> + <script src="chrome://resources/polymer/v1_0/html-imports/html-imports.min.js"></script> <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> <link rel="stylesheet" href="../file_manager/foreground/css/list.css">
diff --git a/ui/file_manager/gallery/js/gallery.js b/ui/file_manager/gallery/js/gallery.js index 4e3cfb7..87129b9 100644 --- a/ui/file_manager/gallery/js/gallery.js +++ b/ui/file_manager/gallery/js/gallery.js
@@ -1094,7 +1094,10 @@ * it to create the gallery. Calls reload() to populate the gallery entries. */ function initializeGallery() { - const promise = Promise.resolve().then(() => { + const htmlImportsPromise = new Promise(resolve => { + window.HTMLImports.whenReady(resolve); + }); + const promise = htmlImportsPromise.then(() => { return Promise.all([loadTimeDataPromise, volumeManagerPromise]); });
diff --git a/ui/file_manager/gallery/manifest.json b/ui/file_manager/gallery/manifest.json index d252b193..975afec 100644 --- a/ui/file_manager/gallery/manifest.json +++ b/ui/file_manager/gallery/manifest.json
@@ -85,6 +85,6 @@ "js/background_scripts.js" ] }, - "content_security_policy": "default-src 'none'; script-src 'self' blob: filesystem: chrome://resources chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj; style-src 'self' blob: filesystem: chrome://resources 'unsafe-inline'; img-src 'self' blob: filesystem: chrome://resources chrome://theme data: https://*.googleusercontent.com chrome://extension-icon; media-src 'self' blob: filesystem:; object-src 'self' blob: filesystem:; font-src chrome://resources;" + "content_security_policy": "default-src 'none'; script-src 'self' blob: filesystem: chrome://resources chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj; style-src 'self' blob: filesystem: chrome://resources 'unsafe-inline'; img-src 'self' blob: filesystem: chrome://resources chrome://theme data: https://*.googleusercontent.com chrome://extension-icon; media-src 'self' blob: filesystem:; connect-src chrome://resources ; object-src 'self' blob: filesystem:; font-src chrome://resources; " } }
diff --git a/ui/gfx/animation/tween.cc b/ui/gfx/animation/tween.cc index 7fb952fa1..917fe0e 100644 --- a/ui/gfx/animation/tween.cc +++ b/ui/gfx/animation/tween.cc
@@ -188,6 +188,18 @@ } // static +gfx::RectF Tween::RectFValueBetween(double value, + const gfx::RectF& start, + const gfx::RectF& target) { + const float x = FloatValueBetween(value, start.x(), target.x()); + const float y = FloatValueBetween(value, start.y(), target.y()); + const float right = FloatValueBetween(value, start.right(), target.right()); + const float bottom = + FloatValueBetween(value, start.bottom(), target.bottom()); + return gfx::RectF(x, y, right - x, bottom - y); +} + +// static gfx::Transform Tween::TransformValueBetween(double value, const gfx::Transform& start, const gfx::Transform& target) {
diff --git a/ui/gfx/animation/tween.h b/ui/gfx/animation/tween.h index 90cd45a..5d26786a 100644 --- a/ui/gfx/animation/tween.h +++ b/ui/gfx/animation/tween.h
@@ -9,6 +9,7 @@ #include "third_party/skia/include/core/SkColor.h" #include "ui/gfx/animation/animation_export.h" #include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/geometry/size_f.h" #include "ui/gfx/transform.h" @@ -73,6 +74,10 @@ const gfx::Rect& start, const gfx::Rect& target); + static gfx::RectF RectFValueBetween(double value, + const gfx::RectF& start, + const gfx::RectF& target); + static gfx::Transform TransformValueBetween(double value, const gfx::Transform& start, const gfx::Transform& target);
diff --git a/ui/gl/gl_image_native_pixmap.cc b/ui/gl/gl_image_native_pixmap.cc index 0bae74d4..7f47f8c 100644 --- a/ui/gl/gl_image_native_pixmap.cc +++ b/ui/gl/gl_image_native_pixmap.cc
@@ -150,7 +150,7 @@ GLImageNativePixmap::~GLImageNativePixmap() {} -bool GLImageNativePixmap::Initialize(gfx::NativePixmap* pixmap) { +bool GLImageNativePixmap::Initialize(scoped_refptr<gfx::NativePixmap> pixmap) { DCHECK(!pixmap_); if (GetInternalFormatFromFormat(format_) == GL_NONE) { LOG(ERROR) << "Unsupported format: " << gfx::BufferFormatToString(format_);
diff --git a/ui/gl/gl_image_native_pixmap.h b/ui/gl/gl_image_native_pixmap.h index 93160a1..4e81a986 100644 --- a/ui/gl/gl_image_native_pixmap.h +++ b/ui/gl/gl_image_native_pixmap.h
@@ -20,7 +20,7 @@ GLImageNativePixmap(const gfx::Size& size, gfx::BufferFormat format); // Create an EGLImage from a given NativePixmap. - bool Initialize(gfx::NativePixmap* pixmap); + bool Initialize(scoped_refptr<gfx::NativePixmap> pixmap); // Create an EGLImage from a given GL texture. bool InitializeFromTexture(uint32_t texture_id); // Export the wrapped EGLImage to dmabuf fds.
diff --git a/ui/keyboard/public/keyboard_switches.cc b/ui/keyboard/public/keyboard_switches.cc index 261acac..64cc2d3d 100644 --- a/ui/keyboard/public/keyboard_switches.cc +++ b/ui/keyboard/public/keyboard_switches.cc
@@ -7,7 +7,6 @@ namespace keyboard { namespace switches { -const char kDisableInputView[] = "disable-input-view"; const char kDisableVoiceInput[] = "disable-voice-input"; const char kDisableGestureTyping[] = "disable-gesture-typing"; const char kEnableVirtualKeyboard[] = "enable-virtual-keyboard";
diff --git a/ui/keyboard/public/keyboard_switches.h b/ui/keyboard/public/keyboard_switches.h index a2ac6b7..d5944e7 100644 --- a/ui/keyboard/public/keyboard_switches.h +++ b/ui/keyboard/public/keyboard_switches.h
@@ -10,10 +10,6 @@ namespace keyboard { namespace switches { -// Disables IME extension APIs from overriding the URL for specifying the -// contents of the virtual keyboard container. -KEYBOARD_EXPORT extern const char kDisableInputView[]; - // Disables voice input. KEYBOARD_EXPORT extern const char kDisableVoiceInput[];
diff --git a/ui/ozone/demo/skia/skia_surfaceless_gl_renderer.cc b/ui/ozone/demo/skia/skia_surfaceless_gl_renderer.cc index 06a28aba..18f47f3 100644 --- a/ui/ozone/demo/skia/skia_surfaceless_gl_renderer.cc +++ b/ui/ozone/demo/skia/skia_surfaceless_gl_renderer.cc
@@ -115,7 +115,7 @@ ->GetSurfaceFactoryOzone() ->CreateNativePixmap(widget, size, format, gfx::BufferUsage::SCANOUT); auto image = base::MakeRefCounted<gl::GLImageNativePixmap>(size, format); - if (!image->Initialize(pixmap.get())) { + if (!image->Initialize(std::move(pixmap))) { LOG(ERROR) << "Failed to create GLImage"; return false; }
diff --git a/ui/ozone/demo/surfaceless_gl_renderer.cc b/ui/ozone/demo/surfaceless_gl_renderer.cc index 1da2211..0160057 100644 --- a/ui/ozone/demo/surfaceless_gl_renderer.cc +++ b/ui/ozone/demo/surfaceless_gl_renderer.cc
@@ -86,7 +86,7 @@ ->GetSurfaceFactoryOzone() ->CreateNativePixmap(widget, size, format, gfx::BufferUsage::SCANOUT); auto image = base::MakeRefCounted<gl::GLImageNativePixmap>(size, format); - if (!image->Initialize(pixmap.get())) { + if (!image->Initialize(std::move(pixmap))) { LOG(ERROR) << "Failed to create GLImage"; return false; }
diff --git a/ui/strings/ui_strings.grd b/ui/strings/ui_strings.grd index d540a664..40f1930 100644 --- a/ui/strings/ui_strings.grd +++ b/ui/strings/ui_strings.grd
@@ -901,6 +901,9 @@ <message name="IDS_SATURATED_BADGE_CONTENT" desc="The content to display when the application's badge is too large to display to indicate that the badge is more than a given maximum. This string should be as short as possible, preferably only one character beyond the content"> <ph name="MAXIMUM_VALUE">$1<ex>99</ex></ph>+ </message> + <message name="IDS_BADGE_UNREAD_NOTIFICATIONS_SATURATED" desc="The accessibility text which will be read by a screen reader when the notification count is too large to display (e.g. greater than 99)."> + {MAX_UNREAD_NOTIFICATIONS, plural, =1 {More than 1 unread notification} other {More than # unread notifications}} + </message> <message name="IDS_BADGE_UNREAD_NOTIFICATIONS_UNSPECIFIED" desc="The accessibility text which will be read by a screen reader when there are some unspecified number of notifications, or user attention is required"> Unread Notifications </message>
diff --git a/ui/webui/resources/cr_components/chromeos/multidevice_setup/BUILD.gn b/ui/webui/resources/cr_components/chromeos/multidevice_setup/BUILD.gn index f48ee398..6f2aa215 100644 --- a/ui/webui/resources/cr_components/chromeos/multidevice_setup/BUILD.gn +++ b/ui/webui/resources/cr_components/chromeos/multidevice_setup/BUILD.gn
@@ -26,14 +26,14 @@ js_library("fake_mojo_service") { deps = [ - "//chromeos/services/multidevice_setup/public/mojom:mojom_js_externs", + "//chromeos/services/multidevice_setup/public/mojom:mojom_js_library_for_compile", "//ui/webui/resources/js:cr", ] } js_library("mojo_api") { deps = [ - "//chromeos/services/multidevice_setup/public/mojom:mojom_js_externs", + "//chromeos/services/multidevice_setup/public/mojom:mojom_js_library_for_compile", "//ui/webui/resources/js:cr", ] }
diff --git a/ui/webui/resources/cr_components/managed_footnote/managed_footnote.html b/ui/webui/resources/cr_components/managed_footnote/managed_footnote.html index 04b3e91..a6c7b2c 100644 --- a/ui/webui/resources/cr_components/managed_footnote/managed_footnote.html +++ b/ui/webui/resources/cr_components/managed_footnote/managed_footnote.html
@@ -41,7 +41,7 @@ <template is="dom-if" if="[[isManaged_]]"> <iron-icon icon="cr:domain"></iron-icon> - <div id="content" inner-h-t-m-l="[[message_]]"></div> + <div id="content" inner-h-t-m-l="[[i18nAdvanced('managedByOrg')]]"></div> </template> </template> <script src="managed_footnote.js"></script>
diff --git a/ui/webui/resources/cr_components/managed_footnote/managed_footnote.js b/ui/webui/resources/cr_components/managed_footnote/managed_footnote.js index 09ce1cf..80e9731 100644 --- a/ui/webui/resources/cr_components/managed_footnote/managed_footnote.js +++ b/ui/webui/resources/cr_components/managed_footnote/managed_footnote.js
@@ -12,12 +12,6 @@ */ (function() { -/** - * URL of the help article for the clickable link. - * @type {string} - */ -// TODO(nicolaso): Use a p-link instead, once it's available. b/117655761 -const HELP_ARTICLE_URL = 'https://support.google.com/chromebook/answer/1331549'; Polymer({ is: 'managed-footnote', @@ -37,26 +31,10 @@ return loadTimeData.getBoolean('isManaged'); }, }, - - /** - * Localized message to display in the footnote. May contain an <a> - * element. - * @private - */ - message_: String, }, /** @override */ ready: function() { - this.message_ = this.i18nAdvanced('managedByOrg', { - substitutions: [HELP_ARTICLE_URL], - tags: ['a'], - attrs: { - target: (node, v) => v === '_blank', - href: (node, v) => v === HELP_ARTICLE_URL, - }, - }); - cr.addWebUIListener('is-managed-changed', managed => { loadTimeData.overrideValues({isManaged: managed}); this.isManaged_ = managed; @@ -65,5 +43,4 @@ }); chrome.send('observeManagedUI'); - })();
diff --git a/ui/wm/core/coordinate_conversion.cc b/ui/wm/core/coordinate_conversion.cc index 17104b35..c73c03c 100644 --- a/ui/wm/core/coordinate_conversion.cc +++ b/ui/wm/core/coordinate_conversion.cc
@@ -6,6 +6,7 @@ #include "ui/aura/client/screen_position_client.h" #include "ui/gfx/geometry/point.h" +#include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/rect_f.h" @@ -21,6 +22,14 @@ ConvertPointToScreen(window, point); } +void ConvertPointToScreen(const aura::Window* window, gfx::PointF* point) { + DCHECK(window); + DCHECK(window->GetRootWindow()); + DCHECK(aura::client::GetScreenPositionClient(window->GetRootWindow())); + aura::client::GetScreenPositionClient(window->GetRootWindow()) + ->ConvertPointToScreen(window, point); +} + void ConvertPointFromScreen(const aura::Window* window, gfx::Point* point_in_screen) { DCHECK(window); @@ -30,12 +39,27 @@ ConvertPointFromScreen(window, point_in_screen); } +void ConvertPointFromScreen(const aura::Window* window, + gfx::PointF* point_in_screen) { + DCHECK(window); + DCHECK(window->GetRootWindow()); + DCHECK(aura::client::GetScreenPositionClient(window->GetRootWindow())); + aura::client::GetScreenPositionClient(window->GetRootWindow()) + ->ConvertPointFromScreen(window, point_in_screen); +} + void ConvertRectToScreen(const aura::Window* window, gfx::Rect* rect) { gfx::Point origin = rect->origin(); ConvertPointToScreen(window, &origin); rect->set_origin(origin); } +void TranslateRectToScreen(const aura::Window* window, gfx::RectF* rect) { + gfx::PointF origin = rect->origin(); + ConvertPointToScreen(window, &origin); + rect->set_origin(origin); +} + void ConvertRectFromScreen(const aura::Window* window, gfx::Rect* rect_in_screen) { gfx::Point origin = rect_in_screen->origin(); @@ -43,4 +67,10 @@ rect_in_screen->set_origin(origin); } +void TranslateRectFromScreen(const aura::Window* window, gfx::RectF* rect) { + gfx::PointF origin = rect->origin(); + ConvertPointFromScreen(window, &origin); + rect->set_origin(origin); +} + } // namespace wm
diff --git a/ui/wm/core/coordinate_conversion.h b/ui/wm/core/coordinate_conversion.h index 43bbe9c6..e719999d 100644 --- a/ui/wm/core/coordinate_conversion.h +++ b/ui/wm/core/coordinate_conversion.h
@@ -13,31 +13,48 @@ namespace gfx { class Point; +class PointF; class Rect; +class RectF; } // namespace gfx namespace wm { // Converts the |point| from a given |window|'s coordinates into the screen // coordinates. +// TODO: Remove the integer versions of these functions. See crbug.com/773331. WM_CORE_EXPORT void ConvertPointToScreen(const aura::Window* window, gfx::Point* point); +WM_CORE_EXPORT void ConvertPointToScreen(const aura::Window* window, + gfx::PointF* point); + // Converts the |point| from the screen coordinates to a given |window|'s // coordinates. WM_CORE_EXPORT void ConvertPointFromScreen(const aura::Window* window, gfx::Point* point_in_screen); +WM_CORE_EXPORT void ConvertPointFromScreen(const aura::Window* window, + gfx::PointF* point_in_screen); + // Converts |rect| from |window|'s coordinates to the virtual screen // coordinates. +// TODO: Change the Rect versions to TranslateRect(To|From)Screen since they +// do not handle size changes. WM_CORE_EXPORT void ConvertRectToScreen(const aura::Window* window, gfx::Rect* rect); +WM_CORE_EXPORT void TranslateRectToScreen(const aura::Window* window, + gfx::RectF* rect); + // Converts |rect| from virtual screen coordinates to the |window|'s // coordinates. WM_CORE_EXPORT void ConvertRectFromScreen(const aura::Window* window, gfx::Rect* rect_in_screen); +WM_CORE_EXPORT void TranslateRectFromScreen(const aura::Window* window, + gfx::RectF* rect_in_screen); + } // namespace wm #endif // UI_WM_CORE_COORDINATE_CONVERSION_H_
diff --git a/url/url_canon_stdstring.h b/url/url_canon_stdstring.h index f693bd08..fed2e79 100644 --- a/url/url_canon_stdstring.h +++ b/url/url_canon_stdstring.h
@@ -13,6 +13,7 @@ #include "base/compiler_specific.h" #include "base/component_export.h" +#include "base/macros.h" #include "base/strings/string_piece.h" #include "url/url_canon.h" @@ -45,6 +46,7 @@ protected: std::string* str_; + DISALLOW_COPY_AND_ASSIGN(StdStringCanonOutput); }; // An extension of the Replacements class that allows the setters to use