diff --git a/.gn b/.gn index eb2723b..44842c8 100644 --- a/.gn +++ b/.gn
@@ -146,7 +146,7 @@ "//third_party/libaddressinput/*", "//third_party/libphonenumber/*", "//third_party/libwebp/*", - "//third_party/WebKit/Source/*", + "//third_party/WebKit/*", "//tools/*", #"//ui/*", # Work left on Chromeos w/ use_ozone. Some parts of UI that work:
diff --git a/DEPS b/DEPS index bbc7a5d..37e0f28 100644 --- a/DEPS +++ b/DEPS
@@ -44,7 +44,7 @@ # 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': '3d4e62602948f3c76a26eb7a11e71333a2e9e889', + 'v8_revision': '1811f739ed4fdb5a90de6fb797cc6b6c333de3a9', # 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. @@ -64,7 +64,7 @@ # 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': '852fb12d554abbbda65bbbf3720117a0aad5a9c9', + 'pdfium_revision': '3ba6010b63a97271f23ed921a58dc9298d2e74ef', # 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.
diff --git a/android_webview/BUILD.gn b/android_webview/BUILD.gn index 233bd475..7ba1756 100644 --- a/android_webview/BUILD.gn +++ b/android_webview/BUILD.gn
@@ -36,6 +36,184 @@ } } +source_set("native") { + deps = [ + ":native_jni", + "//android_webview:generate_components_strings", + "//android_webview/common:version", + "//base", + "//base/third_party/dynamic_annotations:dynamic_annotations", + "//cc:cc", + "//components/autofill/content/browser:browser", + "//components/spellcheck:build_features", + "//components/web_contents_delegate_android:web_contents_delegate_android", + "//content/public/common", + "//media", + "//net", + "//skia", + "//storage/browser", + "//storage/common", + "//third_party/boringssl", + "//ui/base", + "//ui/gfx", + "//ui/gfx/geometry:geometry", + ] + + include_dirs = [ + "//skia/config", + "//third_party/protobuf", + ] + + sources = [ + "browser/address_parser.cc", + "browser/address_parser.h", + "browser/address_parser_internal.cc", + "browser/address_parser_internal.h", + "browser/android_protocol_handler.cc", + "browser/android_protocol_handler.h", + "browser/android_webview_jni_registrar.cc", + "browser/android_webview_jni_registrar.h", + "browser/aw_autofill_client.cc", + "browser/aw_autofill_client.h", + "browser/aw_contents.cc", + "browser/aw_contents.h", + "browser/aw_contents_background_thread_client.cc", + "browser/aw_contents_background_thread_client.h", + "browser/aw_contents_client_bridge.cc", + "browser/aw_contents_client_bridge.h", + "browser/aw_contents_io_thread_client_impl.cc", + "browser/aw_contents_io_thread_client_impl.h", + "browser/aw_contents_lifecycle_notifier.cc", + "browser/aw_contents_lifecycle_notifier.h", + "browser/aw_contents_statics.cc", + "browser/aw_contents_statics.h", + "browser/aw_debug.cc", + "browser/aw_debug.h", + "browser/aw_devtools_server.cc", + "browser/aw_devtools_server.h", + "browser/aw_form_database.cc", + "browser/aw_form_database.h", + "browser/aw_gl_functor.cc", + "browser/aw_gl_functor.h", + "browser/aw_http_auth_handler.cc", + "browser/aw_http_auth_handler.h", + "browser/aw_locale_manager_impl.cc", + "browser/aw_locale_manager_impl.h", + "browser/aw_media_url_interceptor.cc", + "browser/aw_media_url_interceptor.h", + "browser/aw_metrics_log_uploader.cc", + "browser/aw_metrics_log_uploader.h", + "browser/aw_metrics_service_client_impl.cc", + "browser/aw_metrics_service_client_impl.h", + "browser/aw_pdf_exporter.cc", + "browser/aw_pdf_exporter.h", + "browser/aw_picture.cc", + "browser/aw_picture.h", + "browser/aw_quota_manager_bridge_impl.cc", + "browser/aw_quota_manager_bridge_impl.h", + "browser/aw_renderer_priority_manager.cc", + "browser/aw_renderer_priority_manager.h", + "browser/aw_resource.cc", + "browser/aw_settings.cc", + "browser/aw_settings.h", + "browser/aw_web_contents_delegate.cc", + "browser/aw_web_contents_delegate.h", + "browser/aw_web_contents_view_delegate.cc", + "browser/aw_web_contents_view_delegate.h", + "browser/aw_web_preferences_populater_impl.cc", + "browser/aw_web_preferences_populater_impl.h", + "browser/aw_web_resource_response_impl.cc", + "browser/aw_web_resource_response_impl.h", + "browser/cookie_manager.cc", + "browser/cookie_manager.h", + "browser/input_stream_impl.cc", + "browser/input_stream_impl.h", + "browser/java_browser_view_renderer_helper.cc", + "browser/java_browser_view_renderer_helper.h", + "browser/net_init_native_callback.cc", + "browser/permission/aw_permission_request.cc", + "browser/permission/aw_permission_request.h", + "browser/permission/aw_permission_request_delegate.cc", + "browser/permission/aw_permission_request_delegate.h", + "browser/permission/media_access_permission_request.cc", + "browser/permission/media_access_permission_request.h", + "browser/permission/permission_request_handler.cc", + "browser/permission/permission_request_handler.h", + "browser/permission/permission_request_handler_client.cc", + "browser/permission/permission_request_handler_client.h", + "browser/permission/simple_permission_request.cc", + "browser/permission/simple_permission_request.h", + "browser/popup_touch_handle_drawable.cc", + "browser/popup_touch_handle_drawable.h", + "browser/state_serializer.cc", + "browser/state_serializer.h", + "browser/token_binding_manager_bridge.cc", + "browser/token_binding_manager_bridge.h", + ] + + if (enable_spellcheck) { + deps += [ "//components/spellcheck/browser:browser" ] + } + + libs = [ "jnigraphics" ] +} + +generate_jni("native_jni") { + sources = [ + "java/src/org/chromium/android_webview/AndroidProtocolHandler.java", + "java/src/org/chromium/android_webview/AwAutofillClient.java", + "java/src/org/chromium/android_webview/AwContents.java", + "java/src/org/chromium/android_webview/AwContentsBackgroundThreadClient.java", + "java/src/org/chromium/android_webview/AwContentsClientBridge.java", + "java/src/org/chromium/android_webview/AwContentsIoThreadClient.java", + "java/src/org/chromium/android_webview/AwContentsLifecycleNotifier.java", + "java/src/org/chromium/android_webview/AwContentsStatics.java", + "java/src/org/chromium/android_webview/AwCookieManager.java", + "java/src/org/chromium/android_webview/AwDebug.java", + "java/src/org/chromium/android_webview/AwDevToolsServer.java", + "java/src/org/chromium/android_webview/AwFormDatabase.java", + "java/src/org/chromium/android_webview/AwGLFunctor.java", + "java/src/org/chromium/android_webview/AwHttpAuthHandler.java", + "java/src/org/chromium/android_webview/AwMetricsLogUploader.java", + "java/src/org/chromium/android_webview/AwMetricsServiceClient.java", + "java/src/org/chromium/android_webview/AwPdfExporter.java", + "java/src/org/chromium/android_webview/AwPicture.java", + "java/src/org/chromium/android_webview/AwQuotaManagerBridge.java", + "java/src/org/chromium/android_webview/AwRendererPriorityManager.java", + "java/src/org/chromium/android_webview/AwResource.java", + "java/src/org/chromium/android_webview/AwSettings.java", + "java/src/org/chromium/android_webview/AwTokenBindingManager.java", + "java/src/org/chromium/android_webview/AwWebContentsDelegate.java", + "java/src/org/chromium/android_webview/AwWebResourceResponse.java", + "java/src/org/chromium/android_webview/InputStreamUtil.java", + "java/src/org/chromium/android_webview/JavaBrowserViewRendererHelper.java", + "java/src/org/chromium/android_webview/PopupTouchHandleDrawable.java", + "java/src/org/chromium/android_webview/permission/AwPermissionRequest.java", + ] + jni_package = "android_webview" + + deps = [ + ":cancellation_signal_android_jar_jni_headers", + ] +} + +generate_jar_jni("cancellation_signal_android_jar_jni_headers") { + classes = [ "android/os/CancellationSignal.class" ] + jni_package = "android_webview" +} + +java_cpp_enum("aw_permission_request_resource") { + sources = [ + "browser/permission/aw_permission_request.h", + ] +} + +java_cpp_enum("aw_renderer_priority_manager_renderer_priority") { + sources = [ + "browser/aw_renderer_priority_manager.h", + ] +} + jinja_template("system_webview_manifest") { input = "apk/java/AndroidManifest.xml" output = system_webview_android_manifest @@ -547,8 +725,8 @@ ":generate_aw_resources", ":generate_aw_strings", ":generate_components_strings", + ":native", "//android_webview/common:version", - "//android_webview/native:native", "//cc/surfaces", "//components/autofill/content/browser", "//components/autofill/content/renderer", @@ -711,8 +889,8 @@ } srcjar_deps = [ - "//android_webview/native:aw_permission_request_resource", - "//android_webview/native:aw_renderer_priority_manager_renderer_priority", + ":aw_permission_request_resource", + ":aw_renderer_priority_manager_renderer_priority", ] }
diff --git a/android_webview/browser/DEPS b/android_webview/browser/DEPS index 4bf7d52..da57d62 100644 --- a/android_webview/browser/DEPS +++ b/android_webview/browser/DEPS
@@ -3,7 +3,7 @@ "+android_webview/browser", "+android_webview/common", "+android_webview/grit", - "+android_webview/native/public", + "+android_webview/jni", "+android_webview/public/browser", "+cc", @@ -42,15 +42,18 @@ "+media/base/android", "+components/policy/policy_constants.h", + "+components/web_contents_delegate_android", "+printing", "+services/service_manager/public/cpp", "+storage/browser/quota", + "+storage/common/quota", "+ui/gfx", "+ui/gl", + "+ui/touch_selection/touch_handle.h", # Temporary until we bundle our own favicon. See # AwContentBrowserClient::GetDefaultFavicon
diff --git a/android_webview/native/address_parser.cc b/android_webview/browser/address_parser.cc similarity index 98% rename from android_webview/native/address_parser.cc rename to android_webview/browser/address_parser.cc index 62dc17f8..60395d9 100644 --- a/android_webview/native/address_parser.cc +++ b/android_webview/browser/address_parser.cc
@@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/native/address_parser.h" +#include "android_webview/browser/address_parser.h" -#include "android_webview/native/address_parser_internal.h" +#include "android_webview/browser/address_parser_internal.h" #include "base/logging.h" #include "base/strings/string_util.h"
diff --git a/android_webview/native/address_parser.h b/android_webview/browser/address_parser.h similarity index 87% rename from android_webview/native/address_parser.h rename to android_webview/browser/address_parser.h index 43fdc391..4ded8cf8 100644 --- a/android_webview/native/address_parser.h +++ b/android_webview/browser/address_parser.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_NATIVE_ADDRESS_PARSER_H_ -#define ANDROID_WEBVIEW_NATIVE_ADDRESS_PARSER_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_ADDRESS_PARSER_H_ +#define ANDROID_WEBVIEW_BROWSER_ADDRESS_PARSER_H_ #include <stddef.h> @@ -33,4 +33,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_ADDRESS_PARSER_H_ +#endif // ANDROID_WEBVIEW_BROWSER_ADDRESS_PARSER_H_
diff --git a/android_webview/native/address_parser_internal.cc b/android_webview/browser/address_parser_internal.cc similarity index 99% rename from android_webview/native/address_parser_internal.cc rename to android_webview/browser/address_parser_internal.cc index e053c46..3d3031a 100644 --- a/android_webview/native/address_parser_internal.cc +++ b/android_webview/browser/address_parser_internal.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/native/address_parser_internal.h" +#include "android_webview/browser/address_parser_internal.h" #include <bitset>
diff --git a/android_webview/native/address_parser_internal.h b/android_webview/browser/address_parser_internal.h similarity index 92% rename from android_webview/native/address_parser_internal.h rename to android_webview/browser/address_parser_internal.h index 8ed69171..82f6219 100644 --- a/android_webview/native/address_parser_internal.h +++ b/android_webview/browser/address_parser_internal.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_NATIVE_ADDRESS_PARSER_INTERNAL_H_ -#define ANDROID_WEBVIEW_NATIVE_ADDRESS_PARSER_INTERNAL_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_ADDRESS_PARSER_INTERNAL_H_ +#define ANDROID_WEBVIEW_BROWSER_ADDRESS_PARSER_INTERNAL_H_ #include <stddef.h> @@ -86,4 +86,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_ADDRESS_PARSER_INTERNAL_H_ +#endif // ANDROID_WEBVIEW_BROWSER_ADDRESS_PARSER_INTERNAL_H_
diff --git a/android_webview/native/address_parser_unittest.cc b/android_webview/browser/address_parser_unittest.cc similarity index 99% rename from android_webview/native/address_parser_unittest.cc rename to android_webview/browser/address_parser_unittest.cc index 304925e..82c11847 100644 --- a/android_webview/native/address_parser_unittest.cc +++ b/android_webview/browser/address_parser_unittest.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/native/address_parser.h" +#include "android_webview/browser/address_parser.h" #include <stddef.h> #include <memory> -#include "android_webview/native/address_parser_internal.h" +#include "android_webview/browser/address_parser_internal.h" #include "base/macros.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h"
diff --git a/android_webview/native/android_protocol_handler.cc b/android_webview/browser/android_protocol_handler.cc similarity index 95% rename from android_webview/native/android_protocol_handler.cc rename to android_webview/browser/android_protocol_handler.cc index b59a840..2355206 100644 --- a/android_webview/native/android_protocol_handler.cc +++ b/android_webview/browser/android_protocol_handler.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 "android_webview/native/android_protocol_handler.h" +#include "android_webview/browser/android_protocol_handler.h" #include <utility> +#include "android_webview/browser/input_stream_impl.h" #include "android_webview/browser/net/android_stream_reader_url_request_job.h" #include "android_webview/browser/net/aw_url_request_job_factory.h" #include "android_webview/common/url_constants.h" -#include "android_webview/native/input_stream_impl.h" #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/android/jni_weak_ref.h" @@ -103,8 +103,7 @@ AndroidStreamReaderURLRequestJobDelegateImpl() {} AndroidStreamReaderURLRequestJobDelegateImpl:: -~AndroidStreamReaderURLRequestJobDelegateImpl() { -} + ~AndroidStreamReaderURLRequestJobDelegateImpl() {} std::unique_ptr<InputStream> AndroidStreamReaderURLRequestJobDelegateImpl::OpenInputStream(JNIEnv* env, @@ -113,8 +112,7 @@ DCHECK(env); // Open the input stream. - ScopedJavaLocalRef<jstring> jurl = - ConvertUTF8ToJavaString(env, url.spec()); + ScopedJavaLocalRef<jstring> jurl = ConvertUTF8ToJavaString(env, url.spec()); ScopedJavaLocalRef<jobject> stream = android_webview::Java_AndroidProtocolHandler_open(env, jurl); @@ -146,8 +144,7 @@ // fail, as the mime type cannot be determined for all supported schemes. ScopedJavaLocalRef<jstring> url = ConvertUTF8ToJavaString(env, request->url().spec()); - const InputStreamImpl* stream_impl = - InputStreamImpl::FromInputStream(stream); + const InputStreamImpl* stream_impl = InputStreamImpl::FromInputStream(stream); ScopedJavaLocalRef<jstring> returned_type = android_webview::Java_AndroidProtocolHandler_getMimeType( env, stream_impl->jobj(), url); @@ -203,8 +200,7 @@ // AssetFileRequestInterceptor ------------------------------------------------ -AssetFileRequestInterceptor::AssetFileRequestInterceptor() { -} +AssetFileRequestInterceptor::AssetFileRequestInterceptor() {} bool AssetFileRequestInterceptor::ShouldHandleRequest( const net::URLRequest* request) const { @@ -213,8 +209,7 @@ // ContentSchemeRequestInterceptor -------------------------------------------- -ContentSchemeRequestInterceptor::ContentSchemeRequestInterceptor() { -} +ContentSchemeRequestInterceptor::ContentSchemeRequestInterceptor() {} bool ContentSchemeRequestInterceptor::ShouldHandleRequest( const net::URLRequest* request) const {
diff --git a/android_webview/native/android_protocol_handler.h b/android_webview/browser/android_protocol_handler.h similarity index 85% rename from android_webview/native/android_protocol_handler.h rename to android_webview/browser/android_protocol_handler.h index e003b0e5..9cd1b0e5 100644 --- a/android_webview/native/android_protocol_handler.h +++ b/android_webview/browser/android_protocol_handler.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_NATIVE_ANDROID_PROTOCOL_HANDLER_H_ -#define ANDROID_WEBVIEW_NATIVE_ANDROID_PROTOCOL_HANDLER_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_ANDROID_PROTOCOL_HANDLER_H_ +#define ANDROID_WEBVIEW_BROWSER_ANDROID_PROTOCOL_HANDLER_H_ #include <memory> @@ -33,4 +33,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_ANDROID_PROTOCOL_HANDLER_H_ +#endif // ANDROID_WEBVIEW_BROWSER_ANDROID_PROTOCOL_HANDLER_H_
diff --git a/android_webview/browser/android_webview_jni_registrar.cc b/android_webview/browser/android_webview_jni_registrar.cc new file mode 100644 index 0000000..b713e3b --- /dev/null +++ b/android_webview/browser/android_webview_jni_registrar.cc
@@ -0,0 +1,67 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "android_webview/browser/android_webview_jni_registrar.h" + +#include "android_webview/browser/android_protocol_handler.h" +#include "android_webview/browser/aw_autofill_client.h" +#include "android_webview/browser/aw_contents.h" +#include "android_webview/browser/aw_contents_client_bridge.h" +#include "android_webview/browser/aw_contents_statics.h" +#include "android_webview/browser/aw_debug.h" +#include "android_webview/browser/aw_devtools_server.h" +#include "android_webview/browser/aw_form_database.h" +#include "android_webview/browser/aw_gl_functor.h" +#include "android_webview/browser/aw_http_auth_handler.h" +#include "android_webview/browser/aw_metrics_service_client_impl.h" +#include "android_webview/browser/aw_pdf_exporter.h" +#include "android_webview/browser/aw_picture.h" +#include "android_webview/browser/aw_quota_manager_bridge_impl.h" +#include "android_webview/browser/aw_settings.h" +#include "android_webview/browser/aw_web_contents_delegate.h" +#include "android_webview/browser/cookie_manager.h" +#include "android_webview/browser/permission/aw_permission_request.h" +#include "base/android/jni_android.h" +#include "base/android/jni_registrar.h" +#include "base/trace_event/trace_event.h" +#include "components/spellcheck/spellcheck_build_features.h" + +#if BUILDFLAG(ENABLE_SPELLCHECK) +#include "components/spellcheck/browser/android/component_jni_registrar.h" +#endif + +namespace android_webview { + +static base::android::RegistrationMethod kWebViewRegisteredMethods[] = { + // Register JNI for android_webview classes. + {"AndroidProtocolHandler", RegisterAndroidProtocolHandler}, + {"AwAutofillClient", RegisterAwAutofillClient}, + {"AwContents", RegisterAwContents}, + {"AwContentsClientBridge", RegisterAwContentsClientBridge}, + {"AwContentsStatics", RegisterAwContentsStatics}, + {"AwDebug", RegisterAwDebug}, + {"AwDevToolsServer", RegisterAwDevToolsServer}, + {"AwFormDatabase", RegisterAwFormDatabase}, + {"AwPicture", RegisterAwPicture}, + {"AwSettings", RegisterAwSettings}, + {"AwHttpAuthHandler", RegisterAwHttpAuthHandler}, + {"AwMetricsServiceClient", RegisterAwMetricsServiceClient}, + {"AwPdfExporter", RegisterAwPdfExporter}, + {"AwPermissionRequest", RegisterAwPermissionRequest}, + {"AwQuotaManagerBridge", RegisterAwQuotaManagerBridge}, + {"AwWebContentsDelegate", RegisterAwWebContentsDelegate}, + {"CookieManager", RegisterCookieManager}, + {"AwGLFunctor", RegisterAwGLFunctor}, +#if BUILDFLAG(ENABLE_SPELLCHECK) + {"SpellCheckerSessionBridge", spellcheck::android::RegisterSpellcheckJni}, +#endif +}; + +bool RegisterJni(JNIEnv* env) { + TRACE_EVENT0("startup", "android_webview::RegisterJni"); + return RegisterNativeMethods(env, kWebViewRegisteredMethods, + arraysize(kWebViewRegisteredMethods)); +} + +} // namespace android_webview
diff --git a/android_webview/browser/android_webview_jni_registrar.h b/android_webview/browser/android_webview_jni_registrar.h new file mode 100644 index 0000000..2c9b85a --- /dev/null +++ b/android_webview/browser/android_webview_jni_registrar.h
@@ -0,0 +1,17 @@ +// 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 ANDROID_WEBVIEW_BROWSER_ANDROID_WEBVIEW_JNI_REGISTRAR_H_ +#define ANDROID_WEBVIEW_BROWSER_ANDROID_WEBVIEW_JNI_REGISTRAR_H_ + +#include <jni.h> + +namespace android_webview { + +// Register all JNI bindings necessary for chrome. +bool RegisterJni(JNIEnv* env); + +} // namespace android_webview + +#endif // ANDROID_WEBVIEW_BROWSER_ANDROID_WEBVIEW_JNI_REGISTRAR_H_
diff --git a/android_webview/native/aw_autofill_client.cc b/android_webview/browser/aw_autofill_client.cc similarity index 97% rename from android_webview/native/aw_autofill_client.cc rename to android_webview/browser/aw_autofill_client.cc index 26f2b94..1ca74bc 100644 --- a/android_webview/native/aw_autofill_client.cc +++ b/android_webview/browser/aw_autofill_client.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/native/aw_autofill_client.h" +#include "android_webview/browser/aw_autofill_client.h" #include "android_webview/browser/aw_browser_context.h" #include "android_webview/browser/aw_content_browser_client.h" +#include "android_webview/browser/aw_contents.h" #include "android_webview/browser/aw_form_database_service.h" -#include "android_webview/native/aw_contents.h" #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" @@ -100,7 +100,8 @@ AwAutofillClient::GetDatabase() { android_webview::AwFormDatabaseService* service = static_cast<android_webview::AwBrowserContext*>( - web_contents_->GetBrowserContext())->GetFormDatabaseService(); + web_contents_->GetBrowserContext()) + ->GetFormDatabaseService(); return service->get_autofill_webdata_service(); }
diff --git a/android_webview/native/aw_autofill_client.h b/android_webview/browser/aw_autofill_client.h similarity index 94% rename from android_webview/native/aw_autofill_client.h rename to android_webview/browser/aw_autofill_client.h index 0316127..58ceee5 100644 --- a/android_webview/native/aw_autofill_client.h +++ b/android_webview/browser/aw_autofill_client.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_NATIVE_AW_AUTOFILL_CLIENT_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_AUTOFILL_CLIENT_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_AUTOFILL_CLIENT_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_AUTOFILL_CLIENT_H_ #include <jni.h> #include <memory> @@ -108,8 +108,7 @@ void StartSigninFlow() override; void ShowHttpNotSecureExplanation() override; - void Dismissed(JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj); + void Dismissed(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); void SuggestionSelected(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, jint position); @@ -141,4 +140,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_AUTOFILL_CLIENT_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_AUTOFILL_CLIENT_H_
diff --git a/android_webview/native/aw_contents.cc b/android_webview/browser/aw_contents.cc similarity index 94% rename from android_webview/native/aw_contents.cc rename to android_webview/browser/aw_contents.cc index 184c6878..86143f8b 100644 --- a/android_webview/native/aw_contents.cc +++ b/android_webview/browser/aw_contents.cc
@@ -2,38 +2,38 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/native/aw_contents.h" +#include "android_webview/browser/aw_contents.h" #include <limits> #include <utility> +#include "android_webview/browser/aw_autofill_client.h" #include "android_webview/browser/aw_browser_context.h" #include "android_webview/browser/aw_browser_main_parts.h" +#include "android_webview/browser/aw_contents_client_bridge.h" +#include "android_webview/browser/aw_contents_io_thread_client_impl.h" +#include "android_webview/browser/aw_contents_lifecycle_notifier.h" +#include "android_webview/browser/aw_gl_functor.h" +#include "android_webview/browser/aw_pdf_exporter.h" +#include "android_webview/browser/aw_picture.h" +#include "android_webview/browser/aw_renderer_priority_manager.h" #include "android_webview/browser/aw_resource_context.h" +#include "android_webview/browser/aw_web_contents_delegate.h" #include "android_webview/browser/browser_view_renderer.h" #include "android_webview/browser/child_frame.h" #include "android_webview/browser/deferred_gpu_command_service.h" +#include "android_webview/browser/java_browser_view_renderer_helper.h" #include "android_webview/browser/net_disk_cache_remover.h" +#include "android_webview/browser/permission/aw_permission_request.h" +#include "android_webview/browser/permission/permission_request_handler.h" +#include "android_webview/browser/permission/simple_permission_request.h" #include "android_webview/browser/render_thread_manager.h" #include "android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.h" #include "android_webview/browser/scoped_app_gl_state_restore.h" +#include "android_webview/browser/state_serializer.h" #include "android_webview/common/aw_hit_test_data.h" #include "android_webview/common/aw_switches.h" #include "android_webview/common/devtools_instrumentation.h" -#include "android_webview/native/aw_autofill_client.h" -#include "android_webview/native/aw_contents_client_bridge.h" -#include "android_webview/native/aw_contents_io_thread_client_impl.h" -#include "android_webview/native/aw_contents_lifecycle_notifier.h" -#include "android_webview/native/aw_gl_functor.h" -#include "android_webview/native/aw_pdf_exporter.h" -#include "android_webview/native/aw_picture.h" -#include "android_webview/native/aw_renderer_priority_manager.h" -#include "android_webview/native/aw_web_contents_delegate.h" -#include "android_webview/native/java_browser_view_renderer_helper.h" -#include "android_webview/native/permission/aw_permission_request.h" -#include "android_webview/native/permission/permission_request_handler.h" -#include "android_webview/native/permission/simple_permission_request.h" -#include "android_webview/native/state_serializer.h" #include "android_webview/public/browser/draw_gl.h" #include "base/android/jni_android.h" #include "base/android/jni_array.h" @@ -146,10 +146,12 @@ AwContents* AwContents::FromID(int render_process_id, int render_view_id) { content::RenderViewHost* rvh = content::RenderViewHost::FromID(render_process_id, render_view_id); - if (!rvh) return NULL; + if (!rvh) + return NULL; content::WebContents* web_contents = content::WebContents::FromRenderViewHost(rvh); - if (!web_contents) return NULL; + if (!web_contents) + return NULL; return FromWebContents(web_contents); } @@ -174,9 +176,10 @@ // static AwBrowserPermissionRequestDelegate* AwBrowserPermissionRequestDelegate::FromID( - int render_process_id, int render_frame_id) { - AwContents* aw_contents = AwContents::FromWebContents( - content::WebContents::FromRenderFrameHost( + int render_process_id, + int render_frame_id) { + AwContents* aw_contents = + AwContents::FromWebContents(content::WebContents::FromRenderFrameHost( content::RenderFrameHost::FromID(render_process_id, render_frame_id))); return aw_contents; @@ -283,8 +286,8 @@ // We need to check for the existence, since autofill_manager_delegate // may not be created when the setting is false. if (AwAutofillClient::FromWebContents(web_contents_.get())) { - AwAutofillClient::FromWebContents(web_contents_.get())-> - SetSaveFormData(enabled); + AwAutofillClient::FromWebContents(web_contents_.get()) + ->SetSaveFormData(enabled); } } @@ -451,10 +454,7 @@ void AwContents::CreatePdfExporter(JNIEnv* env, const JavaParamRef<jobject>& obj, const JavaParamRef<jobject>& pdfExporter) { - pdf_exporter_.reset( - new AwPdfExporter(env, - pdfExporter, - web_contents_.get())); + pdf_exporter_.reset(new AwPdfExporter(env, pdfExporter, web_contents_.get())); } bool AwContents::OnReceivedHttpAuthRequest(const JavaRef<jobject>& handler, @@ -485,8 +485,8 @@ const JavaParamRef<jobjectArray>& jvisited_links) { DCHECK_CURRENTLY_ON(BrowserThread::UI); std::vector<base::string16> visited_link_strings; - base::android::AppendJavaStringArrayToStringVector( - env, jvisited_links, &visited_link_strings); + base::android::AppendJavaStringArrayToStringVector(env, jvisited_links, + &visited_link_strings); std::vector<GURL> visited_link_gurls; std::vector<base::string16>::const_iterator itr; @@ -523,15 +523,12 @@ JNIEnv* env = AttachCurrentThread(); if (java_ref.get(env).obj()) { content::BrowserThread::PostTask( - content::BrowserThread::UI, - FROM_HERE, - base::Bind(&ShowGeolocationPromptHelperTask, - java_ref, - origin)); + content::BrowserThread::UI, FROM_HERE, + base::Bind(&ShowGeolocationPromptHelperTask, java_ref, origin)); } } -} // anonymous namespace +} // anonymous namespace void AwContents::ShowGeolocationPrompt(const GURL& requesting_frame, base::Callback<void(bool)> callback) { @@ -592,7 +589,7 @@ } if (!pending_geolocation_prompts_.empty()) { ShowGeolocationPromptHelper(java_ref_, - pending_geolocation_prompts_.front().first); + pending_geolocation_prompts_.front().first); } } } @@ -673,8 +670,8 @@ HideGeolocationPrompt(origin); return; } - permission_request_handler_->CancelRequest( - origin, AwPermissionRequest::Geolocation); + permission_request_handler_->CancelRequest(origin, + AwPermissionRequest::Geolocation); } void AwContents::RequestMIDISysexPermission( @@ -833,7 +830,8 @@ void AwContents::UpdateLastHitTestData(JNIEnv* env, const JavaParamRef<jobject>& obj) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!render_view_host_ext_->HasNewHitTestData()) return; + if (!render_view_host_ext_->HasNewHitTestData()) + return; const AwHitTestData& data = render_view_host_ext_->GetLastHitTestData(); render_view_host_ext_->MarkHitTestDataRead(); @@ -841,8 +839,8 @@ // Make sure to null the Java object if data is empty/invalid. ScopedJavaLocalRef<jstring> extra_data_for_type; if (data.extra_data_for_type.length()) - extra_data_for_type = ConvertUTF8ToJavaString( - env, data.extra_data_for_type); + extra_data_for_type = + ConvertUTF8ToJavaString(env, data.extra_data_for_type); ScopedJavaLocalRef<jstring> href; if (data.href.length()) @@ -1178,7 +1176,7 @@ JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> obj = java_ref.get(env); if (obj.is_null()) - return; + return; Java_AwContents_invokeVisualStateCallback(env, obj, callback, request_id); } } // namespace @@ -1296,8 +1294,8 @@ if (jextra_headers) extra_headers = ConvertJavaStringToUTF8(env, jextra_headers); AwResourceContext* resource_context = static_cast<AwResourceContext*>( - AwBrowserContext::FromWebContents(web_contents_.get())-> - GetResourceContext()); + AwBrowserContext::FromWebContents(web_contents_.get()) + ->GetResourceContext()); resource_context->SetExtraHeaders(GURL(ConvertJavaStringToUTF8(env, url)), extra_headers); } @@ -1344,12 +1342,8 @@ const JavaParamRef<jstring>& target_origin, const JavaParamRef<jobjectArray>& ports) { // Use an empty source origin for android webview. - content::MessagePortProvider::PostMessageToFrame(web_contents_.get(), - env, - nullptr, - target_origin, - message, - ports); + content::MessagePortProvider::PostMessageToFrame( + web_contents_.get(), env, nullptr, target_origin, message, ports); } void AwContents::GrantFileSchemeAccesstoChildProcess( @@ -1440,16 +1434,15 @@ Java_AwContents_onRenderProcessGone(env, obj, child_process_id); } -bool AwContents::OnRenderProcessGoneDetail(int child_process_id, - bool crashed) { +bool AwContents::OnRenderProcessGoneDetail(int child_process_id, bool crashed) { DCHECK_CURRENTLY_ON(BrowserThread::UI); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> obj = java_ref_.get(env); if (obj.is_null()) return false; - return Java_AwContents_onRenderProcessGoneDetail(env, obj, - child_process_id, crashed); + return Java_AwContents_onRenderProcessGoneDetail(env, obj, child_process_id, + crashed); } void AwContents::RenderProcessReady(content::RenderProcessHost* host) {
diff --git a/android_webview/native/aw_contents.h b/android_webview/browser/aw_contents.h similarity index 98% rename from android_webview/native/aw_contents.h rename to android_webview/browser/aw_contents.h index 1248bd1..f6db432 100644 --- a/android_webview/native/aw_contents.h +++ b/android_webview/browser/aw_contents.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_NATIVE_AW_CONTENTS_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_CONTENTS_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_H_ #include <jni.h> @@ -14,17 +14,17 @@ #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_renderer_priority_manager.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/gl_view_renderer_manager.h" #include "android_webview/browser/icon_helper.h" +#include "android_webview/browser/permission/permission_request_handler_client.h" #include "android_webview/browser/render_thread_manager.h" #include "android_webview/browser/render_thread_manager_client.h" #include "android_webview/browser/renderer_host/aw_render_view_host_ext.h" -#include "android_webview/native/aw_renderer_priority_manager.h" -#include "android_webview/native/permission/permission_request_handler_client.h" #include "base/android/jni_weak_ref.h" #include "base/android/scoped_java_ref.h" #include "base/callback_forward.h" @@ -426,4 +426,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_CONTENTS_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_H_
diff --git a/android_webview/native/aw_contents_background_thread_client.cc b/android_webview/browser/aw_contents_background_thread_client.cc similarity index 92% rename from android_webview/native/aw_contents_background_thread_client.cc rename to android_webview/browser/aw_contents_background_thread_client.cc index d2fa3de..3a07a585 100644 --- a/android_webview/native/aw_contents_background_thread_client.cc +++ b/android_webview/browser/aw_contents_background_thread_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 "android_webview/native/aw_contents_background_thread_client.h" +#include "android_webview/browser/aw_contents_background_thread_client.h" #include "jni/AwContentsBackgroundThreadClient_jni.h"
diff --git a/android_webview/native/aw_contents_background_thread_client.h b/android_webview/browser/aw_contents_background_thread_client.h similarity index 77% rename from android_webview/native/aw_contents_background_thread_client.h rename to android_webview/browser/aw_contents_background_thread_client.h index d08cea19..73e3402 100644 --- a/android_webview/native/aw_contents_background_thread_client.h +++ b/android_webview/browser/aw_contents_background_thread_client.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_NATIVE_AW_CONTENTS_BACKGROUND_THREAD_CLIENT_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_CONTENTS_BACKGROUND_THREAD_CLIENT_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_BACKGROUND_THREAD_CLIENT_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_BACKGROUND_THREAD_CLIENT_H_ #include "base/android/scoped_java_ref.h" @@ -21,7 +21,6 @@ const base::android::JavaRef<jobjectArray>& requestHeaderNames, const base::android::JavaRef<jobjectArray>& requestHeaderValues); }; - } -#endif // ANDROID_WEBVIEW_NATIVE_AW_CONTENTS_BACKGROUND_THREAD_CLIENT_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_BACKGROUND_THREAD_CLIENT_H_
diff --git a/android_webview/native/aw_contents_client_bridge.cc b/android_webview/browser/aw_contents_client_bridge.cc similarity index 98% rename from android_webview/native/aw_contents_client_bridge.cc rename to android_webview/browser/aw_contents_client_bridge.cc index b85568a..eb4ecab 100644 --- a/android_webview/native/aw_contents_client_bridge.cc +++ b/android_webview/browser/aw_contents_client_bridge.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 "android_webview/native/aw_contents_client_bridge.h" +#include "android_webview/browser/aw_contents_client_bridge.h" #include <memory> #include <utility> +#include "android_webview/browser/aw_contents.h" #include "android_webview/common/devtools_instrumentation.h" #include "android_webview/grit/components_strings.h" -#include "android_webview/native/aw_contents.h" #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" @@ -103,8 +103,8 @@ ScopedJavaLocalRef<jbyteArray> jcert = base::android::ToJavaByteArray( env, reinterpret_cast<const uint8_t*>(der_string.data()), der_string.length()); - ScopedJavaLocalRef<jstring> jurl(ConvertUTF8ToJavaString( - env, request_url.spec())); + ScopedJavaLocalRef<jstring> jurl( + ConvertUTF8ToJavaString(env, request_url.spec())); // We need to add the callback before making the call to java side, // as it may do a synchronous callback prior to returning. int request_id = pending_cert_error_callbacks_.Add( @@ -145,8 +145,7 @@ // Make sure callback is run on error. base::ScopedClosureRunner guard(base::Bind( &AwContentsClientBridge::HandleErrorInClientCertificateResponse, - base::Unretained(this), - request_id)); + base::Unretained(this), request_id)); JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jobject> obj = java_ref_.get(env); @@ -224,8 +223,7 @@ // Make sure callback is run on error. base::ScopedClosureRunner guard(base::Bind( &AwContentsClientBridge::HandleErrorInClientCertificateResponse, - base::Unretained(this), - request_id)); + base::Unretained(this), request_id)); // Convert the encoded chain to a vector of strings. std::vector<std::string> encoded_chain_strings; @@ -315,7 +313,7 @@ break; } default: - NOTREACHED(); + NOTREACHED(); } }
diff --git a/android_webview/native/aw_contents_client_bridge.h b/android_webview/browser/aw_contents_client_bridge.h similarity index 95% rename from android_webview/native/aw_contents_client_bridge.h rename to android_webview/browser/aw_contents_client_bridge.h index db1f28d..38485ec8 100644 --- a/android_webview/native/aw_contents_client_bridge.h +++ b/android_webview/browser/aw_contents_client_bridge.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ANDROID_WEBVIEW_NATIVE_AW_CONTENTS_CLIENT_BRIDGE_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_CONTENTS_CLIENT_BRIDGE_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_CLIENT_BRIDGE_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_CLIENT_BRIDGE_H_ #include <jni.h> @@ -115,4 +115,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_CONTENTS_CLIENT_BRIDGE_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_CLIENT_BRIDGE_H_
diff --git a/android_webview/native/aw_contents_client_bridge_unittest.cc b/android_webview/browser/aw_contents_client_bridge_unittest.cc similarity index 90% rename from android_webview/native/aw_contents_client_bridge_unittest.cc rename to android_webview/browser/aw_contents_client_bridge_unittest.cc index 1b100e3..923dee9 100644 --- a/android_webview/native/aw_contents_client_bridge_unittest.cc +++ b/android_webview/browser/aw_contents_client_bridge_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/native/aw_contents_client_bridge.h" +#include "android_webview/browser/aw_contents_client_bridge.h" #include <memory> @@ -36,10 +36,11 @@ // Tests the android_webview contents client bridge. class AwContentsClientBridgeTest : public Test { public: - AwContentsClientBridgeTest() { } + AwContentsClientBridgeTest() {} // Callback method called when a cert is selected. void CertSelected(X509Certificate* cert); + protected: void SetUp() override; void TestCertType(SSLClientCertType type, const std::string& expected_name); @@ -71,14 +72,15 @@ DISALLOW_COPY_AND_ASSIGN(TestClientCertificateDelegate); }; -} // namespace +} // namespace void AwContentsClientBridgeTest::SetUp() { env_ = AttachCurrentThread(); ASSERT_THAT(env_, NotNull()); ASSERT_TRUE(android_webview::RegisterAwContentsClientBridge(env_)); ASSERT_TRUE(net::android::RegisterJni(env_)); - jbridge_.Reset(env_, + jbridge_.Reset( + env_, Java_MockAwContentsClientBridge_getAwContentsClientBridge(env_).obj()); bridge_.reset(new AwContentsClientBridge(env_, jbridge_)); selected_cert_ = nullptr; @@ -101,8 +103,9 @@ } } -void AwContentsClientBridgeTest::TestCertType(SSLClientCertType type, - const std::string& expected_name) { +void AwContentsClientBridgeTest::TestCertType( + SSLClientCertType type, + const std::string& expected_name) { cert_request_info_->cert_key_types.clear(); cert_request_info_->cert_key_types.push_back(type); bridge_->SelectClientCertificate( @@ -113,8 +116,7 @@ ScopedJavaLocalRef<jobjectArray> key_types = Java_MockAwContentsClientBridge_getKeyTypes(env_, jbridge_); std::vector<std::string> vec; - base::android::AppendJavaStringArrayToStringVector(env_, - key_types.obj(), + base::android::AppendJavaStringArrayToStringVector(env_, key_types.obj(), &vec); EXPECT_EQ(1u, vec.size()); EXPECT_EQ(expected_name, vec[0]); @@ -123,7 +125,7 @@ // Verify that ProvideClientCertificateResponse works properly when the client // responds with a null key. TEST_F(AwContentsClientBridgeTest, - TestProvideClientCertificateResponseCallsCallbackOnNullKey) { + TestProvideClientCertificateResponseCallsCallbackOnNullKey) { // Call SelectClientCertificate to create a callback id that mock java object // can call on. bridge_->SelectClientCertificate( @@ -142,7 +144,7 @@ // Verify that ProvideClientCertificateResponse calls the callback with // null parameters when private key is not provided. TEST_F(AwContentsClientBridgeTest, - TestProvideClientCertificateResponseCallsCallbackOnNullChain) { + TestProvideClientCertificateResponseCallsCallbackOnNullChain) { // Call SelectClientCertificate to create a callback id that mock java object // can call on. bridge_->SelectClientCertificate( @@ -156,4 +158,4 @@ EXPECT_EQ(1, cert_selected_callbacks_); } -} // android_webview +} // android_webview
diff --git a/android_webview/native/aw_contents_io_thread_client_impl.cc b/android_webview/browser/aw_contents_io_thread_client_impl.cc similarity index 93% rename from android_webview/native/aw_contents_io_thread_client_impl.cc rename to android_webview/browser/aw_contents_io_thread_client_impl.cc index 855cc86..c85a803 100644 --- a/android_webview/native/aw_contents_io_thread_client_impl.cc +++ b/android_webview/browser/aw_contents_io_thread_client_impl.cc
@@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/native/aw_contents_io_thread_client_impl.h" +#include "android_webview/browser/aw_contents_io_thread_client_impl.h" #include <map> #include <memory> #include <utility> +#include "android_webview/browser/aw_contents_background_thread_client.h" +#include "android_webview/browser/aw_web_resource_response_impl.h" #include "android_webview/browser/net/aw_web_resource_request.h" #include "android_webview/common/devtools_instrumentation.h" -#include "android_webview/native/aw_contents_background_thread_client.h" -#include "android_webview/native/aw_web_resource_response_impl.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/android/jni_weak_ref.h" @@ -103,8 +103,8 @@ rfh_to_io_thread_client_[rfh_id] = client; } -bool RfhToIoThreadClientMap::Get( - pair<int, int> rfh_id, IoThreadClientData* client) { +bool RfhToIoThreadClientMap::Get(pair<int, int> rfh_id, + IoThreadClientData* client) { base::AutoLock lock(map_lock_); RenderFrameHostToIoThreadClientType::iterator iterator = rfh_to_io_thread_client_.find(rfh_id); @@ -147,7 +147,8 @@ class ClientMapEntryUpdater : public content::WebContentsObserver { public: - ClientMapEntryUpdater(JNIEnv* env, WebContents* web_contents, + ClientMapEntryUpdater(JNIEnv* env, + WebContents* web_contents, jobject jdelegate); void RenderFrameCreated(RenderFrameHost* render_frame_host) override; @@ -161,8 +162,7 @@ ClientMapEntryUpdater::ClientMapEntryUpdater(JNIEnv* env, WebContents* web_contents, jobject jdelegate) - : content::WebContentsObserver(web_contents), - jdelegate_(env, jdelegate) { + : content::WebContentsObserver(web_contents), jdelegate_(env, jdelegate) { DCHECK(web_contents); DCHECK(jdelegate); @@ -189,7 +189,7 @@ delete this; } -} // namespace +} // namespace // AwContentsIoThreadClientImpl ----------------------------------------------- @@ -253,9 +253,8 @@ } // static -void AwContentsIoThreadClientImpl::Associate( - WebContents* web_contents, - const JavaRef<jobject>& jclient) { +void AwContentsIoThreadClientImpl::Associate(WebContents* web_contents, + const JavaRef<jobject>& jclient) { JNIEnv* env = AttachCurrentThread(); // The ClientMapEntryUpdater lifespan is tied to the WebContents. new ClientMapEntryUpdater(env, web_contents, jclient.obj()); @@ -288,9 +287,7 @@ AwContentsIoThreadClientImpl::AwContentsIoThreadClientImpl( bool pending_association, const JavaRef<jobject>& obj) - : pending_association_(pending_association), - java_object_(obj) { -} + : pending_association_(pending_association), java_object_(obj) {} AwContentsIoThreadClientImpl::~AwContentsIoThreadClientImpl() { // explict, out-of-line destructor. @@ -300,8 +297,8 @@ return pending_association_; } -AwContentsIoThreadClient::CacheMode -AwContentsIoThreadClientImpl::GetCacheMode() const { +AwContentsIoThreadClient::CacheMode AwContentsIoThreadClientImpl::GetCacheMode() + const { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (java_object_.is_null()) return AwContentsIoThreadClient::LOAD_DEFAULT; @@ -311,7 +308,6 @@ Java_AwContentsIoThreadClient_getCacheMode(env, java_object_)); } - namespace { std::unique_ptr<AwWebResourceResponse> RunShouldInterceptRequest( @@ -414,4 +410,4 @@ java_object_); } -} // namespace android_webview +} // namespace android_webview
diff --git a/android_webview/native/aw_contents_io_thread_client_impl.h b/android_webview/browser/aw_contents_io_thread_client_impl.h similarity index 87% rename from android_webview/native/aw_contents_io_thread_client_impl.h rename to android_webview/browser/aw_contents_io_thread_client_impl.h index 33b7bc1..5200c47 100644 --- a/android_webview/native/aw_contents_io_thread_client_impl.h +++ b/android_webview/browser/aw_contents_io_thread_client_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_NATIVE_AW_CONTENTS_IO_THREAD_CLIENT_IMPL_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_CONTENTS_IO_THREAD_CLIENT_IMPL_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_IO_THREAD_CLIENT_IMPL_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_IO_THREAD_CLIENT_IMPL_H_ #include <stdint.h> @@ -24,7 +24,7 @@ class AwContentsIoThreadClientImpl : public AwContentsIoThreadClient { public: - // Called when AwContents is created before there is a Java client. + // Called when AwContents is created before there is a Java client. static void RegisterPendingContents(content::WebContents* web_contents); // Associates the |jclient| instance (which must implement the @@ -65,6 +65,6 @@ DISALLOW_COPY_AND_ASSIGN(AwContentsIoThreadClientImpl); }; -} // namespace android_webview +} // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_CONTENTS_IO_THREAD_CLIENT_IMPL_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_IO_THREAD_CLIENT_IMPL_H_
diff --git a/android_webview/native/aw_contents_lifecycle_notifier.cc b/android_webview/browser/aw_contents_lifecycle_notifier.cc similarity index 89% rename from android_webview/native/aw_contents_lifecycle_notifier.cc rename to android_webview/browser/aw_contents_lifecycle_notifier.cc index 69921d98..32f7f64 100644 --- a/android_webview/native/aw_contents_lifecycle_notifier.cc +++ b/android_webview/browser/aw_contents_lifecycle_notifier.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/native/aw_contents_lifecycle_notifier.h" +#include "android_webview/browser/aw_contents_lifecycle_notifier.h" #include "jni/AwContentsLifecycleNotifier_jni.h"
diff --git a/android_webview/native/aw_contents_lifecycle_notifier.h b/android_webview/browser/aw_contents_lifecycle_notifier.h similarity index 100% rename from android_webview/native/aw_contents_lifecycle_notifier.h rename to android_webview/browser/aw_contents_lifecycle_notifier.h
diff --git a/android_webview/native/aw_contents_statics.cc b/android_webview/browser/aw_contents_statics.cc similarity index 90% rename from android_webview/native/aw_contents_statics.cc rename to android_webview/browser/aw_contents_statics.cc index a9262329..e46dcc1 100644 --- a/android_webview/native/aw_contents_statics.cc +++ b/android_webview/browser/aw_contents_statics.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 "android_webview/native/aw_contents_statics.h" +#include "android_webview/browser/aw_contents_statics.h" +#include "android_webview/browser/address_parser.h" #include "android_webview/browser/aw_browser_context.h" +#include "android_webview/browser/aw_contents_io_thread_client_impl.h" #include "android_webview/browser/aw_safe_browsing_config_helper.h" #include "android_webview/browser/net/aw_url_request_context_getter.h" #include "android_webview/common/aw_version_info_values.h" -#include "android_webview/native/address_parser.h" -#include "android_webview/native/aw_contents_io_thread_client_impl.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/callback.h" @@ -78,8 +78,7 @@ } // static -jboolean GetSafeBrowsingEnabled(JNIEnv* env, - const JavaParamRef<jclass>&) { +jboolean GetSafeBrowsingEnabled(JNIEnv* env, const JavaParamRef<jclass>&) { return AwSafeBrowsingConfigHelper::GetSafeBrowsingEnabled(); } @@ -96,8 +95,8 @@ const JavaParamRef<jclass>&, const base::android::JavaParamRef<jobject>& io_thread_client, const base::android::JavaParamRef<jobject>& browser_context) { - AwContentsIoThreadClientImpl::SetServiceWorkerIoThreadClient( - io_thread_client, browser_context); + AwContentsIoThreadClientImpl::SetServiceWorkerIoThreadClient(io_thread_client, + browser_context); } // static
diff --git a/android_webview/native/aw_contents_statics.h b/android_webview/browser/aw_contents_statics.h similarity index 75% rename from android_webview/native/aw_contents_statics.h rename to android_webview/browser/aw_contents_statics.h index 0de5485..26953df 100644 --- a/android_webview/native/aw_contents_statics.h +++ b/android_webview/browser/aw_contents_statics.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_NATIVE_AW_CONTENTS_STATICS_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_CONTENTS_STATICS_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_STATICS_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_STATICS_H_ #include <jni.h>
diff --git a/android_webview/native/aw_debug.cc b/android_webview/browser/aw_debug.cc similarity index 97% rename from android_webview/native/aw_debug.cc rename to android_webview/browser/aw_debug.cc index 1a0ffd6..140ef4fb 100644 --- a/android_webview/native/aw_debug.cc +++ b/android_webview/browser/aw_debug.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/native/aw_debug.h" +#include "android_webview/browser/aw_debug.h" #include "android_webview/common/crash_reporter/aw_microdump_crash_reporter.h" #include "android_webview/common/crash_reporter/crash_keys.h"
diff --git a/android_webview/native/aw_debug.h b/android_webview/browser/aw_debug.h similarity index 75% rename from android_webview/native/aw_debug.h rename to android_webview/browser/aw_debug.h index 0f41f3d..8b55a6a 100644 --- a/android_webview/native/aw_debug.h +++ b/android_webview/browser/aw_debug.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_NATIVE_AW_DEBUG_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_DEBUG_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_DEBUG_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_DEBUG_H_ #include <jni.h> @@ -17,4 +17,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_DEBUG_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_DEBUG_H_
diff --git a/android_webview/native/aw_devtools_server.cc b/android_webview/browser/aw_devtools_server.cc similarity index 90% rename from android_webview/native/aw_devtools_server.cc rename to android_webview/browser/aw_devtools_server.cc index 9ced44b..0348f39 100644 --- a/android_webview/native/aw_devtools_server.cc +++ b/android_webview/browser/aw_devtools_server.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/native/aw_devtools_server.h" +#include "android_webview/browser/aw_devtools_server.h" #include <utility> +#include "android_webview/browser/aw_contents.h" #include "android_webview/browser/browser_view_renderer.h" #include "android_webview/common/aw_content_client.h" -#include "android_webview/native/aw_contents.h" #include "base/bind.h" #include "base/files/file_path.h" #include "base/json/json_writer.h" @@ -41,9 +41,7 @@ class UnixDomainServerSocketFactory : public content::DevToolsSocketFactory { public: explicit UnixDomainServerSocketFactory(const std::string& socket_name) - : socket_name_(socket_name), - last_tethering_socket_(0) { - } + : socket_name_(socket_name), last_tethering_socket_(0) {} private: // content::DevToolsAgentHost::ServerSocketFactory. @@ -60,8 +58,8 @@ std::unique_ptr<net::ServerSocket> CreateForTethering( std::string* name) override { - *name = base::StringPrintf( - kTetheringSocketName, getpid(), ++last_tethering_socket_); + *name = base::StringPrintf(kTetheringSocketName, getpid(), + ++last_tethering_socket_); std::unique_ptr<net::UnixDomainServerSocket> socket( new net::UnixDomainServerSocket( base::Bind(&content::CanUserConnectToDevTools), @@ -82,8 +80,7 @@ namespace android_webview { -AwDevToolsServer::AwDevToolsServer() : is_started_(false) { -} +AwDevToolsServer::AwDevToolsServer() : is_started_(false) {} AwDevToolsServer::~AwDevToolsServer() { Stop(); @@ -100,8 +97,7 @@ DevToolsAgentHost::StartRemoteDebuggingServer( std::move(factory), base::StringPrintf(kFrontEndURL, content::GetWebKitRevision().c_str()), - base::FilePath(), base::FilePath(), - GetProduct(), GetUserAgent()); + base::FilePath(), base::FilePath(), GetProduct(), GetUserAgent()); } void AwDevToolsServer::Stop() {
diff --git a/android_webview/native/aw_devtools_server.h b/android_webview/browser/aw_devtools_server.h similarity index 82% rename from android_webview/native/aw_devtools_server.h rename to android_webview/browser/aw_devtools_server.h index 6f1f0f0..1eba6788 100644 --- a/android_webview/native/aw_devtools_server.h +++ b/android_webview/browser/aw_devtools_server.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_NATIVE_AW_DEVTOOLS_SERVER_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_DEVTOOLS_SERVER_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_DEVTOOLS_SERVER_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_DEVTOOLS_SERVER_H_ #include <jni.h> @@ -37,4 +37,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_DEVTOOLS_SERVER_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_DEVTOOLS_SERVER_H_
diff --git a/android_webview/native/aw_form_database.cc b/android_webview/browser/aw_form_database.cc similarity index 90% rename from android_webview/native/aw_form_database.cc rename to android_webview/browser/aw_form_database.cc index 3e3ebb9..9755ab2 100644 --- a/android_webview/native/aw_form_database.cc +++ b/android_webview/browser/aw_form_database.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/native/aw_form_database.h" +#include "android_webview/browser/aw_form_database.h" #include "android_webview/browser/aw_browser_context.h" #include "android_webview/browser/aw_content_browser_client.h" @@ -19,13 +19,12 @@ namespace { AwFormDatabaseService* GetFormDatabaseService() { - AwBrowserContext* context = AwContentBrowserClient::GetAwBrowserContext(); AwFormDatabaseService* service = context->GetFormDatabaseService(); return service; } -} // anonymous namespace +} // anonymous namespace // static jboolean HasFormData(JNIEnv*, const JavaParamRef<jclass>&) { @@ -41,4 +40,4 @@ return RegisterNativesImpl(env); } -} // namespace android_webview +} // namespace android_webview
diff --git a/android_webview/native/aw_form_database.h b/android_webview/browser/aw_form_database.h similarity index 64% rename from android_webview/native/aw_form_database.h rename to android_webview/browser/aw_form_database.h index ae1ceb0..541e13b 100644 --- a/android_webview/native/aw_form_database.h +++ b/android_webview/browser/aw_form_database.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_NATIVE_AW_FORM_DATABASE_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_FORM_DATABASE_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_FORM_DATABASE_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_FORM_DATABASE_H_ #include <jni.h> @@ -13,4 +13,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_FORM_DATABASE_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_FORM_DATABASE_H_
diff --git a/android_webview/native/aw_gl_functor.cc b/android_webview/browser/aw_gl_functor.cc similarity index 98% rename from android_webview/native/aw_gl_functor.cc rename to android_webview/browser/aw_gl_functor.cc index b9470f3..257b1b5 100644 --- a/android_webview/native/aw_gl_functor.cc +++ b/android_webview/browser/aw_gl_functor.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/native/aw_gl_functor.h" +#include "android_webview/browser/aw_gl_functor.h" #include "android_webview/public/browser/draw_gl.h" #include "content/public/browser/browser_thread.h"
diff --git a/android_webview/native/aw_gl_functor.h b/android_webview/browser/aw_gl_functor.h similarity index 90% rename from android_webview/native/aw_gl_functor.h rename to android_webview/browser/aw_gl_functor.h index 0899beb..108b2e95 100644 --- a/android_webview/native/aw_gl_functor.h +++ b/android_webview/browser/aw_gl_functor.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_NATIVE_AW_GL_FUNCTOR_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_GL_FUNCTOR_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_GL_FUNCTOR_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_GL_FUNCTOR_H_ #include <jni.h> @@ -43,4 +43,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_GL_FUNCTOR_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_GL_FUNCTOR_H_
diff --git a/android_webview/native/aw_http_auth_handler.cc b/android_webview/browser/aw_http_auth_handler.cc similarity index 90% rename from android_webview/native/aw_http_auth_handler.cc rename to android_webview/browser/aw_http_auth_handler.cc index 263bf7f..d0a22db 100644 --- a/android_webview/native/aw_http_auth_handler.cc +++ b/android_webview/browser/aw_http_auth_handler.cc
@@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/native/aw_http_auth_handler.h" +#include "android_webview/browser/aw_http_auth_handler.h" +#include "android_webview/browser/aw_contents.h" #include "android_webview/browser/aw_login_delegate.h" -#include "android_webview/native/aw_contents.h" #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/web_contents.h" #include "jni/AwHttpAuthHandler_jni.h" #include "net/base/auth.h" -#include "content/public/browser/web_contents.h" using base::android::ConvertJavaStringToUTF16; using base::android::JavaParamRef; @@ -27,12 +27,11 @@ realm_(auth_info->realm) { DCHECK_CURRENTLY_ON(BrowserThread::UI); JNIEnv* env = base::android::AttachCurrentThread(); - http_auth_handler_.Reset( - Java_AwHttpAuthHandler_create( - env, reinterpret_cast<intptr_t>(this), first_auth_attempt)); + http_auth_handler_.Reset(Java_AwHttpAuthHandler_create( + env, reinterpret_cast<intptr_t>(this), first_auth_attempt)); } -AwHttpAuthHandler:: ~AwHttpAuthHandler() { +AwHttpAuthHandler::~AwHttpAuthHandler() { DCHECK_CURRENTLY_ON(BrowserThread::UI); Java_AwHttpAuthHandler_handlerDestroyed(base::android::AttachCurrentThread(), http_auth_handler_);
diff --git a/android_webview/native/aw_http_auth_handler.h b/android_webview/browser/aw_http_auth_handler.h similarity index 90% rename from android_webview/native/aw_http_auth_handler.h rename to android_webview/browser/aw_http_auth_handler.h index 09f6ed12..5fdc9881 100644 --- a/android_webview/native/aw_http_auth_handler.h +++ b/android_webview/browser/aw_http_auth_handler.h
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ANDROID_WEBVIEW_NATIVE_AW_HTTP_AUTH_HANDLER_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_HTTP_AUTH_HANDLER_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_HTTP_AUTH_HANDLER_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_HTTP_AUTH_HANDLER_H_ #include <jni.h> #include <string> -#include "android_webview/browser/aw_login_delegate.h" #include "android_webview/browser/aw_http_auth_handler_base.h" +#include "android_webview/browser/aw_login_delegate.h" #include "base/android/jni_android.h" #include "base/android/scoped_java_ref.h" #include "base/memory/ref_counted.h" @@ -54,4 +54,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_HTTP_AUTH_HANDLER_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_HTTP_AUTH_HANDLER_H_
diff --git a/android_webview/native/aw_locale_manager_impl.cc b/android_webview/browser/aw_locale_manager_impl.cc similarity index 66% rename from android_webview/native/aw_locale_manager_impl.cc rename to android_webview/browser/aw_locale_manager_impl.cc index 0657c1ec..e229d1b 100644 --- a/android_webview/native/aw_locale_manager_impl.cc +++ b/android_webview/browser/aw_locale_manager_impl.cc
@@ -2,17 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/native/aw_locale_manager_impl.h" +#include "android_webview/browser/aw_locale_manager_impl.h" -#include "android_webview/native/aw_contents.h" +#include "android_webview/browser/aw_contents.h" namespace android_webview { -AwLocaleManagerImpl::AwLocaleManagerImpl() { -} +AwLocaleManagerImpl::AwLocaleManagerImpl() {} -AwLocaleManagerImpl::~AwLocaleManagerImpl() { -} +AwLocaleManagerImpl::~AwLocaleManagerImpl() {} std::string AwLocaleManagerImpl::GetLocale() { return AwContents::GetLocale();
diff --git a/android_webview/native/aw_locale_manager_impl.h b/android_webview/browser/aw_locale_manager_impl.h similarity index 76% rename from android_webview/native/aw_locale_manager_impl.h rename to android_webview/browser/aw_locale_manager_impl.h index c6d142e..01a12ef 100644 --- a/android_webview/native/aw_locale_manager_impl.h +++ b/android_webview/browser/aw_locale_manager_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_NATIVE_AW_LOCALE_MANAGER_IMPL_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_LOCALE_MANAGER_IMPL_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_LOCALE_MANAGER_IMPL_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_LOCALE_MANAGER_IMPL_H_ #include "android_webview/browser/aw_locale_manager.h" @@ -26,4 +26,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_LOCALE_MANAGER_IMPL_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_LOCALE_MANAGER_IMPL_H_
diff --git a/android_webview/native/aw_media_url_interceptor.cc b/android_webview/browser/aw_media_url_interceptor.cc similarity index 85% rename from android_webview/native/aw_media_url_interceptor.cc rename to android_webview/browser/aw_media_url_interceptor.cc index 3ec6eea..1476aca 100644 --- a/android_webview/native/aw_media_url_interceptor.cc +++ b/android_webview/browser/aw_media_url_interceptor.cc
@@ -4,8 +4,8 @@ #include <string> +#include "android_webview/browser/aw_media_url_interceptor.h" #include "android_webview/common/url_constants.h" -#include "android_webview/native/aw_media_url_interceptor.h" #include "base/android/apk_assets.h" #include "base/strings/string_util.h" #include "content/public/common/url_constants.h" @@ -22,8 +22,8 @@ if (base::StartsWith(url, asset_file_prefix, base::CompareCase::SENSITIVE)) { std::string filename(url); - base::ReplaceFirstSubstringAfterOffset( - &filename, 0, asset_file_prefix, "assets/"); + base::ReplaceFirstSubstringAfterOffset(&filename, 0, asset_file_prefix, + "assets/"); base::MemoryMappedFile::Region region = base::MemoryMappedFile::Region::kWholeFile; *fd = base::android::OpenApkAsset(filename, ®ion);
diff --git a/android_webview/native/aw_media_url_interceptor.h b/android_webview/browser/aw_media_url_interceptor.h similarity index 77% rename from android_webview/native/aw_media_url_interceptor.h rename to android_webview/browser/aw_media_url_interceptor.h index 4f46e4d..88447e4 100644 --- a/android_webview/native/aw_media_url_interceptor.h +++ b/android_webview/browser/aw_media_url_interceptor.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_NATIVE_AW_MEDIA_URL_INTERCEPTOR_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_MEDIA_URL_INTERCEPTOR_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_MEDIA_URL_INTERCEPTOR_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_MEDIA_URL_INTERCEPTOR_H_ #include <stdint.h> @@ -25,4 +25,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_MEDIA_URL_INTERCEPTOR_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_MEDIA_URL_INTERCEPTOR_H_
diff --git a/android_webview/native/aw_media_url_interceptor_unittest.cc b/android_webview/browser/aw_media_url_interceptor_unittest.cc similarity index 68% rename from android_webview/native/aw_media_url_interceptor_unittest.cc rename to android_webview/browser/aw_media_url_interceptor_unittest.cc index b43dab9..aa8c226 100644 --- a/android_webview/native/aw_media_url_interceptor_unittest.cc +++ b/android_webview/browser/aw_media_url_interceptor_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/native/aw_media_url_interceptor.h" +#include "android_webview/browser/aw_media_url_interceptor.h" #include <memory> #include <string> @@ -20,15 +20,17 @@ class AwMediaUrlInterceptorTest : public Test { public: - AwMediaUrlInterceptorTest() - : fd_(UNSET_VALUE), offset_(UNSET_VALUE), size_(UNSET_VALUE), - url_interceptor_(new AwMediaUrlInterceptor()){ - } + AwMediaUrlInterceptorTest() + : fd_(UNSET_VALUE), + offset_(UNSET_VALUE), + size_(UNSET_VALUE), + url_interceptor_(new AwMediaUrlInterceptor()) {} + protected: - int fd_; - int64_t offset_; - int64_t size_; - std::unique_ptr<AwMediaUrlInterceptor> url_interceptor_; + int fd_; + int64_t offset_; + int64_t size_; + std::unique_ptr<AwMediaUrlInterceptor> url_interceptor_; }; } // namespace @@ -36,11 +38,10 @@ TEST_F(AwMediaUrlInterceptorTest, TestInterceptValidAssetUrl) { // This asset file exists in the android_webview_unittests-debug.apk. // See gyp rule android_webview_unittests_apk. - const std::string valid_asset_url( - "file:///android_asset/asset_file.ogg"); + const std::string valid_asset_url("file:///android_asset/asset_file.ogg"); - ASSERT_TRUE(url_interceptor_->Intercept( - valid_asset_url, &fd_, &offset_, &size_)); + ASSERT_TRUE( + url_interceptor_->Intercept(valid_asset_url, &fd_, &offset_, &size_)); EXPECT_NE(UNSET_VALUE, fd_); EXPECT_NE(UNSET_VALUE, offset_); EXPECT_NE(UNSET_VALUE, size_); @@ -52,8 +53,8 @@ const std::string invalid_asset_url( "file:///android_asset/file_does_not_exist.ogg"); - ASSERT_FALSE(url_interceptor_->Intercept( - invalid_asset_url, &fd_, &offset_, &size_)); + ASSERT_FALSE( + url_interceptor_->Intercept(invalid_asset_url, &fd_, &offset_, &size_)); EXPECT_EQ(UNSET_VALUE, fd_); EXPECT_EQ(UNSET_VALUE, offset_); EXPECT_EQ(UNSET_VALUE, size_); @@ -63,8 +64,8 @@ // This url does not refer to an asset in the apk. const std::string non_asset_url("file:///sdcard/file.txt"); - ASSERT_FALSE(url_interceptor_->Intercept( - non_asset_url, &fd_, &offset_, &size_)); + ASSERT_FALSE( + url_interceptor_->Intercept(non_asset_url, &fd_, &offset_, &size_)); EXPECT_EQ(UNSET_VALUE, fd_); EXPECT_EQ(UNSET_VALUE, offset_); EXPECT_EQ(UNSET_VALUE, size_);
diff --git a/android_webview/native/aw_metrics_log_uploader.cc b/android_webview/browser/aw_metrics_log_uploader.cc similarity index 96% rename from android_webview/native/aw_metrics_log_uploader.cc rename to android_webview/browser/aw_metrics_log_uploader.cc index fb714b8..c79eeb1 100644 --- a/android_webview/native/aw_metrics_log_uploader.cc +++ b/android_webview/browser/aw_metrics_log_uploader.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/native/aw_metrics_log_uploader.h" +#include "android_webview/browser/aw_metrics_log_uploader.h" #include "android_webview/jni/AwMetricsLogUploader_jni.h" #include "base/android/jni_array.h"
diff --git a/android_webview/native/aw_metrics_log_uploader.h b/android_webview/browser/aw_metrics_log_uploader.h similarity index 83% rename from android_webview/native/aw_metrics_log_uploader.h rename to android_webview/browser/aw_metrics_log_uploader.h index e8e0458c..91dabde 100644 --- a/android_webview/native/aw_metrics_log_uploader.h +++ b/android_webview/browser/aw_metrics_log_uploader.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_NATIVE_AW_METRICS_LOG_UPLOADER_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_METRICS_LOG_UPLOADER_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_METRICS_LOG_UPLOADER_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_METRICS_LOG_UPLOADER_H_ #include <jni.h> #include <string> @@ -32,4 +32,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_METRICS_LOG_UPLOADER_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_METRICS_LOG_UPLOADER_H_
diff --git a/android_webview/native/aw_metrics_service_client_impl.cc b/android_webview/browser/aw_metrics_service_client_impl.cc similarity index 94% rename from android_webview/native/aw_metrics_service_client_impl.cc rename to android_webview/browser/aw_metrics_service_client_impl.cc index 381fb98..2baf2a15 100644 --- a/android_webview/native/aw_metrics_service_client_impl.cc +++ b/android_webview/browser/aw_metrics_service_client_impl.cc
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/native/aw_metrics_service_client_impl.h" +#include "android_webview/browser/aw_metrics_service_client_impl.h" +#include "android_webview/browser/aw_metrics_log_uploader.h" #include "android_webview/common/aw_version_info_values.h" #include "android_webview/jni/AwMetricsServiceClient_jni.h" -#include "android_webview/native/aw_metrics_log_uploader.h" #include "base/android/build_info.h" #include "base/bind.h" #include "base/files/file_util.h" @@ -82,7 +82,7 @@ const base::FilePath guid_file_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(pref_service_ == nullptr); // Initialize should only happen once. + DCHECK(pref_service_ == nullptr); // Initialize should only happen once. DCHECK(request_context_ == nullptr); pref_service_ = pref_service; request_context_ = request_context; @@ -93,8 +93,7 @@ // GUID, and then pick up where we left off, back on the UI thread, in // InitializeWithGUID. content::BrowserThread::PostTaskAndReply( - content::BrowserThread::FILE, - FROM_HERE, + content::BrowserThread::FILE, FROM_HERE, base::Bind(&GetOrCreateGUID, guid_file_path, guid), base::Bind(&AwMetricsServiceClientImpl::InitializeWithGUID, base::Unretained(this), base::Owned(guid))); @@ -226,17 +225,14 @@ } AwMetricsServiceClientImpl::AwMetricsServiceClientImpl() - : is_enabled_(false), - pref_service_(nullptr), - request_context_(nullptr) {} + : is_enabled_(false), pref_service_(nullptr), request_context_(nullptr) {} AwMetricsServiceClientImpl::~AwMetricsServiceClientImpl() {} // static -void SetMetricsEnabled( - JNIEnv* env, - const base::android::JavaParamRef<jclass>& jcaller, - jboolean enabled) { +void SetMetricsEnabled(JNIEnv* env, + const base::android::JavaParamRef<jclass>& jcaller, + jboolean enabled) { g_lazy_instance_.Pointer()->SetMetricsEnabled(enabled); }
diff --git a/android_webview/native/aw_metrics_service_client_impl.h b/android_webview/browser/aw_metrics_service_client_impl.h similarity index 93% rename from android_webview/native/aw_metrics_service_client_impl.h rename to android_webview/browser/aw_metrics_service_client_impl.h index 4471c6e..33ab2cb 100644 --- a/android_webview/native/aw_metrics_service_client_impl.h +++ b/android_webview/browser/aw_metrics_service_client_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_NATIVE_AW_METRICS_SERVICE_CLIENT_IMPL_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_METRICS_SERVICE_CLIENT_IMPL_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_METRICS_SERVICE_CLIENT_IMPL_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_METRICS_SERVICE_CLIENT_IMPL_H_ #include <jni.h> #include <memory> @@ -80,4 +80,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_METRICS_SERVICE_CLIENT_IMPL_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_METRICS_SERVICE_CLIENT_IMPL_H_
diff --git a/android_webview/native/aw_pdf_exporter.cc b/android_webview/browser/aw_pdf_exporter.cc similarity index 84% rename from android_webview/native/aw_pdf_exporter.cc rename to android_webview/browser/aw_pdf_exporter.cc index 2197a3e0..6ba16f5 100644 --- a/android_webview/native/aw_pdf_exporter.cc +++ b/android_webview/browser/aw_pdf_exporter.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/native/aw_pdf_exporter.h" +#include "android_webview/browser/aw_pdf_exporter.h" #include "android_webview/browser/aw_print_manager.h" #include "base/android/jni_android.h" @@ -40,8 +40,8 @@ content::WebContents* web_contents) : java_ref_(env, obj), web_contents_(web_contents) { DCHECK(!obj.is_null()); - Java_AwPdfExporter_setNativeAwPdfExporter( - env, obj, reinterpret_cast<intptr_t>(this)); + Java_AwPdfExporter_setNativeAwPdfExporter(env, obj, + reinterpret_cast<intptr_t>(this)); } AwPdfExporter::~AwPdfExporter() { @@ -63,10 +63,9 @@ printing::PageRanges page_ranges; GetPageRanges(env, pages, &page_ranges); InitPdfSettings(env, obj, page_ranges, print_settings); - AwPrintManager* print_manager = - AwPrintManager::CreateForWebContents( - web_contents_, print_settings, base::FileDescriptor(fd, false), - base::Bind(&AwPdfExporter::DidExportPdf, base::Unretained(this))); + AwPrintManager* print_manager = AwPrintManager::CreateForWebContents( + web_contents_, print_settings, base::FileDescriptor(fd, false), + base::Bind(&AwPdfExporter::DidExportPdf, base::Unretained(this))); if (!print_manager->PrintNow()) DidExportPdf(fd, false); @@ -102,16 +101,12 @@ // TODO(sgurun) verify that the value for newly added parameter for // (i.e. landscape_needs_flip) is correct. settings.SetPrinterPrintableArea(physical_size_device_units, - printable_area_device_units, - true); + printable_area_device_units, true); printing::PageMargins margins; - margins.left = - MilsToDots(Java_AwPdfExporter_getLeftMargin(env, obj), dpi); - margins.right = - MilsToDots(Java_AwPdfExporter_getRightMargin(env, obj), dpi); - margins.top = - MilsToDots(Java_AwPdfExporter_getTopMargin(env, obj), dpi); + margins.left = MilsToDots(Java_AwPdfExporter_getLeftMargin(env, obj), dpi); + margins.right = MilsToDots(Java_AwPdfExporter_getRightMargin(env, obj), dpi); + margins.top = MilsToDots(Java_AwPdfExporter_getTopMargin(env, obj), dpi); margins.bottom = MilsToDots(Java_AwPdfExporter_getBottomMargin(env, obj), dpi); settings.SetCustomMargins(margins);
diff --git a/android_webview/native/aw_pdf_exporter.h b/android_webview/browser/aw_pdf_exporter.h similarity index 89% rename from android_webview/native/aw_pdf_exporter.h rename to android_webview/browser/aw_pdf_exporter.h index 6145e86..8ca42899 100644 --- a/android_webview/native/aw_pdf_exporter.h +++ b/android_webview/browser/aw_pdf_exporter.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_NATIVE_AW_PDF_EXPORTER_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_PDF_EXPORTER_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_PDF_EXPORTER_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_PDF_EXPORTER_H_ #include <jni.h> @@ -54,4 +54,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_PDF_EXPORTER_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_PDF_EXPORTER_H_
diff --git a/android_webview/native/aw_picture.cc b/android_webview/browser/aw_picture.cc similarity index 87% rename from android_webview/native/aw_picture.cc rename to android_webview/browser/aw_picture.cc index edc2003e..8b50268 100644 --- a/android_webview/native/aw_picture.cc +++ b/android_webview/browser/aw_picture.cc
@@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/native/aw_picture.h" +#include "android_webview/browser/aw_picture.h" -#include "android_webview/native/java_browser_view_renderer_helper.h" +#include "android_webview/browser/java_browser_view_renderer_helper.h" #include "base/bind.h" #include "jni/AwPicture_jni.h" #include "third_party/skia/include/core/SkPicture.h" @@ -13,8 +13,7 @@ namespace android_webview { -AwPicture::AwPicture(sk_sp<SkPicture> picture) - : picture_(std::move(picture)) { +AwPicture::AwPicture(sk_sp<SkPicture> picture) : picture_(std::move(picture)) { DCHECK(picture_); }
diff --git a/android_webview/native/aw_picture.h b/android_webview/browser/aw_picture.h similarity index 92% rename from android_webview/native/aw_picture.h rename to android_webview/browser/aw_picture.h index 84a0e65..e6b39b1 100644 --- a/android_webview/native/aw_picture.h +++ b/android_webview/browser/aw_picture.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_NATIVE_AW_PICTURE_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_PICTURE_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_PICTURE_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_PICTURE_H_ #include <jni.h>
diff --git a/android_webview/native/aw_quota_manager_bridge_impl.cc b/android_webview/browser/aw_quota_manager_bridge_impl.cc similarity index 81% rename from android_webview/native/aw_quota_manager_bridge_impl.cc rename to android_webview/browser/aw_quota_manager_bridge_impl.cc index 85d45b6..b4bdc5820 100644 --- a/android_webview/native/aw_quota_manager_bridge_impl.cc +++ b/android_webview/browser/aw_quota_manager_bridge_impl.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/native/aw_quota_manager_bridge_impl.h" +#include "android_webview/browser/aw_quota_manager_bridge_impl.h" #include <set> @@ -37,9 +37,8 @@ // are destroyed at the end of DoneOnUIThread. class GetOriginsTask : public base::RefCountedThreadSafe<GetOriginsTask> { public: - GetOriginsTask( - const AwQuotaManagerBridgeImpl::GetOriginsCallback& callback, - QuotaManager* quota_manager); + GetOriginsTask(const AwQuotaManagerBridgeImpl::GetOriginsCallback& callback, + QuotaManager* quota_manager); void Run(); @@ -74,8 +73,7 @@ GetOriginsTask::GetOriginsTask( const AwQuotaManagerBridgeImpl::GetOriginsCallback& callback, QuotaManager* quota_manager) - : ui_callback_(callback), - quota_manager_(quota_manager) { + : ui_callback_(callback), quota_manager_(quota_manager) { DCHECK_CURRENTLY_ON(BrowserThread::UI); } @@ -84,10 +82,8 @@ void GetOriginsTask::Run() { DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserThread::PostTask( - BrowserThread::IO, - FROM_HERE, - base::Bind(&QuotaManager::GetOriginsModifiedSince, - quota_manager_, + BrowserThread::IO, FROM_HERE, + base::Bind(&QuotaManager::GetOriginsModifiedSince, quota_manager_, storage::kStorageTypeTemporary, base::Time() /* Since beginning of time. */, base::Bind(&GetOriginsTask::OnOriginsObtained, this))); @@ -100,11 +96,9 @@ num_callbacks_received_ = 0u; for (std::set<GURL>::const_iterator origin = origins.begin(); - origin != origins.end(); - ++origin) { + origin != origins.end(); ++origin) { quota_manager_->GetUsageAndQuota( - *origin, - type, + *origin, type, base::Bind(&GetOriginsTask::OnUsageAndQuotaObtained, this, *origin)); } @@ -130,10 +124,8 @@ void GetOriginsTask::CheckDone() { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (num_callbacks_received_ == num_callbacks_to_wait_) { - BrowserThread::PostTask( - BrowserThread::UI, - FROM_HERE, - base::Bind(&GetOriginsTask::DoneOnUIThread, this)); + BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, + base::Bind(&GetOriginsTask::DoneOnUIThread, this)); } else if (num_callbacks_received_ > num_callbacks_to_wait_) { NOTREACHED(); } @@ -155,7 +147,6 @@ } // namespace - // static jlong GetDefaultNativeAwQuotaManagerBridge(JNIEnv* env, const JavaParamRef<jclass>& clazz) { @@ -176,9 +167,7 @@ AwQuotaManagerBridgeImpl::AwQuotaManagerBridgeImpl( AwBrowserContext* browser_context) - : browser_context_(browser_context), - weak_factory_(this) { -} + : browser_context_(browser_context), weak_factory_(this) {} AwQuotaManagerBridgeImpl::~AwQuotaManagerBridgeImpl() {} @@ -208,8 +197,8 @@ void AwQuotaManagerBridgeImpl::DeleteAllData( JNIEnv* env, const JavaParamRef<jobject>& object) { - RunOnUIThread(base::Bind(&AwQuotaManagerBridgeImpl::DeleteAllDataOnUiThread, - this)); + RunOnUIThread( + base::Bind(&AwQuotaManagerBridgeImpl::DeleteAllDataOnUiThread, this)); } void AwQuotaManagerBridgeImpl::DeleteAllDataOnUiThread() { @@ -221,9 +210,9 @@ StoragePartition::REMOVE_DATA_MASK_INDEXEDDB | StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE | StoragePartition::REMOVE_DATA_MASK_WEBSQL, - StoragePartition::QUOTA_MANAGED_STORAGE_MASK_TEMPORARY, - GURL(), StoragePartition::OriginMatcherFunction(), - base::Time(), base::Time::Max(), base::Bind(&base::DoNothing)); + StoragePartition::QUOTA_MANAGED_STORAGE_MASK_TEMPORARY, GURL(), + StoragePartition::OriginMatcherFunction(), base::Time(), + base::Time::Max(), base::Bind(&base::DoNothing)); } void AwQuotaManagerBridgeImpl::DeleteOrigin( @@ -233,8 +222,7 @@ base::string16 origin_string( base::android::ConvertJavaStringToUTF16(env, origin)); RunOnUIThread(base::Bind(&AwQuotaManagerBridgeImpl::DeleteOriginOnUiThread, - this, - origin_string)); + this, origin_string)); } void AwQuotaManagerBridgeImpl::DeleteOriginOnUiThread( @@ -247,27 +235,23 @@ StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS | StoragePartition::REMOVE_DATA_MASK_INDEXEDDB | StoragePartition::REMOVE_DATA_MASK_WEBSQL, - StoragePartition::QUOTA_MANAGED_STORAGE_MASK_TEMPORARY, - GURL(origin), - storage_partition->GetURLRequestContext(), - base::Bind(&base::DoNothing)); + StoragePartition::QUOTA_MANAGED_STORAGE_MASK_TEMPORARY, GURL(origin), + storage_partition->GetURLRequestContext(), base::Bind(&base::DoNothing)); } void AwQuotaManagerBridgeImpl::GetOrigins(JNIEnv* env, const JavaParamRef<jobject>& object, jint callback_id) { RunOnUIThread(base::Bind(&AwQuotaManagerBridgeImpl::GetOriginsOnUiThread, - this, - callback_id)); + this, callback_id)); } void AwQuotaManagerBridgeImpl::GetOriginsOnUiThread(jint callback_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - const GetOriginsCallback ui_callback = base::Bind( - &AwQuotaManagerBridgeImpl::GetOriginsCallbackImpl, - weak_factory_.GetWeakPtr(), - callback_id); + const GetOriginsCallback ui_callback = + base::Bind(&AwQuotaManagerBridgeImpl::GetOriginsCallbackImpl, + weak_factory_.GetWeakPtr(), callback_id); (new GetOriginsTask(ui_callback, GetQuotaManager()))->Run(); } @@ -301,13 +285,11 @@ usage = 0; quota = 0; } - BrowserThread::PostTask( - BrowserThread::UI, - FROM_HERE, - base::Bind(ui_callback, usage, quota)); + BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, + base::Bind(ui_callback, usage, quota)); } -} // namespace +} // namespace void AwQuotaManagerBridgeImpl::GetUsageAndQuotaForOrigin( JNIEnv* env, @@ -317,12 +299,9 @@ bool is_quota) { base::string16 origin_string( base::android::ConvertJavaStringToUTF16(env, origin)); - RunOnUIThread(base::Bind( - &AwQuotaManagerBridgeImpl::GetUsageAndQuotaForOriginOnUiThread, - this, - origin_string, - callback_id, - is_quota)); + RunOnUIThread( + base::Bind(&AwQuotaManagerBridgeImpl::GetUsageAndQuotaForOriginOnUiThread, + this, origin_string, callback_id, is_quota)); } void AwQuotaManagerBridgeImpl::GetUsageAndQuotaForOriginOnUiThread( @@ -330,19 +309,14 @@ jint callback_id, bool is_quota) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - const QuotaUsageCallback ui_callback = base::Bind( - &AwQuotaManagerBridgeImpl::QuotaUsageCallbackImpl, - weak_factory_.GetWeakPtr(), - callback_id, - is_quota); + const QuotaUsageCallback ui_callback = + base::Bind(&AwQuotaManagerBridgeImpl::QuotaUsageCallbackImpl, + weak_factory_.GetWeakPtr(), callback_id, is_quota); BrowserThread::PostTask( - BrowserThread::IO, - FROM_HERE, - base::Bind(&QuotaManager::GetUsageAndQuota, - GetQuotaManager(), - GURL(origin), - storage::kStorageTypeTemporary, + BrowserThread::IO, FROM_HERE, + base::Bind(&QuotaManager::GetUsageAndQuota, GetQuotaManager(), + GURL(origin), storage::kStorageTypeTemporary, base::Bind(&OnUsageAndQuotaObtained, ui_callback))); }
diff --git a/android_webview/native/aw_quota_manager_bridge_impl.h b/android_webview/browser/aw_quota_manager_bridge_impl.h similarity index 93% rename from android_webview/native/aw_quota_manager_bridge_impl.h rename to android_webview/browser/aw_quota_manager_bridge_impl.h index 7478433..054411e 100644 --- a/android_webview/native/aw_quota_manager_bridge_impl.h +++ b/android_webview/browser/aw_quota_manager_bridge_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_NATIVE_AW_QUOTA_MANAGER_BRIDGE_IMPL_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_QUOTA_MANAGER_BRIDGE_IMPL_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_QUOTA_MANAGER_BRIDGE_IMPL_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_QUOTA_MANAGER_BRIDGE_IMPL_H_ #include <jni.h> #include <stdint.h> @@ -96,4 +96,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_QUOTA_MANAGER_BRIDGE_IMPL_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_QUOTA_MANAGER_BRIDGE_IMPL_H_
diff --git a/android_webview/native/aw_renderer_priority_manager.cc b/android_webview/browser/aw_renderer_priority_manager.cc similarity index 95% rename from android_webview/native/aw_renderer_priority_manager.cc rename to android_webview/browser/aw_renderer_priority_manager.cc index c19f323..a062988 100644 --- a/android_webview/native/aw_renderer_priority_manager.cc +++ b/android_webview/browser/aw_renderer_priority_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/native/aw_renderer_priority_manager.h" +#include "android_webview/browser/aw_renderer_priority_manager.h" #include "base/android/jni_android.h" #include "content/public/browser/browser_thread.h"
diff --git a/android_webview/native/aw_renderer_priority_manager.h b/android_webview/browser/aw_renderer_priority_manager.h similarity index 100% rename from android_webview/native/aw_renderer_priority_manager.h rename to android_webview/browser/aw_renderer_priority_manager.h
diff --git a/android_webview/native/aw_resource.cc b/android_webview/browser/aw_resource.cc similarity index 100% rename from android_webview/native/aw_resource.cc rename to android_webview/browser/aw_resource.cc
diff --git a/android_webview/native/aw_settings.cc b/android_webview/browser/aw_settings.cc similarity index 94% rename from android_webview/native/aw_settings.cc rename to android_webview/browser/aw_settings.cc index e596533..e1321b4 100644 --- a/android_webview/native/aw_settings.cc +++ b/android_webview/browser/aw_settings.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/native/aw_settings.h" +#include "android_webview/browser/aw_settings.h" #include "android_webview/browser/aw_content_browser_client.h" +#include "android_webview/browser/aw_contents.h" #include "android_webview/browser/renderer_host/aw_render_view_host_ext.h" #include "android_webview/common/aw_content_client.h" -#include "android_webview/native/aw_contents.h" #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/macros.h" @@ -38,7 +38,8 @@ content::TAP_MULTIPLE_TARGETS_STRATEGY_NONE; // TODO(boliu): Deduplicate with chrome/ code. - CR_DEFINE_STATIC_LOCAL(const gfx::FontRenderParams, params, + CR_DEFINE_STATIC_LOCAL( + const gfx::FontRenderParams, params, (gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), NULL))); prefs->should_antialias_text = params.antialiasing; prefs->use_subpixel_positioning = params.subpixel_positioning; @@ -106,16 +107,19 @@ } AwRenderViewHostExt* AwSettings::GetAwRenderViewHostExt() { - if (!web_contents()) return NULL; + if (!web_contents()) + return NULL; AwContents* contents = AwContents::FromWebContents(web_contents()); - if (!contents) return NULL; + if (!contents) + return NULL; return contents->render_view_host_ext(); } void AwSettings::ResetScrollAndScaleState(JNIEnv* env, const JavaParamRef<jobject>& obj) { AwRenderViewHostExt* rvhe = GetAwRenderViewHostExt(); - if (!rvhe) return; + if (!rvhe) + return; rvhe->ResetScrollAndScaleState(); } @@ -142,7 +146,8 @@ void AwSettings::UpdateUserAgentLocked(JNIEnv* env, const JavaParamRef<jobject>& obj) { - if (!web_contents()) return; + if (!web_contents()) + return; ScopedJavaLocalRef<jstring> str = Java_AwSettings_getUserAgentLocked(env, obj); @@ -162,13 +167,16 @@ void AwSettings::UpdateWebkitPreferencesLocked( JNIEnv* env, const JavaParamRef<jobject>& obj) { - if (!web_contents()) return; + if (!web_contents()) + return; AwRenderViewHostExt* render_view_host_ext = GetAwRenderViewHostExt(); - if (!render_view_host_ext) return; + if (!render_view_host_ext) + return; content::RenderViewHost* render_view_host = web_contents()->GetRenderViewHost(); - if (!render_view_host) return; + if (!render_view_host) + return; render_view_host->OnWebkitPreferencesChanged(); } @@ -176,15 +184,16 @@ JNIEnv* env, const JavaParamRef<jobject>& obj) { AwRenderViewHostExt* rvhe = GetAwRenderViewHostExt(); - if (!rvhe) return; + if (!rvhe) + return; float initial_page_scale_percent = Java_AwSettings_getInitialPageScalePercentLocked(env, obj); if (initial_page_scale_percent == 0) { rvhe->SetInitialPageScale(-1); } else { - float dip_scale = static_cast<float>( - Java_AwSettings_getDIPScaleLocked(env, obj)); + float dip_scale = + static_cast<float>(Java_AwSettings_getDIPScaleLocked(env, obj)); rvhe->SetInitialPageScale(initial_page_scale_percent / dip_scale / 100.0f); } } @@ -192,9 +201,11 @@ void AwSettings::UpdateFormDataPreferencesLocked( JNIEnv* env, const JavaParamRef<jobject>& obj) { - if (!web_contents()) return; + if (!web_contents()) + return; AwContents* contents = AwContents::FromWebContents(web_contents()); - if (!contents) return; + if (!contents) + return; contents->SetSaveFormData(Java_AwSettings_getSaveFormDataLocked(env, obj)); } @@ -202,7 +213,8 @@ void AwSettings::UpdateRendererPreferencesLocked( JNIEnv* env, const JavaParamRef<jobject>& obj) { - if (!web_contents()) return; + if (!web_contents()) + return; bool update_prefs = false; RendererPreferences* prefs = web_contents()->GetMutableRendererPrefs(); @@ -260,7 +272,8 @@ const JavaParamRef<jobject>& obj, jlong web_prefs_ptr) { AwRenderViewHostExt* render_view_host_ext = GetAwRenderViewHostExt(); - if (!render_view_host_ext) return; + if (!render_view_host_ext) + return; WebPreferences* web_prefs = reinterpret_cast<WebPreferences*>(web_prefs_ptr); PopulateFixedWebPreferences(web_prefs); @@ -376,8 +389,8 @@ ScopedJavaLocalRef<jstring> url = Java_AwSettings_getDefaultVideoPosterURLLocked(env, obj); - web_prefs->default_video_poster_url = url.obj() ? - GURL(ConvertJavaStringToUTF8(url)) : GURL(); + web_prefs->default_video_poster_url = + url.obj() ? GURL(ConvertJavaStringToUTF8(url)) : GURL(); bool support_quirks = Java_AwSettings_getSupportLegacyQuirksLocked(env, obj); // Please see the corresponding Blink settings for bug references. @@ -400,8 +413,8 @@ Java_AwSettings_getSpatialNavigationLocked(env, obj); bool enable_supported_hardware_accelerated_features = - Java_AwSettings_getEnableSupportedHardwareAcceleratedFeaturesLocked( - env, obj); + Java_AwSettings_getEnableSupportedHardwareAcceleratedFeaturesLocked(env, + obj); bool accelerated_2d_canvas_enabled_by_switch = web_prefs->accelerated_2d_canvas_enabled; @@ -449,8 +462,8 @@ static jlong Init(JNIEnv* env, const JavaParamRef<jobject>& obj, const JavaParamRef<jobject>& web_contents) { - content::WebContents* contents = content::WebContents::FromJavaWebContents( - web_contents); + content::WebContents* contents = + content::WebContents::FromJavaWebContents(web_contents); AwSettings* settings = new AwSettings(env, obj, contents); return reinterpret_cast<intptr_t>(settings); }
diff --git a/android_webview/native/aw_settings.h b/android_webview/browser/aw_settings.h similarity index 93% rename from android_webview/native/aw_settings.h rename to android_webview/browser/aw_settings.h index 3fe69dc..0b016cc 100644 --- a/android_webview/native/aw_settings.h +++ b/android_webview/browser/aw_settings.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_NATIVE_AW_SETTINGS_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_SETTINGS_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_SETTINGS_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_SETTINGS_H_ #include <jni.h> @@ -13,7 +13,7 @@ #include "base/android/scoped_java_ref.h" #include "content/public/browser/web_contents_observer.h" -namespace content{ +namespace content { struct WebPreferences; } @@ -78,4 +78,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_SETTINGS_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_SETTINGS_H_
diff --git a/android_webview/native/aw_web_contents_delegate.cc b/android_webview/browser/aw_web_contents_delegate.cc similarity index 90% rename from android_webview/native/aw_web_contents_delegate.cc rename to android_webview/browser/aw_web_contents_delegate.cc index 20819bb..7e6b728 100644 --- a/android_webview/native/aw_web_contents_delegate.cc +++ b/android_webview/browser/aw_web_contents_delegate.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 "android_webview/native/aw_web_contents_delegate.h" +#include "android_webview/browser/aw_web_contents_delegate.h" +#include "android_webview/browser/aw_contents.h" +#include "android_webview/browser/aw_contents_io_thread_client_impl.h" #include "android_webview/browser/aw_javascript_dialog_manager.h" #include "android_webview/browser/find_helper.h" -#include "android_webview/native/aw_contents.h" -#include "android_webview/native/aw_contents_io_thread_client_impl.h" -#include "android_webview/native/permission/media_access_permission_request.h" -#include "android_webview/native/permission/permission_request_handler.h" +#include "android_webview/browser/permission/media_access_permission_request.h" +#include "android_webview/browser/permission/permission_request_handler.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" @@ -52,15 +52,10 @@ g_javascript_dialog_manager = LAZY_INSTANCE_INITIALIZER; } -AwWebContentsDelegate::AwWebContentsDelegate( - JNIEnv* env, - jobject obj) - : WebContentsDelegateAndroid(env, obj), - is_fullscreen_(false) { -} +AwWebContentsDelegate::AwWebContentsDelegate(JNIEnv* env, jobject obj) + : WebContentsDelegateAndroid(env, obj), is_fullscreen_(false) {} -AwWebContentsDelegate::~AwWebContentsDelegate() { -} +AwWebContentsDelegate::~AwWebContentsDelegate() {} content::JavaScriptDialogManager* AwWebContentsDelegate::GetJavaScriptDialogManager(WebContents* source) { @@ -77,10 +72,8 @@ if (!aw_contents) return; - aw_contents->GetFindHelper()->HandleFindReply(request_id, - number_of_matches, - active_match_ordinal, - final_update); + aw_contents->GetFindHelper()->HandleFindReply( + request_id, number_of_matches, active_match_ordinal, final_update); } void AwWebContentsDelegate::CanDownload( @@ -247,7 +240,8 @@ } void AwWebContentsDelegate::EnterFullscreenModeForTab( - content::WebContents* web_contents, const GURL& origin) { + content::WebContents* web_contents, + const GURL& origin) { WebContentsDelegateAndroid::EnterFullscreenModeForTab(web_contents, origin); is_fullscreen_ = true; web_contents->GetRenderViewHost()->GetWidget()->WasResized(); @@ -291,11 +285,13 @@ GURL url(file_path_str[i]); if (!url.is_valid()) continue; - base::FilePath path(url.SchemeIsFile() ? - net::UnescapeURLComponent(url.path(), - net::UnescapeRule::SPACES | - net::UnescapeRule::URL_SPECIAL_CHARS_EXCEPT_PATH_SEPARATORS) : - file_path_str[i]); + base::FilePath path( + url.SchemeIsFile() + ? net::UnescapeURLComponent( + url.path(), net::UnescapeRule::SPACES | + net::UnescapeRule:: + URL_SPECIAL_CHARS_EXCEPT_PATH_SEPARATORS) + : file_path_str[i]); content::FileChooserFileInfo file_info; file_info.file_path = path; if (!display_name_str[i].empty())
diff --git a/android_webview/native/aw_web_contents_delegate.h b/android_webview/browser/aw_web_contents_delegate.h similarity index 94% rename from android_webview/native/aw_web_contents_delegate.h rename to android_webview/browser/aw_web_contents_delegate.h index 9211606..f816ddc 100644 --- a/android_webview/native/aw_web_contents_delegate.h +++ b/android_webview/browser/aw_web_contents_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 ANDROID_WEBVIEW_NATIVE_AW_WEB_CONTENTS_DELEGATE_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_WEB_CONTENTS_DELEGATE_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_WEB_CONTENTS_DELEGATE_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_WEB_CONTENTS_DELEGATE_H_ #include <jni.h> @@ -71,4 +71,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_WEB_CONTENTS_DELEGATE_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_WEB_CONTENTS_DELEGATE_H_
diff --git a/android_webview/native/aw_web_contents_view_delegate.cc b/android_webview/browser/aw_web_contents_view_delegate.cc similarity index 95% rename from android_webview/native/aw_web_contents_view_delegate.cc rename to android_webview/browser/aw_web_contents_view_delegate.cc index d42b9a6f..c42bcac1 100644 --- a/android_webview/native/aw_web_contents_view_delegate.cc +++ b/android_webview/browser/aw_web_contents_view_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 "android_webview/native/aw_web_contents_view_delegate.h" +#include "android_webview/browser/aw_web_contents_view_delegate.h" #include "content/public/browser/android/content_view_core.h" #include "content/public/browser/web_contents.h"
diff --git a/android_webview/native/aw_web_contents_view_delegate.h b/android_webview/browser/aw_web_contents_view_delegate.h similarity index 84% rename from android_webview/native/aw_web_contents_view_delegate.h rename to android_webview/browser/aw_web_contents_view_delegate.h index 61958ea..4ae7af4 100644 --- a/android_webview/native/aw_web_contents_view_delegate.h +++ b/android_webview/browser/aw_web_contents_view_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 ANDROID_WEBVIEW_NATIVE_AW_WEB_CONTENTS_VIEW_DELEGATE_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_WEB_CONTENTS_VIEW_DELEGATE_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_WEB_CONTENTS_VIEW_DELEGATE_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_WEB_CONTENTS_VIEW_DELEGATE_H_ #include "content/public/browser/web_contents_view_delegate.h" @@ -39,5 +39,4 @@ } // namespace android_webview - -#endif // ANDROID_WEBVIEW_NATIVE_AW_WEB_CONTENTS_VIEW_DELEGATE_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_WEB_CONTENTS_VIEW_DELEGATE_H_
diff --git a/android_webview/native/aw_web_preferences_populater_impl.cc b/android_webview/browser/aw_web_preferences_populater_impl.cc similarity index 83% rename from android_webview/native/aw_web_preferences_populater_impl.cc rename to android_webview/browser/aw_web_preferences_populater_impl.cc index 5228267..2725969 100644 --- a/android_webview/native/aw_web_preferences_populater_impl.cc +++ b/android_webview/browser/aw_web_preferences_populater_impl.cc
@@ -2,17 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/native/aw_web_preferences_populater_impl.h" +#include "android_webview/browser/aw_web_preferences_populater_impl.h" -#include "android_webview/native/aw_settings.h" +#include "android_webview/browser/aw_settings.h" namespace android_webview { -AwWebPreferencesPopulaterImpl::AwWebPreferencesPopulaterImpl() { -} +AwWebPreferencesPopulaterImpl::AwWebPreferencesPopulaterImpl() {} -AwWebPreferencesPopulaterImpl::~AwWebPreferencesPopulaterImpl() { -} +AwWebPreferencesPopulaterImpl::~AwWebPreferencesPopulaterImpl() {} void AwWebPreferencesPopulaterImpl::PopulateFor( content::WebContents* web_contents,
diff --git a/android_webview/native/aw_web_preferences_populater_impl.h b/android_webview/browser/aw_web_preferences_populater_impl.h similarity index 75% rename from android_webview/native/aw_web_preferences_populater_impl.h rename to android_webview/browser/aw_web_preferences_populater_impl.h index d20e432..e30292da 100644 --- a/android_webview/native/aw_web_preferences_populater_impl.h +++ b/android_webview/browser/aw_web_preferences_populater_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_NATIVE_AW_WEB_PREFERENCES_POPULATER_IMPL_H_ -#define ANDROID_WEBVIEW_NATIVE_AW_WEB_PREFERENCES_POPULATER_IMPL_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_AW_WEB_PREFERENCES_POPULATER_IMPL_H_ +#define ANDROID_WEBVIEW_BROWSER_AW_WEB_PREFERENCES_POPULATER_IMPL_H_ #include "android_webview/browser/aw_web_preferences_populater.h" #include "base/compiler_specific.h" @@ -22,4 +22,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_AW_WEB_PREFERENCES_POPULATER_IMPL_H_ +#endif // ANDROID_WEBVIEW_BROWSER_AW_WEB_PREFERENCES_POPULATER_IMPL_H_
diff --git a/android_webview/native/aw_web_resource_response_impl.cc b/android_webview/browser/aw_web_resource_response_impl.cc similarity index 79% rename from android_webview/native/aw_web_resource_response_impl.cc rename to android_webview/browser/aw_web_resource_response_impl.cc index b65973334..238af75 100644 --- a/android_webview/native/aw_web_resource_response_impl.cc +++ b/android_webview/browser/aw_web_resource_response_impl.cc
@@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/native/aw_web_resource_response_impl.h" +#include "android_webview/browser/aw_web_resource_response_impl.h" -#include "android_webview/native/input_stream_impl.h" +#include "android_webview/browser/input_stream_impl.h" #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" @@ -21,11 +21,9 @@ AwWebResourceResponseImpl::AwWebResourceResponseImpl( const base::android::JavaRef<jobject>& obj) - : java_object_(obj) { -} + : java_object_(obj) {} -AwWebResourceResponseImpl::~AwWebResourceResponseImpl() { -} +AwWebResourceResponseImpl::~AwWebResourceResponseImpl() {} std::unique_ptr<InputStream> AwWebResourceResponseImpl::GetInputStream( JNIEnv* env) const { @@ -37,7 +35,7 @@ } bool AwWebResourceResponseImpl::GetMimeType(JNIEnv* env, - std::string* mime_type) const { + std::string* mime_type) const { ScopedJavaLocalRef<jstring> jstring_mime_type = Java_AwWebResourceResponse_getMimeType(env, java_object_); if (jstring_mime_type.is_null()) @@ -46,8 +44,8 @@ return true; } -bool AwWebResourceResponseImpl::GetCharset( - JNIEnv* env, std::string* charset) const { +bool AwWebResourceResponseImpl::GetCharset(JNIEnv* env, + std::string* charset) const { ScopedJavaLocalRef<jstring> jstring_charset = Java_AwWebResourceResponse_getCharset(env, java_object_); if (jstring_charset.is_null()) @@ -81,12 +79,12 @@ return false; std::vector<std::string> header_names; std::vector<std::string> header_values; - AppendJavaStringArrayToStringVector( - env, jstringArray_headerNames.obj(), &header_names); - AppendJavaStringArrayToStringVector( - env, jstringArray_headerValues.obj(), &header_values); + AppendJavaStringArrayToStringVector(env, jstringArray_headerNames.obj(), + &header_names); + AppendJavaStringArrayToStringVector(env, jstringArray_headerValues.obj(), + &header_values); DCHECK_EQ(header_values.size(), header_names.size()); - for(size_t i = 0; i < header_names.size(); ++i) { + for (size_t i = 0; i < header_names.size(); ++i) { std::string header_line(header_names[i]); header_line.append(": "); header_line.append(header_values[i]); @@ -95,4 +93,4 @@ return true; } -} // namespace android_webview +} // namespace android_webview
diff --git a/android_webview/native/aw_web_resource_response_impl.h b/android_webview/browser/aw_web_resource_response_impl.h similarity index 97% rename from android_webview/native/aw_web_resource_response_impl.h rename to android_webview/browser/aw_web_resource_response_impl.h index 77d748c..b6a12bef 100644 --- a/android_webview/native/aw_web_resource_response_impl.h +++ b/android_webview/browser/aw_web_resource_response_impl.h
@@ -42,6 +42,6 @@ DISALLOW_COPY_AND_ASSIGN(AwWebResourceResponseImpl); }; -} // namespace android_webview +} // namespace android_webview #endif // ANDROID_WEBVIEW_NATIVE_INTERCEPTED_REQUEST_DATA_IMPL_H_
diff --git a/android_webview/native/cookie_manager.cc b/android_webview/browser/cookie_manager.cc similarity index 92% rename from android_webview/native/cookie_manager.cc rename to android_webview/browser/cookie_manager.cc index 33c24db6..1b283e9 100644 --- a/android_webview/native/cookie_manager.cc +++ b/android_webview/browser/cookie_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/native/cookie_manager.h" +#include "android_webview/browser/cookie_manager.h" #include <memory> #include <utility> @@ -252,8 +252,7 @@ cookie_store_task_runner_ = cookie_store_client_thread_.task_runner(); } -CookieManager::~CookieManager() { -} +CookieManager::~CookieManager() {} // Executes the |task| on |cookie_store_task_runner_| and waits for it to // complete before returning. @@ -366,24 +365,19 @@ BoolCallback callback = BoolCookieCallbackHolder::ConvertToCallback(std::move(callback_holder)); ExecCookieTask(base::Bind(&CookieManager::SetCookieHelper, - base::Unretained(this), - host, - cookie_value, + base::Unretained(this), host, cookie_value, callback)); } void CookieManager::SetCookieSync(const GURL& host, - const std::string& cookie_value) { + const std::string& cookie_value) { ExecCookieTaskSync(base::Bind(&CookieManager::SetCookieHelper, - base::Unretained(this), - host, - cookie_value)); + base::Unretained(this), host, cookie_value)); } -void CookieManager::SetCookieHelper( - const GURL& host, - const std::string& value, - const BoolCallback callback) { +void CookieManager::SetCookieHelper(const GURL& host, + const std::string& value, + const BoolCallback callback) { net::CookieOptions options; options.set_include_httponly(); @@ -411,22 +405,20 @@ std::string CookieManager::GetCookie(const GURL& host) { std::string cookie_value; ExecCookieTaskSync(base::Bind(&CookieManager::GetCookieValueAsyncHelper, - base::Unretained(this), - host, - &cookie_value)); + base::Unretained(this), host, &cookie_value)); return cookie_value; } -void CookieManager::GetCookieValueAsyncHelper( - const GURL& host, - std::string* result, - base::Closure complete) { +void CookieManager::GetCookieValueAsyncHelper(const GURL& host, + std::string* result, + base::Closure complete) { net::CookieOptions options; options.set_include_httponly(); GetCookieStore()->GetCookiesWithOptionsAsync( - host, options, base::Bind(&CookieManager::GetCookieValueCompleted, - base::Unretained(this), complete, result)); + host, options, + base::Bind(&CookieManager::GetCookieValueCompleted, + base::Unretained(this), complete, result)); } void CookieManager::GetCookieValueCompleted(base::Closure complete, @@ -441,25 +433,22 @@ BoolCallback callback = BoolCookieCallbackHolder::ConvertToCallback(std::move(callback_holder)); ExecCookieTask(base::Bind(&CookieManager::RemoveSessionCookiesHelper, - base::Unretained(this), - callback)); + base::Unretained(this), callback)); } void CookieManager::RemoveSessionCookiesSync() { ExecCookieTaskSync(base::Bind(&CookieManager::RemoveSessionCookiesHelper, - base::Unretained(this))); + base::Unretained(this))); } -void CookieManager::RemoveSessionCookiesHelper( - BoolCallback callback) { +void CookieManager::RemoveSessionCookiesHelper(BoolCallback callback) { GetCookieStore()->DeleteSessionCookiesAsync( base::Bind(&CookieManager::RemoveCookiesCompleted, base::Unretained(this), callback)); } -void CookieManager::RemoveCookiesCompleted( - BoolCallback callback, - int num_deleted) { +void CookieManager::RemoveCookiesCompleted(BoolCallback callback, + int num_deleted) { callback.Run(num_deleted > 0); } @@ -468,17 +457,15 @@ BoolCallback callback = BoolCookieCallbackHolder::ConvertToCallback(std::move(callback_holder)); ExecCookieTask(base::Bind(&CookieManager::RemoveAllCookiesHelper, - base::Unretained(this), - callback)); + base::Unretained(this), callback)); } void CookieManager::RemoveAllCookiesSync() { ExecCookieTaskSync(base::Bind(&CookieManager::RemoveAllCookiesHelper, - base::Unretained(this))); + base::Unretained(this))); } -void CookieManager::RemoveAllCookiesHelper( - const BoolCallback callback) { +void CookieManager::RemoveAllCookiesHelper(const BoolCallback callback) { GetCookieStore()->DeleteAllAsync( base::Bind(&CookieManager::RemoveCookiesCompleted, base::Unretained(this), callback)); @@ -491,19 +478,17 @@ void CookieManager::FlushCookieStore() { ExecCookieTaskSync(base::Bind(&CookieManager::FlushCookieStoreAsyncHelper, - base::Unretained(this))); + base::Unretained(this))); } -void CookieManager::FlushCookieStoreAsyncHelper( - base::Closure complete) { +void CookieManager::FlushCookieStoreAsyncHelper(base::Closure complete) { GetCookieStore()->FlushStore(complete); } bool CookieManager::HasCookies() { bool has_cookies; ExecCookieTaskSync(base::Bind(&CookieManager::HasCookiesAsyncHelper, - base::Unretained(this), - &has_cookies)); + base::Unretained(this), &has_cookies)); return has_cookies; } @@ -588,7 +573,7 @@ static void RemoveSessionCookiesSync(JNIEnv* env, const JavaParamRef<jobject>& obj) { - CookieManager::GetInstance()->RemoveSessionCookiesSync(); + CookieManager::GetInstance()->RemoveSessionCookiesSync(); } static void RemoveAllCookies(JNIEnv* env,
diff --git a/android_webview/native/cookie_manager.h b/android_webview/browser/cookie_manager.h similarity index 65% rename from android_webview/native/cookie_manager.h rename to android_webview/browser/cookie_manager.h index 2807555..1b4c8b1 100644 --- a/android_webview/native/cookie_manager.h +++ b/android_webview/browser/cookie_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_NATIVE_COOKIE_MANAGER_H_ -#define ANDROID_WEBVIEW_NATIVE_COOKIE_MANAGER_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_COOKIE_MANAGER_H_ +#define ANDROID_WEBVIEW_BROWSER_COOKIE_MANAGER_H_ #include <jni.h> @@ -13,4 +13,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_COOKIE_MANAGER_H_ +#endif // ANDROID_WEBVIEW_BROWSER_COOKIE_MANAGER_H_
diff --git a/android_webview/native/input_stream_impl.cc b/android_webview/browser/input_stream_impl.cc similarity index 94% rename from android_webview/native/input_stream_impl.cc rename to android_webview/browser/input_stream_impl.cc index a2310cf..62b972dd 100644 --- a/android_webview/native/input_stream_impl.cc +++ b/android_webview/browser/input_stream_impl.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/native/input_stream_impl.h" +#include "android_webview/browser/input_stream_impl.h" #include "base/android/jni_android.h" // Disable "Warnings treated as errors" for input_stream_jni as it's a Java @@ -24,7 +24,6 @@ // This should be the same as InputStramUtil.EXCEPTION_THROWN_STATUS. const int kExceptionThrownStatusCode = -2; - } // Maximum number of bytes to be read in a single read. @@ -32,15 +31,14 @@ // static const InputStreamImpl* InputStreamImpl::FromInputStream( - const InputStream* input_stream) { - return static_cast<const InputStreamImpl*>(input_stream); + const InputStream* input_stream) { + return static_cast<const InputStreamImpl*>(input_stream); } // TODO: Use unsafe version for all Java_InputStream methods in this file // once BUG 157880 is fixed and implement graceful exception handling. -InputStreamImpl::InputStreamImpl() { -} +InputStreamImpl::InputStreamImpl() {} InputStreamImpl::InputStreamImpl(const JavaRef<jobject>& stream) : jobject_(stream) { @@ -128,4 +126,4 @@ return true; } -} // namespace android_webview +} // namespace android_webview
diff --git a/android_webview/native/input_stream_impl.h b/android_webview/browser/input_stream_impl.h similarity index 94% rename from android_webview/native/input_stream_impl.h rename to android_webview/browser/input_stream_impl.h index c505663..ef8d91bb 100644 --- a/android_webview/native/input_stream_impl.h +++ b/android_webview/browser/input_stream_impl.h
@@ -50,6 +50,6 @@ DISALLOW_COPY_AND_ASSIGN(InputStreamImpl); }; -} // namespace android_webview +} // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_INPUT_STREAM_H_ +#endif // ANDROID_WEBVIEW_NATIVE_INPUT_STREAM_H_
diff --git a/android_webview/native/input_stream_unittest.cc b/android_webview/browser/input_stream_unittest.cc similarity index 97% rename from android_webview/native/input_stream_unittest.cc rename to android_webview/browser/input_stream_unittest.cc index 5cd8032..5ee9ebf2 100644 --- a/android_webview/native/input_stream_unittest.cc +++ b/android_webview/browser/input_stream_unittest.cc
@@ -4,7 +4,7 @@ #include <memory> -#include "android_webview/native/input_stream_impl.h" +#include "android_webview/browser/input_stream_impl.h" #include "base/android/jni_android.h" #include "base/android/scoped_java_ref.h" #include "jni/InputStreamUnittest_jni.h" @@ -32,8 +32,8 @@ class InputStreamTest : public Test { public: - InputStreamTest() { - } + InputStreamTest() {} + protected: void SetUp() override { env_ = AttachCurrentThread(); @@ -131,7 +131,6 @@ int bytes_available; EXPECT_FALSE(input_stream->BytesAvailable(&bytes_available)); - const int bytes_requested = 10; int bytes_read = 0; scoped_refptr<IOBuffer> buffer = new IOBuffer(bytes_requested);
diff --git a/android_webview/native/java_browser_view_renderer_helper.cc b/android_webview/browser/java_browser_view_renderer_helper.cc similarity index 98% rename from android_webview/native/java_browser_view_renderer_helper.cc rename to android_webview/browser/java_browser_view_renderer_helper.cc index 70eca1d..91992694 100644 --- a/android_webview/native/java_browser_view_renderer_helper.cc +++ b/android_webview/browser/java_browser_view_renderer_helper.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/native/java_browser_view_renderer_helper.h" +#include "android_webview/browser/java_browser_view_renderer_helper.h" #include <android/bitmap.h>
diff --git a/android_webview/native/java_browser_view_renderer_helper.h b/android_webview/browser/java_browser_view_renderer_helper.h similarity index 80% rename from android_webview/native/java_browser_view_renderer_helper.h rename to android_webview/browser/java_browser_view_renderer_helper.h index 266626fb..623fa41 100644 --- a/android_webview/native/java_browser_view_renderer_helper.h +++ b/android_webview/browser/java_browser_view_renderer_helper.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_NATIVE_JAVA_BROWSER_VIEW_RENDERER_HELPER_H_ -#define ANDROID_WEBVIEW_NATIVE_JAVA_BROWSER_VIEW_RENDERER_HELPER_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_JAVA_BROWSER_VIEW_RENDERER_HELPER_H_ +#define ANDROID_WEBVIEW_BROWSER_JAVA_BROWSER_VIEW_RENDERER_HELPER_H_ #include <jni.h> @@ -35,4 +35,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_JAVA_BROWSER_VIEW_RENDERER_HELPER_H_ +#endif // ANDROID_WEBVIEW_BROWSER_JAVA_BROWSER_VIEW_RENDERER_HELPER_H_
diff --git a/android_webview/native/net_init_native_callback.cc b/android_webview/browser/net_init_native_callback.cc similarity index 91% rename from android_webview/native/net_init_native_callback.cc rename to android_webview/browser/net_init_native_callback.cc index 5b3fef3..821dac8 100644 --- a/android_webview/native/net_init_native_callback.cc +++ b/android_webview/browser/net_init_native_callback.cc
@@ -4,8 +4,8 @@ #include "android_webview/browser/net/init_native_callback.h" +#include "android_webview/browser/android_protocol_handler.h" #include "android_webview/browser/net/aw_url_request_job_factory.h" -#include "android_webview/native/android_protocol_handler.h" #include "net/url_request/url_request_interceptor.h" namespace android_webview {
diff --git a/android_webview/native/permission/aw_permission_request.cc b/android_webview/browser/permission/aw_permission_request.cc similarity index 94% rename from android_webview/native/permission/aw_permission_request.cc rename to android_webview/browser/permission/aw_permission_request.cc index 4f2f09b..5426be72 100644 --- a/android_webview/native/permission/aw_permission_request.cc +++ b/android_webview/browser/permission/aw_permission_request.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/native/permission/aw_permission_request.h" +#include "android_webview/browser/permission/aw_permission_request.h" #include <utility> -#include "android_webview/native/permission/aw_permission_request_delegate.h" +#include "android_webview/browser/permission/aw_permission_request_delegate.h" #include "base/android/jni_string.h" #include "jni/AwPermissionRequest_jni.h"
diff --git a/android_webview/native/permission/aw_permission_request.h b/android_webview/browser/permission/aw_permission_request.h similarity index 100% rename from android_webview/native/permission/aw_permission_request.h rename to android_webview/browser/permission/aw_permission_request.h
diff --git a/android_webview/native/permission/aw_permission_request_delegate.cc b/android_webview/browser/permission/aw_permission_request_delegate.cc similarity index 81% rename from android_webview/native/permission/aw_permission_request_delegate.cc rename to android_webview/browser/permission/aw_permission_request_delegate.cc index ed5309f..2205501 100644 --- a/android_webview/native/permission/aw_permission_request_delegate.cc +++ b/android_webview/browser/permission/aw_permission_request_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 "android_webview/native/permission/aw_permission_request_delegate.h" +#include "android_webview/browser/permission/aw_permission_request_delegate.h" namespace android_webview {
diff --git a/android_webview/native/permission/aw_permission_request_delegate.h b/android_webview/browser/permission/aw_permission_request_delegate.h similarity index 100% rename from android_webview/native/permission/aw_permission_request_delegate.h rename to android_webview/browser/permission/aw_permission_request_delegate.h
diff --git a/android_webview/native/permission/media_access_permission_request.cc b/android_webview/browser/permission/media_access_permission_request.cc similarity index 67% rename from android_webview/native/permission/media_access_permission_request.cc rename to android_webview/browser/permission/media_access_permission_request.cc index ac88a92..b4d73e09 100644 --- a/android_webview/native/permission/media_access_permission_request.cc +++ b/android_webview/browser/permission/media_access_permission_request.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/native/permission/media_access_permission_request.h" +#include "android_webview/browser/permission/media_access_permission_request.h" #include <utility> -#include "android_webview/native/permission/aw_permission_request.h" +#include "android_webview/browser/permission/aw_permission_request.h" #include "content/public/browser/media_capture_devices.h" using content::MediaCaptureDevices; @@ -40,12 +40,9 @@ MediaAccessPermissionRequest::MediaAccessPermissionRequest( const content::MediaStreamRequest& request, const content::MediaResponseCallback& callback) - : request_(request), - callback_(callback) { -} + : request_(request), callback_(callback) {} -MediaAccessPermissionRequest::~MediaAccessPermissionRequest() { -} +MediaAccessPermissionRequest::~MediaAccessPermissionRequest() {} void MediaAccessPermissionRequest::NotifyRequestResult(bool allowed) { std::unique_ptr<content::MediaStreamUI> ui; @@ -57,9 +54,10 @@ } if (request_.audio_type == content::MEDIA_DEVICE_AUDIO_CAPTURE) { - const MediaStreamDevices& audio_devices = audio_test_devices_.empty()? - MediaCaptureDevices::GetInstance()->GetAudioCaptureDevices() : - audio_test_devices_; + const MediaStreamDevices& audio_devices = + audio_test_devices_.empty() + ? MediaCaptureDevices::GetInstance()->GetAudioCaptureDevices() + : audio_test_devices_; const MediaStreamDevice* device = GetDeviceByIdOrFirstAvailable( audio_devices, request_.requested_audio_device_id); if (device) @@ -67,16 +65,18 @@ } if (request_.video_type == content::MEDIA_DEVICE_VIDEO_CAPTURE) { - const MediaStreamDevices& video_devices = video_test_devices_.empty()? - MediaCaptureDevices::GetInstance()->GetVideoCaptureDevices() : - video_test_devices_; + const MediaStreamDevices& video_devices = + video_test_devices_.empty() + ? MediaCaptureDevices::GetInstance()->GetVideoCaptureDevices() + : video_test_devices_; const MediaStreamDevice* device = GetDeviceByIdOrFirstAvailable( video_devices, request_.requested_video_device_id); if (device) devices.push_back(*device); } - callback_.Run(devices, devices.empty() ? content::MEDIA_DEVICE_NO_HARDWARE - : content::MEDIA_DEVICE_OK, + callback_.Run(devices, + devices.empty() ? content::MEDIA_DEVICE_NO_HARDWARE + : content::MEDIA_DEVICE_OK, std::move(ui)); } @@ -85,10 +85,12 @@ } int64_t MediaAccessPermissionRequest::GetResources() { - return (request_.audio_type == content::MEDIA_DEVICE_AUDIO_CAPTURE ? - AwPermissionRequest::AudioCapture : 0) | - (request_.video_type == content::MEDIA_DEVICE_VIDEO_CAPTURE ? - AwPermissionRequest::VideoCapture : 0); + return (request_.audio_type == content::MEDIA_DEVICE_AUDIO_CAPTURE + ? AwPermissionRequest::AudioCapture + : 0) | + (request_.video_type == content::MEDIA_DEVICE_VIDEO_CAPTURE + ? AwPermissionRequest::VideoCapture + : 0); } } // namespace android_webview
diff --git a/android_webview/native/permission/media_access_permission_request.h b/android_webview/browser/permission/media_access_permission_request.h similarity index 94% rename from android_webview/native/permission/media_access_permission_request.h rename to android_webview/browser/permission/media_access_permission_request.h index ed6ae7e..ed4429b 100644 --- a/android_webview/native/permission/media_access_permission_request.h +++ b/android_webview/browser/permission/media_access_permission_request.h
@@ -7,7 +7,7 @@ #include <stdint.h> -#include "android_webview/native/permission/aw_permission_request_delegate.h" +#include "android_webview/browser/permission/aw_permission_request_delegate.h" #include "base/callback.h" #include "base/macros.h" #include "content/public/common/media_stream_request.h"
diff --git a/android_webview/native/permission/media_access_permission_request_unittest.cc b/android_webview/browser/permission/media_access_permission_request_unittest.cc similarity index 85% rename from android_webview/native/permission/media_access_permission_request_unittest.cc rename to android_webview/browser/permission/media_access_permission_request_unittest.cc index a34f6f9a..402ee34 100644 --- a/android_webview/native/permission/media_access_permission_request_unittest.cc +++ b/android_webview/browser/permission/media_access_permission_request_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/native/permission/media_access_permission_request.h" +#include "android_webview/browser/permission/media_access_permission_request.h" #include "base/bind.h" #include "testing/gtest/include/gtest/gtest.h" @@ -34,20 +34,16 @@ std::string audio_id, std::string video_id) { content::MediaStreamDevices audio_devices; - audio_devices.push_back( - content::MediaStreamDevice(content::MEDIA_DEVICE_AUDIO_CAPTURE, - first_audio_device_id_, "a2")); - audio_devices.push_back( - content::MediaStreamDevice(content::MEDIA_DEVICE_AUDIO_CAPTURE, - audio_device_id_, "a1")); + audio_devices.push_back(content::MediaStreamDevice( + content::MEDIA_DEVICE_AUDIO_CAPTURE, first_audio_device_id_, "a2")); + audio_devices.push_back(content::MediaStreamDevice( + content::MEDIA_DEVICE_AUDIO_CAPTURE, audio_device_id_, "a1")); content::MediaStreamDevices video_devices; - video_devices.push_back( - content::MediaStreamDevice(content::MEDIA_DEVICE_VIDEO_CAPTURE, - first_video_device_id_, "v2")); - video_devices.push_back( - content::MediaStreamDevice(content::MEDIA_DEVICE_VIDEO_CAPTURE, - video_device_id_, "v1")); + video_devices.push_back(content::MediaStreamDevice( + content::MEDIA_DEVICE_VIDEO_CAPTURE, first_video_device_id_, "v2")); + video_devices.push_back(content::MediaStreamDevice( + content::MEDIA_DEVICE_VIDEO_CAPTURE, video_device_id_, "v1")); GURL origin("https://www.google.com"); content::MediaStreamRequest request( @@ -70,6 +66,7 @@ std::string first_video_device_id_; content::MediaStreamDevices devices_; content::MediaStreamRequestResult result_; + private: void Callback(const content::MediaStreamDevices& devices, content::MediaStreamRequestResult result,
diff --git a/android_webview/native/permission/permission_request_handler.cc b/android_webview/browser/permission/permission_request_handler.cc similarity index 91% rename from android_webview/native/permission/permission_request_handler.cc rename to android_webview/browser/permission/permission_request_handler.cc index 17f4212b..2dc5cbb 100644 --- a/android_webview/native/permission/permission_request_handler.cc +++ b/android_webview/browser/permission/permission_request_handler.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/native/permission/permission_request_handler.h" +#include "android_webview/browser/permission/permission_request_handler.h" #include <utility> -#include "android_webview/native/permission/aw_permission_request.h" -#include "android_webview/native/permission/aw_permission_request_delegate.h" -#include "android_webview/native/permission/permission_request_handler_client.h" +#include "android_webview/browser/permission/aw_permission_request.h" +#include "android_webview/browser/permission/aw_permission_request_delegate.h" +#include "android_webview/browser/permission/permission_request_handler_client.h" #include "base/android/scoped_java_ref.h" #include "base/bind.h" #include "content/public/browser/navigation_details.h" @@ -22,7 +22,8 @@ namespace { int GetLastCommittedEntryID(content::WebContents* web_contents) { - if (!web_contents) return 0; + if (!web_contents) + return 0; content::NavigationEntry* entry = web_contents->GetController().GetLastCommittedEntry(); @@ -36,8 +37,7 @@ content::WebContents* web_contents) : content::WebContentsObserver(web_contents), client_(client), - contents_unique_id_(GetLastCommittedEntryID(web_contents)) { -} + contents_unique_id_(GetLastCommittedEntryID(web_contents)) {} PermissionRequestHandler::~PermissionRequestHandler() { CancelAllRequests(); @@ -136,7 +136,7 @@ preauthorized_permission_.find(origin.GetOrigin().spec()); return i != preauthorized_permission_.end() && - (resources & i->second) == resources; + (resources & i->second) == resources; } } // namespace android_webivew
diff --git a/android_webview/native/permission/permission_request_handler.h b/android_webview/browser/permission/permission_request_handler.h similarity index 94% rename from android_webview/native/permission/permission_request_handler.h rename to android_webview/browser/permission/permission_request_handler.h index 659825b..2b44394 100644 --- a/android_webview/native/permission/permission_request_handler.h +++ b/android_webview/browser/permission/permission_request_handler.h
@@ -48,7 +48,7 @@ private: friend class TestPermissionRequestHandler; - typedef std::vector<base::WeakPtr<AwPermissionRequest> >::iterator + typedef std::vector<base::WeakPtr<AwPermissionRequest>>::iterator RequestIterator; // Return the request initiated by |origin| for accessing |resources|. @@ -68,7 +68,7 @@ PermissionRequestHandlerClient* client_; // A list of ongoing requests. - std::vector<base::WeakPtr<AwPermissionRequest> > requests_; + std::vector<base::WeakPtr<AwPermissionRequest>> requests_; std::map<std::string, int64_t> preauthorized_permission_;
diff --git a/android_webview/native/permission/permission_request_handler_client.cc b/android_webview/browser/permission/permission_request_handler_client.cc similarity index 81% rename from android_webview/native/permission/permission_request_handler_client.cc rename to android_webview/browser/permission/permission_request_handler_client.cc index 5ec97e0..17580c56 100644 --- a/android_webview/native/permission/permission_request_handler_client.cc +++ b/android_webview/browser/permission/permission_request_handler_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 "android_webview/native/permission/permission_request_handler_client.h" +#include "android_webview/browser/permission/permission_request_handler_client.h" namespace android_webview {
diff --git a/android_webview/native/permission/permission_request_handler_client.h b/android_webview/browser/permission/permission_request_handler_client.h similarity index 100% rename from android_webview/native/permission/permission_request_handler_client.h rename to android_webview/browser/permission/permission_request_handler_client.h
diff --git a/android_webview/native/permission/permission_request_handler_unittest.cc b/android_webview/browser/permission/permission_request_handler_unittest.cc similarity index 84% rename from android_webview/native/permission/permission_request_handler_unittest.cc rename to android_webview/browser/permission/permission_request_handler_unittest.cc index 6f20a7c28..e0c9a83 100644 --- a/android_webview/native/permission/permission_request_handler_unittest.cc +++ b/android_webview/browser/permission/permission_request_handler_unittest.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/native/permission/permission_request_handler.h" +#include "android_webview/browser/permission/permission_request_handler.h" #include <utility> -#include "android_webview/native/permission/aw_permission_request.h" -#include "android_webview/native/permission/aw_permission_request_delegate.h" -#include "android_webview/native/permission/permission_request_handler_client.h" +#include "android_webview/browser/permission/aw_permission_request.h" +#include "android_webview/browser/permission/aw_permission_request_delegate.h" +#include "android_webview/browser/permission/permission_request_handler_client.h" #include "base/bind.h" #include "base/callback.h" #include "testing/gtest/include/gtest/gtest.h" @@ -37,24 +37,21 @@ base::Callback<void(bool)> callback_; }; -class TestPermissionRequestHandlerClient : - public PermissionRequestHandlerClient { +class TestPermissionRequestHandlerClient + : public PermissionRequestHandlerClient { public: struct Permission { - Permission() - :resources(0) {} + Permission() : resources(0) {} Permission(const GURL& origin, int64_t resources) : origin(origin), resources(resources) {} GURL origin; int64_t resources; }; - TestPermissionRequestHandlerClient() - : request_(NULL) {} + TestPermissionRequestHandlerClient() : request_(NULL) {} - void OnPermissionRequest( - base::android::ScopedJavaLocalRef<jobject> j_request, - AwPermissionRequest* request) override { + void OnPermissionRequest(base::android::ScopedJavaLocalRef<jobject> j_request, + AwPermissionRequest* request) override { DCHECK(request); request_ = request; java_request_ = j_request; @@ -67,17 +64,11 @@ Permission(request->GetOrigin(), request->GetResources()); } - AwPermissionRequest* request() { - return request_; - } + AwPermissionRequest* request() { return request_; } - const Permission& requested_permission() { - return requested_permission_; - } + const Permission& requested_permission() { return requested_permission_; } - const Permission& canceled_permission() { - return canceled_permission_; - } + const Permission& canceled_permission() { return canceled_permission_; } void Grant() { request_->OnAccept(NULL, NULL, true); @@ -107,27 +98,20 @@ class TestPermissionRequestHandler : public PermissionRequestHandler { public: TestPermissionRequestHandler(PermissionRequestHandlerClient* client) - : PermissionRequestHandler(client, NULL) { - } + : PermissionRequestHandler(client, NULL) {} - const std::vector<base::WeakPtr<AwPermissionRequest> > requests() { + const std::vector<base::WeakPtr<AwPermissionRequest>> requests() { return requests_; } - void PruneRequests() { - return PermissionRequestHandler::PruneRequests(); - } + void PruneRequests() { return PermissionRequestHandler::PruneRequests(); } }; class PermissionRequestHandlerTest : public testing::Test { public: - PermissionRequestHandlerTest() - : handler_(&client_), - allowed_(false) {} + PermissionRequestHandlerTest() : handler_(&client_), allowed_(false) {} - void NotifyRequestResult(bool allowed) { - allowed_ = allowed; - } + void NotifyRequestResult(bool allowed) { allowed_ = allowed; } protected: void SetUp() override { @@ -135,16 +119,13 @@ origin_ = GURL("http://www.google.com"); resources_ = AwPermissionRequest::VideoCapture | AwPermissionRequest::AudioCapture; - delegate_.reset( - new TestAwPermissionRequestDelegate( - origin_, resources_, base::Bind( - &PermissionRequestHandlerTest::NotifyRequestResult, - base::Unretained(this)))); + delegate_.reset(new TestAwPermissionRequestDelegate( + origin_, resources_, + base::Bind(&PermissionRequestHandlerTest::NotifyRequestResult, + base::Unretained(this)))); } - const GURL& origin() { - return origin_; - } + const GURL& origin() { return origin_; } int64_t resources() { return resources_; } @@ -152,17 +133,11 @@ return std::move(delegate_); } - TestPermissionRequestHandler* handler() { - return &handler_; - } + TestPermissionRequestHandler* handler() { return &handler_; } - TestPermissionRequestHandlerClient* client() { - return &client_; - } + TestPermissionRequestHandlerClient* client() { return &client_; } - bool allowed() { - return allowed_; - } + bool allowed() { return allowed_; } private: GURL origin_; @@ -246,7 +221,8 @@ EXPECT_EQ(resources1, client()->request()->GetResources()); // Send 3rd request which has same origin and resources as first one. - delegate1.reset(new TestAwPermissionRequestDelegate(origin(), resources(), + delegate1.reset(new TestAwPermissionRequestDelegate( + origin(), resources(), base::Bind(&PermissionRequestHandlerTest::NotifyRequestResult, base::Unretained(this)))); handler()->SendRequest(std::move(delegate1)); @@ -299,7 +275,7 @@ handler()->PreauthorizePermission(origin(), resources()); // Ask the origin which wasn't preauthorized. - GURL origin ("http://a.google.com/a/b"); + GURL origin("http://a.google.com/a/b"); std::unique_ptr<AwPermissionRequestDelegate> delegate; int64_t requested_resources = AwPermissionRequest::AudioCapture; delegate.reset(new TestAwPermissionRequestDelegate( @@ -335,9 +311,9 @@ TEST_F(PermissionRequestHandlerTest, TestPreauthorizeMultiplePermission) { handler()->PreauthorizePermission(origin(), resources()); // Preauthorize another permission. - GURL origin ("http://a.google.com/a/b"); + GURL origin("http://a.google.com/a/b"); handler()->PreauthorizePermission(origin, AwPermissionRequest::Geolocation); - GURL origin_hostname ("http://a.google.com/"); + GURL origin_hostname("http://a.google.com/"); std::unique_ptr<AwPermissionRequestDelegate> delegate; delegate.reset(new TestAwPermissionRequestDelegate( origin_hostname, AwPermissionRequest::Geolocation,
diff --git a/android_webview/native/permission/simple_permission_request.cc b/android_webview/browser/permission/simple_permission_request.cc similarity index 78% rename from android_webview/native/permission/simple_permission_request.cc rename to android_webview/browser/permission/simple_permission_request.cc index d16b9e6..1f76830 100644 --- a/android_webview/native/permission/simple_permission_request.cc +++ b/android_webview/browser/permission/simple_permission_request.cc
@@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/native/permission/simple_permission_request.h" +#include "android_webview/browser/permission/simple_permission_request.h" -#include "android_webview/native/permission/aw_permission_request.h" +#include "android_webview/browser/permission/aw_permission_request.h" #include "base/callback.h" namespace android_webview { @@ -15,8 +15,7 @@ const base::Callback<void(bool)>& callback) : origin_(origin), resources_(resources), callback_(callback) {} -SimplePermissionRequest::~SimplePermissionRequest() { -} +SimplePermissionRequest::~SimplePermissionRequest() {} void SimplePermissionRequest::NotifyRequestResult(bool allowed) { callback_.Run(allowed);
diff --git a/android_webview/native/permission/simple_permission_request.h b/android_webview/browser/permission/simple_permission_request.h similarity index 93% rename from android_webview/native/permission/simple_permission_request.h rename to android_webview/browser/permission/simple_permission_request.h index e1fe00d..fb8c637e 100644 --- a/android_webview/native/permission/simple_permission_request.h +++ b/android_webview/browser/permission/simple_permission_request.h
@@ -7,7 +7,7 @@ #include <stdint.h> -#include "android_webview/native/permission/aw_permission_request_delegate.h" +#include "android_webview/browser/permission/aw_permission_request_delegate.h" #include "base/callback.h" #include "base/macros.h"
diff --git a/android_webview/native/popup_touch_handle_drawable.cc b/android_webview/browser/popup_touch_handle_drawable.cc similarity index 94% rename from android_webview/native/popup_touch_handle_drawable.cc rename to android_webview/browser/popup_touch_handle_drawable.cc index 0ba52f1..3bd0bc6 100644 --- a/android_webview/native/popup_touch_handle_drawable.cc +++ b/android_webview/browser/popup_touch_handle_drawable.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/native/popup_touch_handle_drawable.h" +#include "android_webview/browser/popup_touch_handle_drawable.h" #include "jni/PopupTouchHandleDrawable_jni.h" @@ -15,8 +15,8 @@ JNIEnv* env, jobject obj, float horizontal_padding_ratio) - : java_ref_(env, obj) - , drawable_horizontal_padding_ratio_(horizontal_padding_ratio) { + : java_ref_(env, obj), + drawable_horizontal_padding_ratio_(horizontal_padding_ratio) { DCHECK(obj); }
diff --git a/android_webview/native/popup_touch_handle_drawable.h b/android_webview/browser/popup_touch_handle_drawable.h similarity index 99% rename from android_webview/native/popup_touch_handle_drawable.h rename to android_webview/browser/popup_touch_handle_drawable.h index fbdca9f..7d678d4d 100644 --- a/android_webview/native/popup_touch_handle_drawable.h +++ b/android_webview/browser/popup_touch_handle_drawable.h
@@ -36,7 +36,6 @@ float GetDrawableHorizontalPaddingRatio() const override; private: - JavaObjectWeakGlobalRef java_ref_; const float drawable_horizontal_padding_ratio_;
diff --git a/android_webview/native/state_serializer.cc b/android_webview/browser/state_serializer.cc similarity index 99% rename from android_webview/native/state_serializer.cc rename to android_webview/browser/state_serializer.cc index fd828ef..3da314f 100644 --- a/android_webview/native/state_serializer.cc +++ b/android_webview/browser/state_serializer.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/native/state_serializer.h" +#include "android_webview/browser/state_serializer.h" #include <string>
diff --git a/android_webview/native/state_serializer.h b/android_webview/browser/state_serializer.h similarity index 93% rename from android_webview/native/state_serializer.h rename to android_webview/browser/state_serializer.h index 644d5cca..15346c1 100644 --- a/android_webview/native/state_serializer.h +++ b/android_webview/browser/state_serializer.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_NATIVE_STATE_SERIALIZER_H_ -#define ANDROID_WEBVIEW_NATIVE_STATE_SERIALIZER_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_STATE_SERIALIZER_H_ +#define ANDROID_WEBVIEW_BROWSER_STATE_SERIALIZER_H_ #include <cstdint> @@ -36,7 +36,6 @@ bool RestoreFromPickle(base::PickleIterator* iterator, content::WebContents* web_contents) WARN_UNUSED_RESULT; - namespace internal { const uint32_t AW_STATE_VERSION_INITIAL = 20130814; @@ -68,4 +67,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_STATE_SERIALIZER_H_ +#endif // ANDROID_WEBVIEW_BROWSER_STATE_SERIALIZER_H_
diff --git a/android_webview/native/state_serializer_unittest.cc b/android_webview/browser/state_serializer_unittest.cc similarity index 99% rename from android_webview/native/state_serializer_unittest.cc rename to android_webview/browser/state_serializer_unittest.cc index 03d65b8..31454df 100644 --- a/android_webview/native/state_serializer_unittest.cc +++ b/android_webview/browser/state_serializer_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/native/state_serializer.h" +#include "android_webview/browser/state_serializer.h" #include <memory> #include <string>
diff --git a/android_webview/native/token_binding_manager_bridge.cc b/android_webview/browser/token_binding_manager_bridge.cc similarity index 95% rename from android_webview/native/token_binding_manager_bridge.cc rename to android_webview/browser/token_binding_manager_bridge.cc index 2e71a06..1aaa0ec 100644 --- a/android_webview/native/token_binding_manager_bridge.cc +++ b/android_webview/browser/token_binding_manager_bridge.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "android_webview/native/token_binding_manager_bridge.h" +#include "android_webview/browser/token_binding_manager_bridge.h" #include "android_webview/browser/net/token_binding_manager.h" #include "base/android/jni_android.h" @@ -44,8 +44,8 @@ std::vector<uint8_t> public_key; key->ExportPublicKey(&public_key); - ScopedJavaLocalRef<jbyteArray> jpublic_key = base::android::ToJavaByteArray( - env, public_key.data(), public_key.size()); + ScopedJavaLocalRef<jbyteArray> jpublic_key = + base::android::ToJavaByteArray(env, public_key.data(), public_key.size()); Java_AwTokenBindingManager_onKeyReady(env, callback, jprivate_key, jpublic_key);
diff --git a/android_webview/native/token_binding_manager_bridge.h b/android_webview/browser/token_binding_manager_bridge.h similarity index 60% rename from android_webview/native/token_binding_manager_bridge.h rename to android_webview/browser/token_binding_manager_bridge.h index f2fdece..e7c8451 100644 --- a/android_webview/native/token_binding_manager_bridge.h +++ b/android_webview/browser/token_binding_manager_bridge.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ANDROID_WEBVIEW_NATIVE_TOKEN_BINDING_MANAGER_BRIDGE_H_ -#define ANDROID_WEBVIEW_NATIVE_TOKEN_BINDING_MANAGER_BRIDGE_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_TOKEN_BINDING_MANAGER_BRIDGE_H_ +#define ANDROID_WEBVIEW_BROWSER_TOKEN_BINDING_MANAGER_BRIDGE_H_ #include <jni.h> @@ -13,4 +13,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_NATIVE_TOKEN_BINDING_MANAGER_BRIDGE_H_ +#endif // ANDROID_WEBVIEW_BROWSER_TOKEN_BINDING_MANAGER_BRIDGE_H_
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/WebViewModalDialogOverrideTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/WebViewModalDialogOverrideTest.java index 788074ac..12f4a0e 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/WebViewModalDialogOverrideTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/WebViewModalDialogOverrideTest.java
@@ -17,7 +17,7 @@ import org.chromium.android_webview.test.util.AwTestTouchUtils; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.Feature; -import org.chromium.base.test.util.RetryOnFailure; +import org.chromium.content_public.browser.GestureStateListener; import java.util.concurrent.atomic.AtomicBoolean; @@ -157,13 +157,40 @@ assertEquals("false", result); } + private static class TapGestureStateListener extends GestureStateListener { + private CallbackHelper mCallbackHelper = new CallbackHelper(); + + public int getCallCount() { + return mCallbackHelper.getCallCount(); + } + + public void waitForTap(int currentCallCount) throws Throwable { + mCallbackHelper.waitForCallback(currentCallCount); + } + + @Override + public void onSingleTap(boolean consumed) { + mCallbackHelper.notifyCalled(); + } + } + + /** + * Taps on a view and waits for a callback. + */ + private void tapViewAndWait(AwTestContainerView view) throws Throwable { + final TapGestureStateListener tapGestureStateListener = new TapGestureStateListener(); + int callCount = tapGestureStateListener.getCallCount(); + view.getContentViewCore().addGestureStateListener(tapGestureStateListener); + + AwTestTouchUtils.simulateTouchCenterOfView(view); + tapGestureStateListener.waitForTap(callCount); + } + /* * Verify that when the AwContentsClient calls handleJsBeforeUnload - * Flaky (crbug/719308) */ @MediumTest @Feature({"AndroidWebView"}) - @RetryOnFailure public void testOverrideBeforeUnloadHandling() throws Throwable { final CallbackHelper jsBeforeUnloadHelper = new CallbackHelper(); TestAwContentsClient client = new TestAwContentsClient() { @@ -181,7 +208,7 @@ "text/html", false); enableJavaScriptOnUiThread(awContents); // JavaScript onbeforeunload dialogs require a user gesture. - AwTestTouchUtils.simulateTouchCenterOfView(view); + tapViewAndWait(view); // Don't wait synchronously because we don't leave the page. int currentCallCount = jsBeforeUnloadHelper.getCallCount();
diff --git a/android_webview/lib/main/aw_main_delegate.cc b/android_webview/lib/main/aw_main_delegate.cc index b9dc2490..0dbed8b0 100644 --- a/android_webview/lib/main/aw_main_delegate.cc +++ b/android_webview/lib/main/aw_main_delegate.cc
@@ -7,7 +7,12 @@ #include <memory> #include "android_webview/browser/aw_content_browser_client.h" +#include "android_webview/browser/aw_locale_manager_impl.h" +#include "android_webview/browser/aw_media_url_interceptor.h" +#include "android_webview/browser/aw_quota_manager_bridge_impl.h" #include "android_webview/browser/aw_safe_browsing_config_helper.h" +#include "android_webview/browser/aw_web_contents_view_delegate.h" +#include "android_webview/browser/aw_web_preferences_populater_impl.h" #include "android_webview/browser/browser_view_renderer.h" #include "android_webview/browser/command_line_helper.h" #include "android_webview/browser/deferred_gpu_command_service.h" @@ -17,11 +22,6 @@ #include "android_webview/common/crash_reporter/aw_microdump_crash_reporter.h" #include "android_webview/common/crash_reporter/crash_keys.h" #include "android_webview/gpu/aw_content_gpu_client.h" -#include "android_webview/native/aw_locale_manager_impl.h" -#include "android_webview/native/aw_media_url_interceptor.h" -#include "android_webview/native/aw_quota_manager_bridge_impl.h" -#include "android_webview/native/aw_web_contents_view_delegate.h" -#include "android_webview/native/aw_web_preferences_populater_impl.h" #include "android_webview/renderer/aw_content_renderer_client.h" #include "base/android/apk_assets.h" #include "base/android/build_info.h"
diff --git a/android_webview/lib/main/webview_jni_onload.cc b/android_webview/lib/main/webview_jni_onload.cc index 1edce09..3a7207a 100644 --- a/android_webview/lib/main/webview_jni_onload.cc +++ b/android_webview/lib/main/webview_jni_onload.cc
@@ -4,9 +4,9 @@ #include "android_webview/lib/main/webview_jni_onload.h" +#include "android_webview/browser/android_webview_jni_registrar.h" #include "android_webview/common/aw_version_info_values.h" #include "android_webview/lib/main/aw_main_delegate.h" -#include "android_webview/native/android_webview_jni_registrar.h" #include "base/android/jni_android.h" #include "base/android/jni_registrar.h" #include "base/android/library_loader/library_loader_hooks.h"
diff --git a/android_webview/lib/main/webview_tests.cc b/android_webview/lib/main/webview_tests.cc index ac2d295..4e20c1d 100644 --- a/android_webview/lib/main/webview_tests.cc +++ b/android_webview/lib/main/webview_tests.cc
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "android_webview/browser/android_webview_jni_registrar.h" #include "android_webview/browser/deferred_gpu_command_service.h" -#include "android_webview/native/android_webview_jni_registrar.h" #include "base/android/jni_android.h" #include "base/command_line.h" #include "base/test/test_suite.h"
diff --git a/android_webview/native/BUILD.gn b/android_webview/native/BUILD.gn deleted file mode 100644 index 096fe2c..0000000 --- a/android_webview/native/BUILD.gn +++ /dev/null
@@ -1,185 +0,0 @@ -# Copyright 2015 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//build/config/android/config.gni") -import("//build/config/android/rules.gni") -import("//components/spellcheck/spellcheck_build_features.gni") - -source_set("native") { - deps = [ - ":native_jni", - "//android_webview:generate_components_strings", - "//android_webview/common:version", - "//base", - "//base/third_party/dynamic_annotations:dynamic_annotations", - "//cc:cc", - "//components/autofill/content/browser:browser", - "//components/spellcheck:build_features", - "//components/web_contents_delegate_android:web_contents_delegate_android", - "//content/public/common", - "//media", - "//net", - "//skia", - "//storage/browser", - "//storage/common", - "//third_party/boringssl", - "//ui/base", - "//ui/gfx", - "//ui/gfx/geometry:geometry", - ] - - include_dirs = [ - "//skia/config", - "//third_party/protobuf", - ] - - sources = [ - "address_parser.cc", - "address_parser.h", - "address_parser_internal.cc", - "address_parser_internal.h", - "android_protocol_handler.cc", - "android_protocol_handler.h", - "android_webview_jni_registrar.cc", - "android_webview_jni_registrar.h", - "aw_autofill_client.cc", - "aw_autofill_client.h", - "aw_contents.cc", - "aw_contents.h", - "aw_contents_background_thread_client.cc", - "aw_contents_background_thread_client.h", - "aw_contents_client_bridge.cc", - "aw_contents_client_bridge.h", - "aw_contents_io_thread_client_impl.cc", - "aw_contents_io_thread_client_impl.h", - "aw_contents_lifecycle_notifier.cc", - "aw_contents_lifecycle_notifier.h", - "aw_contents_statics.cc", - "aw_contents_statics.h", - "aw_debug.cc", - "aw_debug.h", - "aw_devtools_server.cc", - "aw_devtools_server.h", - "aw_form_database.cc", - "aw_form_database.h", - "aw_gl_functor.cc", - "aw_gl_functor.h", - "aw_http_auth_handler.cc", - "aw_http_auth_handler.h", - "aw_locale_manager_impl.cc", - "aw_locale_manager_impl.h", - "aw_media_url_interceptor.cc", - "aw_media_url_interceptor.h", - "aw_metrics_log_uploader.cc", - "aw_metrics_log_uploader.h", - "aw_metrics_service_client_impl.cc", - "aw_metrics_service_client_impl.h", - "aw_pdf_exporter.cc", - "aw_pdf_exporter.h", - "aw_picture.cc", - "aw_picture.h", - "aw_quota_manager_bridge_impl.cc", - "aw_quota_manager_bridge_impl.h", - "aw_renderer_priority_manager.cc", - "aw_renderer_priority_manager.h", - "aw_resource.cc", - "aw_settings.cc", - "aw_settings.h", - "aw_web_contents_delegate.cc", - "aw_web_contents_delegate.h", - "aw_web_contents_view_delegate.cc", - "aw_web_contents_view_delegate.h", - "aw_web_preferences_populater_impl.cc", - "aw_web_preferences_populater_impl.h", - "aw_web_resource_response_impl.cc", - "aw_web_resource_response_impl.h", - "cookie_manager.cc", - "cookie_manager.h", - "input_stream_impl.cc", - "input_stream_impl.h", - "java_browser_view_renderer_helper.cc", - "java_browser_view_renderer_helper.h", - "net_init_native_callback.cc", - "permission/aw_permission_request.cc", - "permission/aw_permission_request.h", - "permission/aw_permission_request_delegate.cc", - "permission/aw_permission_request_delegate.h", - "permission/media_access_permission_request.cc", - "permission/media_access_permission_request.h", - "permission/permission_request_handler.cc", - "permission/permission_request_handler.h", - "permission/permission_request_handler_client.cc", - "permission/permission_request_handler_client.h", - "permission/simple_permission_request.cc", - "permission/simple_permission_request.h", - "popup_touch_handle_drawable.cc", - "popup_touch_handle_drawable.h", - "state_serializer.cc", - "state_serializer.h", - "token_binding_manager_bridge.cc", - "token_binding_manager_bridge.h", - ] - - if (enable_spellcheck) { - deps += [ "//components/spellcheck/browser:browser" ] - } - - libs = [ "jnigraphics" ] -} - -generate_jni("native_jni") { - sources = [ - "../java/src/org/chromium/android_webview/AndroidProtocolHandler.java", - "../java/src/org/chromium/android_webview/AwAutofillClient.java", - "../java/src/org/chromium/android_webview/AwContents.java", - "../java/src/org/chromium/android_webview/AwContentsBackgroundThreadClient.java", - "../java/src/org/chromium/android_webview/AwContentsClientBridge.java", - "../java/src/org/chromium/android_webview/AwContentsIoThreadClient.java", - "../java/src/org/chromium/android_webview/AwContentsLifecycleNotifier.java", - "../java/src/org/chromium/android_webview/AwContentsStatics.java", - "../java/src/org/chromium/android_webview/AwCookieManager.java", - "../java/src/org/chromium/android_webview/AwDebug.java", - "../java/src/org/chromium/android_webview/AwDevToolsServer.java", - "../java/src/org/chromium/android_webview/AwFormDatabase.java", - "../java/src/org/chromium/android_webview/AwGLFunctor.java", - "../java/src/org/chromium/android_webview/AwHttpAuthHandler.java", - "../java/src/org/chromium/android_webview/AwMetricsLogUploader.java", - "../java/src/org/chromium/android_webview/AwMetricsServiceClient.java", - "../java/src/org/chromium/android_webview/AwPdfExporter.java", - "../java/src/org/chromium/android_webview/AwPicture.java", - "../java/src/org/chromium/android_webview/AwQuotaManagerBridge.java", - "../java/src/org/chromium/android_webview/AwRendererPriorityManager.java", - "../java/src/org/chromium/android_webview/AwResource.java", - "../java/src/org/chromium/android_webview/AwSettings.java", - "../java/src/org/chromium/android_webview/AwTokenBindingManager.java", - "../java/src/org/chromium/android_webview/AwWebContentsDelegate.java", - "../java/src/org/chromium/android_webview/AwWebResourceResponse.java", - "../java/src/org/chromium/android_webview/InputStreamUtil.java", - "../java/src/org/chromium/android_webview/JavaBrowserViewRendererHelper.java", - "../java/src/org/chromium/android_webview/PopupTouchHandleDrawable.java", - "../java/src/org/chromium/android_webview/permission/AwPermissionRequest.java", - ] - jni_package = "android_webview" - - deps = [ - ":cancellation_signal_android_jar_jni_headers", - ] -} - -generate_jar_jni("cancellation_signal_android_jar_jni_headers") { - classes = [ "android/os/CancellationSignal.class" ] - jni_package = "android_webview" -} - -java_cpp_enum("aw_permission_request_resource") { - sources = [ - "permission/aw_permission_request.h", - ] -} - -java_cpp_enum("aw_renderer_priority_manager_renderer_priority") { - sources = [ - "aw_renderer_priority_manager.h", - ] -}
diff --git a/android_webview/native/DEPS b/android_webview/native/DEPS deleted file mode 100644 index 9835be8..0000000 --- a/android_webview/native/DEPS +++ /dev/null
@@ -1,22 +0,0 @@ -include_rules = [ - "+content/public/browser", - "+content/public/test", - "+media/base/android", - "+storage/browser/quota", - "+storage/common/quota", - "+ui/gfx", - "+ui/shell_dialogs", - "+ui/touch_selection/touch_handle.h", - - # Components that Android WebView depends on. - "+components/autofill/content/browser", - "+components/autofill/core/browser", - "+components/autofill/core/common", - "+components/navigation_interception", - "+components/spellcheck/browser/android", - "+components/user_prefs", - "+components/web_contents_delegate_android", - - "+printing", - -]
diff --git a/android_webview/native/android_webview_jni_registrar.cc b/android_webview/native/android_webview_jni_registrar.cc deleted file mode 100644 index 9523993..0000000 --- a/android_webview/native/android_webview_jni_registrar.cc +++ /dev/null
@@ -1,67 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "android_webview/native/android_webview_jni_registrar.h" - -#include "android_webview/native/android_protocol_handler.h" -#include "android_webview/native/aw_autofill_client.h" -#include "android_webview/native/aw_contents.h" -#include "android_webview/native/aw_contents_client_bridge.h" -#include "android_webview/native/aw_contents_statics.h" -#include "android_webview/native/aw_debug.h" -#include "android_webview/native/aw_devtools_server.h" -#include "android_webview/native/aw_form_database.h" -#include "android_webview/native/aw_gl_functor.h" -#include "android_webview/native/aw_http_auth_handler.h" -#include "android_webview/native/aw_metrics_service_client_impl.h" -#include "android_webview/native/aw_pdf_exporter.h" -#include "android_webview/native/aw_picture.h" -#include "android_webview/native/aw_quota_manager_bridge_impl.h" -#include "android_webview/native/aw_settings.h" -#include "android_webview/native/aw_web_contents_delegate.h" -#include "android_webview/native/cookie_manager.h" -#include "android_webview/native/permission/aw_permission_request.h" -#include "base/android/jni_android.h" -#include "base/android/jni_registrar.h" -#include "base/trace_event/trace_event.h" -#include "components/spellcheck/spellcheck_build_features.h" - -#if BUILDFLAG(ENABLE_SPELLCHECK) -#include "components/spellcheck/browser/android/component_jni_registrar.h" -#endif - -namespace android_webview { - -static base::android::RegistrationMethod kWebViewRegisteredMethods[] = { - // Register JNI for android_webview classes. - { "AndroidProtocolHandler", RegisterAndroidProtocolHandler }, - { "AwAutofillClient", RegisterAwAutofillClient }, - { "AwContents", RegisterAwContents }, - { "AwContentsClientBridge", RegisterAwContentsClientBridge }, - { "AwContentsStatics", RegisterAwContentsStatics }, - { "AwDebug", RegisterAwDebug }, - { "AwDevToolsServer", RegisterAwDevToolsServer }, - { "AwFormDatabase", RegisterAwFormDatabase }, - { "AwPicture", RegisterAwPicture }, - { "AwSettings", RegisterAwSettings }, - { "AwHttpAuthHandler", RegisterAwHttpAuthHandler }, - { "AwMetricsServiceClient", RegisterAwMetricsServiceClient }, - { "AwPdfExporter", RegisterAwPdfExporter }, - { "AwPermissionRequest", RegisterAwPermissionRequest }, - { "AwQuotaManagerBridge", RegisterAwQuotaManagerBridge }, - { "AwWebContentsDelegate", RegisterAwWebContentsDelegate }, - { "CookieManager", RegisterCookieManager }, - { "AwGLFunctor", RegisterAwGLFunctor }, -#if BUILDFLAG(ENABLE_SPELLCHECK) - {"SpellCheckerSessionBridge", spellcheck::android::RegisterSpellcheckJni}, -#endif -}; - -bool RegisterJni(JNIEnv* env) { - TRACE_EVENT0("startup", "android_webview::RegisterJni"); - return RegisterNativeMethods(env, - kWebViewRegisteredMethods, arraysize(kWebViewRegisteredMethods)); -} - -} // namespace android_webview
diff --git a/android_webview/native/android_webview_jni_registrar.h b/android_webview/native/android_webview_jni_registrar.h deleted file mode 100644 index a1a37487..0000000 --- a/android_webview/native/android_webview_jni_registrar.h +++ /dev/null
@@ -1,17 +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 ANDROID_WEBVIEW_NATIVE_ANDROID_WEBVIEW_JNI_REGISTRAR_H_ -#define ANDROID_WEBVIEW_NATIVE_ANDROID_WEBVIEW_JNI_REGISTRAR_H_ - -#include <jni.h> - -namespace android_webview { - -// Register all JNI bindings necessary for chrome. -bool RegisterJni(JNIEnv* env); - -} // namespace android_webview - -#endif // ANDROID_WEBVIEW_NATIVE_ANDROID_WEBVIEW_JNI_REGISTRAR_H_
diff --git a/android_webview/test/BUILD.gn b/android_webview/test/BUILD.gn index 79dd6e0f..9f28f078 100644 --- a/android_webview/test/BUILD.gn +++ b/android_webview/test/BUILD.gn
@@ -284,13 +284,19 @@ "../browser/test/rendering_test.cc", "../browser/test/rendering_test.h", "../lib/main/webview_tests.cc", - "../native/address_parser_unittest.cc", - "../native/aw_contents_client_bridge_unittest.cc", - "../native/aw_media_url_interceptor_unittest.cc", - "../native/input_stream_unittest.cc", - "../native/permission/media_access_permission_request_unittest.cc", - "../native/permission/permission_request_handler_unittest.cc", - "../native/state_serializer_unittest.cc", + ] + + # TODO(ctzsm): Remove following block. + # Take out old native/ tests files from sources for now + # for easier distinguishing them from actual browser/ files. + sources += [ + "../browser/address_parser_unittest.cc", + "../browser/aw_contents_client_bridge_unittest.cc", + "../browser/aw_media_url_interceptor_unittest.cc", + "../browser/input_stream_unittest.cc", + "../browser/permission/media_access_permission_request_unittest.cc", + "../browser/permission/permission_request_handler_unittest.cc", + "../browser/state_serializer_unittest.cc", ] }
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 94d174a..60d2237 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -61,8 +61,6 @@ "ash_touch_exploration_manager_chromeos.cc", "ash_touch_exploration_manager_chromeos.h", "ash_view_ids.h", - "aura/aura_layout_manager_adapter.cc", - "aura/aura_layout_manager_adapter.h", "aura/key_event_watcher_aura.cc", "aura/key_event_watcher_aura.h", "aura/pointer_watcher_adapter.cc", @@ -201,6 +199,10 @@ "link_handler_model.h", "link_handler_model_factory.cc", "link_handler_model_factory.h", + "login/views/lock_contents_view.cc", + "login/views/lock_contents_view.h", + "login/views/lock_screen.cc", + "login/views/lock_screen.h", "login_status.h", "magnifier/magnification_controller.cc", "magnifier/magnification_controller.h", @@ -803,7 +805,6 @@ "wm/workspace_controller.cc", "wm/workspace_controller.h", "wm_display_observer.h", - "wm_layout_manager.h", "wm_transient_window_observer.h", "wm_window.cc", "wm_window.h",
diff --git a/ash/aura/aura_layout_manager_adapter.cc b/ash/aura/aura_layout_manager_adapter.cc deleted file mode 100644 index 140cad98..0000000 --- a/ash/aura/aura_layout_manager_adapter.cc +++ /dev/null
@@ -1,73 +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 "ash/aura/aura_layout_manager_adapter.h" - -#include "ash/wm_layout_manager.h" -#include "ash/wm_window.h" -#include "ui/aura/window.h" -#include "ui/base/class_property.h" - -DECLARE_UI_CLASS_PROPERTY_TYPE(ash::AuraLayoutManagerAdapter*); - -namespace ash { -namespace { -// AuraLayoutManagerAdapter is an aura::LayoutManager, so it's owned by the -// aura::Window it is installed on. This property is used to lookup the -// AuraLayoutManagerAdapter given only an aura::Window. -DEFINE_UI_CLASS_PROPERTY_KEY(AuraLayoutManagerAdapter*, - kAuraLayoutManagerAdapter, - nullptr); -} // namespace - -AuraLayoutManagerAdapter::AuraLayoutManagerAdapter( - aura::Window* window, - std::unique_ptr<WmLayoutManager> wm_layout_manager) - : window_(window), wm_layout_manager_(std::move(wm_layout_manager)) { - window->SetProperty(kAuraLayoutManagerAdapter, this); -} - -AuraLayoutManagerAdapter::~AuraLayoutManagerAdapter() { - // Only one AuraLayoutManagerAdapter is created per window at a time, so this - // AuraLayoutManagerAdapter should be the installed AuraLayoutManagerAdapter. - DCHECK_EQ(this, window_->GetProperty(kAuraLayoutManagerAdapter)); - window_->ClearProperty(kAuraLayoutManagerAdapter); -} - -// static -AuraLayoutManagerAdapter* AuraLayoutManagerAdapter::Get(aura::Window* window) { - return window->GetProperty(kAuraLayoutManagerAdapter); -} - -void AuraLayoutManagerAdapter::OnWindowResized() { - wm_layout_manager_->OnWindowResized(); -} - -void AuraLayoutManagerAdapter::OnWindowAddedToLayout(aura::Window* child) { - wm_layout_manager_->OnWindowAddedToLayout(WmWindow::Get(child)); -} - -void AuraLayoutManagerAdapter::OnWillRemoveWindowFromLayout( - aura::Window* child) { - wm_layout_manager_->OnWillRemoveWindowFromLayout(WmWindow::Get(child)); -} - -void AuraLayoutManagerAdapter::OnWindowRemovedFromLayout(aura::Window* child) { - wm_layout_manager_->OnWindowRemovedFromLayout(WmWindow::Get(child)); -} - -void AuraLayoutManagerAdapter::OnChildWindowVisibilityChanged( - aura::Window* child, - bool visible) { - wm_layout_manager_->OnChildWindowVisibilityChanged(WmWindow::Get(child), - visible); -} - -void AuraLayoutManagerAdapter::SetChildBounds( - aura::Window* child, - const gfx::Rect& requested_bounds) { - wm_layout_manager_->SetChildBounds(WmWindow::Get(child), requested_bounds); -} - -} // namespace ash
diff --git a/ash/aura/aura_layout_manager_adapter.h b/ash/aura/aura_layout_manager_adapter.h deleted file mode 100644 index 9e29f39..0000000 --- a/ash/aura/aura_layout_manager_adapter.h +++ /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. - -#ifndef ASH_AURA_AURA_LAYOUT_MANAGER_ADAPTER_H_ -#define ASH_AURA_AURA_LAYOUT_MANAGER_ADAPTER_H_ - -#include <memory> - -#include "ash/ash_export.h" -#include "base/macros.h" -#include "ui/aura/layout_manager.h" - -namespace ash { - -class WmLayoutManager; - -// AuraLayoutManagerAdapter is an aura::LayoutManager that calls to -// WmLayoutManager. Use it when you have a WmLayoutManager you want to use -// with an aura::Window. -class ASH_EXPORT AuraLayoutManagerAdapter : public aura::LayoutManager { - public: - AuraLayoutManagerAdapter(aura::Window* window, - std::unique_ptr<WmLayoutManager> wm_layout_manager); - ~AuraLayoutManagerAdapter() override; - - // Returns the AuraLayoutManagerAdapter installed on |window|, or null if - // an AuraLayoutManagerAdapter is not installed on |window|. - static AuraLayoutManagerAdapter* Get(aura::Window* window); - - WmLayoutManager* wm_layout_manager() { return wm_layout_manager_.get(); } - - // aura::LayoutManager: - void OnWindowResized() override; - void OnWindowAddedToLayout(aura::Window* child) override; - void OnWillRemoveWindowFromLayout(aura::Window* child) override; - void OnWindowRemovedFromLayout(aura::Window* child) override; - void OnChildWindowVisibilityChanged(aura::Window* child, - bool visible) override; - void SetChildBounds(aura::Window* child, - const gfx::Rect& requested_bounds) override; - - private: - aura::Window* window_; - std::unique_ptr<WmLayoutManager> wm_layout_manager_; - - DISALLOW_COPY_AND_ASSIGN(AuraLayoutManagerAdapter); -}; - -} // namespace ash - -#endif // ASH_AURA_AURA_LAYOUT_MANAGER_ADAPTER_H_
diff --git a/ash/keyboard/keyboard_observer_register.cc b/ash/keyboard/keyboard_observer_register.cc index 9a38d46..2f6902bb 100644 --- a/ash/keyboard/keyboard_observer_register.cc +++ b/ash/keyboard/keyboard_observer_register.cc
@@ -10,8 +10,8 @@ void UpdateKeyboardObserverFromStateChanged( bool keyboard_activated, - WmWindow* keyboard_root_window, - WmWindow* observer_root_window, + aura::Window* keyboard_root_window, + aura::Window* observer_root_window, ScopedObserver<keyboard::KeyboardController, keyboard::KeyboardControllerObserver>* keyboard_observer) { if (keyboard_root_window != observer_root_window)
diff --git a/ash/keyboard/keyboard_observer_register.h b/ash/keyboard/keyboard_observer_register.h index a95aae4..e34f2d10 100644 --- a/ash/keyboard/keyboard_observer_register.h +++ b/ash/keyboard/keyboard_observer_register.h
@@ -7,6 +7,10 @@ #include "base/scoped_observer.h" +namespace aura { +class Window; +} + namespace keyboard { class KeyboardController; class KeyboardControllerObserver; @@ -14,8 +18,6 @@ namespace ash { -class WmWindow; - // Helper function to start/stop observing KeyboardController. // |keyboard_root_window| is the root window where KeyboardController changes // states. |observer_root_window| is the root window relevant to the @@ -25,8 +27,8 @@ // false. void UpdateKeyboardObserverFromStateChanged( bool keyboard_activated, - WmWindow* keyboard_root_window, - WmWindow* observer_root_window, + aura::Window* keyboard_root_window, + aura::Window* observer_root_window, ScopedObserver<keyboard::KeyboardController, keyboard::KeyboardControllerObserver>* keyboard_observer);
diff --git a/ash/login/views/lock_contents_view.cc b/ash/login/views/lock_contents_view.cc new file mode 100644 index 0000000..5c557b9 --- /dev/null +++ b/ash/login/views/lock_contents_view.cc
@@ -0,0 +1,40 @@ +// 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 "ash/login/views/lock_contents_view.h" + +#include "base/strings/utf_string_conversions.h" +#include "ui/views/background.h" +#include "ui/views/border.h" +#include "ui/views/layout/box_layout.h" + +namespace ash { + +LockContentsView::LockContentsView() { + auto* layout = new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 0); + SetLayoutManager(layout); + + views::Label* label = new views::Label(); + label->SetBorder(views::CreateEmptyBorder(2, 3, 4, 5)); + label->set_background(views::Background::CreateThemedSolidBackground( + label, ui::NativeTheme::kColorId_BubbleBackground)); + label->SetText(base::ASCIIToUTF16("User")); + AddChildView(label); + + unlock_button_ = + views::MdTextButton::Create(this, base::ASCIIToUTF16("Unlock")); + AddChildView(unlock_button_); +} + +LockContentsView::~LockContentsView() {} + +void LockContentsView::ButtonPressed(views::Button* sender, + const ui::Event& event) { + DCHECK(unlock_button_ == sender); + + // TODO: Run mojo call that talks to backend which unlocks the device. + NOTIMPLEMENTED(); +} + +} // namespace ash
diff --git a/ash/login/views/lock_contents_view.h b/ash/login/views/lock_contents_view.h new file mode 100644 index 0000000..0738812 --- /dev/null +++ b/ash/login/views/lock_contents_view.h
@@ -0,0 +1,34 @@ +// 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 ASH_LOGIN_VIEWS_CONTENTS_VIEW_H_ +#define ASH_LOGIN_VIEWS_CONTENTS_VIEW_H_ + +#include "base/macros.h" +#include "ui/views/controls/button/md_text_button.h" +#include "ui/views/view.h" + +namespace ash { + +// LockContentsView hosts the root view for the lock screen. All other lock +// screen views are embedded within this one. LockContentsView is per-display, +// but the lock screen should only ever be shown on a single display, so there +// is effectively only a single instance. +class LockContentsView : public views::View, public views::ButtonListener { + public: + LockContentsView(); + ~LockContentsView() override; + + // views::ButtonListener: + void ButtonPressed(views::Button* sender, const ui::Event& event) override; + + private: + views::Button* unlock_button_; + + DISALLOW_COPY_AND_ASSIGN(LockContentsView); +}; + +} // namespace ash + +#endif // ASH_LOGIN_VIEWS_CONTENTS_VIEW_H_
diff --git a/ash/login/views/lock_screen.cc b/ash/login/views/lock_screen.cc new file mode 100644 index 0000000..44bd17d --- /dev/null +++ b/ash/login/views/lock_screen.cc
@@ -0,0 +1,18 @@ +// 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 "ash/login/views/lock_screen.h" + +#include "ash/login/views/lock_contents_view.h" +#include "ui/views/widget/widget.h" + +namespace ash { + +void ShowLockScreenInWidget(views::Widget* widget) { + views::View* contents = new LockContentsView(); + widget->SetContentsView(contents); + widget->Show(); +} + +} // namespace ash
diff --git a/ash/login/views/lock_screen.h b/ash/login/views/lock_screen.h new file mode 100644 index 0000000..41a5705 --- /dev/null +++ b/ash/login/views/lock_screen.h
@@ -0,0 +1,23 @@ +// 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 ASH_LOGIN_VIEWS_LOCK_SCREEN_H_ +#define ASH_LOGIN_VIEWS_LOCK_SCREEN_H_ + +#include "ash/ash_export.h" + +namespace views { +class Widget; +} + +namespace ash { + +// Fills the given widget with the lock screen view and displays it. +// +// The lock screen communicates with the backend C++ via a mojo API. +ASH_EXPORT void ShowLockScreenInWidget(views::Widget* widget); + +} // namespace ash + +#endif // ASH_LOGIN_VIEWS_LOCK_SCREEN_H_
diff --git a/ash/root_window_controller.cc b/ash/root_window_controller.cc index 95c991d..ab4e14c 100644 --- a/ash/root_window_controller.cc +++ b/ash/root_window_controller.cc
@@ -11,7 +11,6 @@ #include "ash/ash_constants.h" #include "ash/ash_switches.h" #include "ash/ash_touch_exploration_manager_chromeos.h" -#include "ash/aura/aura_layout_manager_adapter.h" #include "ash/focus_cycler.h" #include "ash/high_contrast/high_contrast_controller.h" #include "ash/host/ash_window_tree_host.h" @@ -234,8 +233,7 @@ src_container->children(); auto iter = src_container_children.begin(); while (iter != src_container_children.end() && - SystemModalContainerLayoutManager::IsModalBackground( - WmWindow::Get(*iter))) { + SystemModalContainerLayoutManager::IsModalBackground(*iter)) { ++iter; } // If the entire window list is modal background windows then stop. @@ -384,26 +382,25 @@ } SystemModalContainerLayoutManager* -RootWindowController::GetSystemModalLayoutManager(WmWindow* window) { - WmWindow* modal_container = nullptr; +RootWindowController::GetSystemModalLayoutManager(aura::Window* window) { + aura::Window* modal_container = nullptr; if (window) { - aura::Window* window_container = - wm::GetContainerForWindow(window->aura_window()); + aura::Window* window_container = wm::GetContainerForWindow(window); if (window_container && window_container->id() >= kShellWindowId_LockScreenContainer) { - modal_container = GetWmContainer(kShellWindowId_LockSystemModalContainer); + modal_container = GetContainer(kShellWindowId_LockSystemModalContainer); } else { - modal_container = GetWmContainer(kShellWindowId_SystemModalContainer); + modal_container = GetContainer(kShellWindowId_SystemModalContainer); } } else { int modal_window_id = Shell::Get()->session_controller()->IsUserSessionBlocked() ? kShellWindowId_LockSystemModalContainer : kShellWindowId_SystemModalContainer; - modal_container = GetWmContainer(modal_window_id); + modal_container = GetContainer(modal_window_id); } return modal_container ? static_cast<SystemModalContainerLayoutManager*>( - modal_container->GetLayoutManager()) + modal_container->layout_manager()) : nullptr; } @@ -441,7 +438,7 @@ aura::Window* modal_container = GetContainer(modal_container_id); SystemModalContainerLayoutManager* modal_layout_manager = nullptr; modal_layout_manager = static_cast<SystemModalContainerLayoutManager*>( - WmWindow::Get(modal_container)->GetLayoutManager()); + modal_container->layout_manager()); if (modal_layout_manager->has_window_dimmer()) blocking_container = modal_container; @@ -458,8 +455,7 @@ // If the window is in the target modal container, only allow the top most // one. if (modal_container && modal_container->Contains(window)) - return modal_layout_manager->IsPartOfActiveModalWindow( - WmWindow::Get(window)); + return modal_layout_manager->IsPartOfActiveModalWindow(window); return true; } @@ -646,8 +642,7 @@ return; } DCHECK(keyboard_controller); - Shell::Get()->NotifyVirtualKeyboardActivated(true, - WmWindow::Get(GetRootWindow())); + Shell::Get()->NotifyVirtualKeyboardActivated(true, GetRootWindow()); aura::Window* parent = GetContainer(kShellWindowId_ImeWindowParentContainer); DCHECK(parent); aura::Window* keyboard_container = keyboard_controller->GetContainerWindow(); @@ -671,8 +666,7 @@ keyboard_controller->HideKeyboard( keyboard::KeyboardController::HIDE_REASON_AUTOMATIC); parent->RemoveChild(keyboard_container); - Shell::Get()->NotifyVirtualKeyboardActivated( - false, WmWindow::Get(GetRootWindow())); + Shell::Get()->NotifyVirtualKeyboardActivated(false, GetRootWindow()); } } @@ -795,32 +789,30 @@ DCHECK(!wm_shelf_->shelf_widget()); GetShelf()->CreateShelfWidget(GetWindow()); - WmWindow* root = GetWindow(); + aura::Window* root = GetRootWindow(); root_window_layout_manager_ = new wm::RootWindowLayoutManager(root); - root->SetLayoutManager(base::WrapUnique(root_window_layout_manager_)); + root->SetLayoutManager(root_window_layout_manager_); aura::Window* default_container = GetContainer(kShellWindowId_DefaultContainer); // Installs WorkspaceLayoutManager on |default_container|. workspace_controller_.reset(new WorkspaceController(default_container)); - WmWindow* modal_container = - GetWmContainer(kShellWindowId_SystemModalContainer); - DCHECK(modal_container); + aura::Window* modal_container = + GetContainer(kShellWindowId_SystemModalContainer); modal_container->SetLayoutManager( - base::MakeUnique<SystemModalContainerLayoutManager>(modal_container)); + new SystemModalContainerLayoutManager(modal_container)); - WmWindow* lock_modal_container = - GetWmContainer(kShellWindowId_LockSystemModalContainer); + aura::Window* lock_modal_container = + GetContainer(kShellWindowId_LockSystemModalContainer); DCHECK(lock_modal_container); lock_modal_container->SetLayoutManager( - base::MakeUnique<SystemModalContainerLayoutManager>( - lock_modal_container)); + new SystemModalContainerLayoutManager(lock_modal_container)); - WmWindow* lock_container = GetWmContainer(kShellWindowId_LockScreenContainer); + aura::Window* lock_container = + GetContainer(kShellWindowId_LockScreenContainer); DCHECK(lock_container); - lock_container->SetLayoutManager( - base::MakeUnique<LockLayoutManager>(lock_container)); + lock_container->SetLayoutManager(new LockLayoutManager(lock_container)); WmWindow* always_on_top_container = GetWmContainer(kShellWindowId_AlwaysOnTopContainer);
diff --git a/ash/root_window_controller.h b/ash/root_window_controller.h index 641710e8..6f0945f 100644 --- a/ash/root_window_controller.h +++ b/ash/root_window_controller.h
@@ -179,7 +179,7 @@ // modal container is used if the screen is currently locked. Otherwise, the // default modal container is used. SystemModalContainerLayoutManager* GetSystemModalLayoutManager( - WmWindow* window); + aura::Window* window); AlwaysOnTopController* always_on_top_controller() { return always_on_top_controller_.get();
diff --git a/ash/root_window_controller_unittest.cc b/ash/root_window_controller_unittest.cc index 4693707..242c6d0 100644 --- a/ash/root_window_controller_unittest.cc +++ b/ash/root_window_controller_unittest.cc
@@ -18,7 +18,6 @@ #include "ash/wm/window_state.h" #include "ash/wm/window_state_aura.h" #include "ash/wm/window_util.h" -#include "ash/wm_window.h" #include "base/command_line.h" #include "ui/aura/client/focus_change_observer.h" #include "ui/aura/client/focus_client.h" @@ -95,8 +94,9 @@ DISALLOW_COPY_AND_ASSIGN(DeleteOnBlurDelegate); }; -WmLayoutManager* GetLayoutManager(RootWindowController* controller, int id) { - return WmWindow::Get(controller->GetContainer(id))->GetLayoutManager(); +aura::LayoutManager* GetLayoutManager(RootWindowController* controller, + int id) { + return controller->GetContainer(id)->layout_manager(); } } // namespace @@ -394,7 +394,7 @@ CreateModalWidget(gfx::Rect(300, 10, 100, 100)); EXPECT_EQ(GetLayoutManager(controller, kShellWindowId_SystemModalContainer), controller->GetSystemModalLayoutManager( - WmWindow::Get(session_modal_widget->GetNativeWindow()))); + session_modal_widget->GetNativeWindow())); Shell::Get()->session_controller()->LockScreenAndFlushForTest(); EXPECT_TRUE(Shell::Get()->session_controller()->IsScreenLocked()); @@ -409,10 +409,10 @@ EXPECT_EQ( GetLayoutManager(controller, kShellWindowId_LockSystemModalContainer), controller->GetSystemModalLayoutManager( - WmWindow::Get(lock_modal_widget->GetNativeWindow()))); + lock_modal_widget->GetNativeWindow())); EXPECT_EQ(GetLayoutManager(controller, kShellWindowId_SystemModalContainer), controller->GetSystemModalLayoutManager( - WmWindow::Get(session_modal_widget->GetNativeWindow()))); + session_modal_widget->GetNativeWindow())); GetSessionControllerClient()->UnlockScreen(); } @@ -439,7 +439,7 @@ EXPECT_EQ( GetLayoutManager(controller, kShellWindowId_LockSystemModalContainer), controller->GetSystemModalLayoutManager( - WmWindow::Get(login_modal_widget->GetNativeWindow()))); + login_modal_widget->GetNativeWindow())); login_modal_widget->Close(); // Configure user session environment. @@ -454,7 +454,7 @@ CreateModalWidget(gfx::Rect(300, 10, 100, 100)); EXPECT_EQ(GetLayoutManager(controller, kShellWindowId_SystemModalContainer), controller->GetSystemModalLayoutManager( - WmWindow::Get(session_modal_widget->GetNativeWindow()))); + session_modal_widget->GetNativeWindow())); } TEST_F(RootWindowControllerTest, ModalContainerBlockedSession) { @@ -469,7 +469,7 @@ CreateModalWidget(gfx::Rect(300, 10, 100, 100)); EXPECT_EQ(GetLayoutManager(controller, kShellWindowId_SystemModalContainer), controller->GetSystemModalLayoutManager( - WmWindow::Get(session_modal_widget->GetNativeWindow()))); + session_modal_widget->GetNativeWindow())); EXPECT_EQ(GetLayoutManager(controller, kShellWindowId_SystemModalContainer), controller->GetSystemModalLayoutManager(NULL)); session_modal_widget->Close(); @@ -485,12 +485,12 @@ EXPECT_EQ( GetLayoutManager(controller, kShellWindowId_LockSystemModalContainer), controller->GetSystemModalLayoutManager( - WmWindow::Get(lock_modal_widget->GetNativeWindow()))); + lock_modal_widget->GetNativeWindow())); session_modal_widget = CreateModalWidget(gfx::Rect(300, 10, 100, 100)); EXPECT_EQ(GetLayoutManager(controller, kShellWindowId_SystemModalContainer), controller->GetSystemModalLayoutManager( - WmWindow::Get(session_modal_widget->GetNativeWindow()))); + session_modal_widget->GetNativeWindow())); session_modal_widget->Close(); lock_modal_widget->Close();
diff --git a/ash/shelf/shelf_layout_manager.cc b/ash/shelf/shelf_layout_manager.cc index 0d27fb1a..19deab0a 100644 --- a/ash/shelf/shelf_layout_manager.cc +++ b/ash/shelf/shelf_layout_manager.cc
@@ -389,15 +389,14 @@ LayoutShelf(); } -void ShelfLayoutManager::SetChildBounds(WmWindow* child, +void ShelfLayoutManager::SetChildBounds(aura::Window* child, const gfx::Rect& requested_bounds) { wm::WmSnapToPixelLayoutManager::SetChildBounds(child, requested_bounds); // We may contain other widgets (such as frame maximize bubble) but they don't // effect the layout in anyway. if (!updating_bounds_ && - ((WmWindow::Get(shelf_widget_->GetNativeWindow()) == child) || - (WmWindow::Get(shelf_widget_->status_area_widget()->GetNativeWindow()) == - child))) { + ((shelf_widget_->GetNativeWindow() == child) || + (shelf_widget_->status_area_widget()->GetNativeWindow() == child))) { LayoutShelf(); } } @@ -412,11 +411,11 @@ UpdateVisibilityState(); } -void ShelfLayoutManager::OnVirtualKeyboardStateChanged(bool activated, - WmWindow* root_window) { +void ShelfLayoutManager::OnVirtualKeyboardStateChanged( + bool activated, + aura::Window* root_window) { UpdateKeyboardObserverFromStateChanged( - activated, root_window, - WmWindow::Get(shelf_widget_->GetNativeWindow())->GetRootWindow(), + activated, root_window, shelf_widget_->GetNativeWindow()->GetRootWindow(), &keyboard_observer_); }
diff --git a/ash/shelf/shelf_layout_manager.h b/ash/shelf/shelf_layout_manager.h index 1f56cb7..5a88d01 100644 --- a/ash/shelf/shelf_layout_manager.h +++ b/ash/shelf/shelf_layout_manager.h
@@ -129,14 +129,14 @@ // Overridden from wm::WmSnapToPixelLayoutManager: void OnWindowResized() override; - void SetChildBounds(WmWindow* child, + void SetChildBounds(aura::Window* child, const gfx::Rect& requested_bounds) override; // Overridden from ShellObserver: void OnShelfAutoHideBehaviorChanged(WmWindow* root_window) override; void OnPinnedStateChanged(WmWindow* pinned_window) override; void OnVirtualKeyboardStateChanged(bool activated, - WmWindow* root_window) override; + aura::Window* root_window) override; // Overridden from aura::client::ActivationChangeObserver: void OnWindowActivated(ActivationReason reason,
diff --git a/ash/shelf/shelf_widget.cc b/ash/shelf/shelf_widget.cc index abc20e1..96a7321 100644 --- a/ash/shelf/shelf_widget.cc +++ b/ash/shelf/shelf_widget.cc
@@ -156,7 +156,7 @@ shelf_layout_manager_ = new ShelfLayoutManager(this, wm_shelf_); shelf_layout_manager_->AddObserver(this); - shelf_container->SetLayoutManager(base::WrapUnique(shelf_layout_manager_)); + shelf_container->aura_window()->SetLayoutManager(shelf_layout_manager_); background_animator_.PaintBackground( shelf_layout_manager_->GetShelfBackgroundType(), AnimationChangeType::IMMEDIATE); @@ -184,8 +184,8 @@ status_area_widget_->Show(); Shell::Get()->focus_cycler()->AddWidget(status_area_widget_); background_animator_.AddObserver(status_area_widget_); - status_container->SetLayoutManager( - base::MakeUnique<StatusAreaLayoutManager>(this)); + status_container->aura_window()->SetLayoutManager( + new StatusAreaLayoutManager(this)); } void ShelfWidget::SetPaintsBackground(ShelfBackgroundType background_type,
diff --git a/ash/shell.cc b/ash/shell.cc index 95ff72c..3988f49 100644 --- a/ash/shell.cc +++ b/ash/shell.cc
@@ -524,7 +524,7 @@ } void Shell::NotifyVirtualKeyboardActivated(bool activated, - WmWindow* root_window) { + aura::Window* root_window) { for (auto& observer : shell_observers_) observer.OnVirtualKeyboardStateChanged(activated, root_window); }
diff --git a/ash/shell.h b/ash/shell.h index bdc37975..94fc96da 100644 --- a/ash/shell.h +++ b/ash/shell.h
@@ -580,7 +580,8 @@ // Notifies observers that the virtual keyboard has been // activated/deactivated for |root_window|. - void NotifyVirtualKeyboardActivated(bool activated, WmWindow* root_window); + void NotifyVirtualKeyboardActivated(bool activated, + aura::Window* root_window); // Notifies observers that the shelf was created for |root_window|. // TODO(jamescook): Move to Shelf.
diff --git a/ash/shell_observer.h b/ash/shell_observer.h index 53e8d5f..a98700a 100644 --- a/ash/shell_observer.h +++ b/ash/shell_observer.h
@@ -8,6 +8,10 @@ #include "ash/ash_export.h" #include "ash/login_status.h" +namespace aura { +class Window; +} + namespace ash { class WmWindow; @@ -59,7 +63,7 @@ // Called when keyboard is activated/deactivated in |root_window|. virtual void OnVirtualKeyboardStateChanged(bool activated, - WmWindow* root_window) {} + aura::Window* root_window) {} // Called at the end of Shell::Init. virtual void OnShellInitialized() {}
diff --git a/ash/shell_port.cc b/ash/shell_port.cc index 91c0f6a..66d9c43d 100644 --- a/ash/shell_port.cc +++ b/ash/shell_port.cc
@@ -98,25 +98,25 @@ return false; } -void ShellPort::CreateModalBackground(WmWindow* window) { - for (WmWindow* root_window : GetAllRootWindows()) { - root_window->GetRootWindowController() +void ShellPort::CreateModalBackground(aura::Window* window) { + for (aura::Window* root_window : Shell::GetAllRootWindows()) { + RootWindowController::ForWindow(root_window) ->GetSystemModalLayoutManager(window) ->CreateModalBackground(); } } -void ShellPort::OnModalWindowRemoved(WmWindow* removed) { - WmWindow::Windows root_windows = GetAllRootWindows(); - for (WmWindow* root_window : root_windows) { - if (root_window->GetRootWindowController() +void ShellPort::OnModalWindowRemoved(aura::Window* removed) { + aura::Window::Windows root_windows = Shell::GetAllRootWindows(); + for (aura::Window* root_window : root_windows) { + if (RootWindowController::ForWindow(root_window) ->GetSystemModalLayoutManager(removed) ->ActivateNextModalWindow()) { return; } } - for (WmWindow* root_window : root_windows) { - root_window->GetRootWindowController() + for (aura::Window* root_window : root_windows) { + RootWindowController::ForWindow(root_window) ->GetSystemModalLayoutManager(removed) ->DestroyModalBackground(); }
diff --git a/ash/shell_port.h b/ash/shell_port.h index ea1ea9c..1daaeeb 100644 --- a/ash/shell_port.h +++ b/ash/shell_port.h
@@ -120,11 +120,11 @@ // Creates a modal background (a partially-opaque fullscreen window) on all // displays for |window|. - void CreateModalBackground(WmWindow* window); + void CreateModalBackground(aura::Window* window); // Called when a modal window is removed. It will activate another modal // window if any, or remove modal screens on all displays. - void OnModalWindowRemoved(WmWindow* removed); + void OnModalWindowRemoved(aura::Window* removed); // For testing only: set simulation that a modal window is open void SimulateModalWindowOpenForTesting(bool modal_window_open) {
diff --git a/ash/system/audio/volume_view.cc b/ash/system/audio/volume_view.cc index c7ed0f3..e541e5e 100644 --- a/ash/system/audio/volume_view.cc +++ b/ash/system/audio/volume_view.cc
@@ -101,7 +101,7 @@ l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_VOLUME_MUTE)); node_data->role = ui::AX_ROLE_TOGGLE_BUTTON; if (CrasAudioHandler::Get()->IsOutputMuted()) - node_data->AddStateFlag(ui::AX_STATE_PRESSED); + node_data->AddState(ui::AX_STATE_PRESSED); } views::ImageView* image_;
diff --git a/ash/system/ime_menu/ime_menu_tray_unittest.cc b/ash/system/ime_menu/ime_menu_tray_unittest.cc index c759c18..4fefaa4 100644 --- a/ash/system/ime_menu/ime_menu_tray_unittest.cc +++ b/ash/system/ime_menu/ime_menu_tray_unittest.cc
@@ -70,7 +70,6 @@ // Tests that the checked IME is the current IME. ui::AXNodeData node_data; - node_data.state = 0; ime.first->GetAccessibleNodeData(&node_data); const auto checked_state = static_cast<ui::AXCheckedState>( node_data.GetIntAttribute(ui::AX_ATTR_CHECKED_STATE));
diff --git a/ash/system/status_area_layout_manager.cc b/ash/system/status_area_layout_manager.cc index f095995..05140c5b 100644 --- a/ash/system/status_area_layout_manager.cc +++ b/ash/system/status_area_layout_manager.cc
@@ -7,8 +7,8 @@ #include "ash/shelf/shelf_layout_manager.h" #include "ash/shelf/shelf_widget.h" #include "ash/system/status_area_widget.h" -#include "ash/wm_window.h" #include "base/auto_reset.h" +#include "ui/aura/window.h" namespace ash { @@ -28,12 +28,11 @@ } void StatusAreaLayoutManager::SetChildBounds( - WmWindow* child, + aura::Window* child, const gfx::Rect& requested_bounds) { // Only need to have the shelf do a layout if the child changing is the status // area and the shelf isn't in the process of doing a layout. - if (child != WmWindow::Get( - shelf_widget_->status_area_widget()->GetNativeWindow()) || + if (child != shelf_widget_->status_area_widget()->GetNativeWindow() || in_layout_) { wm::WmSnapToPixelLayoutManager::SetChildBounds(child, requested_bounds); return;
diff --git a/ash/system/status_area_layout_manager.h b/ash/system/status_area_layout_manager.h index 2d1fecb..2b67501 100644 --- a/ash/system/status_area_layout_manager.h +++ b/ash/system/status_area_layout_manager.h
@@ -22,7 +22,7 @@ // Overridden from wm::WmSnapToPixelLayoutManager: void OnWindowResized() override; - void SetChildBounds(WmWindow* child, + void SetChildBounds(aura::Window* child, const gfx::Rect& requested_bounds) override; private:
diff --git a/ash/wm/lock_layout_manager.cc b/ash/wm/lock_layout_manager.cc index 32cdf72..2ad40948 100644 --- a/ash/wm/lock_layout_manager.cc +++ b/ash/wm/lock_layout_manager.cc
@@ -8,6 +8,7 @@ #include "ash/shell.h" #include "ash/wm/lock_window_state.h" #include "ash/wm/window_state.h" +#include "ash/wm/window_state_aura.h" #include "ash/wm/wm_event.h" #include "ash/wm_window.h" #include "ui/events/event.h" @@ -16,23 +17,23 @@ namespace ash { -LockLayoutManager::LockLayoutManager(WmWindow* window) +LockLayoutManager::LockLayoutManager(aura::Window* window) : wm::WmSnapToPixelLayoutManager(), window_(window), root_window_(window->GetRootWindow()), keyboard_observer_(this) { Shell::Get()->AddShellObserver(this); - root_window_->aura_window()->AddObserver(this); + root_window_->AddObserver(this); if (keyboard::KeyboardController::GetInstance()) keyboard_observer_.Add(keyboard::KeyboardController::GetInstance()); } LockLayoutManager::~LockLayoutManager() { if (root_window_) - root_window_->aura_window()->RemoveObserver(this); + root_window_->RemoveObserver(this); - for (WmWindow* child : window_->GetChildren()) - child->aura_window()->RemoveObserver(this); + for (aura::Window* child : window_->children()) + child->RemoveObserver(this); Shell::Get()->RemoveShellObserver(this); } @@ -42,48 +43,50 @@ AdjustWindowsForWorkAreaChange(&event); } -void LockLayoutManager::OnWindowAddedToLayout(WmWindow* child) { - child->aura_window()->AddObserver(this); +void LockLayoutManager::OnWindowAddedToLayout(aura::Window* child) { + child->AddObserver(this); // LockWindowState replaces default WindowState of a child. - wm::WindowState* window_state = LockWindowState::SetLockWindowState(child); + wm::WindowState* window_state = + LockWindowState::SetLockWindowState(WmWindow::Get(child)); wm::WMEvent event(wm::WM_EVENT_ADDED_TO_WORKSPACE); window_state->OnWMEvent(&event); } -void LockLayoutManager::OnWillRemoveWindowFromLayout(WmWindow* child) { - child->aura_window()->RemoveObserver(this); +void LockLayoutManager::OnWillRemoveWindowFromLayout(aura::Window* child) { + child->RemoveObserver(this); } -void LockLayoutManager::OnWindowRemovedFromLayout(WmWindow* child) {} +void LockLayoutManager::OnWindowRemovedFromLayout(aura::Window* child) {} -void LockLayoutManager::OnChildWindowVisibilityChanged(WmWindow* child, +void LockLayoutManager::OnChildWindowVisibilityChanged(aura::Window* child, bool visible) {} -void LockLayoutManager::SetChildBounds(WmWindow* child, +void LockLayoutManager::SetChildBounds(aura::Window* child, const gfx::Rect& requested_bounds) { - wm::WindowState* window_state = child->GetWindowState(); + wm::WindowState* window_state = wm::GetWindowState(child); wm::SetBoundsEvent event(wm::WM_EVENT_SET_BOUNDS, requested_bounds); window_state->OnWMEvent(&event); } void LockLayoutManager::OnWindowDestroying(aura::Window* window) { window->RemoveObserver(this); - if (root_window_ == WmWindow::Get(window)) + if (root_window_ == window) root_window_ = nullptr; } void LockLayoutManager::OnWindowBoundsChanged(aura::Window* window, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) { - if (root_window_ == WmWindow::Get(window)) { + if (root_window_ == window) { const wm::WMEvent wm_event(wm::WM_EVENT_DISPLAY_BOUNDS_CHANGED); AdjustWindowsForWorkAreaChange(&wm_event); } } -void LockLayoutManager::OnVirtualKeyboardStateChanged(bool activated, - WmWindow* root_window) { +void LockLayoutManager::OnVirtualKeyboardStateChanged( + bool activated, + aura::Window* root_window) { UpdateKeyboardObserverFromStateChanged(activated, root_window, root_window_, &keyboard_observer_); } @@ -102,8 +105,8 @@ DCHECK(event->type() == wm::WM_EVENT_DISPLAY_BOUNDS_CHANGED || event->type() == wm::WM_EVENT_WORKAREA_BOUNDS_CHANGED); - for (WmWindow* child : window_->GetChildren()) - child->GetWindowState()->OnWMEvent(event); + for (aura::Window* child : window_->children()) + wm::GetWindowState(child)->OnWMEvent(event); } } // namespace ash
diff --git a/ash/wm/lock_layout_manager.h b/ash/wm/lock_layout_manager.h index 4a3ec61..2674e2b 100644 --- a/ash/wm/lock_layout_manager.h +++ b/ash/wm/lock_layout_manager.h
@@ -39,16 +39,17 @@ public ShellObserver, public keyboard::KeyboardControllerObserver { public: - explicit LockLayoutManager(WmWindow* window); + explicit LockLayoutManager(aura::Window* window); ~LockLayoutManager() override; // Overridden from WmSnapToPixelLayoutManager: void OnWindowResized() override; - void OnWindowAddedToLayout(WmWindow* child) override; - void OnWillRemoveWindowFromLayout(WmWindow* child) override; - void OnWindowRemovedFromLayout(WmWindow* child) override; - void OnChildWindowVisibilityChanged(WmWindow* child, bool visibile) override; - void SetChildBounds(WmWindow* child, + void OnWindowAddedToLayout(aura::Window* child) override; + void OnWillRemoveWindowFromLayout(aura::Window* child) override; + void OnWindowRemovedFromLayout(aura::Window* child) override; + void OnChildWindowVisibilityChanged(aura::Window* child, + bool visibile) override; + void SetChildBounds(aura::Window* child, const gfx::Rect& requested_bounds) override; // Overriden from aura::WindowObserver: @@ -59,7 +60,7 @@ // ShellObserver: void OnVirtualKeyboardStateChanged(bool activated, - WmWindow* root_window) override; + aura::Window* root_window) override; // keyboard::KeyboardControllerObserver overrides: void OnKeyboardBoundsChanging(const gfx::Rect& new_bounds) override; @@ -70,8 +71,8 @@ // This happens when the display size, work area insets has changed. void AdjustWindowsForWorkAreaChange(const wm::WMEvent* event); - WmWindow* window_; - WmWindow* root_window_; + aura::Window* window_; + aura::Window* root_window_; ScopedObserver<keyboard::KeyboardController, keyboard::KeyboardControllerObserver>
diff --git a/ash/wm/panels/panel_layout_manager.cc b/ash/wm/panels/panel_layout_manager.cc index aaedc7c..81f8fe83 100644 --- a/ash/wm/panels/panel_layout_manager.cc +++ b/ash/wm/panels/panel_layout_manager.cc
@@ -337,7 +337,7 @@ } //////////////////////////////////////////////////////////////////////////////// -// PanelLayoutManager, WmLayoutManager implementation: +// PanelLayoutManager, aura::LayoutManager implementation: void PanelLayoutManager::OnWindowResized() { Relayout(); } @@ -458,11 +458,12 @@ Relayout(); } -void PanelLayoutManager::OnVirtualKeyboardStateChanged(bool activated, - WmWindow* root_window) { - UpdateKeyboardObserverFromStateChanged(activated, root_window, - panel_container_->GetRootWindow(), - &keyboard_observer_); +void PanelLayoutManager::OnVirtualKeyboardStateChanged( + bool activated, + aura::Window* root_window) { + UpdateKeyboardObserverFromStateChanged( + activated, root_window, panel_container_->GetRootWindow()->aura_window(), + &keyboard_observer_); } /////////////////////////////////////////////////////////////////////////////
diff --git a/ash/wm/panels/panel_layout_manager.h b/ash/wm/panels/panel_layout_manager.h index da5fab2..9cc572f4 100644 --- a/ash/wm/panels/panel_layout_manager.h +++ b/ash/wm/panels/panel_layout_manager.h
@@ -84,7 +84,7 @@ WmShelf* shelf() { return shelf_; } void SetShelf(WmShelf* shelf); - // WmLayoutManager: + // aura::LayoutManager: void OnWindowResized() override; void OnWindowAddedToLayout(aura::Window* child) override; void OnWillRemoveWindowFromLayout(aura::Window* child) override; @@ -98,7 +98,7 @@ void OnOverviewModeEnded() override; void OnShelfAlignmentChanged(WmWindow* root_window) override; void OnVirtualKeyboardStateChanged(bool activated, - WmWindow* root_window) override; + aura::Window* root_window) override; // aura::WindowObserver void OnWindowPropertyChanged(aura::Window* window,
diff --git a/ash/wm/root_window_layout_manager.cc b/ash/wm/root_window_layout_manager.cc index 40b4df6..58359b0e 100644 --- a/ash/wm/root_window_layout_manager.cc +++ b/ash/wm/root_window_layout_manager.cc
@@ -4,7 +4,6 @@ #include "ash/wm/root_window_layout_manager.h" -#include "ash/wm_window.h" #include "ui/aura/window.h" #include "ui/aura/window_tracker.h" @@ -42,7 +41,7 @@ //////////////////////////////////////////////////////////////////////////////// // RootWindowLayoutManager, public: -RootWindowLayoutManager::RootWindowLayoutManager(WmWindow* owner) +RootWindowLayoutManager::RootWindowLayoutManager(aura::Window* owner) : owner_(owner) {} RootWindowLayoutManager::~RootWindowLayoutManager() {} @@ -51,23 +50,24 @@ // RootWindowLayoutManager, aura::LayoutManager implementation: void RootWindowLayoutManager::OnWindowResized() { - ResizeWindow(owner_->aura_window()->children(), - gfx::Rect(owner_->GetBounds().size()), 0); + ResizeWindow(owner_->children(), gfx::Rect(owner_->bounds().size()), 0); } -void RootWindowLayoutManager::OnWindowAddedToLayout(WmWindow* child) {} +void RootWindowLayoutManager::OnWindowAddedToLayout(aura::Window* child) {} -void RootWindowLayoutManager::OnWillRemoveWindowFromLayout(WmWindow* child) {} +void RootWindowLayoutManager::OnWillRemoveWindowFromLayout( + aura::Window* child) {} -void RootWindowLayoutManager::OnWindowRemovedFromLayout(WmWindow* child) {} +void RootWindowLayoutManager::OnWindowRemovedFromLayout(aura::Window* child) {} -void RootWindowLayoutManager::OnChildWindowVisibilityChanged(WmWindow* child, - bool visible) {} +void RootWindowLayoutManager::OnChildWindowVisibilityChanged( + aura::Window* child, + bool visible) {} void RootWindowLayoutManager::SetChildBounds( - WmWindow* child, + aura::Window* child, const gfx::Rect& requested_bounds) { - child->SetBoundsDirect(requested_bounds); + SetChildBoundsDirect(child, requested_bounds); } } // namespace wm
diff --git a/ash/wm/root_window_layout_manager.h b/ash/wm/root_window_layout_manager.h index 4ea099b..00c4d1d 100644 --- a/ash/wm/root_window_layout_manager.h +++ b/ash/wm/root_window_layout_manager.h
@@ -5,8 +5,8 @@ #ifndef ASH_WM_ROOT_WINDOW_LAYOUT_MANAGER_H_ #define ASH_WM_ROOT_WINDOW_LAYOUT_MANAGER_H_ -#include "ash/wm_layout_manager.h" #include "base/macros.h" +#include "ui/aura/layout_manager.h" namespace ash { namespace wm { @@ -14,22 +14,23 @@ // A layout manager for the root window. // Resizes all of its immediate children and their descendants to fill the // bounds of the associated window. -class RootWindowLayoutManager : public WmLayoutManager { +class RootWindowLayoutManager : public aura::LayoutManager { public: - explicit RootWindowLayoutManager(WmWindow* owner); + explicit RootWindowLayoutManager(aura::Window* owner); ~RootWindowLayoutManager() override; // Overridden from aura::LayoutManager: void OnWindowResized() override; - void OnWindowAddedToLayout(WmWindow* child) override; - void OnWillRemoveWindowFromLayout(WmWindow* child) override; - void OnWindowRemovedFromLayout(WmWindow* child) override; - void OnChildWindowVisibilityChanged(WmWindow* child, bool visible) override; - void SetChildBounds(WmWindow* child, + void OnWindowAddedToLayout(aura::Window* child) override; + void OnWillRemoveWindowFromLayout(aura::Window* child) override; + void OnWindowRemovedFromLayout(aura::Window* child) override; + void OnChildWindowVisibilityChanged(aura::Window* child, + bool visible) override; + void SetChildBounds(aura::Window* child, const gfx::Rect& requested_bounds) override; private: - WmWindow* owner_; + aura::Window* owner_; DISALLOW_COPY_AND_ASSIGN(RootWindowLayoutManager); };
diff --git a/ash/wm/system_modal_container_layout_manager.cc b/ash/wm/system_modal_container_layout_manager.cc index 1a2d659..333ae9e 100644 --- a/ash/wm/system_modal_container_layout_manager.cc +++ b/ash/wm/system_modal_container_layout_manager.cc
@@ -13,12 +13,12 @@ #include "ash/shell_port.h" #include "ash/wm/window_dimmer.h" #include "ash/wm/window_util.h" -#include "ash/wm_window.h" #include "base/memory/ptr_util.h" #include "base/stl_util.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/keyboard/keyboard_controller.h" +#include "ui/wm/core/window_util.h" namespace ash { namespace { @@ -27,13 +27,13 @@ // of the container to be kept centered upon resizing operations. const int kCenterPixelDelta = 32; -ui::ModalType GetModalType(WmWindow* window) { - return static_cast<ui::ModalType>( - window->aura_window()->GetProperty(aura::client::kModalKey)); +ui::ModalType GetModalType(aura::Window* window) { + return window->GetProperty(aura::client::kModalKey); } -bool HasTransientAncestor(const WmWindow* window, const WmWindow* ancestor) { - const WmWindow* transient_parent = window->GetTransientParent(); +bool HasTransientAncestor(const aura::Window* window, + const aura::Window* ancestor) { + const aura::Window* transient_parent = ::wm::GetTransientParent(window); if (transient_parent == ancestor) return true; return transient_parent ? HasTransientAncestor(transient_parent, ancestor) @@ -45,7 +45,7 @@ // SystemModalContainerLayoutManager, public: SystemModalContainerLayoutManager::SystemModalContainerLayoutManager( - WmWindow* container) + aura::Window* container) : container_(container) {} SystemModalContainerLayoutManager::~SystemModalContainerLayoutManager() { @@ -54,10 +54,10 @@ } //////////////////////////////////////////////////////////////////////////////// -// SystemModalContainerLayoutManager, WmLayoutManager implementation: +// SystemModalContainerLayoutManager, aura::LayoutManager implementation: void SystemModalContainerLayoutManager::OnChildWindowVisibilityChanged( - WmWindow* window, + aura::Window* window, bool visible) { if (GetModalType(window) != ui::MODAL_TYPE_SYSTEM) return; @@ -75,14 +75,14 @@ PositionDialogsAfterWorkAreaResize(); } -void SystemModalContainerLayoutManager::OnWindowAddedToLayout(WmWindow* child) { - DCHECK(child->GetType() == ui::wm::WINDOW_TYPE_NORMAL || - child->GetType() == ui::wm::WINDOW_TYPE_POPUP); +void SystemModalContainerLayoutManager::OnWindowAddedToLayout( + aura::Window* child) { + DCHECK(child->type() == ui::wm::WINDOW_TYPE_NORMAL || + child->type() == ui::wm::WINDOW_TYPE_POPUP); // TODO(mash): IsUserSessionBlocked() depends on knowing the login state. We // need a non-stub version of SessionStateDelegate. crbug.com/648964 if (Shell::GetAshConfig() != Config::MASH) { - DCHECK(container_->aura_window()->id() != - kShellWindowId_LockSystemModalContainer || + DCHECK(container_->id() != kShellWindowId_LockSystemModalContainer || Shell::Get()->session_controller()->IsUserSessionBlocked()); } // Since this is for SystemModal, there is no good reason to add windows @@ -91,21 +91,21 @@ DCHECK_NE(GetModalType(child), ui::MODAL_TYPE_CHILD); DCHECK_NE(GetModalType(child), ui::MODAL_TYPE_WINDOW); - child->aura_window()->AddObserver(this); + child->AddObserver(this); if (GetModalType(child) == ui::MODAL_TYPE_SYSTEM && child->IsVisible()) AddModalWindow(child); } void SystemModalContainerLayoutManager::OnWillRemoveWindowFromLayout( - WmWindow* child) { - child->aura_window()->RemoveObserver(this); + aura::Window* child) { + child->RemoveObserver(this); windows_to_center_.erase(child); if (GetModalType(child) == ui::MODAL_TYPE_SYSTEM) RemoveModalWindow(child); } void SystemModalContainerLayoutManager::SetChildBounds( - WmWindow* child, + aura::Window* child, const gfx::Rect& requested_bounds) { WmSnapToPixelLayoutManager::SetChildBounds(child, requested_bounds); if (IsBoundsCentered(requested_bounds)) @@ -124,14 +124,13 @@ if (key != aura::client::kModalKey || !window->IsVisible()) return; - WmWindow* wm_window = WmWindow::Get(window); if (window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_SYSTEM) { - if (base::ContainsValue(modal_windows_, wm_window)) + if (base::ContainsValue(modal_windows_, window)) return; - AddModalWindow(wm_window); + AddModalWindow(window); } else { - if (RemoveModalWindow(wm_window)) - ShellPort::Get()->OnModalWindowRemoved(wm_window); + if (RemoveModalWindow(window)) + ShellPort::Get()->OnModalWindowRemoved(window); } } @@ -147,23 +146,23 @@ void SystemModalContainerLayoutManager::OnKeyboardClosed() {} bool SystemModalContainerLayoutManager::IsPartOfActiveModalWindow( - WmWindow* window) { + aura::Window* window) { return modal_window() && (modal_window()->Contains(window) || - HasTransientAncestor(window->GetToplevelWindowForFocus(), + HasTransientAncestor(::wm::GetToplevelWindow(window), modal_window())); } bool SystemModalContainerLayoutManager::ActivateNextModalWindow() { if (modal_windows_.empty()) return false; - modal_window()->Activate(); + wm::ActivateWindow(modal_window()); return true; } void SystemModalContainerLayoutManager::CreateModalBackground() { if (!window_dimmer_) { - window_dimmer_ = base::MakeUnique<WindowDimmer>(container_->aura_window()); + window_dimmer_ = base::MakeUnique<WindowDimmer>(container_); window_dimmer_->window()->SetName( "SystemModalContainerLayoutManager.ModalBackground"); // There isn't always a keyboard controller. @@ -183,24 +182,25 @@ } // static -bool SystemModalContainerLayoutManager::IsModalBackground(WmWindow* window) { - int id = window->GetParent()->aura_window()->id(); +bool SystemModalContainerLayoutManager::IsModalBackground( + aura::Window* window) { + int id = window->parent()->id(); if (id != kShellWindowId_SystemModalContainer && id != kShellWindowId_LockSystemModalContainer) return false; SystemModalContainerLayoutManager* layout_manager = static_cast<SystemModalContainerLayoutManager*>( - window->GetParent()->GetLayoutManager()); + window->parent()->layout_manager()); return layout_manager->window_dimmer_ && - WmWindow::Get(layout_manager->window_dimmer_->window()) == window; + layout_manager->window_dimmer_->window() == window; } //////////////////////////////////////////////////////////////////////////////// // SystemModalContainerLayoutManager, private: -void SystemModalContainerLayoutManager::AddModalWindow(WmWindow* window) { +void SystemModalContainerLayoutManager::AddModalWindow(aura::Window* window) { if (modal_windows_.empty()) { - WmWindow* capture_window = WmWindow::Get(wm::GetCaptureWindow()); + aura::Window* capture_window = wm::GetCaptureWindow(); if (capture_window) capture_window->ReleaseCapture(); } @@ -209,14 +209,15 @@ modal_windows_.push_back(window); ShellPort::Get()->CreateModalBackground(window); - window->GetParent()->StackChildAtTop(window); + window->parent()->StackChildAtTop(window); - gfx::Rect target_bounds = window->GetBounds(); + gfx::Rect target_bounds = window->bounds(); target_bounds.AdjustToFit(GetUsableDialogArea()); window->SetBounds(target_bounds); } -bool SystemModalContainerLayoutManager::RemoveModalWindow(WmWindow* window) { +bool SystemModalContainerLayoutManager::RemoveModalWindow( + aura::Window* window) { auto it = std::find(modal_windows_.begin(), modal_windows_.end(), window); if (it == modal_windows_.end()) return false; @@ -228,7 +229,7 @@ if (modal_windows_.empty()) return; - for (WmWindow* window : modal_windows_) + for (aura::Window* window : modal_windows_) window->SetBounds(GetCenteredAndOrFittedBounds(window)); } @@ -236,7 +237,7 @@ // Instead of resizing the system modal container, we move only the modal // windows. This way we avoid flashing lines upon resize animation and if the // keyboard will not fill left to right, the background is still covered. - gfx::Rect valid_bounds = container_->GetBounds(); + gfx::Rect valid_bounds = container_->bounds(); keyboard::KeyboardController* keyboard_controller = keyboard::KeyboardController::GetInstance(); if (keyboard_controller) { @@ -250,23 +251,23 @@ } gfx::Rect SystemModalContainerLayoutManager::GetCenteredAndOrFittedBounds( - const WmWindow* window) { + const aura::Window* window) { gfx::Rect target_bounds; gfx::Rect usable_area = GetUsableDialogArea(); if (windows_to_center_.count(window) > 0) { // Keep the dialog centered if it was centered before. target_bounds = usable_area; - target_bounds.ClampToCenteredSize(window->GetBounds().size()); + target_bounds.ClampToCenteredSize(window->bounds().size()); } else { // Keep the dialog within the usable area. - target_bounds = window->GetBounds(); + target_bounds = window->bounds(); target_bounds.AdjustToFit(usable_area); } - if (usable_area != container_->GetBounds()) { + if (usable_area != container_->bounds()) { // Don't clamp the dialog for the keyboard. Keep the size as it is but make // sure that the top remains visible. // TODO(skuhne): M37 should add over scroll functionality to address this. - target_bounds.set_size(window->GetBounds().size()); + target_bounds.set_size(window->bounds().size()); } return target_bounds; }
diff --git a/ash/wm/system_modal_container_layout_manager.h b/ash/wm/system_modal_container_layout_manager.h index 3e9a4230..d1633ef 100644 --- a/ash/wm/system_modal_container_layout_manager.h +++ b/ash/wm/system_modal_container_layout_manager.h
@@ -30,17 +30,18 @@ public aura::WindowObserver, public keyboard::KeyboardControllerObserver { public: - explicit SystemModalContainerLayoutManager(WmWindow* container); + explicit SystemModalContainerLayoutManager(aura::Window* container); ~SystemModalContainerLayoutManager() override; bool has_window_dimmer() const { return window_dimmer_ != nullptr; } // Overridden from WmSnapToPixelLayoutManager: - void OnChildWindowVisibilityChanged(WmWindow* child, bool visible) override; + void OnChildWindowVisibilityChanged(aura::Window* child, + bool visible) override; void OnWindowResized() override; - void OnWindowAddedToLayout(WmWindow* child) override; - void OnWillRemoveWindowFromLayout(WmWindow* child) override; - void SetChildBounds(WmWindow* child, + void OnWindowAddedToLayout(aura::Window* child) override; + void OnWillRemoveWindowFromLayout(aura::Window* child) override; + void SetChildBounds(aura::Window* child, const gfx::Rect& requested_bounds) override; // Overridden from aura::WindowObserver: @@ -54,7 +55,7 @@ // True if the window is either contained by the top most modal window, // or contained by its transient children. - bool IsPartOfActiveModalWindow(WmWindow* window); + bool IsPartOfActiveModalWindow(aura::Window* window); // Activates next modal window if any. Returns false if there // are no more modal windows in this layout manager. @@ -68,14 +69,14 @@ void DestroyModalBackground(); // Is the |window| modal background? - static bool IsModalBackground(WmWindow* window); + static bool IsModalBackground(aura::Window* window); private: - void AddModalWindow(WmWindow* window); + void AddModalWindow(aura::Window* window); // Removes |window| from |modal_windows_|. Returns true if |window| was in // |modal_windows_|. - bool RemoveModalWindow(WmWindow* window); + bool RemoveModalWindow(aura::Window* window); // Reposition the dialogs to become visible after the work area changes. void PositionDialogsAfterWorkAreaResize(); @@ -85,28 +86,28 @@ // Gets the new bounds for a |window| to use which are either centered (if the // window was previously centered) or fitted to the screen. - gfx::Rect GetCenteredAndOrFittedBounds(const WmWindow* window); + gfx::Rect GetCenteredAndOrFittedBounds(const aura::Window* window); // Returns true if |bounds| is considered centered. bool IsBoundsCentered(const gfx::Rect& window_bounds) const; - WmWindow* modal_window() { + aura::Window* modal_window() { return !modal_windows_.empty() ? modal_windows_.back() : nullptr; } // The container that owns the layout manager. - WmWindow* container_; + aura::Window* container_; // WindowDimmer used to dim windows behind the modal window(s) being shown in // |container_|. std::unique_ptr<WindowDimmer> window_dimmer_; // A stack of modal windows. Only the topmost can receive events. - std::vector<WmWindow*> modal_windows_; + std::vector<aura::Window*> modal_windows_; // Windows contained in this set are centered. Windows are automatically // added to this based on IsBoundsCentered(). - std::set<const WmWindow*> windows_to_center_; + std::set<const aura::Window*> windows_to_center_; DISALLOW_COPY_AND_ASSIGN(SystemModalContainerLayoutManager); };
diff --git a/ash/wm/system_modal_container_layout_manager_unittest.cc b/ash/wm/system_modal_container_layout_manager_unittest.cc index 70146ee6..a3c10da 100644 --- a/ash/wm/system_modal_container_layout_manager_unittest.cc +++ b/ash/wm/system_modal_container_layout_manager_unittest.cc
@@ -15,7 +15,6 @@ #include "ash/test/ash_test_base.h" #include "ash/wm/container_finder.h" #include "ash/wm/window_util.h" -#include "ash/wm_window.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/memory/ptr_util.h" @@ -54,7 +53,7 @@ bool has_modal_screen = !containers.empty(); for (aura::Window* container : containers) { has_modal_screen &= static_cast<SystemModalContainerLayoutManager*>( - WmWindow::Get(container)->GetLayoutManager()) + container->layout_manager()) ->has_window_dimmer(); } return has_modal_screen; @@ -804,7 +803,7 @@ SystemModalContainerLayoutManager* layout_manager = ShellPort::Get() ->GetPrimaryRootWindowController() - ->GetSystemModalLayoutManager(WmWindow::Get(modal_window.get())); + ->GetSystemModalLayoutManager(modal_window.get()); EXPECT_FALSE(ShellPort::Get()->IsSystemModalWindowOpen()); EXPECT_FALSE(layout_manager->has_window_dimmer());
diff --git a/ash/wm/window_positioning_utils.cc b/ash/wm/window_positioning_utils.cc index 03df182a..f733954 100644 --- a/ash/wm/window_positioning_utils.cc +++ b/ash/wm/window_positioning_utils.cc
@@ -152,7 +152,8 @@ // All containers that uses screen coordinates must have valid window ids. DCHECK_GE(container_id, 0); // Don't move modal background. - if (!SystemModalContainerLayoutManager::IsModalBackground(window)) + if (!SystemModalContainerLayoutManager::IsModalBackground( + window->aura_window())) dst_container = dst_root->GetChildByShellWindowId(container_id); }
diff --git a/ash/wm/wm_snap_to_pixel_layout_manager.cc b/ash/wm/wm_snap_to_pixel_layout_manager.cc index a645cc8..6eafdcc 100644 --- a/ash/wm/wm_snap_to_pixel_layout_manager.cc +++ b/ash/wm/wm_snap_to_pixel_layout_manager.cc
@@ -6,8 +6,7 @@ #include "ash/public/cpp/shell_window_ids.h" #include "ash/wm/window_properties.h" -#include "ash/wm_window.h" -#include "base/memory/ptr_util.h" +#include "ash/wm/window_util.h" #include "ui/aura/window.h" namespace ash { @@ -18,14 +17,14 @@ WmSnapToPixelLayoutManager::~WmSnapToPixelLayoutManager() {} // static -void WmSnapToPixelLayoutManager::InstallOnContainers(WmWindow* window) { - for (WmWindow* child : window->GetChildren()) { - if (child->aura_window()->id() < kShellWindowId_Min || - child->aura_window()->id() > kShellWindowId_Max) // not a container +void WmSnapToPixelLayoutManager::InstallOnContainers(aura::Window* window) { + for (aura::Window* child : window->children()) { + if (child->id() < kShellWindowId_Min || + child->id() > kShellWindowId_Max) // not a container continue; - if (child->aura_window()->GetProperty(kSnapChildrenToPixelBoundary)) { - if (!child->GetLayoutManager() && !child->aura_window()->layout_manager()) - child->SetLayoutManager(base::MakeUnique<WmSnapToPixelLayoutManager>()); + if (child->GetProperty(kSnapChildrenToPixelBoundary)) { + if (!child->layout_manager()) + child->SetLayoutManager(new WmSnapToPixelLayoutManager()); } else { InstallOnContainers(child); } @@ -34,22 +33,23 @@ void WmSnapToPixelLayoutManager::OnWindowResized() {} -void WmSnapToPixelLayoutManager::OnWindowAddedToLayout(WmWindow* child) {} +void WmSnapToPixelLayoutManager::OnWindowAddedToLayout(aura::Window* child) {} -void WmSnapToPixelLayoutManager::OnWillRemoveWindowFromLayout(WmWindow* child) { -} +void WmSnapToPixelLayoutManager::OnWillRemoveWindowFromLayout( + aura::Window* child) {} -void WmSnapToPixelLayoutManager::OnWindowRemovedFromLayout(WmWindow* child) {} +void WmSnapToPixelLayoutManager::OnWindowRemovedFromLayout( + aura::Window* child) {} -void WmSnapToPixelLayoutManager::OnChildWindowVisibilityChanged(WmWindow* child, - bool visibile) { -} +void WmSnapToPixelLayoutManager::OnChildWindowVisibilityChanged( + aura::Window* child, + bool visibile) {} void WmSnapToPixelLayoutManager::SetChildBounds( - WmWindow* child, + aura::Window* child, const gfx::Rect& requested_bounds) { - child->SetBoundsDirect(requested_bounds); - child->SnapToPixelBoundaryIfNecessary(); + SetChildBoundsDirect(child, requested_bounds); + wm::SnapWindowToPixelBoundary(child); } } // namespace wm
diff --git a/ash/wm/wm_snap_to_pixel_layout_manager.h b/ash/wm/wm_snap_to_pixel_layout_manager.h index 2d201e6..3e9ac75 100644 --- a/ash/wm/wm_snap_to_pixel_layout_manager.h +++ b/ash/wm/wm_snap_to_pixel_layout_manager.h
@@ -6,31 +6,32 @@ #define ASH_WM_WM_SNAP_TO_PIXEL_LAYOUT_MANAGER_H_ #include "ash/ash_export.h" -#include "ash/wm_layout_manager.h" #include "base/macros.h" +#include "ui/aura/layout_manager.h" namespace ash { namespace wm { // A layout manager that places children's layer at the physical pixel // boundaries. -class ASH_EXPORT WmSnapToPixelLayoutManager : public WmLayoutManager { +class ASH_EXPORT WmSnapToPixelLayoutManager : public aura::LayoutManager { public: WmSnapToPixelLayoutManager(); ~WmSnapToPixelLayoutManager() override; // Sets WmSnapToPixelLayoutManager as the LayoutManager on the appropriate // descendants of |window|. - static void InstallOnContainers(WmWindow* window); + static void InstallOnContainers(aura::Window* window); protected: // Overridden from aura::LayoutManager: void OnWindowResized() override; - void OnWindowAddedToLayout(WmWindow* child) override; - void OnWillRemoveWindowFromLayout(WmWindow* child) override; - void OnWindowRemovedFromLayout(WmWindow* child) override; - void OnChildWindowVisibilityChanged(WmWindow* child, bool visibile) override; - void SetChildBounds(WmWindow* child, + void OnWindowAddedToLayout(aura::Window* child) override; + void OnWillRemoveWindowFromLayout(aura::Window* child) override; + void OnWindowRemovedFromLayout(aura::Window* child) override; + void OnChildWindowVisibilityChanged(aura::Window* child, + bool visibile) override; + void SetChildBounds(aura::Window* child, const gfx::Rect& requested_bounds) override; private:
diff --git a/ash/wm/workspace/workspace_layout_manager.cc b/ash/wm/workspace/workspace_layout_manager.cc index 32e6e17..4da7bbc 100644 --- a/ash/wm/workspace/workspace_layout_manager.cc +++ b/ash/wm/workspace/workspace_layout_manager.cc
@@ -342,9 +342,9 @@ void WorkspaceLayoutManager::OnVirtualKeyboardStateChanged( bool activated, - WmWindow* root_window) { - UpdateKeyboardObserverFromStateChanged( - activated, root_window, WmWindow::Get(root_window_), &keyboard_observer_); + aura::Window* root_window) { + UpdateKeyboardObserverFromStateChanged(activated, root_window, root_window_, + &keyboard_observer_); } //////////////////////////////////////////////////////////////////////////////
diff --git a/ash/wm/workspace/workspace_layout_manager.h b/ash/wm/workspace/workspace_layout_manager.h index 6d0e6fe..3c092d4 100644 --- a/ash/wm/workspace/workspace_layout_manager.h +++ b/ash/wm/workspace/workspace_layout_manager.h
@@ -97,7 +97,7 @@ WmWindow* root_window) override; void OnPinnedStateChanged(WmWindow* pinned_window) override; void OnVirtualKeyboardStateChanged(bool activated, - WmWindow* root_window) override; + aura::Window* root_window) override; private: typedef std::set<aura::Window*> WindowSet;
diff --git a/ash/wm_layout_manager.h b/ash/wm_layout_manager.h deleted file mode 100644 index 63ba80f..0000000 --- a/ash/wm_layout_manager.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ASH_WM_LAYOUT_MANAGER_H_ -#define ASH_WM_LAYOUT_MANAGER_H_ - -#include "ash/ash_export.h" - -namespace gfx { -class Rect; -} - -namespace ash { - -class WmWindow; - -// Used to position the child WmWindows of a WmWindow. WmLayoutManager is called -// at key points in a WmWindows life cycle thats allow sthe WmLayoutManager to -// position or change child WmWindows. -class ASH_EXPORT WmLayoutManager { - public: - virtual ~WmLayoutManager() {} - - // Invoked when the window the WmLayoutManager is associated with is resized. - virtual void OnWindowResized() = 0; - - // Invoked when a window is added to the window the WmLayoutManager is - // associated with. - virtual void OnWindowAddedToLayout(WmWindow* child) = 0; - - // Invoked prior to removing |child|. - virtual void OnWillRemoveWindowFromLayout(WmWindow* child) = 0; - - // Invoked after removing |child|. - virtual void OnWindowRemovedFromLayout(WmWindow* child) = 0; - - // Invoked when SetVisible() is invoked on |child|. |visible| is the value - // supplied to SetVisible(). If |visible| is true, child->IsVisible() may - // still return false. See description in aura::Window::IsVisible() for - // details. - virtual void OnChildWindowVisibilityChanged(WmWindow* child, - bool visibile) = 0; - - // Invoked when WmWindow::SetBounds() is called on |child|. This allows the - // WmLayoutManager to modify the bounds as appropriate before processing the - // request, including ignoring the request. Implementation must call - // SetChildBoundsDirect() so that an infinite loop does not result. - virtual void SetChildBounds(WmWindow* child, - const gfx::Rect& requested_bounds) = 0; -}; - -} // namespace ash - -#endif // ASH_WM_LAYOUT_MANAGER_H_
diff --git a/ash/wm_window.cc b/ash/wm_window.cc index 186d14e..d8387b9 100644 --- a/ash/wm_window.cc +++ b/ash/wm_window.cc
@@ -5,7 +5,6 @@ #include "ash/wm_window.h" #include "ash/ash_constants.h" -#include "ash/aura/aura_layout_manager_adapter.h" #include "ash/public/cpp/config.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/public/cpp/window_properties.h" @@ -20,7 +19,6 @@ #include "ash/wm/window_state.h" #include "ash/wm/window_state_aura.h" #include "ash/wm/window_util.h" -#include "ash/wm_layout_manager.h" #include "ash/wm_transient_window_observer.h" #include "base/memory/ptr_util.h" #include "services/ui/public/interfaces/window_manager_constants.mojom.h" @@ -309,23 +307,6 @@ return ash::wm::MoveWindowToEventRoot(window_, event); } -void WmWindow::SetLayoutManager( - std::unique_ptr<WmLayoutManager> layout_manager) { - // See ~AuraLayoutManagerAdapter for why SetLayoutManager(nullptr) is called. - window_->SetLayoutManager(nullptr); - if (!layout_manager) - return; - - // |window_| takes ownership of AuraLayoutManagerAdapter. - window_->SetLayoutManager( - new AuraLayoutManagerAdapter(window_, std::move(layout_manager))); -} - -WmLayoutManager* WmWindow::GetLayoutManager() { - AuraLayoutManagerAdapter* adapter = AuraLayoutManagerAdapter::Get(window_); - return adapter ? adapter->wm_layout_manager() : nullptr; -} - void WmWindow::SetVisibilityChangesAnimated() { ::wm::SetWindowVisibilityChangesAnimated(window_); }
diff --git a/ash/wm_window.h b/ash/wm_window.h index de47237a..6483edd1 100644 --- a/ash/wm_window.h +++ b/ash/wm_window.h
@@ -44,7 +44,6 @@ class ImmersiveFullscreenController; class RootWindowController; -class WmLayoutManager; class WmTransientWindowObserver; class WmWindowTestApi; enum class WmWindowProperty; @@ -187,9 +186,6 @@ // Moves this to the display where |event| occurred; returns true if moved. bool MoveToEventRoot(const ui::Event& event); - void SetLayoutManager(std::unique_ptr<WmLayoutManager> layout_manager); - WmLayoutManager* GetLayoutManager(); - // See wm::SetWindowVisibilityChangesAnimated() for details on what this // does. void SetVisibilityChangesAnimated();
diff --git a/base/observer_list_unittest.cc b/base/observer_list_unittest.cc index d0248c9..d2c349317 100644 --- a/base/observer_list_unittest.cc +++ b/base/observer_list_unittest.cc
@@ -600,7 +600,7 @@ // TaskScheduler can safely use |barrier|. test::ScopedTaskEnvironment scoped_task_environment; - CreateSequencedTaskRunnerWithTraits(TaskTraits().WithBaseSyncPrimitives()) + CreateSequencedTaskRunnerWithTraits({WithBaseSyncPrimitives()}) ->PostTask(FROM_HERE, base::Bind(&ObserverListThreadSafe<Foo>::AddObserver, observer_list, Unretained(&observer)));
diff --git a/base/process/kill_win.cc b/base/process/kill_win.cc index 2911b36..79e5ded 100644 --- a/base/process/kill_win.cc +++ b/base/process/kill_win.cc
@@ -144,9 +144,7 @@ PostDelayedTaskWithTraits( FROM_HERE, - TaskTraits() - .WithPriority(TaskPriority::BACKGROUND) - .WithShutdownBehavior(TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN), + {TaskPriority::BACKGROUND, TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, Bind( [](Process process) { if (WaitForSingleObject(process.Handle(), 0) == WAIT_OBJECT_0)
diff --git a/base/task_scheduler/post_task.h b/base/task_scheduler/post_task.h index 69eda89..1fc10bf 100644 --- a/base/task_scheduler/post_task.h +++ b/base/task_scheduler/post_task.h
@@ -30,7 +30,7 @@ // To post a high priority one-off task to respond to a user interaction: // PostTaskWithTraits( // FROM_HERE, -// TaskTraits().WithPriority(TaskPriority::USER_BLOCKING), +// {TaskPriority::USER_BLOCKING}, // Bind(...)); // // To post tasks that must run in sequence with default traits: @@ -43,8 +43,7 @@ // shutdown: // scoped_refptr<SequencedTaskRunner> task_runner = // CreateSequencedTaskRunnerWithTraits( -// TaskTraits().MayBlock().WithShutdownBehavior( -// TaskShutdownBehavior::SKIP_ON_SHUTDOWN)); +// {MayBlock(), TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); // task_runner.PostTask(FROM_HERE, Bind(...)); // task_runner.PostTask(FROM_HERE, Bind(...)); //
diff --git a/base/task_scheduler/priority_queue_unittest.cc b/base/task_scheduler/priority_queue_unittest.cc index afaeafb..43db55059 100644 --- a/base/task_scheduler/priority_queue_unittest.cc +++ b/base/task_scheduler/priority_queue_unittest.cc
@@ -60,27 +60,27 @@ TEST(TaskSchedulerPriorityQueueTest, PushPopPeek) { // Create test sequences. scoped_refptr<Sequence> sequence_a(new Sequence); - sequence_a->PushTask(MakeUnique<Task>( - FROM_HERE, Bind(&DoNothing), - TaskTraits().WithPriority(TaskPriority::USER_VISIBLE), TimeDelta())); + sequence_a->PushTask(MakeUnique<Task>(FROM_HERE, Bind(&DoNothing), + TaskTraits(TaskPriority::USER_VISIBLE), + TimeDelta())); SequenceSortKey sort_key_a = sequence_a->GetSortKey(); scoped_refptr<Sequence> sequence_b(new Sequence); - sequence_b->PushTask(MakeUnique<Task>( - FROM_HERE, Bind(&DoNothing), - TaskTraits().WithPriority(TaskPriority::USER_BLOCKING), TimeDelta())); + sequence_b->PushTask(MakeUnique<Task>(FROM_HERE, Bind(&DoNothing), + TaskTraits(TaskPriority::USER_BLOCKING), + TimeDelta())); SequenceSortKey sort_key_b = sequence_b->GetSortKey(); scoped_refptr<Sequence> sequence_c(new Sequence); - sequence_c->PushTask(MakeUnique<Task>( - FROM_HERE, Bind(&DoNothing), - TaskTraits().WithPriority(TaskPriority::USER_BLOCKING), TimeDelta())); + sequence_c->PushTask(MakeUnique<Task>(FROM_HERE, Bind(&DoNothing), + TaskTraits(TaskPriority::USER_BLOCKING), + TimeDelta())); SequenceSortKey sort_key_c = sequence_c->GetSortKey(); scoped_refptr<Sequence> sequence_d(new Sequence); - sequence_d->PushTask(MakeUnique<Task>( - FROM_HERE, Bind(&DoNothing), - TaskTraits().WithPriority(TaskPriority::BACKGROUND), TimeDelta())); + sequence_d->PushTask(MakeUnique<Task>(FROM_HERE, Bind(&DoNothing), + TaskTraits(TaskPriority::BACKGROUND), + TimeDelta())); SequenceSortKey sort_key_d = sequence_d->GetSortKey(); // Create a PriorityQueue and a Transaction.
diff --git a/base/task_scheduler/scheduler_single_thread_task_runner_manager.cc b/base/task_scheduler/scheduler_single_thread_task_runner_manager.cc index 3a8900b..d96b8ce 100644 --- a/base/task_scheduler/scheduler_single_thread_task_runner_manager.cc +++ b/base/task_scheduler/scheduler_single_thread_task_runner_manager.cc
@@ -214,7 +214,7 @@ DispatchMessage(&msg); }, std::move(msg)), - TaskTraits().MayBlock(), TimeDelta()); + TaskTraits(MayBlock()), TimeDelta()); if (task_tracker_->WillPostTask(pump_message_task.get())) { bool was_empty = message_pump_sequence_->PushTask(std::move(pump_message_task));
diff --git a/base/task_scheduler/scheduler_single_thread_task_runner_manager_unittest.cc b/base/task_scheduler/scheduler_single_thread_task_runner_manager_unittest.cc index 7ff0c9d0..4415f5fd 100644 --- a/base/task_scheduler/scheduler_single_thread_task_runner_manager_unittest.cc +++ b/base/task_scheduler/scheduler_single_thread_task_runner_manager_unittest.cc
@@ -93,14 +93,12 @@ single_thread_task_runner_manager_ ->CreateSingleThreadTaskRunnerWithTraits( "A", ThreadPriority::NORMAL, - TaskTraits().WithShutdownBehavior( - TaskShutdownBehavior::BLOCK_SHUTDOWN)); + {TaskShutdownBehavior::BLOCK_SHUTDOWN}); scoped_refptr<SingleThreadTaskRunner> task_runner_2 = single_thread_task_runner_manager_ ->CreateSingleThreadTaskRunnerWithTraits( "B", ThreadPriority::NORMAL, - TaskTraits().WithShutdownBehavior( - TaskShutdownBehavior::BLOCK_SHUTDOWN)); + {TaskShutdownBehavior::BLOCK_SHUTDOWN}); PlatformThreadRef thread_ref_1; task_runner_1->PostTask(FROM_HERE, @@ -122,14 +120,13 @@ // events to determine when a task is run. scoped_refptr<SingleThreadTaskRunner> task_runner_background = single_thread_task_runner_manager_ - ->CreateSingleThreadTaskRunnerWithTraits( - "Background", ThreadPriority::BACKGROUND, - TaskTraits().WithPriority(TaskPriority::BACKGROUND)); + ->CreateSingleThreadTaskRunnerWithTraits("Background", + ThreadPriority::BACKGROUND, + {TaskPriority::BACKGROUND}); scoped_refptr<SingleThreadTaskRunner> task_runner_normal = single_thread_task_runner_manager_ ->CreateSingleThreadTaskRunnerWithTraits( - "Normal", ThreadPriority::NORMAL, - TaskTraits().WithPriority(TaskPriority::USER_VISIBLE)); + "Normal", ThreadPriority::NORMAL, {TaskPriority::USER_VISIBLE}); ThreadPriority thread_priority_background; task_runner_background->PostTask( @@ -200,14 +197,12 @@ single_thread_task_runner_manager_ ->CreateSingleThreadTaskRunnerWithTraits( "A", ThreadPriority::NORMAL, - TaskTraits().WithShutdownBehavior( - TaskShutdownBehavior::BLOCK_SHUTDOWN)); + {TaskShutdownBehavior::BLOCK_SHUTDOWN}); scoped_refptr<SingleThreadTaskRunner> task_runner_2 = single_thread_task_runner_manager_ ->CreateSingleThreadTaskRunnerWithTraits( "B", ThreadPriority::NORMAL, - TaskTraits().WithShutdownBehavior( - TaskShutdownBehavior::BLOCK_SHUTDOWN)); + {TaskShutdownBehavior::BLOCK_SHUTDOWN}); EXPECT_FALSE(task_runner_1->RunsTasksOnCurrentThread()); EXPECT_FALSE(task_runner_2->RunsTasksOnCurrentThread()); @@ -287,10 +282,10 @@ WaitableEvent::InitialState::NOT_SIGNALED); { - auto task_runner = single_thread_task_runner_manager_ - ->CreateSingleThreadTaskRunnerWithTraits( - "A", ThreadPriority::NORMAL, - TaskTraits().WithBaseSyncPrimitives()); + auto task_runner = + single_thread_task_runner_manager_ + ->CreateSingleThreadTaskRunnerWithTraits( + "A", ThreadPriority::NORMAL, {WithBaseSyncPrimitives()}); EXPECT_TRUE(task_runner->PostTask( FROM_HERE, BindOnce(&WaitableEvent::Signal, Unretained(&task_running)))); @@ -317,10 +312,10 @@ WaitableEvent::InitialState::NOT_SIGNALED); { - auto task_runner = single_thread_task_runner_manager_ - ->CreateSingleThreadTaskRunnerWithTraits( - "A", ThreadPriority::NORMAL, - TaskTraits().WithBaseSyncPrimitives()); + auto task_runner = + single_thread_task_runner_manager_ + ->CreateSingleThreadTaskRunnerWithTraits( + "A", ThreadPriority::NORMAL, {WithBaseSyncPrimitives()}); EXPECT_TRUE(task_runner->PostTask( FROM_HERE, BindOnce(&WaitableEvent::Signal, Unretained(&task_running)))); @@ -343,9 +338,7 @@ TEST_F(TaskSchedulerSingleThreadTaskRunnerManagerTest, COMSTAInitialized) { scoped_refptr<SingleThreadTaskRunner> com_task_runner = single_thread_task_runner_manager_->CreateCOMSTATaskRunnerWithTraits( - "A", ThreadPriority::NORMAL, - TaskTraits().WithShutdownBehavior( - TaskShutdownBehavior::BLOCK_SHUTDOWN)); + "A", ThreadPriority::NORMAL, {TaskShutdownBehavior::BLOCK_SHUTDOWN}); com_task_runner->PostTask( FROM_HERE, BindOnce([]() { @@ -407,9 +400,7 @@ TEST_F(TaskSchedulerSingleThreadTaskRunnerManagerTestWin, PumpsMessages) { scoped_refptr<SingleThreadTaskRunner> com_task_runner = single_thread_task_runner_manager_->CreateCOMSTATaskRunnerWithTraits( - "A", ThreadPriority::NORMAL, - TaskTraits().WithShutdownBehavior( - TaskShutdownBehavior::BLOCK_SHUTDOWN)); + "A", ThreadPriority::NORMAL, {TaskShutdownBehavior::BLOCK_SHUTDOWN}); HWND hwnd = nullptr; // HWNDs process messages on the thread that created them, so we have to // create them within the context of the task runner to properly simulate a
diff --git a/base/task_scheduler/scheduler_worker_pool_impl_unittest.cc b/base/task_scheduler/scheduler_worker_pool_impl_unittest.cc index 6ee55294..527f73c0 100644 --- a/base/task_scheduler/scheduler_worker_pool_impl_unittest.cc +++ b/base/task_scheduler/scheduler_worker_pool_impl_unittest.cc
@@ -113,7 +113,7 @@ SchedulerWorkerPoolImpl* worker_pool, test::ExecutionMode execution_mode) { // Allow tasks posted to the returned TaskRunner to wait on a WaitableEvent. - const TaskTraits traits = TaskTraits().WithBaseSyncPrimitives(); + const TaskTraits traits = {WithBaseSyncPrimitives()}; switch (execution_mode) { case test::ExecutionMode::PARALLEL: return worker_pool->CreateTaskRunnerWithTraits(traits); @@ -413,13 +413,11 @@ WaitableEvent barrier(WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); - worker_pool_ - ->CreateTaskRunnerWithTraits(TaskTraits().WithBaseSyncPrimitives()) + worker_pool_->CreateTaskRunnerWithTraits({WithBaseSyncPrimitives()}) ->PostTask(FROM_HERE, Bind(&TaskPostedBeforeStart, Unretained(&task_1_thread_ref), Unretained(&task_1_scheduled), Unretained(&barrier))); - worker_pool_ - ->CreateTaskRunnerWithTraits(TaskTraits().WithBaseSyncPrimitives()) + worker_pool_->CreateTaskRunnerWithTraits({WithBaseSyncPrimitives()}) ->PostTask(FROM_HERE, Bind(&TaskPostedBeforeStart, Unretained(&task_2_thread_ref), Unretained(&task_2_scheduled), Unretained(&barrier))); @@ -491,8 +489,7 @@ std::vector<std::unique_ptr<test::TestTaskFactory>> factories; for (size_t i = 0; i < kNumWorkersInWorkerPool; ++i) { factories.push_back(MakeUnique<test::TestTaskFactory>( - worker_pool_->CreateTaskRunnerWithTraits( - TaskTraits().WithBaseSyncPrimitives()), + worker_pool_->CreateTaskRunnerWithTraits({WithBaseSyncPrimitives()}), test::ExecutionMode::PARALLEL)); ASSERT_TRUE(factories.back()->PostTask( PostNestedTask::NO, @@ -564,7 +561,7 @@ WaitableEvent::InitialState::NOT_SIGNALED); CreateAndStartWorkerPool(TimeDelta::Max(), kNumWorkersInWorkerPool); auto task_runner = worker_pool_->CreateSequencedTaskRunnerWithTraits( - TaskTraits().WithBaseSyncPrimitives()); + {WithBaseSyncPrimitives()}); // Post a task. task_runner->PostTask(FROM_HERE, @@ -607,8 +604,8 @@ WaitableEvent tasks_can_exit_event(WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); CreateAndStartWorkerPool(kReclaimTimeForDetachTests, kNumWorkersInWorkerPool); - auto task_runner = worker_pool_->CreateTaskRunnerWithTraits( - TaskTraits().WithBaseSyncPrimitives()); + auto task_runner = + worker_pool_->CreateTaskRunnerWithTraits({WithBaseSyncPrimitives()}); // Post tasks to saturate the pool. std::vector<std::unique_ptr<WaitableEvent>> task_started_events; @@ -672,7 +669,7 @@ auto histogrammed_thread_task_runner = worker_pool_->CreateSequencedTaskRunnerWithTraits( - TaskTraits().WithBaseSyncPrimitives()); + {WithBaseSyncPrimitives()}); // Post 3 tasks and hold the thread for idle thread stack ordering. // This test assumes |histogrammed_thread_task_runner| gets assigned the same @@ -730,7 +727,7 @@ WaitableEvent::InitialState::NOT_SIGNALED); auto task_runner_for_top_idle = worker_pool_->CreateSequencedTaskRunnerWithTraits( - TaskTraits().WithBaseSyncPrimitives()); + {WithBaseSyncPrimitives()}); task_runner_for_top_idle->PostTask( FROM_HERE, BindOnce( [](PlatformThreadRef thread_ref,
diff --git a/base/task_scheduler/scheduler_worker_unittest.cc b/base/task_scheduler/scheduler_worker_unittest.cc index 8d2d1b02..5d218a7 100644 --- a/base/task_scheduler/scheduler_worker_unittest.cc +++ b/base/task_scheduler/scheduler_worker_unittest.cc
@@ -450,8 +450,7 @@ }, Unretained(&controls_->work_processed_), Unretained(&controls_->work_running_)), - TaskTraits().WithBaseSyncPrimitives().WithShutdownBehavior( - TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN), + {WithBaseSyncPrimitives(), TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, TimeDelta())); EXPECT_TRUE(task_tracker_->WillPostTask(task.get())); sequence->PushTask(std::move(task));
diff --git a/base/task_scheduler/sequence_unittest.cc b/base/task_scheduler/sequence_unittest.cc index 7093b1e..c5d0506 100644 --- a/base/task_scheduler/sequence_unittest.cc +++ b/base/task_scheduler/sequence_unittest.cc
@@ -23,31 +23,26 @@ class TaskSchedulerSequenceTest : public testing::Test { public: TaskSchedulerSequenceTest() - : task_a_owned_( - new Task(FROM_HERE, - Bind(&DoNothing), - TaskTraits().WithPriority(TaskPriority::BACKGROUND), - TimeDelta())), - task_b_owned_( - new Task(FROM_HERE, - Bind(&DoNothing), - TaskTraits().WithPriority(TaskPriority::USER_VISIBLE), - TimeDelta())), - task_c_owned_( - new Task(FROM_HERE, - Bind(&DoNothing), - TaskTraits().WithPriority(TaskPriority::USER_BLOCKING), - TimeDelta())), - task_d_owned_( - new Task(FROM_HERE, - Bind(&DoNothing), - TaskTraits().WithPriority(TaskPriority::USER_BLOCKING), - TimeDelta())), - task_e_owned_( - new Task(FROM_HERE, - Bind(&DoNothing), - TaskTraits().WithPriority(TaskPriority::BACKGROUND), - TimeDelta())), + : task_a_owned_(new Task(FROM_HERE, + Bind(&DoNothing), + {TaskPriority::BACKGROUND}, + TimeDelta())), + task_b_owned_(new Task(FROM_HERE, + Bind(&DoNothing), + {TaskPriority::USER_VISIBLE}, + TimeDelta())), + task_c_owned_(new Task(FROM_HERE, + Bind(&DoNothing), + {TaskPriority::USER_BLOCKING}, + TimeDelta())), + task_d_owned_(new Task(FROM_HERE, + Bind(&DoNothing), + {TaskPriority::USER_BLOCKING}, + TimeDelta())), + task_e_owned_(new Task(FROM_HERE, + Bind(&DoNothing), + {TaskPriority::BACKGROUND}, + TimeDelta())), task_a_(task_a_owned_.get()), task_b_(task_b_owned_.get()), task_c_(task_c_owned_.get()),
diff --git a/base/task_scheduler/task_scheduler_impl_unittest.cc b/base/task_scheduler/task_scheduler_impl_unittest.cc index cc71fdf..baa3baf 100644 --- a/base/task_scheduler/task_scheduler_impl_unittest.cc +++ b/base/task_scheduler/task_scheduler_impl_unittest.cc
@@ -175,10 +175,8 @@ priority_index <= static_cast<size_t>(TaskPriority::HIGHEST); ++priority_index) { const TaskPriority priority = static_cast<TaskPriority>(priority_index); - params.push_back(TraitsExecutionModePair( - TaskTraits().WithPriority(priority), execution_mode)); - params.push_back(TraitsExecutionModePair( - TaskTraits().WithPriority(priority).MayBlock(), execution_mode)); + params.push_back(TraitsExecutionModePair({priority}, execution_mode)); + params.push_back(TraitsExecutionModePair({MayBlock()}, execution_mode)); } } @@ -368,22 +366,17 @@ TEST_F(TaskSchedulerImplTest, GetMaxConcurrentTasksWithTraitsDeprecated) { StartTaskScheduler(); EXPECT_EQ(1, scheduler_.GetMaxConcurrentTasksWithTraitsDeprecated( - TaskTraits().WithPriority(TaskPriority::BACKGROUND))); - EXPECT_EQ( - 3, scheduler_.GetMaxConcurrentTasksWithTraitsDeprecated( - TaskTraits().WithPriority(TaskPriority::BACKGROUND).MayBlock())); + {TaskPriority::BACKGROUND})); + EXPECT_EQ(3, scheduler_.GetMaxConcurrentTasksWithTraitsDeprecated( + {MayBlock(), TaskPriority::BACKGROUND})); EXPECT_EQ(4, scheduler_.GetMaxConcurrentTasksWithTraitsDeprecated( - TaskTraits().WithPriority(TaskPriority::USER_VISIBLE))); - EXPECT_EQ( - 12, - scheduler_.GetMaxConcurrentTasksWithTraitsDeprecated( - TaskTraits().WithPriority(TaskPriority::USER_VISIBLE).MayBlock())); + {TaskPriority::USER_VISIBLE})); + EXPECT_EQ(12, scheduler_.GetMaxConcurrentTasksWithTraitsDeprecated( + {MayBlock(), TaskPriority::USER_VISIBLE})); EXPECT_EQ(4, scheduler_.GetMaxConcurrentTasksWithTraitsDeprecated( - TaskTraits().WithPriority(TaskPriority::USER_BLOCKING))); - EXPECT_EQ( - 12, - scheduler_.GetMaxConcurrentTasksWithTraitsDeprecated( - TaskTraits().WithPriority(TaskPriority::USER_BLOCKING).MayBlock())); + {TaskPriority::USER_BLOCKING})); + EXPECT_EQ(12, scheduler_.GetMaxConcurrentTasksWithTraitsDeprecated( + {MayBlock(), TaskPriority::USER_BLOCKING})); } // Verify that the RunsTasksOnCurrentThread() method of a SequencedTaskRunner @@ -488,8 +481,7 @@ scoped_refptr<TaskRunner> blocking_task_runner = scheduler_.CreateSequencedTaskRunnerWithTraits( - TaskTraits().WithShutdownBehavior( - TaskShutdownBehavior::BLOCK_SHUTDOWN)); + {TaskShutdownBehavior::BLOCK_SHUTDOWN}); blocking_task_runner->PostTask( FROM_HERE, BindOnce(
diff --git a/base/task_scheduler/task_tracker_unittest.cc b/base/task_scheduler/task_tracker_unittest.cc index 96bda677..2fbfff27 100644 --- a/base/task_scheduler/task_tracker_unittest.cc +++ b/base/task_scheduler/task_tracker_unittest.cc
@@ -149,7 +149,7 @@ return MakeUnique<Task>( FROM_HERE, Bind(&TaskSchedulerTaskTrackerTest::RunTaskCallback, Unretained(this)), - TaskTraits().WithShutdownBehavior(shutdown_behavior), TimeDelta()); + TaskTraits(shutdown_behavior), TimeDelta()); } // Calls tracker_->Shutdown() on a new thread. When this returns, Shutdown() @@ -269,16 +269,15 @@ WaitableEvent::InitialState::NOT_SIGNALED); WaitableEvent task_barrier(WaitableEvent::ResetPolicy::AUTOMATIC, WaitableEvent::InitialState::NOT_SIGNALED); - auto blocked_task = base::MakeUnique<Task>( + auto blocked_task = MakeUnique<Task>( FROM_HERE, Bind( [](WaitableEvent* task_running, WaitableEvent* task_barrier) { task_running->Signal(); task_barrier->Wait(); }, - Unretained(&task_running), base::Unretained(&task_barrier)), - TaskTraits().WithBaseSyncPrimitives().WithShutdownBehavior(GetParam()), - TimeDelta()); + Unretained(&task_running), Unretained(&task_barrier)), + TaskTraits(WithBaseSyncPrimitives(), GetParam()), TimeDelta()); // Inform |task_tracker_| that |blocked_task| will be posted. EXPECT_TRUE(tracker_.WillPostTask(blocked_task.get())); @@ -429,7 +428,7 @@ TaskTracker tracker; std::unique_ptr<Task> task( new Task(FROM_HERE, BindOnce(&ThreadRestrictions::AssertSingletonAllowed), - TaskTraits().WithShutdownBehavior(GetParam()), TimeDelta())); + TaskTraits(GetParam()), TimeDelta())); EXPECT_TRUE(tracker.WillPostTask(task.get())); // Set the singleton allowed bit to the opposite of what it is expected to be @@ -453,12 +452,12 @@ // Unset the IO allowed bit. Expect TaskTracker to set it before running a // task with the MayBlock() trait. ThreadRestrictions::SetIOAllowed(false); - auto task_with_may_block = MakeUnique<Task>( - FROM_HERE, Bind([]() { - // Shouldn't fail. - ThreadRestrictions::AssertIOAllowed(); - }), - TaskTraits().MayBlock().WithShutdownBehavior(GetParam()), TimeDelta()); + auto task_with_may_block = + MakeUnique<Task>(FROM_HERE, Bind([]() { + // Shouldn't fail. + ThreadRestrictions::AssertIOAllowed(); + }), + TaskTraits(MayBlock(), GetParam()), TimeDelta()); EXPECT_TRUE(tracker.WillPostTask(task_with_may_block.get())); tracker.RunTask(std::move(task_with_may_block), SequenceToken::Create()); @@ -469,7 +468,7 @@ FROM_HERE, Bind([]() { EXPECT_DCHECK_DEATH({ ThreadRestrictions::AssertIOAllowed(); }); }), - TaskTraits().WithShutdownBehavior(GetParam()), TimeDelta()); + TaskTraits(GetParam()), TimeDelta()); EXPECT_TRUE(tracker.WillPostTask(task_without_may_block.get())); tracker.RunTask(std::move(task_without_may_block), SequenceToken::Create()); } @@ -503,7 +502,7 @@ // scope per no TaskRunner ref being set to it. std::unique_ptr<Task> verify_task( new Task(FROM_HERE, BindOnce(&VerifyNoTaskRunnerHandle), - TaskTraits().WithShutdownBehavior(GetParam()), TimeDelta())); + TaskTraits(GetParam()), TimeDelta())); RunTaskRunnerHandleVerificationTask(&tracker_, std::move(verify_task)); } @@ -525,8 +524,8 @@ std::unique_ptr<Task> verify_task( new Task(FROM_HERE, BindOnce(&VerifySequencedTaskRunnerHandle, - base::Unretained(test_task_runner.get())), - TaskTraits().WithShutdownBehavior(GetParam()), TimeDelta())); + Unretained(test_task_runner.get())), + TaskTraits(GetParam()), TimeDelta())); verify_task->sequenced_task_runner_ref = test_task_runner; RunTaskRunnerHandleVerificationTask(&tracker_, std::move(verify_task)); @@ -551,8 +550,8 @@ std::unique_ptr<Task> verify_task( new Task(FROM_HERE, BindOnce(&VerifyThreadTaskRunnerHandle, - base::Unretained(test_task_runner.get())), - TaskTraits().WithShutdownBehavior(GetParam()), TimeDelta())); + Unretained(test_task_runner.get())), + TaskTraits(GetParam()), TimeDelta())); verify_task->single_thread_task_runner_ref = test_task_runner; RunTaskRunnerHandleVerificationTask(&tracker_, std::move(verify_task)); @@ -560,17 +559,15 @@ TEST_P(TaskSchedulerTaskTrackerTest, FlushPendingDelayedTask) { const Task delayed_task(FROM_HERE, BindOnce(&DoNothing), - TaskTraits().WithShutdownBehavior(GetParam()), - TimeDelta::FromDays(1)); + TaskTraits(GetParam()), TimeDelta::FromDays(1)); tracker_.WillPostTask(&delayed_task); // Flush() should return even if the delayed task didn't run. tracker_.Flush(); } TEST_P(TaskSchedulerTaskTrackerTest, FlushPendingUndelayedTask) { - auto undelayed_task = base::MakeUnique<Task>( - FROM_HERE, Bind(&DoNothing), - TaskTraits().WithShutdownBehavior(GetParam()), TimeDelta()); + auto undelayed_task = MakeUnique<Task>(FROM_HERE, Bind(&DoNothing), + TaskTraits(GetParam()), TimeDelta()); tracker_.WillPostTask(undelayed_task.get()); // Flush() shouldn't return before the undelayed task runs. @@ -584,9 +581,8 @@ } TEST_P(TaskSchedulerTaskTrackerTest, PostTaskDuringFlush) { - auto undelayed_task = base::MakeUnique<Task>( - FROM_HERE, Bind(&DoNothing), - TaskTraits().WithShutdownBehavior(GetParam()), TimeDelta()); + auto undelayed_task = MakeUnique<Task>(FROM_HERE, Bind(&DoNothing), + TaskTraits(GetParam()), TimeDelta()); tracker_.WillPostTask(undelayed_task.get()); // Flush() shouldn't return before the undelayed task runs. @@ -595,9 +591,8 @@ VERIFY_ASYNC_FLUSH_IN_PROGRESS(); // Simulate posting another undelayed task. - auto other_undelayed_task = base::MakeUnique<Task>( - FROM_HERE, Bind(&DoNothing), - TaskTraits().WithShutdownBehavior(GetParam()), TimeDelta()); + auto other_undelayed_task = MakeUnique<Task>( + FROM_HERE, Bind(&DoNothing), TaskTraits(GetParam()), TimeDelta()); tracker_.WillPostTask(other_undelayed_task.get()); // Run the first undelayed task. @@ -614,13 +609,12 @@ TEST_P(TaskSchedulerTaskTrackerTest, RunDelayedTaskDuringFlush) { // Simulate posting a delayed and an undelayed task. - auto delayed_task = base::MakeUnique<Task>( - FROM_HERE, Bind(&DoNothing), - TaskTraits().WithShutdownBehavior(GetParam()), TimeDelta::FromDays(1)); + auto delayed_task = + MakeUnique<Task>(FROM_HERE, Bind(&DoNothing), TaskTraits(GetParam()), + TimeDelta::FromDays(1)); tracker_.WillPostTask(delayed_task.get()); - auto undelayed_task = base::MakeUnique<Task>( - FROM_HERE, Bind(&DoNothing), - TaskTraits().WithShutdownBehavior(GetParam()), TimeDelta()); + auto undelayed_task = MakeUnique<Task>(FROM_HERE, Bind(&DoNothing), + TaskTraits(GetParam()), TimeDelta()); tracker_.WillPostTask(undelayed_task.get()); // Flush() shouldn't return before the undelayed task runs. @@ -648,9 +642,8 @@ return; // Simulate posting a task. - auto undelayed_task = base::MakeUnique<Task>( - FROM_HERE, Bind(&DoNothing), - TaskTraits().WithShutdownBehavior(GetParam()), TimeDelta()); + auto undelayed_task = MakeUnique<Task>(FROM_HERE, Bind(&DoNothing), + TaskTraits(GetParam()), TimeDelta()); tracker_.WillPostTask(undelayed_task.get()); // Shutdown() should return immediately since there are no pending @@ -667,9 +660,8 @@ return; // Simulate posting a task. - auto undelayed_task = base::MakeUnique<Task>( - FROM_HERE, Bind(&DoNothing), - TaskTraits().WithShutdownBehavior(GetParam()), TimeDelta()); + auto undelayed_task = MakeUnique<Task>(FROM_HERE, Bind(&DoNothing), + TaskTraits(GetParam()), TimeDelta()); tracker_.WillPostTask(undelayed_task.get()); // Flush() shouldn't return before the undelayed task runs or @@ -711,9 +703,9 @@ // when a Task runs. TEST_F(TaskSchedulerTaskTrackerTest, CurrentSequenceToken) { const SequenceToken sequence_token(SequenceToken::Create()); - auto task = base::MakeUnique<Task>(FROM_HERE, - Bind(&ExpectSequenceToken, sequence_token), - TaskTraits(), TimeDelta()); + auto task = + MakeUnique<Task>(FROM_HERE, Bind(&ExpectSequenceToken, sequence_token), + TaskTraits(), TimeDelta()); tracker_.WillPostTask(task.get()); EXPECT_FALSE(SequenceToken::GetForCurrentThread().IsValid()); @@ -879,7 +871,7 @@ // Shouldn't fail. ThreadRestrictions::AssertWaitAllowed(); }), - TaskTraits().WithBaseSyncPrimitives(), TimeDelta()); + TaskTraits(WithBaseSyncPrimitives()), TimeDelta()); EXPECT_TRUE(tracker.WillPostTask(task_with_sync_primitives.get())); tracker.RunTask(std::move(task_with_sync_primitives), SequenceToken::Create()); @@ -912,32 +904,26 @@ const TaskTraits traits; const char* const expected_histogram; } tests[] = { - {TaskTraits().WithPriority(TaskPriority::BACKGROUND), + {{TaskPriority::BACKGROUND}, "TaskScheduler.TaskLatencyMicroseconds.BackgroundTaskPriority"}, - {TaskTraits().WithPriority(TaskPriority::BACKGROUND).MayBlock(), + {{MayBlock(), TaskPriority::BACKGROUND}, "TaskScheduler.TaskLatencyMicroseconds.BackgroundTaskPriority.MayBlock"}, - {TaskTraits() - .WithPriority(TaskPriority::BACKGROUND) - .WithBaseSyncPrimitives(), + {{WithBaseSyncPrimitives(), TaskPriority::BACKGROUND}, "TaskScheduler.TaskLatencyMicroseconds.BackgroundTaskPriority.MayBlock"}, - {TaskTraits().WithPriority(TaskPriority::USER_VISIBLE), + {{TaskPriority::USER_VISIBLE}, "TaskScheduler.TaskLatencyMicroseconds.UserVisibleTaskPriority"}, - {TaskTraits().WithPriority(TaskPriority::USER_VISIBLE).MayBlock(), + {{MayBlock(), TaskPriority::USER_VISIBLE}, "TaskScheduler.TaskLatencyMicroseconds.UserVisibleTaskPriority." "MayBlock"}, - {TaskTraits() - .WithPriority(TaskPriority::USER_VISIBLE) - .WithBaseSyncPrimitives(), + {{WithBaseSyncPrimitives(), TaskPriority::USER_VISIBLE}, "TaskScheduler.TaskLatencyMicroseconds.UserVisibleTaskPriority." "MayBlock"}, - {TaskTraits().WithPriority(TaskPriority::USER_BLOCKING), + {{TaskPriority::USER_BLOCKING}, "TaskScheduler.TaskLatencyMicroseconds.UserBlockingTaskPriority"}, - {TaskTraits().WithPriority(TaskPriority::USER_BLOCKING).MayBlock(), + {{MayBlock(), TaskPriority::USER_BLOCKING}, "TaskScheduler.TaskLatencyMicroseconds.UserBlockingTaskPriority." "MayBlock"}, - {TaskTraits() - .WithPriority(TaskPriority::USER_BLOCKING) - .WithBaseSyncPrimitives(), + {{WithBaseSyncPrimitives(), TaskPriority::USER_BLOCKING}, "TaskScheduler.TaskLatencyMicroseconds.UserBlockingTaskPriority." "MayBlock"}};
diff --git a/base/task_scheduler/task_unittest.cc b/base/task_scheduler/task_unittest.cc index fb076d76..0da2700 100644 --- a/base/task_scheduler/task_unittest.cc +++ b/base/task_scheduler/task_unittest.cc
@@ -18,23 +18,20 @@ // should not change. TEST(TaskSchedulerTaskTest, ShutdownBehaviorChangeWithDelay) { Task continue_on_shutdown(FROM_HERE, BindOnce(&DoNothing), - TaskTraits().WithShutdownBehavior( - TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN), + {TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, TimeDelta::FromSeconds(1)); EXPECT_EQ(TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN, continue_on_shutdown.traits.shutdown_behavior()); - Task skip_on_shutdown( - FROM_HERE, BindOnce(&DoNothing), - TaskTraits().WithShutdownBehavior(TaskShutdownBehavior::SKIP_ON_SHUTDOWN), - TimeDelta::FromSeconds(1)); + Task skip_on_shutdown(FROM_HERE, BindOnce(&DoNothing), + {TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + TimeDelta::FromSeconds(1)); EXPECT_EQ(TaskShutdownBehavior::SKIP_ON_SHUTDOWN, skip_on_shutdown.traits.shutdown_behavior()); - Task block_shutdown( - FROM_HERE, BindOnce(&DoNothing), - TaskTraits().WithShutdownBehavior(TaskShutdownBehavior::BLOCK_SHUTDOWN), - TimeDelta::FromSeconds(1)); + Task block_shutdown(FROM_HERE, BindOnce(&DoNothing), + {TaskShutdownBehavior::BLOCK_SHUTDOWN}, + TimeDelta::FromSeconds(1)); EXPECT_EQ(TaskShutdownBehavior::SKIP_ON_SHUTDOWN, block_shutdown.traits.shutdown_behavior()); } @@ -42,23 +39,18 @@ // Verify that the shutdown behavior of undelayed tasks is not adjusted. TEST(TaskSchedulerTaskTest, NoShutdownBehaviorChangeNoDelay) { Task continue_on_shutdown(FROM_HERE, BindOnce(&DoNothing), - TaskTraits().WithShutdownBehavior( - TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN), + {TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, TimeDelta()); EXPECT_EQ(TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN, continue_on_shutdown.traits.shutdown_behavior()); - Task skip_on_shutdown( - FROM_HERE, BindOnce(&DoNothing), - TaskTraits().WithShutdownBehavior(TaskShutdownBehavior::SKIP_ON_SHUTDOWN), - TimeDelta()); + Task skip_on_shutdown(FROM_HERE, BindOnce(&DoNothing), + {TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, TimeDelta()); EXPECT_EQ(TaskShutdownBehavior::SKIP_ON_SHUTDOWN, skip_on_shutdown.traits.shutdown_behavior()); - Task block_shutdown( - FROM_HERE, BindOnce(&DoNothing), - TaskTraits().WithShutdownBehavior(TaskShutdownBehavior::BLOCK_SHUTDOWN), - TimeDelta()); + Task block_shutdown(FROM_HERE, BindOnce(&DoNothing), + {TaskShutdownBehavior::BLOCK_SHUTDOWN}, TimeDelta()); EXPECT_EQ(TaskShutdownBehavior::BLOCK_SHUTDOWN, block_shutdown.traits.shutdown_behavior()); }
diff --git a/base/test/scoped_task_scheduler_unittest.cc b/base/test/scoped_task_scheduler_unittest.cc index 3323ebf..6a14bda 100644 --- a/base/test/scoped_task_scheduler_unittest.cc +++ b/base/test/scoped_task_scheduler_unittest.cc
@@ -257,18 +257,15 @@ TEST(ScopedTaskSchedulerTest, NonBlockShutdownTasksPostedAfterShutdownDontRun) { ScopedTaskScheduler scoped_task_scheduler; TaskScheduler::GetInstance()->Shutdown(); - PostTaskWithTraits(FROM_HERE, - TaskTraits().WithShutdownBehavior( - TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN), + PostTaskWithTraits(FROM_HERE, {TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, BindOnce([]() { ADD_FAILURE() << "CONTINUE_ON_SHUTDOWN task should not run"; })); - PostTaskWithTraits( - FROM_HERE, - TaskTraits().WithShutdownBehavior(TaskShutdownBehavior::SKIP_ON_SHUTDOWN), - BindOnce( - []() { ADD_FAILURE() << "SKIP_ON_SHUTDOWN task should not run"; })); + PostTaskWithTraits(FROM_HERE, {TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + BindOnce([]() { + ADD_FAILURE() << "SKIP_ON_SHUTDOWN task should not run"; + })); // This should not run anything. RunLoop().RunUntilIdle(); @@ -278,28 +275,22 @@ bool block_shutdown_task_ran = false; { ScopedTaskScheduler scoped_task_scheduler; - PostTaskWithTraits(FROM_HERE, - TaskTraits().WithShutdownBehavior( - TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN), + PostTaskWithTraits(FROM_HERE, {TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, BindOnce([]() { ADD_FAILURE() << "CONTINUE_ON_SHUTDOWN task should not run"; })); - PostTaskWithTraits(FROM_HERE, - TaskTraits().WithShutdownBehavior( - TaskShutdownBehavior::SKIP_ON_SHUTDOWN), + PostTaskWithTraits(FROM_HERE, {TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, BindOnce([]() { ADD_FAILURE() << "SKIP_ON_SHUTDOWN task should not run"; })); - PostTaskWithTraits( - FROM_HERE, - TaskTraits().WithShutdownBehavior(TaskShutdownBehavior::BLOCK_SHUTDOWN), - BindOnce( - [](bool* block_shutdown_task_ran) { - *block_shutdown_task_ran = true; - }, - Unretained(&block_shutdown_task_ran))); + PostTaskWithTraits(FROM_HERE, {TaskShutdownBehavior::BLOCK_SHUTDOWN}, + BindOnce( + [](bool* block_shutdown_task_ran) { + *block_shutdown_task_ran = true; + }, + Unretained(&block_shutdown_task_ran))); } EXPECT_TRUE(block_shutdown_task_ran); }
diff --git a/base/threading/sequenced_worker_pool.cc b/base/threading/sequenced_worker_pool.cc index 1a6aca749..a764592 100644 --- a/base/threading/sequenced_worker_pool.cc +++ b/base/threading/sequenced_worker_pool.cc
@@ -827,11 +827,8 @@ const TaskShutdownBehavior task_shutdown_behavior = static_cast<TaskShutdownBehavior>(sequenced.shutdown_behavior); - const TaskTraits traits = TaskTraits() - .MayBlock() - .WithBaseSyncPrimitives() - .WithPriority(task_priority_) - .WithShutdownBehavior(task_shutdown_behavior); + const TaskTraits traits = {MayBlock(), WithBaseSyncPrimitives(), + task_priority_, task_shutdown_behavior}; return GetTaskSchedulerTaskRunner(sequenced.sequence_token_id, traits) ->PostDelayedTask(sequenced.posted_from, std::move(sequenced.task), delay); @@ -881,8 +878,7 @@ if (g_all_pools_state == AllPoolsState::REDIRECTED_TO_TASK_SCHEDULER) { if (!runs_tasks_on_verifier_) { runs_tasks_on_verifier_ = CreateTaskRunnerWithTraits( - TaskTraits().MayBlock().WithBaseSyncPrimitives().WithPriority( - task_priority_)); + {MayBlock(), WithBaseSyncPrimitives(), task_priority_}); } return runs_tasks_on_verifier_->RunsTasksOnCurrentThread(); } else {
diff --git a/build/android/pylib/utils/google_storage_helper.py b/build/android/pylib/utils/google_storage_helper.py index 98b2ddd..7a993a16 100644 --- a/build/android/pylib/utils/google_storage_helper.py +++ b/build/android/pylib/utils/google_storage_helper.py
@@ -53,7 +53,7 @@ gs_path = 'gs://%s/%s' % (bucket, name) logging.info('Uploading %s to %s', filepath, gs_path) - cmd = [_GSUTIL_PATH] + cmd = [_GSUTIL_PATH, '-q'] if content_type: cmd.extend(['-h', 'Content-Type:%s' % content_type]) cmd.extend(['cp', filepath, gs_path])
diff --git a/cc/ipc/struct_traits_unittest.cc b/cc/ipc/struct_traits_unittest.cc index c884e71..d437c164 100644 --- a/cc/ipc/struct_traits_unittest.cc +++ b/cc/ipc/struct_traits_unittest.cc
@@ -1109,8 +1109,9 @@ const bool is_overlay_candidate = true; const bool secure_output_only = true; const bool nearest_neighbor = true; - const gfx::ColorSpace color_space = - gfx::ColorSpace::CreateVideo(4, 5, 9, gfx::ColorSpace::RangeID::LIMITED); + const gfx::ColorSpace color_space = gfx::ColorSpace( + gfx::ColorSpace::PrimaryID::BT470M, gfx::ColorSpace::TransferID::GAMMA28, + gfx::ColorSpace::MatrixID::BT2020_NCL, gfx::ColorSpace::RangeID::LIMITED); #if defined(OS_ANDROID) const bool is_backed_by_surface_texture = true; const bool wants_promotion_hint = true;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java index ede4b3e..48a54eb1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java
@@ -10,6 +10,7 @@ import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.SuppressFBWarnings; import org.chromium.chrome.R; import org.chromium.chrome.browser.ResourceId; import org.chromium.chrome.browser.preferences.autofill.AutofillAndPaymentsPreferences; @@ -18,6 +19,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.concurrent.TimeUnit; /** * Android wrapper of the PersonalDataManager which provides access from the Java @@ -62,6 +64,20 @@ } /** + * Callback for subKeys request. + */ + public interface GetSubKeysRequestDelegate { + /** + * Called when the sub-keys are received sucessfully. + * Here the sub-keys are admin areas. + * + * @param subKeys The subKeys. + */ + @CalledByNative("GetSubKeysRequestDelegate") + void onSubKeysReceived(String[] subKeys); + } + + /** * Callback for normalized addresses. */ public interface NormalizedAddressRequestDelegate { @@ -512,6 +528,8 @@ private static PersonalDataManager sManager; + // Suppress FindBugs warning, since |sManager| is only used on the UI thread. + @SuppressFBWarnings("LI_LAZY_INIT_STATIC") public static PersonalDataManager getInstance() { ThreadUtils.assertOnUiThread(); if (sManager == null) { @@ -805,16 +823,42 @@ * * @param regionCode The code of the region for which to load the rules. */ - public void loadRulesForRegion(String regionCode) { + public void loadRulesForAddressNormalization(String regionCode) { ThreadUtils.assertOnUiThread(); - nativeLoadRulesForRegion(mPersonalDataManagerAndroid, regionCode); + nativeLoadRulesForAddressNormalization(mPersonalDataManagerAndroid, regionCode); } /** - * Normalizes the address of the {@code profile} if the rules associated with the - * {@code regionCode} are done loading. Otherwise sets up the callback to start normalizing the - * address when the rules are loaded. The normalized profile will be sent to the - * {@code delegate}. If the profile is not normalized in the specified + * Starts loading the sub-key request rules for the specified {@code regionCode}. + * + * @param regionCode The code of the region for which to load the rules. + */ + public void loadRulesForSubKeys(String regionCode) { + ThreadUtils.assertOnUiThread(); + nativeLoadRulesForSubKeys(mPersonalDataManagerAndroid, regionCode); + } + + /** + * Starts loading the sub keys for the specified {@code regionCode}. + * + * @param regionCode The code of the region for which to load the sub keys. + */ + public void getRegionSubKeys(String regionCode, GetSubKeysRequestDelegate delegate) { + ThreadUtils.assertOnUiThread(); + nativeStartRegionSubKeysRequest(mPersonalDataManagerAndroid, regionCode, delegate); + } + + /** Cancels the pending sub keys request. */ + public void cancelPendingGetSubKeys() { + ThreadUtils.assertOnUiThread(); + nativeCancelPendingGetSubKeys(mPersonalDataManagerAndroid); + } + + /** + * Normalizes the address of the profile associated with the {@code guid} if the rules + * associated with the {@code regionCode} are done loading. Otherwise sets up the callback to + * start normalizing the address when the rules are loaded. The normalized profile will be sent + * to the {@code delegate}. If the profile is not normalized in the specified * {@code sNormalizationTimeoutSeconds}, the {@code delegate} will be notified. * * @param profile The profile to normalize. @@ -888,6 +932,13 @@ sNormalizationTimeoutSeconds = timeout; } + /** + * @return The sub-key request timeout in milliseconds. + */ + public static long getRequestTimeoutMS() { + return TimeUnit.SECONDS.toMillis(sNormalizationTimeoutSeconds); + } + private native long nativeInit(); private native boolean nativeIsDataLoaded(long nativePersonalDataManagerAndroid); private native String[] nativeGetProfileGUIDsForSettings(long nativePersonalDataManagerAndroid); @@ -947,11 +998,15 @@ long nativePersonalDataManagerAndroid, String guid); private native void nativeGetFullCardForPaymentRequest(long nativePersonalDataManagerAndroid, WebContents webContents, CreditCard card, FullCardRequestDelegate delegate); - private native void nativeLoadRulesForRegion( + private native void nativeLoadRulesForAddressNormalization( + long nativePersonalDataManagerAndroid, String regionCode); + private native void nativeLoadRulesForSubKeys( long nativePersonalDataManagerAndroid, String regionCode); private native void nativeStartAddressNormalization(long nativePersonalDataManagerAndroid, AutofillProfile profile, String regionCode, int timeoutSeconds, NormalizedAddressRequestDelegate delegate); + private native void nativeStartRegionSubKeysRequest(long nativePersonalDataManagerAndroid, + String regionCode, GetSubKeysRequestDelegate delegate); private static native boolean nativeHasProfiles(long nativePersonalDataManagerAndroid); private static native boolean nativeHasCreditCards(long nativePersonalDataManagerAndroid); private static native boolean nativeIsAutofillEnabled(); @@ -960,4 +1015,5 @@ private static native boolean nativeIsPaymentsIntegrationEnabled(); private static native void nativeSetPaymentsIntegrationEnabled(boolean enable); private static native String nativeToCountryCode(String countryName); + private static native void nativeCancelPendingGetSubKeys(long nativePersonalDataManagerAndroid); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/remote/CastNotificationControl.java b/chrome/android/java/src/org/chromium/chrome/browser/media/remote/CastNotificationControl.java index 809f55e..e1ac3f1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/remote/CastNotificationControl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/remote/CastNotificationControl.java
@@ -49,6 +49,14 @@ private String mTitle = ""; private AudioManager mAudioManager; + /** + * Contains the origin of the tab containing the video when it's cast. The origin is formatted + * to be presented better from the security POV if the URL is parseable. Otherwise it's just the + * URL of the tab if the tab exists. Can be null. + */ + @Nullable + private String mTabOrigin; + private boolean mIsShowing; private static final Object LOCK = new Object(); @@ -128,10 +136,6 @@ updateNotificationBuilderIfPosterIsGoodEnough(); mState = initialState; - // Set origin once per the notification so it doesn't change if another tab becomes active. - String origin = getCurrentTabOrigin(); - if (origin != null) mNotificationBuilder.setOrigin(origin); - updateNotification(); mIsShowing = true; } @@ -147,6 +151,7 @@ if (mNotificationBuilder == null) return; mNotificationBuilder.setMetadata(new MediaMetadata(mTitle, "", "")); + if (mTabOrigin != null) mNotificationBuilder.setOrigin(mTabOrigin); if (mState == PlayerState.PAUSED || mState == PlayerState.PLAYING) { mNotificationBuilder.setPaused(mState != PlayerState.PLAYING); @@ -190,6 +195,9 @@ @Override public void onRouteSelected(String name, MediaRouteController mediaRouteController) { + // The notification will be shown/updated later so don't update it in case it's still + // showing for the previous video. + mTabOrigin = getCurrentTabOrigin(); } @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/AddressEditor.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/AddressEditor.java index de356a09..2c59c3b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/AddressEditor.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/AddressEditor.java
@@ -4,6 +4,7 @@ package org.chromium.chrome.browser.payments; +import android.app.ProgressDialog; import android.os.Handler; import android.util.Pair; @@ -11,6 +12,7 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.autofill.PersonalDataManager; import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; +import org.chromium.chrome.browser.autofill.PersonalDataManager.GetSubKeysRequestDelegate; import org.chromium.chrome.browser.autofill.PhoneNumberUtil; import org.chromium.chrome.browser.payments.ui.EditorFieldModel; import org.chromium.chrome.browser.payments.ui.EditorFieldModel.EditorFieldValidator; @@ -31,15 +33,27 @@ /** * An address editor. Can be used for either shipping or billing address editing. */ -public class AddressEditor extends EditorBase<AutofillAddress> { +public class AddressEditor + extends EditorBase<AutofillAddress> implements GetSubKeysRequestDelegate { private final Handler mHandler = new Handler(); private final Map<Integer, EditorFieldModel> mAddressFields = new HashMap<>(); private final Set<CharSequence> mPhoneNumbers = new HashSet<>(); - @Nullable private AutofillProfileBridge mAutofillProfileBridge; - @Nullable private EditorFieldModel mCountryField; - @Nullable private EditorFieldModel mPhoneField; - @Nullable private EditorFieldValidator mPhoneValidator; - @Nullable private List<AddressUiComponent> mAddressUiComponents; + @Nullable + private AutofillProfileBridge mAutofillProfileBridge; + @Nullable + private EditorFieldModel mCountryField; + @Nullable + private EditorFieldModel mPhoneField; + @Nullable + private EditorFieldValidator mPhoneValidator; + @Nullable + private List<AddressUiComponent> mAddressUiComponents; + private boolean mAdminAreasLoaded; + private String mRecentlySelectedCountry; + private Runnable mCountryChangeCallback; + private AutofillProfile mProfile; + private EditorModel mEditor; + private ProgressDialog mProgressDialog; /** * Adds the given phone number to the autocomplete set, if it's valid. @@ -72,17 +86,21 @@ // default locale on this device. boolean isNewAddress = toEdit == null; - // Ensure that |address| and |profile| are always not null. + // Ensure that |address| and |mProfile| are always not null. final AutofillAddress address = isNewAddress ? new AutofillAddress(mContext, new AutofillProfile()) : toEdit; - final AutofillProfile profile = address.getProfile(); + mProfile = address.getProfile(); // The title of the editor depends on whether we're adding a new address or editing an // existing address. - final EditorModel editor = - new EditorModel(isNewAddress ? mContext.getString(R.string.payments_add_address) + mEditor = + new EditorModel(isNewAddress ? mContext.getString(R.string.autofill_create_profile) : toEdit.getEditTitle()); + // When edit is called, a new form is started, so the country on the + // dropdown list is not changed. => mRecentlySelectedCountry should be null. + mRecentlySelectedCountry = null; + // The country dropdown is always present on the editor. if (mCountryField == null) { mCountryField = EditorFieldModel.createDropdown( @@ -94,24 +112,25 @@ // Changing the country will update which fields are in the model. The actual fields are not // discarded, so their contents are preserved. mCountryField.setDropdownCallback(new Callback<Pair<String, Runnable>>() { + /** + * If the selected country on the country dropdown list is changed, + * the first element of eventData is the recently selected dropdown key, + * the second element is the callback to invoke for when the dropdown + * change has been processed. + */ @Override public void onResult(Pair<String, Runnable> eventData) { - editor.removeAllFields(); - editor.addField(mCountryField); - addAddressTextFieldsToEditor(editor, eventData.first, - Locale.getDefault().getLanguage()); - editor.addField(mPhoneField); - - // Notify EditorView that the fields in the model have changed. EditorView should - // re-read the model and update the UI accordingly. - mHandler.post(eventData.second); + mEditor.removeAllFields(); + showProgressDialog(); + mRecentlySelectedCountry = eventData.first; + mCountryChangeCallback = eventData.second; + loadAdminAreasForCountry(mRecentlySelectedCountry); } }); // Country dropdown is cached, so the selected item needs to be updated for the new profile // that's being edited. This will not fire the dropdown callback. - mCountryField.setValue(AutofillAddress.getCountryCode(profile)); - editor.addField(mCountryField); + mCountryField.setValue(AutofillAddress.getCountryCode(mProfile)); // There's a finite number of fields for address editing. Changing the country will re-order // and relabel the fields. The meaning of each field remains the same. @@ -121,10 +140,6 @@ mAddressFields.put(AddressField.DEPENDENT_LOCALITY, EditorFieldModel.createTextInput()); mAddressFields.put(AddressField.ORGANIZATION, EditorFieldModel.createTextInput()); - // State should be formatted in all capitals. - mAddressFields.put(AddressField.ADMIN_AREA, EditorFieldModel.createTextInput( - EditorFieldModel.INPUT_TYPE_HINT_REGION)); - // Sorting code and postal code (a.k.a. ZIP code) should show both letters and digits on // the keyboard, if possible. mAddressFields.put(AddressField.SORTING_CODE, EditorFieldModel.createTextInput( @@ -141,18 +156,6 @@ EditorFieldModel.INPUT_TYPE_HINT_PERSON_NAME)); } - // Address fields are cached, so their values need to be updated for every new profile - // that's being edited. - for (Map.Entry<Integer, EditorFieldModel> entry : mAddressFields.entrySet()) { - entry.getValue().setValue(AutofillAddress.getProfileField(profile, entry.getKey())); - } - - // Both country code and language code dictate which fields should be added to the editor. - // For example, "US" will not add dependent locality to the editor. A "JP" address will - // start with a person's full name or a with a prefecture name, depending on whether the - // language code is "ja-Latn" or "ja". - addAddressTextFieldsToEditor( - editor, mCountryField.getValue().toString(), profile.getLanguageCode()); // Phone number is present and required for all countries. if (mPhoneField == null) { @@ -165,30 +168,48 @@ // Phone number field is cached, so its value needs to be updated for every new profile // that's being edited. - mPhoneField.setValue(profile.getPhoneNumber()); - editor.addField(mPhoneField); + mPhoneField.setValue(mProfile.getPhoneNumber()); // If the user clicks [Cancel], send |toEdit| address back to the caller, which was the // original state (could be null, a complete address, a partial address). - editor.setCancelCallback(new Runnable() { + mEditor.setCancelCallback(new Runnable() { @Override public void run() { + // This makes sure that onSubKeysReceived returns early if it's + // ever called when Cancel has already occurred. + mAdminAreasLoaded = true; + PersonalDataManager.getInstance().cancelPendingGetSubKeys(); callback.onResult(toEdit); } }); // If the user clicks [Done], save changes on disk, mark the address "complete," and send it // back to the caller. - editor.setDoneCallback(new Runnable() { + mEditor.setDoneCallback(new Runnable() { @Override public void run() { - commitChanges(profile); - address.completeAddress(profile); + mAdminAreasLoaded = true; + PersonalDataManager.getInstance().cancelPendingGetSubKeys(); + commitChanges(mProfile); + address.completeAddress(mProfile); callback.onResult(address); } }); - mEditorView.show(editor); + loadAdminAreasForCountry(mProfile.getCountryCode()); + } + + private void showProgressDialog() { + mProgressDialog = new ProgressDialog(mContext); + mProgressDialog.setMessage(mContext.getText(R.string.payments_loading_message)); + mProgressDialog.show(); + } + + private void dismissProgressDialog() { + if (mProgressDialog != null && mProgressDialog.isShowing()) { + mProgressDialog.dismiss(); + } + mProgressDialog = null; } /** Saves the edited profile on disk. */ @@ -220,7 +241,7 @@ } // Save the edited autofill profile locally. - profile.setGUID(PersonalDataManager.getInstance().setProfileToLocal(profile)); + profile.setGUID(PersonalDataManager.getInstance().setProfileToLocal(mProfile)); profile.setIsLocal(true); } @@ -265,27 +286,115 @@ return value == null ? "" : value.toString(); } - /** - * Adds text fields to the editor model based on the country and language code of the profile - * that's being edited. - */ - private void addAddressTextFieldsToEditor( - EditorModel container, String countryCode, String languageCode) { - mAddressUiComponents = mAutofillProfileBridge.getAddressUiComponents(countryCode, - languageCode); + private void setAddressFieldValuesFromCache() { + // Address fields are cached, so their values need to be updated for every new profile + // that's being edited. + for (Map.Entry<Integer, EditorFieldModel> entry : mAddressFields.entrySet()) { + entry.getValue().setValue(AutofillAddress.getProfileField(mProfile, entry.getKey())); + } + } + @Override + public void onSubKeysReceived(String[] adminAreas) { + if (mAdminAreasLoaded) return; + mAdminAreasLoaded = true; + + // If Chrome can't get admin areas from the server or there is no admin area on the server, + // then use the text field. + // Otherwise, use the dropdown list. + if (adminAreas == null || adminAreas.length == 0) { + mAddressFields.put(AddressField.ADMIN_AREA, EditorFieldModel.createTextInput()); + } else { + mAddressFields.put(AddressField.ADMIN_AREA, EditorFieldModel.createDropdown()); + } + + // Admin areas need to be fetched in two cases: + // 1. Initial loading of the form. + // 2. When the selected country is changed in the form. + // mRecentlySelectedCountry is not null if and only if it's the second case + if (mRecentlySelectedCountry != null) { + dismissProgressDialog(); + // Both country code and language code dictate which fields should be added to the + // editor. + // For example, "US" will not add dependent locality to the editor. A "JP" address will + // start with a person's full name or a with a prefecture name, depending on whether the + // language code is "ja-Latn" or "ja". + addAddressFieldsToEditor( + mRecentlySelectedCountry, Locale.getDefault().getLanguage(), adminAreas); + // Notify EditorView that the fields in the model have changed. EditorView should + // re-read the model and update the UI accordingly. + mHandler.post(mCountryChangeCallback); + } else { + // This should be called when all required fields are put in mAddressField. + setAddressFieldValuesFromCache(); + addAddressFieldsToEditor( + mProfile.getCountryCode(), mProfile.getLanguageCode(), adminAreas); + mEditorView.show(mEditor); + } + } + + /** Requests the list of admin areas. */ + private void loadAdminAreasForCountry(String countryCode) { + // Used to check if the callback is called (for time-out). + mAdminAreasLoaded = false; + + onAdminAreasLoading(); + // In each rule, admin area keys are saved under sub-keys of country. + PersonalDataManager.getInstance().loadRulesForSubKeys(countryCode); + PersonalDataManager.getInstance().getRegionSubKeys(countryCode, this); + } + + /** Cancels the request for the list of admin areas. */ + private void cancelAdminAreasRequest() { + if (mAdminAreasLoaded) return; + onSubKeysReceived(null); + PersonalDataManager.getInstance().cancelPendingGetSubKeys(); + } + + /** + * In case the the admin areas are not loaded yet, or the time out is set to 0 for testing, + * starts a timer to cancel the request. + */ + public void onAdminAreasLoading() { + if (mAdminAreasLoaded) return; + // Handler().postDelayed sometimes adds an additional delay to the time-out, + // therefore the case for time-out == 0 is checked initially. + if (PersonalDataManager.getInstance().getRequestTimeoutMS() == 0) { + cancelAdminAreasRequest(); + return; + } + new Handler().postDelayed(new Runnable() { + @Override + public void run() { + cancelAdminAreasRequest(); + } + }, PersonalDataManager.getInstance().getRequestTimeoutMS()); + } + + /** + * Adds fields to the editor model based on the country and language code of + * the profile that's being edited. + */ + private void addAddressFieldsToEditor( + String countryCode, String languageCode, String[] adminAreas) { + mAddressUiComponents = + mAutofillProfileBridge.getAddressUiComponents(countryCode, languageCode); + // In terms of order, country must be the first field. + mEditor.addField(mCountryField); for (int i = 0; i < mAddressUiComponents.size(); i++) { AddressUiComponent component = mAddressUiComponents.get(i); - // The country field is a dropdown, so there's no need to add a text field for it. - if (component.id == AddressField.COUNTRY) continue; - EditorFieldModel field = mAddressFields.get(component.id); // Labels depend on country, e.g., state is called province in some countries. These are // already localized. field.setLabel(component.label); field.setIsFullLine(component.isFullLine); + if (component.id == AddressField.ADMIN_AREA && field.isDropdownField()) { + field.setDropdownKeyValues( + mAutofillProfileBridge.getAdminAreaDropdownList(adminAreas)); + } + // Libaddressinput formats do not always require the full name (RECIPIENT), but // PaymentRequest does. if (component.isRequired || component.id == AddressField.RECIPIENT) { @@ -294,9 +403,10 @@ } else { field.setRequiredErrorMessage(null); } - - container.addField(field); + mEditor.addField(field); } + // Phone number must be the last field. + mEditor.addField(mPhoneField); } private EditorFieldValidator getPhoneValidator() {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java index 6c78fa4..61164ab4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java
@@ -566,7 +566,7 @@ String countryCode = AutofillAddress.getCountryCode(addresses.get(i).getProfile()); if (!uniqueCountryCodes.contains(countryCode)) { uniqueCountryCodes.add(countryCode); - PersonalDataManager.getInstance().loadRulesForRegion(countryCode); + PersonalDataManager.getInstance().loadRulesForAddressNormalization(countryCode); } } @@ -1531,7 +1531,7 @@ String countryCode = AutofillAddress.getCountryCode(creditCard.getBillingAddress()); if (!uniqueCountryCodes.contains(countryCode)) { uniqueCountryCodes.add(countryCode); - PersonalDataManager.getInstance().loadRulesForRegion(countryCode); + PersonalDataManager.getInstance().loadRulesForAddressNormalization(countryCode); } // If there's a card on file with a valid number and a name, then
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/EditorDropdownField.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/EditorDropdownField.java index e7f30183..e1568b4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/EditorDropdownField.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/EditorDropdownField.java
@@ -18,12 +18,15 @@ import android.widget.TextView; import org.chromium.chrome.R; +import org.chromium.chrome.browser.payments.ui.PaymentRequestUI.PaymentRequestObserverForTest; import org.chromium.chrome.browser.preferences.autofill.AutofillProfileBridge.DropdownKeyValue; import org.chromium.ui.UiUtils; import java.util.ArrayList; import java.util.List; +import javax.annotation.Nullable; + /** * Helper class for creating a dropdown view with a label. */ @@ -33,6 +36,8 @@ private final TextView mLabel; private final Spinner mDropdown; private int mSelectedIndex; + @Nullable + private PaymentRequestObserverForTest mObserverForTest; /** * Builds a dropdown view. @@ -44,9 +49,10 @@ * processed. */ public EditorDropdownField(Context context, ViewGroup root, final EditorFieldModel fieldModel, - final Runnable changedCallback) { + final Runnable changedCallback, @Nullable PaymentRequestObserverForTest observer) { assert fieldModel.getInputTypeHint() == EditorFieldModel.INPUT_TYPE_HINT_DROPDOWN; mFieldModel = fieldModel; + mObserverForTest = observer; mLayout = LayoutInflater.from(context).inflate( R.layout.payment_request_editor_dropdown, root, false); @@ -97,6 +103,9 @@ mFieldModel.getDropdownKeyValues().get(position).getKey(), changedCallback); } + if (mObserverForTest != null) { + mObserverForTest.onPaymentRequestEditorTextUpdate(); + } } @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/EditorFieldModel.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/EditorFieldModel.java index 690834b..08037a6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/EditorFieldModel.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/EditorFieldModel.java
@@ -198,6 +198,11 @@ return result; } + /** Constructs a dropdown field model. */ + public static EditorFieldModel createDropdown() { + return new EditorFieldModel(INPUT_TYPE_HINT_DROPDOWN); + } + /** * Constructs a dropdown field model. * @@ -332,11 +337,17 @@ return mValueIconGenerator; } - private boolean isTextField() { + /** @return Whether the input is a text field. */ + public boolean isTextField() { return mInputTypeHint >= INPUT_TYPE_HINT_MIN_INCLUSIVE && mInputTypeHint < INPUT_TYPE_HINT_MAX_TEXT_INPUT_EXCLUSIVE; } + /** @return Whether the input is a dropdown field. */ + public boolean isDropdownField() { + return mInputTypeHint == INPUT_TYPE_HINT_DROPDOWN; + } + /** @return The type of input, for example, INPUT_TYPE_HINT_PHONE. */ public int getInputTypeHint() { return mInputTypeHint;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/EditorView.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/EditorView.java index 38a8b959..3c9164b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/EditorView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/EditorView.java
@@ -385,8 +385,8 @@ if (mObserverForTest != null) mObserverForTest.onPaymentRequestReadyToEdit(); } }; - EditorDropdownField dropdownView = - new EditorDropdownField(mContext, parent, fieldModel, prepareEditorRunnable); + EditorDropdownField dropdownView = new EditorDropdownField( + mContext, parent, fieldModel, prepareEditorRunnable, mObserverForTest); mFieldViews.add(dropdownView); mDropdownFields.add(dropdownView.getDropdown());
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/autofill/AutofillProfileBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/autofill/AutofillProfileBridge.java index 7f0f63d..a5bc8eb5 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/autofill/AutofillProfileBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/autofill/AutofillProfileBridge.java
@@ -97,10 +97,31 @@ return result; } }); - return countries; } + /** @return The list of admin areas sorted by their localized display names. */ + public static List<DropdownKeyValue> getAdminAreaDropdownList(String[] keys) { + List<DropdownKeyValue> adminAreas = new ArrayList<>(); + + for (int i = 0; i < keys.length; ++i) { + // TODO (parastoog): show names, save keys. @crbug.com/691643 + adminAreas.add(new DropdownKeyValue(keys[i], keys[i])); + } + + final Collator collator = Collator.getInstance(Locale.getDefault()); + collator.setStrength(Collator.PRIMARY); + Collections.sort(adminAreas, new Comparator<DropdownKeyValue>() { + @Override + public int compare(DropdownKeyValue lhs, DropdownKeyValue rhs) { + // Sorted according to the admin area values, such as Quebec, + // rather than the admin area keys, such as QC. + return collator.compare(lhs.getValue(), rhs.getValue()); + } + }); + return adminAreas; + } + /** @return The list of required fields. COUNTRY is always included. RECIPIENT often omitted. */ public static List<Integer> getRequiredAddressFields(String countryCode) { List<Integer> requiredFields = new ArrayList<>();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/AutofillTestHelper.java b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/AutofillTestHelper.java index 5892cb4..f792814c 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/AutofillTestHelper.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/AutofillTestHelper.java
@@ -31,7 +31,7 @@ ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { - PersonalDataManager.getInstance().setNormalizationTimeoutForTesting(1); + PersonalDataManager.getInstance().setNormalizationTimeoutForTesting(0); } }); }
diff --git a/chrome/browser/autofill/android/personal_data_manager_android.cc b/chrome/browser/autofill/android/personal_data_manager_android.cc index bb6e4d2a..34b2b9c 100644 --- a/chrome/browser/autofill/android/personal_data_manager_android.cc +++ b/chrome/browser/autofill/android/personal_data_manager_android.cc
@@ -13,6 +13,7 @@ #include "base/android/jni_string.h" #include "base/command_line.h" #include "base/format_macros.h" +#include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "chrome/browser/android/resource_mapper.h" @@ -306,6 +307,40 @@ DISALLOW_COPY_AND_ASSIGN(AndroidAddressNormalizerDelegate); }; +class AndroidSubKeyRequesterDelegate + : public PersonalDataManagerAndroid::SubKeyRequestDelegate, + public base::SupportsWeakPtr<AndroidSubKeyRequesterDelegate> { + public: + AndroidSubKeyRequesterDelegate( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& jdelegate, + const std::string& region_code, + base::WeakPtr<PersonalDataManagerAndroid> personal_data_manager_android) { + jdelegate_.Reset(env, jdelegate); + region_code_ = region_code; + personal_data_manager_android_ = personal_data_manager_android; + } + + ~AndroidSubKeyRequesterDelegate() override {} + + private: + // PersonalDataManagerAndroid::SubKeyRequestDelegate: + void OnRulesSuccessfullyLoaded() override { + if (personal_data_manager_android_) { + JNIEnv* env = base::android::AttachCurrentThread(); + Java_GetSubKeysRequestDelegate_onSubKeysReceived( + env, jdelegate_, + personal_data_manager_android_->GetSubKeys(env, region_code_)); + } + } + + ScopedJavaGlobalRef<jobject> jdelegate_; + std::string region_code_; + base::WeakPtr<PersonalDataManagerAndroid> personal_data_manager_android_; + + DISALLOW_COPY_AND_ASSIGN(AndroidSubKeyRequesterDelegate); +}; + } // namespace PersonalDataManagerAndroid::PersonalDataManagerAndroid(JNIEnv* env, jobject obj) @@ -317,7 +352,13 @@ new autofill::ChromeMetadataSource( I18N_ADDRESS_VALIDATION_DATA_URL, personal_data_manager_->GetURLRequestContextGetter())), - ValidationRulesStorageFactory::CreateStorage()) { + ValidationRulesStorageFactory::CreateStorage()), + address_validator_( + base::MakeUnique<autofill::ChromeMetadataSource>( + I18N_ADDRESS_VALIDATION_DATA_URL, + personal_data_manager_->GetURLRequestContextGetter()), + ValidationRulesStorageFactory::CreateStorage(), + this) { personal_data_manager_->AddObserver(this); } @@ -699,7 +740,7 @@ return base::Time::Now().ToTimeT(); } -void PersonalDataManagerAndroid::LoadRulesForRegion( +void PersonalDataManagerAndroid::LoadRulesForAddressNormalization( JNIEnv* env, const base::android::JavaParamRef<jobject>& unused_obj, const base::android::JavaParamRef<jstring>& jregion_code) { @@ -707,6 +748,13 @@ ConvertJavaStringToUTF8(env, jregion_code)); } +void PersonalDataManagerAndroid::LoadRulesForSubKeys( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& unused_obj, + const base::android::JavaParamRef<jstring>& jregion_code) { + address_validator_.LoadRules(ConvertJavaStringToUTF8(env, jregion_code)); +} + void PersonalDataManagerAndroid::StartAddressNormalization( JNIEnv* env, const JavaParamRef<jobject>& unused_obj, @@ -740,6 +788,53 @@ return !personal_data_manager_->GetCreditCards().empty(); } +base::android::ScopedJavaLocalRef<jobjectArray> +PersonalDataManagerAndroid::GetSubKeys(JNIEnv* env, + const std::string& region_code) { + std::vector<std::string> sub_keys = + address_validator_.GetRegionSubKeys(region_code); + return base::android::ToJavaArrayOfStrings(env, sub_keys); +} + +void PersonalDataManagerAndroid::OnAddressValidationRulesLoaded( + const std::string& region_code, + bool success) { + // if |success| == false, AddressValidator::GetRegionSubKeys will return an + // empty list of sub-keys. => No need to check for |success|. + // Check if there is any sub-key request for that region code. + if (!pending_subkey_region_code_.compare(region_code)) + pending_subkey_request_->OnRulesSuccessfullyLoaded(); + pending_subkey_region_code_.clear(); + pending_subkey_request_.reset(); +} + +void PersonalDataManagerAndroid::StartRegionSubKeysRequest( + JNIEnv* env, + const JavaParamRef<jobject>& unused_obj, + const JavaParamRef<jstring>& jregion_code, + const JavaParamRef<jobject>& jdelegate) { + const std::string region_code = ConvertJavaStringToUTF8(env, jregion_code); + std::unique_ptr<SubKeyRequestDelegate> requester = + base::MakeUnique<AndroidSubKeyRequesterDelegate>( + env, jdelegate, region_code, AsWeakPtr()); + + if (AreRulesLoadedForRegion(region_code)) { + requester->OnRulesSuccessfullyLoaded(); + } else { + // Setup the variables so that the sub-keys request is sent, when the rules + // are loaded. + pending_subkey_region_code_ = region_code; + pending_subkey_request_ = std::move(requester); + } +} + +void PersonalDataManagerAndroid::CancelPendingGetSubKeys( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& unused_obj) { + pending_subkey_region_code_.clear(); + pending_subkey_request_.reset(); +} + ScopedJavaLocalRef<jobjectArray> PersonalDataManagerAndroid::GetProfileGUIDs( JNIEnv* env, const std::vector<AutofillProfile*>& profiles) { @@ -762,7 +857,7 @@ bool PersonalDataManagerAndroid::AreRulesLoadedForRegion( const std::string& region_code) { - return address_normalizer_.AreRulesLoadedForRegion(region_code); + return address_validator_.AreRulesLoadedForRegion(region_code); } ScopedJavaLocalRef<jobjectArray> PersonalDataManagerAndroid::GetProfileLabels(
diff --git a/chrome/browser/autofill/android/personal_data_manager_android.h b/chrome/browser/autofill/android/personal_data_manager_android.h index d140508..d1628739 100644 --- a/chrome/browser/autofill/android/personal_data_manager_android.h +++ b/chrome/browser/autofill/android/personal_data_manager_android.h
@@ -15,14 +15,25 @@ #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/browser/personal_data_manager_observer.h" #include "components/payments/core/address_normalizer_impl.h" +#include "third_party/libaddressinput/chromium/chrome_address_validator.h" namespace autofill { // Android wrapper of the PersonalDataManager which provides access from the // Java layer. Note that on Android, there's only a single profile, and // therefore a single instance of this wrapper. -class PersonalDataManagerAndroid : public PersonalDataManagerObserver { +class PersonalDataManagerAndroid + : public PersonalDataManagerObserver, + public LoadRulesListener, + public base::SupportsWeakPtr<PersonalDataManagerAndroid> { public: + // The interface for the sub-key request. + class SubKeyRequestDelegate { + public: + virtual void OnRulesSuccessfullyLoaded() = 0; + virtual ~SubKeyRequestDelegate() {} + }; + // Registers the JNI bindings for this class. static bool Register(JNIEnv* env); @@ -288,7 +299,14 @@ // Starts loading the address validation rules for the specified // |region_code|. - void LoadRulesForRegion( + void LoadRulesForAddressNormalization( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& unused_obj, + const base::android::JavaParamRef<jstring>& region_code); + + // Starts loading the rules for the specified |region_code| for the further + // sub-key request. + void LoadRulesForSubKeys( JNIEnv* env, const base::android::JavaParamRef<jobject>& unused_obj, const base::android::JavaParamRef<jstring>& region_code); @@ -316,6 +334,31 @@ JNIEnv* env, const base::android::JavaParamRef<jobject>& unused_obj); + // Gets the sub-keys for the region with |jregion_code| code, if the + // |jregion_code| rules have finished loading. Otherwise, sets up a task to + // get the sub-keys, when the rules are loaded. + void StartRegionSubKeysRequest( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& unused_obj, + const base::android::JavaParamRef<jstring>& jregion_code, + const base::android::JavaParamRef<jobject>& jdelegate); + + // Gets the sub-keys of the rule associated with |jregion_code|. Should only + // be called when the rules are loaded. + base::android::ScopedJavaLocalRef<jobjectArray> GetSubKeys( + JNIEnv* env, + const std::string& jregion_code); + + // Callback of the sub-keys request. + // This is called when the sub-keys are loaded. + void OnAddressValidationRulesLoaded(const std::string& region_code, + bool success) override; + + // Cancels the pending sub-key request task. + void CancelPendingGetSubKeys( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& unused_obj); + private: ~PersonalDataManagerAndroid() override; @@ -366,6 +409,13 @@ // The address validator used to normalize addresses. payments::AddressNormalizerImpl address_normalizer_; + // The address validator used for sub-key request. + AddressValidator address_validator_; + + // The region code and the request for the pending sub-key request. + std::unique_ptr<SubKeyRequestDelegate> pending_subkey_request_; + std::string pending_subkey_region_code_; + DISALLOW_COPY_AND_ASSIGN(PersonalDataManagerAndroid); };
diff --git a/chrome/browser/chromeos/arc/accessibility/ax_tree_source_arc.cc b/chrome/browser/chromeos/arc/accessibility/ax_tree_source_arc.cc index ef70c62..5ec7065 100644 --- a/chrome/browser/chromeos/arc/accessibility/ax_tree_source_arc.cc +++ b/chrome/browser/chromeos/arc/accessibility/ax_tree_source_arc.cc
@@ -165,11 +165,9 @@ void PopulateAXState(arc::mojom::AccessibilityNodeInfoData* node, ui::AXNodeData* out_data) { - out_data->state = 0; - #define MAP_STATE(android_boolean_property, chrome_state) \ if (GetBooleanProperty(node, android_boolean_property)) \ - out_data->AddStateFlag(chrome_state); + out_data->AddState(chrome_state); using AXBooleanProperty = arc::mojom::AccessibilityBooleanProperty; @@ -194,7 +192,7 @@ } if (!GetBooleanProperty(node, AXBooleanProperty::ENABLED)) - out_data->AddStateFlag(ui::AX_STATE_DISABLED); + out_data->AddState(ui::AX_STATE_DISABLED); } } // namespace
diff --git a/chrome/browser/chromeos/hats/hats_notification_controller_unittest.cc b/chrome/browser/chromeos/hats/hats_notification_controller_unittest.cc index cc69995d..6486c88 100644 --- a/chrome/browser/chromeos/hats/hats_notification_controller_unittest.cc +++ b/chrome/browser/chromeos/hats/hats_notification_controller_unittest.cc
@@ -123,7 +123,7 @@ } scoped_refptr<HatsNotificationController> InstantiateHatsController() { - MockImageFetcher* mock_image_fetcher_ = new MockImageFetcher; + mock_image_fetcher_ = new MockImageFetcher; // The initialization will fail since the function IsNewDevice() will return // true. scoped_refptr<HatsNotificationController> hats_notification_controller = @@ -177,6 +177,7 @@ TestingProfile profile_; StrictMock<MockNetworkPortalDetector> mock_network_portal_detector_; + MockImageFetcher* mock_image_fetcher_; private: std::unique_ptr<TestingProfileManager> profile_manager_; @@ -226,6 +227,17 @@ RemoveObserver(hats_notification_controller.get())) .Times(2); + EXPECT_CALL(*mock_image_fetcher_, + StartOrQueueNetworkRequest( + HatsNotificationController::kImageFetcher1xId, + GURL(HatsNotificationController::kGoogleIcon1xUrl), _)) + .Times(1); + EXPECT_CALL(*mock_image_fetcher_, + StartOrQueueNetworkRequest( + HatsNotificationController::kImageFetcher2xId, + GURL(HatsNotificationController::kGoogleIcon2xUrl), _)) + .Times(1); + hats_notification_controller->Initialize(false); // Finally check if notification was launched to confirm initialization.
diff --git a/chrome/browser/chromeos/login/lock/screen_locker.cc b/chrome/browser/chromeos/login/lock/screen_locker.cc index 47da0d87..f8cb2c2 100644 --- a/chrome/browser/chromeos/login/lock/screen_locker.cc +++ b/chrome/browser/chromeos/login/lock/screen_locker.cc
@@ -7,6 +7,9 @@ #include <string> #include <vector> +#include "ash/login/views/lock_screen.h" +#include "ash/public/interfaces/constants.mojom.h" +#include "ash/public/interfaces/session_controller.mojom.h" #include "ash/shell.h" #include "ash/wm/window_state.h" #include "ash/wm/window_state_aura.h" @@ -46,6 +49,7 @@ #include "chrome/grit/browser_resources.h" #include "chrome/grit/generated_resources.h" #include "chromeos/audio/chromeos_sounds.h" +#include "chromeos/chromeos_switches.h" #include "chromeos/dbus/biod/constants.pb.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager_client.h" @@ -66,6 +70,8 @@ #include "services/device/public/interfaces/constants.mojom.h" #include "services/service_manager/public/cpp/connector.h" #include "ui/base/resource/resource_bundle.h" +#include "ui/display/display.h" +#include "ui/display/screen.h" #include "ui/gfx/image/image.h" #include "url/gurl.h" @@ -81,6 +87,12 @@ // unlock happens even if animations are broken. const int kUnlockGuardTimeoutMs = 400; +// Returns true if we are using md-based login/lock. +bool IsUsingMdLogin() { + return base::CommandLine::ForCurrentProcess()->HasSwitch( + chromeos::switches::kShowMdLogin); +} + // Returns true if fingerprint authentication is available for one of the // |users|. bool IsFingerprintAuthenticationAvailableForUsers( @@ -111,7 +123,7 @@ ~ScreenLockObserver() override { if (DBusThreadManager::IsInitialized()) { DBusThreadManager::Get()->GetSessionManagerClient()->SetStubDelegate( - NULL); + nullptr); } } @@ -153,12 +165,47 @@ DISALLOW_COPY_AND_ASSIGN(ScreenLockObserver); }; -ScreenLockObserver* g_screen_lock_observer = NULL; +// Stubbed delegate that will eventually be replaced by mojo calls. +class StubDelegate : public ScreenLocker::Delegate { + public: + StubDelegate() = default; + ~StubDelegate() override = default; + + // ScreenLocker::Delegate: + void SetPasswordInputEnabled(bool enabled) override { NOTIMPLEMENTED(); } + void ShowErrorMessage(int error_msg_id, + HelpAppLauncher::HelpTopic help_topic_id) override { + NOTIMPLEMENTED(); + } + void ClearErrors() override { NOTIMPLEMENTED(); } + void AnimateAuthenticationSuccess() override { NOTIMPLEMENTED(); } + void OnLockWebUIReady() override { NOTIMPLEMENTED(); } + void OnLockBackgroundDisplayed() override { NOTIMPLEMENTED(); } + void OnHeaderBarVisible() override { NOTIMPLEMENTED(); } + void OnAshLockAnimationFinished() override { NOTIMPLEMENTED(); } + void SetFingerprintState(const AccountId& account_id, + ScreenLocker::FingerprintState state) override { + NOTIMPLEMENTED(); + } + content::WebContents* GetWebContents() override { return nullptr; } + + private: + DISALLOW_COPY_AND_ASSIGN(StubDelegate); +}; + +ScreenLockObserver* g_screen_lock_observer = nullptr; } // namespace // static -ScreenLocker* ScreenLocker::screen_locker_ = NULL; +ScreenLocker* ScreenLocker::screen_locker_ = nullptr; + +////////////////////////////////////////////////////////////////////////////// +// ScreenLocker::Delegate, public: + +ScreenLocker::Delegate::Delegate() = default; + +ScreenLocker::Delegate::~Delegate() = default; ////////////////////////////////////////////////////////////////////////////// // ScreenLocker, public: @@ -188,15 +235,36 @@ authenticator_ = UserSessionManager::GetInstance()->CreateAuthenticator(this); extended_authenticator_ = ExtendedAuthenticator::Create(this); - web_ui_.reset(new WebUIScreenLocker(this)); - web_ui()->LockScreen(); + if (IsUsingMdLogin()) { + // Create delegate that will eventually call into the views-based lock + // screen via mojo. + delegate_ = new StubDelegate(); + owns_delegate_ = true; - // Ownership of |icon_image_source| is passed. - screenlock_icon_provider_.reset(new ScreenlockIconProvider); - ScreenlockIconSource* screenlock_icon_source = - new ScreenlockIconSource(screenlock_icon_provider_->AsWeakPtr()); - content::URLDataSource::Add(web_ui()->GetWebContents()->GetBrowserContext(), - screenlock_icon_source); + // Create and display lock screen. + // TODO(jdufualt): LockWindow should live in ash. + // TODO(jdufault): Calling ash::ShowLockScreenInWidget should be a mojo + // call. We should only set the session state to locked after the mojo call + // has completed. + LockWindow* lock_window = new LockWindow(); + lock_window->SetBounds( + display::Screen::GetScreen()->GetPrimaryDisplay().bounds()); + ash::ShowLockScreenInWidget(lock_window); + session_manager::SessionManager::Get()->SetSessionState( + session_manager::SessionState::LOCKED); + } else { + web_ui_.reset(new WebUIScreenLocker(this)); + delegate_ = web_ui_.get(); + owns_delegate_ = false; + web_ui_->LockScreen(); + + // Ownership of |icon_image_source| is passed. + screenlock_icon_provider_ = base::MakeUnique<ScreenlockIconProvider>(); + ScreenlockIconSource* screenlock_icon_source = + new ScreenlockIconSource(screenlock_icon_provider_->AsWeakPtr()); + content::URLDataSource::Add(web_ui_->web_contents()->GetBrowserContext(), + screenlock_icon_source); + } // Start locking on ash side. SessionControllerClient::Get()->StartLock(base::Bind( @@ -220,10 +288,10 @@ // Don't enable signout button here as we're showing // MessageBubble. - web_ui()->ShowErrorMessage(incorrect_passwords_count_++ - ? IDS_LOGIN_ERROR_AUTHENTICATING_2ND_TIME - : IDS_LOGIN_ERROR_AUTHENTICATING, - HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT); + delegate_->ShowErrorMessage(incorrect_passwords_count_++ + ? IDS_LOGIN_ERROR_AUTHENTICATING_2ND_TIME + : IDS_LOGIN_ERROR_AUTHENTICATING, + HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT); if (auth_status_consumer_) auth_status_consumer_->OnAuthFailure(error); @@ -247,7 +315,7 @@ user_manager::UserManager::Get()->FindUser(user_context.GetAccountId()); if (user) { if (!user->is_active()) { - saved_ime_state_ = NULL; + saved_ime_state_ = nullptr; user_manager::UserManager::Get()->SwitchActiveUser( user_context.GetAccountId()); } @@ -280,7 +348,7 @@ FROM_HERE, base::Bind(&ScreenLocker::UnlockOnLoginSuccess, weak_factory_.GetWeakPtr()), base::TimeDelta::FromMilliseconds(kUnlockGuardTimeoutMs)); - web_ui()->AnimateAuthenticationSuccess(); + delegate_->AnimateAuthenticationSuccess(); } void ScreenLocker::OnPasswordAuthSuccess(const UserContext& user_context) { @@ -315,7 +383,7 @@ << "Invalid user trying to unlock."; authentication_start_time_ = base::Time::Now(); - web_ui()->SetInputEnabled(false); + delegate_->SetPasswordInputEnabled(false); if (user_context.IsUsingPin()) unlock_attempt_type_ = AUTH_PIN; @@ -379,18 +447,18 @@ if (!locked) return; - web_ui()->OnAshLockAnimationFinished(); + delegate_->OnAshLockAnimationFinished(); AccessibilityManager::Get()->PlayEarcon( chromeos::SOUND_LOCK, PlaySoundOption::SPOKEN_FEEDBACK_ENABLED); } void ScreenLocker::ClearErrors() { - web_ui()->ClearErrors(); + delegate_->ClearErrors(); } void ScreenLocker::Signout() { - web_ui()->ClearErrors(); + delegate_->ClearErrors(); base::RecordAction(UserMetricsAction("ScreenLocker_Signout")); // We expect that this call will not wait for any user input. // If it changes at some point, we will need to force exit. @@ -401,14 +469,14 @@ } void ScreenLocker::EnableInput() { - web_ui()->SetInputEnabled(true); + delegate_->SetPasswordInputEnabled(true); } void ScreenLocker::ShowErrorMessage(int error_msg_id, HelpAppLauncher::HelpTopic help_topic_id, bool sign_out_only) { - web_ui()->SetInputEnabled(!sign_out_only); - web_ui()->ShowErrorMessage(error_msg_id, help_topic_id); + delegate_->SetPasswordInputEnabled(!sign_out_only); + delegate_->ShowErrorMessage(error_msg_id, help_topic_id); } void ScreenLocker::SetLoginStatusConsumer( @@ -426,7 +494,7 @@ void ScreenLocker::ShutDownClass() { DCHECK(g_screen_lock_observer); delete g_screen_lock_observer; - g_screen_lock_observer = NULL; + g_screen_lock_observer = nullptr; } // static @@ -512,7 +580,7 @@ // static void ScreenLocker::ScheduleDeletion() { // Avoid possible multiple calls. - if (screen_locker_ == NULL) + if (screen_locker_ == nullptr) return; VLOG(1) << "Deleting ScreenLocker " << screen_locker_; @@ -520,7 +588,7 @@ SOUND_UNLOCK, PlaySoundOption::SPOKEN_FEEDBACK_ENABLED); delete screen_locker_; - screen_locker_ = NULL; + screen_locker_ = nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -531,10 +599,10 @@ DCHECK(base::MessageLoopForUI::IsCurrent()); if (authenticator_.get()) - authenticator_->SetConsumer(NULL); + authenticator_->SetConsumer(nullptr); ClearErrors(); - screen_locker_ = NULL; + screen_locker_ = nullptr; bool state = false; VLOG(1) << "Emitting SCREEN_LOCK_STATE_CHANGED with state=" << state; content::NotificationService::current()->Notify( @@ -552,6 +620,12 @@ if (saved_ime_state_.get()) { input_method::InputMethodManager::Get()->SetState(saved_ime_state_); } + + if (owns_delegate_) { + owns_delegate_ = false; + delete delegate_; + delegate_ = nullptr; + } } void ScreenLocker::SetAuthenticator(Authenticator* authenticator) { @@ -616,8 +690,8 @@ OnFingerprintAuthFailure(*active_user); return; } - web_ui()->SetFingerprintState(active_user->GetAccountId(), - WebUIScreenLocker::FingerprintState::kSignin); + delegate_->SetFingerprintState(active_user->GetAccountId(), + FingerprintState::kSignin); OnAuthSuccess(user_context); } @@ -629,8 +703,8 @@ UMA_HISTOGRAM_ENUMERATION("ScreenLocker.AuthenticationFailure", unlock_attempt_type_, UnlockType::AUTH_COUNT); - web_ui()->SetFingerprintState(user.GetAccountId(), - WebUIScreenLocker::FingerprintState::kFailed); + delegate_->SetFingerprintState(user.GetAccountId(), + FingerprintState::kFailed); quick_unlock::QuickUnlockStorage* quick_unlock_storage = quick_unlock::QuickUnlockFactory::GetForUser(&user); @@ -638,10 +712,10 @@ quick_unlock_storage->IsFingerprintAuthenticationAvailable()) { quick_unlock_storage->fingerprint_storage()->AddUnlockAttempt(); if (quick_unlock_storage->fingerprint_storage()->ExceededUnlockAttempts()) { - web_ui()->SetFingerprintState( - user.GetAccountId(), WebUIScreenLocker::FingerprintState::kRemoved); - web_ui()->ShowErrorMessage(IDS_LOGIN_ERROR_FINGERPRINT_MAX_ATTEMPT, - HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT); + delegate_->SetFingerprintState(user.GetAccountId(), + FingerprintState::kRemoved); + delegate_->ShowErrorMessage(IDS_LOGIN_ERROR_FINGERPRINT_MAX_ATTEMPT, + HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT); } }
diff --git a/chrome/browser/chromeos/login/lock/screen_locker.h b/chrome/browser/chromeos/login/lock/screen_locker.h index 5a4aff9..dba07eb4 100644 --- a/chrome/browser/chromeos/login/lock/screen_locker.h +++ b/chrome/browser/chromeos/login/lock/screen_locker.h
@@ -24,6 +24,10 @@ #include "ui/base/accelerators/accelerator.h" #include "ui/base/ime/chromeos/input_method_manager.h" +namespace content { +class WebContents; +} + namespace chromeos { class Authenticator; @@ -44,6 +48,59 @@ class ScreenLocker : public AuthStatusConsumer, public device::mojom::FingerprintObserver { public: + enum class FingerprintState { + kHidden, + kDefault, + kSignin, + kFailed, + kRemoved, + }; + + // Delegate used to send internal state changes back to the UI. + class Delegate { + public: + Delegate(); + virtual ~Delegate(); + + // Enable/disable password input. + virtual void SetPasswordInputEnabled(bool enabled) = 0; + + // Show the given error message. + virtual void ShowErrorMessage(int error_msg_id, + HelpAppLauncher::HelpTopic help_topic_id) = 0; + + // Close any displayed error messages. + virtual void ClearErrors() = 0; + + // Run any visual effects after authentication is successful. This must call + // ScreenLocker::UnlockOnLoginSuccess() after all effects are done. + virtual void AnimateAuthenticationSuccess() = 0; + + // Called when the webui lock screen is ready. This gets invoked by a + // chrome.send from the embedded webui. + virtual void OnLockWebUIReady() = 0; + + // Called when webui lock screen wallpaper is loaded and displayed. + virtual void OnLockBackgroundDisplayed() = 0; + + // Called when the webui header bar becomes visible. + virtual void OnHeaderBarVisible() = 0; + + // Called by ScreenLocker to notify that ash lock animation finishes. + virtual void OnAshLockAnimationFinished() = 0; + + // Called when fingerprint state has changed. + virtual void SetFingerprintState(const AccountId& account_id, + FingerprintState state) = 0; + + // Returns the web contents used to back the lock screen. + // TODO(jdufault): Remove this function when we remove WebUIScreenLocker. + virtual content::WebContents* GetWebContents() = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(Delegate); + }; + explicit ScreenLocker(const user_manager::UserList& users); // Returns the default instance if it has been created. @@ -87,8 +144,13 @@ HelpAppLauncher::HelpTopic help_topic_id, bool sign_out_only); - // Returns the WebUIScreenLocker used to lock the screen. - WebUIScreenLocker* web_ui() { return web_ui_.get(); } + // Returns the WebUIScreenLocker instance. This should only be used in tests. + // When using views-based lock this will be a nullptr. + // TODO(jdufault): Remove this function, make tests agnostic to ui impl. + WebUIScreenLocker* web_ui_for_testing() { return web_ui_.get(); } + + // Returns delegate that can be used to talk to the view-layer. + Delegate* delegate() { return delegate_; } // Returns the users to authenticate. const user_manager::UserList& users() const { return users_; } @@ -169,6 +231,10 @@ // WebUIScreenLocker instance in use. std::unique_ptr<WebUIScreenLocker> web_ui_; + // Delegate used to talk to the view. + Delegate* delegate_ = nullptr; + bool owns_delegate_ = false; + // Users that can unlock the device. user_manager::UserList users_;
diff --git a/chrome/browser/chromeos/login/lock/screen_locker_tester.cc b/chrome/browser/chromeos/login/lock/screen_locker_tester.cc index 1748288..5937ed8 100644 --- a/chrome/browser/chromeos/login/lock/screen_locker_tester.cc +++ b/chrome/browser/chromeos/login/lock/screen_locker_tester.cc
@@ -179,7 +179,7 @@ WebUIScreenLocker* WebUIScreenLockerTester::webui_screen_locker() const { DCHECK(ScreenLocker::screen_locker_); - return ScreenLocker::screen_locker_->web_ui(); + return ScreenLocker::screen_locker_->web_ui_for_testing(); } content::WebUI* WebUIScreenLockerTester::webui() const {
diff --git a/chrome/browser/chromeos/login/lock/webui_screen_locker.cc b/chrome/browser/chromeos/login/lock/webui_screen_locker.cc index 061bba94..ad666c4 100644 --- a/chrome/browser/chromeos/login/lock/webui_screen_locker.cc +++ b/chrome/browser/chromeos/login/lock/webui_screen_locker.cc
@@ -151,7 +151,7 @@ gfx::Rect bounds = display::Screen::GetScreen()->GetPrimaryDisplay().bounds(); lock_time_ = base::TimeTicks::Now(); - lock_window_ = new LockWindow(this); + lock_window_ = new LockWindow(); lock_window_->AddObserver(this); Init(); @@ -177,7 +177,7 @@ DisableKeyboardOverscroll(); } -void WebUIScreenLocker::SetInputEnabled(bool enabled) { +void WebUIScreenLocker::SetPasswordInputEnabled(bool enabled) { login_display_->SetUIEnabled(enabled); } @@ -202,7 +202,7 @@ UMA_HISTOGRAM_TIMES("LockScreen.LockReady", base::TimeTicks::Now() - lock_time_); screen_locker_->ScreenLockReady(); - SetInputEnabled(true); + SetPasswordInputEnabled(true); } void WebUIScreenLocker::OnLockWindowReady() { @@ -266,11 +266,12 @@ "cr.ui.Oobe.animateOnceFullyDisplayed"); } -void WebUIScreenLocker::SetFingerprintState(const AccountId& account_id, - FingerprintState state) { +void WebUIScreenLocker::SetFingerprintState( + const AccountId& account_id, + ScreenLocker::FingerprintState state) { // TODO(xiaoyinh@): Modify JS side to consolidate removeUserPodFingerprintIcon // and setUserPodFingerprintIcon into single JS function. - if (state == FingerprintState::kRemoved) { + if (state == ScreenLocker::FingerprintState::kRemoved) { GetWebUI()->CallJavascriptFunctionUnsafe( "login.AccountPickerScreen.removeUserPodFingerprintIcon", ::login::MakeValue(account_id)); @@ -281,7 +282,7 @@ chromeos::quick_unlock::QuickUnlockFactory::GetForAccountId(account_id); if (!quick_unlock_storage || !quick_unlock_storage->IsFingerprintAuthenticationAvailable()) { - state = FingerprintState::kHidden; + state = ScreenLocker::FingerprintState::kHidden; } GetWebUI()->CallJavascriptFunctionUnsafe( "login.AccountPickerScreen.setUserPodFingerprintIcon", @@ -289,6 +290,10 @@ ::login::MakeValue(static_cast<int>(state))); } +content::WebContents* WebUIScreenLocker::GetWebContents() { + return WebUILoginView::GetWebContents(); +} + //////////////////////////////////////////////////////////////////////////////// // WebUIScreenLocker, LoginDisplay::Delegate:
diff --git a/chrome/browser/chromeos/login/lock/webui_screen_locker.h b/chrome/browser/chromeos/login/lock/webui_screen_locker.h index 60b8fce..a68ecc3 100644 --- a/chrome/browser/chromeos/login/lock/webui_screen_locker.h +++ b/chrome/browser/chromeos/login/lock/webui_screen_locker.h
@@ -13,6 +13,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" +#include "chrome/browser/chromeos/login/lock/screen_locker.h" #include "chrome/browser/chromeos/login/signin_screen_controller.h" #include "chrome/browser/chromeos/login/signin_specifics.h" #include "chrome/browser/chromeos/login/ui/lock_window.h" @@ -43,20 +44,13 @@ // Displays a WebUI lock screen based on the Oobe account picker screen. class WebUIScreenLocker : public WebUILoginView, + public ScreenLocker::Delegate, public LoginDisplay::Delegate, public views::WidgetObserver, public PowerManagerClient::Observer, public display::DisplayObserver, public content::WebContentsObserver { public: - enum class FingerprintState { - kHidden, - kDefault, - kSignin, - kFailed, - kRemoved, - }; - // Request lock screen preload when the user is idle. Does nothing if // preloading is disabled or if the preload hueristics return false. static void RequestPreload(); @@ -68,37 +62,6 @@ // ScreenLockReady is called when all initialization has finished. void LockScreen(); - // Enable/disable password input. - void SetInputEnabled(bool enabled); - - // Disables all UI needed and shows error bubble with |message|. If - // |sign_out_only| is true then all other input except "Sign Out" button is - // blocked. - void ShowErrorMessage(int error_msg_id, - HelpAppLauncher::HelpTopic help_topic_id); - - // Close message bubble to clear error messages. - void ClearErrors(); - - // Allows to have visual effects once unlock authentication is successful, - // Must call ScreenLocker::UnlockOnLoginSuccess() once all effects are done. - void AnimateAuthenticationSuccess(); - - // Called when the webui lock screen is ready. This gets invoked by a - // chrome.send from the embedded webui. - void OnLockWebUIReady(); - - // Called when webui lock screen wallpaper is loaded and displayed. - void OnLockBackgroundDisplayed(); - - // Called when the webui header bar becomes visible. - void OnHeaderBarVisible(); - - // Called by ScreenLocker to notify that ash lock animation finishes. - void OnAshLockAnimationFinished(); - - void SetFingerprintState(const AccountId& account_id, FingerprintState state); - private: friend class test::WebUIScreenLockerTester; @@ -107,6 +70,20 @@ // Helper function that creates and preloads a views::WebView. static std::unique_ptr<views::WebView> DoPreload(Profile* profile); + // ScreenLocker::Delegate: + void SetPasswordInputEnabled(bool enabled) override; + void ShowErrorMessage(int error_msg_id, + HelpAppLauncher::HelpTopic help_topic_id) override; + void ClearErrors() override; + void AnimateAuthenticationSuccess() override; + void OnLockWebUIReady() override; + void OnLockBackgroundDisplayed() override; + void OnHeaderBarVisible() override; + void OnAshLockAnimationFinished() override; + void SetFingerprintState(const AccountId& account_id, + ScreenLocker::FingerprintState state) override; + content::WebContents* GetWebContents() override; + // LoginDisplay::Delegate: void CancelPasswordChangedFlow() override; void CompleteLogin(const UserContext& user_context) override;
diff --git a/chrome/browser/chromeos/login/signin_screen_controller.cc b/chrome/browser/chromeos/login/signin_screen_controller.cc index 480abc9..4b22d52 100644 --- a/chrome/browser/chromeos/login/signin_screen_controller.cc +++ b/chrome/browser/chromeos/login/signin_screen_controller.cc
@@ -60,7 +60,7 @@ gaia_screen_->MaybePreloadAuthExtension(); user_selection_screen_->InitEasyUnlock(); if (ScreenLocker::default_screen_locker()) - ScreenLocker::default_screen_locker()->web_ui()->OnLockWebUIReady(); + ScreenLocker::default_screen_locker()->delegate()->OnLockWebUIReady(); } void SignInScreenController::RemoveUser(const AccountId& account_id) {
diff --git a/chrome/browser/chromeos/login/ui/lock_window.cc b/chrome/browser/chromeos/login/ui/lock_window.cc index c810969..a2c30f7 100644 --- a/chrome/browser/chromeos/login/ui/lock_window.cc +++ b/chrome/browser/chromeos/login/ui/lock_window.cc
@@ -14,8 +14,7 @@ namespace chromeos { -LockWindow::LockWindow(views::View* initially_focused_view) - : initially_focused_view_(initially_focused_view) { +LockWindow::LockWindow() { ui::GestureRecognizer::Get()->CancelActiveTouchesExcept(nullptr); views::Widget::InitParams params( @@ -47,7 +46,8 @@ } views::View* LockWindow::GetInitiallyFocusedView() { - return initially_focused_view_; + // There are multiple GetContentsView definitions; use the views::Widget one. + return views::Widget::GetContentsView(); } } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/ui/lock_window.h b/chrome/browser/chromeos/login/ui/lock_window.h index bbc2d79..9cc43560 100644 --- a/chrome/browser/chromeos/login/ui/lock_window.h +++ b/chrome/browser/chromeos/login/ui/lock_window.h
@@ -16,10 +16,10 @@ namespace chromeos { -// Shows the widget for the WebUI screen locker. +// Shows the widget for the lock screen. class LockWindow : public views::Widget, public views::WidgetDelegate { public: - explicit LockWindow(views::View* initially_focused_view); + LockWindow(); ~LockWindow() override; private: @@ -28,9 +28,6 @@ views::Widget* GetWidget() override; const views::Widget* GetWidget() const override; - // The view which should be initially focused. - views::View* initially_focused_view_ = nullptr; - DISALLOW_COPY_AND_ASSIGN(LockWindow); };
diff --git a/chrome/browser/chromeos/login/ui/webui_login_view.cc b/chrome/browser/chromeos/login/ui/webui_login_view.cc index 6511541..c8d0821 100644 --- a/chrome/browser/chromeos/login/ui/webui_login_view.cc +++ b/chrome/browser/chromeos/login/ui/webui_login_view.cc
@@ -437,7 +437,7 @@ // ash::ShellObserver: void WebUILoginView::OnVirtualKeyboardStateChanged(bool activated, - ash::WmWindow* root_window) { + aura::Window* root_window) { auto* keyboard_controller = keyboard::KeyboardController::GetInstance(); if (keyboard_controller) { if (activated) {
diff --git a/chrome/browser/chromeos/login/ui/webui_login_view.h b/chrome/browser/chromeos/login/ui/webui_login_view.h index ff303d5..27084d6 100644 --- a/chrome/browser/chromeos/login/ui/webui_login_view.h +++ b/chrome/browser/chromeos/login/ui/webui_login_view.h
@@ -143,7 +143,7 @@ // ash::ShellObserver: void OnVirtualKeyboardStateChanged(bool activated, - ash::WmWindow* root_window) override; + aura::Window* root_window) override; // keyboard::KeyboardControllerObserver: void OnKeyboardBoundsChanging(const gfx::Rect& new_bounds) override;
diff --git a/chrome/browser/chromeos/power/renderer_freezer.cc b/chrome/browser/chromeos/power/renderer_freezer.cc index 707e4cc..05d4314 100644 --- a/chrome/browser/chromeos/power/renderer_freezer.cc +++ b/chrome/browser/chromeos/power/renderer_freezer.cc
@@ -148,9 +148,11 @@ // RendererFreezer::SuspendImminent(), it is guaranteed that the screen locker // renderer will not be frozen at any point. if (is_locked) { - delegate_->SetShouldFreezeRenderer( - locker->web_ui()->GetWebContents()->GetRenderProcessHost()->GetHandle(), - false); + delegate_->SetShouldFreezeRenderer(locker->delegate() + ->GetWebContents() + ->GetRenderProcessHost() + ->GetHandle(), + false); } }
diff --git a/chrome/browser/chromeos/shutdown_policy_browsertest.cc b/chrome/browser/chromeos/shutdown_policy_browsertest.cc index c5b040f..8d71ed0f 100644 --- a/chrome/browser/chromeos/shutdown_policy_browsertest.cc +++ b/chrome/browser/chromeos/shutdown_policy_browsertest.cc
@@ -238,7 +238,8 @@ if (!tester->IsLocked()) lock_state_observer.Wait(); ScreenLocker* screen_locker = ScreenLocker::default_screen_locker(); - WebUIScreenLocker* web_ui_screen_locker = screen_locker->web_ui(); + WebUIScreenLocker* web_ui_screen_locker = + screen_locker->web_ui_for_testing(); ASSERT_TRUE(web_ui_screen_locker); content::WebUI* web_ui = web_ui_screen_locker->GetWebUI(); ASSERT_TRUE(web_ui);
diff --git a/chrome/browser/memory/tab_manager_delegate_chromeos_unittest.cc b/chrome/browser/memory/tab_manager_delegate_chromeos_unittest.cc index dff31b85..fd25dbbe 100644 --- a/chrome/browser/memory/tab_manager_delegate_chromeos_unittest.cc +++ b/chrome/browser/memory/tab_manager_delegate_chromeos_unittest.cc
@@ -78,25 +78,34 @@ candidates = TabManagerDelegate::GetSortedCandidates( tab_list, arc_processes); - EXPECT_EQ(9U, candidates.size()); + ASSERT_EQ(9U, candidates.size()); // focused app. + ASSERT_TRUE(candidates[0].app()); EXPECT_EQ("focused", candidates[0].app()->process_name()); // visible app 1, last_activity_time larger than visible app 2. + ASSERT_TRUE(candidates[1].app()); EXPECT_EQ("visible1", candidates[1].app()->process_name()); // visible app 2, last_activity_time less than visible app 1. + ASSERT_TRUE(candidates[2].app()); EXPECT_EQ("visible2", candidates[2].app()->process_name()); // pinned and media. + ASSERT_TRUE(candidates[3].tab()); EXPECT_EQ(300, candidates[3].tab()->tab_contents_id); // media. + ASSERT_TRUE(candidates[4].tab()); EXPECT_EQ(400, candidates[4].tab()->tab_contents_id); // pinned. + ASSERT_TRUE(candidates[5].tab()); EXPECT_EQ(100, candidates[5].tab()->tab_contents_id); // chrome app. + ASSERT_TRUE(candidates[6].tab()); EXPECT_EQ(500, candidates[6].tab()->tab_contents_id); // internal page. + ASSERT_TRUE(candidates[7].tab()); EXPECT_EQ(200, candidates[7].tab()->tab_contents_id); // background service. + ASSERT_TRUE(candidates[8].app()); EXPECT_EQ("service", candidates[8].app()->process_name()); }
diff --git a/chrome/browser/notifications/notification_platform_bridge_linux.cc b/chrome/browser/notifications/notification_platform_bridge_linux.cc index dfd306c..aa3a6efc 100644 --- a/chrome/browser/notifications/notification_platform_bridge_linux.cc +++ b/chrome/browser/notifications/notification_platform_bridge_linux.cc
@@ -17,9 +17,11 @@ #include "base/metrics/histogram_macros.h" #include "base/strings/nullable_string16.h" #include "base/strings/string_number_conversions.h" +#include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/task_scheduler/post_task.h" +#include "base/version.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/notifications/native_notification_display_service.h" @@ -51,6 +53,7 @@ NATIVE_NOTIFICATIONS_NOT_SUPPORTED = 1, MISSING_REQUIRED_CAPABILITIES = 2, COULD_NOT_CONNECT_TO_SIGNALS = 3, + INCOMPATIBLE_SPEC_VERSION = 4, NUM_ITEMS }; @@ -347,6 +350,30 @@ } RecordMetricsForCapabilities(); + dbus::MethodCall get_server_information_call(kFreedesktopNotificationsName, + "GetServerInformation"); + std::unique_ptr<dbus::Response> server_information_response = + notification_proxy_->CallMethodAndBlock( + &get_server_information_call, + dbus::ObjectProxy::TIMEOUT_USE_DEFAULT); + if (server_information_response) { + dbus::MessageReader reader(server_information_response.get()); + std::string spec_version; + reader.PopString(&spec_version); // name + reader.PopString(&spec_version); // vendor + reader.PopString(&spec_version); // version + reader.PopString(&spec_version); // spec_version + spec_version_ = base::Version(spec_version); + } + // The minimum supported spec version is 1.1, because this was the + // version that added image hints. + if (!spec_version_.IsValid() || + spec_version_ < base::Version(std::vector<uint32_t>{1, 1})) { + OnConnectionInitializationFinishedOnTaskRunner( + ConnectionInitializationStatusCode::INCOMPATIBLE_SPEC_VERSION); + return; + } + connected_signals_barrier_ = base::BarrierClosure( 2, base::Bind(&NotificationPlatformBridgeLinuxImpl:: OnConnectionInitializationFinishedOnTaskRunner, @@ -472,7 +499,10 @@ if (icon_file) { dbus::MessageWriter image_path_writer(nullptr); hints_writer.OpenDictEntry(&image_path_writer); - image_path_writer.AppendString("image-path"); + image_path_writer.AppendString( + spec_version_ == base::Version(std::vector<uint32_t>{1, 1}) + ? "image_path" + : "image-path"); image_path_writer.AppendVariantOfString(icon_file->file_path().value()); hints_writer.CloseContainer(&image_path_writer); data->resource_files.push_back(std::move(icon_file)); @@ -700,6 +730,8 @@ std::unordered_set<std::string> capabilities_; + base::Version spec_version_; + base::Closure connected_signals_barrier_; // A std::set<std::unique_ptr<T>> doesn't work well because
diff --git a/chrome/browser/notifications/notification_platform_bridge_linux_unittest.cc b/chrome/browser/notifications/notification_platform_bridge_linux_unittest.cc index 0917914..24c4a37 100644 --- a/chrome/browser/notifications/notification_platform_bridge_linux_unittest.cc +++ b/chrome/browser/notifications/notification_platform_bridge_linux_unittest.cc
@@ -44,6 +44,16 @@ return response; } +ACTION_P(OnGetServerInformation, spec_version) { + dbus::Response* response = dbus::Response::CreateEmpty().release(); + dbus::MessageWriter writer(response); + writer.AppendString(""); // name + writer.AppendString(""); // vendor + writer.AppendString(""); // version + writer.AppendString(spec_version); + return response; +} + ACTION_P(OnNotify, id) { // The "Notify" message must have type (susssasa{sv}i). // https://developer.gnome.org/notification-spec/#command-notify @@ -142,6 +152,10 @@ MockCallMethodAndBlock(Calls("GetCapabilities"), _)) .WillOnce(OnGetCapabilities(std::vector<std::string>())); + EXPECT_CALL(*mock_notification_proxy_.get(), + MockCallMethodAndBlock(Calls("GetServerInformation"), _)) + .WillOnce(OnGetServerInformation("1.2")); + EXPECT_CALL( *mock_notification_proxy_.get(), ConnectToSignal(kFreedesktopNotificationsName, "ActionInvoked", _, _)) @@ -151,9 +165,6 @@ ConnectToSignal(kFreedesktopNotificationsName, "NotificationClosed", _, _)) .WillOnce(RegisterSignalCallback(¬ification_closed_callback_)); - - notification_bridge_linux_ = - base::WrapUnique(new NotificationPlatformBridgeLinux(mock_bus_)); } void TearDown() override { @@ -166,6 +177,11 @@ } protected: + void CreateNotificationBridgeLinux() { + notification_bridge_linux_ = + base::WrapUnique(new NotificationPlatformBridgeLinux(mock_bus_)); + } + content::TestBrowserThreadBundle thread_bundle_; scoped_refptr<dbus::MockBus> mock_bus_; @@ -180,19 +196,21 @@ DISALLOW_COPY_AND_ASSIGN(NotificationPlatformBridgeLinuxTest); }; -TEST_F(NotificationPlatformBridgeLinuxTest, SetUpAndTearDown) {} +TEST_F(NotificationPlatformBridgeLinuxTest, SetUpAndTearDown) { + CreateNotificationBridgeLinux(); +} -// Frequently triggers a data race. Disabled as flaky: https://crbug.com/719485 -TEST_F(NotificationPlatformBridgeLinuxTest, DISABLED_NotifyAndCloseFormat) { +TEST_F(NotificationPlatformBridgeLinuxTest, NotifyAndCloseFormat) { EXPECT_CALL(*mock_notification_proxy_.get(), MockCallMethodAndBlock(Calls("Notify"), _)) .WillOnce(OnNotify(1)); - notification_bridge_linux_->Display(NotificationCommon::PERSISTENT, "", "", - false, - CreateNotification("id1", "", "", "")); - EXPECT_CALL(*mock_notification_proxy_.get(), MockCallMethodAndBlock(Calls("CloseNotification"), _)) .WillOnce(OnCloseNotification()); + + CreateNotificationBridgeLinux(); + notification_bridge_linux_->Display(NotificationCommon::PERSISTENT, "", "", + false, + CreateNotification("id1", "", "", "")); notification_bridge_linux_->Close("", ""); }
diff --git a/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc b/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc index 3894f76..a1216c84 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc
@@ -83,7 +83,8 @@ safe_browsing::LoginReputationClientRequest::Frame*)); MOCK_METHOD0(IsExtendedReporting, bool()); MOCK_METHOD0(IsIncognito, bool()); - MOCK_METHOD0(IsPingingEnabled, bool()); + MOCK_METHOD1(IsPingingEnabled, bool(const base::Feature&)); + MOCK_METHOD0(IsHistorySyncEnabled, bool()); MOCK_METHOD3(MaybeStartLowReputationRequest, void(const GURL&, const GURL&, const GURL&));
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/api.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/api.js index c4c3cf6d..ca84baef 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/api.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/api.js
@@ -53,19 +53,19 @@ * Tracks whether or not the ChromeVox API should be considered active. * @type {boolean} */ - var isActive_ = false; + var isActive = false; /** * The next id to use for async callbacks. * @type {number} */ - var nextCallbackId_ = 1; + var nextCallbackId = 1; /** * Map from callback ID to callback function. * @type {Object<number, function(*)>} */ - var callbackMap_ = {}; + var callbackMap = {}; /** * Internal function to connect to the content script. @@ -85,9 +85,9 @@ } try { var message = JSON.parse(event.data); - if (message['id'] && callbackMap_[message['id']]) { - callbackMap_[message['id']](message); - delete callbackMap_[message['id']]; + if (message['id'] && callbackMap[message['id']]) { + callbackMap[message['id']](message); + delete callbackMap[message['id']]; } } catch (e) { } @@ -103,13 +103,13 @@ * with the response message. */ function callAsync_(message, callback) { - var id = nextCallbackId_; - nextCallbackId_++; + var id = nextCallbackId; + nextCallbackId++; if (message['args'] === undefined) { message['args'] = []; } message['args'] = [id].concat(message['args']); - callbackMap_[id] = callback; + callbackMap[id] = callback; channel.port1.postMessage(JSON.stringify(message)); } @@ -201,7 +201,7 @@ * Enables the API and connects to the content script. */ cvox.Api.internalEnable = function() { - isActive_ = true; + isActive = true; maybeEnableMathJaX(); if (!implementation) { connect_(); @@ -223,7 +223,7 @@ */ cvox.Api.isChromeVoxActive = function() { if (implementation) { - return isActive_; + return isActive; } return !!channel; };
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/context_menu_widget.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/context_menu_widget.js index 7ea962a1..cc48c5a 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/context_menu_widget.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/context_menu_widget.js
@@ -20,7 +20,7 @@ * @param {Object} node Node to extract from. * @return {*} Extracted list. */ -var extractMenuList_ = function(node) { +var extractMenuList = function(node) { var curr = node; while (curr !== document) { var menuListJSON = curr.getAttribute(CONTEXT_MENU_ATTR); @@ -37,7 +37,7 @@ * @private * @return {Node} Current element node. */ -var getCurrentElement_ = function() { +var getCurrentElement = function() { var currNode = cvox.ChromeVox.navigationManager.getCurrentNode(); while (currNode.nodeType !== Node.ELEMENT_NODE) { currNode = currNode.parentNode; @@ -58,12 +58,12 @@ * @private * @type {Node} */ - this.triggerElement_ = getCurrentElement_(); + this.triggerElement_ = getCurrentElement(); /** * List of menu items in the context menu. */ - this.menuList = extractMenuList_(this.triggerElement_); + this.menuList = extractMenuList(this.triggerElement_); if (!this.menuList) { console.log('No context menu found.');
diff --git a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/util.js b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/util.js index 1cccde9..b40e4dd 100644 --- a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/util.js +++ b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/util.js
@@ -66,7 +66,7 @@ * @return {?string} The id of the active descendant. * @private */ -var getActiveDescendantId_ = function(targetNode) { +var getActiveDescendantId = function(targetNode) { if (!targetNode.getAttribute) { return null; } @@ -93,7 +93,7 @@ var node = targetNode; while (node) { - var activeId = getActiveDescendantId_(node); + var activeId = getActiveDescendantId(node); if (!activeId) { break; }
diff --git a/chrome/browser/resources/chromeos/keyboard/keyboard_utils.js b/chrome/browser/resources/chromeos/keyboard/keyboard_utils.js index bea741ccc..6537865 100644 --- a/chrome/browser/resources/chromeos/keyboard/keyboard_utils.js +++ b/chrome/browser/resources/chromeos/keyboard/keyboard_utils.js
@@ -12,14 +12,14 @@ * saves the host window. * @private */ -var keyboardHostWindow_; +var keyboardHostWindow; /** * keyboard_utils may be injected as content script. This variable gets and * saves the host origin. * @private */ -var keyboardHostOrigin_; +var keyboardHostOrigin; /** * Handles the initial messaging posted from webview, where this script is @@ -30,8 +30,8 @@ keyboard.onInitMessage_ = function(event) { if (event.data == 'initialMessage' && event.origin == 'chrome://oobe') { - keyboardHostWindow_ = event.source; - keyboardHostOrigin_ = event.origin; + keyboardHostWindow = event.source; + keyboardHostOrigin = event.origin; } }; @@ -104,16 +104,16 @@ // (since it is not available) we send an event to the host script // which will make the chrome.send call on our behalf. if (event.key == 'ArrowLeft' || event.key == 'ArrowUp') { - if (!keyboardHostWindow_) + if (!keyboardHostWindow) keyboard.onAdvanceFocus(true); else - keyboardHostWindow_.postMessage('backwardFocus', keyboardHostOrigin_); + keyboardHostWindow.postMessage('backwardFocus', keyboardHostOrigin); event.preventDefault(); } else if (event.key == 'ArrowRight' || event.key == 'ArrowDown') { - if (!keyboardHostWindow_) + if (!keyboardHostWindow) keyboard.onAdvanceFocus(false); else - keyboardHostWindow_.postMessage('forwardFocus', keyboardHostOrigin_); + keyboardHostWindow.postMessage('forwardFocus', keyboardHostOrigin); event.preventDefault(); } }
diff --git a/chrome/browser/resources/chromeos/wallpaper_manager/js/wallpaper_manager.js b/chrome/browser/resources/chromeos/wallpaper_manager/js/wallpaper_manager.js index c2e61fea..0d194f3c 100644 --- a/chrome/browser/resources/chromeos/wallpaper_manager/js/wallpaper_manager.js +++ b/chrome/browser/resources/chromeos/wallpaper_manager/js/wallpaper_manager.js
@@ -476,7 +476,7 @@ return; } var self = this; - var presetCategoryInner_ = function() { + var presetCategoryInner = function() { // Selects the first category in the categories list of current // wallpaper as the default selected category when showing wallpaper // picker UI. @@ -496,7 +496,7 @@ self.categoriesList_.selectionModel.selectedIndex = presetCategory; }; if (navigator.onLine) { - presetCategoryInner_(); + presetCategoryInner(); } else { // If device is offline, gets the available offline wallpaper list first. // Wallpapers which are not in the list will display a grayscaled @@ -506,7 +506,7 @@ self.downloadedListMap_ = {}; for (var i = 0; i < lists.length; i++) self.downloadedListMap_[lists[i]] = true; - presetCategoryInner_(); + presetCategoryInner(); }); } };
diff --git a/chrome/browser/resources/cryptotoken/cryptotokenbackground.js b/chrome/browser/resources/cryptotoken/cryptotokenbackground.js index 717c936..4b8c3004b 100644 --- a/chrome/browser/resources/cryptotoken/cryptotokenbackground.js +++ b/chrome/browser/resources/cryptotoken/cryptotokenbackground.js
@@ -156,24 +156,24 @@ */ function handleLogSaverMessage(request) { if (request === 'start') { - if (originalUtilFmt_) { + if (originalUtilFmt) { // We're already sending return false; } - originalUtilFmt_ = UTIL_fmt; + originalUtilFmt = UTIL_fmt; UTIL_fmt = function(s) { - var line = originalUtilFmt_(s); + var line = originalUtilFmt(s); chrome.runtime.sendMessage(LOG_SAVER_EXTENSION_ID, line); return line; }; } else if (request === 'stop') { - if (originalUtilFmt_) { - UTIL_fmt = originalUtilFmt_; - originalUtilFmt_ = null; + if (originalUtilFmt) { + UTIL_fmt = originalUtilFmt; + originalUtilFmt = null; } } return false; } /** @private */ -var originalUtilFmt_ = null; +var originalUtilFmt = null;
diff --git a/chrome/browser/resources/identity_internals.js b/chrome/browser/resources/identity_internals.js index ae03623..3fc17de 100644 --- a/chrome/browser/resources/identity_internals.js +++ b/chrome/browser/resources/identity_internals.js
@@ -173,17 +173,17 @@ }, }; - var tokenList_; + var tokenList; /** * Initializes the UI by asking the contoller for list of identity tokens. */ function initialize() { chrome.send('identityInternalsGetTokens'); - tokenList_ = $('token-list'); - tokenList_.data_ = []; - tokenList_.__proto__ = TokenList.prototype; - tokenList_.decorate(); + tokenList = $('token-list'); + tokenList.data_ = []; + tokenList.__proto__ = TokenList.prototype; + tokenList.decorate(); } /** @@ -191,8 +191,8 @@ * @param {!Token[]} tokens A list of tokens to be displayed */ function returnTokens(tokens) { - tokenList_.data_ = tokens; - tokenList_.showTokenNodes_(); + tokenList.data_ = tokens; + tokenList.showTokenNodes_(); } /** @@ -202,7 +202,7 @@ */ function tokenRevokeDone(accessTokens) { assert(accessTokens.length > 0); - tokenList_.removeTokenNode_(accessTokens[0]); + tokenList.removeTokenNode_(accessTokens[0]); } // Return an object with all of the exports.
diff --git a/chrome/browser/resources/offline_pages/offline_internals.js b/chrome/browser/resources/offline_pages/offline_internals.js index 892b5a5..c2e1616 100644 --- a/chrome/browser/resources/offline_pages/offline_internals.js +++ b/chrome/browser/resources/offline_pages/offline_internals.js
@@ -12,7 +12,7 @@ var savePageRequests = []; /** @type {!offlineInternals.OfflineInternalsBrowserProxy} */ - var browserProxy_ = + var browserProxy = offlineInternals.OfflineInternalsBrowserProxyImpl.getInstance(); /** @@ -116,9 +116,9 @@ * Refresh all displayed information. */ function refreshAll() { - browserProxy_.getStoredPages().then(fillStoredPages); - browserProxy_.getRequestQueue().then(fillRequestQueue); - browserProxy_.getNetworkStatus().then(function(networkStatus) { + browserProxy.getStoredPages().then(fillStoredPages); + browserProxy.getRequestQueue().then(fillRequestQueue); + browserProxy.getNetworkStatus().then(function(networkStatus) { $('current-status').textContent = networkStatus; }); refreshLog(); @@ -135,7 +135,7 @@ selectedIds.push(checkboxes[i].value); } - browserProxy_.deleteSelectedPages(selectedIds).then(pagesDeleted); + browserProxy.deleteSelectedPages(selectedIds).then(pagesDeleted); } /** @@ -149,7 +149,7 @@ selectedIds.push(checkboxes[i].value); } - browserProxy_.deleteSelectedRequests(selectedIds).then(requestsDeleted); + browserProxy.deleteSelectedRequests(selectedIds).then(requestsDeleted); } /** @@ -158,7 +158,7 @@ */ function pagesDeleted(status) { $('page-actions-info').textContent = status; - browserProxy_.getStoredPages().then(fillStoredPages); + browserProxy.getStoredPages().then(fillStoredPages); } /** @@ -166,7 +166,7 @@ */ function requestsDeleted(status) { $('request-queue-actions-info').textContent = status; - browserProxy_.getRequestQueue().then(fillRequestQueue); + browserProxy.getRequestQueue().then(fillRequestQueue); } /** @@ -205,7 +205,7 @@ selectedIds.push(checkboxes[i].value); } - browserProxy_.deleteSelectedPages(selectedIds).then(pagesDeleted); + browserProxy.deleteSelectedPages(selectedIds).then(pagesDeleted); } /** @@ -220,15 +220,15 @@ selectedIds.push(checkboxes[i].value); } - browserProxy_.deleteSelectedRequests(selectedIds).then(requestsDeleted); + browserProxy.deleteSelectedRequests(selectedIds).then(requestsDeleted); } /** * Refreshes the logs. */ function refreshLog() { - browserProxy_.getEventLogs().then(fillEventLog); - browserProxy_.getLoggingState().then(updateLogStatus); + browserProxy.getEventLogs().then(fillEventLog); + browserProxy.getLoggingState().then(updateLogStatus); } function initialize() { @@ -236,7 +236,7 @@ * @param {!boolean} enabled Whether to enable Logging. */ function togglePageModelLog(enabled) { - browserProxy_.setRecordPageModel(enabled); + browserProxy.setRecordPageModel(enabled); $('model-status').textContent = enabled ? 'On' : 'Off'; } @@ -244,7 +244,7 @@ * @param {!boolean} enabled Whether to enable Logging. */ function toggleRequestQueueLog(enabled) { - browserProxy_.setRecordRequestQueue(enabled); + browserProxy.setRecordRequestQueue(enabled); $('request-status').textContent = enabled ? 'On' : 'Off'; } @@ -275,7 +275,7 @@ var counter = saveUrls.length; $('save-url-state').textContent = ''; for (let i = 0; i < saveUrls.length; i++) { - browserProxy_.addToRequestQueue(saveUrls[i]) + browserProxy.addToRequestQueue(saveUrls[i]) .then(function(state) { if (state) { $('save-url-state').textContent += @@ -283,7 +283,7 @@ $('url').value = ''; counter--; if (counter == 0) { - browserProxy_.getRequestQueue().then(fillRequestQueue); + browserProxy.getRequestQueue().then(fillRequestQueue); } } else { $('save-url-state').textContent += @@ -293,11 +293,11 @@ } }; $('schedule-nwake').onclick = function() { - browserProxy_.scheduleNwake(); - } + browserProxy.scheduleNwake(); + }; $('cancel-nwake').onclick = function() { - browserProxy_.cancelNwake(); - } + browserProxy.cancelNwake(); + }; if (!incognito) refreshAll(); }
diff --git a/chrome/browser/resources/options/chromeos/internet_detail_ip_address_field.js b/chrome/browser/resources/options/chromeos/internet_detail_ip_address_field.js index d4cd42a1..a5e4f69 100644 --- a/chrome/browser/resources/options/chromeos/internet_detail_ip_address_field.js +++ b/chrome/browser/resources/options/chromeos/internet_detail_ip_address_field.js
@@ -11,7 +11,7 @@ * @const * @type {RegExp} */ - var singleIp_ = /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/; + var singleIp = /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/; /** * Creates a new field specifically for entering IP addresses. @@ -58,7 +58,7 @@ // Make sure it's only got numbers and ".", there are the correct // count of them, and they are all within the correct range. var fieldValue = this.editField.value.replace(/\s/g, ''); - var matches = singleIp_.exec(fieldValue); + var matches = singleIp.exec(fieldValue); var rangeCorrect = true; if (matches != null) { for (var i = 1; i < matches.length; ++i) { @@ -92,7 +92,7 @@ return value; var fieldValue = value.replace(/\s/g, ''); - var matches = singleIp_.exec(fieldValue); + var matches = singleIp.exec(fieldValue); var result = []; // If we got this far, matches shouldn't be null, but make sure.
diff --git a/chrome/browser/resources/options/chromeos/network_list.js b/chrome/browser/resources/options/chromeos/network_list.js index 1baa9e2..7b75858 100644 --- a/chrome/browser/resources/options/chromeos/network_list.js +++ b/chrome/browser/resources/options/chromeos/network_list.js
@@ -73,56 +73,56 @@ * @type {?string} * @private */ - var activeMenu_ = null; + var activeMenu = null; /** * The state of the cellular device or undefined if not available. * @type {?chrome.networkingPrivate.DeviceStateProperties} * @private */ - var cellularDevice_ = null; + var cellularDevice = null; /** * The active cellular network or null if none. * @type {?NetworkProperties} * @private */ - var cellularNetwork_ = null; + var cellularNetwork = null; /** * The active ethernet network or null if none. * @type {?NetworkProperties} * @private */ - var ethernetNetwork_ = null; + var ethernetNetwork = null; /** * The state of the WiFi device or undefined if not available. * @type {string|undefined} * @private */ - var wifiDeviceState_ = undefined; + var wifiDeviceState = undefined; /** * The state of the WiMAX device or undefined if not available. * @type {string|undefined} * @private */ - var wimaxDeviceState_ = undefined; + var wimaxDeviceState = undefined; /** * The current list of third-party VPN providers. * @type {!Array<!chrome.networkingPrivate.ThirdPartyVPNProperties>}} * @private */ - var vpnProviders_ = []; + var vpnProviders = []; /** * Indicates if mobile data roaming is enabled. * @type {boolean} * @private */ - var enableDataRoaming_ = false; + var enableDataRoaming = false; /** * Returns the display name for 'network'. @@ -400,7 +400,7 @@ */ refreshMenu: function() { this.menu_ = null; - if (activeMenu_ == this.getMenuName()) + if (activeMenu == this.getMenuName()) this.showMenu(); }, @@ -413,7 +413,7 @@ // list is up to date. Networks are periodically rescanned, but depending // on timing, there could be an excessive delay before the first rescan // unless forced. - var rescan = !activeMenu_ && this.data_.key == 'WiFi'; + var rescan = !activeMenu && this.data_.key == 'WiFi'; if (!this.menu_) { rebuild = true; var existing = $(this.getMenuName()); @@ -435,9 +435,9 @@ } var top = this.offsetTop + this.clientHeight; var menuId = this.getMenuName(); - if (menuId != activeMenu_ || rebuild) { + if (menuId != activeMenu || rebuild) { closeMenu_(); - activeMenu_ = menuId; + activeMenu = menuId; this.menu_.style.setProperty('top', top + 'px'); this.menu_.hidden = false; } @@ -537,7 +537,7 @@ if (candidateData && isManaged(candidateData.Source)) this.showManagedNetworkIndicator(); - if (activeMenu_ == this.getMenuName()) { + if (activeMenu == this.getMenuName()) { // Menu is already showing and needs to be updated. Explicitly calling // show menu will force the existing menu to be replaced. The call // is deferred in order to ensure that position of this element has @@ -573,9 +573,9 @@ } addendum.push(item); } else if (this.data_.key == 'Cellular') { - if (cellularDevice_.State == 'Enabled' && - cellularNetwork_ && cellularNetwork_.Cellular && - cellularNetwork_.Cellular.SupportNetworkScan) { + if (cellularDevice.State == 'Enabled' && + cellularNetwork && cellularNetwork.Cellular && + cellularNetwork.Cellular.SupportNetworkScan) { addendum.push({ label: loadTimeData.getString('otherCellularNetworks'), command: createAddNonVPNConnectionCallback_('Cellular'), @@ -584,7 +584,7 @@ }); } - var label = enableDataRoaming_ ? 'disableDataRoaming' : + var label = enableDataRoaming ? 'disableDataRoaming' : 'enableDataRoaming'; var disabled = !loadTimeData.getValue('loggedInAsOwner'); var entry = {label: loadTimeData.getString(label), @@ -598,7 +598,7 @@ entry.command = function() { options.Preferences.setBooleanPref( 'cros.signed.data_roaming_enabled', - !enableDataRoaming_, true); + !enableDataRoaming, true); // Force revalidation of the menu the next time it is displayed. self.menu_ = null; }; @@ -709,7 +709,7 @@ /** @override */ canUpdateMenu: function() { - return this.data_.key == 'WiFi' && activeMenu_ == this.getMenuName(); + return this.data_.key == 'WiFi' && activeMenu == this.getMenuName(); }, /** @@ -925,7 +925,7 @@ var prefs = options.Preferences.getInstance(); prefs.addEventListener('cros.signed.data_roaming_enabled', function(event) { - enableDataRoaming_ = event.value.value; + enableDataRoaming = event.value.value; }); this.endBatchUpdates(); @@ -971,13 +971,13 @@ * @private */ onGetAllExtensions_: function(extensions) { - vpnProviders_ = []; + vpnProviders = []; for (var extension of extensions) this.addVpnProvider_(extension); }, /** - * If |extension| is a third-party VPN provider, add it to vpnProviders_. + * If |extension| is a third-party VPN provider, add it to vpnProviders. * @param {!ExtensionInfo} extension * @private */ @@ -989,7 +989,7 @@ // Ensure that we haven't already added this provider, e.g. if // the onExtensionAdded_ callback gets invoked after onGetAllExtensions_ // for an extension in the returned list. - for (var provider of vpnProviders_) { + for (var provider of vpnProviders) { if (provider.ExtensionID == extension.id) return; } @@ -997,7 +997,7 @@ ExtensionID: extension.id, ProviderName: extension.name }; - vpnProviders_.push(newProvider); + vpnProviders.push(newProvider); this.refreshVpnProviders_(); }, @@ -1016,10 +1016,10 @@ * @private */ onExtensionRemoved_: function(extensionId) { - for (var i = 0; i < vpnProviders_.length; ++i) { - var provider = vpnProviders_[i]; + for (var i = 0; i < vpnProviders.length; ++i) { + var provider = vpnProviders[i]; if (provider.ExtensionID == extensionId) { - vpnProviders_.splice(i, 1); + vpnProviders.splice(i, 1); this.refreshVpnProviders_(); break; } @@ -1072,14 +1072,14 @@ /** @override */ handleKeyDown: function(e) { - if (activeMenu_) { + if (activeMenu) { // keyIdentifier does not report 'Esc' correctly if (e.keyCode == 27 /* Esc */) { closeMenu_(); return; } - if ($(activeMenu_).handleKeyDown(e)) { + if ($(activeMenu).handleKeyDown(e)) { e.preventDefault(); e.stopPropagation(); } @@ -1109,11 +1109,11 @@ // A list item may temporarily become unselected while it is constructing // its menu. The menu should therefore only be closed if a different item // is selected, not when the menu's owner item is deselected. - if (activeMenu_) { + if (activeMenu) { for (var i = 0; i < event.changes.length; ++i) { if (event.changes[i].selected) { var item = this.dataModel.item(event.changes[i].index); - if (!item.getMenuName || item.getMenuName() != activeMenu_) { + if (!item.getMenuName || item.getMenuName() != activeMenu) { closeMenu_(); return; } @@ -1219,24 +1219,24 @@ */ updateNetworkStates: function(deviceStates, networkStates) { // Update device states. - cellularDevice_ = null; - wifiDeviceState_ = undefined; - wimaxDeviceState_ = undefined; + cellularDevice = null; + wifiDeviceState = undefined; + wimaxDeviceState = undefined; for (var i = 0; i < deviceStates.length; ++i) { var device = deviceStates[i]; var type = device.Type; var state = device.State; if (type == 'Cellular') - cellularDevice_ = cellularDevice_ || device; + cellularDevice = cellularDevice || device; else if (type == 'WiFi') - wifiDeviceState_ = wifiDeviceState_ || state; + wifiDeviceState = wifiDeviceState || state; else if (type == 'WiMAX') - wimaxDeviceState_ = wimaxDeviceState_ || state; + wimaxDeviceState = wimaxDeviceState || state; } // Update active network states. - cellularNetwork_ = null; - ethernetNetwork_ = null; + cellularNetwork = null; + ethernetNetwork = null; for (var i = 0; i < networkStates.length; i++) { // Note: This cast is valid since // networkingPrivate.NetworkStateProperties is a subset of @@ -1244,25 +1244,25 @@ var entry = /** @type {NetworkProperties} */ (networkStates[i]); switch (entry.Type) { case 'Cellular': - cellularNetwork_ = cellularNetwork_ || entry; + cellularNetwork = cellularNetwork || entry; break; case 'Ethernet': // Ignore any EAP Parameters networks (which lack ConnectionState). if (entry.ConnectionState) - ethernetNetwork_ = ethernetNetwork_ || entry; + ethernetNetwork = ethernetNetwork || entry; break; } - if (cellularNetwork_ && ethernetNetwork_) + if (cellularNetwork && ethernetNetwork) break; } - if (cellularNetwork_ && cellularNetwork_.GUID) { + if (cellularNetwork && cellularNetwork.GUID) { // Get the complete set of cellular properties which includes SIM and // Scan properties. var networkList = this; chrome.networkingPrivate.getProperties( - cellularNetwork_.GUID, function(cellular) { - cellularNetwork_ = /** @type {NetworkProperties} */ (cellular); + cellularNetwork.GUID, function(cellular) { + cellularNetwork = /** @type {NetworkProperties} */ (cellular); networkList.updateControls(networkStates); }); } else { @@ -1279,9 +1279,9 @@ this.startBatchUpdates(); // Only show Ethernet control if available. - if (ethernetNetwork_) { - var ethernetOptions = showDetails.bind(null, ethernetNetwork_.GUID); - var state = ethernetNetwork_.ConnectionState; + if (ethernetNetwork) { + var ethernetOptions = showDetails.bind(null, ethernetNetwork.GUID); + var state = ethernetNetwork.ConnectionState; var subtitle; if (state == 'Connected') subtitle = loadTimeData.getString('OncConnectionStateConnected'); @@ -1292,29 +1292,29 @@ this.update( { key: 'Ethernet', subtitle: subtitle, - iconData: ethernetNetwork_, + iconData: ethernetNetwork, command: ethernetOptions, - Source: ethernetNetwork_.Source } + Source: ethernetNetwork.Source } ); } else { this.deleteItem('Ethernet'); } - if (wifiDeviceState_ == 'Enabled') + if (wifiDeviceState == 'Enabled') loadData_('WiFi', networkStates); - else if (wifiDeviceState_ == + else if (wifiDeviceState == chrome.networkingPrivate.DeviceStateType.PROHIBITED) setTechnologiesProhibited_(chrome.networkingPrivate.NetworkType.WI_FI); else addEnableNetworkButton_(chrome.networkingPrivate.NetworkType.WI_FI); // Only show cellular control if available. - if (cellularDevice_) { - if (cellularDevice_.State == 'Enabled' && - !isCellularSimAbsent(cellularDevice_) && - !isCellularSimLocked(cellularDevice_)) { + if (cellularDevice) { + if (cellularDevice.State == 'Enabled' && + !isCellularSimAbsent(cellularDevice) && + !isCellularSimLocked(cellularDevice)) { loadData_('Cellular', networkStates); - } else if (cellularDevice_.State == + } else if (cellularDevice.State == chrome.networkingPrivate.DeviceStateType.PROHIBITED) { setTechnologiesProhibited_( chrome.networkingPrivate.NetworkType.CELLULAR); @@ -1327,10 +1327,10 @@ } // Only show wimax control if available. Uses cellular icons. - if (wimaxDeviceState_) { - if (wimaxDeviceState_ == 'Enabled') { + if (wimaxDeviceState) { + if (wimaxDeviceState == 'Enabled') { loadData_('WiMAX', networkStates); - } else if (wimaxDeviceState_ == + } else if (wimaxDeviceState == chrome.networkingPrivate.DeviceStateType.PROHIBITED) { setTechnologiesProhibited_( chrome.networkingPrivate.NetworkType.WI_MAX); @@ -1360,10 +1360,10 @@ if (type == chrome.networkingPrivate.NetworkType.WI_FI) sendChromeMetricsAction('Options_NetworkWifiToggle'); if (type == chrome.networkingPrivate.NetworkType.CELLULAR) { - if (isCellularSimLocked(cellularDevice_)) { + if (isCellularSimLocked(cellularDevice)) { chrome.send('simOperation', ['unlock']); return; - } else if (isCellularSimAbsent(cellularDevice_)) { + } else if (isCellularSimAbsent(cellularDevice)) { chrome.send('simOperation', ['configure']); return; } @@ -1439,7 +1439,7 @@ /** @override */ toggleBubble: function() { - if (activeMenu_ && !$(activeMenu_).contains(this)) + if (activeMenu && !$(activeMenu).contains(this)) closeMenu_(); ControlledSettingIndicator.prototype.toggleBubble.call(this); if (this.showingBubble) { @@ -1489,12 +1489,12 @@ * @private */ function closeMenu_() { - if (activeMenu_) { - var menu = $(activeMenu_); + if (activeMenu) { + var menu = $(activeMenu); menu.hidden = true; if (menu.data && menu.data.discardOnClose) menu.parentNode.removeChild(menu); - activeMenu_ = null; + activeMenu = null; } } @@ -1542,8 +1542,8 @@ */ function createAddVPNConnectionEntries_() { var entries = []; - for (var i = 0; i < vpnProviders_.length; ++i) { - var provider = vpnProviders_[i]; + for (var i = 0; i < vpnProviders.length; ++i) { + var provider = vpnProviders[i]; entries.push({ label: loadTimeData.getStringF('addConnectionVPNTemplate', provider.ProviderName),
diff --git a/chrome/browser/resources/print_preview/print_preview_animations.js b/chrome/browser/resources/print_preview/print_preview_animations.js index b8b1a19b..5b7ad05 100644 --- a/chrome/browser/resources/print_preview/print_preview_animations.js +++ b/chrome/browser/resources/print_preview/print_preview_animations.js
@@ -5,7 +5,7 @@ // Counter used to give animations unique names. var animationCounter = 0; -var animationEventTracker_ = new EventTracker(); +var animationEventTracker = new EventTracker(); function addAnimation(code) { var name = 'anim' + animationCounter; @@ -54,7 +54,7 @@ } else { el.style.height = height + 'px'; var animName = addAnimation(getFadeInAnimationCode(height)); - animationEventTracker_.add( + animationEventTracker.add( el, 'animationend', onFadeInAnimationEnd.bind(el), false); el.style.animationName = animName; } @@ -74,7 +74,7 @@ var height = el.offsetHeight; el.style.height = height + 'px'; el.offsetHeight; // Should force an update of the computed style. - animationEventTracker_.add( + animationEventTracker.add( el, 'transitionend', onFadeOutTransitionEnd.bind(el), false); el.classList.add('closing'); el.classList.remove('visible'); @@ -89,7 +89,7 @@ function onFadeOutTransitionEnd(event) { if (event.propertyName != 'height') return; - animationEventTracker_.remove(this, 'transitionend'); + animationEventTracker.remove(this, 'transitionend'); this.hidden = true; } @@ -113,7 +113,7 @@ if (animEl) animEl.parentNode.removeChild(animEl); element.style.animationName = ''; - animationEventTracker_.remove(element, 'animationend'); + animationEventTracker.remove(element, 'animationend'); } }
diff --git a/chrome/browser/resources/settings/privacy_page/privacy_page.html b/chrome/browser/resources/settings/privacy_page/privacy_page.html index 67000f8..cdc9dc2 100644 --- a/chrome/browser/resources/settings/privacy_page/privacy_page.html +++ b/chrome/browser/resources/settings/privacy_page/privacy_page.html
@@ -404,17 +404,19 @@ </settings-subpage> </template> <template is="dom-if" if="[[enableSafeBrowsingSubresourceFilter_]]" - route-path="/content/subresourceFilter" no-search> - <settings-subpage page-title="$i18n{siteSettingsSubresourceFilter}"> - <category-default-setting - category="{{ContentSettingsTypes.SUBRESOURCE_FILTER}}" - toggle-off-label="$i18n{siteSettingsSubresourceFilterAllow}" - toggle-on-label="$i18n{siteSettingsSubresourceFilterBlock}"> - </category-default-setting> - <category-setting-exceptions - category="{{ContentSettingsTypes.SUBRESOURCE_FILTER}}"> - </category-setting-exceptions> - </settings-subpage> + no-search> + <template is="dom-if" route-path="/content/subresourceFilter" no-search> + <settings-subpage page-title="$i18n{siteSettingsSubresourceFilter}"> + <category-default-setting + category="{{ContentSettingsTypes.SUBRESOURCE_FILTER}}" + toggle-off-label="$i18n{siteSettingsSubresourceFilterAllow}" + toggle-on-label="$i18n{siteSettingsSubresourceFilterBlock}"> + </category-default-setting> + <category-setting-exceptions + category="{{ContentSettingsTypes.SUBRESOURCE_FILTER}}"> + </category-setting-exceptions> + </settings-subpage> + </template> </template> <template is="dom-if" route-path="/content/unsandboxedPlugins" no-search> <settings-subpage page-title="$i18n{siteSettingsUnsandboxedPlugins}">
diff --git a/chrome/browser/resources/settings/route.js b/chrome/browser/resources/settings/route.js index 8dfa435c..d90a53e 100644 --- a/chrome/browser/resources/settings/route.js +++ b/chrome/browser/resources/settings/route.js
@@ -239,23 +239,23 @@ r.DETAILED_BUILD_INFO = r.ABOUT_ABOUT.createChild('/help/details'); // </if> - var routeObservers_ = new Set(); + var routeObservers = new Set(); /** @polymerBehavior */ var RouteObserverBehavior = { /** @override */ attached: function() { - assert(!routeObservers_.has(this)); - routeObservers_.add(this); + assert(!routeObservers.has(this)); + routeObservers.add(this); // Emulating Polymer data bindings, the observer is called when the // element starts observing the route. - this.currentRouteChanged(currentRoute_, undefined); + this.currentRouteChanged(currentRoute, undefined); }, /** @override */ detached: function() { - assert(routeObservers_.delete(this)); + assert(routeObservers.delete(this)); }, /** @@ -297,43 +297,43 @@ * settings.initializeRouteFromUrl. * @private {!settings.Route} */ - var currentRoute_ = Route.BASIC; + var currentRoute = Route.BASIC; /** * The current query parameters. This is updated only by settings.navigateTo * or settings.initializeRouteFromUrl. * @private {!URLSearchParams} */ - var currentQueryParameters_ = new URLSearchParams(); + var currentQueryParameters = new URLSearchParams(); /** @private {boolean} */ var lastRouteChangeWasPopstate_ = false; /** @private */ - var initializeRouteFromUrlCalled_ = false; + var initializeRouteFromUrlCalled = false; /** * Initialize the route and query params from the URL. */ var initializeRouteFromUrl = function() { - assert(!initializeRouteFromUrlCalled_); - initializeRouteFromUrlCalled_ = true; + assert(!initializeRouteFromUrlCalled); + initializeRouteFromUrlCalled = true; var route = getRouteForPath(window.location.pathname); // Never allow direct navigation to ADVANCED. if (route && route != Route.ADVANCED) { - currentRoute_ = route; - currentQueryParameters_ = new URLSearchParams(window.location.search); + currentRoute = route; + currentQueryParameters = new URLSearchParams(window.location.search); } else { window.history.replaceState(undefined, '', Route.BASIC.path); } }; function resetRouteForTesting() { - initializeRouteFromUrlCalled_ = false; + initializeRouteFromUrlCalled = false; lastRouteChangeWasPopstate_ = false; - currentRoute_ = Route.BASIC; - currentQueryParameters_ = new URLSearchParams(); + currentRoute = Route.BASIC; + currentQueryParameters = new URLSearchParams(); } /** @@ -343,21 +343,21 @@ * @param {boolean} isPopstate */ var setCurrentRoute = function(route, queryParameters, isPopstate) { - var oldRoute = currentRoute_; - currentRoute_ = route; - currentQueryParameters_ = queryParameters; + var oldRoute = currentRoute; + currentRoute = route; + currentQueryParameters = queryParameters; lastRouteChangeWasPopstate_ = isPopstate; - routeObservers_.forEach(function(observer) { - observer.currentRouteChanged(currentRoute_, oldRoute); + routeObservers.forEach(function(observer) { + observer.currentRouteChanged(currentRoute, oldRoute); }); }; /** @return {!settings.Route} */ - var getCurrentRoute = function() { return currentRoute_; }; + var getCurrentRoute = function() { return currentRoute; }; /** @return {!URLSearchParams} */ var getQueryParameters = function() { - return new URLSearchParams(currentQueryParameters_); // Defensive copy. + return new URLSearchParams(currentQueryParameters); // Defensive copy. }; /** @return {boolean} */ @@ -394,7 +394,7 @@ url += '?' + queryString; // History serializes the state, so we don't push the actual route object. - window.history.pushState(currentRoute_.path, '', url); + window.history.pushState(currentRoute.path, '', url); setCurrentRoute(route, params, false); }; @@ -408,10 +408,10 @@ window.history.state && assert(getRouteForPath(/** @type {string} */ (window.history.state))); - if (previousRoute && previousRoute.depth <= currentRoute_.depth) + if (previousRoute && previousRoute.depth <= currentRoute.depth) window.history.back(); else - navigateTo(currentRoute_.parent || Route.BASIC); + navigateTo(currentRoute.parent || Route.BASIC); }; window.addEventListener('popstate', function(event) {
diff --git a/chrome/browser/resources/settings/site_settings/website_usage_private_api.js b/chrome/browser/resources/settings/site_settings/website_usage_private_api.js index d3376ea..7be7520f 100644 --- a/chrome/browser/resources/settings/site_settings/website_usage_private_api.js +++ b/chrome/browser/resources/settings/site_settings/website_usage_private_api.js
@@ -61,7 +61,7 @@ /** * @type {string} The host for which the usage total is being fetched. */ - var hostName_; + var hostName; /** * Encapsulates the calls between JS and C++ to fetch how much storage the @@ -73,7 +73,7 @@ if (instance != null) instance.websiteDataUsage = ''; - hostName_ = host; + hostName = host; chrome.send('fetchUsageTotal', [host]); }; @@ -89,7 +89,7 @@ if (instance == null) return; - if (hostName_ == host) { + if (hostName == host) { instance.websiteDataUsage = usage; instance.websiteStorageType = type; }
diff --git a/chrome/browser/resources/translate_internals/translate_internals.js b/chrome/browser/resources/translate_internals/translate_internals.js index 0a24168..6e159def 100644 --- a/chrome/browser/resources/translate_internals/translate_internals.js +++ b/chrome/browser/resources/translate_internals/translate_internals.js
@@ -7,13 +7,7 @@ cr.define('cr.translateInternals', function() { - var detectionLogs_ = null; - - function detectionLogs() { - if (detectionLogs_ === null) - detectionLogs_ = []; - return detectionLogs_; - } + var detectionLogs = []; /** * Initializes UI and sends a message to the browser for @@ -365,7 +359,7 @@ * @param {Object} detail The object which represents the logs. */ function onLanguageDetectionInfoAdded(detail) { - cr.translateInternals.detectionLogs().push(detail); + detectionLogs.push(detail); var tr = document.createElement('tr'); @@ -471,7 +465,7 @@ * The callback of button#detetion-logs-dump. */ function onDetectionLogsDump() { - var data = JSON.stringify(cr.translateInternals.detectionLogs()); + var data = JSON.stringify(detectionLogs); var blob = new Blob([data], {'type': 'text/json'}); var url = URL.createObjectURL(blob); var filename = 'translate_internals_detect_logs_dump.json'; @@ -487,7 +481,6 @@ } return { - detectionLogs: detectionLogs, initialize: initialize, messageHandler: messageHandler, };
diff --git a/chrome/browser/safe_browsing/chrome_password_protection_service.cc b/chrome/browser/safe_browsing/chrome_password_protection_service.cc index f979a75..9c4efee 100644 --- a/chrome/browser/safe_browsing/chrome_password_protection_service.cc +++ b/chrome/browser/safe_browsing/chrome_password_protection_service.cc
@@ -5,12 +5,17 @@ #include "chrome/browser/safe_browsing/chrome_password_protection_service.h" #include "base/feature_list.h" +#include "base/metrics/field_trial_params.h" #include "base/metrics/histogram_macros.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/safe_browsing/safe_browsing_navigation_observer_manager.h" #include "chrome/browser/safe_browsing/safe_browsing_service.h" +#include "chrome/browser/sync/profile_sync_service_factory.h" +#include "components/browser_sync/profile_sync_service.h" +#include "components/safe_browsing/password_protection/password_protection_request.h" +#include "components/safe_browsing_db/database_manager.h" #include "components/safe_browsing_db/safe_browsing_prefs.h" using content::BrowserThread; @@ -22,9 +27,6 @@ const int kPasswordEventAttributionUserGestureLimit = 2; } -const base::Feature kPasswordProtectionPingOnly{ - "PasswordProtectionPingOnly", base::FEATURE_DISABLED_BY_DEFAULT}; - ChromePasswordProtectionService::ChromePasswordProtectionService( SafeBrowsingService* sb_service, Profile* profile) @@ -41,9 +43,11 @@ } ChromePasswordProtectionService::~ChromePasswordProtectionService() { - UMA_HISTOGRAM_COUNTS_1000( - "PasswordProtection.NumberOfCachedVerdictBeforeShutdown", - GetStoredVerdictCount()); + if (content_settings()) { + UMA_HISTOGRAM_COUNTS_1000( + "PasswordProtection.NumberOfCachedVerdictBeforeShutdown", + GetStoredVerdictCount()); + } } void ChromePasswordProtectionService::FillReferrerChain( @@ -72,8 +76,42 @@ return profile_->IsOffTheRecord(); } -bool ChromePasswordProtectionService::IsPingingEnabled() { - return base::FeatureList::IsEnabled(kPasswordProtectionPingOnly); +bool ChromePasswordProtectionService::IsPingingEnabled( + const base::Feature& feature) { + if (!base::FeatureList::IsEnabled(feature)) { + return false; + } + + bool allowed_incognito = + base::GetFieldTrialParamByFeatureAsBool(feature, "incognito", false); + if (IsIncognito() && !allowed_incognito) + return false; + + bool allowed_all_population = + base::GetFieldTrialParamByFeatureAsBool(feature, "all_population", false); + if (!allowed_all_population) { + bool allowed_extended_reporting = base::GetFieldTrialParamByFeatureAsBool( + feature, "extended_reporting", false); + if (IsExtendedReporting() && allowed_extended_reporting) + return true; // Ping enabled because this user opted in extended + // reporting. + + bool allowed_history_sync = + base::GetFieldTrialParamByFeatureAsBool(feature, "history_sync", false); + if (IsHistorySyncEnabled() && allowed_history_sync) + return true; + } + + return allowed_all_population; } +bool ChromePasswordProtectionService::IsHistorySyncEnabled() { + browser_sync::ProfileSyncService* sync = + ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_); + return sync && sync->IsSyncActive() && !sync->IsLocalSyncEnabled() && + sync->GetActiveDataTypes().Has(syncer::HISTORY_DELETE_DIRECTIVES); +} + +ChromePasswordProtectionService::ChromePasswordProtectionService() + : PasswordProtectionService(nullptr, nullptr, nullptr, nullptr) {} } // namespace safe_browsing
diff --git a/chrome/browser/safe_browsing/chrome_password_protection_service.h b/chrome/browser/safe_browsing/chrome_password_protection_service.h index 4124c86..77bbc2fe 100644 --- a/chrome/browser/safe_browsing/chrome_password_protection_service.h +++ b/chrome/browser/safe_browsing/chrome_password_protection_service.h
@@ -35,10 +35,30 @@ bool IsIncognito() override; - // Checks if Finch config allows sending pings to Safe Browsing backend. - bool IsPingingEnabled() override; + // Checks if Finch config allows sending pings to Safe Browsing Server. + // |feature| should be either kLowReputationPinging or + // kProtectedPasswordEntryPinging. + bool IsPingingEnabled(const base::Feature& feature) override; + + // If user enabled history syncing. + bool IsHistorySyncEnabled() override; + + FRIEND_TEST_ALL_PREFIXES( + ChromePasswordProtectionServiceTest, + VerifyFinchControlForLowReputationPingSBEROnlyNoIncognito); + FRIEND_TEST_ALL_PREFIXES( + ChromePasswordProtectionServiceTest, + VerifyFinchControlForLowReputationPingSBERAndHistorySyncNoIncognito); + FRIEND_TEST_ALL_PREFIXES(ChromePasswordProtectionServiceTest, + VerifyFinchControlForLowReputationPingAll); + FRIEND_TEST_ALL_PREFIXES( + ChromePasswordProtectionServiceTest, + VerifyFinchControlForLowReputationPingAllButNoIncognito); private: + friend class MockChromePasswordProtectionService; + // Default constructor used for tests only. + ChromePasswordProtectionService(); // Profile associated with this instance. Profile* profile_; scoped_refptr<SafeBrowsingNavigationObserverManager>
diff --git a/chrome/browser/safe_browsing/chrome_password_protection_service_unittest.cc b/chrome/browser/safe_browsing/chrome_password_protection_service_unittest.cc new file mode 100644 index 0000000..03ec3dbd --- /dev/null +++ b/chrome/browser/safe_browsing/chrome_password_protection_service_unittest.cc
@@ -0,0 +1,228 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +#include "chrome/browser/safe_browsing/chrome_password_protection_service.h" + +#include "base/test/scoped_feature_list.h" +#include "components/variations/variations_params_manager.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace safe_browsing { + +class MockChromePasswordProtectionService + : public ChromePasswordProtectionService { + public: + MockChromePasswordProtectionService() + : ChromePasswordProtectionService(), + is_incognito_(false), + is_extended_reporting_(false), + is_history_sync_enabled_(false) {} + bool IsExtendedReporting() override { return is_extended_reporting_; } + bool IsIncognito() override { return is_incognito_; } + bool IsHistorySyncEnabled() override { return is_history_sync_enabled_; } + + // Configures the results returned by IsExtendedReporting(), IsIncognito(), + // and IsHistorySyncEnabled(). + void ConfigService(bool is_incognito, + bool is_extended_reporting, + bool is_history_sync_enabled) { + is_incognito_ = is_incognito; + is_extended_reporting_ = is_extended_reporting; + is_history_sync_enabled_ = is_history_sync_enabled; + } + + private: + bool is_incognito_; + bool is_extended_reporting_; + bool is_history_sync_enabled_; +}; + +class ChromePasswordProtectionServiceTest : public testing::Test { + public: + typedef std::map<std::string, std::string> Parameters; + ChromePasswordProtectionServiceTest() {} + + // Sets up Finch trial feature parameters. + void SetFeatureParams(const base::Feature& feature, + const std::string& trial_name, + const Parameters& params) { + static std::set<std::string> features = {feature.name}; + params_manager_.ClearAllVariationParams(); + params_manager_.SetVariationParamsWithFeatureAssociations(trial_name, + params, features); + } + + // Creates Finch trial parameters. + Parameters CreateParameters(bool allowed_for_incognito, + bool allowed_for_all, + bool allowed_for_extended_reporting, + bool allowed_for_history_sync) { + return {{"incognito", allowed_for_incognito ? "true" : "false"}, + {"all_population", allowed_for_all ? "true" : "false"}, + {"extended_reporting", + allowed_for_extended_reporting ? "true" : "false"}, + {"history_sync", allowed_for_history_sync ? "true" : "false"}}; + } + + protected: + content::TestBrowserThreadBundle thread_bundle_; + variations::testing::VariationParamsManager params_manager_; + base::test::ScopedFeatureList scoped_feature_list_; +}; + +TEST_F(ChromePasswordProtectionServiceTest, + VerifyFinchControlForLowReputationPingSBEROnlyNoIncognito) { + MockChromePasswordProtectionService service; + // By default kLowReputationPinging feature is disabled. + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); + + // Enables kLowReputationPinging feature. + scoped_feature_list_.InitAndEnableFeature(kLowReputationPinging); + // Creates finch trial parameters correspond to the following experiment: + // "name": "SBEROnlyNoIncognito", + // "params": { + // "incognito": "false", + // "extended_reporting": "true", + // "history_sync": "false" + // }, + // "enable_features": [ + // "LowReputationPinging" + // ] + Parameters sber_and_no_incognito = + CreateParameters(false, false, true, false); + SetFeatureParams(kLowReputationPinging, "SBEROnlyNoIncognito", + sber_and_no_incognito); + service.ConfigService(false /*incognito*/, false /*SBER*/, false /*sync*/); + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(false /*incognito*/, false /*SBER*/, true /*sync*/); + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(false /*incognito*/, true /*SBER*/, false /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(false /*incognito*/, true /*SBER*/, true /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(true /*incognito*/, false /*SBER*/, false /*sync*/); + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(true /*incognito*/, false /*SBER*/, true /*sync*/); + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(true /*incognito*/, true /*SBER*/, false /*sync*/); + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(true /*incognito*/, true /*SBER*/, true /*sync*/); + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); +} + +TEST_F(ChromePasswordProtectionServiceTest, + VerifyFinchControlForLowReputationPingSBERAndHistorySyncNoIncognito) { + MockChromePasswordProtectionService service; + // By default kLowReputationPinging feature is disabled. + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); + + // Enables kLowReputationPinging feature. + scoped_feature_list_.InitAndEnableFeature(kLowReputationPinging); + // Creates finch trial parameters correspond to the following experiment: + // "name": "SBERAndHistorySyncNoIncognito", + // "params": { + // "incognito": "false", + // "extended_reporting": "true", + // "history_sync": "true" + // }, + // "enable_features": [ + // "LowReputationPinging" + // ] + Parameters sber_and_sync_no_incognito = + CreateParameters(false, false, true, true); + SetFeatureParams(kLowReputationPinging, "SBERAndHistorySyncNoIncognito", + sber_and_sync_no_incognito); + service.ConfigService(false /*incognito*/, false /*SBER*/, false /*sync*/); + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(false /*incognito*/, false /*SBER*/, true /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(false /*incognito*/, true /*SBER*/, false /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(false /*incognito*/, true /*SBER*/, true /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(true /*incognito*/, false /*SBER*/, false /*sync*/); + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(true /*incognito*/, false /*SBER*/, true /*sync*/); + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(true /*incognito*/, true /*SBER*/, false /*sync*/); + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(true /*incognito*/, true /*SBER*/, true /*sync*/); + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); +} + +TEST_F(ChromePasswordProtectionServiceTest, + VerifyFinchControlForLowReputationPingAllButNoIncognito) { + MockChromePasswordProtectionService service; + // By default kLowReputationPinging feature is disabled. + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); + + // Enables kLowReputationPinging feature. + scoped_feature_list_.InitAndEnableFeature(kLowReputationPinging); + // Creates finch trial parameters correspond to the following experiment: + // "name": "AllButNoIncognito", + // "params": { + // "all_population": "true", + // "incongito": "false" + // }, + // "enable_features": [ + // "LowReputationPinging" + // ] + Parameters all_users = CreateParameters(false, true, true, true); + SetFeatureParams(kLowReputationPinging, "AllButNoIncognito", all_users); + service.ConfigService(false /*incognito*/, false /*SBER*/, false /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(false /*incognito*/, false /*SBER*/, true /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(false /*incognito*/, true /*SBER*/, false /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(false /*incognito*/, true /*SBER*/, true /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(true /*incognito*/, false /*SBER*/, false /*sync*/); + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(true /*incognito*/, false /*SBER*/, true /*sync*/); + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(true /*incognito*/, true /*SBER*/, false /*sync*/); + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(true /*incognito*/, true /*SBER*/, true /*sync*/); + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); +} + +TEST_F(ChromePasswordProtectionServiceTest, + VerifyFinchControlForLowReputationPingAll) { + MockChromePasswordProtectionService service; + // By default kLowReputationPinging feature is disabled. + EXPECT_FALSE(service.IsPingingEnabled(kLowReputationPinging)); + + // Enables kLowReputationPinging feature. + scoped_feature_list_.InitAndEnableFeature(kLowReputationPinging); + // Creates finch trial parameters correspond to the following experiment: + // "name": "All", + // "params": { + // "all_population": "true", + // "incognito": "true" + // }, + // "enable_features": [ + // "LowReputationPinging" + // ] + Parameters all_users = CreateParameters(true, true, true, true); + SetFeatureParams(kLowReputationPinging, "All", all_users); + service.ConfigService(false /*incognito*/, false /*SBER*/, false /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(false /*incognito*/, false /*SBER*/, true /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(false /*incognito*/, true /*SBER*/, false /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(false /*incognito*/, true /*SBER*/, true /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(true /*incognito*/, false /*SBER*/, false /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(true /*incognito*/, false /*SBER*/, true /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(true /*incognito*/, true /*SBER*/, false /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); + service.ConfigService(true /*incognito*/, true /*SBER*/, true /*sync*/); + EXPECT_TRUE(service.IsPingingEnabled(kLowReputationPinging)); +} + +} // namespace safe_browsing
diff --git a/chrome/browser/subresource_filter/chrome_subresource_filter_client.cc b/chrome/browser/subresource_filter/chrome_subresource_filter_client.cc index fc42142..c8e2adb 100644 --- a/chrome/browser/subresource_filter/chrome_subresource_filter_client.cc +++ b/chrome/browser/subresource_filter/chrome_subresource_filter_client.cc
@@ -10,11 +10,12 @@ #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/content_settings/tab_specific_content_settings.h" #include "chrome/browser/infobars/infobar_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/safe_browsing/safe_browsing_service.h" +#include "chrome/browser/subresource_filter/subresource_filter_content_settings_manager.h" +#include "chrome/browser/subresource_filter/subresource_filter_profile_context.h" #include "chrome/browser/subresource_filter/subresource_filter_profile_context_factory.h" #include "chrome/browser/ui/android/content_settings/subresource_filter_infobar_delegate.h" #include "components/content_settings/core/browser/host_content_settings_map.h" @@ -25,7 +26,9 @@ #include "components/subresource_filter/content/browser/content_subresource_filter_driver_factory.h" #include "components/subresource_filter/content/browser/subresource_filter_safe_browsing_activation_throttle.h" #include "components/subresource_filter/core/browser/subresource_filter_features.h" +#include "components/subresource_filter/core/common/activation_level.h" #include "components/subresource_filter/core/common/activation_scope.h" +#include "components/subresource_filter/core/common/activation_state.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_handle.h" @@ -35,9 +38,10 @@ content::WebContents* web_contents) : web_contents_(web_contents), did_show_ui_for_navigation_(false) { DCHECK(web_contents); - SubresourceFilterProfileContextFactory::EnsureForProfile( - Profile::FromBrowserContext(web_contents_->GetBrowserContext())); - + SubresourceFilterProfileContext* context = + SubresourceFilterProfileContextFactory::GetForProfile( + Profile::FromBrowserContext(web_contents_->GetBrowserContext())); + settings_manager_ = context->settings_manager(); subresource_filter::ContentSubresourceFilterDriverFactory:: CreateForWebContents(web_contents, this); } @@ -85,21 +89,28 @@ bool visibility) { if (did_show_ui_for_navigation_ && visibility) return; - - did_show_ui_for_navigation_ = visibility; - TabSpecificContentSettings* content_settings = - TabSpecificContentSettings::FromWebContents(web_contents_); + did_show_ui_for_navigation_ = false; // |visibility| is false when a new navigation starts. if (visibility) { - content_settings->OnContentBlocked( - CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER); - LogAction(kActionUIShown); + const GURL& top_level_url = web_contents_->GetLastCommittedURL(); + if (!settings_manager_->ShouldShowUIForSite(top_level_url)) { + LogAction(kActionUISuppressed); + return; + } #if defined(OS_ANDROID) InfoBarService* infobar_service = InfoBarService::FromWebContents(web_contents_); SubresourceFilterInfobarDelegate::Create(infobar_service); #endif + TabSpecificContentSettings* content_settings = + TabSpecificContentSettings::FromWebContents(web_contents_); + content_settings->OnContentBlocked( + CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER); + + LogAction(kActionUIShown); + did_show_ui_for_navigation_ = true; + settings_manager_->OnDidShowUI(top_level_url); } else { LogAction(kActionNavigationStarted); } @@ -110,22 +121,12 @@ const GURL& url(navigation_handle->GetURL()); return navigation_handle->IsInMainFrame() && (whitelisted_hosts_.find(url.host()) != whitelisted_hosts_.end() || - GetContentSettingForUrl(url) == CONTENT_SETTING_BLOCK); + settings_manager_->GetSitePermission(url) == CONTENT_SETTING_BLOCK); } void ChromeSubresourceFilterClient::WhitelistByContentSettings( - const GURL& url) { - // Whitelist via content settings. - Profile* profile = - Profile::FromBrowserContext(web_contents_->GetBrowserContext()); - DCHECK(profile); - HostContentSettingsMap* settings_map = - HostContentSettingsMapFactory::GetForProfile(profile); - settings_map->SetContentSettingDefaultScope( - url, url, ContentSettingsType::CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER, - std::string(), CONTENT_SETTING_BLOCK); - - LogAction(kActionContentSettingsBlockedFromUI); + const GURL& top_level_url) { + settings_manager_->WhitelistSite(top_level_url); } void ChromeSubresourceFilterClient::WhitelistInCurrentWebContents( @@ -140,18 +141,6 @@ kActionLastEntry); } -ContentSetting ChromeSubresourceFilterClient::GetContentSettingForUrl( - const GURL& url) { - Profile* profile = - Profile::FromBrowserContext(web_contents_->GetBrowserContext()); - DCHECK(profile); - HostContentSettingsMap* settings_map = - HostContentSettingsMapFactory::GetForProfile(profile); - return settings_map->GetContentSetting( - url, url, ContentSettingsType::CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER, - std::string()); -} - subresource_filter::VerifiedRulesetDealer::Handle* ChromeSubresourceFilterClient::GetRulesetDealer() { subresource_filter::ContentRulesetService* ruleset_service =
diff --git a/chrome/browser/subresource_filter/chrome_subresource_filter_client.h b/chrome/browser/subresource_filter/chrome_subresource_filter_client.h index c1b8d15..8e47d34 100644 --- a/chrome/browser/subresource_filter/chrome_subresource_filter_client.h +++ b/chrome/browser/subresource_filter/chrome_subresource_filter_client.h
@@ -16,6 +16,7 @@ #include "content/public/browser/web_contents_user_data.h" class GURL; +class SubresourceFilterContentSettingsManager; namespace content { class NavigationHandle; @@ -45,7 +46,8 @@ // Content setting updated automatically via the standard UI. kActionContentSettingsBlockedFromUI, - // Content settings which target specific origins (e.g. no wildcards). + // Content settings which target specific origins (e.g. no wildcards). These + // updates do not include updates from the main UI. kActionContentSettingsAllowed, kActionContentSettingsBlocked, @@ -61,6 +63,16 @@ // flexible. kActionContentSettingsWildcardUpdate, + // The UI was suppressed due to "smart" logic which tries not to spam the UI + // on navigations on the same origin within a certain time. + kActionUISuppressed, + + // The feature was blocked via content setting manually while smart UI was + // suppressing the UI. Potentially indicates that the smart UI is too + // aggressive if this happens frequently. This is a reported alongside + // kActionContentSettingsBlocked if the UI is currently in suppressed mode. + kActionContentSettingsBlockedWhileUISuppressed, + kActionLastEntry }; @@ -94,8 +106,11 @@ static void LogAction(SubresourceFilterAction action); private: - ContentSetting GetContentSettingForUrl(const GURL& url); std::set<std::string> whitelisted_hosts_; + + // Owned by the profile. + SubresourceFilterContentSettingsManager* settings_manager_; + content::WebContents* web_contents_; bool did_show_ui_for_navigation_;
diff --git a/chrome/browser/subresource_filter/subresource_filter_browsertest.cc b/chrome/browser/subresource_filter/subresource_filter_browsertest.cc index c2941ea7..e115e7a 100644 --- a/chrome/browser/subresource_filter/subresource_filter_browsertest.cc +++ b/chrome/browser/subresource_filter/subresource_filter_browsertest.cc
@@ -18,6 +18,7 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/test/histogram_tester.h" +#include "base/test/simple_test_clock.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/content_settings/tab_specific_content_settings.h" @@ -26,6 +27,9 @@ #include "chrome/browser/safe_browsing/test_safe_browsing_service.h" #include "chrome/browser/safe_browsing/v4_test_utils.h" #include "chrome/browser/subresource_filter/chrome_subresource_filter_client.h" +#include "chrome/browser/subresource_filter/subresource_filter_content_settings_manager.h" +#include "chrome/browser/subresource_filter/subresource_filter_profile_context.h" +#include "chrome/browser/subresource_filter/subresource_filter_profile_context_factory.h" #include "chrome/browser/subresource_filter/test_ruleset_publisher.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" @@ -262,6 +266,13 @@ content::SetupCrossSiteRedirector(embedded_test_server()); ASSERT_TRUE(embedded_test_server()->Start()); ResetConfigurationToEnableOnPhishingSites(); + + settings_manager_ = SubresourceFilterProfileContextFactory::GetForProfile( + browser()->profile()) + ->settings_manager(); +#if defined(OS_ANDROID) + EXPECT_TRUE(settings_manager->should_use_smart_ui()); +#endif } GURL GetTestUrl(const std::string& relative_url) { @@ -292,6 +303,10 @@ return browser()->tab_strip_model()->GetActiveWebContents(); } + SubresourceFilterContentSettingsManager* settings_manager() { + return settings_manager_; + } + content::RenderFrameHost* FindFrameByName(const std::string& name) { return content::FrameMatchingPredicate( web_contents(), base::Bind(&content::FrameMatchesName, name)); @@ -383,6 +398,9 @@ // Owned by the V4GetHashProtocolManager. safe_browsing::TestV4GetHashProtocolManagerFactory* v4_get_hash_factory_; + // Owned by the profile. + SubresourceFilterContentSettingsManager* settings_manager_; + DISALLOW_COPY_AND_ASSIGN(SubresourceFilterBrowserTest); }; @@ -825,6 +843,8 @@ ASSERT_NO_FATAL_FAILURE( SetRulesetToDisallowURLsWithPathSuffix("included_script.js")); GURL url(GetTestUrl(kTestFrameSetPath)); + GURL a_url(embedded_test_server()->GetURL( + "a.com", "/subresource_filter/frame_with_included_script.html")); ConfigureAsPhishingURL(url); base::HistogramTester tester; ui_test_utils::NavigateToURL(browser(), url); @@ -834,8 +854,10 @@ EXPECT_FALSE(IsDynamicScriptElementLoaded(FindFrameByName("five"))); tester.ExpectBucketCount(kSubresourceFilterActionsHistogram, kActionUIShown, 1); - // Check that bubble is shown for new navigation. - ui_test_utils::NavigateToURL(browser(), url); + // Check that bubble is shown for new navigation. Must be cross site to avoid + // triggering smart UI on Android. + ConfigureAsPhishingURL(a_url); + ui_test_utils::NavigateToURL(browser(), a_url); tester.ExpectBucketCount(kSubresourceFilterActionsHistogram, kActionUIShown, 2); } @@ -1004,6 +1026,70 @@ EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); } +// Test the "smart" UI, aka the logic to hide the UI on subsequent same-domain +// navigations, until a certain time threshold has been reached. This is an +// android-only feature. +IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest, + DoNotShowUIUntilThresholdReached) { + ASSERT_NO_FATAL_FAILURE( + SetRulesetToDisallowURLsWithPathSuffix("included_script.js")); + GURL a_url(embedded_test_server()->GetURL( + "a.com", "/subresource_filter/frame_with_included_script.html")); + GURL b_url(embedded_test_server()->GetURL( + "b.com", "/subresource_filter/frame_with_included_script.html")); + // Test utils only support one blacklisted site at a time. + // TODO(csharrison): Add support for more than one URL. + ConfigureAsPhishingURL(a_url); + + // Cast is safe because this is the only type of client in non-unittest code. + ChromeSubresourceFilterClient* client = + static_cast<ChromeSubresourceFilterClient*>( + ContentSubresourceFilterDriverFactory::FromWebContents(web_contents()) + ->client()); + auto test_clock = base::MakeUnique<base::SimpleTestClock>(); + base::SimpleTestClock* raw_clock = test_clock.get(); + settings_manager()->set_clock_for_testing(std::move(test_clock)); + + base::HistogramTester histogram_tester; + + // First load should trigger the UI. + ui_test_utils::NavigateToURL(browser(), a_url); + EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + EXPECT_TRUE(client->did_show_ui_for_navigation()); + + histogram_tester.ExpectBucketCount(kSubresourceFilterActionsHistogram, + kActionUISuppressed, 0); + + // Second load should not trigger the UI, but should still filter content. + ui_test_utils::NavigateToURL(browser(), a_url); + EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + + bool use_smart_ui = settings_manager()->should_use_smart_ui(); + EXPECT_EQ(client->did_show_ui_for_navigation(), !use_smart_ui); + + histogram_tester.ExpectBucketCount(kSubresourceFilterActionsHistogram, + kActionUISuppressed, use_smart_ui ? 1 : 0); + + ConfigureAsPhishingURL(b_url); + + // Load to another domain should trigger the UI. + ui_test_utils::NavigateToURL(browser(), b_url); + EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + EXPECT_TRUE(client->did_show_ui_for_navigation()); + + ConfigureAsPhishingURL(a_url); + + // Fast forward the clock, and a_url should trigger the UI again. + raw_clock->Advance( + SubresourceFilterContentSettingsManager::kDelayBeforeShowingInfobarAgain); + ui_test_utils::NavigateToURL(browser(), a_url); + EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + EXPECT_TRUE(client->did_show_ui_for_navigation()); + + histogram_tester.ExpectBucketCount(kSubresourceFilterActionsHistogram, + kActionUISuppressed, use_smart_ui ? 1 : 0); +} + IN_PROC_BROWSER_TEST_P(SubresourceFilterWebSocketBrowserTest, BlockWebSocket) { GURL url(GetTestUrl( base::StringPrintf("subresource_filter/page_with_websocket.html?%s",
diff --git a/chrome/browser/subresource_filter/subresource_filter_content_settings_manager.cc b/chrome/browser/subresource_filter/subresource_filter_content_settings_manager.cc index a478ab1..0fec6e74 100644 --- a/chrome/browser/subresource_filter/subresource_filter_content_settings_manager.cc +++ b/chrome/browser/subresource_filter/subresource_filter_content_settings_manager.cc
@@ -4,27 +4,128 @@ #include "chrome/browser/subresource_filter/subresource_filter_content_settings_manager.h" +#include "base/auto_reset.h" +#include "base/bind.h" +#include "base/feature_list.h" #include "base/logging.h" +#include "base/memory/ptr_util.h" +#include "base/time/default_clock.h" +#include "base/values.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" +#include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/subresource_filter/chrome_subresource_filter_client.h" #include "components/content_settings/core/browser/content_settings_details.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings.h" #include "components/content_settings/core/common/content_settings_pattern.h" +#include "components/history/core/browser/history_service.h" +#include "components/keyed_service/core/service_access_type.h" +#include "components/subresource_filter/core/browser/subresource_filter_features.h" #include "url/gurl.h" +namespace { + +// Key into the website setting dict for the smart UI. +const char kInfobarLastShownTimeKey[] = "InfobarLastShownTime"; + +bool ShouldUseSmartUI() { +#if defined(OS_ANDROID) + return base::FeatureList::IsEnabled( + subresource_filter::kSafeBrowsingSubresourceFilterExperimentalUI); +#endif + return false; +} + +} // namespace + +constexpr base::TimeDelta + SubresourceFilterContentSettingsManager::kDelayBeforeShowingInfobarAgain; + SubresourceFilterContentSettingsManager:: SubresourceFilterContentSettingsManager(Profile* profile) - : settings_map_(HostContentSettingsMapFactory::GetForProfile(profile)) { + : history_observer_(this), + settings_map_(HostContentSettingsMapFactory::GetForProfile(profile)), + clock_(base::MakeUnique<base::DefaultClock>(base::DefaultClock())), + should_use_smart_ui_(ShouldUseSmartUI()) { DCHECK(profile); DCHECK(settings_map_); settings_map_->AddObserver(this); + + if (should_use_smart_ui()) { + if (auto* history_service = HistoryServiceFactory::GetForProfile( + profile, ServiceAccessType::EXPLICIT_ACCESS)) { + history_observer_.Add(history_service); + } + } } SubresourceFilterContentSettingsManager:: ~SubresourceFilterContentSettingsManager() { settings_map_->RemoveObserver(this); + settings_map_ = nullptr; + history_observer_.RemoveAll(); +} + +ContentSetting SubresourceFilterContentSettingsManager::GetSitePermission( + const GURL& url) const { + return settings_map_->GetContentSetting( + url, GURL(), + ContentSettingsType::CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER, + std::string()); +} + +void SubresourceFilterContentSettingsManager::WhitelistSite(const GURL& url) { + base::AutoReset<bool> resetter(&ignore_settings_changes_, true); + settings_map_->SetContentSettingDefaultScope( + url, GURL(), + ContentSettingsType::CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER, + std::string(), CONTENT_SETTING_BLOCK); + ChromeSubresourceFilterClient::LogAction(kActionContentSettingsBlockedFromUI); +} + +void SubresourceFilterContentSettingsManager::OnDidShowUI(const GURL& url) { + if (!should_use_smart_ui()) + return; + auto dict = base::MakeUnique<base::DictionaryValue>(); + double now = clock_->Now().ToDoubleT(); + dict->SetDouble(kInfobarLastShownTimeKey, now); + SetSiteMetadata(url, std::move(dict)); +} + +bool SubresourceFilterContentSettingsManager::ShouldShowUIForSite( + const GURL& url) const { + if (!should_use_smart_ui()) + return true; + + std::unique_ptr<base::DictionaryValue> dict = GetSiteMetadata(url); + if (!dict) + return true; + + double last_shown_time_double = 0; + if (dict->GetDouble(kInfobarLastShownTimeKey, &last_shown_time_double)) { + base::Time last_shown = base::Time::FromDoubleT(last_shown_time_double); + if (clock_->Now() - last_shown < kDelayBeforeShowingInfobarAgain) + return false; + } + return true; +} + +std::unique_ptr<base::DictionaryValue> +SubresourceFilterContentSettingsManager::GetSiteMetadata( + const GURL& url) const { + return base::DictionaryValue::From(settings_map_->GetWebsiteSetting( + url, GURL(), CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER_DATA, std::string(), + nullptr)); +} + +void SubresourceFilterContentSettingsManager::SetSiteMetadata( + const GURL& url, + std::unique_ptr<base::DictionaryValue> dict) { + settings_map_->SetWebsiteSettingDefaultScope( + url, GURL(), + ContentSettingsType::CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER_DATA, + std::string(), std::move(dict)); } void SubresourceFilterContentSettingsManager::OnContentSettingChanged( @@ -32,7 +133,8 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, std::string resource_identifier) { - if (content_type != CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER) + if (content_type != CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER || + ignore_settings_changes_) return; const ContentSettingsDetails details(primary_pattern, secondary_pattern, @@ -76,4 +178,36 @@ } else { NOTREACHED(); } + + if (!should_use_smart_ui()) + return; + + if (!ShouldShowUIForSite(url)) { + ChromeSubresourceFilterClient::LogAction( + kActionContentSettingsBlockedWhileUISuppressed); + } + + // Reset the smart UI to ensure the user can easily change their decision. + SetSiteMetadata(url, nullptr); +} + +// When history URLs are deleted, clear the metadata for the smart UI. +void SubresourceFilterContentSettingsManager::OnURLsDeleted( + history::HistoryService* history_service, + bool all_history, + bool expired, + const history::URLRows& deleted_rows, + const std::set<GURL>& favicon_urls) { + DCHECK(should_use_smart_ui()); + if (all_history) { + settings_map_->ClearSettingsForOneType( + CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER_DATA); + return; + } + + // Careful note: This clears the setting even if there are other URLs with the + // same origin in the history. i.e. this is an aggressive policy. + for (const auto& deleted_row : deleted_rows) { + SetSiteMetadata(deleted_row.url(), nullptr); + } }
diff --git a/chrome/browser/subresource_filter/subresource_filter_content_settings_manager.h b/chrome/browser/subresource_filter/subresource_filter_content_settings_manager.h index c1552ec..31be4339 100644 --- a/chrome/browser/subresource_filter/subresource_filter_content_settings_manager.h +++ b/chrome/browser/subresource_filter/subresource_filter_content_settings_manager.h
@@ -5,24 +5,63 @@ #ifndef CHROME_BROWSER_SUBRESOURCE_FILTER_SUBRESOURCE_FILTER_CONTENT_SETTINGS_MANAGER_H_ #define CHROME_BROWSER_SUBRESOURCE_FILTER_SUBRESOURCE_FILTER_CONTENT_SETTINGS_MANAGER_H_ +#include <memory> +#include <set> #include <string> +#include <utility> #include "base/macros.h" +#include "base/scoped_observer.h" +#include "base/time/clock.h" +#include "base/time/time.h" #include "components/content_settings/core/browser/content_settings_observer.h" +#include "components/content_settings/core/common/content_settings.h" #include "components/content_settings/core/common/content_settings_types.h" +#include "components/history/core/browser/history_service_observer.h" class ContentSettingsPattern; +class GURL; class HostContentSettingsMap; class Profile; -// This class observes subresource filter content settings changes for metrics -// collection. +namespace base { +class DictionaryValue; +} // namespace base + +namespace history { +class HistoryService; +} // namespace history + +// This class contains helpers to get/set content and website settings related +// to subresource filtering. It also observes content setting changes for +// metrics collection. class SubresourceFilterContentSettingsManager - : public content_settings::Observer { + : public content_settings::Observer, + public history::HistoryServiceObserver { public: explicit SubresourceFilterContentSettingsManager(Profile* profile); ~SubresourceFilterContentSettingsManager() override; + ContentSetting GetSitePermission(const GURL& url) const; + + // Only called via direct user action on via the subresource filter UI. Sets + // the content setting to turn off the subresource filter. + void WhitelistSite(const GURL& url); + + // Specific logic for more intelligent UI. + void OnDidShowUI(const GURL& url); + bool ShouldShowUIForSite(const GURL& url) const; + bool should_use_smart_ui() const { return should_use_smart_ui_; } + + void set_clock_for_testing(std::unique_ptr<base::Clock> tick_clock) { + clock_ = std::move(tick_clock); + } + + // Time before showing the UI again on a domain. + // TODO(csharrison): Consider setting this via a finch param. + static constexpr base::TimeDelta kDelayBeforeShowingInfobarAgain = + base::TimeDelta::FromMinutes(30); + private: // content_settings::Observer: void OnContentSettingChanged(const ContentSettingsPattern& primary_pattern, @@ -30,8 +69,32 @@ ContentSettingsType content_type, std::string resource_identifier) override; + // history::HistoryServiceObserver: + void OnURLsDeleted(history::HistoryService* history_service, + bool all_history, + bool expired, + const history::URLRows& deleted_rows, + const std::set<GURL>& favicon_urls) override; + + std::unique_ptr<base::DictionaryValue> GetSiteMetadata(const GURL& url) const; + void SetSiteMetadata(const GURL& url, + std::unique_ptr<base::DictionaryValue> dict); + + ScopedObserver<history::HistoryService, history::HistoryServiceObserver> + history_observer_; + HostContentSettingsMap* settings_map_; + // A clock is injected into this class so tests can set arbitrary timestamps + // in website settings. + std::unique_ptr<base::Clock> clock_; + + // Used internally so the class ignores changes to the settings that are not + // user initiated through the settings UI. + bool ignore_settings_changes_ = false; + + const bool should_use_smart_ui_ = false; + DISALLOW_COPY_AND_ASSIGN(SubresourceFilterContentSettingsManager); };
diff --git a/chrome/browser/subresource_filter/subresource_filter_content_settings_manager_unittest.cc b/chrome/browser/subresource_filter/subresource_filter_content_settings_manager_unittest.cc index e588e89..06fa25c9 100644 --- a/chrome/browser/subresource_filter/subresource_filter_content_settings_manager_unittest.cc +++ b/chrome/browser/subresource_filter/subresource_filter_content_settings_manager_unittest.cc
@@ -4,15 +4,29 @@ #include "chrome/browser/subresource_filter/subresource_filter_content_settings_manager.h" +#include <set> +#include <utility> + #include "base/macros.h" +#include "base/memory/ptr_util.h" +#include "base/run_loop.h" +#include "base/task/cancelable_task_tracker.h" #include "base/test/histogram_tester.h" +#include "base/test/simple_test_clock.h" +#include "base/time/time.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" +#include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/subresource_filter/chrome_subresource_filter_client.h" +#include "chrome/browser/subresource_filter/subresource_filter_profile_context.h" #include "chrome/browser/subresource_filter/subresource_filter_profile_context_factory.h" #include "chrome/test/base/testing_profile.h" #include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/content_settings/core/common/content_settings.h" +#include "components/history/core/browser/history_service.h" +#include "components/history/core/test/history_service_test_util.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" namespace { @@ -23,24 +37,71 @@ SubresourceFilterContentSettingsManagerTest() {} void SetUp() override { - SubresourceFilterProfileContextFactory::EnsureForProfile(&testing_profile_); + settings_manager_ = + SubresourceFilterProfileContextFactory::GetForProfile(&testing_profile_) + ->settings_manager(); + auto test_clock = base::MakeUnique<base::SimpleTestClock>(); + test_clock_ = test_clock.get(); + settings_manager_->set_clock_for_testing(std::move(test_clock)); histogram_tester().ExpectTotalCount(kActionsHistogram, 0); } HostContentSettingsMap* GetSettingsMap() { - return HostContentSettingsMapFactory::GetForProfile(&testing_profile_); + return HostContentSettingsMapFactory::GetForProfile(profile()); } const base::HistogramTester& histogram_tester() { return histogram_tester_; } + SubresourceFilterContentSettingsManager* settings_manager() { + return settings_manager_; + } + + TestingProfile* profile() { return &testing_profile_; } + + ContentSetting GetContentSettingMatchingUrlWithEmptyPath(const GURL& url) { + ContentSettingsForOneType host_settings; + GetSettingsMap()->GetSettingsForOneType( + ContentSettingsType::CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER, + std::string(), &host_settings); + GURL url_with_empty_path = url.GetWithEmptyPath(); + for (const auto& it : host_settings) { + // Need GURL conversion to get rid of unnecessary default ports. + if (GURL(it.primary_pattern.ToString()) == url_with_empty_path) + return it.setting; + } + return CONTENT_SETTING_DEFAULT; + } + + base::SimpleTestClock* test_clock() { return test_clock_; } + private: + base::ScopedTempDir scoped_dir_; + content::TestBrowserThreadBundle thread_bundle_; TestingProfile testing_profile_; base::HistogramTester histogram_tester_; + // Owned by the testing_profile_. + SubresourceFilterContentSettingsManager* settings_manager_ = nullptr; + + // Owned by the settings_manager_. + base::SimpleTestClock* test_clock_ = nullptr; + DISALLOW_COPY_AND_ASSIGN(SubresourceFilterContentSettingsManagerTest); }; +// It isn't very cheap to initialize the history service. Tests that need it can +// use this harness. +class SubresourceFilterContentSettingsManagerHistoryTest + : public SubresourceFilterContentSettingsManagerTest { + public: + void SetUp() override { + ASSERT_TRUE(profile()->CreateHistoryService(true /* delete_file */, + false /* no_db */)); + SubresourceFilterContentSettingsManagerTest::SetUp(); + } +}; + TEST_F(SubresourceFilterContentSettingsManagerTest, IrrelevantSetting) { GetSettingsMap()->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_POPUPS, CONTENT_SETTING_ALLOW); @@ -98,4 +159,163 @@ kActionContentSettingsWildcardUpdate, 2); } +TEST_F(SubresourceFilterContentSettingsManagerTest, SmartUI) { + if (!settings_manager()->should_use_smart_ui()) + return; + + GURL url("https://example.test/"); + GURL url2("https://example.test/path"); + EXPECT_TRUE(settings_manager()->ShouldShowUIForSite(url)); + EXPECT_TRUE(settings_manager()->ShouldShowUIForSite(url2)); + + EXPECT_EQ(CONTENT_SETTING_DEFAULT, + GetContentSettingMatchingUrlWithEmptyPath(url)); + settings_manager()->OnDidShowUI(url); + + // Subsequent same-origin navigations should not show UI. + EXPECT_FALSE(settings_manager()->ShouldShowUIForSite(url)); + EXPECT_FALSE(settings_manager()->ShouldShowUIForSite(url2)); + + // Showing the UI should trigger a forced content setting update, but no + // metrics should be recorded. + histogram_tester().ExpectBucketCount(kActionsHistogram, + kActionContentSettingsAllowed, 0); + + // Fast forward the clock. + test_clock()->Advance( + SubresourceFilterContentSettingsManager::kDelayBeforeShowingInfobarAgain); + EXPECT_TRUE(settings_manager()->ShouldShowUIForSite(url)); + EXPECT_TRUE(settings_manager()->ShouldShowUIForSite(url2)); +} + +// If the user manually sets a content setting to block the feature, the smart +// UI should be reset. +TEST_F(SubresourceFilterContentSettingsManagerTest, + SmartUIWithOverride_Resets) { + if (!settings_manager()->should_use_smart_ui()) + return; + + GURL url("https://example.test/"); + EXPECT_TRUE(settings_manager()->ShouldShowUIForSite(url)); + + settings_manager()->OnDidShowUI(url); + + // Subsequent navigations to same-domains should not show UI. + EXPECT_FALSE(settings_manager()->ShouldShowUIForSite(url)); + + // The user changed their mind, make sure the feature is showing up in the + // settings UI. i.e. the setting should be non-default. + EXPECT_EQ(CONTENT_SETTING_ALLOW, settings_manager()->GetSitePermission(url)); + GetSettingsMap()->SetContentSettingDefaultScope( + url, GURL(), CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER, std::string(), + CONTENT_SETTING_BLOCK); + + histogram_tester().ExpectBucketCount(kActionsHistogram, + kActionContentSettingsBlocked, 1); + histogram_tester().ExpectBucketCount(kActionsHistogram, + kActionContentSettingsBlockedFromUI, 0); + histogram_tester().ExpectBucketCount( + kActionsHistogram, kActionContentSettingsBlockedWhileUISuppressed, 1); + + // Smart UI should be reset. + EXPECT_TRUE(settings_manager()->ShouldShowUIForSite(url)); +} + +TEST_F(SubresourceFilterContentSettingsManagerTest, + DistinguishMetricsFromUIAndSettingsPage) { + GURL url("https://example.test/"); + EXPECT_TRUE(settings_manager()->ShouldShowUIForSite(url)); + + settings_manager()->OnDidShowUI(url); + histogram_tester().ExpectTotalCount(kActionsHistogram, 0); + + // Simulate changing the setting via the infobar UI. + settings_manager()->WhitelistSite(url); + histogram_tester().ExpectBucketCount(kActionsHistogram, + kActionContentSettingsBlockedFromUI, 1); + + // The standard "Block" histograms are only triggered when blocking from the + // settings UI, not our standard UI. + histogram_tester().ExpectBucketCount(kActionsHistogram, + kActionContentSettingsBlocked, 0); + histogram_tester().ExpectBucketCount( + kActionsHistogram, kActionContentSettingsBlockedWhileUISuppressed, 0); + + GURL url2("https://example.test2/"); + GetSettingsMap()->SetContentSettingDefaultScope( + url2, GURL(), CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER, std::string(), + CONTENT_SETTING_BLOCK); + histogram_tester().ExpectBucketCount(kActionsHistogram, + kActionContentSettingsBlocked, 1); + histogram_tester().ExpectBucketCount(kActionsHistogram, + kActionContentSettingsBlockedFromUI, 1); +} + +TEST_F(SubresourceFilterContentSettingsManagerHistoryTest, + HistoryUrlDeleted_ClearsWebsiteSetting) { + if (!settings_manager()->should_use_smart_ui()) + return; + + // Simulate a history already populated with a URL. + auto* history_service = HistoryServiceFactory::GetForProfile( + profile(), ServiceAccessType::EXPLICIT_ACCESS); + ASSERT_TRUE(history_service); + history_service->AddPage(GURL("https://already-browsed.com/"), + base::Time::Now(), history::SOURCE_BROWSED); + + // Ensure the website setting is set. + GURL url("https://example.test"); + EXPECT_TRUE(settings_manager()->ShouldShowUIForSite(url)); + settings_manager()->OnDidShowUI(url); + + // Simulate adding the page to the history. + history_service->AddPage(url, base::Time::Now(), history::SOURCE_BROWSED); + history::BlockUntilHistoryProcessesPendingRequests(history_service); + + EXPECT_FALSE(settings_manager()->ShouldShowUIForSite(url)); + + // Deleting the URL from history should clear the setting for this URL. Note + // that since there is another URL in the history this won't clear all items. + history_service->DeleteURL(url); + history::BlockUntilHistoryProcessesPendingRequests(history_service); + + EXPECT_TRUE(settings_manager()->ShouldShowUIForSite(url)); +} + +TEST_F(SubresourceFilterContentSettingsManagerHistoryTest, + AllHistoryUrlDeleted_ClearsWebsiteSetting) { + if (!settings_manager()->should_use_smart_ui()) + return; + + auto* history_service = HistoryServiceFactory::GetForProfile( + profile(), ServiceAccessType::EXPLICIT_ACCESS); + ASSERT_TRUE(history_service); + + GURL url1("https://example.test"); + GURL url2("https://example.test"); + EXPECT_TRUE(settings_manager()->ShouldShowUIForSite(url1)); + EXPECT_TRUE(settings_manager()->ShouldShowUIForSite(url2)); + settings_manager()->OnDidShowUI(url1); + settings_manager()->OnDidShowUI(url2); + + // Simulate adding the pages to the history. + history_service->AddPage(url1, base::Time::Now(), history::SOURCE_BROWSED); + history_service->AddPage(url2, base::Time::Now(), history::SOURCE_BROWSED); + history::BlockUntilHistoryProcessesPendingRequests(history_service); + + EXPECT_FALSE(settings_manager()->ShouldShowUIForSite(url1)); + EXPECT_FALSE(settings_manager()->ShouldShowUIForSite(url2)); + + // Deleting all the URLs should clear everything. + base::RunLoop run_loop; + base::CancelableTaskTracker task_tracker; + history_service->ExpireHistoryBetween(std::set<GURL>(), base::Time(), + base::Time(), run_loop.QuitClosure(), + &task_tracker); + run_loop.Run(); + + EXPECT_TRUE(settings_manager()->ShouldShowUIForSite(url1)); + EXPECT_TRUE(settings_manager()->ShouldShowUIForSite(url2)); +} + } // namespace
diff --git a/chrome/browser/subresource_filter/subresource_filter_profile_context.cc b/chrome/browser/subresource_filter/subresource_filter_profile_context.cc index b88de345..2978f24 100644 --- a/chrome/browser/subresource_filter/subresource_filter_profile_context.cc +++ b/chrome/browser/subresource_filter/subresource_filter_profile_context.cc
@@ -9,11 +9,11 @@ SubresourceFilterProfileContext::SubresourceFilterProfileContext( Profile* profile) - : content_settings_manager_( + : settings_manager_( base::MakeUnique<SubresourceFilterContentSettingsManager>(profile)) {} SubresourceFilterProfileContext::~SubresourceFilterProfileContext() {} void SubresourceFilterProfileContext::Shutdown() { - content_settings_manager_.reset(); + settings_manager_.reset(); }
diff --git a/chrome/browser/subresource_filter/subresource_filter_profile_context.h b/chrome/browser/subresource_filter/subresource_filter_profile_context.h index 582e041..572da530c 100644 --- a/chrome/browser/subresource_filter/subresource_filter_profile_context.h +++ b/chrome/browser/subresource_filter/subresource_filter_profile_context.h
@@ -19,12 +19,15 @@ explicit SubresourceFilterProfileContext(Profile* profile); ~SubresourceFilterProfileContext() override; + SubresourceFilterContentSettingsManager* settings_manager() { + return settings_manager_.get(); + } + private: // KeyedService: void Shutdown() override; - std::unique_ptr<SubresourceFilterContentSettingsManager> - content_settings_manager_; + std::unique_ptr<SubresourceFilterContentSettingsManager> settings_manager_; DISALLOW_COPY_AND_ASSIGN(SubresourceFilterProfileContext); };
diff --git a/chrome/browser/subresource_filter/subresource_filter_profile_context_factory.cc b/chrome/browser/subresource_filter/subresource_filter_profile_context_factory.cc index 1d0878d..f172958 100644 --- a/chrome/browser/subresource_filter/subresource_filter_profile_context_factory.cc +++ b/chrome/browser/subresource_filter/subresource_filter_profile_context_factory.cc
@@ -5,15 +5,17 @@ #include "chrome/browser/subresource_filter/subresource_filter_profile_context_factory.h" #include "base/memory/singleton.h" +#include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/subresource_filter/subresource_filter_profile_context.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/keyed_service/core/keyed_service.h" // static -void SubresourceFilterProfileContextFactory::EnsureForProfile( - Profile* profile) { - GetInstance()->GetServiceForBrowserContext(profile, true /* create */); +SubresourceFilterProfileContext* +SubresourceFilterProfileContextFactory::GetForProfile(Profile* profile) { + return static_cast<SubresourceFilterProfileContext*>( + GetInstance()->GetServiceForBrowserContext(profile, true /* create */)); } // static @@ -31,3 +33,9 @@ content::BrowserContext* profile) const { return new SubresourceFilterProfileContext(static_cast<Profile*>(profile)); } + +content::BrowserContext* +SubresourceFilterProfileContextFactory::GetBrowserContextToUse( + content::BrowserContext* context) const { + return chrome::GetBrowserContextOwnInstanceInIncognito(context); +}
diff --git a/chrome/browser/subresource_filter/subresource_filter_profile_context_factory.h b/chrome/browser/subresource_filter/subresource_filter_profile_context_factory.h index 292259c0..1392563 100644 --- a/chrome/browser/subresource_filter/subresource_filter_profile_context_factory.h +++ b/chrome/browser/subresource_filter/subresource_filter_profile_context_factory.h
@@ -10,13 +10,14 @@ class KeyedService; class Profile; +class SubresourceFilterProfileContext; // This class is responsible for instantiating a profile-scoped context for // subresource filtering. class SubresourceFilterProfileContextFactory : public BrowserContextKeyedServiceFactory { public: - static void EnsureForProfile(Profile* profile); + static SubresourceFilterProfileContext* GetForProfile(Profile* profile); static SubresourceFilterProfileContextFactory* GetInstance(); @@ -26,6 +27,9 @@ KeyedService* BuildServiceInstanceFor( content::BrowserContext* profile) const override; + content::BrowserContext* GetBrowserContextToUse( + content::BrowserContext* context) const override; + DISALLOW_COPY_AND_ASSIGN(SubresourceFilterProfileContextFactory); };
diff --git a/chrome/browser/ui/aura/accessibility/ax_root_obj_wrapper.cc b/chrome/browser/ui/aura/accessibility/ax_root_obj_wrapper.cc index a512660..1d5acd8 100644 --- a/chrome/browser/ui/aura/accessibility/ax_root_obj_wrapper.cc +++ b/chrome/browser/ui/aura/accessibility/ax_root_obj_wrapper.cc
@@ -54,7 +54,6 @@ void AXRootObjWrapper::Serialize(ui::AXNodeData* out_node_data) { out_node_data->id = id_; out_node_data->role = ui::AX_ROLE_DESKTOP; - out_node_data->state = 0; out_node_data->AddStringAttribute(ui::AX_ATTR_CHROME_CHANNEL, chrome::GetChannelString()); }
diff --git a/chrome/browser/ui/cocoa/browser_window_controller_private.h b/chrome/browser/ui/cocoa/browser_window_controller_private.h index 483c4ea1..698945e 100644 --- a/chrome/browser/ui/cocoa/browser_window_controller_private.h +++ b/chrome/browser/ui/cocoa/browser_window_controller_private.h
@@ -93,8 +93,8 @@ // Update visibility of the infobar tip, depending on the state of the window. - (void)updateInfoBarTipVisibility; -// The min Y of the bubble point in the coordinate space of the toolbar. -- (NSInteger)pageInfoBubblePointY; +// The distance from the toolbar bottom to the anchor point for InfoBars. +- (NSInteger)infoBarAnchorPointY; // Toggles the AppKit Fullscreen API. By default, doing so enters Canonical // Fullscreen.
diff --git a/chrome/browser/ui/cocoa/browser_window_controller_private.mm b/chrome/browser/ui/cocoa/browser_window_controller_private.mm index 5883198..6749daca 100644 --- a/chrome/browser/ui/cocoa/browser_window_controller_private.mm +++ b/chrome/browser/ui/cocoa/browser_window_controller_private.mm
@@ -813,11 +813,11 @@ setShouldSuppressTopInfoBarTip:![self hasToolbar]]; } -- (NSInteger)pageInfoBubblePointY { +- (NSInteger)infoBarAnchorPointY { LocationBarViewMac* locationBarView = [self locationBarBridge]; // The point, in window coordinates. - NSPoint iconBottom = locationBarView->GetPageInfoBubblePoint(); + NSPoint iconBottom = locationBarView->GetInfoBarAnchorPoint(); // The toolbar, in window coordinates. NSView* toolbar = [toolbarController_ view]; @@ -899,7 +899,7 @@ NSHeight([[bookmarkBarController_ view] bounds])]; [layout setInfoBarHeight:[infoBarContainerController_ heightOfInfoBars]]; - [layout setPageInfoBubblePointY:[self pageInfoBubblePointY]]; + [layout setInfoBarAnchorPointY:[self infoBarAnchorPointY]]; [layout setHasDownloadShelf:(downloadShelfController_.get() != nil)]; [layout setDownloadShelfHeight: @@ -923,7 +923,7 @@ [infoBarContainerController_ setMaxTopArrowHeight:output.infoBarMaxTopArrowHeight]; [infoBarContainerController_ - setInfobarArrowX:[self locationBarBridge]->GetPageInfoBubblePoint().x]; + setInfobarArrowX:[self locationBarBridge]->GetInfoBarAnchorPoint().x]; [[downloadShelfController_ view] setFrame:output.downloadShelfFrame];
diff --git a/chrome/browser/ui/cocoa/browser_window_layout.h b/chrome/browser/ui/cocoa/browser_window_layout.h index 6c96ccbf..9444c17 100644 --- a/chrome/browser/ui/cocoa/browser_window_layout.h +++ b/chrome/browser/ui/cocoa/browser_window_layout.h
@@ -72,7 +72,7 @@ // The distance from the bottom of the location icon to the bottom of the // toolbar. Only needs to be set if infoBarHeight is not 0 and hasToolbar is // YES. - CGFloat pageInfoBubblePointY; + CGFloat infoBarAnchorPointY; BOOL hasDownloadShelf; CGFloat downloadShelfHeight; @@ -172,8 +172,8 @@ // The height of the info bar, not including the top arrow. - (void)setInfoBarHeight:(CGFloat)infoBarHeight; -// The min Y of the bubble point, relative to the toolbar. -- (void)setPageInfoBubblePointY:(CGFloat)pageInfoBubblePointY; +// The min Y of the infobar anchor point, relative to the toolbar. +- (void)setInfoBarAnchorPointY:(CGFloat)infoBarAnchorPointY; - (void)setHasDownloadShelf:(BOOL)hasDownloadShelf; - (void)setDownloadShelfHeight:(CGFloat)downloadShelfHeight;
diff --git a/chrome/browser/ui/cocoa/browser_window_layout.mm b/chrome/browser/ui/cocoa/browser_window_layout.mm index 9581932..dbee384 100644 --- a/chrome/browser/ui/cocoa/browser_window_layout.mm +++ b/chrome/browser/ui/cocoa/browser_window_layout.mm
@@ -168,8 +168,8 @@ parameters_.infoBarHeight = infoBarHeight; } -- (void)setPageInfoBubblePointY:(CGFloat)pageInfoBubblePointY { - parameters_.pageInfoBubblePointY = pageInfoBubblePointY; +- (void)setInfoBarAnchorPointY:(CGFloat)infoBarAnchorPointY { + parameters_.infoBarAnchorPointY = infoBarAnchorPointY; } - (void)setHasDownloadShelf:(BOOL)hasDownloadShelf { @@ -343,7 +343,7 @@ // info bubble icon. if (parameters_.hasToolbar) { infoBarMaxY = - NSMinY(output_.toolbarFrame) + parameters.pageInfoBubblePointY; + NSMinY(output_.toolbarFrame) + parameters.infoBarAnchorPointY; } output_.infoBarFrame =
diff --git a/chrome/browser/ui/cocoa/browser_window_layout_unittest.mm b/chrome/browser/ui/cocoa/browser_window_layout_unittest.mm index 00e6481..d3395f81 100644 --- a/chrome/browser/ui/cocoa/browser_window_layout_unittest.mm +++ b/chrome/browser/ui/cocoa/browser_window_layout_unittest.mm
@@ -31,7 +31,7 @@ [layout setBookmarkBarHidden:NO]; [layout setBookmarkBarHeight:26]; [layout setInfoBarHeight:72]; - [layout setPageInfoBubblePointY:13]; + [layout setInfoBarAnchorPointY:13]; [layout setHasDownloadShelf:YES]; [layout setDownloadShelfHeight:44]; [layout setOSYosemiteOrLater:NO];
diff --git a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.h b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.h index 300bc90..b4e0a74 100644 --- a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.h +++ b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.h
@@ -166,9 +166,13 @@ // via -[NSView addToolTipRect:owner:userData:]. - (void)addToolTip:(NSString*)tooltip forRect:(NSRect)aRect; -// Obtain the bubble anchor point for |decoration|. In window coordinates. +// Obtain the bubble anchor point for |decoration| in window coordinates. - (NSPoint)bubblePointForDecoration:(LocationBarDecoration*)decoration; +// Returns the anchor point for arrows pointing to |decoration| in window +// coordinates. +- (NSPoint)arrowAnchorPointForDecoration:(LocationBarDecoration*)decoration; + @end #endif // CHROME_BROWSER_UI_COCOA_LOCATION_BAR_AUTOCOMPLETE_TEXT_FIELD_H_
diff --git a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.mm b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.mm index 13549db..00a78454 100644 --- a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.mm +++ b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.mm
@@ -288,23 +288,25 @@ } - (NSPoint)bubblePointForDecoration:(LocationBarDecoration*)decoration { - NSPoint point; - if (ui::MaterialDesignController::IsSecondaryUiMaterial()) { - // Under MD, dialogs have no arrow and anchor to corner of the decoration - // frame, not a specific point within it. See http://crbug.com/566115. - BOOL isLeftDecoration; - const NSRect frame = - [[self cell] backgroundFrameForDecoration:decoration - inFrame:[self bounds] - isLeftDecoration:&isLeftDecoration]; - point.y = NSMaxY(frame); - point.x = isLeftDecoration ? NSMinX(frame) : NSMaxX(frame); - } else { - const NSRect frame = - [[self cell] frameForDecoration:decoration inFrame:[self bounds]]; - point = decoration->GetBubblePointInFrame(frame); - } + if (!ui::MaterialDesignController::IsSecondaryUiMaterial()) + return [self arrowAnchorPointForDecoration:decoration]; + // Under MD, dialogs have no arrow and anchor to corner of the decoration + // frame, not a specific point within it. See http://crbug.com/566115. + BOOL isLeftDecoration; + const NSRect frame = + [[self cell] backgroundFrameForDecoration:decoration + inFrame:[self bounds] + isLeftDecoration:&isLeftDecoration]; + NSPoint point = NSMakePoint(isLeftDecoration ? NSMinX(frame) : NSMaxX(frame), + NSMaxY(frame)); + return [self convertPoint:point toView:nil]; +} + +- (NSPoint)arrowAnchorPointForDecoration:(LocationBarDecoration*)decoration { + const NSRect frame = + [[self cell] frameForDecoration:decoration inFrame:[self bounds]]; + NSPoint point = decoration->GetBubblePointInFrame(frame); return [self convertPoint:point toView:nil]; }
diff --git a/chrome/browser/ui/cocoa/location_bar/location_bar_decoration.mm b/chrome/browser/ui/cocoa/location_bar/location_bar_decoration.mm index 7e710115..9d99e217 100644 --- a/chrome/browser/ui/cocoa/location_bar/location_bar_decoration.mm +++ b/chrome/browser/ui/cocoa/location_bar/location_bar_decoration.mm
@@ -144,7 +144,7 @@ @end const CGFloat LocationBarDecoration::kOmittedWidth = 0.0; -const SkColor LocationBarDecoration::kMaterialDarkModeTextColor = 0xCCFFFFFF; +const SkColor LocationBarDecoration::kMaterialDarkModeTextColor = SK_ColorWHITE; LocationBarDecoration::LocationBarDecoration() { accessibility_view_.reset(
diff --git a/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h b/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h index 5bfd53c7..ab747156 100644 --- a/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h +++ b/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h
@@ -108,10 +108,13 @@ // save credit card bubble to aim at. NSPoint GetSaveCreditCardBubblePoint() const; - // Get the point in window coordinates in the security icon at which the page - // info bubble aims. + // Get the point in window coordinates for the page info bubble anchor. NSPoint GetPageInfoBubblePoint() const; + // Get the point in window coordinates in the security icon at which infobar + // arrows should point. + NSPoint GetInfoBarAnchorPoint() const; + // When any image decorations change, call this to ensure everything is // redrawn and laid out if necessary. void OnDecorationsChanged();
diff --git a/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm b/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm index 474a524..9416253c 100644 --- a/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm +++ b/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm
@@ -330,6 +330,10 @@ return [field_ bubblePointForDecoration:GetPageInfoDecoration()]; } +NSPoint LocationBarViewMac::GetInfoBarAnchorPoint() const { + return [field_ arrowAnchorPointForDecoration:GetPageInfoDecoration()]; +} + void LocationBarViewMac::OnDecorationsChanged() { // TODO(shess): The field-editor frame and cursor rects should not // change, here.
diff --git a/chrome/browser/ui/startup/startup_tab_provider.cc b/chrome/browser/ui/startup/startup_tab_provider.cc index f8a25f3..83ace6e 100644 --- a/chrome/browser/ui/startup/startup_tab_provider.cc +++ b/chrome/browser/ui/startup/startup_tab_provider.cc
@@ -171,10 +171,12 @@ if (set_default_browser_allowed && !has_seen_win10_promo && !is_default_browser) { tabs.emplace_back(GetWin10WelcomePageUrl(!is_first_run), false); - } else if (!has_seen_welcome_page && is_signin_allowed && !is_signed_in) { - tabs.emplace_back(GetWelcomePageUrl(!is_first_run), false); + return tabs; } - return tabs; + + return GetStandardOnboardingTabsForState(is_first_run, has_seen_welcome_page, + is_signin_allowed, is_signed_in, + is_supervised_user); } #endif @@ -245,8 +247,6 @@ // static GURL StartupTabProviderImpl::GetWelcomePageUrl(bool use_later_run_variant) { - // Record that the Welcome page was added to the startup url list. - UMA_HISTOGRAM_BOOLEAN("Welcome.Win10.NewPromoPageAdded", true); GURL url(chrome::kChromeUIWelcomeURL); return use_later_run_variant ? net::AppendQueryParameter(url, "variant", "everywhere") @@ -257,6 +257,8 @@ // static GURL StartupTabProviderImpl::GetWin10WelcomePageUrl( bool use_later_run_variant) { + // Record that the Welcome page was added to the startup url list. + UMA_HISTOGRAM_BOOLEAN("Welcome.Win10.NewPromoPageAdded", true); GURL url(chrome::kChromeUIWelcomeWin10URL); return use_later_run_variant ? net::AppendQueryParameter(url, "text", "faster")
diff --git a/chrome/browser/ui/views/download/download_item_view.cc b/chrome/browser/ui/views/download/download_item_view.cc index 39701e2..ac6bae1 100644 --- a/chrome/browser/ui/views/download/download_item_view.cc +++ b/chrome/browser/ui/views/download/download_item_view.cc
@@ -488,9 +488,9 @@ node_data->SetName(accessible_name_); node_data->role = ui::AX_ROLE_BUTTON; if (model_.IsDangerous()) - node_data->AddStateFlag(ui::AX_STATE_DISABLED); + node_data->AddState(ui::AX_STATE_DISABLED); else - node_data->AddStateFlag(ui::AX_STATE_HASPOPUP); + node_data->AddState(ui::AX_STATE_HASPOPUP); } void DownloadItemView::OnThemeChanged() {
diff --git a/chrome/browser/ui/views/omnibox/omnibox_view_views.cc b/chrome/browser/ui/views/omnibox/omnibox_view_views.cc index 09ffc9e0..6add5dd 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_view_views.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_view_views.cc
@@ -723,9 +723,9 @@ node_data->AddIntAttribute(ui::AX_ATTR_TEXT_SEL_END, entry_end); if (popup_window_mode_) { - node_data->AddStateFlag(ui::AX_STATE_READ_ONLY); + node_data->AddState(ui::AX_STATE_READ_ONLY); } else { - node_data->AddStateFlag(ui::AX_STATE_EDITABLE); + node_data->AddState(ui::AX_STATE_EDITABLE); } }
diff --git a/chrome/browser/ui/views/page_info/non_accessible_image_view.cc b/chrome/browser/ui/views/page_info/non_accessible_image_view.cc index eca9f37..2a02fbff 100644 --- a/chrome/browser/ui/views/page_info/non_accessible_image_view.cc +++ b/chrome/browser/ui/views/page_info/non_accessible_image_view.cc
@@ -8,5 +8,5 @@ #include "ui/accessibility/ax_node_data.h" void NonAccessibleImageView::GetAccessibleNodeData(ui::AXNodeData* node_data) { - node_data->AddStateFlag(ui::AX_STATE_INVISIBLE); + node_data->AddState(ui::AX_STATE_INVISIBLE); }
diff --git a/chrome/browser/ui/views/tabs/tab.cc b/chrome/browser/ui/views/tabs/tab.cc index 901375a..9473bf31 100644 --- a/chrome/browser/ui/views/tabs/tab.cc +++ b/chrome/browser/ui/views/tabs/tab.cc
@@ -991,11 +991,11 @@ void Tab::GetAccessibleNodeData(ui::AXNodeData* node_data) { node_data->role = ui::AX_ROLE_TAB; node_data->SetName(controller_->GetAccessibleTabName(this)); - node_data->AddStateFlag(ui::AX_STATE_MULTISELECTABLE); - node_data->AddStateFlag(ui::AX_STATE_SELECTABLE); + node_data->AddState(ui::AX_STATE_MULTISELECTABLE); + node_data->AddState(ui::AX_STATE_SELECTABLE); controller_->UpdateTabAccessibilityState(this, node_data); if (IsSelected()) - node_data->AddStateFlag(ui::AX_STATE_SELECTED); + node_data->AddState(ui::AX_STATE_SELECTED); } ////////////////////////////////////////////////////////////////////////////////
diff --git a/chrome/browser/ui/views/toolbar/toolbar_actions_bar_bubble_views_unittest.cc b/chrome/browser/ui/views/toolbar/toolbar_actions_bar_bubble_views_unittest.cc index 5c4178f19..8517dca 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_actions_bar_bubble_views_unittest.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_actions_bar_bubble_views_unittest.cc
@@ -62,6 +62,7 @@ CreateParams(views::Widget::InitParams::TYPE_WINDOW); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; anchor_widget->Init(params); + anchor_widget->Show(); return anchor_widget; }
diff --git a/chrome/browser/ui/views/toolbar/toolbar_button.cc b/chrome/browser/ui/views/toolbar/toolbar_button.cc index 359d821..83bf10e 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_button.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_button.cc
@@ -130,7 +130,7 @@ void ToolbarButton::GetAccessibleNodeData(ui::AXNodeData* node_data) { CustomButton::GetAccessibleNodeData(node_data); node_data->role = ui::AX_ROLE_BUTTON_DROP_DOWN; - node_data->AddStateFlag(ui::AX_STATE_HASPOPUP); + node_data->AddState(ui::AX_STATE_HASPOPUP); if (enabled()) { node_data->AddIntAttribute(ui::AX_ATTR_ACTION, ui::AX_SUPPORTED_ACTION_PRESS);
diff --git a/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc b/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc index 668be6c..b254777 100644 --- a/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc
@@ -485,7 +485,7 @@ if (login_display_host) login_display_host->SetStatusAreaVisible(true); if (ScreenLocker::default_screen_locker()) - ScreenLocker::default_screen_locker()->web_ui()->OnHeaderBarVisible(); + ScreenLocker::default_screen_locker()->delegate()->OnHeaderBarVisible(); } void CoreOobeHandler::HandleRaiseTabKeyEvent(bool reverse) {
diff --git a/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc index 52dbf79..8367856 100644 --- a/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc
@@ -1343,7 +1343,7 @@ void SigninScreenHandler::HandleWallpaperReady() { if (ScreenLocker::default_screen_locker()) { ScreenLocker::default_screen_locker() - ->web_ui() + ->delegate() ->OnLockBackgroundDisplayed(); } }
diff --git a/chrome/installer/linux/common/installer.include b/chrome/installer/linux/common/installer.include index d9aaa97..1d31a12 100644 --- a/chrome/installer/linux/common/installer.include +++ b/chrome/installer/linux/common/installer.include
@@ -169,6 +169,13 @@ install -m 644 "${BUILDDIR}/libEGL.so" "${STAGEDIR}/${INSTALLDIR}/" fi + # SwiftShader + if [ -f "${BUILDDIR}/swiftshader/libEGL.so" ]; then + install -m 755 -d "${STAGEDIR}/${INSTALLDIR}/swiftshader/" + install -m 644 "${BUILDDIR}/swiftshader/libEGL.so" "${STAGEDIR}/${INSTALLDIR}/swiftshader/" + install -m 644 "${BUILDDIR}/swiftshader/libGLESv2.so" "${STAGEDIR}/${INSTALLDIR}/swiftshader/" + fi + # libc++ if [ -f "${BUILDDIR}/lib/libc++.so" ]; then install -m 755 -d "${STAGEDIR}/${INSTALLDIR}/lib/"
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index cc1bd501..82a31d18 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -4140,6 +4140,7 @@ # TODO(sgurun): enable tests for safe_browsing==2. sources += [ "../browser/safe_browsing/browser_feature_extractor_unittest.cc", + "../browser/safe_browsing/chrome_password_protection_service_unittest.cc", "../browser/safe_browsing/chunk_range_unittest.cc", "../browser/safe_browsing/client_side_detection_host_unittest.cc", "../browser/safe_browsing/client_side_detection_service_unittest.cc",
diff --git a/chrome/test/chromedriver/test/run_py_tests.py b/chrome/test/chromedriver/test/run_py_tests.py index 618af26..e4b8ad4 100755 --- a/chrome/test/chromedriver/test/run_py_tests.py +++ b/chrome/test/chromedriver/test/run_py_tests.py
@@ -73,6 +73,8 @@ _VERSION_SPECIFIC_FILTER = {} _VERSION_SPECIFIC_FILTER['HEAD'] = [ + # https://bugs.chromium.org/p/chromedriver/issues/detail?id=1803 + 'ChromeDriverTest.testAlertHandlingOnPageUnload', ] _VERSION_SPECIFIC_FILTER['58'] = [ # https://bugs.chromium.org/p/chromedriver/issues/detail?id=1673
diff --git a/chromecast/media/cdm/cast_cdm.cc b/chromecast/media/cdm/cast_cdm.cc index 78ce567..e0b02821 100644 --- a/chromecast/media/cdm/cast_cdm.cc +++ b/chromecast/media/cdm/cast_cdm.cc
@@ -111,10 +111,9 @@ return cast_cdm_context_.get(); } -void CastCdm::OnSessionMessage( - const std::string& session_id, - const std::vector<uint8_t>& message, - ::media::ContentDecryptionModule::MessageType message_type) { +void CastCdm::OnSessionMessage(const std::string& session_id, + const std::vector<uint8_t>& message, + ::media::CdmMessageType message_type) { session_message_cb_.Run(session_id, message_type, message); }
diff --git a/chromecast/media/cdm/cast_cdm.h b/chromecast/media/cdm/cast_cdm.h index 004cd63..321f33f 100644 --- a/chromecast/media/cdm/cast_cdm.h +++ b/chromecast/media/cdm/cast_cdm.h
@@ -75,10 +75,9 @@ protected: ~CastCdm() override; - void OnSessionMessage( - const std::string& session_id, - const std::vector<uint8_t>& message, - ::media::ContentDecryptionModule::MessageType message_type); + void OnSessionMessage(const std::string& session_id, + const std::vector<uint8_t>& message, + ::media::CdmMessageType message_type); void OnSessionClosed(const std::string& session_id); void OnSessionKeysChange(const std::string& session_id, bool newly_usable_keys,
diff --git a/components/content_settings/core/browser/website_settings_registry.cc b/components/content_settings/core/browser/website_settings_registry.cc index 1cfb544..e019486 100644 --- a/components/content_settings/core/browser/website_settings_registry.cc +++ b/components/content_settings/core/browser/website_settings_registry.cc
@@ -165,6 +165,11 @@ WebsiteSettingsInfo::UNSYNCABLE, WebsiteSettingsInfo::NOT_LOSSY, WebsiteSettingsInfo::REQUESTING_ORIGIN_ONLY_SCOPE, DESKTOP | PLATFORM_ANDROID, WebsiteSettingsInfo::INHERIT_IN_INCOGNITO); + Register(CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER_DATA, + "subresource-filter-data", nullptr, WebsiteSettingsInfo::UNSYNCABLE, + WebsiteSettingsInfo::LOSSY, + WebsiteSettingsInfo::REQUESTING_ORIGIN_ONLY_SCOPE, PLATFORM_ANDROID, + WebsiteSettingsInfo::INHERIT_IN_INCOGNITO); } } // namespace content_settings
diff --git a/components/content_settings/core/common/content_settings.cc b/components/content_settings/core/common/content_settings.cc index 59fc9c6..4cf2d13 100644 --- a/components/content_settings/core/common/content_settings.cc +++ b/components/content_settings/core/common/content_settings.cc
@@ -56,6 +56,7 @@ {CONTENT_SETTINGS_TYPE_IMPORTANT_SITE_INFO, 30}, {CONTENT_SETTINGS_TYPE_PERMISSION_AUTOBLOCKER_DATA, 31}, {CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER, 32}, + {CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER_DATA, 33}, }; int ContentSettingTypeToHistogramValue(ContentSettingsType content_setting,
diff --git a/components/content_settings/core/common/content_settings_types.h b/components/content_settings/core/common/content_settings_types.h index d7584141..3c31cde2e 100644 --- a/components/content_settings/core/common/content_settings_types.h +++ b/components/content_settings/core/common/content_settings_types.h
@@ -50,6 +50,11 @@ CONTENT_SETTINGS_TYPE_PERMISSION_AUTOBLOCKER_DATA, CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER, + // Website setting which stores metadata for the subresource filter to aid in + // decisions for whether or not to show the UI. Currently only used on + // Android. + CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER_DATA, + // This is special-cased in the permissions layer to always allow, and as // such doesn't have associated prefs data. CONTENT_SETTINGS_TYPE_MIDI,
diff --git a/components/offline_pages/core/background/request_coordinator.cc b/components/offline_pages/core/background/request_coordinator.cc index 78cbccf..87e3c97 100644 --- a/components/offline_pages/core/background/request_coordinator.cc +++ b/components/offline_pages/core/background/request_coordinator.cc
@@ -302,8 +302,8 @@ callback.Run(std::move(requests)); } -void RequestCoordinator::StopPrerendering(const CancelCallback& final_callback, - Offliner::RequestStatus stop_status) { +void RequestCoordinator::StopOfflining(const CancelCallback& final_callback, + Offliner::RequestStatus stop_status) { if (offliner_ && state_ == RequestCoordinatorState::OFFLINING) { DCHECK_NE(active_request_id_, 0); if (offliner_->Cancel(base::Bind( @@ -340,15 +340,13 @@ bool RequestCoordinator::CancelActiveRequestIfItMatches( const std::vector<int64_t>& request_ids) { // If we have a request in progress and need to cancel it, call the - // pre-renderer to cancel. TODO Make sure we remove any page created by the - // prerenderer if it doesn't get the cancel in time. + // offliner to cancel. if (active_request_id_ != 0) { if (request_ids.end() != std::find(request_ids.begin(), request_ids.end(), active_request_id_)) { - StopPrerendering( - base::Bind(&RequestCoordinator::ResetActiveRequestCallback, - weak_ptr_factory_.GetWeakPtr()), - Offliner::RequestStatus::REQUEST_COORDINATOR_CANCELED); + StopOfflining(base::Bind(&RequestCoordinator::ResetActiveRequestCallback, + weak_ptr_factory_.GetWeakPtr()), + Offliner::RequestStatus::REQUEST_COORDINATOR_CANCELED); return true; } } @@ -588,9 +586,9 @@ void RequestCoordinator::StopProcessing(Offliner::RequestStatus stop_status) { processing_state_ = ProcessingWindowState::STOPPED; - StopPrerendering(base::Bind(&RequestCoordinator::StartSchedulerCallback, - weak_ptr_factory_.GetWeakPtr()), - stop_status); + StopOfflining(base::Bind(&RequestCoordinator::StartSchedulerCallback, + weak_ptr_factory_.GetWeakPtr()), + stop_status); } void RequestCoordinator::HandleWatchdogTimeout() { @@ -598,9 +596,9 @@ Offliner::REQUEST_COORDINATOR_TIMED_OUT; if (offliner_->HandleTimeout(active_request_id_)) return; - StopPrerendering(base::Bind(&RequestCoordinator::TryNextRequestCallback, - weak_ptr_factory_.GetWeakPtr()), - watchdog_status); + StopOfflining(base::Bind(&RequestCoordinator::TryNextRequestCallback, + weak_ptr_factory_.GetWeakPtr()), + watchdog_status); } // Returns true if the caller should expect a callback, false otherwise. For @@ -917,7 +915,7 @@ // Inform observer of active request. NotifyChanged(update_result->updated_items.at(0)); - // Start a watchdog timer to catch pre-renders running too long + // Start a watchdog timer to catch offliners running too long watchdog_timer_.Start(FROM_HERE, timeout, this, &RequestCoordinator::HandleWatchdogTimeout); } else {
diff --git a/components/offline_pages/core/background/request_coordinator.h b/components/offline_pages/core/background/request_coordinator.h index 2214906..05a1bace 100644 --- a/components/offline_pages/core/background/request_coordinator.h +++ b/components/offline_pages/core/background/request_coordinator.h
@@ -115,7 +115,7 @@ int64_t SavePageLater(const SavePageLaterParams& save_page_later_params); // Remove a list of requests by |request_id|. This removes requests from the - // request queue, and cancels an in-progress prerender. + // request queue, and cancels an in-progress offliner. void RemoveRequests(const std::vector<int64_t>& request_ids, const RemoveRequestsCallback& callback); @@ -338,9 +338,9 @@ void HandleWatchdogTimeout(); - // Cancels an in progress pre-rendering, and updates state appropriately. - void StopPrerendering(const CancelCallback& callback, - Offliner::RequestStatus stop_status); + // Cancels an in progress offlining, and updates state appropriately. + void StopOfflining(const CancelCallback& callback, + Offliner::RequestStatus stop_status); // Marks attempt on the request and sends it to offliner in continuation. void SendRequestToOffliner(const SavePageRequest& request);
diff --git a/components/offline_pages/core/background/request_coordinator_unittest.cc b/components/offline_pages/core/background/request_coordinator_unittest.cc index 8bdbba1..d756501 100644 --- a/components/offline_pages/core/background/request_coordinator_unittest.cc +++ b/components/offline_pages/core/background/request_coordinator_unittest.cc
@@ -848,7 +848,7 @@ EXPECT_EQ(0L, last_requests().at(0)->completed_attempt_count()); } -TEST_F(RequestCoordinatorTest, OfflinerDonePrerenderingCancel) { +TEST_F(RequestCoordinatorTest, OfflinerDoneOffliningCancel) { // Add a request to the queue, wait for callbacks to finish. offline_pages::SavePageRequest request(kRequestId1, kUrl1, kClientId1, base::Time::Now(), kUserRequested); @@ -867,7 +867,7 @@ // Request still in the queue. EXPECT_EQ(1UL, last_requests().size()); - // Verify prerendering cancel not counted as an attempt after all. + // Verify offlining cancel not counted as an attempt after all. const std::unique_ptr<SavePageRequest>& found_request = last_requests().front(); EXPECT_EQ(0L, found_request->completed_attempt_count());
diff --git a/components/omnibox/browser/url_index_private_data.cc b/components/omnibox/browser/url_index_private_data.cc index b9f2a93..663ee8a 100644 --- a/components/omnibox/browser/url_index_private_data.cc +++ b/components/omnibox/browser/url_index_private_data.cc
@@ -10,6 +10,7 @@ #include <iterator> #include <limits> #include <numeric> +#include <set> #include <string> #include <vector> @@ -155,7 +156,10 @@ (cursor_position < original_search_string.length()) && (cursor_position > 0)) { // The original search_string broken at cursor position. This is one type of - // transformation. + // transformation. It's possible this transformation doesn't actually + // break any words. There's no harm in adding the transformation in this + // case because the searching code below prevents running duplicate + // searches. base::string16 transformed_search_string(original_search_string); transformed_search_string.insert(cursor_position, base::ASCIIToUTF16(" ")); search_strings.push_back(transformed_search_string); @@ -173,6 +177,9 @@ ResetSearchTermCache(); bool history_ids_were_trimmed = false; + // A set containing the list of words extracted from each search string, + // used to prevent running duplicate searches. + std::set<String16Vector> search_string_words; for (const base::string16& search_string : search_strings) { // The search string we receive may contain escaped characters. For reducing // the index we need individual, lower-cased words, ignoring escapings. For @@ -192,6 +199,10 @@ String16VectorFromString16(lower_unescaped_string, false, nullptr)); if (lower_words.empty()) continue; + // If we've already searched for this list of words, don't do it again. + if (search_string_words.find(lower_words) != search_string_words.end()) + continue; + search_string_words.insert(lower_words); HistoryIDVector history_ids = HistoryIDsFromWords(lower_words); history_ids_were_trimmed |= TrimHistoryIdsPool(&history_ids);
diff --git a/components/pdf/renderer/pdf_accessibility_tree.cc b/components/pdf/renderer/pdf_accessibility_tree.cc index d4c2257..4512380 100644 --- a/components/pdf/renderer/pdf_accessibility_tree.cc +++ b/components/pdf/renderer/pdf_accessibility_tree.cc
@@ -275,7 +275,7 @@ ui::AXNodeData* node = new ui::AXNodeData(); node->id = render_accessibility->GenerateAXID(); node->role = role; - node->state = 1 << ui::AX_STATE_READ_ONLY; + node->AddState(ui::AX_STATE_READ_ONLY); // All nodes other than the first one have coordinates relative to // the first node.
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index 7c18de1e..73a0643 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -9526,7 +9526,7 @@ 'schema': { 'type': 'boolean' }, 'supported_on': ['chrome_os:60-'], 'features': { - 'dynamic_refresh': False, + 'dynamic_refresh': True, 'per_profile': True, }, 'example_value': True,
diff --git a/components/safe_browsing/csd.proto b/components/safe_browsing/csd.proto index a69cd10..689c877a 100644 --- a/components/safe_browsing/csd.proto +++ b/components/safe_browsing/csd.proto
@@ -34,6 +34,14 @@ EXTENDED_REPORTING = 2; } optional UserPopulation user_population = 1; + + // If user enabled history sync. + optional bool is_history_sync_enabled = 2; + + // The finch active groups this user belongs to (if any). Active group is + // defined by finch trial name and group name. Trial name and group name are + // concatenated with separator "|", e.g. "PingOnlyTrial|DefaultGroup". + repeated string finch_active_groups = 4; } message ClientPhishingRequest { @@ -214,6 +222,9 @@ // The number of verdicts stored on the client. optional int32 stored_verdict_cnt = 5; + + // Chrome user population. + optional ChromeUserPopulation population = 6; } // The message is used for client response for login reputation requests.
diff --git a/components/safe_browsing/password_protection/password_protection_request.cc b/components/safe_browsing/password_protection/password_protection_request.cc index 2827ed46..4a1f36f3 100644 --- a/components/safe_browsing/password_protection/password_protection_request.cc +++ b/components/safe_browsing/password_protection/password_protection_request.cc
@@ -41,17 +41,6 @@ void PasswordProtectionRequest::Start() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - // Initially we only send ping for Safe Browsing Extended Reporting users when - // they are not in incognito mode. We may loose these conditions later. - if (password_protection_service_->IsIncognito()) { - Finish(RequestOutcome::INCOGNITO, nullptr); - return; - } - if (!password_protection_service_->IsExtendedReporting()) { - Finish(RequestOutcome::NO_EXTENDED_REPORTING, nullptr); - return; - } - CheckWhitelistOnUIThread(); } @@ -97,6 +86,8 @@ request_proto_ = base::MakeUnique<LoginReputationClientRequest>(); request_proto_->set_page_url(main_frame_url_.spec()); request_proto_->set_trigger_type(request_type_); + password_protection_service_->FillUserPopulation(request_type_, + request_proto_.get()); request_proto_->set_stored_verdict_cnt( password_protection_service_->GetStoredVerdictCount()); LoginReputationClientRequest::Frame* main_frame =
diff --git a/components/safe_browsing/password_protection/password_protection_request.h b/components/safe_browsing/password_protection/password_protection_request.h index 7eec452..80193e2 100644 --- a/components/safe_browsing/password_protection/password_protection_request.h +++ b/components/safe_browsing/password_protection/password_protection_request.h
@@ -49,8 +49,8 @@ TIMEDOUT = 3, MATCHED_WHITELIST = 4, RESPONSE_ALREADY_CACHED = 5, - NO_EXTENDED_REPORTING = 6, - INCOGNITO = 7, + DEPRECATED_NO_EXTENDED_REPORTING = 6, + DEPRECATED_INCOGNITO = 7, REQUEST_MALFORMED = 8, FETCH_FAILED = 9, RESPONSE_MALFORMED = 10,
diff --git a/components/safe_browsing/password_protection/password_protection_service.cc b/components/safe_browsing/password_protection/password_protection_service.cc index b50244e..3203837 100644 --- a/components/safe_browsing/password_protection/password_protection_service.cc +++ b/components/safe_browsing/password_protection/password_protection_service.cc
@@ -7,6 +7,7 @@ #include "base/bind.h" #include "base/callback.h" #include "base/memory/ptr_util.h" +#include "base/metrics/field_trial.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" @@ -63,6 +64,12 @@ } // namespace +const base::Feature kLowReputationPinging{"LowReputationPinging", + base::FEATURE_DISABLED_BY_DEFAULT}; + +const base::Feature kProtectedPasswordEntryPinging{ + "ProtectedPasswordEntryPinging", base::FEATURE_DISABLED_BY_DEFAULT}; + PasswordProtectionService::PasswordProtectionService( const scoped_refptr<SafeBrowsingDatabaseManager>& database_manager, scoped_refptr<net::URLRequestContextGetter> request_context_getter, @@ -214,7 +221,7 @@ const GURL& password_form_action, const GURL& password_form_frame_url) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!IsPingingEnabled()) + if (!IsPingingEnabled(kLowReputationPinging)) return; // Skip URLs that we can't get a reliable reputation for. @@ -300,6 +307,31 @@ return kRequestTimeoutMs; } +void PasswordProtectionService::FillUserPopulation( + const LoginReputationClientRequest::TriggerType& request_type, + LoginReputationClientRequest* request_proto) { + ChromeUserPopulation* user_population = request_proto->mutable_population(); + user_population->set_user_population( + IsExtendedReporting() ? ChromeUserPopulation::EXTENDED_REPORTING + : ChromeUserPopulation::SAFE_BROWSING); + user_population->set_is_history_sync_enabled(IsHistorySyncEnabled()); + + base::FieldTrial* low_reputation_field_trial = + base::FeatureList::GetFieldTrial(kLowReputationPinging); + if (low_reputation_field_trial) { + user_population->add_finch_active_groups( + low_reputation_field_trial->trial_name() + "|" + + low_reputation_field_trial->group_name()); + } + base::FieldTrial* password_entry_field_trial = + base::FeatureList::GetFieldTrial(kProtectedPasswordEntryPinging); + if (password_entry_field_trial) { + user_population->add_finch_active_groups( + low_reputation_field_trial->trial_name() + "|" + + low_reputation_field_trial->group_name()); + } +} + void PasswordProtectionService::OnMatchCsdWhiteListResult( const bool* match_whitelist) { UMA_HISTOGRAM_BOOLEAN(
diff --git a/components/safe_browsing/password_protection/password_protection_service.h b/components/safe_browsing/password_protection/password_protection_service.h index e0470cca..9963266 100644 --- a/components/safe_browsing/password_protection/password_protection_service.h +++ b/components/safe_browsing/password_protection/password_protection_service.h
@@ -8,6 +8,7 @@ #include <set> #include "base/callback.h" +#include "base/feature_list.h" #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/ref_counted.h" @@ -32,6 +33,9 @@ class SafeBrowsingDatabaseManager; class PasswordProtectionRequest; +extern const base::Feature kLowReputationPinging; +extern const base::Feature kProtectedPasswordEntryPinging; + // Manage password protection pings and verdicts. There is one instance of this // class per profile. Therefore, every PasswordProtectionService instance is // associated with a unique HistoryService instance and a unique @@ -116,11 +120,17 @@ int event_tab_id, // -1 if tab id is not available. LoginReputationClientRequest::Frame* frame) = 0; + void FillUserPopulation( + const LoginReputationClientRequest::TriggerType& request_type, + LoginReputationClientRequest* request_proto); + virtual bool IsExtendedReporting() = 0; + virtual bool IsIncognito() = 0; - // If we can send ping to Safe Browsing backend. - virtual bool IsPingingEnabled() = 0; + virtual bool IsPingingEnabled(const base::Feature& feature) = 0; + + virtual bool IsHistorySyncEnabled() = 0; void CheckCsdWhitelistOnIOThread(const GURL& url, bool* check_result); @@ -128,6 +138,8 @@ // metric based on input. void OnMatchCsdWhiteListResult(const bool* match_whitelist); + HostContentSettingsMap* content_settings() const { return content_settings_; } + private: friend class PasswordProtectionServiceTest; friend class TestPasswordProtectionService;
diff --git a/components/safe_browsing/password_protection/password_protection_service_unittest.cc b/components/safe_browsing/password_protection/password_protection_service_unittest.cc index 3691dc3..547f23c 100644 --- a/components/safe_browsing/password_protection/password_protection_service_unittest.cc +++ b/components/safe_browsing/password_protection/password_protection_service_unittest.cc
@@ -97,7 +97,9 @@ void set_incognito(bool enabled) { is_incognito_ = enabled; } - bool IsPingingEnabled() override { return true; } + bool IsPingingEnabled(const base::Feature& feature) override { return true; } + + bool IsHistorySyncEnabled() override { return false; } LoginReputationClientResponse* latest_response() { return latest_response_.get(); @@ -425,35 +427,6 @@ EXPECT_EQ(0u, password_protection_service_->GetPendingRequestsCount()); } -TEST_F(PasswordProtectionServiceTest, TestNoRequestSentForIncognito) { - histograms_.ExpectTotalCount(kRequestOutcomeHistogramName, 0); - password_protection_service_->set_incognito(true); - password_protection_service_->StartRequest( - GURL(kTargetUrl), GURL("http://foo.com/submit"), - GURL("http://foo.com/frame"), - LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(nullptr, password_protection_service_->latest_response()); - EXPECT_THAT(histograms_.GetAllSamples(kRequestOutcomeHistogramName), - testing::ElementsAre(base::Bucket(7 /* INCOGNITO */, 1))); -} - -TEST_F(PasswordProtectionServiceTest, - TestNoRequestSentForNonExtendedReporting) { - histograms_.ExpectTotalCount(kRequestOutcomeHistogramName, 0); - password_protection_service_->set_extended_reporting(false); - password_protection_service_->StartRequest( - GURL(kTargetUrl), GURL("http://foo.com/submit"), - GURL("http://foo.com/frame"), - LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE); - - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(nullptr, password_protection_service_->latest_response()); - EXPECT_THAT( - histograms_.GetAllSamples(kRequestOutcomeHistogramName), - testing::ElementsAre(base::Bucket(6 /* NO_EXTENDED_REPORTING */, 1))); -} - TEST_F(PasswordProtectionServiceTest, TestNoRequestSentForWhitelistedURL) { histograms_.ExpectTotalCount(kRequestOutcomeHistogramName, 0); InitializeAndStartRequest(true /* match whitelist */,
diff --git a/components/subresource_filter/content/browser/activation_state_computing_navigation_throttle_unittest.cc b/components/subresource_filter/content/browser/activation_state_computing_navigation_throttle_unittest.cc index 4be0506e..1de00cc 100644 --- a/components/subresource_filter/content/browser/activation_state_computing_navigation_throttle_unittest.cc +++ b/components/subresource_filter/content/browser/activation_state_computing_navigation_throttle_unittest.cc
@@ -6,6 +6,7 @@ #include <memory> #include <utility> +#include <vector> #include "base/callback.h" #include "base/macros.h" @@ -363,6 +364,28 @@ EXPECT_FALSE(state.generic_blocking_rules_disabled); } +TEST_F(ActivationStateComputingThrottleSubFrameTest, + DryRunWithLoggingIsPropagated) { + ActivationState page_state(ActivationLevel::DRYRUN); + page_state.enable_logging = true; + NavigateAndCommitMainFrameWithPageActivationState( + GURL("http://example.test/"), page_state); + EXPECT_EQ(ActivationLevel::DRYRUN, last_activation_state().activation_level); + + CreateSubframeAndInitTestNavigation(GURL("http://example.child/"), + last_committed_frame_host(), + last_activation_state()); + SimulateStartAndExpectToProceed(); + SimulateRedirectAndExpectToProceed(GURL("http://example.child/?v=1")); + SimulateCommitAndExpectToProceed(); + + ActivationState state = last_activation_state(); + EXPECT_EQ(ActivationLevel::DRYRUN, state.activation_level); + EXPECT_TRUE(state.enable_logging); + EXPECT_FALSE(state.filtering_disabled_for_document); + EXPECT_FALSE(state.generic_blocking_rules_disabled); +} + TEST_F(ActivationStateComputingThrottleSubFrameTest, DisabledStatePropagated) { NavigateAndCommitMainFrameWithPageActivationState( GURL("http://allow-child-to-be-whitelisted.com/"),
diff --git a/components/subresource_filter/content/browser/content_subresource_filter_driver_factory.cc b/components/subresource_filter/content/browser/content_subresource_filter_driver_factory.cc index 4ade5b9..d89d37c 100644 --- a/components/subresource_filter/content/browser/content_subresource_filter_driver_factory.cc +++ b/components/subresource_filter/content/browser/content_subresource_filter_driver_factory.cc
@@ -204,6 +204,9 @@ configurations->the_one_and_only().performance_measurement_rate); ActivationState state = ActivationState(activation_level_); state.measure_performance = measure_performance_; + // TODO(csharrison): Set state.enable_logging based on metadata returns from + // the safe browsing filter, when it is available. Add tests for this + // behavior. throttle_manager_->NotifyPageActivationComputed(navigation_handle, state); }
diff --git a/components/subresource_filter/content/browser/subresource_filter_client.h b/components/subresource_filter/content/browser/subresource_filter_client.h index eb61f07..6792ad6 100644 --- a/components/subresource_filter/content/browser/subresource_filter_client.h +++ b/components/subresource_filter/content/browser/subresource_filter_client.h
@@ -34,9 +34,9 @@ virtual bool ShouldSuppressActivation( content::NavigationHandle* navigation_handle) = 0; - // Adds |url| to the BLOCKED state via content settings for the current - // profile. - virtual void WhitelistByContentSettings(const GURL& url) = 0; + // Adds |top_level_url| to the BLOCKED state via content settings for the + // current profile. + virtual void WhitelistByContentSettings(const GURL& top_level_url) = 0; // Adds |url| to a per-WebContents whitelist. virtual void WhitelistInCurrentWebContents(const GURL& url) = 0;
diff --git a/components/subresource_filter/content/renderer/web_document_subresource_filter_impl.cc b/components/subresource_filter/content/renderer/web_document_subresource_filter_impl.cc index 80a57c64..de17ed65 100644 --- a/components/subresource_filter/content/renderer/web_document_subresource_filter_impl.cc +++ b/components/subresource_filter/content/renderer/web_document_subresource_filter_impl.cc
@@ -118,6 +118,10 @@ std::move(first_disallowed_load_callback_).Run(); } +bool WebDocumentSubresourceFilterImpl::ShouldLogToConsole() { + return filter_.activation_state().enable_logging; +} + WebLoadPolicy WebDocumentSubresourceFilterImpl::getLoadPolicyImpl( const blink::WebURL& url, proto::ElementType element_type) {
diff --git a/components/subresource_filter/content/renderer/web_document_subresource_filter_impl.h b/components/subresource_filter/content/renderer/web_document_subresource_filter_impl.h index 686a81e..9722aa46 100644 --- a/components/subresource_filter/content/renderer/web_document_subresource_filter_impl.h +++ b/components/subresource_filter/content/renderer/web_document_subresource_filter_impl.h
@@ -41,6 +41,7 @@ LoadPolicy GetLoadPolicyForWebSocketConnect( const blink::WebURL& url) override; void ReportDisallowedLoad() override; + bool ShouldLogToConsole() override; private: LoadPolicy getLoadPolicyImpl(const blink::WebURL& url,
diff --git a/components/subresource_filter/core/common/activation_state.h b/components/subresource_filter/core/common/activation_state.h index a591ed6..465e6ae2 100644 --- a/components/subresource_filter/core/common/activation_state.h +++ b/components/subresource_filter/core/common/activation_state.h
@@ -50,6 +50,9 @@ // Whether or not extended performance measurements are enabled for the // current page load (across all frames). bool measure_performance = false; + + // Whether or not to log messages in the devtools console. + bool enable_logging = false; }; } // namespace subresource_filter
diff --git a/components/sync/android/java/src/org/chromium/components/sync/AndroidSyncSettings.java b/components/sync/android/java/src/org/chromium/components/sync/AndroidSyncSettings.java index 296980e..4f1cf17 100644 --- a/components/sync/android/java/src/org/chromium/components/sync/AndroidSyncSettings.java +++ b/components/sync/android/java/src/org/chromium/components/sync/AndroidSyncSettings.java
@@ -251,16 +251,19 @@ AccountManagerHelper.get().getGoogleAccounts(new Callback<Account[]>() { @Override public void onResult(Account[] accounts) { - StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites(); - for (Account account : accounts) { - if (!account.equals(mAccount) - && mSyncContentResolverDelegate.getIsSyncable( - account, mContractAuthority) - > 0) { - mSyncContentResolverDelegate.setIsSyncable(account, mContractAuthority, 0); + synchronized (mLock) { + StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites(); + for (Account account : accounts) { + if (!account.equals(mAccount) + && mSyncContentResolverDelegate.getIsSyncable( + account, mContractAuthority) + > 0) { + mSyncContentResolverDelegate.setIsSyncable( + account, mContractAuthority, 0); + } } + StrictMode.setThreadPolicy(oldPolicy); } - StrictMode.setThreadPolicy(oldPolicy); if (callback != null) callback.onResult(true); }
diff --git a/components/sync/android/javatests/src/org/chromium/components/sync/AndroidSyncSettingsTest.java b/components/sync/android/javatests/src/org/chromium/components/sync/AndroidSyncSettingsTest.java index 4187be76..a6bc34a 100644 --- a/components/sync/android/javatests/src/org/chromium/components/sync/AndroidSyncSettingsTest.java +++ b/components/sync/android/javatests/src/org/chromium/components/sync/AndroidSyncSettingsTest.java
@@ -22,6 +22,7 @@ import org.chromium.components.sync.test.util.MockSyncContentResolverDelegate; import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; /** * Tests for AndroidSyncSettings. @@ -29,46 +30,46 @@ public class AndroidSyncSettingsTest extends InstrumentationTestCase { private static class CountingMockSyncContentResolverDelegate extends MockSyncContentResolverDelegate { - private int mGetMasterSyncAutomaticallyCalls; - private int mGetSyncAutomaticallyCalls; - private int mGetIsSyncableCalls; - private int mSetIsSyncableCalls; - private int mSetSyncAutomaticallyCalls; - private int mRemovePeriodicSyncCalls; + private final AtomicInteger mGetMasterSyncAutomaticallyCalls = new AtomicInteger(); + private final AtomicInteger mGetSyncAutomaticallyCalls = new AtomicInteger(); + private final AtomicInteger mGetIsSyncableCalls = new AtomicInteger(); + private final AtomicInteger mSetIsSyncableCalls = new AtomicInteger(); + private final AtomicInteger mSetSyncAutomaticallyCalls = new AtomicInteger(); + private final AtomicInteger mRemovePeriodicSyncCalls = new AtomicInteger(); @Override public boolean getMasterSyncAutomatically() { - mGetMasterSyncAutomaticallyCalls++; + mGetMasterSyncAutomaticallyCalls.getAndIncrement(); return super.getMasterSyncAutomatically(); } @Override public boolean getSyncAutomatically(Account account, String authority) { - mGetSyncAutomaticallyCalls++; + mGetSyncAutomaticallyCalls.getAndIncrement(); return super.getSyncAutomatically(account, authority); } @Override public int getIsSyncable(Account account, String authority) { - mGetIsSyncableCalls++; + mGetIsSyncableCalls.getAndIncrement(); return super.getIsSyncable(account, authority); } @Override public void setIsSyncable(Account account, String authority, int syncable) { - mSetIsSyncableCalls++; + mSetIsSyncableCalls.getAndIncrement(); super.setIsSyncable(account, authority, syncable); } @Override public void setSyncAutomatically(Account account, String authority, boolean sync) { - mSetSyncAutomaticallyCalls++; + mSetSyncAutomaticallyCalls.getAndIncrement(); super.setSyncAutomatically(account, authority, sync); } @Override public void removePeriodicSync(Account account, String authority, Bundle extras) { - mRemovePeriodicSyncCalls++; + mRemovePeriodicSyncCalls.getAndIncrement(); super.removePeriodicSync(account, authority, extras); } } @@ -107,6 +108,7 @@ AndroidSyncSettings.overrideForTests(mContext, mSyncContentResolverDelegate); mAuthority = AndroidSyncSettings.getContractAuthority(mContext); AndroidSyncSettings.updateAccount(mContext, mAccount); + assertEquals(1, mSyncContentResolverDelegate.getIsSyncable(mAccount, mAuthority)); mSyncSettingsObserver = new MockSyncSettingsObserver(); AndroidSyncSettings.registerObserver(mContext, mSyncSettingsObserver); @@ -158,8 +160,8 @@ @DisabledTest(message = "crbug.com/717960") public void testAccountInitialization() throws InterruptedException, TimeoutException { // mAccount was set to be syncable and not have periodic syncs. - assertEquals(1, mSyncContentResolverDelegate.mSetIsSyncableCalls); - assertEquals(1, mSyncContentResolverDelegate.mRemovePeriodicSyncCalls); + assertEquals(1, mSyncContentResolverDelegate.mSetIsSyncableCalls.get()); + assertEquals(1, mSyncContentResolverDelegate.mRemovePeriodicSyncCalls.get()); final CallbackHelper callbackHelper = new CallbackHelper(); AndroidSyncSettings.updateAccount(mContext, null, new Callback<Boolean>() { @@ -171,12 +173,12 @@ callbackHelper.waitForCallback(0); // mAccount was set to be not syncable. - assertEquals(2, mSyncContentResolverDelegate.mSetIsSyncableCalls); - assertEquals(1, mSyncContentResolverDelegate.mRemovePeriodicSyncCalls); + assertEquals(2, mSyncContentResolverDelegate.mSetIsSyncableCalls.get()); + assertEquals(1, mSyncContentResolverDelegate.mRemovePeriodicSyncCalls.get()); AndroidSyncSettings.updateAccount(mContext, mAlternateAccount); // mAlternateAccount was set to be syncable and not have periodic syncs. - assertEquals(3, mSyncContentResolverDelegate.mSetIsSyncableCalls); - assertEquals(2, mSyncContentResolverDelegate.mRemovePeriodicSyncCalls); + assertEquals(3, mSyncContentResolverDelegate.mSetIsSyncableCalls.get()); + assertEquals(2, mSyncContentResolverDelegate.mRemovePeriodicSyncCalls.get()); } @SmallTest @@ -291,9 +293,10 @@ assertTrue("account should be synced", AndroidSyncSettings.isSyncEnabled(mContext)); int masterSyncAutomaticallyCalls = - mSyncContentResolverDelegate.mGetMasterSyncAutomaticallyCalls; - int isSyncableCalls = mSyncContentResolverDelegate.mGetIsSyncableCalls; - int getSyncAutomaticallyAcalls = mSyncContentResolverDelegate.mGetSyncAutomaticallyCalls; + mSyncContentResolverDelegate.mGetMasterSyncAutomaticallyCalls.get(); + int isSyncableCalls = mSyncContentResolverDelegate.mGetIsSyncableCalls.get(); + int getSyncAutomaticallyAcalls = + mSyncContentResolverDelegate.mGetSyncAutomaticallyCalls.get(); // Do a bunch of reads. AndroidSyncSettings.isMasterSyncEnabled(mContext); @@ -302,10 +305,10 @@ // Ensure values were read from cache. assertEquals(masterSyncAutomaticallyCalls, - mSyncContentResolverDelegate.mGetMasterSyncAutomaticallyCalls); - assertEquals(isSyncableCalls, mSyncContentResolverDelegate.mGetIsSyncableCalls); + mSyncContentResolverDelegate.mGetMasterSyncAutomaticallyCalls.get()); + assertEquals(isSyncableCalls, mSyncContentResolverDelegate.mGetIsSyncableCalls.get()); assertEquals(getSyncAutomaticallyAcalls, - mSyncContentResolverDelegate.mGetSyncAutomaticallyCalls); + mSyncContentResolverDelegate.mGetSyncAutomaticallyCalls.get()); // Do a bunch of reads for alternate account. AndroidSyncSettings.updateAccount(mContext, mAlternateAccount); @@ -315,10 +318,10 @@ // Ensure settings were only fetched once. assertEquals(masterSyncAutomaticallyCalls + 1, - mSyncContentResolverDelegate.mGetMasterSyncAutomaticallyCalls); - assertEquals(isSyncableCalls + 1, mSyncContentResolverDelegate.mGetIsSyncableCalls); + mSyncContentResolverDelegate.mGetMasterSyncAutomaticallyCalls.get()); + assertEquals(isSyncableCalls + 1, mSyncContentResolverDelegate.mGetIsSyncableCalls.get()); assertEquals(getSyncAutomaticallyAcalls + 1, - mSyncContentResolverDelegate.mGetSyncAutomaticallyCalls); + mSyncContentResolverDelegate.mGetSyncAutomaticallyCalls.get()); } @SmallTest @@ -367,12 +370,11 @@ mSyncSettingsObserver.receivedNotification()); } - // @SmallTest - // @Feature({"Sync"}) - @DisabledTest(message = "crbug.com/717960") + @SmallTest + @Feature({"Sync"}) public void testIsSyncableOnSigninAndNotOnSignout() throws InterruptedException, TimeoutException { - assertTrue(mSyncContentResolverDelegate.getIsSyncable(mAccount, mAuthority) == 1); + assertEquals(1, mSyncContentResolverDelegate.getIsSyncable(mAccount, mAuthority)); final CallbackHelper callbackHelper = new CallbackHelper(); AndroidSyncSettings.updateAccount(mContext, null, new Callback<Boolean>() { @@ -383,9 +385,9 @@ }); callbackHelper.waitForCallback(0); - assertTrue(mSyncContentResolverDelegate.getIsSyncable(mAccount, mAuthority) == 0); + assertEquals(0, mSyncContentResolverDelegate.getIsSyncable(mAccount, mAuthority)); AndroidSyncSettings.updateAccount(mContext, mAccount); - assertTrue(mSyncContentResolverDelegate.getIsSyncable(mAccount, mAuthority) == 1); + assertEquals(1, mSyncContentResolverDelegate.getIsSyncable(mAccount, mAuthority)); } /** @@ -408,7 +410,7 @@ // Ensure bug is fixed. AndroidSyncSettings.enableChromeSync(mContext); - assertTrue(mSyncContentResolverDelegate.getIsSyncable(mAccount, mAuthority) == 1); + assertEquals(1, mSyncContentResolverDelegate.getIsSyncable(mAccount, mAuthority)); // Should still be enabled. assertTrue(mSyncContentResolverDelegate.getSyncAutomatically(mAccount, mAuthority)); }
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 4fa3613..333afca9 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -312,6 +312,8 @@ "appcache/appcache_interceptor.h", "appcache/appcache_internals_ui.cc", "appcache/appcache_internals_ui.h", + "appcache/appcache_job.cc", + "appcache/appcache_job.h", "appcache/appcache_manifest_parser.cc", "appcache/appcache_manifest_parser.h", "appcache/appcache_navigation_handle.cc", @@ -335,6 +337,8 @@ "appcache/appcache_storage_impl.h", "appcache/appcache_update_job.cc", "appcache/appcache_update_job.h", + "appcache/appcache_url_loader_job.cc", + "appcache/appcache_url_loader_job.h", "appcache/appcache_url_loader_request.cc", "appcache/appcache_url_loader_request.h", "appcache/appcache_url_request.cc",
diff --git a/content/browser/accessibility/browser_accessibility.cc b/content/browser/accessibility/browser_accessibility.cc index 11a0000b..7d50b00 100644 --- a/content/browser/accessibility/browser_accessibility.cc +++ b/content/browser/accessibility/browser_accessibility.cc
@@ -892,7 +892,7 @@ } bool BrowserAccessibility::HasState(ui::AXState state_enum) const { - return (GetState() >> state_enum) & 1; + return GetData().HasState(state_enum); } bool BrowserAccessibility::IsCellOrTableHeaderRole() const {
diff --git a/content/browser/accessibility/browser_accessibility_manager_android.cc b/content/browser/accessibility/browser_accessibility_manager_android.cc index 5923de3..b279640 100644 --- a/content/browser/accessibility/browser_accessibility_manager_android.cc +++ b/content/browser/accessibility/browser_accessibility_manager_android.cc
@@ -191,7 +191,7 @@ ui::AXNodeData empty_document; empty_document.id = 0; empty_document.role = ui::AX_ROLE_ROOT_WEB_AREA; - empty_document.state = 1 << ui::AX_STATE_READ_ONLY; + empty_document.AddState(ui::AX_STATE_READ_ONLY); ui::AXTreeUpdate update; update.root_id = empty_document.id; @@ -991,9 +991,9 @@ ui::AXNodeData ax_node_data; ax_node_data.role = ui::AX_ROLE_MENU; ax_node_data.SetName("Autofill"); - ax_node_data.state = 1 << ui::AX_STATE_READ_ONLY; - ax_node_data.state |= 1 << ui::AX_STATE_FOCUSABLE; - ax_node_data.state |= 1 << ui::AX_STATE_SELECTABLE; + ax_node_data.AddState(ui::AX_STATE_READ_ONLY); + ax_node_data.AddState(ui::AX_STATE_FOCUSABLE); + ax_node_data.AddState(ui::AX_STATE_SELECTABLE); g_autofill_popup_proxy_node_ax_node->SetData(ax_node_data); g_autofill_popup_proxy_node->Init(this, g_autofill_popup_proxy_node_ax_node);
diff --git a/content/browser/accessibility/browser_accessibility_manager_auralinux.cc b/content/browser/accessibility/browser_accessibility_manager_auralinux.cc index bb67bc9..9fc76b4e 100644 --- a/content/browser/accessibility/browser_accessibility_manager_auralinux.cc +++ b/content/browser/accessibility/browser_accessibility_manager_auralinux.cc
@@ -42,7 +42,7 @@ ui::AXNodeData empty_document; empty_document.id = 0; empty_document.role = ui::AX_ROLE_ROOT_WEB_AREA; - empty_document.state = 1 << ui::AX_STATE_READ_ONLY; + empty_document.AddState(ui::AX_STATE_READ_ONLY); ui::AXTreeUpdate update; update.root_id = empty_document.id; update.nodes.push_back(empty_document);
diff --git a/content/browser/accessibility/browser_accessibility_manager_mac.mm b/content/browser/accessibility/browser_accessibility_manager_mac.mm index b3c484e..8e70dd3 100644 --- a/content/browser/accessibility/browser_accessibility_manager_mac.mm +++ b/content/browser/accessibility/browser_accessibility_manager_mac.mm
@@ -135,8 +135,7 @@ ui::AXNodeData empty_document; empty_document.id = 0; empty_document.role = ui::AX_ROLE_ROOT_WEB_AREA; - empty_document.state = - 1 << ui::AX_STATE_READ_ONLY; + empty_document.AddState(ui::AX_STATE_READ_ONLY); ui::AXTreeUpdate update; update.root_id = empty_document.id; update.nodes.push_back(empty_document); @@ -371,7 +370,7 @@ role == ui::AX_ROLE_TEXT_FIELD) { old_text = old_node_data.GetString16Attribute(ui::AX_ATTR_VALUE); new_text = new_node_data.GetString16Attribute(ui::AX_ATTR_VALUE); - } else if (new_node_data.state & (1 << ui::AX_STATE_EDITABLE)) { + } else if (new_node_data.HasState(ui::AX_STATE_EDITABLE)) { old_text = old_node_data.GetString16Attribute(ui::AX_ATTR_NAME); new_text = new_node_data.GetString16Attribute(ui::AX_ATTR_NAME); }
diff --git a/content/browser/accessibility/browser_accessibility_manager_unittest.cc b/content/browser/accessibility/browser_accessibility_manager_unittest.cc index 0ac8677..578859b 100644 --- a/content/browser/accessibility/browser_accessibility_manager_unittest.cc +++ b/content/browser/accessibility/browser_accessibility_manager_unittest.cc
@@ -100,19 +100,16 @@ button.id = 2; button.SetName("Button"); button.role = ui::AX_ROLE_BUTTON; - button.state = 0; ui::AXNodeData checkbox; checkbox.id = 3; checkbox.SetName("Checkbox"); checkbox.role = ui::AX_ROLE_CHECK_BOX; - checkbox.state = 0; ui::AXNodeData root; root.id = 1; root.SetName("Document"); root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = 0; root.child_ids.push_back(2); root.child_ids.push_back(3); @@ -177,25 +174,21 @@ tree1_child1.id = 2; tree1_child1.SetName("Child1"); tree1_child1.role = ui::AX_ROLE_BUTTON; - tree1_child1.state = 0; ui::AXNodeData tree1_child2; tree1_child2.id = 3; tree1_child2.SetName("Child2"); tree1_child2.role = ui::AX_ROLE_BUTTON; - tree1_child2.state = 0; ui::AXNodeData tree1_child3; tree1_child3.id = 4; tree1_child3.SetName("Child3"); tree1_child3.role = ui::AX_ROLE_BUTTON; - tree1_child3.state = 0; ui::AXNodeData tree1_root; tree1_root.id = 1; tree1_root.SetName("Document"); tree1_root.role = ui::AX_ROLE_ROOT_WEB_AREA; - tree1_root.state = 0; tree1_root.child_ids.push_back(2); tree1_root.child_ids.push_back(3); tree1_root.child_ids.push_back(4); @@ -212,13 +205,11 @@ tree2_child0.id = 5; tree2_child0.SetName("Child0"); tree2_child0.role = ui::AX_ROLE_BUTTON; - tree2_child0.state = 0; ui::AXNodeData tree2_root; tree2_root.id = 1; tree2_root.SetName("DocumentChanged"); tree2_root.role = ui::AX_ROLE_ROOT_WEB_AREA; - tree2_root.state = 0; tree2_root.child_ids.push_back(5); tree2_root.child_ids.push_back(2); tree2_root.child_ids.push_back(3); @@ -312,46 +303,39 @@ tree1_grandchild1.id = 4; tree1_grandchild1.SetName("GrandChild1"); tree1_grandchild1.role = ui::AX_ROLE_BUTTON; - tree1_grandchild1.state = 0; ui::AXNodeData tree1_child1; tree1_child1.id = 3; tree1_child1.SetName("Child1"); tree1_child1.role = ui::AX_ROLE_BUTTON; - tree1_child1.state = 0; tree1_child1.child_ids.push_back(4); ui::AXNodeData tree1_grandchild2; tree1_grandchild2.id = 6; tree1_grandchild2.SetName("GrandChild1"); tree1_grandchild2.role = ui::AX_ROLE_BUTTON; - tree1_grandchild2.state = 0; ui::AXNodeData tree1_child2; tree1_child2.id = 5; tree1_child2.SetName("Child2"); tree1_child2.role = ui::AX_ROLE_BUTTON; - tree1_child2.state = 0; tree1_child2.child_ids.push_back(6); ui::AXNodeData tree1_grandchild3; tree1_grandchild3.id = 8; tree1_grandchild3.SetName("GrandChild3"); tree1_grandchild3.role = ui::AX_ROLE_BUTTON; - tree1_grandchild3.state = 0; ui::AXNodeData tree1_child3; tree1_child3.id = 7; tree1_child3.SetName("Child3"); tree1_child3.role = ui::AX_ROLE_BUTTON; - tree1_child3.state = 0; tree1_child3.child_ids.push_back(8); ui::AXNodeData tree1_container; tree1_container.id = 2; tree1_container.SetName("Container"); tree1_container.role = ui::AX_ROLE_GROUP; - tree1_container.state = 0; tree1_container.child_ids.push_back(3); tree1_container.child_ids.push_back(5); tree1_container.child_ids.push_back(7); @@ -360,7 +344,6 @@ tree1_root.id = 1; tree1_root.SetName("Document"); tree1_root.role = ui::AX_ROLE_ROOT_WEB_AREA; - tree1_root.state = 0; tree1_root.child_ids.push_back(2); // Tree 2: @@ -379,20 +362,17 @@ tree2_grandchild0.id = 9; tree2_grandchild0.SetName("GrandChild0"); tree2_grandchild0.role = ui::AX_ROLE_BUTTON; - tree2_grandchild0.state = 0; ui::AXNodeData tree2_child0; tree2_child0.id = 10; tree2_child0.SetName("Child0"); tree2_child0.role = ui::AX_ROLE_BUTTON; - tree2_child0.state = 0; tree2_child0.child_ids.push_back(9); ui::AXNodeData tree2_container; tree2_container.id = 2; tree2_container.SetName("Container"); tree2_container.role = ui::AX_ROLE_GROUP; - tree2_container.state = 0; tree2_container.child_ids.push_back(10); tree2_container.child_ids.push_back(3); tree2_container.child_ids.push_back(5); @@ -484,21 +464,17 @@ ui::AXNodeData tree1_4; tree1_4.id = 4; - tree1_4.state = 0; ui::AXNodeData tree1_3; tree1_3.id = 3; - tree1_3.state = 0; tree1_3.child_ids.push_back(4); ui::AXNodeData tree1_2; tree1_2.id = 2; - tree1_2.state = 0; ui::AXNodeData tree1_1; tree1_1.id = 1; tree1_1.role = ui::AX_ROLE_ROOT_WEB_AREA; - tree1_1.state = 0; tree1_1.child_ids.push_back(2); tree1_1.child_ids.push_back(3); @@ -511,20 +487,16 @@ ui::AXNodeData tree2_6; tree2_6.id = 6; - tree2_6.state = 0; ui::AXNodeData tree2_5; tree2_5.id = 5; - tree2_5.state = 0; ui::AXNodeData tree2_4; tree2_4.id = 4; - tree2_4.state = 0; tree2_4.child_ids.push_back(6); ui::AXNodeData tree2_1; tree2_1.id = 1; - tree2_1.state = 0; tree2_1.child_ids.push_back(4); tree2_1.child_ids.push_back(5); @@ -1521,7 +1493,6 @@ ui::AXNodeData root; root.id = 1; root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = 0; root.child_ids.push_back(2); ui::AXNodeData node2; @@ -1541,7 +1512,6 @@ ui::AXNodeData root2; root2.id = 3; root2.role = ui::AX_ROLE_ROOT_WEB_AREA; - root2.state = 0; std::vector<AXEventNotificationDetails> events2; events2.push_back(AXEventNotificationDetails()); @@ -1561,7 +1531,6 @@ ui::AXNodeData root; root.id = 1; root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = 0; root.child_ids.push_back(2); root.child_ids.push_back(3); root.child_ids.push_back(4); @@ -1571,11 +1540,9 @@ ui::AXNodeData node3; node3.id = 3; - node3.state = 0; ui::AXNodeData node4; node4.id = 4; - node4.state = 0; ui::AXTreeUpdate initial_state = MakeAXTreeUpdate(root, node2, node3, node4); initial_state.has_tree_data = true; @@ -1591,7 +1558,6 @@ ui::AXNodeData root2; root2.id = 3; root2.role = ui::AX_ROLE_ROOT_WEB_AREA; - root2.state = 0; // Make an update the explicitly clears the previous root. std::vector<AXEventNotificationDetails> events2;
diff --git a/content/browser/accessibility/browser_accessibility_manager_win.cc b/content/browser/accessibility/browser_accessibility_manager_win.cc index 6e572695..afe9e84b 100644 --- a/content/browser/accessibility/browser_accessibility_manager_win.cc +++ b/content/browser/accessibility/browser_accessibility_manager_win.cc
@@ -59,8 +59,8 @@ ui::AXNodeData empty_document; empty_document.id = 0; empty_document.role = ui::AX_ROLE_ROOT_WEB_AREA; - empty_document.state = - (1 << ui::AX_STATE_READ_ONLY) | (1 << ui::AX_STATE_BUSY); + empty_document.AddState(ui::AX_STATE_READ_ONLY); + empty_document.AddState(ui::AX_STATE_BUSY); ui::AXTreeUpdate update; update.root_id = empty_document.id;
diff --git a/content/browser/accessibility/browser_accessibility_win_unittest.cc b/content/browser/accessibility/browser_accessibility_win_unittest.cc index bad00f3..3c3dce0 100644 --- a/content/browser/accessibility/browser_accessibility_win_unittest.cc +++ b/content/browser/accessibility/browser_accessibility_win_unittest.cc
@@ -127,19 +127,16 @@ button.id = 2; button.SetName("Button"); button.role = ui::AX_ROLE_BUTTON; - button.state = 0; ui::AXNodeData checkbox; checkbox.id = 3; checkbox.SetName("Checkbox"); checkbox.role = ui::AX_ROLE_CHECK_BOX; - checkbox.state = 0; ui::AXNodeData root; root.id = 1; root.SetName("Document"); root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = 0; root.child_ids.push_back(2); root.child_ids.push_back(3); @@ -195,13 +192,11 @@ text.id = 2; text.role = ui::AX_ROLE_STATIC_TEXT; text.SetName("old text"); - text.state = 0; ui::AXNodeData root; root.id = 1; root.SetName("Document"); root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = 0; root.child_ids.push_back(2); // Construct a BrowserAccessibilityManager with this @@ -277,17 +272,14 @@ ui::AXNodeData div; div.id = 2; div.role = ui::AX_ROLE_GROUP; - div.state = 0; ui::AXNodeData text3; text3.id = 3; text3.role = ui::AX_ROLE_STATIC_TEXT; - text3.state = 0; ui::AXNodeData text4; text4.id = 4; text4.role = ui::AX_ROLE_STATIC_TEXT; - text4.state = 0; div.child_ids.push_back(3); div.child_ids.push_back(4); @@ -295,7 +287,6 @@ ui::AXNodeData root; root.id = 1; root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = 0; root.child_ids.push_back(2); // Construct a BrowserAccessibilityManager with this @@ -340,7 +331,7 @@ ui::AXNodeData text_field; text_field.id = 2; text_field.role = ui::AX_ROLE_TEXT_FIELD; - text_field.state = 1 << ui::AX_STATE_EDITABLE; + text_field.AddState(ui::AX_STATE_EDITABLE); text_field.SetValue(text_value); std::vector<int32_t> line_start_offsets; line_start_offsets.push_back(15); @@ -353,14 +344,14 @@ ui::AXNodeData static_text1; static_text1.id = 3; static_text1.role = ui::AX_ROLE_STATIC_TEXT; - static_text1.state = 1 << ui::AX_STATE_EDITABLE; + static_text1.AddState(ui::AX_STATE_EDITABLE); static_text1.SetName(line1); static_text1.child_ids.push_back(4); ui::AXNodeData inline_box1; inline_box1.id = 4; inline_box1.role = ui::AX_ROLE_INLINE_TEXT_BOX; - inline_box1.state = 1 << ui::AX_STATE_EDITABLE; + inline_box1.AddState(ui::AX_STATE_EDITABLE); inline_box1.SetName(line1); std::vector<int32_t> word_start_offsets1; word_start_offsets1.push_back(0); @@ -372,20 +363,20 @@ ui::AXNodeData line_break; line_break.id = 5; line_break.role = ui::AX_ROLE_LINE_BREAK; - line_break.state = 1 << ui::AX_STATE_EDITABLE; + line_break.AddState(ui::AX_STATE_EDITABLE); line_break.SetName("\n"); ui::AXNodeData static_text2; static_text2.id = 6; static_text2.role = ui::AX_ROLE_STATIC_TEXT; - static_text2.state = 1 << ui::AX_STATE_EDITABLE; + static_text2.AddState(ui::AX_STATE_EDITABLE); static_text2.SetName(line2); static_text2.child_ids.push_back(7); ui::AXNodeData inline_box2; inline_box2.id = 7; inline_box2.role = ui::AX_ROLE_INLINE_TEXT_BOX; - inline_box2.state = 1 << ui::AX_STATE_EDITABLE; + inline_box2.AddState(ui::AX_STATE_EDITABLE); inline_box2.SetName(line2); std::vector<int32_t> word_start_offsets2; word_start_offsets2.push_back(0); @@ -499,19 +490,19 @@ ui::AXNodeData text1; text1.id = 11; text1.role = ui::AX_ROLE_STATIC_TEXT; - text1.state = 1 << ui::AX_STATE_READ_ONLY; + text1.AddState(ui::AX_STATE_READ_ONLY); text1.SetName(text1_name); ui::AXNodeData text2; text2.id = 12; text2.role = ui::AX_ROLE_STATIC_TEXT; - text2.state = 1 << ui::AX_STATE_READ_ONLY; + text2.AddState(ui::AX_STATE_READ_ONLY); text2.SetName(text2_name); ui::AXNodeData root; root.id = 1; root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = 1 << ui::AX_STATE_READ_ONLY; + root.AddState(ui::AX_STATE_READ_ONLY); root.child_ids.push_back(text1.id); root.child_ids.push_back(text2.id); @@ -582,7 +573,7 @@ ui::AXNodeData text1; text1.id = 11; text1.role = ui::AX_ROLE_STATIC_TEXT; - text1.state = 1 << ui::AX_STATE_READ_ONLY; + text1.AddState(ui::AX_STATE_READ_ONLY); text1.SetName(base::UTF16ToUTF8(text1_name)); ui::AXNodeData combo_box; @@ -594,13 +585,12 @@ ui::AXNodeData text2; text2.id = 13; text2.role = ui::AX_ROLE_STATIC_TEXT; - text2.state = 1 << ui::AX_STATE_READ_ONLY; + text2.AddState(ui::AX_STATE_READ_ONLY); text2.SetName(base::UTF16ToUTF8(text2_name)); ui::AXNodeData check_box; check_box.id = 14; check_box.role = ui::AX_ROLE_CHECK_BOX; - check_box.state = 0; check_box.AddIntAttribute(ui::AX_ATTR_CHECKED_STATE, ui::AX_CHECKED_STATE_TRUE); check_box.SetName(base::UTF16ToUTF8(check_box_name)); @@ -612,8 +602,8 @@ button_text.SetName(base::UTF16ToUTF8(button_text_name)); button.role = ui::AX_ROLE_BUTTON; button_text.role = ui::AX_ROLE_STATIC_TEXT; - button.state = 1 << ui::AX_STATE_READ_ONLY; - button_text.state = 1 << ui::AX_STATE_READ_ONLY; + button.AddState(ui::AX_STATE_READ_ONLY); + button_text.AddState(ui::AX_STATE_READ_ONLY); button.child_ids.push_back(button_text.id); ui::AXNodeData link, link_text; @@ -622,14 +612,14 @@ link_text.SetName(base::UTF16ToUTF8(link_text_name)); link.role = ui::AX_ROLE_LINK; link_text.role = ui::AX_ROLE_STATIC_TEXT; - link.state = 1 << ui::AX_STATE_READ_ONLY; - link_text.state = 1 << ui::AX_STATE_READ_ONLY; + link.AddState(ui::AX_STATE_READ_ONLY); + link_text.AddState(ui::AX_STATE_READ_ONLY); link.child_ids.push_back(link_text.id); ui::AXNodeData root; root.id = 1; root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = 1 << ui::AX_STATE_READ_ONLY; + root.AddState(ui::AX_STATE_READ_ONLY); root.child_ids.push_back(text1.id); root.child_ids.push_back(combo_box.id); root.child_ids.push_back(text2.id); @@ -841,7 +831,6 @@ checkbox.id = 3; checkbox.SetName("Checkbox"); checkbox.role = ui::AX_ROLE_CHECK_BOX; - checkbox.state = 0; checkbox.AddIntAttribute(ui::AX_ATTR_CHECKED_STATE, ui::AX_CHECKED_STATE_TRUE); @@ -849,7 +838,8 @@ root.id = 1; root.SetName("Document"); root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = (1 << ui::AX_STATE_READ_ONLY) | (1 << ui::AX_STATE_FOCUSABLE); + root.AddState(ui::AX_STATE_READ_ONLY); + root.AddState(ui::AX_STATE_FOCUSABLE); root.child_ids.push_back(2); root.child_ids.push_back(3); @@ -896,7 +886,8 @@ ui::AXNodeData root; root.id = 1; root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = (1 << ui::AX_STATE_READ_ONLY) | (1 << ui::AX_STATE_FOCUSABLE); + root.AddState(ui::AX_STATE_READ_ONLY); + root.AddState(ui::AX_STATE_FOCUSABLE); ui::AXNodeData combo_box, combo_box_text; combo_box.id = 2; @@ -905,9 +896,9 @@ combo_box_text.SetName("Combo box text"); combo_box.role = ui::AX_ROLE_COMBO_BOX; combo_box_text.role = ui::AX_ROLE_STATIC_TEXT; - combo_box.state = (1 << ui::AX_STATE_EDITABLE) | - (1 << ui::AX_STATE_FOCUSABLE); - combo_box_text.state = 1 << ui::AX_STATE_EDITABLE; + combo_box.AddState(ui::AX_STATE_EDITABLE); + combo_box.AddState(ui::AX_STATE_FOCUSABLE); + combo_box_text.AddState(ui::AX_STATE_EDITABLE); combo_box.child_ids.push_back(combo_box_text.id); ui::AXNodeData search_box, search_box_text, new_line; @@ -920,17 +911,18 @@ search_box.role = ui::AX_ROLE_SEARCH_BOX; search_box_text.role = ui::AX_ROLE_STATIC_TEXT; new_line.role = ui::AX_ROLE_LINE_BREAK; - search_box.state = (1 << ui::AX_STATE_EDITABLE) | - (1 << ui::AX_STATE_FOCUSABLE); - search_box_text.state = new_line.state = 1 << ui::AX_STATE_EDITABLE; + search_box.AddState(ui::AX_STATE_EDITABLE); + search_box.AddState(ui::AX_STATE_FOCUSABLE); + search_box_text.AddState(ui::AX_STATE_EDITABLE); + new_line.AddState(ui::AX_STATE_EDITABLE); search_box.child_ids.push_back(search_box_text.id); search_box.child_ids.push_back(new_line.id); ui::AXNodeData text_field; text_field.id = 7; text_field.role = ui::AX_ROLE_TEXT_FIELD; - text_field.state = - (1 << ui::AX_STATE_EDITABLE) | (1 << ui::AX_STATE_FOCUSABLE); + text_field.AddState(ui::AX_STATE_EDITABLE); + text_field.AddState(ui::AX_STATE_FOCUSABLE); text_field.SetValue("Text field text"); ui::AXNodeData link, link_text; @@ -939,7 +931,8 @@ link_text.SetName("Link text"); link.role = ui::AX_ROLE_LINK; link_text.role = ui::AX_ROLE_STATIC_TEXT; - link.state = link_text.state = 1 << ui::AX_STATE_READ_ONLY; + link.AddState(ui::AX_STATE_READ_ONLY); + link_text.AddState(ui::AX_STATE_READ_ONLY); link.child_ids.push_back(link_text.id); ui::AXNodeData slider, slider_text; @@ -949,7 +942,8 @@ slider_text.SetName("Slider text"); slider.role = ui::AX_ROLE_SLIDER; slider_text.role = ui::AX_ROLE_STATIC_TEXT; - slider.state = slider_text.state = 1 << ui::AX_STATE_READ_ONLY; + slider.AddState(ui::AX_STATE_READ_ONLY); + slider_text.AddState(ui::AX_STATE_READ_ONLY); slider.child_ids.push_back(slider_text.id); root.child_ids.push_back(2); // Combo box. @@ -1057,7 +1051,8 @@ ui::AXNodeData root; root.id = 1; root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = (1 << ui::AX_STATE_READ_ONLY) | (1 << ui::AX_STATE_FOCUSABLE); + root.AddState(ui::AX_STATE_READ_ONLY); + root.AddState(ui::AX_STATE_FOCUSABLE); ui::AXNodeData textarea, textarea_div, textarea_text; textarea.id = 2; @@ -1066,11 +1061,11 @@ textarea.role = ui::AX_ROLE_TEXT_FIELD; textarea_div.role = ui::AX_ROLE_DIV; textarea_text.role = ui::AX_ROLE_STATIC_TEXT; - textarea.state = (1 << ui::AX_STATE_EDITABLE) | - (1 << ui::AX_STATE_FOCUSABLE) | - (1 << ui::AX_STATE_MULTILINE); - textarea_div.state = 1 << ui::AX_STATE_EDITABLE; - textarea_text.state = 1 << ui::AX_STATE_EDITABLE; + textarea.AddState(ui::AX_STATE_EDITABLE); + textarea.AddState(ui::AX_STATE_FOCUSABLE); + textarea.AddState(ui::AX_STATE_MULTILINE); + textarea_div.AddState(ui::AX_STATE_EDITABLE); + textarea_text.AddState(ui::AX_STATE_EDITABLE); textarea.SetValue(base::UTF16ToUTF8(text)); textarea_text.SetName(base::UTF16ToUTF8(text)); textarea.AddStringAttribute(ui::AX_ATTR_HTML_TAG, "textarea"); @@ -1082,8 +1077,8 @@ textarea_line2.id = 6; textarea_line1.role = ui::AX_ROLE_INLINE_TEXT_BOX; textarea_line2.role = ui::AX_ROLE_INLINE_TEXT_BOX; - textarea_line1.state = 1 << ui::AX_STATE_EDITABLE; - textarea_line2.state = 1 << ui::AX_STATE_EDITABLE; + textarea_line1.AddState(ui::AX_STATE_EDITABLE); + textarea_line2.AddState(ui::AX_STATE_EDITABLE); textarea_line1.SetName(base::UTF16ToUTF8(line1)); textarea_line2.SetName(base::UTF16ToUTF8(line2)); textarea_line1.AddIntListAttribute(ui::AX_ATTR_WORD_STARTS, @@ -1100,10 +1095,10 @@ text_field.role = ui::AX_ROLE_TEXT_FIELD; text_field_div.role = ui::AX_ROLE_DIV; text_field_text.role = ui::AX_ROLE_STATIC_TEXT; - text_field.state = - (1 << ui::AX_STATE_EDITABLE) | (1 << ui::AX_STATE_FOCUSABLE); - text_field_div.state = 1 << ui::AX_STATE_EDITABLE; - text_field_text.state = 1 << ui::AX_STATE_EDITABLE; + text_field.AddState(ui::AX_STATE_EDITABLE); + text_field.AddState(ui::AX_STATE_FOCUSABLE); + text_field_div.AddState(ui::AX_STATE_EDITABLE); + text_field_text.AddState(ui::AX_STATE_EDITABLE); text_field.SetValue(base::UTF16ToUTF8(line1)); text_field_text.SetName(base::UTF16ToUTF8(line1)); text_field.AddStringAttribute(ui::AX_ATTR_HTML_TAG, "input"); @@ -1114,7 +1109,7 @@ ui::AXNodeData text_field_line; text_field_line.id = 10; text_field_line.role = ui::AX_ROLE_INLINE_TEXT_BOX; - text_field_line.state = 1 << ui::AX_STATE_EDITABLE; + text_field_line.AddState(ui::AX_STATE_EDITABLE); text_field_line.SetName(base::UTF16ToUTF8(line1)); text_field_line.AddIntListAttribute(ui::AX_ATTR_WORD_STARTS, line1_word_starts); @@ -1199,13 +1194,14 @@ ui::AXNodeData root; root.id = 1; root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = (1 << ui::AX_STATE_READ_ONLY) | (1 << ui::AX_STATE_FOCUSABLE); + root.AddState(ui::AX_STATE_READ_ONLY); + root.AddState(ui::AX_STATE_FOCUSABLE); ui::AXNodeData combo_box; combo_box.id = 2; combo_box.role = ui::AX_ROLE_COMBO_BOX; - combo_box.state = (1 << ui::AX_STATE_EDITABLE) | - (1 << ui::AX_STATE_FOCUSABLE); + combo_box.AddState(ui::AX_STATE_EDITABLE); + combo_box.AddState(ui::AX_STATE_FOCUSABLE); combo_box.SetValue("Test1"); // Place the caret between 't' and 'e'. combo_box.AddIntAttribute(ui::AX_ATTR_TEXT_SEL_START, 1); @@ -1214,8 +1210,8 @@ ui::AXNodeData text_field; text_field.id = 3; text_field.role = ui::AX_ROLE_TEXT_FIELD; - text_field.state = (1 << ui::AX_STATE_EDITABLE) | - (1 << ui::AX_STATE_FOCUSABLE); + text_field.AddState(ui::AX_STATE_EDITABLE); + text_field.AddState(ui::AX_STATE_FOCUSABLE); text_field.SetValue("Test2"); // Select the letter 'e'. text_field.AddIntAttribute(ui::AX_ATTR_TEXT_SEL_START, 1); @@ -1298,32 +1294,35 @@ ui::AXNodeData root; root.id = 1; root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = (1 << ui::AX_STATE_READ_ONLY) | (1 << ui::AX_STATE_FOCUSABLE); + root.AddState(ui::AX_STATE_READ_ONLY); + root.AddState(ui::AX_STATE_FOCUSABLE); ui::AXNodeData div_editable; div_editable.id = 2; div_editable.role = ui::AX_ROLE_DIV; - div_editable.state = (1 << ui::AX_STATE_EDITABLE) | - (1 << ui::AX_STATE_FOCUSABLE); + div_editable.AddState(ui::AX_STATE_EDITABLE); + div_editable.AddState(ui::AX_STATE_FOCUSABLE); ui::AXNodeData text; text.id = 3; text.role = ui::AX_ROLE_STATIC_TEXT; - text.state = (1 << ui::AX_STATE_EDITABLE); + text.AddState(ui::AX_STATE_EDITABLE); text.SetName("Click "); ui::AXNodeData link; link.id = 4; link.role = ui::AX_ROLE_LINK; - link.state = (1 << ui::AX_STATE_EDITABLE) | - (1 << ui::AX_STATE_FOCUSABLE) | (1 << ui::AX_STATE_LINKED); + link.AddState(ui::AX_STATE_EDITABLE); + link.AddState(ui::AX_STATE_FOCUSABLE); + link.AddState(ui::AX_STATE_LINKED); link.SetName("here"); ui::AXNodeData link_text; link_text.id = 5; link_text.role = ui::AX_ROLE_STATIC_TEXT; - link_text.state = (1 << ui::AX_STATE_EDITABLE) | - (1 << ui::AX_STATE_FOCUSABLE) | (1 << ui::AX_STATE_LINKED); + link_text.AddState(ui::AX_STATE_EDITABLE); + link_text.AddState(ui::AX_STATE_FOCUSABLE); + link_text.AddState(ui::AX_STATE_LINKED); link_text.SetName("here"); root.child_ids.push_back(2); @@ -1419,32 +1418,36 @@ ui::AXNodeData root; root.id = 1; root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = (1 << ui::AX_STATE_READ_ONLY) | (1 << ui::AX_STATE_FOCUSABLE); + root.AddState(ui::AX_STATE_READ_ONLY); + root.AddState(ui::AX_STATE_FOCUSABLE); ui::AXNodeData div_editable; div_editable.id = 2; div_editable.role = ui::AX_ROLE_DIV; - div_editable.state = - (1 << ui::AX_STATE_FOCUSABLE) | (1 << ui::AX_STATE_EDITABLE); + div_editable.AddState(ui::AX_STATE_FOCUSABLE); + div_editable.AddState(ui::AX_STATE_EDITABLE); ui::AXNodeData text; text.id = 3; text.role = ui::AX_ROLE_STATIC_TEXT; - text.state = (1 << ui::AX_STATE_FOCUSABLE) | (1 << ui::AX_STATE_EDITABLE); + text.AddState(ui::AX_STATE_FOCUSABLE); + text.AddState(ui::AX_STATE_EDITABLE); text.SetName("Click "); ui::AXNodeData link; link.id = 4; link.role = ui::AX_ROLE_LINK; - link.state = (1 << ui::AX_STATE_FOCUSABLE) | (1 << ui::AX_STATE_EDITABLE) | - (1 << ui::AX_STATE_LINKED); + link.AddState(ui::AX_STATE_FOCUSABLE); + link.AddState(ui::AX_STATE_EDITABLE); + link.AddState(ui::AX_STATE_LINKED); link.SetName("here"); ui::AXNodeData link_text; link_text.id = 5; link_text.role = ui::AX_ROLE_STATIC_TEXT; - link_text.state = (1 << ui::AX_STATE_FOCUSABLE) | - (1 << ui::AX_STATE_EDITABLE) | (1 << ui::AX_STATE_LINKED); + link_text.AddState(ui::AX_STATE_FOCUSABLE); + link_text.AddState(ui::AX_STATE_EDITABLE); + link_text.AddState(ui::AX_STATE_LINKED); link_text.SetName("here"); root.child_ids.push_back(2); @@ -1574,12 +1577,13 @@ ui::AXNodeData root; root.id = 1; root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = (1 << ui::AX_STATE_READ_ONLY) | (1 << ui::AX_STATE_FOCUSABLE); + root.AddState(ui::AX_STATE_READ_ONLY); + root.AddState(ui::AX_STATE_FOCUSABLE); ui::AXNodeData div; div.id = 2; div.role = ui::AX_ROLE_DIV; - div.state = (1 << ui::AX_STATE_FOCUSABLE); + div.AddState(ui::AX_STATE_FOCUSABLE); ui::AXNodeData text; text.id = 3; @@ -1589,7 +1593,8 @@ ui::AXNodeData link; link.id = 4; link.role = ui::AX_ROLE_LINK; - link.state = (1 << ui::AX_STATE_FOCUSABLE) | (1 << ui::AX_STATE_LINKED); + link.AddState(ui::AX_STATE_FOCUSABLE); + link.AddState(ui::AX_STATE_LINKED); link.SetName("here"); link.AddStringAttribute(ui::AX_ATTR_URL, "example.com"); @@ -1728,19 +1733,20 @@ ui::AXNodeData root; root.id = 1; root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = (1 << ui::AX_STATE_READ_ONLY) | (1 << ui::AX_STATE_FOCUSABLE); + root.AddState(ui::AX_STATE_READ_ONLY); + root.AddState(ui::AX_STATE_FOCUSABLE); ui::AXNodeData div_editable; div_editable.id = 2; div_editable.role = ui::AX_ROLE_DIV; - div_editable.state = - (1 << ui::AX_STATE_EDITABLE) | (1 << ui::AX_STATE_FOCUSABLE); + div_editable.AddState(ui::AX_STATE_EDITABLE); + div_editable.AddState(ui::AX_STATE_FOCUSABLE); div_editable.AddStringAttribute(ui::AX_ATTR_FONT_FAMILY, "Helvetica"); ui::AXNodeData text_before; text_before.id = 3; text_before.role = ui::AX_ROLE_STATIC_TEXT; - text_before.state = (1 << ui::AX_STATE_EDITABLE); + text_before.AddState(ui::AX_STATE_EDITABLE); text_before.SetName("Before "); text_before.AddIntAttribute( ui::AX_ATTR_TEXT_STYLE, @@ -1749,16 +1755,18 @@ ui::AXNodeData link; link.id = 4; link.role = ui::AX_ROLE_LINK; - link.state = (1 << ui::AX_STATE_EDITABLE) | (1 << ui::AX_STATE_FOCUSABLE) | - (1 << ui::AX_STATE_LINKED); + link.AddState(ui::AX_STATE_EDITABLE); + link.AddState(ui::AX_STATE_FOCUSABLE); + link.AddState(ui::AX_STATE_LINKED); link.SetName("lnk"); link.AddIntAttribute(ui::AX_ATTR_TEXT_STYLE, ui::AX_TEXT_STYLE_UNDERLINE); ui::AXNodeData link_text; link_text.id = 5; link_text.role = ui::AX_ROLE_STATIC_TEXT; - link_text.state = (1 << ui::AX_STATE_EDITABLE) | - (1 << ui::AX_STATE_FOCUSABLE) | (1 << ui::AX_STATE_LINKED); + link_text.AddState(ui::AX_STATE_EDITABLE); + link_text.AddState(ui::AX_STATE_FOCUSABLE); + link_text.AddState(ui::AX_STATE_LINKED); link_text.SetName("lnk"); link_text.AddIntAttribute(ui::AX_ATTR_TEXT_STYLE, ui::AX_TEXT_STYLE_UNDERLINE); @@ -1777,7 +1785,7 @@ ui::AXNodeData text_after; text_after.id = 6; text_after.role = ui::AX_ROLE_STATIC_TEXT; - text_after.state = (1 << ui::AX_STATE_EDITABLE); + text_after.AddState(ui::AX_STATE_EDITABLE); text_after.SetName(" after."); // Leave text style as normal. @@ -1968,30 +1976,31 @@ ui::AXNodeData root; root.id = 1; root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = (1 << ui::AX_STATE_READ_ONLY) | (1 << ui::AX_STATE_FOCUSABLE); + root.AddState(ui::AX_STATE_READ_ONLY); + root.AddState(ui::AX_STATE_FOCUSABLE); ui::AXNodeData combo_box; combo_box.id = 2; combo_box.role = ui::AX_ROLE_COMBO_BOX; - combo_box.state = - (1 << ui::AX_STATE_EDITABLE) | (1 << ui::AX_STATE_FOCUSABLE); + combo_box.AddState(ui::AX_STATE_EDITABLE); + combo_box.AddState(ui::AX_STATE_FOCUSABLE); combo_box.SetValue(value1 + value2); ui::AXNodeData combo_box_div; combo_box_div.id = 3; combo_box_div.role = ui::AX_ROLE_DIV; - combo_box_div.state = 1 << ui::AX_STATE_EDITABLE; + combo_box_div.AddState(ui::AX_STATE_EDITABLE); ui::AXNodeData static_text1; static_text1.id = 4; static_text1.role = ui::AX_ROLE_STATIC_TEXT; - static_text1.state = 1 << ui::AX_STATE_EDITABLE; + static_text1.AddState(ui::AX_STATE_EDITABLE); static_text1.SetName(value1); ui::AXNodeData static_text2; static_text2.id = 5; static_text2.role = ui::AX_ROLE_STATIC_TEXT; - static_text2.state = 1 << ui::AX_STATE_EDITABLE; + static_text2.AddState(ui::AX_STATE_EDITABLE); static_text2.SetName(value2); std::vector<int32_t> marker_types;
diff --git a/content/browser/accessibility/one_shot_accessibility_tree_search_unittest.cc b/content/browser/accessibility/one_shot_accessibility_tree_search_unittest.cc index 9b34ad36..92fd8cdd 100644 --- a/content/browser/accessibility/one_shot_accessibility_tree_search_unittest.cc +++ b/content/browser/accessibility/one_shot_accessibility_tree_search_unittest.cc
@@ -51,7 +51,6 @@ root.id = 1; root.SetName("Document"); root.role = ui::AX_ROLE_ROOT_WEB_AREA; - root.state = 0; root.child_ids.push_back(2); root.child_ids.push_back(3); root.child_ids.push_back(6); @@ -60,12 +59,10 @@ heading.id = 2; heading.SetName("Heading"); heading.role = ui::AX_ROLE_HEADING; - heading.state = 0; ui::AXNodeData list; list.id = 3; list.role = ui::AX_ROLE_LIST; - list.state = 0; list.child_ids.push_back(4); list.child_ids.push_back(5); @@ -73,19 +70,17 @@ list_item_1.id = 4; list_item_1.SetName("Autobots"); list_item_1.role = ui::AX_ROLE_LIST_ITEM; - list_item_1.state = 0; ui::AXNodeData list_item_2; list_item_2.id = 5; list_item_2.SetName("Decepticons"); list_item_2.role = ui::AX_ROLE_LIST_ITEM; - list_item_2.state = 0; ui::AXNodeData footer; footer.id = 6; footer.SetName("Footer"); footer.role = ui::AX_ROLE_FOOTER; - footer.state = 1 << ui::AX_STATE_OFFSCREEN; + footer.AddState(ui::AX_STATE_OFFSCREEN); tree_.reset(new TestBrowserAccessibilityManager( MakeAXTreeUpdate(root, heading, list, list_item_1, list_item_2, footer)));
diff --git a/content/browser/appcache/appcache_interceptor.cc b/content/browser/appcache/appcache_interceptor.cc index ab01aef..ab2ace4 100644 --- a/content/browser/appcache/appcache_interceptor.cc +++ b/content/browser/appcache/appcache_interceptor.cc
@@ -119,8 +119,7 @@ return; } DCHECK_NE(kAppCacheNoHostId, new_host_id); - handler->CompleteCrossSiteTransfer(new_process_id, - new_host_id); + handler->CompleteCrossSiteTransfer(new_process_id, new_host_id); } void AppCacheInterceptor::MaybeCompleteCrossSiteTransferInOldProcess( @@ -143,7 +142,9 @@ AppCacheRequestHandler* handler = GetHandler(request); if (!handler) return NULL; - return handler->MaybeLoadResource(network_delegate); + + AppCacheJob* job = handler->MaybeLoadResource(network_delegate); + return job ? job->AsURLRequestJob() : nullptr; } net::URLRequestJob* AppCacheInterceptor::MaybeInterceptRedirect( @@ -153,7 +154,10 @@ AppCacheRequestHandler* handler = GetHandler(request); if (!handler) return NULL; - return handler->MaybeLoadFallbackForRedirect(network_delegate, location); + + AppCacheJob* job = + handler->MaybeLoadFallbackForRedirect(network_delegate, location); + return job ? job->AsURLRequestJob() : nullptr; } net::URLRequestJob* AppCacheInterceptor::MaybeInterceptResponse( @@ -161,7 +165,9 @@ AppCacheRequestHandler* handler = GetHandler(request); if (!handler) return NULL; - return handler->MaybeLoadFallbackForResponse(network_delegate); + + AppCacheJob* job = handler->MaybeLoadFallbackForResponse(network_delegate); + return job ? job->AsURLRequestJob() : nullptr; } } // namespace content
diff --git a/content/browser/appcache/appcache_job.cc b/content/browser/appcache/appcache_job.cc new file mode 100644 index 0000000..0666c92 --- /dev/null +++ b/content/browser/appcache/appcache_job.cc
@@ -0,0 +1,47 @@ +// Copyright (c) 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/browser/appcache/appcache_job.h" + +#include "base/command_line.h" +#include "content/browser/appcache/appcache_request.h" +#include "content/browser/appcache/appcache_url_loader_job.h" +#include "content/browser/appcache/appcache_url_request_job.h" + +#include "content/public/common/content_switches.h" + +namespace content { + +std::unique_ptr<AppCacheJob> AppCacheJob::Create( + bool is_main_resource, + AppCacheHost* host, + AppCacheStorage* storage, + AppCacheRequest* request, + net::NetworkDelegate* network_delegate, + const OnPrepareToRestartCallback& restart_callback) { + std::unique_ptr<AppCacheJob> job; + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kEnableNetworkService)) { + job.reset(new AppCacheURLLoaderJob); + } else { + job.reset(new AppCacheURLRequestJob(request->GetURLRequest(), + network_delegate, storage, host, + is_main_resource, restart_callback)); + } + return job; +} + +AppCacheJob::~AppCacheJob() {} + +base::WeakPtr<AppCacheJob> AppCacheJob::GetWeakPtr() { + return weak_factory_.GetWeakPtr(); +} + +net::URLRequestJob* AppCacheJob::AsURLRequestJob() { + return nullptr; +} + +AppCacheJob::AppCacheJob() : weak_factory_(this) {} + +} // namespace content
diff --git a/content/browser/appcache/appcache_job.h b/content/browser/appcache/appcache_job.h new file mode 100644 index 0000000..a28bc33 --- /dev/null +++ b/content/browser/appcache/appcache_job.h
@@ -0,0 +1,116 @@ +// Copyright (c) 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_BROWSER_APPCACHE_APPCACHE_JOB_H_ +#define CONTENT_BROWSER_APPCACHE_APPCACHE_JOB_H_ + +#include <memory> + +#include "base/logging.h" +#include "base/memory/weak_ptr.h" +#include "base/strings/string16.h" +#include "base/threading/non_thread_safe.h" +#include "content/common/content_export.h" +#include "url/gurl.h" + +namespace net { +class NetworkDelegate; +class URLRequestJob; +} + +namespace content { + +class AppCacheEntry; +class AppCacheHost; +class AppCacheRequest; +class AppCacheStorage; +class URLRequestJob; + +// Interface for an AppCache job. This is used to send data stored in the +// AppCache to networking consumers. +// Subclasses implement this interface to wrap custom job objects like +// URLRequestJob, URLLoaderJob, etc to ensure that these dependencies stay out +// of the AppCache code. +class CONTENT_EXPORT AppCacheJob + : NON_EXPORTED_BASE(public base::NonThreadSafe), + public base::SupportsWeakPtr<AppCacheJob> { + public: + // Callback that will be invoked before the request is restarted. The caller + // can use this opportunity to grab state from the job to determine how it + // should behave when the request is restarted. + // TODO(ananta) + // This applies only to the URLRequestJob at the moment. Look into taking + // this knowledge out of this class. + using OnPrepareToRestartCallback = base::Closure; + + // Factory function to create the AppCacheJob instance for the |request| + // passed in. The |job_type| parameter controls the type of job which is + // created. + static std::unique_ptr<AppCacheJob> Create( + bool is_main_resource, + AppCacheHost* host, + AppCacheStorage* storage, + AppCacheRequest* request, + net::NetworkDelegate* network_delegate, + const OnPrepareToRestartCallback& restart_callback); + + virtual ~AppCacheJob(); + + // Kills the job. + virtual void Kill() = 0; + + // Returns true if the job was started. + virtual bool IsStarted() const = 0; + + // Returns true if the job is waiting for instructions. + virtual bool IsWaiting() const = 0; + + // Returns true if the job is delivering a response from the cache. + virtual bool IsDeliveringAppCacheResponse() const = 0; + + // Returns true if the job is delivering a response from the network. + virtual bool IsDeliveringNetworkResponse() const = 0; + + // Returns true if the job is delivering an error response. + virtual bool IsDeliveringErrorResponse() const = 0; + + // Returns true if the cache entry was not found in the cache. + virtual bool IsCacheEntryNotFound() const = 0; + + // Informs the job of what response it should deliver. Only one of these + // methods should be called, and only once per job. A job will sit idle and + // wait indefinitely until one of the deliver methods is called. + virtual void DeliverAppCachedResponse(const GURL& manifest_url, + int64_t cache_id, + const AppCacheEntry& entry, + bool is_fallback) = 0; + + // Informs the job that it should deliver the response from the network. This + // is generally controlled by the entries in the manifest file. + virtual void DeliverNetworkResponse() = 0; + + // Informs the job that it should deliver an error response. + virtual void DeliverErrorResponse() = 0; + + // Returns a weak pointer reference to the job. + virtual base::WeakPtr<AppCacheJob> GetWeakPtr(); + + // Returns the URL of the job. + virtual const GURL& GetURL() const = 0; + + // Returns the underlying URLRequestJob if any. This only applies to + // AppCaches loaded via the URLRequest mechanism. + virtual net::URLRequestJob* AsURLRequestJob(); + + protected: + AppCacheJob(); + + base::WeakPtrFactory<AppCacheJob> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(AppCacheJob); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_APPCACHE_APPCACHE_JOB_H_
diff --git a/content/browser/appcache/appcache_request.h b/content/browser/appcache/appcache_request.h index 089223d..ce727c5 100644 --- a/content/browser/appcache/appcache_request.h +++ b/content/browser/appcache/appcache_request.h
@@ -61,6 +61,8 @@ protected: friend class AppCacheRequestHandler; + // Enables the AppCacheJob to call GetURLRequest() and GetResourceRequest(). + friend class AppCacheJob; AppCacheRequest() {}
diff --git a/content/browser/appcache/appcache_request_handler.cc b/content/browser/appcache/appcache_request_handler.cc index 7ab9676..870fa7d 100644 --- a/content/browser/appcache/appcache_request_handler.cc +++ b/content/browser/appcache/appcache_request_handler.cc
@@ -58,7 +58,7 @@ return host_->storage(); } -AppCacheURLRequestJob* AppCacheRequestHandler::MaybeLoadResource( +AppCacheJob* AppCacheRequestHandler::MaybeLoadResource( net::NetworkDelegate* network_delegate) { maybe_load_resource_executed_ = true; if (!host_ || @@ -87,7 +87,7 @@ found_manifest_url_ = GURL(); found_network_namespace_ = false; - std::unique_ptr<AppCacheURLRequestJob> job; + std::unique_ptr<AppCacheJob> job; if (is_main_resource()) job = MaybeLoadMainResource(network_delegate); else @@ -96,15 +96,15 @@ // If its been setup to deliver a network response, we can just delete // it now and return NULL instead to achieve that since it couldn't // have been started yet. - if (job && job->is_delivering_network_response()) { - DCHECK(!job->has_been_started()); + if (job && job->IsDeliveringNetworkResponse()) { + DCHECK(!job->IsStarted()); job.reset(); } return job.release(); } -AppCacheURLRequestJob* AppCacheRequestHandler::MaybeLoadFallbackForRedirect( +AppCacheJob* AppCacheRequestHandler::MaybeLoadFallbackForRedirect( net::NetworkDelegate* network_delegate, const GURL& location) { if (!host_ || @@ -122,7 +122,7 @@ DCHECK(!job_.get()); // our jobs never generate redirects - std::unique_ptr<AppCacheURLRequestJob> job; + std::unique_ptr<AppCacheJob> job; if (found_fallback_entry_.has_response_id()) { // 6.9.6, step 4: If this results in a redirect to another origin, // get the resource of the fallback entry. @@ -141,7 +141,7 @@ return job.release(); } -AppCacheURLRequestJob* AppCacheRequestHandler::MaybeLoadFallbackForResponse( +AppCacheJob* AppCacheRequestHandler::MaybeLoadFallbackForResponse( net::NetworkDelegate* network_delegate) { if (!host_ || !AppCacheRequest::IsSchemeAndMethodSupportedForAppCache(request_.get()) || @@ -157,7 +157,7 @@ // We don't fallback for responses that we delivered. if (job_.get()) { - DCHECK(!job_->is_delivering_network_response()); + DCHECK(!job_->IsDeliveringNetworkResponse()); return NULL; } @@ -179,7 +179,7 @@ // 6.9.6, step 4: If this results in a 4xx or 5xx status code // or there were network errors, get the resource of the fallback entry. - std::unique_ptr<AppCacheURLRequestJob> job = CreateJob(network_delegate); + std::unique_ptr<AppCacheJob> job = CreateJob(network_delegate); DeliverAppCachedResponse(found_fallback_entry_, found_cache_id_, found_manifest_url_, true, found_namespace_entry_url_); @@ -254,7 +254,7 @@ const GURL& manifest_url, bool is_fallback, const GURL& namespace_entry_url) { - DCHECK(host_ && job_.get() && job_->is_waiting()); + DCHECK(host_ && job_.get() && job_->IsWaiting()); DCHECK(entry.has_response_id()); // Cache information about the response, for use by GetExtraResponseInfo. @@ -268,50 +268,47 @@ } void AppCacheRequestHandler::DeliverErrorResponse() { - DCHECK(job_.get() && job_->is_waiting()); + DCHECK(job_.get() && job_->IsWaiting()); DCHECK_EQ(kAppCacheNoCacheId, cache_id_); DCHECK(manifest_url_.is_empty()); job_->DeliverErrorResponse(); } void AppCacheRequestHandler::DeliverNetworkResponse() { - DCHECK(job_.get() && job_->is_waiting()); + DCHECK(job_.get() && job_->IsWaiting()); DCHECK_EQ(kAppCacheNoCacheId, cache_id_); DCHECK(manifest_url_.is_empty()); job_->DeliverNetworkResponse(); } void AppCacheRequestHandler::OnPrepareToRestart() { - DCHECK(job_->is_delivering_network_response() || - job_->cache_entry_not_found()); + DCHECK(job_->IsDeliveringNetworkResponse() || job_->IsCacheEntryNotFound()); // Any information about the source of the response is no longer relevant. cache_id_ = kAppCacheNoCacheId; manifest_url_ = GURL(); - cache_entry_not_found_ = job_->cache_entry_not_found(); - is_delivering_network_response_ = job_->is_delivering_network_response(); + cache_entry_not_found_ = job_->IsCacheEntryNotFound(); + is_delivering_network_response_ = job_->IsDeliveringNetworkResponse(); storage()->CancelDelegateCallbacks(this); job_.reset(); } -std::unique_ptr<AppCacheURLRequestJob> AppCacheRequestHandler::CreateJob( +std::unique_ptr<AppCacheJob> AppCacheRequestHandler::CreateJob( net::NetworkDelegate* network_delegate) { - std::unique_ptr<AppCacheURLRequestJob> job(new AppCacheURLRequestJob( - request_->GetURLRequest(), network_delegate, storage(), host_, - is_main_resource(), + std::unique_ptr<AppCacheJob> job = AppCacheJob::Create( + is_main_resource(), host_, storage(), request_.get(), network_delegate, base::Bind(&AppCacheRequestHandler::OnPrepareToRestart, - base::Unretained(this)))); + base::Unretained(this))); job_ = job->GetWeakPtr(); return job; } // Main-resource handling ---------------------------------------------- -std::unique_ptr<AppCacheURLRequestJob> -AppCacheRequestHandler::MaybeLoadMainResource( +std::unique_ptr<AppCacheJob> AppCacheRequestHandler::MaybeLoadMainResource( net::NetworkDelegate* network_delegate) { DCHECK(!job_.get()); DCHECK(host_); @@ -335,7 +332,7 @@ // We may have to wait for our storage query to complete, but // this query can also complete syncrhonously. - std::unique_ptr<AppCacheURLRequestJob> job = CreateJob(network_delegate); + std::unique_ptr<AppCacheJob> job = CreateJob(network_delegate); storage()->FindResponseForMainRequest(request_->GetURL(), preferred_manifest_url, this); return job; @@ -412,8 +409,7 @@ // Sub-resource handling ---------------------------------------------- -std::unique_ptr<AppCacheURLRequestJob> -AppCacheRequestHandler::MaybeLoadSubResource( +std::unique_ptr<AppCacheJob> AppCacheRequestHandler::MaybeLoadSubResource( net::NetworkDelegate* network_delegate) { DCHECK(!job_.get()); @@ -430,7 +426,7 @@ return nullptr; } - std::unique_ptr<AppCacheURLRequestJob> job = CreateJob(network_delegate); + std::unique_ptr<AppCacheJob> job = CreateJob(network_delegate); ContinueMaybeLoadSubResource(); return job; } @@ -442,7 +438,7 @@ DCHECK(job_.get()); DCHECK(host_->associated_cache() && host_->associated_cache()->is_complete()); - const GURL& url = job_->request()->url(); + const GURL& url = job_->GetURL(); AppCache* cache = host_->associated_cache(); storage()->FindResponseForSubRequest( host_->associated_cache(), url,
diff --git a/content/browser/appcache/appcache_request_handler.h b/content/browser/appcache/appcache_request_handler.h index 077e22b01..3b7e167 100644 --- a/content/browser/appcache/appcache_request_handler.h +++ b/content/browser/appcache/appcache_request_handler.h
@@ -25,6 +25,7 @@ } // namespace net namespace content { +class AppCacheJob; class AppCacheRequest; class AppCacheRequestHandlerTest; class AppCacheURLRequestJob; @@ -43,12 +44,11 @@ ~AppCacheRequestHandler() override; // These are called on each request intercept opportunity. - AppCacheURLRequestJob* MaybeLoadResource( - net::NetworkDelegate* network_delegate); - AppCacheURLRequestJob* MaybeLoadFallbackForRedirect( + AppCacheJob* MaybeLoadResource(net::NetworkDelegate* network_delegate); + AppCacheJob* MaybeLoadFallbackForRedirect( net::NetworkDelegate* network_delegate, const GURL& location); - AppCacheURLRequestJob* MaybeLoadFallbackForResponse( + AppCacheJob* MaybeLoadFallbackForResponse( net::NetworkDelegate* network_delegate); void GetExtraResponseInfo(int64_t* cache_id, GURL* manifest_url); @@ -98,9 +98,9 @@ // restarting, so can correctly continue to handle the request. void OnPrepareToRestart(); - // Helper method to create an AppCacheURLRequestJob and populate job_. + // Helper method to create an AppCacheJob and populate job_. // Caller takes ownership of returned value. - std::unique_ptr<AppCacheURLRequestJob> CreateJob( + std::unique_ptr<AppCacheJob> CreateJob( net::NetworkDelegate* network_delegate); // Helper to retrieve a pointer to the storage object. @@ -113,7 +113,7 @@ // Main-resource loading ------------------------------------- // Frame and SharedWorker main resources are handled here. - std::unique_ptr<AppCacheURLRequestJob> MaybeLoadMainResource( + std::unique_ptr<AppCacheJob> MaybeLoadMainResource( net::NetworkDelegate* network_delegate); // AppCacheStorage::Delegate methods @@ -128,7 +128,7 @@ // Sub-resource loading ------------------------------------- // Dedicated worker and all manner of sub-resources are handled here. - std::unique_ptr<AppCacheURLRequestJob> MaybeLoadSubResource( + std::unique_ptr<AppCacheJob> MaybeLoadSubResource( net::NetworkDelegate* network_delegate); void ContinueMaybeLoadSubResource(); @@ -177,7 +177,7 @@ // 1) Before request has started a job. // 2) Request is not being handled by appcache. // 3) Request has been cancelled, and the job killed. - base::WeakPtr<AppCacheURLRequestJob> job_; + base::WeakPtr<AppCacheJob> job_; // During a cross site navigation, we transfer ownership the AppcacheHost // from the old processes structures over to the new structures.
diff --git a/content/browser/appcache/appcache_request_handler_unittest.cc b/content/browser/appcache/appcache_request_handler_unittest.cc index 627ee95..3ae29404 100644 --- a/content/browser/appcache/appcache_request_handler_unittest.cc +++ b/content/browser/appcache/appcache_request_handler_unittest.cc
@@ -277,18 +277,19 @@ RESOURCE_TYPE_MAIN_FRAME, false); EXPECT_TRUE(handler_.get()); - job_.reset( - handler_->MaybeLoadResource(request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()) + ->AsURLRequestJob())); EXPECT_TRUE(job_.get()); - EXPECT_TRUE(job_->is_waiting()); + EXPECT_TRUE(job_->IsWaiting()); // We have to wait for completion of storage->FindResponseForMainRequest. ScheduleNextTask(); } void Verify_MainResource_Miss() { - EXPECT_FALSE(job_->is_waiting()); - EXPECT_TRUE(job_->is_delivering_network_response()); + EXPECT_FALSE(job_->IsWaiting()); + EXPECT_TRUE(job_->IsDeliveringNetworkResponse()); int64_t cache_id = kAppCacheNoCacheId; GURL manifest_url; @@ -298,12 +299,14 @@ EXPECT_EQ(0, handler_->found_group_id_); std::unique_ptr<AppCacheURLRequestJob> fallback_job( - handler_->MaybeLoadFallbackForRedirect( - request_->context()->network_delegate(), - GURL("http://blah/redirect"))); + static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForRedirect( + request_->context()->network_delegate(), + GURL("http://blah/redirect")))); EXPECT_FALSE(fallback_job); - fallback_job.reset(handler_->MaybeLoadFallbackForResponse( - request_->context()->network_delegate())); + fallback_job.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForResponse( + request_->context()->network_delegate()))); EXPECT_FALSE(fallback_job); EXPECT_TRUE(host_->preferred_manifest_url().is_empty()); @@ -330,18 +333,18 @@ GURL(), AppCacheEntry(), 1, 2, GURL("http://blah/manifest/")); - job_.reset( - handler_->MaybeLoadResource(request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); EXPECT_TRUE(job_.get()); - EXPECT_TRUE(job_->is_waiting()); + EXPECT_TRUE(job_->IsWaiting()); // We have to wait for completion of storage->FindResponseForMainRequest. ScheduleNextTask(); } void Verify_MainResource_Hit() { - EXPECT_FALSE(job_->is_waiting()); - EXPECT_TRUE(job_->is_delivering_appcache_response()); + EXPECT_FALSE(job_->IsWaiting()); + EXPECT_TRUE(job_->IsDeliveringAppCacheResponse()); int64_t cache_id = kAppCacheNoCacheId; GURL manifest_url; @@ -351,8 +354,9 @@ EXPECT_EQ(2, handler_->found_group_id_); std::unique_ptr<AppCacheURLRequestJob> fallback_job( - handler_->MaybeLoadFallbackForResponse( - request_->context()->network_delegate())); + static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForResponse( + request_->context()->network_delegate()))); EXPECT_FALSE(fallback_job); EXPECT_EQ(GURL("http://blah/manifest/"), @@ -381,10 +385,10 @@ AppCacheEntry(AppCacheEntry::EXPLICIT, 1), 1, 2, GURL("http://blah/manifest/")); - job_.reset( - handler_->MaybeLoadResource(request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); EXPECT_TRUE(job_.get()); - EXPECT_TRUE(job_->is_waiting()); + EXPECT_TRUE(job_->IsWaiting()); // We have to wait for completion of storage->FindResponseForMainRequest. ScheduleNextTask(); @@ -412,8 +416,8 @@ } void Verify_MainResource_Fallback() { - EXPECT_FALSE(job_->is_waiting()); - EXPECT_TRUE(job_->is_delivering_network_response()); + EXPECT_FALSE(job_->IsWaiting()); + EXPECT_TRUE(job_->IsDeliveringNetworkResponse()); // The handler expects to the job to tell it that the request is going to // be restarted before it sees the next request. @@ -422,17 +426,18 @@ // When the request is restarted, the existing job is dropped so a // real network job gets created. We expect NULL here which will cause // the net library to create a real job. - job_.reset( - handler_->MaybeLoadResource(request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); EXPECT_FALSE(job_.get()); // Simulate an http error of the real network job. SimulateResponseCode(500); - job_.reset(handler_->MaybeLoadFallbackForResponse( - request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForResponse( + request_->context()->network_delegate()))); EXPECT_TRUE(job_.get()); - EXPECT_TRUE(job_->is_delivering_appcache_response()); + EXPECT_TRUE(job_->IsDeliveringAppCacheResponse()); int64_t cache_id = kAppCacheNoCacheId; GURL manifest_url; @@ -469,18 +474,18 @@ AppCacheEntry(AppCacheEntry::EXPLICIT, 1), 1, 2, GURL("http://blah/manifest/")); - job_.reset( - handler_->MaybeLoadResource(request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); EXPECT_TRUE(job_.get()); - EXPECT_TRUE(job_->is_waiting()); + EXPECT_TRUE(job_->IsWaiting()); // We have to wait for completion of storage->FindResponseForMainRequest. ScheduleNextTask(); } void Verify_MainResource_FallbackOverride() { - EXPECT_FALSE(job_->is_waiting()); - EXPECT_TRUE(job_->is_delivering_network_response()); + EXPECT_FALSE(job_->IsWaiting()); + EXPECT_TRUE(job_->IsDeliveringNetworkResponse()); // The handler expects to the job to tell it that the request is going to // be restarted before it sees the next request. @@ -489,8 +494,8 @@ // When the request is restarted, the existing job is dropped so a // real network job gets created. We expect NULL here which will cause // the net library to create a real job. - job_.reset( - handler_->MaybeLoadResource(request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); EXPECT_FALSE(job_.get()); // Simulate an http error of the real network job, but with custom @@ -504,8 +509,9 @@ std::string(kOverrideHeaders, arraysize(kOverrideHeaders))); SimulateResponseInfo(info); - job_.reset(handler_->MaybeLoadFallbackForResponse( - request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForResponse( + request_->context()->network_delegate()))); EXPECT_FALSE(job_.get()); // GetExtraResponseInfo should return no information. @@ -548,18 +554,20 @@ RESOURCE_TYPE_SUB_RESOURCE, false); EXPECT_TRUE(handler_.get()); - job_.reset( - handler_->MaybeLoadResource(request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); EXPECT_TRUE(job_.get()); - EXPECT_TRUE(job_->is_delivering_error_response()); + EXPECT_TRUE(job_->IsDeliveringErrorResponse()); std::unique_ptr<AppCacheURLRequestJob> fallback_job( - handler_->MaybeLoadFallbackForRedirect( - request_->context()->network_delegate(), - GURL("http://blah/redirect"))); + static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForRedirect( + request_->context()->network_delegate(), + GURL("http://blah/redirect")))); EXPECT_FALSE(fallback_job); - fallback_job.reset(handler_->MaybeLoadFallbackForResponse( - request_->context()->network_delegate())); + fallback_job.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForResponse( + request_->context()->network_delegate()))); EXPECT_FALSE(fallback_job); TestFinished(); @@ -579,22 +587,24 @@ host_->CreateRequestHandler(AppCacheURLRequest::Create(request_.get()), RESOURCE_TYPE_SUB_RESOURCE, false); EXPECT_TRUE(handler_.get()); - job_.reset( - handler_->MaybeLoadResource(request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); EXPECT_TRUE(job_.get()); - EXPECT_TRUE(job_->is_waiting()); + EXPECT_TRUE(job_->IsWaiting()); host_->FinishCacheSelection(cache.get(), NULL); - EXPECT_FALSE(job_->is_waiting()); - EXPECT_TRUE(job_->is_delivering_error_response()); + EXPECT_FALSE(job_->IsWaiting()); + EXPECT_TRUE(job_->IsDeliveringErrorResponse()); std::unique_ptr<AppCacheURLRequestJob> fallback_job( - handler_->MaybeLoadFallbackForRedirect( - request_->context()->network_delegate(), - GURL("http://blah/redirect"))); + static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForRedirect( + request_->context()->network_delegate(), + GURL("http://blah/redirect")))); EXPECT_FALSE(fallback_job); - fallback_job.reset(handler_->MaybeLoadFallbackForResponse( - request_->context()->network_delegate())); + fallback_job.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForResponse( + request_->context()->network_delegate()))); EXPECT_FALSE(fallback_job); TestFinished(); @@ -614,18 +624,20 @@ host_->CreateRequestHandler(AppCacheURLRequest::Create(request_.get()), RESOURCE_TYPE_SUB_RESOURCE, false); EXPECT_TRUE(handler_.get()); - job_.reset( - handler_->MaybeLoadResource(request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); EXPECT_TRUE(job_.get()); - EXPECT_TRUE(job_->is_delivering_appcache_response()); + EXPECT_TRUE(job_->IsDeliveringAppCacheResponse()); std::unique_ptr<AppCacheURLRequestJob> fallback_job( - handler_->MaybeLoadFallbackForRedirect( - request_->context()->network_delegate(), - GURL("http://blah/redirect"))); + static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForRedirect( + request_->context()->network_delegate(), + GURL("http://blah/redirect")))); EXPECT_FALSE(fallback_job); - fallback_job.reset(handler_->MaybeLoadFallbackForResponse( - request_->context()->network_delegate())); + fallback_job.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForResponse( + request_->context()->network_delegate()))); EXPECT_FALSE(fallback_job); TestFinished(); @@ -647,19 +659,21 @@ host_->CreateRequestHandler(AppCacheURLRequest::Create(request_.get()), RESOURCE_TYPE_SUB_RESOURCE, false); EXPECT_TRUE(handler_.get()); - job_.reset( - handler_->MaybeLoadResource(request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); EXPECT_FALSE(job_.get()); - job_.reset(handler_->MaybeLoadFallbackForRedirect( - request_->context()->network_delegate(), - GURL("http://not_blah/redirect"))); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForRedirect( + request_->context()->network_delegate(), + GURL("http://not_blah/redirect")))); EXPECT_TRUE(job_.get()); - EXPECT_TRUE(job_->is_delivering_appcache_response()); + EXPECT_TRUE(job_->IsDeliveringAppCacheResponse()); std::unique_ptr<AppCacheURLRequestJob> fallback_job( - handler_->MaybeLoadFallbackForResponse( - request_->context()->network_delegate())); + static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForResponse( + request_->context()->network_delegate()))); EXPECT_FALSE(fallback_job); TestFinished(); @@ -681,19 +695,21 @@ host_->CreateRequestHandler(AppCacheURLRequest::Create(request_.get()), RESOURCE_TYPE_SUB_RESOURCE, false); EXPECT_TRUE(handler_.get()); - job_.reset( - handler_->MaybeLoadResource(request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); EXPECT_FALSE(job_.get()); std::unique_ptr<AppCacheURLRequestJob> fallback_job( - handler_->MaybeLoadFallbackForRedirect( - request_->context()->network_delegate(), - GURL("http://blah/redirect"))); + static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForRedirect( + request_->context()->network_delegate(), + GURL("http://blah/redirect")))); EXPECT_FALSE(fallback_job); SimulateResponseCode(200); - fallback_job.reset(handler_->MaybeLoadFallbackForResponse( - request_->context()->network_delegate())); + fallback_job.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForResponse( + request_->context()->network_delegate()))); EXPECT_FALSE(fallback_job); TestFinished(); @@ -716,17 +732,19 @@ host_->CreateRequestHandler(AppCacheURLRequest::Create(request_.get()), RESOURCE_TYPE_SUB_RESOURCE, false); EXPECT_TRUE(handler_.get()); - job_.reset( - handler_->MaybeLoadResource(request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); EXPECT_FALSE(job_.get()); std::unique_ptr<AppCacheURLRequestJob> fallback_job( - handler_->MaybeLoadFallbackForRedirect( - request_->context()->network_delegate(), - GURL("http://blah/redirect"))); + static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForRedirect( + request_->context()->network_delegate(), + GURL("http://blah/redirect")))); EXPECT_FALSE(fallback_job); - fallback_job.reset(handler_->MaybeLoadFallbackForResponse( - request_->context()->network_delegate())); + fallback_job.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForResponse( + request_->context()->network_delegate()))); EXPECT_FALSE(fallback_job); TestFinished(); @@ -750,13 +768,15 @@ backend_impl_->UnregisterHost(1); host_ = NULL; - EXPECT_FALSE( - handler_->MaybeLoadResource(request_->context()->network_delegate())); - EXPECT_FALSE(handler_->MaybeLoadFallbackForRedirect( - request_->context()->network_delegate(), - GURL("http://blah/redirect"))); - EXPECT_FALSE(handler_->MaybeLoadFallbackForResponse( - request_->context()->network_delegate())); + EXPECT_FALSE(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); + EXPECT_FALSE(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForRedirect( + request_->context()->network_delegate(), + GURL("http://blah/redirect")))); + EXPECT_FALSE(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForResponse( + request_->context()->network_delegate()))); TestFinished(); } @@ -774,22 +794,24 @@ RESOURCE_TYPE_SUB_RESOURCE, false); EXPECT_TRUE(handler_.get()); - job_.reset( - handler_->MaybeLoadResource(request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); EXPECT_TRUE(job_.get()); - EXPECT_TRUE(job_->is_waiting()); + EXPECT_TRUE(job_->IsWaiting()); backend_impl_->UnregisterHost(1); host_ = NULL; EXPECT_TRUE(job_->has_been_killed()); - EXPECT_FALSE( - handler_->MaybeLoadResource(request_->context()->network_delegate())); - EXPECT_FALSE(handler_->MaybeLoadFallbackForRedirect( - request_->context()->network_delegate(), - GURL("http://blah/redirect"))); - EXPECT_FALSE(handler_->MaybeLoadFallbackForResponse( - request_->context()->network_delegate())); + EXPECT_FALSE(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); + EXPECT_FALSE(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForRedirect( + request_->context()->network_delegate(), + GURL("http://blah/redirect")))); + EXPECT_FALSE(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForResponse( + request_->context()->network_delegate()))); TestFinished(); } @@ -808,8 +830,8 @@ host_->CreateRequestHandler(AppCacheURLRequest::Create(request_.get()), RESOURCE_TYPE_SUB_RESOURCE, false); EXPECT_TRUE(handler_.get()); - job_.reset( - handler_->MaybeLoadResource(request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); EXPECT_TRUE(job_.get()); backend_impl_.reset(); @@ -819,13 +841,15 @@ host_ = NULL; EXPECT_TRUE(job_->has_been_killed()); - EXPECT_FALSE( - handler_->MaybeLoadResource(request_->context()->network_delegate())); - EXPECT_FALSE(handler_->MaybeLoadFallbackForRedirect( - request_->context()->network_delegate(), - GURL("http://blah/redirect"))); - EXPECT_FALSE(handler_->MaybeLoadFallbackForResponse( - request_->context()->network_delegate())); + EXPECT_FALSE(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); + EXPECT_FALSE(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForRedirect( + request_->context()->network_delegate(), + GURL("http://blah/redirect")))); + EXPECT_FALSE(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForResponse( + request_->context()->network_delegate()))); TestFinished(); } @@ -847,13 +871,15 @@ host_ = NULL; EXPECT_FALSE(handler_->host_for_cross_site_transfer_.get()); - EXPECT_FALSE( - handler_->MaybeLoadResource(request_->context()->network_delegate())); - EXPECT_FALSE(handler_->MaybeLoadFallbackForRedirect( - request_->context()->network_delegate(), - GURL("http://blah/redirect"))); - EXPECT_FALSE(handler_->MaybeLoadFallbackForResponse( - request_->context()->network_delegate())); + EXPECT_FALSE(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); + EXPECT_FALSE(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForRedirect( + request_->context()->network_delegate(), + GURL("http://blah/redirect")))); + EXPECT_FALSE(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForResponse( + request_->context()->network_delegate()))); TestFinished(); } @@ -871,13 +897,15 @@ RESOURCE_TYPE_SUB_RESOURCE, false); EXPECT_TRUE(handler_.get()); // we could redirect to http (conceivably) - EXPECT_FALSE( - handler_->MaybeLoadResource(request_->context()->network_delegate())); - EXPECT_FALSE(handler_->MaybeLoadFallbackForRedirect( - request_->context()->network_delegate(), - GURL("ftp://blah/redirect"))); - EXPECT_FALSE(handler_->MaybeLoadFallbackForResponse( - request_->context()->network_delegate())); + EXPECT_FALSE(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); + EXPECT_FALSE(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForRedirect( + request_->context()->network_delegate(), + GURL("ftp://blah/redirect")))); + EXPECT_FALSE(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForResponse( + request_->context()->network_delegate()))); TestFinished(); } @@ -892,24 +920,25 @@ RESOURCE_TYPE_MAIN_FRAME, false); EXPECT_TRUE(handler_.get()); - job_.reset( - handler_->MaybeLoadResource(request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); EXPECT_TRUE(job_.get()); - EXPECT_TRUE(job_->is_waiting()); - EXPECT_FALSE(job_->has_been_started()); + EXPECT_TRUE(job_->IsWaiting()); + EXPECT_FALSE(job_->IsStarted()); - base::WeakPtr<AppCacheURLRequestJob> weak_job = job_->GetWeakPtr(); + base::WeakPtr<AppCacheJob> weak_job = job_->GetWeakPtr(); job_factory_->SetJob(std::move(job_)); request_->Start(); ASSERT_TRUE(weak_job); - EXPECT_TRUE(weak_job->has_been_started()); + EXPECT_TRUE(weak_job->IsStarted()); request_->Cancel(); ASSERT_FALSE(weak_job); - EXPECT_FALSE(handler_->MaybeLoadFallbackForResponse( - request_->context()->network_delegate())); + EXPECT_FALSE(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadFallbackForResponse( + request_->context()->network_delegate()))); TestFinished(); } @@ -979,18 +1008,18 @@ GURL(), AppCacheEntry(), 1, 2, GURL("http://blah/manifest/")); - job_.reset( - handler_->MaybeLoadResource(request_->context()->network_delegate())); + job_.reset(static_cast<AppCacheURLRequestJob*>( + handler_->MaybeLoadResource(request_->context()->network_delegate()))); EXPECT_TRUE(job_.get()); - EXPECT_TRUE(job_->is_waiting()); + EXPECT_TRUE(job_->IsWaiting()); // We have to wait for completion of storage->FindResponseForMainRequest. ScheduleNextTask(); } void Verify_MainResource_Blocked() { - EXPECT_FALSE(job_->is_waiting()); - EXPECT_FALSE(job_->is_delivering_appcache_response()); + EXPECT_FALSE(job_->IsWaiting()); + EXPECT_FALSE(job_->IsDeliveringAppCacheResponse()); EXPECT_EQ(0, handler_->found_cache_id_); EXPECT_EQ(0, handler_->found_group_id_);
diff --git a/content/browser/appcache/appcache_url_loader_job.cc b/content/browser/appcache/appcache_url_loader_job.cc new file mode 100644 index 0000000..09f1545 --- /dev/null +++ b/content/browser/appcache/appcache_url_loader_job.cc
@@ -0,0 +1,53 @@ +// Copyright (c) 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/browser/appcache/appcache_url_loader_job.h" +#include "content/browser/appcache/appcache_entry.h" + +namespace content { + +AppCacheURLLoaderJob::~AppCacheURLLoaderJob() {} + +void AppCacheURLLoaderJob::Kill() {} + +bool AppCacheURLLoaderJob::IsStarted() const { + return false; +} + +bool AppCacheURLLoaderJob::IsWaiting() const { + return false; +} + +bool AppCacheURLLoaderJob::IsDeliveringAppCacheResponse() const { + return false; +} + +bool AppCacheURLLoaderJob::IsDeliveringNetworkResponse() const { + return false; +} + +bool AppCacheURLLoaderJob::IsDeliveringErrorResponse() const { + return false; +} + +bool AppCacheURLLoaderJob::IsCacheEntryNotFound() const { + return false; +} + +void AppCacheURLLoaderJob::DeliverAppCachedResponse(const GURL& manifest_url, + int64_t cache_id, + const AppCacheEntry& entry, + bool is_fallback) {} + +void AppCacheURLLoaderJob::DeliverNetworkResponse() {} + +void AppCacheURLLoaderJob::DeliverErrorResponse() {} + +const GURL& AppCacheURLLoaderJob::GetURL() const { + return url_; +} + +AppCacheURLLoaderJob::AppCacheURLLoaderJob() {} + +} // namespace content
diff --git a/content/browser/appcache/appcache_url_loader_job.h b/content/browser/appcache/appcache_url_loader_job.h new file mode 100644 index 0000000..3d526c9 --- /dev/null +++ b/content/browser/appcache/appcache_url_loader_job.h
@@ -0,0 +1,54 @@ +// Copyright (c) 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_BROWSER_APPCACHE_APPCACHE_URL_LOADER_JOB_H_ +#define CONTENT_BROWSER_APPCACHE_APPCACHE_URL_LOADER_JOB_H_ + +#include "base/logging.h" +#include "base/strings/string16.h" +#include "content/browser/appcache/appcache_job.h" +#include "content/common/content_export.h" + +namespace content { + +class AppCacheHost; +class AppCacheRequest; +class AppCacheStorage; + +// AppCacheJob wrapper for a mojom::URLLoader implementation which returns +// responses stored in the AppCache. +class CONTENT_EXPORT AppCacheURLLoaderJob : public AppCacheJob { + public: + ~AppCacheURLLoaderJob() override; + + // AppCacheJob overrides. + void Kill() override; + bool IsStarted() const override; + bool IsWaiting() const override; + bool IsDeliveringAppCacheResponse() const override; + bool IsDeliveringNetworkResponse() const override; + bool IsDeliveringErrorResponse() const override; + bool IsCacheEntryNotFound() const override; + void DeliverAppCachedResponse(const GURL& manifest_url, + int64_t cache_id, + const AppCacheEntry& entry, + bool is_fallback) override; + void DeliverNetworkResponse() override; + void DeliverErrorResponse() override; + const GURL& GetURL() const override; + + protected: + // AppCacheJob::Create() creates this instance. + friend class AppCacheJob; + + AppCacheURLLoaderJob(); + + GURL url_; + + DISALLOW_COPY_AND_ASSIGN(AppCacheURLLoaderJob); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_APPCACHE_APPCACHE_URL_LOADER_JOB_H_
diff --git a/content/browser/appcache/appcache_url_request_job.cc b/content/browser/appcache/appcache_url_request_job.cc index 467f39f..8a89def 100644 --- a/content/browser/appcache/appcache_url_request_job.cc +++ b/content/browser/appcache/appcache_url_request_job.cc
@@ -32,33 +32,54 @@ namespace content { -AppCacheURLRequestJob::AppCacheURLRequestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - AppCacheStorage* storage, - AppCacheHost* host, - bool is_main_resource, - const OnPrepareToRestartCallback& restart_callback) - : net::URLRequestJob(request, network_delegate), - host_(host), - storage_(storage), - has_been_started_(false), - has_been_killed_(false), - delivery_type_(AWAITING_DELIVERY_ORDERS), - cache_id_(kAppCacheNoCacheId), - is_fallback_(false), - is_main_resource_(is_main_resource), - cache_entry_not_found_(false), - on_prepare_to_restart_callback_(restart_callback), - weak_factory_(this) { - DCHECK(storage_); -} - AppCacheURLRequestJob::~AppCacheURLRequestJob() { if (storage_) storage_->CancelDelegateCallbacks(this); } +void AppCacheURLRequestJob::Kill() { + if (!has_been_killed_) { + has_been_killed_ = true; + reader_.reset(); + handler_source_reader_.reset(); + if (storage_) { + storage_->CancelDelegateCallbacks(this); + storage_ = NULL; + } + host_ = NULL; + info_ = NULL; + cache_ = NULL; + group_ = NULL; + range_response_info_.reset(); + net::URLRequestJob::Kill(); + AppCacheJob::weak_factory_.InvalidateWeakPtrs(); + } +} + +bool AppCacheURLRequestJob::IsStarted() const { + return has_been_started_; +} + +bool AppCacheURLRequestJob::IsWaiting() const { + return delivery_type_ == AWAITING_DELIVERY_ORDERS; +} + +bool AppCacheURLRequestJob::IsDeliveringAppCacheResponse() const { + return delivery_type_ == APPCACHED_DELIVERY; +} + +bool AppCacheURLRequestJob::IsDeliveringNetworkResponse() const { + return delivery_type_ == NETWORK_DELIVERY; +} + +bool AppCacheURLRequestJob::IsDeliveringErrorResponse() const { + return delivery_type_ == ERROR_DELIVERY; +} + +bool AppCacheURLRequestJob::IsCacheEntryNotFound() const { + return cache_entry_not_found_; +} + void AppCacheURLRequestJob::DeliverAppCachedResponse(const GURL& manifest_url, int64_t cache_id, const AppCacheEntry& entry, @@ -87,22 +108,47 @@ MaybeBeginDelivery(); } -base::WeakPtr<AppCacheURLRequestJob> AppCacheURLRequestJob::GetWeakPtr() { - return weak_factory_.GetWeakPtr(); +const GURL& AppCacheURLRequestJob::GetURL() const { + return request()->url(); +} + +net::URLRequestJob* AppCacheURLRequestJob::AsURLRequestJob() { + return this; +} + +AppCacheURLRequestJob::AppCacheURLRequestJob( + net::URLRequest* request, + net::NetworkDelegate* network_delegate, + AppCacheStorage* storage, + AppCacheHost* host, + bool is_main_resource, + const OnPrepareToRestartCallback& restart_callback) + : net::URLRequestJob(request, network_delegate), + host_(host), + storage_(storage), + has_been_started_(false), + has_been_killed_(false), + delivery_type_(AWAITING_DELIVERY_ORDERS), + cache_id_(kAppCacheNoCacheId), + is_fallback_(false), + is_main_resource_(is_main_resource), + cache_entry_not_found_(false), + on_prepare_to_restart_callback_(restart_callback) { + DCHECK(storage_); } void AppCacheURLRequestJob::MaybeBeginDelivery() { - if (has_been_started() && has_delivery_orders()) { + if (IsStarted() && has_delivery_orders()) { // Start asynchronously so that all error reporting and data // callbacks happen as they would for network requests. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&AppCacheURLRequestJob::BeginDelivery, - weak_factory_.GetWeakPtr())); + StaticAsWeakPtr(this))); } } void AppCacheURLRequestJob::BeginDelivery() { - DCHECK(has_delivery_orders() && has_been_started()); + DCHECK(has_delivery_orders() && IsStarted()); if (has_been_killed()) return; @@ -236,7 +282,7 @@ handler->HandleRequest( request(), base::Bind(&AppCacheURLRequestJob::OnExecutableResponseCallback, - weak_factory_.GetWeakPtr())); + StaticAsWeakPtr(this))); } void AppCacheURLRequestJob::OnExecutableResponseCallback( @@ -280,7 +326,7 @@ void AppCacheURLRequestJob::OnResponseInfoLoaded( AppCacheResponseInfo* response_info, int64_t response_id) { - DCHECK(is_delivering_appcache_response()); + DCHECK(IsDeliveringAppCacheResponse()); if (response_info) { info_ = response_info; reader_.reset( @@ -317,7 +363,7 @@ void AppCacheURLRequestJob::SetupRangeResponse() { DCHECK(is_range_request() && info_.get() && reader_.get() && - is_delivering_appcache_response()); + IsDeliveringAppCacheResponse()); int resource_size = static_cast<int>(info_->response_data_size()); if (resource_size < 0 || !range_requested_.ComputeBounds(resource_size)) { range_requested_ = net::HttpByteRange(); @@ -342,7 +388,7 @@ } void AppCacheURLRequestJob::OnReadComplete(int result) { - DCHECK(is_delivering_appcache_response()); + DCHECK(IsDeliveringAppCacheResponse()); if (result == 0) { AppCacheHistograms::CountResponseRetrieval( true, is_main_resource_, manifest_url_.GetOrigin()); @@ -360,33 +406,14 @@ // net::URLRequestJob overrides ------------------------------------------------ void AppCacheURLRequestJob::Start() { - DCHECK(!has_been_started()); + DCHECK(!IsStarted()); has_been_started_ = true; start_time_tick_ = base::TimeTicks::Now(); MaybeBeginDelivery(); } -void AppCacheURLRequestJob::Kill() { - if (!has_been_killed_) { - has_been_killed_ = true; - reader_.reset(); - handler_source_reader_.reset(); - if (storage_) { - storage_->CancelDelegateCallbacks(this); - storage_ = NULL; - } - host_ = NULL; - info_ = NULL; - cache_ = NULL; - group_ = NULL; - range_response_info_.reset(); - net::URLRequestJob::Kill(); - weak_factory_.InvalidateWeakPtrs(); - } -} - net::LoadState AppCacheURLRequestJob::GetLoadState() const { - if (!has_been_started()) + if (!IsStarted()) return net::LOAD_STATE_IDLE; if (!has_delivery_orders()) return net::LOAD_STATE_WAITING_FOR_APPCACHE; @@ -418,7 +445,7 @@ } int AppCacheURLRequestJob::ReadRawData(net::IOBuffer* buf, int buf_size) { - DCHECK(is_delivering_appcache_response()); + DCHECK(IsDeliveringAppCacheResponse()); DCHECK_NE(buf_size, 0); DCHECK(!reader_->IsReadPending()); reader_->ReadData(buf, buf_size,
diff --git a/content/browser/appcache/appcache_url_request_job.h b/content/browser/appcache/appcache_url_request_job.h index 3b6de0d..56b3cfa 100644 --- a/content/browser/appcache/appcache_url_request_job.h +++ b/content/browser/appcache/appcache_url_request_job.h
@@ -10,9 +10,9 @@ #include <string> #include "base/callback.h" -#include "base/memory/weak_ptr.h" #include "content/browser/appcache/appcache_entry.h" #include "content/browser/appcache/appcache_executable_handler.h" +#include "content/browser/appcache/appcache_job.h" #include "content/browser/appcache/appcache_response.h" #include "content/browser/appcache/appcache_storage.h" #include "content/common/content_export.h" @@ -30,49 +30,33 @@ // A net::URLRequestJob derivative that knows how to return a response stored // in the appcache. -class CONTENT_EXPORT AppCacheURLRequestJob - : public net::URLRequestJob, - public AppCacheStorage::Delegate { +class CONTENT_EXPORT AppCacheURLRequestJob : public net::URLRequestJob, + public AppCacheStorage::Delegate, + public AppCacheJob { public: // Callback that will be invoked before the request is restarted. The caller // can use this opportunity to grab state from the AppCacheURLRequestJob to // determine how it should behave when the request is restarted. using OnPrepareToRestartCallback = base::Closure; - AppCacheURLRequestJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate, - AppCacheStorage* storage, - AppCacheHost* host, - bool is_main_resource, - const OnPrepareToRestartCallback& restart_callback_); - ~AppCacheURLRequestJob() override; - // Informs the job of what response it should deliver. Only one of these - // methods should be called, and only once per job. A job will sit idle and - // wait indefinitely until one of the deliver methods is called. + // AppCacheJob overrides. + void Kill() override; + bool IsStarted() const override; + bool IsWaiting() const override; + bool IsDeliveringAppCacheResponse() const override; + bool IsDeliveringNetworkResponse() const override; + bool IsDeliveringErrorResponse() const override; + bool IsCacheEntryNotFound() const override; void DeliverAppCachedResponse(const GURL& manifest_url, int64_t cache_id, const AppCacheEntry& entry, - bool is_fallback); - void DeliverNetworkResponse(); - void DeliverErrorResponse(); - - bool is_waiting() const { - return delivery_type_ == AWAITING_DELIVERY_ORDERS; - } - - bool is_delivering_appcache_response() const { - return delivery_type_ == APPCACHED_DELIVERY; - } - - bool is_delivering_network_response() const { - return delivery_type_ == NETWORK_DELIVERY; - } - - bool is_delivering_error_response() const { - return delivery_type_ == ERROR_DELIVERY; - } + bool is_fallback) override; + void DeliverNetworkResponse() override; + void DeliverErrorResponse() override; + const GURL& GetURL() const override; + net::URLRequestJob* AsURLRequestJob() override; // Accessors for the info about the appcached response, if any, // that this job has been instructed to deliver. These are only @@ -81,31 +65,23 @@ int64_t cache_id() const { return cache_id_; } const AppCacheEntry& entry() const { return entry_; } - // net::URLRequestJob's Kill method is made public so the users of this - // class in the appcache namespace can call it. - void Kill() override; - - // Returns true if the job has been started by the net library. - bool has_been_started() const { - return has_been_started_; - } - // Returns true if the job has been killed. bool has_been_killed() const { return has_been_killed_; } - // Returns true if the cache entry was not found in the disk cache. - bool cache_entry_not_found() const { - return cache_entry_not_found_; - } - private: friend class AppCacheRequestHandlerTest; friend class AppCacheURLRequestJobTest; + // AppCacheJob::Create() creates this instance. + friend class AppCacheJob; - // Friend so it can get a weak pointer. - friend class AppCacheRequestHandler; + AppCacheURLRequestJob(net::URLRequest* request, + net::NetworkDelegate* network_delegate, + AppCacheStorage* storage, + AppCacheHost* host, + bool is_main_resource, + const OnPrepareToRestartCallback& restart_callback_); enum DeliveryType { AWAITING_DELIVERY_ORDERS, @@ -114,12 +90,8 @@ ERROR_DELIVERY }; - base::WeakPtr<AppCacheURLRequestJob> GetWeakPtr(); - // Returns true if one of the Deliver methods has been called. - bool has_delivery_orders() const { - return !is_waiting(); - } + bool has_delivery_orders() const { return !IsWaiting(); } void MaybeBeginDelivery(); void BeginDelivery(); @@ -184,7 +156,6 @@ scoped_refptr<AppCache> cache_; scoped_refptr<AppCacheGroup> group_; const OnPrepareToRestartCallback on_prepare_to_restart_callback_; - base::WeakPtrFactory<AppCacheURLRequestJob> weak_factory_; }; } // namespace content
diff --git a/content/browser/appcache/appcache_url_request_job_unittest.cc b/content/browser/appcache/appcache_url_request_job_unittest.cc index f29607db..eb2ea07 100644 --- a/content/browser/appcache/appcache_url_request_job_unittest.cc +++ b/content/browser/appcache/appcache_url_request_job_unittest.cc
@@ -466,11 +466,11 @@ std::unique_ptr<AppCacheURLRequestJob> job( new AppCacheURLRequestJob(request_.get(), nullptr, storage, nullptr, false, base::Bind(&ExpectNotRestarted))); - EXPECT_TRUE(job->is_waiting()); - EXPECT_FALSE(job->is_delivering_appcache_response()); - EXPECT_FALSE(job->is_delivering_network_response()); - EXPECT_FALSE(job->is_delivering_error_response()); - EXPECT_FALSE(job->has_been_started()); + EXPECT_TRUE(job->IsWaiting()); + EXPECT_FALSE(job->IsDeliveringAppCacheResponse()); + EXPECT_FALSE(job->IsDeliveringNetworkResponse()); + EXPECT_FALSE(job->IsDeliveringErrorResponse()); + EXPECT_FALSE(job->IsStarted()); EXPECT_FALSE(job->has_been_killed()); EXPECT_EQ(GURL(), job->manifest_url()); EXPECT_EQ(kAppCacheNoCacheId, job->cache_id()); @@ -492,15 +492,15 @@ new AppCacheURLRequestJob(request.get(), nullptr, storage, nullptr, false, base::Bind(&ExpectNotRestarted))); job->DeliverErrorResponse(); - EXPECT_TRUE(job->is_delivering_error_response()); - EXPECT_FALSE(job->has_been_started()); + EXPECT_TRUE(job->IsDeliveringErrorResponse()); + EXPECT_FALSE(job->IsStarted()); job.reset(new AppCacheURLRequestJob(request.get(), nullptr, storage, nullptr, false, base::Bind(&ExpectNotRestarted))); job->DeliverNetworkResponse(); - EXPECT_TRUE(job->is_delivering_network_response()); - EXPECT_FALSE(job->has_been_started()); + EXPECT_TRUE(job->IsDeliveringNetworkResponse()); + EXPECT_FALSE(job->IsStarted()); job.reset(new AppCacheURLRequestJob(request.get(), nullptr, storage, nullptr, false, @@ -509,9 +509,9 @@ const int64_t kCacheId(1); const AppCacheEntry kEntry(AppCacheEntry::EXPLICIT, 1); job->DeliverAppCachedResponse(kManifestUrl, kCacheId, kEntry, false); - EXPECT_FALSE(job->is_waiting()); - EXPECT_TRUE(job->is_delivering_appcache_response()); - EXPECT_FALSE(job->has_been_started()); + EXPECT_FALSE(job->IsWaiting()); + EXPECT_TRUE(job->IsDeliveringAppCacheResponse()); + EXPECT_FALSE(job->IsStarted()); EXPECT_EQ(kManifestUrl, job->manifest_url()); EXPECT_EQ(kCacheId, job->cache_id()); EXPECT_EQ(kEntry.types(), job->entry().types()); @@ -539,8 +539,8 @@ request_.get(), nullptr, storage, nullptr, false, base::Bind(&SetIfCalled, &restart_callback_invoked_))); mock_job->DeliverNetworkResponse(); - EXPECT_TRUE(mock_job->is_delivering_network_response()); - EXPECT_FALSE(mock_job->has_been_started()); + EXPECT_TRUE(mock_job->IsDeliveringNetworkResponse()); + EXPECT_FALSE(mock_job->IsStarted()); job_factory_->SetJob(std::move(mock_job)); // Start the request. @@ -577,8 +577,8 @@ new AppCacheURLRequestJob(request_.get(), nullptr, storage, nullptr, false, base::Bind(&ExpectNotRestarted))); mock_job->DeliverErrorResponse(); - EXPECT_TRUE(mock_job->is_delivering_error_response()); - EXPECT_FALSE(mock_job->has_been_started()); + EXPECT_TRUE(mock_job->IsDeliveringErrorResponse()); + EXPECT_FALSE(mock_job->IsStarted()); job_factory_->SetJob(std::move(mock_job)); // Start the request. @@ -633,24 +633,24 @@ job->DeliverAppCachedResponse( GURL(), 111, AppCacheEntry(AppCacheEntry::EXPLICIT, written_response_id_), false); - EXPECT_TRUE(job->is_delivering_appcache_response()); + EXPECT_TRUE(job->IsDeliveringAppCacheResponse()); } // Start the request. - EXPECT_FALSE(job->has_been_started()); - base::WeakPtr<AppCacheURLRequestJob> weak_job = job->GetWeakPtr(); + EXPECT_FALSE(job->IsStarted()); + base::WeakPtr<AppCacheJob> weak_job = job->GetWeakPtr(); job_factory_->SetJob(std::move(job)); request_->Start(); EXPECT_FALSE(job_factory_->has_job()); ASSERT_TRUE(weak_job); - EXPECT_TRUE(weak_job->has_been_started()); + EXPECT_TRUE(weak_job->IsStarted()); if (!start_after_delivery_orders) { weak_job->DeliverAppCachedResponse( GURL(), 111, AppCacheEntry(AppCacheEntry::EXPLICIT, written_response_id_), false); ASSERT_TRUE(weak_job); - EXPECT_TRUE(weak_job->is_delivering_appcache_response()); + EXPECT_TRUE(weak_job->IsDeliveringAppCacheResponse()); } // Completion is async. @@ -751,10 +751,10 @@ job->DeliverAppCachedResponse( GURL(), 111, AppCacheEntry(AppCacheEntry::EXPLICIT, written_response_id_), false); - EXPECT_TRUE(job->is_delivering_appcache_response()); + EXPECT_TRUE(job->IsDeliveringAppCacheResponse()); // Start the request. - EXPECT_FALSE(job->has_been_started()); + EXPECT_FALSE(job->IsStarted()); job_factory_->SetJob(std::move(job)); request_->Start(); EXPECT_FALSE(job_factory_->has_job());
diff --git a/content/browser/frame_host/render_frame_host_delegate.cc b/content/browser/frame_host/render_frame_host_delegate.cc index 4d0a8ea5..fab177f 100644 --- a/content/browser/frame_host/render_frame_host_delegate.cc +++ b/content/browser/frame_host/render_frame_host_delegate.cc
@@ -77,8 +77,7 @@ return nullptr; } -device::mojom::WakeLockContext* -RenderFrameHostDelegate::GetWakeLockServiceContext() { +device::mojom::WakeLockService* RenderFrameHostDelegate::GetRendererWakeLock() { return nullptr; }
diff --git a/content/browser/frame_host/render_frame_host_delegate.h b/content/browser/frame_host/render_frame_host_delegate.h index 120e18e..92f6c2b 100644 --- a/content/browser/frame_host/render_frame_host_delegate.h +++ b/content/browser/frame_host/render_frame_host_delegate.h
@@ -18,6 +18,7 @@ #include "content/public/browser/site_instance.h" #include "content/public/common/javascript_dialog_type.h" #include "content/public/common/media_stream_request.h" +#include "device/wake_lock/public/interfaces/wake_lock_service.mojom.h" #include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h" #include "net/http/http_response_headers.h" #include "ui/base/window_open_disposition.h" @@ -38,10 +39,6 @@ namespace device { class GeolocationServiceContext; - -namespace mojom { -class WakeLockContext; -} } namespace gfx { @@ -194,8 +191,8 @@ // Gets the GeolocationServiceContext associated with this delegate. virtual device::GeolocationServiceContext* GetGeolocationServiceContext(); - // Gets the WakeLockServiceContext associated with this delegate. - virtual device::mojom::WakeLockContext* GetWakeLockServiceContext(); + // Gets the WakeLockService that serves wake lock requests from the renderer. + virtual device::mojom::WakeLockService* GetRendererWakeLock(); // Notification that the frame wants to go into fullscreen mode. // |origin| represents the origin of the frame that requests fullscreen.
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index 8908381e..42f550f0 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -58,6 +58,7 @@ #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/browser/shared_worker/shared_worker_service_impl.h" #include "content/browser/websockets/websocket_manager.h" +#include "content/browser/webui/url_data_manager_backend.h" #include "content/browser/webui/web_ui_controller_factory_registry.h" #include "content/browser/webui/web_ui_url_loader_factory.h" #include "content/common/accessibility_messages.h" @@ -3050,14 +3051,15 @@ commit_data.handle = handle.release(); // TODO(scottmg): Pass a factory for SW, etc. once we have one. if (base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kEnableNetworkService) && - common_params.url.SchemeIs(kChromeUIScheme)) { - commit_data.url_loader_factory = GetWebUIURLLoader(frame_tree_node_) - .PassInterface() - .PassHandle() - .release(); - } else { - commit_data.url_loader_factory = mojo::MessagePipeHandle(); + switches::kEnableNetworkService)) { + const auto& schemes = URLDataManagerBackend::GetWebUISchemes(); + if (std::find(schemes.begin(), schemes.end(), common_params.url.scheme()) != + schemes.end()) { + commit_data.url_loader_factory = GetWebUIURLLoader(frame_tree_node_) + .PassInterface() + .PassHandle() + .release(); + } } Send(new FrameMsg_CommitNavigation(routing_id_, head, body_url, commit_data, common_params, request_params)); @@ -3731,10 +3733,10 @@ void RenderFrameHostImpl::BindWakeLockServiceRequest( const service_manager::BindSourceInfo& source_info, device::mojom::WakeLockServiceRequest request) { - device::mojom::WakeLockContext* wake_lock_service_context = - delegate_ ? delegate_->GetWakeLockServiceContext() : nullptr; - if (wake_lock_service_context) - wake_lock_service_context->GetWakeLock(std::move(request)); + device::mojom::WakeLockService* renderer_wake_lock = + delegate_ ? delegate_->GetRendererWakeLock() : nullptr; + if (renderer_wake_lock) + renderer_wake_lock->AddClient(std::move(request)); } void RenderFrameHostImpl::GetInterface(
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 1acf57f..31a2bd2 100644 --- a/content/browser/frame_host/render_frame_host_manager_browsertest.cc +++ b/content/browser/frame_host/render_frame_host_manager_browsertest.cc
@@ -1295,87 +1295,11 @@ EXPECT_EQ(orig_site_instance, new_site_instance); } -// A collection of tests to prevent URL spoofs when showing pending URLs above -// initial empty documents, ensuring that the URL reverts to about:blank if the -// document is accessed. See https://crbug.com/9682. -class RenderFrameHostManagerSpoofingTest : public RenderFrameHostManagerTest { - public: - void SetUpInProcessBrowserTestFixture() override { - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - - base::CommandLine new_command_line(command_line->GetProgram()); - base::CommandLine::SwitchMap switches = command_line->GetSwitches(); - - // Injecting the DOM automation controller causes false positives, since it - // triggers the DidAccessInitialDocument() callback by mutating the global - // object. - switches.erase(switches::kDomAutomationController); - - for (const auto& it : switches) - new_command_line.AppendSwitchNative(it.first, it.second); - - *command_line = new_command_line; - } - - protected: - // Custom ExecuteScript() helper that doesn't depend on DOM automation - // controller. This is used to guarantee the script has completed execution, - // but the spoofing tests synchronize execution using window title changes. - void ExecuteScript(const ToRenderFrameHost& adapter, const char* script) { - adapter.render_frame_host()->ExecuteJavaScriptForTests( - base::UTF8ToUTF16(script)); - } -}; - -// Sanity test that a newly opened window shows the pending URL if the initial -// empty document is not modified. This is intentionally structured as similarly -// as possible to the subsequent ShowLoadingURLUntil*Spoof tests: it performs -// the same operations as the subsequent tests except DOM modification. This -// should help catch instances where the subsequent tests incorrectly pass due -// to a side effect of the test infrastructure. -IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerSpoofingTest, - ShowLoadingURLIfNotModified) { - ASSERT_TRUE(embedded_test_server()->Start()); - - // Load a page that can open a URL that won't commit in a new window. - NavigateToURL(shell(), - embedded_test_server()->GetURL("/click-nocontent-link.html")); - WebContents* orig_contents = shell()->web_contents(); - - // Click a /nocontent link that opens in a new window but never commits. - ShellAddedObserver new_shell_observer; - ExecuteScript(orig_contents, "clickNoContentTargetedLink();"); - - // Wait for the window to open. - Shell* new_shell = new_shell_observer.GetShell(); - - // Ensure the destination URL is visible, because it is considered the - // initial navigation. - WebContents* contents = new_shell->web_contents(); - EXPECT_TRUE(contents->GetController().IsInitialNavigation()); - EXPECT_EQ("/nocontent", - contents->GetController().GetVisibleEntry()->GetURL().path()); - - // Now get another reference to the window object, but don't otherwise access - // it. This is to ensure that DidAccessInitialDocument() notifications are not - // incorrectly generated when nothing is modified. - base::string16 expected_title = ASCIIToUTF16("Modified Title"); - TitleWatcher title_watcher(orig_contents, expected_title); - ExecuteScript(orig_contents, "getNewWindowReference();"); - ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle()); - - // The destination URL should still be visible, since nothing was modified. - EXPECT_TRUE(contents->GetController().IsInitialNavigation()); - EXPECT_EQ("/nocontent", - contents->GetController().GetVisibleEntry()->GetURL().path()); -} - // Test for crbug.com/9682. We should show the URL for a pending renderer- // initiated navigation in a new tab, until the content of the initial // about:blank page is modified by another window. At that point, we should // revert to showing about:blank to prevent a URL spoof. -IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerSpoofingTest, - ShowLoadingURLUntilSpoof) { +IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, ShowLoadingURLUntilSpoof) { ASSERT_TRUE(embedded_test_server()->Start()); // Load a page that can open a URL that won't commit in a new window. @@ -1385,7 +1309,12 @@ // Click a /nocontent link that opens in a new window but never commits. ShellAddedObserver new_shell_observer; - ExecuteScript(orig_contents, "clickNoContentTargetedLink();"); + bool success = false; + EXPECT_TRUE(ExecuteScriptAndExtractBool( + orig_contents, + "window.domAutomationController.send(clickNoContentTargetedLink());", + &success)); + EXPECT_TRUE(success); // Wait for the window to open. Shell* new_shell = new_shell_observer.GetShell(); @@ -1400,52 +1329,13 @@ // Now modify the contents of the new window from the opener. This will also // modify the title of the document to give us something to listen for. base::string16 expected_title = ASCIIToUTF16("Modified Title"); - TitleWatcher title_watcher(orig_contents, expected_title); - ExecuteScript(orig_contents, "modifyNewWindow();"); - ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle()); - - // At this point, we should no longer be showing the destination URL. - // The visible entry should be null, resulting in about:blank in the address - // bar. - EXPECT_FALSE(contents->GetController().GetVisibleEntry()); -} - -// Similar but using document.open(): once a Document is opened, subsequent -// document.write() calls can insert arbitrary content into the target Document. -// Since this could result in URL spoofing, the pending URL should no longer be -// shown in the omnibox. -// -// Note: document.write() implicitly invokes document.open() if the Document has -// not already been opened, so there's no need to test document.write() -// separately. -IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerSpoofingTest, - ShowLoadingURLUntilDocumentOpenSpoof) { - ASSERT_TRUE(embedded_test_server()->Start()); - - // Load a page that can open a URL that won't commit in a new window. - NavigateToURL(shell(), - embedded_test_server()->GetURL("/click-nocontent-link.html")); - WebContents* orig_contents = shell()->web_contents(); - - // Click a /nocontent link that opens in a new window but never commits. - ShellAddedObserver new_shell_observer; - ExecuteScript(orig_contents, "clickNoContentTargetedLink();"); - - // Wait for the window to open. - Shell* new_shell = new_shell_observer.GetShell(); - - // Ensure the destination URL is visible, because it is considered the - // initial navigation. - WebContents* contents = new_shell->web_contents(); - EXPECT_TRUE(contents->GetController().IsInitialNavigation()); - EXPECT_EQ("/nocontent", - contents->GetController().GetVisibleEntry()->GetURL().path()); - - // Now modify the contents of the new window from the opener. This will also - // modify the title of the document to give us something to listen for. - base::string16 expected_title = ASCIIToUTF16("Modified Title"); - TitleWatcher title_watcher(orig_contents, expected_title); - ExecuteScript(orig_contents, "modifyNewWindowWithDocumentOpen();"); + TitleWatcher title_watcher(contents, expected_title); + success = false; + EXPECT_TRUE(ExecuteScriptAndExtractBool( + orig_contents, + "window.domAutomationController.send(modifyNewWindow());", + &success)); + EXPECT_TRUE(success); ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle()); // At this point, we should no longer be showing the destination URL.
diff --git a/content/browser/loader/navigation_url_loader_network_service.cc b/content/browser/loader/navigation_url_loader_network_service.cc index e82a39da..be7fcf1 100644 --- a/content/browser/loader/navigation_url_loader_network_service.cc +++ b/content/browser/loader/navigation_url_loader_network_service.cc
@@ -15,6 +15,7 @@ #include "content/browser/loader/navigation_resource_handler.h" #include "content/browser/loader/navigation_resource_throttle.h" #include "content/browser/loader/navigation_url_loader_delegate.h" +#include "content/browser/webui/url_data_manager_backend.h" #include "content/browser/webui/web_ui_url_loader_factory.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/global_request_id.h" @@ -214,7 +215,9 @@ // This is fine for now since the only user of this is WebUI which doesn't // need this, but we'll have to fix this when other consumers come up. mojom::URLLoaderFactoryPtr factory_ptr; - if (request->url.SchemeIs(kChromeUIScheme)) { + const auto& schemes = URLDataManagerBackend::GetWebUISchemes(); + if (std::find(schemes.begin(), schemes.end(), request->url.scheme()) != + schemes.end()) { FrameTreeNode* frame_tree_node = FrameTreeNode::GloballyFindByID(request_info_->frame_tree_node_id); factory_ptr = GetWebUIURLLoader(frame_tree_node);
diff --git a/content/browser/storage_partition_impl_map.cc b/content/browser/storage_partition_impl_map.cc index e71456af..40004a9 100644 --- a/content/browser/storage_partition_impl_map.cc +++ b/content/browser/storage_partition_impl_map.cc
@@ -415,23 +415,12 @@ linked_ptr<net::URLRequestJobFactory::ProtocolHandler>( CreateFileSystemProtocolHandler(partition_domain, partition->GetFileSystemContext())); - protocol_handlers[kChromeUIScheme] = - linked_ptr<net::URLRequestJobFactory::ProtocolHandler>( - URLDataManagerBackend::CreateProtocolHandler( - browser_context_->GetResourceContext(), - blob_storage_context).release()); - std::vector<std::string> additional_webui_schemes; - GetContentClient()->browser()->GetAdditionalWebUISchemes( - &additional_webui_schemes); - for (std::vector<std::string>::const_iterator it = - additional_webui_schemes.begin(); - it != additional_webui_schemes.end(); - ++it) { - protocol_handlers[*it] = + for (const auto& scheme : URLDataManagerBackend::GetWebUISchemes()) { + protocol_handlers[scheme] = linked_ptr<net::URLRequestJobFactory::ProtocolHandler>( URLDataManagerBackend::CreateProtocolHandler( - browser_context_->GetResourceContext(), - blob_storage_context).release()); + browser_context_->GetResourceContext(), blob_storage_context) + .release()); } protocol_handlers[kChromeDevToolsScheme] =
diff --git a/content/browser/wake_lock/wake_lock_browsertest.cc b/content/browser/wake_lock/wake_lock_browsertest.cc index fee42cae..cae2296 100644 --- a/content/browser/wake_lock/wake_lock_browsertest.cc +++ b/content/browser/wake_lock/wake_lock_browsertest.cc
@@ -66,15 +66,15 @@ return GetNestedFrameNode()->current_frame_host(); } - device::mojom::WakeLockContext* GetWakeLockServiceContext() { - return GetWebContentsImpl()->GetWakeLockServiceContext(); + device::mojom::WakeLockService* GetRendererWakeLock() { + return GetWebContentsImpl()->GetRendererWakeLock(); } bool HasWakeLock() { bool has_wakelock = false; base::RunLoop run_loop; - GetWakeLockServiceContext()->HasWakeLockForTests( + GetRendererWakeLock()->HasWakeLockForTests( base::Bind(&OnHasWakeLock, &has_wakelock)); run_loop.Run(); return has_wakelock;
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index a107c23..6cee92c 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -2622,12 +2622,26 @@ return geolocation_service_context_.get(); } -device::mojom::WakeLockContext* WebContentsImpl::GetWakeLockServiceContext() { +device::mojom::WakeLockContext* WebContentsImpl::GetWakeLockContext() { if (!wake_lock_context_host_) wake_lock_context_host_.reset(new WakeLockContextHost(this)); return wake_lock_context_host_->GetWakeLockContext(); } +device::mojom::WakeLockService* WebContentsImpl::GetRendererWakeLock() { + // WebContents creates a long-lived connection to one WakeLockServiceImpl. + // All the frames' requests will be added into the BindingSet of + // WakeLockServiceImpl via this connection. + if (!renderer_wake_lock_) { + device::mojom::WakeLockContext* wake_lock_context = GetWakeLockContext(); + if (!wake_lock_context) { + return nullptr; + } + wake_lock_context->GetWakeLock(mojo::MakeRequest(&renderer_wake_lock_)); + } + return renderer_wake_lock_.get(); +} + void WebContentsImpl::OnShowValidationMessage( RenderViewHostImpl* source, const gfx::Rect& anchor_in_root_view,
diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h index d198927..6918f5fe 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h
@@ -44,7 +44,7 @@ #include "content/public/common/renderer_preferences.h" #include "content/public/common/resource_type.h" #include "content/public/common/three_d_api_types.h" -#include "device/wake_lock/public/interfaces/wake_lock_context.mojom.h" +#include "device/wake_lock/public/interfaces/wake_lock_service.mojom.h" #include "net/base/load_states.h" #include "net/http/http_response_headers.h" #include "ppapi/features/features.h" @@ -506,7 +506,8 @@ RenderFrameHost* render_frame_host, int browser_plugin_instance_id) override; device::GeolocationServiceContext* GetGeolocationServiceContext() override; - device::mojom::WakeLockContext* GetWakeLockServiceContext() override; + device::mojom::WakeLockContext* GetWakeLockContext() override; + device::mojom::WakeLockService* GetRendererWakeLock() override; void EnterFullscreenMode(const GURL& origin) override; void ExitFullscreenMode(bool will_cause_resize) override; bool ShouldRouteMessageEvent( @@ -1511,6 +1512,8 @@ std::unique_ptr<WakeLockContextHost> wake_lock_context_host_; + device::mojom::WakeLockServicePtr renderer_wake_lock_; + std::unique_ptr<ScreenOrientationProvider> screen_orientation_provider_; std::unique_ptr<ManifestManagerHost> manifest_manager_host_;
diff --git a/content/browser/webui/url_data_manager_backend.cc b/content/browser/webui/url_data_manager_backend.cc index fa7c08d9..fabcd98 100644 --- a/content/browser/webui/url_data_manager_backend.cc +++ b/content/browser/webui/url_data_manager_backend.cc
@@ -701,6 +701,13 @@ path->assign(spec.substr(offset)); } +std::vector<std::string> URLDataManagerBackend::GetWebUISchemes() { + std::vector<std::string> schemes; + schemes.push_back(kChromeUIScheme); + GetContentClient()->browser()->GetAdditionalWebUISchemes(&schemes); + return schemes; +} + namespace { class DevToolsJobFactory
diff --git a/content/browser/webui/url_data_manager_backend.h b/content/browser/webui/url_data_manager_backend.h index 6c706fdd..171d723 100644 --- a/content/browser/webui/url_data_manager_backend.h +++ b/content/browser/webui/url_data_manager_backend.h
@@ -77,6 +77,10 @@ // path is the remaining portion after the scheme and hostname. static void URLToRequestPath(const GURL& url, std::string* path); + // Returns the schemes that are used by WebUI (i.e. the set from content and + // its embedder). + static std::vector<std::string> GetWebUISchemes(); + private: friend class URLRequestChromeJob;
diff --git a/content/public/browser/BUILD.gn b/content/public/browser/BUILD.gn index 2775d68..6d7dc27 100644 --- a/content/public/browser/BUILD.gn +++ b/content/public/browser/BUILD.gn
@@ -313,6 +313,7 @@ "//content/browser", # Must not be public_deps! "//device/geolocation", "//device/power_save_blocker", + "//device/wake_lock/public/interfaces", "//gpu", "//media", "//net",
diff --git a/content/public/browser/DEPS b/content/public/browser/DEPS index e779c4c..f2291a9 100644 --- a/content/public/browser/DEPS +++ b/content/public/browser/DEPS
@@ -1,6 +1,7 @@ include_rules = [ "+components/payments/mojom/payment_app.mojom.h", "+device/screen_orientation/public/interfaces", + "+device/wake_lock/public/interfaces", ] specific_include_rules = {
diff --git a/content/public/browser/web_contents.h b/content/public/browser/web_contents.h index 2d788807..ebd18a0 100644 --- a/content/public/browser/web_contents.h +++ b/content/public/browser/web_contents.h
@@ -44,6 +44,12 @@ struct WebFindOptions; } +namespace device { +namespace mojom { +class WakeLockContext; +} +} + namespace net { struct LoadStateWithParam; } @@ -674,6 +680,9 @@ // otherwise. virtual WebContents* GetOriginalOpener() const = 0; + // Returns the WakeLockContext accociated with this WebContents. + virtual device::mojom::WakeLockContext* GetWakeLockContext() = 0; + typedef base::Callback<void( int, /* id */ int, /* HTTP status code */
diff --git a/content/renderer/accessibility/blink_ax_tree_source.cc b/content/renderer/accessibility/blink_ax_tree_source.cc index 5b71ff8..c92c61a 100644 --- a/content/renderer/accessibility/blink_ax_tree_source.cc +++ b/content/renderer/accessibility/blink_ax_tree_source.cc
@@ -630,7 +630,7 @@ dst->AddBoolAttribute(ui::AX_ATTR_LIVE_ATOMIC, src.LiveRegionAtomic()); dst->AddBoolAttribute(ui::AX_ATTR_LIVE_BUSY, src.LiveRegionBusy()); if (src.LiveRegionBusy()) - dst->state |= (1 << ui::AX_STATE_BUSY); + dst->AddState(ui::AX_STATE_BUSY); if (!src.LiveRegionStatus().IsEmpty()) { dst->AddStringAttribute(ui::AX_ATTR_LIVE_STATUS, src.LiveRegionStatus().Utf8());
diff --git a/content/renderer/media/cdm/ppapi_decryptor.cc b/content/renderer/media/cdm/ppapi_decryptor.cc index bfca0d1..cdc7f3f1 100644 --- a/content/renderer/media/cdm/ppapi_decryptor.cc +++ b/content/renderer/media/cdm/ppapi_decryptor.cc
@@ -396,7 +396,7 @@ } void PpapiDecryptor::OnSessionMessage(const std::string& session_id, - MessageType message_type, + media::CdmMessageType message_type, const std::vector<uint8_t>& message) { DCHECK(render_task_runner_->BelongsToCurrentThread()); session_message_cb_.Run(session_id, message_type, message);
diff --git a/content/renderer/media/cdm/ppapi_decryptor.h b/content/renderer/media/cdm/ppapi_decryptor.h index 107c655d..2ae10ed6 100644 --- a/content/renderer/media/cdm/ppapi_decryptor.h +++ b/content/renderer/media/cdm/ppapi_decryptor.h
@@ -114,7 +114,7 @@ // Callbacks for |plugin_cdm_delegate_| to fire session events. void OnSessionMessage(const std::string& session_id, - ContentDecryptionModule::MessageType message_type, + media::CdmMessageType message_type, const std::vector<uint8_t>& message); void OnSessionKeysChange(const std::string& session_id, bool has_additional_usable_key,
diff --git a/content/renderer/pepper/content_decryptor_delegate.cc b/content/renderer/pepper/content_decryptor_delegate.cc index a28e2a7..36a102a 100644 --- a/content/renderer/pepper/content_decryptor_delegate.cc +++ b/content/renderer/pepper/content_decryptor_delegate.cc
@@ -35,6 +35,7 @@ #include "ppapi/thunk/ppb_buffer_api.h" #include "ui/gfx/geometry/rect.h" +using media::CdmMessageType; using media::CdmPromise; using media::CdmSessionType; using media::ContentDecryptionModule; @@ -347,18 +348,18 @@ } } -ContentDecryptionModule::MessageType PpCdmMessageTypeToMediaMessageType( +CdmMessageType PpCdmMessageTypeToMediaMessageType( PP_CdmMessageType message_type) { switch (message_type) { case PP_CDMMESSAGETYPE_LICENSE_REQUEST: - return ContentDecryptionModule::LICENSE_REQUEST; + return CdmMessageType::LICENSE_REQUEST; case PP_CDMMESSAGETYPE_LICENSE_RENEWAL: - return ContentDecryptionModule::LICENSE_RENEWAL; + return CdmMessageType::LICENSE_RENEWAL; case PP_CDMMESSAGETYPE_LICENSE_RELEASE: - return ContentDecryptionModule::LICENSE_RELEASE; + return CdmMessageType::LICENSE_RELEASE; default: NOTREACHED(); - return ContentDecryptionModule::LICENSE_REQUEST; + return CdmMessageType::LICENSE_REQUEST; } }
diff --git a/content/shell/test_runner/mock_web_document_subresource_filter.cc b/content/shell/test_runner/mock_web_document_subresource_filter.cc index 04274a7..6d338c6 100644 --- a/content/shell/test_runner/mock_web_document_subresource_filter.cc +++ b/content/shell/test_runner/mock_web_document_subresource_filter.cc
@@ -46,4 +46,8 @@ void MockWebDocumentSubresourceFilter::ReportDisallowedLoad() {} +bool MockWebDocumentSubresourceFilter::ShouldLogToConsole() { + return false; +} + } // namespace test_runner
diff --git a/content/shell/test_runner/mock_web_document_subresource_filter.h b/content/shell/test_runner/mock_web_document_subresource_filter.h index 37047df..c1aff78 100644 --- a/content/shell/test_runner/mock_web_document_subresource_filter.h +++ b/content/shell/test_runner/mock_web_document_subresource_filter.h
@@ -31,6 +31,7 @@ LoadPolicy GetLoadPolicyForWebSocketConnect( const blink::WebURL& url) override; void ReportDisallowedLoad() override; + bool ShouldLogToConsole() override; private: LoadPolicy getLoadPolicyImpl(const blink::WebURL& url);
diff --git a/content/test/data/click-nocontent-link.html b/content/test/data/click-nocontent-link.html index 893a639..e60b5138 100644 --- a/content/test/data/click-nocontent-link.html +++ b/content/test/data/click-nocontent-link.html
@@ -20,44 +20,17 @@ "nocontent_scripted_targeted_link")); } - function getNewWindowReference() { - // Grab a reference to the existing foo window, but don't otherwise access - // it in any way. - var w = window.open("", "foo"); - // w is intentionally unused after this point to avoid triggering a call to - // DidAccessInitialDocument(). - - // Modify the title to give the test a notification to listen for. Use a - // timeout so that any DidAccessInitialDocument() notification arrives - // first. Note that this intentionally uses |window| instead of |w| to avoid - // test boilerplate from triggering calls to DidAccessInitialDocument(). - setTimeout(function() { window.document.title = "Modified Title"; }); - } - + var w; function modifyNewWindow() { // Grab a reference to the existing foo window and modify its content. - var w = window.open("", "foo"); + w = window.open("", "foo"); w.document.body.innerHTML += "Modified"; - // Modify the title to give the test a notification to listen for. Use a - // timeout so that any DidAccessInitialDocument() notification arrives - // first. Note that this intentionally uses |window| instead of |w| to avoid - // test boilerplate from triggering calls to DidAccessInitialDocument(). - setTimeout(function() { window.document.title = "Modified Title"; }); - } - - function modifyNewWindowWithDocumentOpen() { - // Grab a reference to the existing foo window and modify its content. - var w = window.open("", "foo"); - w.document.open(); - w.document.write("Modified"); - w.document.close(); - - // Modify the title to give the test a notification to listen for. Use a - // timeout so that any DidAccessInitialDocument() notification arrives - // first. Note that this intentionally uses |window| instead of |w| to avoid - // test boilerplate from triggering calls to DidAccessInitialDocument(). - setTimeout(function() { window.document.title = "Modified Title"; }); + // Also modify the title to give the test a notification to listen for. + // Use a timeout so that the didAccessInitialDocument notification arrives + // first. + setTimeout('w.document.title = "Modified Title"'); + return true; } </script> </head>
diff --git a/device/wake_lock/DEPS b/device/wake_lock/DEPS index b273ae3..93fe821 100644 --- a/device/wake_lock/DEPS +++ b/device/wake_lock/DEPS
@@ -1,3 +1,4 @@ include_rules = [ + "+device/power_save_blocker", "+ui/gfx", ]
diff --git a/device/wake_lock/public/interfaces/wake_lock_context.mojom b/device/wake_lock/public/interfaces/wake_lock_context.mojom index 24cd02f..bb01e64b 100644 --- a/device/wake_lock/public/interfaces/wake_lock_context.mojom +++ b/device/wake_lock/public/interfaces/wake_lock_context.mojom
@@ -10,8 +10,4 @@ interface WakeLockContext { // Gets a WakeLockService within this context. GetWakeLock(WakeLockService& wake_lock); - - // Test-only method that returns whethere a wake lock is currently active - // within this context. - HasWakeLockForTests() => (bool result); };
diff --git a/device/wake_lock/public/interfaces/wake_lock_service.mojom b/device/wake_lock/public/interfaces/wake_lock_service.mojom index 8c6e7a49..aa3b1da 100644 --- a/device/wake_lock/public/interfaces/wake_lock_service.mojom +++ b/device/wake_lock/public/interfaces/wake_lock_service.mojom
@@ -6,6 +6,23 @@ // WebLockService receives wake lock preferences from its client. interface WakeLockService { + // Requests that a wake lock be applied on behalf of this client. Has no + // effect if the client has previously called this method without + // subsequently calling CancelWakeLock(). RequestWakeLock(); + + // Cancels all outstanding wake lock requests from this client. If there are + // no more outstanding requests from any clients, the active wake lock (if + // there is one) will be turned off. CancelWakeLock(); + + // Adds a client to this WakeLockService instance. Clients are grouped on a + // per-WakeLockService instance basis: that is, a given WakeLockService + // instance turns on its wake lock whenever *any* of its clients make a + // request to do so and turns off its wake lock only when *all* its clients + // that had previously called RequestWakelock() cancel their requests. + AddClient(WakeLockService& wake_lock); + + // Test-only method that returns whether a wake lock is currently active. + HasWakeLockForTests() => (bool result); };
diff --git a/device/wake_lock/wake_lock_context_provider.cc b/device/wake_lock/wake_lock_context_provider.cc index 289b1c64..9d6543a7 100644 --- a/device/wake_lock/wake_lock_context_provider.cc +++ b/device/wake_lock/wake_lock_context_provider.cc
@@ -31,10 +31,10 @@ void WakeLockContextProvider::GetContext( int context_id, mojo::InterfaceRequest<mojom::WakeLockContext> request) { - // WakeLockServiceContext owns itself (see the comment on - // wake_lock_service_context.h). - new WakeLockServiceContext(std::move(request), context_id, file_task_runner_, - native_view_getter_); + mojo::MakeStrongBinding( + base::MakeUnique<WakeLockServiceContext>(context_id, file_task_runner_, + native_view_getter_), + std::move(request)); } } // namespace device
diff --git a/device/wake_lock/wake_lock_service_context.cc b/device/wake_lock/wake_lock_service_context.cc index b56680f..4652b33 100644 --- a/device/wake_lock/wake_lock_service_context.cc +++ b/device/wake_lock/wake_lock_service_context.cc
@@ -6,103 +6,30 @@ #include <utility> -#include "base/bind.h" -#include "base/memory/ptr_util.h" -#include "base/threading/thread_task_runner_handle.h" -#include "build/build_config.h" #include "device/power_save_blocker/power_save_blocker.h" +#include "device/wake_lock/wake_lock_service_impl.h" namespace device { WakeLockServiceContext::WakeLockServiceContext( - mojom::WakeLockContextRequest request, int context_id, scoped_refptr<base::SingleThreadTaskRunner> file_task_runner, const WakeLockContextCallback& native_view_getter) - : main_task_runner_(base::ThreadTaskRunnerHandle::Get()), - file_task_runner_(std::move(file_task_runner)), - num_lock_requests_(0), -#if defined(OS_ANDROID) + : file_task_runner_(std::move(file_task_runner)), context_id_(context_id), - native_view_getter_(native_view_getter), -#endif - context_binding_(this, std::move(request)), - context_binding_encountered_error_(false) { - context_binding_.set_connection_error_handler(base::Bind( - &WakeLockServiceContext::OnContextBindingError, base::Unretained(this))); - wake_lock_bindings_.set_connection_error_handler( - base::Bind(&WakeLockServiceContext::DestroyIfNoLongerNeeded, - base::Unretained(this))); -} + native_view_getter_(native_view_getter) {} WakeLockServiceContext::~WakeLockServiceContext() {} void WakeLockServiceContext::GetWakeLock( - mojo::InterfaceRequest<mojom::WakeLockService> request) { - wake_lock_bindings_.AddBinding(base::MakeUnique<WakeLockServiceImpl>(this), - std::move(request)); -} - -void WakeLockServiceContext::RequestWakeLock() { - DCHECK(main_task_runner_->RunsTasksOnCurrentThread()); - num_lock_requests_++; - UpdateWakeLock(); -} - -void WakeLockServiceContext::CancelWakeLock() { - DCHECK(main_task_runner_->RunsTasksOnCurrentThread()); - num_lock_requests_--; - UpdateWakeLock(); -} - -void WakeLockServiceContext::HasWakeLockForTests( - const HasWakeLockForTestsCallback& callback) { - callback.Run(!!wake_lock_); -} - -void WakeLockServiceContext::CreateWakeLock() { - DCHECK(!wake_lock_); - wake_lock_.reset(new device::PowerSaveBlocker( - device::PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep, - device::PowerSaveBlocker::kReasonOther, "Wake Lock API", - main_task_runner_, file_task_runner_)); - -#if defined(OS_ANDROID) - gfx::NativeView native_view = native_view_getter_.Run(context_id_); - if (native_view) { - wake_lock_.get()->InitDisplaySleepBlocker(native_view); - } -#endif -} - -void WakeLockServiceContext::RemoveWakeLock() { - DCHECK(wake_lock_); - wake_lock_.reset(); -} - -void WakeLockServiceContext::UpdateWakeLock() { - DCHECK(num_lock_requests_ >= 0); - if (num_lock_requests_) { - if (!wake_lock_) - CreateWakeLock(); - } else { - if (wake_lock_) - RemoveWakeLock(); - } -} - -void WakeLockServiceContext::OnContextBindingError() { - context_binding_encountered_error_ = true; - DestroyIfNoLongerNeeded(); -} - -void WakeLockServiceContext::DestroyIfNoLongerNeeded() { - if (context_binding_encountered_error_ && wake_lock_bindings_.empty()) { - // Delete this instance once there are no more live connections to it. - // However, ensure that this instance stays alive throughout the destructor - // of a WakeLockServiceImpl instance that might be triggering this callback. - base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); - } + mojom::WakeLockServiceRequest request) { + // WakeLockServiceImpl owns itself. + new WakeLockServiceImpl(std::move(request), + device::PowerSaveBlocker::PowerSaveBlockerType:: + kPowerSaveBlockPreventDisplaySleep, + device::PowerSaveBlocker::Reason::kReasonOther, + "Wake Lock API", context_id_, native_view_getter_, + file_task_runner_); } } // namespace device
diff --git a/device/wake_lock/wake_lock_service_context.h b/device/wake_lock/wake_lock_service_context.h index 0baa1a7..f5c5fd9 100644 --- a/device/wake_lock/wake_lock_service_context.h +++ b/device/wake_lock/wake_lock_service_context.h
@@ -6,86 +6,37 @@ #define DEVICE_WAKE_LOCK_WAKE_LOCK_SERVICE_CONTEXT_H_ #include <memory> -#include <set> #include <utility> #include "base/callback.h" -#include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/sequenced_task_runner.h" +#include "base/single_thread_task_runner.h" #include "device/wake_lock/public/interfaces/wake_lock_context.mojom.h" -#include "device/wake_lock/wake_lock_service_impl.h" -#include "mojo/public/cpp/bindings/binding.h" -#include "mojo/public/cpp/bindings/interface_request.h" -#include "mojo/public/cpp/bindings/strong_binding_set.h" #include "ui/gfx/native_widget_types.h" namespace device { -class PowerSaveBlocker; - // Callback that maps a context ID to the NativeView associated with // that context. This callback is provided to the Device Service by its // embedder. using WakeLockContextCallback = base::Callback<gfx::NativeView(int)>; // Serves requests for WakeLockService connections within a given context. - -// Note that the lifetime model of WakeLockContext is somewhat complex: It must -// stay alive as long as either -// (1) Its Mojo connection is still valid (as the client might make future -// GetWakeLock() calls) OR -// (2) There are still live WakeLock instances that it has instantiated (since -// they call into it when they receive Mojo requests from *their* clients). -// Consequently, WakeLockContext monitors the state of the connections described -// in (1) and (2), dying only when *all* of those connections go away. class WakeLockServiceContext : public mojom::WakeLockContext { public: WakeLockServiceContext( - mojom::WakeLockContextRequest request, int context_id, scoped_refptr<base::SingleThreadTaskRunner> file_task_runner, const WakeLockContextCallback& native_view_getter); ~WakeLockServiceContext() override; // mojom::WakeLockContext: - void GetWakeLock( - mojo::InterfaceRequest<mojom::WakeLockService> request) override; - void HasWakeLockForTests( - const HasWakeLockForTestsCallback& callback) override; - - // Requests wake lock. - void RequestWakeLock(); - - // Cancels pending wake lock request. - void CancelWakeLock(); + void GetWakeLock(mojom::WakeLockServiceRequest request) override; private: - void CreateWakeLock(); - void RemoveWakeLock(); - void UpdateWakeLock(); - void OnContextBindingError(); - - // Checks whether this instance is still needed, and if not, destroys it. - void DestroyIfNoLongerNeeded(); - - scoped_refptr<base::SequencedTaskRunner> main_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> file_task_runner_; - - int num_lock_requests_; - - // The actual power save blocker for screen. - std::unique_ptr<PowerSaveBlocker> wake_lock_; - -#if defined(OS_ANDROID) int context_id_; WakeLockContextCallback native_view_getter_; -#endif - - mojo::Binding<mojom::WakeLockContext> context_binding_; - bool context_binding_encountered_error_; - - mojo::StrongBindingSet<mojom::WakeLockService> wake_lock_bindings_; DISALLOW_COPY_AND_ASSIGN(WakeLockServiceContext); };
diff --git a/device/wake_lock/wake_lock_service_impl.cc b/device/wake_lock/wake_lock_service_impl.cc index ae998aa6..6e157180 100644 --- a/device/wake_lock/wake_lock_service_impl.cc +++ b/device/wake_lock/wake_lock_service_impl.cc
@@ -6,31 +6,124 @@ #include <utility> -#include "device/wake_lock/wake_lock_service_context.h" +#include "base/memory/ptr_util.h" namespace device { -WakeLockServiceImpl::WakeLockServiceImpl(WakeLockServiceContext* context) - : context_(context), wake_lock_request_outstanding_(false) {} +WakeLockServiceImpl::WakeLockServiceImpl( + mojom::WakeLockServiceRequest request, + device::PowerSaveBlocker::PowerSaveBlockerType type, + device::PowerSaveBlocker::Reason reason, + const std::string& description, + int context_id, + WakeLockContextCallback native_view_getter, + scoped_refptr<base::SingleThreadTaskRunner> file_task_runner) + : type_(type), + reason_(reason), + description_(base::MakeUnique<std::string>(description)), + num_lock_requests_(0), +#if defined(OS_ANDROID) + context_id_(context_id), + native_view_getter_(native_view_getter), +#endif + main_task_runner_(base::ThreadTaskRunnerHandle::Get()), + file_task_runner_(std::move(file_task_runner)) { + AddClient(std::move(request)); + binding_set_.set_connection_error_handler(base::Bind( + &WakeLockServiceImpl::OnConnectionError, base::Unretained(this))); +} -WakeLockServiceImpl::~WakeLockServiceImpl() { - CancelWakeLock(); +WakeLockServiceImpl::~WakeLockServiceImpl() {} + +void WakeLockServiceImpl::AddClient(mojom::WakeLockServiceRequest request) { + binding_set_.AddBinding(this, std::move(request), + base::MakeUnique<bool>(false)); } void WakeLockServiceImpl::RequestWakeLock() { - if (wake_lock_request_outstanding_) + DCHECK(main_task_runner_->RunsTasksOnCurrentThread()); + DCHECK(binding_set_.dispatch_context()); + + // Uses the Context to get the outstanding status of current binding. + // Two consecutive requests from the same client should be coalesced + // as one request. + if (*binding_set_.dispatch_context()) return; - wake_lock_request_outstanding_ = true; - context_->RequestWakeLock(); + *binding_set_.dispatch_context() = true; + num_lock_requests_++; + UpdateWakeLock(); } void WakeLockServiceImpl::CancelWakeLock() { - if (!wake_lock_request_outstanding_) + DCHECK(main_task_runner_->RunsTasksOnCurrentThread()); + DCHECK(binding_set_.dispatch_context()); + + if (!(*binding_set_.dispatch_context())) return; - wake_lock_request_outstanding_ = false; - context_->CancelWakeLock(); + *binding_set_.dispatch_context() = false; + if (num_lock_requests_ > 0) { + num_lock_requests_--; + UpdateWakeLock(); + } +} + +void WakeLockServiceImpl::HasWakeLockForTests( + const HasWakeLockForTestsCallback& callback) { + callback.Run(!!wake_lock_); +} +void WakeLockServiceImpl::UpdateWakeLock() { + DCHECK(num_lock_requests_ >= 0); + + if (num_lock_requests_) { + if (!wake_lock_) + CreateWakeLock(); + } else { + if (wake_lock_) + RemoveWakeLock(); + } +} + +void WakeLockServiceImpl::CreateWakeLock() { + DCHECK(!wake_lock_); + + if (type_ != device::PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep || + reason_ != device::PowerSaveBlocker::kReasonOther || + *description_ != "Wake Lock API") { + // TODO(ke.he@intel.com): Fully generalize the WakeLock interface and impl. + NOTREACHED(); + return; + } + + wake_lock_ = base::MakeUnique<device::PowerSaveBlocker>( + type_, reason_, *description_, main_task_runner_, file_task_runner_); + +#if defined(OS_ANDROID) + gfx::NativeView native_view = native_view_getter_.Run(context_id_); + if (native_view) + wake_lock_.get()->InitDisplaySleepBlocker(native_view); +#endif +} + +void WakeLockServiceImpl::RemoveWakeLock() { + DCHECK(wake_lock_); + wake_lock_.reset(); +} + +void WakeLockServiceImpl::OnConnectionError() { + DCHECK(binding_set_.dispatch_context()); + + // If the error-happening client's wakelock is in outstanding status, + // decrease the num_lock_requests and call UpdateWakeLock(). + if (*binding_set_.dispatch_context() && num_lock_requests_ > 0) { + num_lock_requests_--; + UpdateWakeLock(); + } + + // If |binding_set_| is empty, WakeLockServiceImpl should delele itself. + if (binding_set_.empty()) + base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); } } // namespace device
diff --git a/device/wake_lock/wake_lock_service_impl.h b/device/wake_lock/wake_lock_service_impl.h index c66ec8d1a..204aa83 100644 --- a/device/wake_lock/wake_lock_service_impl.h +++ b/device/wake_lock/wake_lock_service_impl.h
@@ -5,27 +5,66 @@ #ifndef DEVICE_WAKE_LOCK_WAKE_LOCK_SERVICE_IMPL_H_ #define DEVICE_WAKE_LOCK_WAKE_LOCK_SERVICE_IMPL_H_ +#include <memory> + #include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/single_thread_task_runner.h" +#include "device/power_save_blocker/power_save_blocker.h" #include "device/wake_lock/public/interfaces/wake_lock_service.mojom.h" -#include "mojo/public/cpp/bindings/interface_request.h" +#include "device/wake_lock/wake_lock_service_context.h" +#include "mojo/public/cpp/bindings/binding_set.h" +#include "ui/gfx/native_widget_types.h" namespace device { -class WakeLockServiceContext; - class WakeLockServiceImpl : public mojom::WakeLockService { public: - explicit WakeLockServiceImpl(WakeLockServiceContext* context); + WakeLockServiceImpl( + mojom::WakeLockServiceRequest request, + device::PowerSaveBlocker::PowerSaveBlockerType type, + device::PowerSaveBlocker::Reason reason, + const std::string& description, + int context_id, + WakeLockContextCallback native_view_getter, + scoped_refptr<base::SingleThreadTaskRunner> file_task_runner); ~WakeLockServiceImpl() override; // WakeLockSevice implementation. void RequestWakeLock() override; void CancelWakeLock() override; + void AddClient(mojom::WakeLockServiceRequest request) override; + void HasWakeLockForTests( + const HasWakeLockForTestsCallback& callback) override; private: - // Will outlive this instance. - WakeLockServiceContext* context_; - bool wake_lock_request_outstanding_; + void UpdateWakeLock(); + void CreateWakeLock(); + void RemoveWakeLock(); + void OnConnectionError(); + + device::PowerSaveBlocker::PowerSaveBlockerType type_; + device::PowerSaveBlocker::Reason reason_; + std::unique_ptr<std::string> description_; + int num_lock_requests_; + +#if defined(OS_ANDROID) + int context_id_; + WakeLockContextCallback native_view_getter_; +#endif + + scoped_refptr<base::SequencedTaskRunner> main_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> file_task_runner_; + + // The actual power save blocker for screen. + std::unique_ptr<PowerSaveBlocker> wake_lock_; + + // Multiple clients that associate to the same WebContents share the same one + // WakeLockServiceImpl instance. Two consecutive |RequestWakeLock| requests + // from the same client should be coalesced as one request. Everytime a new + // client is being added into the BindingSet, we create an unique_ptr<bool> + // as its context, which records this client's request status. + mojo::BindingSet<mojom::WakeLockService, std::unique_ptr<bool>> binding_set_; DISALLOW_COPY_AND_ASSIGN(WakeLockServiceImpl); };
diff --git a/headless/lib/browser/headless_content_browser_client.cc b/headless/lib/browser/headless_content_browser_client.cc index 1e19a50..56e09a6 100644 --- a/headless/lib/browser/headless_content_browser_client.cc +++ b/headless/lib/browser/headless_content_browser_client.cc
@@ -204,6 +204,21 @@ #endif // defined(HEADLESS_USE_BREAKPAD) } +void HeadlessContentBrowserClient::AllowCertificateError( + content::WebContents* web_contents, + int cert_error, + const net::SSLInfo& ssl_info, + const GURL& request_url, + content::ResourceType resource_type, + bool overridable, + bool strict_enforcement, + bool expired_previous_decision, + const base::Callback<void(content::CertificateRequestResultType)>& + callback) { + if (!callback.is_null()) + callback.Run(content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY); +} + void HeadlessContentBrowserClient::ResourceDispatcherHostCreated() { resource_dispatcher_host_delegate_.reset( new HeadlessResourceDispatcherHostDelegate);
diff --git a/headless/lib/browser/headless_content_browser_client.h b/headless/lib/browser/headless_content_browser_client.h index d1ca74cc..1c3f95f 100644 --- a/headless/lib/browser/headless_content_browser_client.h +++ b/headless/lib/browser/headless_content_browser_client.h
@@ -38,6 +38,18 @@ void AppendExtraCommandLineSwitches(base::CommandLine* command_line, int child_process_id) override; + void AllowCertificateError( + content::WebContents* web_contents, + int cert_error, + const net::SSLInfo& ssl_info, + const GURL& request_url, + content::ResourceType resource_type, + bool overridable, + bool strict_enforcement, + bool expired_previous_decision, + const base::Callback<void(content::CertificateRequestResultType)>& + callback) override; + void ResourceDispatcherHostCreated() override; private:
diff --git a/headless/lib/headless_browser_browsertest.cc b/headless/lib/headless_browser_browsertest.cc index f23d5af..824a39d 100644 --- a/headless/lib/headless_browser_browsertest.cc +++ b/headless/lib/headless_browser_browsertest.cc
@@ -31,6 +31,7 @@ #include "headless/test/test_url_request_job.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "net/cookies/cookie_store.h" +#include "net/http/http_util.h" #include "net/test/spawned_test_server/spawned_test_server.h" #include "net/url_request/url_request_context.h" #include "testing/gmock/include/gmock/gmock.h" @@ -392,12 +393,6 @@ namespace { -// True if the request method is "safe" (per section 4.2.1 of RFC 7231). -bool IsMethodSafe(const std::string& method) { - return method == "GET" || method == "HEAD" || method == "OPTIONS" || - method == "TRACE"; -} - class ProtocolHandlerWithCookies : public net::URLRequestJobFactory::ProtocolHandler { public: @@ -468,7 +463,7 @@ net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) { options.set_same_site_cookie_mode( net::CookieOptions::SameSiteCookieMode::INCLUDE_STRICT_AND_LAX); - } else if (IsMethodSafe(request_->method())) { + } else if (net::HttpUtil::IsMethodSafe(request_->method())) { options.set_same_site_cookie_mode( net::CookieOptions::SameSiteCookieMode::INCLUDE_LAX); }
diff --git a/headless/lib/headless_web_contents_browsertest.cc b/headless/lib/headless_web_contents_browsertest.cc index b0afaa9..9d92f2a 100644 --- a/headless/lib/headless_web_contents_browsertest.cc +++ b/headless/lib/headless_web_contents_browsertest.cc
@@ -109,6 +109,22 @@ EXPECT_TRUE(result); } +IN_PROC_BROWSER_TEST_F(HeadlessWebContentsTest, HandleSSLError) { + net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS); + https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED); + ASSERT_TRUE(https_server.Start()); + + HeadlessBrowserContext* browser_context = + browser()->CreateBrowserContextBuilder().Build(); + + HeadlessWebContents* web_contents = + browser_context->CreateWebContentsBuilder() + .SetInitialURL(https_server.GetURL("/hello.html")) + .Build(); + + EXPECT_FALSE(WaitForLoad(web_contents)); +} + namespace { bool DecodePNG(std::string base64_data, SkBitmap* bitmap) { std::string png_data;
diff --git a/headless/public/util/generic_url_request_job.cc b/headless/public/util/generic_url_request_job.cc index dcc75c2d..d3fc0a7 100644 --- a/headless/public/util/generic_url_request_job.cc +++ b/headless/public/util/generic_url_request_job.cc
@@ -21,18 +21,10 @@ #include "net/base/upload_bytes_element_reader.h" #include "net/cookies/cookie_store.h" #include "net/http/http_response_headers.h" +#include "net/http/http_util.h" #include "net/url_request/url_request_context.h" namespace headless { -namespace { - -// True if the request method is "safe" (per section 4.2.1 of RFC 7231). -bool IsMethodSafe(const std::string& method) { - return method == "GET" || method == "HEAD" || method == "OPTIONS" || - method == "TRACE"; -} - -} // namespace uint64_t GenericURLRequestJob::next_request_id_ = 0; @@ -91,7 +83,7 @@ net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) { options.set_same_site_cookie_mode( net::CookieOptions::SameSiteCookieMode::INCLUDE_STRICT_AND_LAX); - } else if (IsMethodSafe(request_->method())) { + } else if (net::HttpUtil::IsMethodSafe(request_->method())) { options.set_same_site_cookie_mode( net::CookieOptions::SameSiteCookieMode::INCLUDE_LAX); }
diff --git a/ios/chrome/browser/ui/authentication/signin_interaction_controller_egtest.mm b/ios/chrome/browser/ui/authentication/signin_interaction_controller_egtest.mm index cf90395e..79d2da3 100644 --- a/ios/chrome/browser/ui/authentication/signin_interaction_controller_egtest.mm +++ b/ios/chrome/browser/ui/authentication/signin_interaction_controller_egtest.mm
@@ -30,6 +30,8 @@ #error "This file requires ARC support." #endif +using chrome_test_util::NavigationBarDoneButton; + namespace { // Returns a fake identity. @@ -143,8 +145,8 @@ TapButtonWithLabelId(IDS_IOS_ACCOUNT_CONSISTENCY_SETUP_SIGNIN_BUTTON); TapButtonWithLabelId(IDS_IOS_ACCOUNT_CONSISTENCY_CONFIRMATION_OK_BUTTON); - // Close Settings. - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; // Check |identity| is signed-in. AssertAuthenticatedIdentityInActiveProfile(identity); @@ -185,8 +187,8 @@ // Check the signed-in user did change. AssertAuthenticatedIdentityInActiveProfile(identity2); - // Close Settings. - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; } // Tests signing in with one account, switching sync account to a second and @@ -224,8 +226,8 @@ // Check the signed-in user did change. AssertAuthenticatedIdentityInActiveProfile(identity2); - // Close Settings. - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; } // Tests that switching from a managed account to a non-managed account works @@ -274,8 +276,8 @@ AssertAuthenticatedIdentityInActiveProfile(identity); - // Close Settings. - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; } // Tests that signing out from the Settings works correctly. @@ -305,8 +307,8 @@ // Check that the settings home screen is shown. WaitForMatcher(grey_accessibilityID(kSettingsSignInCellId)); - // Close Settings. - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; // Check that there is no signed in user. AssertAuthenticatedIdentityInActiveProfile(nil); @@ -350,8 +352,8 @@ // Check that the settings home screen is shown. WaitForMatcher(grey_accessibilityID(kSettingsSignInCellId)); - // Close Settings. - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; // Check that there is no signed in user. AssertAuthenticatedIdentityInActiveProfile(nil); @@ -377,8 +379,8 @@ [[EarlGrey selectElementWithMatcher:settings_link_matcher] performAction:grey_tap()]; - // Close Settings. - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; // All Settings should be gone and user signed in. id<GREYMatcher> settings_matcher = @@ -416,7 +418,8 @@ // Close sign-in screen and Settings. TapButtonWithLabelId(IDS_IOS_ACCOUNT_CONSISTENCY_SETUP_SKIP_BUTTON); - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; } // Opens the add account screen and then cancels it by opening a new tab. @@ -454,7 +457,8 @@ // Close sign-in screen and Settings. TapButtonWithLabelId(IDS_IOS_ACCOUNT_CONSISTENCY_SETUP_SKIP_BUTTON); - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; } // Starts an authentication flow and cancel it by opening a new tab. Ensures @@ -513,7 +517,8 @@ // Close sign-in screen and Settings. TapButtonWithLabelId(IDS_IOS_ACCOUNT_CONSISTENCY_SETUP_SKIP_BUTTON); - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; AssertAuthenticatedIdentityInActiveProfile(nil); } @@ -585,7 +590,8 @@ // Close sign-in screen and Bookmarks. TapButtonWithLabelId(IDS_IOS_ACCOUNT_CONSISTENCY_SETUP_SKIP_BUTTON); if (!IsIPadIdiom()) { - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; } }
diff --git a/ios/chrome/browser/ui/history/history_ui_egtest.mm b/ios/chrome/browser/ui/history/history_ui_egtest.mm index e86fa3d..014dfa30 100644 --- a/ios/chrome/browser/ui/history/history_ui_egtest.mm +++ b/ios/chrome/browser/ui/history/history_ui_egtest.mm
@@ -391,9 +391,9 @@ // Include sufficientlyVisible condition for the case of the clear browsing // dialog, which also has a "Done" button and is displayed over the history // panel. - id<GREYMatcher> visibleDoneButton = grey_allOf( - ButtonWithAccessibilityLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON), - grey_sufficientlyVisible(), nil); + id<GREYMatcher> visibleDoneButton = + grey_allOf(chrome_test_util::NavigationBarDoneButton(), + grey_sufficientlyVisible(), nil); [[EarlGrey selectElementWithMatcher:visibleDoneButton] performAction:grey_tap()];
diff --git a/ios/chrome/browser/ui/settings/accounts_collection_egtest.mm b/ios/chrome/browser/ui/settings/accounts_collection_egtest.mm index 73adca9e..b256e0e 100644 --- a/ios/chrome/browser/ui/settings/accounts_collection_egtest.mm +++ b/ios/chrome/browser/ui/settings/accounts_collection_egtest.mm
@@ -25,6 +25,8 @@ #error "This file requires ARC support." #endif +using chrome_test_util::NavigationBarDoneButton; + namespace { // Returns a fake identity. @@ -121,8 +123,8 @@ assertWithMatcher:grey_sufficientlyVisible()]; AssertAuthenticatedIdentityInActiveProfile(nil); - // Close Settings. - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; } // Tests that the Account Settings screen is correctly popped if the signed in @@ -159,8 +161,8 @@ assertWithMatcher:grey_sufficientlyVisible()]; AssertAuthenticatedIdentityInActiveProfile(nil); - // Close Settings. - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; } // Tests that the Account Settings screen is correctly reloaded when one of @@ -193,8 +195,8 @@ assertWithMatcher:grey_nil()]; AssertAuthenticatedIdentityInActiveProfile(identity1); - // Close Settings. - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; } // Tests that the Sync Settings screen is correctly reloaded when one of the @@ -234,8 +236,8 @@ assertWithMatcher:grey_nil()]; AssertAuthenticatedIdentityInActiveProfile(identity1); - // Close Settings. - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; } // Tests that the Account Settings screen is popped and the user signed out @@ -263,8 +265,8 @@ assertWithMatcher:grey_sufficientlyVisible()]; AssertAuthenticatedIdentityInActiveProfile(nil); - // Close Settings. - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; } // Tests that the user isn't signed out and the UI is correct when the @@ -301,8 +303,8 @@ assertWithMatcher:grey_sufficientlyVisible()]; AssertAuthenticatedIdentityInActiveProfile(identity); - // Close Settings. - TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] + performAction:grey_tap()]; } @end
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index 1e7c47326..162acc5 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -81,6 +81,7 @@ #import "ios/web/web_state/js/crw_js_plugin_placeholder_manager.h" #import "ios/web/web_state/js/crw_js_post_request_loader.h" #import "ios/web/web_state/js/crw_js_window_id_manager.h" +#include "ios/web/web_state/navigation_context_impl.h" #import "ios/web/web_state/page_viewport_state.h" #import "ios/web/web_state/ui/crw_context_menu_controller.h" #import "ios/web/web_state/ui/crw_swipe_recognizer_provider.h" @@ -644,14 +645,18 @@ // Attempts to handle a script message. Returns YES on success, NO otherwise. - (BOOL)respondToWKScriptMessage:(WKScriptMessage*)scriptMessage; // Registers load request with empty referrer and link or client redirect -// transition based on user interaction state. -- (void)registerLoadRequest:(const GURL&)URL; +// transition based on user interaction state. Returns navigation context for +// this request. +- (std::unique_ptr<web::NavigationContextImpl>)registerLoadRequestForURL: + (const GURL&)URL; // Prepares web controller and delegates for anticipated page change. // Allows several methods to invoke webWill/DidAddPendingURL on anticipated page // change, using the same cached request and calculated transition types. -- (void)registerLoadRequest:(const GURL&)URL - referrer:(const web::Referrer&)referrer - transition:(ui::PageTransition)transition; +// Returns navigation context for this request. +- (std::unique_ptr<web::NavigationContextImpl>) +registerLoadRequestForURL:(const GURL&)URL + referrer:(const web::Referrer&)referrer + transition:(ui::PageTransition)transition; // Updates the HTML5 history state of the page using the current NavigationItem. // For same-document navigations and navigations affected by // window.history.[push/replace]State(), the URL and serialized state object @@ -1433,7 +1438,8 @@ return [_webView estimatedProgress]; } -- (void)registerLoadRequest:(const GURL&)URL { +- (std::unique_ptr<web::NavigationContextImpl>)registerLoadRequestForURL: + (const GURL&)URL { // Get the navigation type from the last main frame load request, and try to // map that to a PageTransition. WKNavigationType navigationType = @@ -1466,12 +1472,15 @@ } // The referrer is not known yet, and will be updated later. const web::Referrer emptyReferrer; - [self registerLoadRequest:URL referrer:emptyReferrer transition:transition]; + return [self registerLoadRequestForURL:URL + referrer:emptyReferrer + transition:transition]; } -- (void)registerLoadRequest:(const GURL&)requestURL - referrer:(const web::Referrer&)referrer - transition:(ui::PageTransition)transition { +- (std::unique_ptr<web::NavigationContextImpl>) +registerLoadRequestForURL:(const GURL&)requestURL + referrer:(const web::Referrer&)referrer + transition:(ui::PageTransition)transition { // Transfer time is registered so that further transitions within the time // envelope are not also registered as links. _lastTransferTimeInSeconds = CFAbsoluteTimeGetCurrent(); @@ -1504,8 +1513,13 @@ web::NavigationInitiationType::RENDERER_INITIATED, web::NavigationManager::UserAgentOverrideOption::INHERIT); } + std::unique_ptr<web::NavigationContextImpl> context = + web::NavigationContextImpl::CreateNavigationContext( + _webStateImpl, requestURL, nullptr /* response_headers */); _webStateImpl->SetIsLoading(true); + // TODO(crbug.com/713836): pass context to |OnProvisionalNavigationStarted|. _webStateImpl->OnProvisionalNavigationStarted(requestURL); + return context; } - (void)updateHTML5HistoryState { @@ -1800,9 +1814,10 @@ item->SetVirtualURL([nativeContent virtualURL]); } - [self registerLoadRequest:targetURL - referrer:referrer - transition:self.currentTransition]; + std::unique_ptr<web::NavigationContextImpl> navigationContext = + [self registerLoadRequestForURL:targetURL + referrer:referrer + transition:self.currentTransition]; [self loadNativeViewWithSuccess:YES]; } @@ -4365,7 +4380,8 @@ } return; } else { - [self registerLoadRequest:webViewURL]; + std::unique_ptr<web::NavigationContextImpl> navigationContext = + [self registerLoadRequestForURL:webViewURL]; } } @@ -4379,9 +4395,12 @@ [_navigationStates setState:web::WKNavigationState::REDIRECTED forNavigation:navigation]; - [self registerLoadRequest:net::GURLWithNSURL(webView.URL) - referrer:[self currentReferrer] - transition:ui::PAGE_TRANSITION_SERVER_REDIRECT]; + // It is fine to ignore returned NavigationContext. Context does not change + // for redirect and old context stored _navigationStates is valid and it + // should not be replaced. + [self registerLoadRequestForURL:net::GURLWithNSURL(webView.URL) + referrer:[self currentReferrer] + transition:ui::PAGE_TRANSITION_SERVER_REDIRECT]; } - (void)webView:(WKWebView*)webView @@ -4850,11 +4869,12 @@ // registering a load request logically comes before updating the document // URL, but also must come first since it uses state that is reset on URL // changes. + std::unique_ptr<web::NavigationContextImpl> navigationContext; if (!_changingHistoryState) { // If this wasn't a previously-expected load (e.g., certain back/forward // navigations), register the load request. if (![self isLoadRequestPendingForURL:newURL]) - [self registerLoadRequest:newURL]; + navigationContext = [self registerLoadRequestForURL:newURL]; } [self setDocumentURL:newURL]; @@ -4904,9 +4924,10 @@ [request setAllHTTPHeaderFields:self.currentHTTPHeaders]; GURL navigationURL = currentItem ? currentItem->GetURL() : GURL::EmptyGURL(); - [self registerLoadRequest:navigationURL - referrer:self.currentNavItemReferrer - transition:self.currentTransition]; + std::unique_ptr<web::NavigationContextImpl> navigationContext = + [self registerLoadRequestForURL:navigationURL + referrer:self.currentNavItemReferrer + transition:self.currentTransition]; [self loadPOSTRequest:request]; return; } @@ -4914,9 +4935,10 @@ ProceduralBlock defaultNavigationBlock = ^{ web::NavigationItem* item = self.currentNavItem; GURL navigationURL = item ? item->GetURL() : GURL::EmptyGURL(); - [self registerLoadRequest:navigationURL - referrer:self.currentNavItemReferrer - transition:self.currentTransition]; + std::unique_ptr<web::NavigationContextImpl> navigationContext = + [self registerLoadRequestForURL:navigationURL + referrer:self.currentNavItemReferrer + transition:self.currentTransition]; [self loadRequest:request]; [self reportBackForwardNavigationTypeForFastNavigation:NO]; }; @@ -4951,9 +4973,10 @@ // so |reload| must be explicitly called. web::NavigationItem* item = self.currentNavItem; GURL navigationURL = item ? item->GetURL() : GURL::EmptyGURL(); - [self registerLoadRequest:navigationURL - referrer:self.currentNavItemReferrer - transition:self.currentTransition]; + std::unique_ptr<web::NavigationContextImpl> navigationContext = + [self registerLoadRequestForURL:navigationURL + referrer:self.currentNavItemReferrer + transition:self.currentTransition]; WKNavigation* navigation = nil; if (navigationURL == net::GURLWithNSURL([_webView URL])) { navigation = [_webView reload];
diff --git a/ios/web_view/BUILD.gn b/ios/web_view/BUILD.gn index a3c8d33..01a4d6c3 100644 --- a/ios/web_view/BUILD.gn +++ b/ios/web_view/BUILD.gn
@@ -22,12 +22,14 @@ "public/ChromeWebView.h", "public/cwv_export.h", "public/cwv_html_element.h", + "public/cwv_language_detection_result.h", "public/cwv_navigation_action.h", "public/cwv_navigation_delegate.h", "public/cwv_scroll_view.h", "public/cwv_scroll_view_delegate.h", - "public/cwv_translate_delegate.h", - "public/cwv_translate_manager.h", + "public/cwv_translation_controller.h", + "public/cwv_translation_controller_delegate.h", + "public/cwv_translation_language.h", "public/cwv_ui_delegate.h", "public/cwv_user_content_controller.h", "public/cwv_user_script.h", @@ -50,8 +52,12 @@ "internal/cwv_web_view_configuration_internal.h", "internal/pref_names.cc", "internal/pref_names.h", - "internal/translate/cwv_translate_manager_impl.h", - "internal/translate/cwv_translate_manager_impl.mm", + "internal/translate/cwv_language_detection_result_internal.h", + "internal/translate/cwv_language_detection_result.mm", + "internal/translate/cwv_translation_controller.mm", + "internal/translate/cwv_translation_controller_internal.h", + "internal/translate/cwv_translation_language_internal.h", + "internal/translate/cwv_translation_language.mm", "internal/translate/web_view_translate_accept_languages_factory.cc", "internal/translate/web_view_translate_accept_languages_factory.h", "internal/translate/web_view_translate_client.h",
diff --git a/ios/web_view/internal/cwv_web_view.mm b/ios/web_view/internal/cwv_web_view.mm index 544a327..c391d89 100644 --- a/ios/web_view/internal/cwv_web_view.mm +++ b/ios/web_view/internal/cwv_web_view.mm
@@ -26,6 +26,7 @@ #import "ios/web_view/internal/cwv_navigation_action_internal.h" #import "ios/web_view/internal/cwv_scroll_view_internal.h" #import "ios/web_view/internal/cwv_web_view_configuration_internal.h" +#import "ios/web_view/internal/translate/cwv_translation_controller_internal.h" #import "ios/web_view/internal/translate/web_view_translate_client.h" #include "ios/web_view/internal/web_view_browser_state.h" #import "ios/web_view/internal/web_view_java_script_dialog_presenter.h" @@ -84,9 +85,9 @@ @implementation CWVWebView @synthesize configuration = _configuration; -@synthesize navigationDelegate = _navigationDelegate; -@synthesize translationDelegate = _translationDelegate; @synthesize estimatedProgress = _estimatedProgress; +@synthesize navigationDelegate = _navigationDelegate; +@synthesize translationController = _translationController; @synthesize UIDelegate = _UIDelegate; @synthesize scrollView = _scrollView; @@ -192,12 +193,6 @@ _javaScriptDialogPresenter->SetUIDelegate(_UIDelegate); } -- (void)setTranslationDelegate:(id<CWVTranslateDelegate>)translationDelegate { - _translationDelegate = translationDelegate; - ios_web_view::WebViewTranslateClient::FromWebState(_webState.get()) - ->set_translate_delegate(translationDelegate); -} - // ----------------------------------------------------------------------- // WebStateObserver implementation. @@ -295,6 +290,16 @@ return _javaScriptDialogPresenter.get(); } +#pragma mark - Translation + +- (CWVTranslationController*)translationController { + if (!_translationController) { + _translationController = [[CWVTranslationController alloc] init]; + _translationController.webState = _webState.get(); + } + return _translationController; +} + #pragma mark - Preserving and Restoring State - (void)encodeRestorableStateWithCoder:(NSCoder*)coder { @@ -348,8 +353,7 @@ _scrollView.proxy = _webState.get()->GetWebViewProxy().scrollViewProxy; - // Initialize Translate. - ios_web_view::WebViewTranslateClient::CreateForWebState(_webState.get()); + _translationController.webState = _webState.get(); [self addInternalWebViewAsSubview]; }
diff --git a/ios/web_view/internal/translate/cwv_language_detection_result.mm b/ios/web_view/internal/translate/cwv_language_detection_result.mm new file mode 100644 index 0000000..7cd0546 --- /dev/null +++ b/ios/web_view/internal/translate/cwv_language_detection_result.mm
@@ -0,0 +1,32 @@ +// 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. + +#import "ios/web_view/internal/translate/cwv_language_detection_result_internal.h" + +#import "ios/web_view/public/cwv_translation_language.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@implementation CWVLanguageDetectionResult + +@synthesize pageLanguage = _pageLanguage; +@synthesize suggestedTargetLanguage = _suggestedTargetLanguage; +@synthesize supportedLanguages = _supportedLanguages; + +- (instancetype) + initWithPageLanguage:(CWVTranslationLanguage*)pageLanguage +suggestedTargetLanguage:(CWVTranslationLanguage*)suggestedTargetLanguage + supportedLanguages:(NSArray<CWVTranslationLanguage*>*)supportedLanguages { + self = [super init]; + if (self) { + _pageLanguage = pageLanguage; + _suggestedTargetLanguage = suggestedTargetLanguage; + _supportedLanguages = supportedLanguages; + } + return self; +} + +@end
diff --git a/ios/web_view/internal/translate/cwv_language_detection_result_internal.h b/ios/web_view/internal/translate/cwv_language_detection_result_internal.h new file mode 100644 index 0000000..39668841 --- /dev/null +++ b/ios/web_view/internal/translate/cwv_language_detection_result_internal.h
@@ -0,0 +1,29 @@ +// 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 IOS_WEB_VIEW_INTERNAL_CWV_LANGUAGE_DETECTION_RESULT_INTERNAL_H +#define IOS_WEB_VIEW_INTERNAL_CWV_LANGUAGE_DETECTION_RESULT_INTERNAL_H + +#import <Foundation/Foundation.h> + +#import "ios/web_view/public/cwv_language_detection_result.h" + +NS_ASSUME_NONNULL_BEGIN + +@class CWVTranslationLanguage; + +// Internal methods for CWVLanguageDetectionResult. +@interface CWVLanguageDetectionResult () + +- (instancetype) + initWithPageLanguage:(CWVTranslationLanguage*)pageLanguage +suggestedTargetLanguage:(CWVTranslationLanguage*)suggestedTargetLanguage + supportedLanguages:(NSArray<CWVTranslationLanguage*>*)supportedLanguages + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END + +#endif // IOS_WEB_VIEW_INTERNAL_CWV_LANGUAGE_DETECTION_RESULT_INTERNAL_H
diff --git a/ios/web_view/internal/translate/cwv_translate_manager_impl.h b/ios/web_view/internal/translate/cwv_translate_manager_impl.h deleted file mode 100644 index 88f8c14..0000000 --- a/ios/web_view/internal/translate/cwv_translate_manager_impl.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_WEB_VIEW_INTERNAL_TRANSLATE_CWV_TRANSLATE_MANAGER_IMPL_H_ -#define IOS_WEB_VIEW_INTERNAL_TRANSLATE_CWV_TRANSLATE_MANAGER_IMPL_H_ - -#include <string> - -#import "ios/web_view/public/cwv_translate_manager.h" - -namespace translate { -class TranslateManager; -} - -// CWVTranslateManagerImpl is mostly an Objective-C wrapper around -// translate::TranslateUIDelegate. -@interface CWVTranslateManagerImpl : NSObject<CWVTranslateManager> - -- (instancetype)init NS_UNAVAILABLE; - -// |manager| is expexted to outlive this CWVTranslateManagerImpl. -- (instancetype)initWithTranslateManager:(translate::TranslateManager*)manager - sourceLanguage:(const std::string&)source - targetLanguage:(const std::string&)target - NS_DESIGNATED_INITIALIZER; - -@end - -#endif // IOS_WEB_VIEW_INTERNAL_TRANSLATE_CWV_TRANSLATE_MANAGER_IMPL_H_
diff --git a/ios/web_view/internal/translate/cwv_translate_manager_impl.mm b/ios/web_view/internal/translate/cwv_translate_manager_impl.mm deleted file mode 100644 index 6d63289..0000000 --- a/ios/web_view/internal/translate/cwv_translate_manager_impl.mm +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "ios/web_view/internal/translate/cwv_translate_manager_impl.h" - -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "components/translate/core/browser/translate_manager.h" -#include "components/translate/core/browser/translate_ui_delegate.h" - -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - -@implementation CWVTranslateManagerImpl { - std::unique_ptr<translate::TranslateUIDelegate> _translateUIDelegate; -} - -- (instancetype)initWithTranslateManager:(translate::TranslateManager*)manager - sourceLanguage:(const std::string&)source - targetLanguage:(const std::string&)target { - if ((self = [super init])) { - DCHECK(manager); - _translateUIDelegate = base::MakeUnique<translate::TranslateUIDelegate>( - manager->GetWeakPtr(), source, target); - } - return self; -} - -#pragma mark CWVTranslateManager methods - -- (void)translate { - _translateUIDelegate->Translate(); -} - -- (void)revertTranslation { - _translateUIDelegate->RevertTranslation(); -} - -@end
diff --git a/ios/web_view/internal/translate/cwv_translation_controller.mm b/ios/web_view/internal/translate/cwv_translation_controller.mm new file mode 100644 index 0000000..f38e1ee0 --- /dev/null +++ b/ios/web_view/internal/translate/cwv_translation_controller.mm
@@ -0,0 +1,170 @@ +// 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. + +#import "ios/web_view/internal/translate/cwv_translation_controller_internal.h" + +#include <string> + +#include "base/memory/ptr_util.h" +#include "base/strings/string16.h" +#include "components/translate/core/browser/translate_manager.h" +#include "components/translate/core/browser/translate_ui_delegate.h" +#import "ios/web_view/internal/translate/cwv_language_detection_result_internal.h" +#import "ios/web_view/internal/translate/cwv_translation_language_internal.h" +#import "ios/web_view/internal/translate/web_view_translate_client.h" +#import "ios/web_view/public/cwv_translation_controller_delegate.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +NSErrorDomain const CWVTranslationErrorDomain = + @"org.chromium.chromewebview.TranslationErrorDomain"; + +const NSInteger CWVTranslationErrorNetwork = + translate::TranslateErrors::NETWORK; +const NSInteger CWVTranslationErrorInitializationError = + translate::TranslateErrors::INITIALIZATION_ERROR; +const NSInteger CWVTranslationErrorUnknownLanguage = + translate::TranslateErrors::UNKNOWN_LANGUAGE; +const NSInteger CWVTranslationErrorUnsupportedLanguage = + translate::TranslateErrors::UNSUPPORTED_LANGUAGE; +const NSInteger CWVTranslationErrorIdenticalLanguages = + translate::TranslateErrors::IDENTICAL_LANGUAGES; +const NSInteger CWVTranslationErrorTranslationError = + translate::TranslateErrors::TRANSLATION_ERROR; +const NSInteger CWVTranslationErrorTranslationTimeout = + translate::TranslateErrors::TRANSLATION_TIMEOUT; +const NSInteger CWVTranslationErrorUnexpectedScriptError = + translate::TranslateErrors::UNEXPECTED_SCRIPT_ERROR; +const NSInteger CWVTranslationErrorBadOrigin = + translate::TranslateErrors::BAD_ORIGIN; +const NSInteger CWVTranslationErrorScriptLoadError = + translate::TranslateErrors::SCRIPT_LOAD_ERROR; + +@interface CWVTranslationController () + +// Convenience method to generate all supported languages from +// |translateUIDelegate|. +- (NSArray<CWVTranslationLanguage*>*)supportedLanguages; + +// Convenience method to get a language at |index| from |translateUIDelegate|. +- (CWVTranslationLanguage*)languageAtIndex:(size_t)index; + +@end + +@implementation CWVTranslationController { + ios_web_view::WebViewTranslateClient* _translateClient; + std::unique_ptr<translate::TranslateUIDelegate> _translateUIDelegate; +} + +@synthesize delegate = _delegate; +@synthesize webState = _webState; + +#pragma mark - Internal Methods + +- (void)setWebState:(web::WebState*)webState { + _webState = webState; + + ios_web_view::WebViewTranslateClient::CreateForWebState(_webState); + _translateClient = + ios_web_view::WebViewTranslateClient::FromWebState(_webState); + _translateClient->set_translation_controller(self); +} + +- (void)updateTranslateStep:(translate::TranslateStep)step + sourceLanguage:(const std::string&)sourceLanguage + targetLanguage:(const std::string&)targetLanguage + errorType:(translate::TranslateErrors::Type)errorType + triggeredFromMenu:(bool)triggeredFromMenu { + translate::TranslateManager* manager = _translateClient->translate_manager(); + _translateUIDelegate = base::MakeUnique<translate::TranslateUIDelegate>( + manager->GetWeakPtr(), sourceLanguage, targetLanguage); + + CWVTranslationLanguage* source = + [self languageAtIndex:_translateUIDelegate->GetOriginalLanguageIndex()]; + CWVTranslationLanguage* target = + [self languageAtIndex:_translateUIDelegate->GetTargetLanguageIndex()]; + + NSError* error; + if (errorType != translate::TranslateErrors::NONE) { + error = [NSError errorWithDomain:CWVTranslationErrorDomain + code:errorType + userInfo:nil]; + } + + switch (step) { + case translate::TRANSLATE_STEP_BEFORE_TRANSLATE: { + CWVLanguageDetectionResult* languageDetectionResult = + [[CWVLanguageDetectionResult alloc] + initWithPageLanguage:source + suggestedTargetLanguage:target + supportedLanguages:[self supportedLanguages]]; + if ([_delegate respondsToSelector:@selector + (translationController:didFinishLanguageDetectionWithResult + :error:)]) { + [_delegate translationController:self + didFinishLanguageDetectionWithResult:languageDetectionResult + error:error]; + } + break; + } + case translate::TRANSLATE_STEP_TRANSLATING: + if ([_delegate respondsToSelector:@selector + (translationController:didStartTranslationFromLanguage + :toLanguage:)]) { + [_delegate translationController:self + didStartTranslationFromLanguage:source + toLanguage:target]; + } + break; + case translate::TRANSLATE_STEP_AFTER_TRANSLATE: + if ([_delegate respondsToSelector:@selector + (translationController:didFinishTranslationFromLanguage + :toLanguage:error:)]) { + [_delegate translationController:self + didFinishTranslationFromLanguage:source + toLanguage:target + error:error]; + } + break; + case translate::TRANSLATE_STEP_NEVER_TRANSLATE: + break; + case translate::TRANSLATE_STEP_TRANSLATE_ERROR: + break; + } +} + +#pragma mark - Public Methods + +- (void)translatePageFromLanguage:(CWVTranslationLanguage*)sourceLanguage + toLanguage:(CWVTranslationLanguage*)targetLanguage { + // TODO(706289): Use the passed parameters. + _translateUIDelegate->Translate(); +} + +- (void)revertTranslation { + _translateUIDelegate->RevertTranslation(); +} + +#pragma mark - Private Methods + +- (NSArray<CWVTranslationLanguage*>*)supportedLanguages { + NSMutableArray* supportedLanguages = [NSMutableArray array]; + for (size_t i = 0; i < _translateUIDelegate->GetNumberOfLanguages(); i++) { + CWVTranslationLanguage* language = [self languageAtIndex:i]; + [supportedLanguages addObject:language]; + } + + return [supportedLanguages copy]; +} + +- (CWVTranslationLanguage*)languageAtIndex:(size_t)index { + std::string languageCode = _translateUIDelegate->GetLanguageCodeAt(index); + base::string16 languageName = _translateUIDelegate->GetLanguageNameAt(index); + return [[CWVTranslationLanguage alloc] initWithLanguageCode:languageCode + languageName:languageName]; +} + +@end
diff --git a/ios/web_view/internal/translate/cwv_translation_controller_internal.h b/ios/web_view/internal/translate/cwv_translation_controller_internal.h new file mode 100644 index 0000000..6b74d55 --- /dev/null +++ b/ios/web_view/internal/translate/cwv_translation_controller_internal.h
@@ -0,0 +1,43 @@ +// 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 IOS_WEB_VIEW_INTERNAL_TRANSLATE_CWV_TRANSLATION_CONTROLLER_INTERNAL_H +#define IOS_WEB_VIEW_INTERNAL_TRANSLATE_CWV_TRANSLATION_CONTROLLER_INTERNAL_H + +#import "ios/web_view/public/cwv_translation_controller.h" + +#include <string> + +#include "components/translate/core/browser/translate_step.h" +#include "components/translate/core/common/translate_errors.h" + +namespace web { +class WebState; +} + +NS_ASSUME_NONNULL_BEGIN + +// Some internal methods needed to hide any C++ details. +@interface CWVTranslationController () + +// Set to create a new translate stack under the new webState. +@property(nonatomic, assign) web::WebState* webState; + +// Called to keep this class informed of the current translate progress. +// |step| the state of current translation. +// |sourceLanguage| the source language associated with the current |step|. +// |targetLanguage| the target langauge associated with the current |step|. +// |errorType| the error, if any for the current |step|. +// |triggeredFromMenu| should be true if this was a result from user action. +- (void)updateTranslateStep:(translate::TranslateStep)step + sourceLanguage:(const std::string&)sourceLanguage + targetLanguage:(const std::string&)targetLanguage + errorType:(translate::TranslateErrors::Type)errorType + triggeredFromMenu:(bool)triggeredFromMenu; + +@end + +NS_ASSUME_NONNULL_END + +#endif // IOS_WEB_VIEW_INTERNAL_TRANSLATE_CWV_TRANSLATION_CONTROLLER_INTERNAL_H
diff --git a/ios/web_view/internal/translate/cwv_translation_language.mm b/ios/web_view/internal/translate/cwv_translation_language.mm new file mode 100644 index 0000000..2edc88d --- /dev/null +++ b/ios/web_view/internal/translate/cwv_translation_language.mm
@@ -0,0 +1,29 @@ +// 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. + +#import "ios/web_view/internal/translate/cwv_translation_language_internal.h" + +#include "base/strings/string16.h" +#include "base/strings/sys_string_conversions.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@implementation CWVTranslationLanguage + +@synthesize languageCode = _languageCode; +@synthesize languageName = _languageName; + +- (instancetype)initWithLanguageCode:(const std::string&)languageCode + languageName:(const base::string16&)languageName { + self = [super init]; + if (self) { + _languageCode = base::SysUTF8ToNSString(languageCode); + _languageName = base::SysUTF16ToNSString(languageName); + } + return self; +} + +@end
diff --git a/ios/web_view/internal/translate/cwv_translation_language_internal.h b/ios/web_view/internal/translate/cwv_translation_language_internal.h new file mode 100644 index 0000000..f4d8cda --- /dev/null +++ b/ios/web_view/internal/translate/cwv_translation_language_internal.h
@@ -0,0 +1,26 @@ +// 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 IOS_WEB_VIEW_INTERNAL_TRANSLATE_CWV_TRANSLATION_LANGUAGE_INTERNAL_H +#define IOS_WEB_VIEW_INTERNAL_TRANSLATE_CWV_TRANSLATION_LANGUAGE_INTERNAL_H + +#import "ios/web_view/public/cwv_translation_language.h" + +#include <string> + +#include "base/strings/string16.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface CWVTranslationLanguage () + +- (instancetype)initWithLanguageCode:(const std::string&)languageCode + languageName:(const base::string16&)languageName + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END + +#endif // IOS_WEB_VIEW_INTERNAL_TRANSLATE_CWV_TRANSLATION_LANGUAGE_INTERNAL_H
diff --git a/ios/web_view/internal/translate/web_view_translate_client.h b/ios/web_view/internal/translate/web_view_translate_client.h index e3f1d4d..b214e5f 100644 --- a/ios/web_view/internal/translate/web_view_translate_client.h +++ b/ios/web_view/internal/translate/web_view_translate_client.h
@@ -15,7 +15,8 @@ #import "components/translate/ios/browser/ios_translate_driver.h" #include "ios/web/public/web_state/web_state_observer.h" #import "ios/web/public/web_state/web_state_user_data.h" -#import "ios/web_view/public/cwv_translate_delegate.h" + +@class CWVTranslationController; class PrefService; @@ -38,10 +39,13 @@ public: ~WebViewTranslateClient() override; - // Sets the delegate passed by the embedder. - // |delegate| is assumed to outlive this WebViewTranslateClient. - void set_translate_delegate(id<CWVTranslateDelegate> delegate) { - delegate_.reset(delegate); + // This |controller| is assumed to outlive this WebViewTranslateClient. + void set_translation_controller(CWVTranslationController* controller) { + translation_controller_.reset(controller); + } + + translate::TranslateManager* translate_manager() { + return translate_manager_.get(); } private: @@ -73,8 +77,8 @@ std::unique_ptr<translate::TranslateManager> translate_manager_; translate::IOSTranslateDriver translate_driver_; - // Delegate provided by the embedder. - base::WeakNSProtocol<id<CWVTranslateDelegate>> delegate_; + // ObjC class that wraps this class. + base::WeakNSObject<CWVTranslationController> translation_controller_; DISALLOW_COPY_AND_ASSIGN(WebViewTranslateClient); };
diff --git a/ios/web_view/internal/translate/web_view_translate_client.mm b/ios/web_view/internal/translate/web_view_translate_client.mm index 6b8ee429..20af5637 100644 --- a/ios/web_view/internal/translate/web_view_translate_client.mm +++ b/ios/web_view/internal/translate/web_view_translate_client.mm
@@ -20,11 +20,10 @@ #include "ios/web/public/browser_state.h" #import "ios/web/public/web_state/web_state.h" #include "ios/web_view/internal/pref_names.h" -#import "ios/web_view/internal/translate/cwv_translate_manager_impl.h" +#import "ios/web_view/internal/translate/cwv_translation_controller_internal.h" #include "ios/web_view/internal/translate/web_view_translate_accept_languages_factory.h" #include "ios/web_view/internal/translate/web_view_translate_ranker_factory.h" #include "ios/web_view/internal/web_view_browser_state.h" -#import "ios/web_view/public/cwv_translate_delegate.h" #include "url/gurl.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -63,12 +62,6 @@ const std::string& target_language, translate::TranslateErrors::Type error_type, bool triggered_from_menu) { - if (!delegate_.get()) - return; - - if (error_type != translate::TranslateErrors::NONE) - step = translate::TRANSLATE_STEP_TRANSLATE_ERROR; - translate_manager_->GetLanguageState().SetTranslateEnabled(true); if (step == translate::TRANSLATE_STEP_BEFORE_TRANSLATE && @@ -76,32 +69,11 @@ return; } - base::scoped_nsobject<CWVTranslateManagerImpl> criwv_manager( - [[CWVTranslateManagerImpl alloc] - initWithTranslateManager:translate_manager_.get() - sourceLanguage:source_language - targetLanguage:target_language]); - - CRIWVTransateStep criwv_step; - switch (step) { - case translate::TRANSLATE_STEP_BEFORE_TRANSLATE: - criwv_step = CRIWVTransateStepBeforeTranslate; - break; - case translate::TRANSLATE_STEP_TRANSLATING: - criwv_step = CRIWVTransateStepTranslating; - break; - case translate::TRANSLATE_STEP_AFTER_TRANSLATE: - criwv_step = CRIWVTransateStepAfterTranslate; - break; - case translate::TRANSLATE_STEP_TRANSLATE_ERROR: - criwv_step = CRIWVTransateStepError; - break; - case translate::TRANSLATE_STEP_NEVER_TRANSLATE: - NOTREACHED() << "Never translate is not supported yet in web_view."; - criwv_step = CRIWVTransateStepError; - break; - } - [delegate_ translateStepChanged:criwv_step manager:criwv_manager.get()]; + [translation_controller_ updateTranslateStep:step + sourceLanguage:source_language + targetLanguage:target_language + errorType:error_type + triggeredFromMenu:triggered_from_menu]; } translate::TranslateDriver* WebViewTranslateClient::GetTranslateDriver() {
diff --git a/ios/web_view/public/ChromeWebView.h b/ios/web_view/public/ChromeWebView.h index 4b2a1358..c0b07b6 100644 --- a/ios/web_view/public/ChromeWebView.h +++ b/ios/web_view/public/ChromeWebView.h
@@ -7,12 +7,14 @@ #import <ChromeWebView/cwv_export.h> #import <ChromeWebView/cwv_html_element.h> +#import <ChromeWebView/cwv_language_detection_result.h> #import <ChromeWebView/cwv_navigation_action.h> #import <ChromeWebView/cwv_navigation_delegate.h> #import <ChromeWebView/cwv_scroll_view.h> #import <ChromeWebView/cwv_scroll_view_delegate.h> -#import <ChromeWebView/cwv_translate_delegate.h> -#import <ChromeWebView/cwv_translate_manager.h> +#import <ChromeWebView/cwv_translation_controller.h> +#import <ChromeWebView/cwv_translation_controller_delegate.h> +#import <ChromeWebView/cwv_translation_language.h> #import <ChromeWebView/cwv_ui_delegate.h> #import <ChromeWebView/cwv_user_content_controller.h> #import <ChromeWebView/cwv_user_script.h>
diff --git a/ios/web_view/public/cwv_language_detection_result.h b/ios/web_view/public/cwv_language_detection_result.h new file mode 100644 index 0000000..78115c8 --- /dev/null +++ b/ios/web_view/public/cwv_language_detection_result.h
@@ -0,0 +1,35 @@ +// 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 IOS_WEB_VIEW_PUBLIC_CWV_LANGUAGE_DETECTION_RESULT_H +#define IOS_WEB_VIEW_PUBLIC_CWV_LANGUAGE_DETECTION_RESULT_H + +#import <ChromeWebView/cwv_export.h> +#import <Foundation/Foundation.h> + +NS_ASSUME_NONNULL_BEGIN + +@class CWVTranslationLanguage; + +// Encapsulates the results of language detection in one class. +CWV_EXPORT +@interface CWVLanguageDetectionResult : NSObject + +- (instancetype)init NS_UNAVAILABLE; + +// The detected language of the page. +@property(nonatomic, readonly) CWVTranslationLanguage* pageLanguage; + +// The suggested language to translate to. +@property(nonatomic, readonly) CWVTranslationLanguage* suggestedTargetLanguage; + +// The list of supported languages that can be used in translation. +@property(nonatomic, copy, readonly) + NSArray<CWVTranslationLanguage*>* supportedLanguages; + +@end + +NS_ASSUME_NONNULL_END + +#endif // IOS_WEB_VIEW_PUBLIC_CWV_LANGUAGE_DETECTION_RESULT_H
diff --git a/ios/web_view/public/cwv_translate_delegate.h b/ios/web_view/public/cwv_translate_delegate.h deleted file mode 100644 index d05ab15d..0000000 --- a/ios/web_view/public/cwv_translate_delegate.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_WEB_VIEW_PUBLIC_CWV_TRANSLATE_DELEGATE_H_ -#define IOS_WEB_VIEW_PUBLIC_CWV_TRANSLATE_DELEGATE_H_ - -#import <ChromeWebView/cwv_export.h> -#import <Foundation/Foundation.h> - -@protocol CWVTranslateManager; - -typedef NS_ENUM(NSInteger, CRIWVTransateStep) { - CRIWVTransateStepBeforeTranslate, - CRIWVTransateStepTranslating, - CRIWVTransateStepAfterTranslate, - CRIWVTransateStepError, -}; - -// Delegate interface for the CRIWVTranslate. Embedders can implement the -// functions in order to customize the behavior. -CWV_EXPORT -@protocol CWVTranslateDelegate - -- (void)translateStepChanged:(CRIWVTransateStep)step - manager:(id<CWVTranslateManager>)manager; - -@end - -#endif // IOS_WEB_VIEW_PUBLIC_CWV_TRANSLATE_DELEGATE_H_
diff --git a/ios/web_view/public/cwv_translate_manager.h b/ios/web_view/public/cwv_translate_manager.h deleted file mode 100644 index d2262c8..0000000 --- a/ios/web_view/public/cwv_translate_manager.h +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_WEB_VIEW_PUBLIC_CWV_TRANSLATE_MANAGER_H_ -#define IOS_WEB_VIEW_PUBLIC_CWV_TRANSLATE_MANAGER_H_ - -#import <ChromeWebView/cwv_export.h> -#import <Foundation/Foundation.h> - -// Interface to manage the translation flow. -// Clients are not supposed to instantiate or subclass it. -CWV_EXPORT -@protocol CWVTranslateManager<NSObject> - -- (void)translate; - -- (void)revertTranslation; - -@end - -#endif // IOS_WEB_VIEW_PUBLIC_CWV_TRANSLATE_MANAGER_H_
diff --git a/ios/web_view/public/cwv_translation_controller.h b/ios/web_view/public/cwv_translation_controller.h new file mode 100644 index 0000000..3229652 --- /dev/null +++ b/ios/web_view/public/cwv_translation_controller.h
@@ -0,0 +1,71 @@ +// 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 IOS_WEB_VIEW_PUBLIC_CWV_TRANSLATION_CONTROLLER_H +#define IOS_WEB_VIEW_PUBLIC_CWV_TRANSLATION_CONTROLLER_H + +#import <ChromeWebView/cwv_export.h> +#import <Foundation/Foundation.h> + +NS_ASSUME_NONNULL_BEGIN + +@class CWVTranslationLanguage; +@protocol CWVTranslationControllerDelegate; + +// The error domain for translation errors. +extern NSErrorDomain const CWVTranslationErrorDomain; + +// Possible error codes during translation. +// No connectivity. +extern const NSInteger CWVTranslationErrorNetwork; +// The translation script failed to initialize. +extern const NSInteger CWVTranslationErrorInitializationError; +// The page's language could not be detected. +extern const NSInteger CWVTranslationErrorUnknownLanguage; +// The server detected a language that the browser does not know. +extern const NSInteger CWVTranslationErrorUnsupportedLanguage; +// The original and target languages are the same. +extern const NSInteger CWVTranslationErrorIdenticalLanguages; +// An error was reported by the translation script during translation. +extern const NSInteger CWVTranslationErrorTranslationError; +// The library doesn't finish the translation. +extern const NSInteger CWVTranslationErrorTranslationTimeout; +// The library raises an unexpected exception. +extern const NSInteger CWVTranslationErrorUnexpectedScriptError; +// The library is blocked because of bad origin. +extern const NSInteger CWVTranslationErrorBadOrigin; +// Loader fails to load a dependent JavaScript. +extern const NSInteger CWVTranslationErrorScriptLoadError; + +// Allows page translation from one language to another. +CWV_EXPORT +@interface CWVTranslationController : NSObject + +// Delegate to receive translation callbacks. +@property(nullable, nonatomic, weak) id<CWVTranslationControllerDelegate> + delegate; + +// Begins translation on the current page from |sourceLanguage| to +// |targetLanguage|. These language parameters must be chosen from +// a CWWLanguageDetectionResult's |supportedLanguages|. +// This must not be called before the |delegate| receives +// |translationController:didFinishLanguageDetectionWithResult:error:|. +// TODO(crbug.com/706289): Document what happens if you call this out of order +// or many times. +- (void)translatePageFromLanguage:(CWVTranslationLanguage*)sourceLanguage + toLanguage:(CWVTranslationLanguage*)targetLanguage; + +// Reverts any translations done back to the original page language. +// Note that the original page language may be different from |sourceLanguage| +// passed to |translatePageFromLanguage:toLanguage:| above. +// This must not be called before the |delegate| receives +// |translationController:didFinishLanguageDetectionWithResult:error:|. +// TODO(crbug.com/706289): Document what happens if you call this out of order. +- (void)revertTranslation; + +@end + +NS_ASSUME_NONNULL_END + +#endif // IOS_WEB_VIEW_PUBLIC_CWV_TRANSLATION_CONTROLLER_H
diff --git a/ios/web_view/public/cwv_translation_controller_delegate.h b/ios/web_view/public/cwv_translation_controller_delegate.h new file mode 100644 index 0000000..ef09de64 --- /dev/null +++ b/ios/web_view/public/cwv_translation_controller_delegate.h
@@ -0,0 +1,46 @@ +// 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. + +#import <ChromeWebView/cwv_export.h> +#import <Foundation/Foundation.h> + +#ifndef IOS_WEB_VIEW_PUBLIC_CWV_TRANSLATION_CONTROLLER_DELEGATE_H +#define IOS_WEB_VIEW_PUBLIC_CWV_TRANSLATION_CONTROLLER_DELEGATE_H + +NS_ASSUME_NONNULL_BEGIN + +@class CWVTranslationController; +@class CWVLanguageDetectionResult; +@class CWVTranslationLanguage; + +// Updates delegate on translation progress. +CWV_EXPORT +@protocol CWVTranslationControllerDelegate<NSObject> + +@required +// Called when language detection is completed. Contains information on the +// detected language, the assumed target language for translation, as well as +// all languages supported by this translation controller. +// |error| will be nonnull if language detection failed. +- (void)translationController:(CWVTranslationController*)controller + didFinishLanguageDetectionWithResult:(CWVLanguageDetectionResult*)result + error:(nullable NSError*)error; + +@optional +// Called when a translation has started. +- (void)translationController:(CWVTranslationController*)controller + didStartTranslationFromLanguage:(CWVTranslationLanguage*)sourceLanguage + toLanguage:(CWVTranslationLanguage*)targetLanguage; + +// Called when translation finishes. |error| will be nonnull if it failed. +- (void)translationController:(CWVTranslationController*)controller + didFinishTranslationFromLanguage:(CWVTranslationLanguage*)sourceLanguage + toLanguage:(CWVTranslationLanguage*)targetLanguage + error:(nullable NSError*)error; + +@end + +NS_ASSUME_NONNULL_END + +#endif // IOS_WEB_VIEW_PUBLIC_CWV_TRANSLATION_CONTROLLER_DELEGATE_H
diff --git a/ios/web_view/public/cwv_translation_language.h b/ios/web_view/public/cwv_translation_language.h new file mode 100644 index 0000000..4138cd5 --- /dev/null +++ b/ios/web_view/public/cwv_translation_language.h
@@ -0,0 +1,30 @@ +// 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 IOS_WEB_VIEW_PUBLIC_CWV_TRANSLATION_LANGUAGE_H +#define IOS_WEB_VIEW_PUBLIC_CWV_TRANSLATION_LANGUAGE_H + +#import <ChromeWebView/cwv_export.h> +#import <Foundation/Foundation.h> + +NS_ASSUME_NONNULL_BEGIN + +// Represents a single translatable language. +CWV_EXPORT +@interface CWVTranslationLanguage : NSObject + +- (instancetype)init NS_UNAVAILABLE; + +// The ISO language code. en for English, es for Spanish, etc... +// https://cloud.google.com/translate/docs/languages +@property(nonatomic, copy, readonly) NSString* languageCode; + +// The localized language name. +@property(nonatomic, copy, readonly) NSString* languageName; + +@end + +NS_ASSUME_NONNULL_END + +#endif // IOS_WEB_VIEW_PUBLIC_CWV_TRANSLATION_LANGUAGE_H
diff --git a/ios/web_view/public/cwv_web_view.h b/ios/web_view/public/cwv_web_view.h index 3bf3ee6..c4251df2 100644 --- a/ios/web_view/public/cwv_web_view.h +++ b/ios/web_view/public/cwv_web_view.h
@@ -8,9 +8,9 @@ #import <UIKit/UIKit.h> @class CWVScrollView; +@class CWVTranslationController; @class CWVWebViewConfiguration; @protocol CWVUIDelegate; -@protocol CWVTranslateDelegate; @protocol CWVNavigationDelegate; // A web view component (like WKWebView) which uses iOS Chromium's web view @@ -29,12 +29,12 @@ // This web view's navigation delegate. @property(nonatomic, weak) id<CWVNavigationDelegate> navigationDelegate; +// This web view's translation controller. +@property(nonatomic, readonly) CWVTranslationController* translationController; + // This web view's UI delegate @property(nonatomic, weak) id<CWVUIDelegate> UIDelegate; -// A delegate for the translation feature. -@property(nonatomic, weak) id<CWVTranslateDelegate> translationDelegate; - // Whether or not this web view can go backwards or forwards. @property(nonatomic, readonly) BOOL canGoBack; @property(nonatomic, readonly) BOOL canGoForward;
diff --git a/ios/web_view/shell/BUILD.gn b/ios/web_view/shell/BUILD.gn index c67526345..1f178861 100644 --- a/ios/web_view/shell/BUILD.gn +++ b/ios/web_view/shell/BUILD.gn
@@ -20,10 +20,10 @@ "shell_app_delegate.h", "shell_app_delegate.m", "shell_exe_main.m", + "shell_translation_delegate.h", + "shell_translation_delegate.m", "shell_view_controller.h", "shell_view_controller.m", - "translate_controller.h", - "translate_controller.m", ] deps = [
diff --git a/ios/web_view/shell/shell_translation_delegate.h b/ios/web_view/shell/shell_translation_delegate.h new file mode 100644 index 0000000..19b4911 --- /dev/null +++ b/ios/web_view/shell/shell_translation_delegate.h
@@ -0,0 +1,14 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_WEB_VIEW_SHELL_SHELL_TRANSLATION_DELEGATE_H_ +#define IOS_WEB_VIEW_SHELL_SHELL_TRANSLATION_DELEGATE_H_ + +#import <ChromeWebView/ChromeWebView.h> +#import <Foundation/Foundation.h> + +@interface ShellTranslationDelegate : NSObject<CWVTranslationControllerDelegate> +@end + +#endif // IOS_WEB_VIEW_SHELL_SHELL_TRANSLATION_DELEGATE_H_
diff --git a/ios/web_view/shell/shell_translation_delegate.m b/ios/web_view/shell/shell_translation_delegate.m new file mode 100644 index 0000000..a16515ce --- /dev/null +++ b/ios/web_view/shell/shell_translation_delegate.m
@@ -0,0 +1,63 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/web_view/shell/shell_translation_delegate.h" + +#import <UIKit/UIKit.h> + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@interface ShellTranslationDelegate () +// Action Sheet to prompt user whether or not the page should be translated. +@property(nonatomic, strong) UIAlertController* beforeTranslateActionSheet; +@end + +@implementation ShellTranslationDelegate + +@synthesize beforeTranslateActionSheet = _beforeTranslateActionSheet; + +- (void)dealloc { + [_beforeTranslateActionSheet dismissViewControllerAnimated:YES + completion:nil]; +} + +#pragma mark - CWVTranslationDelegate methods + +- (void)translationController:(CWVTranslationController*)controller + didFinishLanguageDetectionWithResult:(CWVLanguageDetectionResult*)result + error:(NSError*)error { + __weak ShellTranslationDelegate* weakSelf = self; + + self.beforeTranslateActionSheet = [UIAlertController + alertControllerWithTitle:nil + message:@"Translate?" + preferredStyle:UIAlertControllerStyleActionSheet]; + UIAlertAction* cancelAction = + [UIAlertAction actionWithTitle:@"Nope." + style:UIAlertActionStyleCancel + handler:^(UIAlertAction* action) { + weakSelf.beforeTranslateActionSheet = nil; + }]; + [_beforeTranslateActionSheet addAction:cancelAction]; + + UIAlertAction* translateAction = [UIAlertAction + actionWithTitle:@"Yes!" + style:UIAlertActionStyleDefault + handler:^(UIAlertAction* action) { + weakSelf.beforeTranslateActionSheet = nil; + CWVTranslationLanguage* source = result.pageLanguage; + CWVTranslationLanguage* target = result.suggestedTargetLanguage; + [controller translatePageFromLanguage:source toLanguage:target]; + }]; + [_beforeTranslateActionSheet addAction:translateAction]; + + [[UIApplication sharedApplication].keyWindow.rootViewController + presentViewController:_beforeTranslateActionSheet + animated:YES + completion:nil]; +} + +@end
diff --git a/ios/web_view/shell/shell_view_controller.m b/ios/web_view/shell/shell_view_controller.m index da1433f..6cd9fc5 100644 --- a/ios/web_view/shell/shell_view_controller.m +++ b/ios/web_view/shell/shell_view_controller.m
@@ -7,7 +7,7 @@ #import <ChromeWebView/ChromeWebView.h> #import <MobileCoreServices/MobileCoreServices.h> -#import "ios/web_view/shell/translate_controller.h" +#import "ios/web_view/shell/shell_translation_delegate.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -32,7 +32,7 @@ // CWV view which renders the web page. @property(nonatomic, strong) CWVWebView* webView; // Handles the translation of the content displayed in |webView|. -@property(nonatomic, strong) TranslateController* translateController; +@property(nonatomic, strong) ShellTranslationDelegate* translationDelegate; - (void)back; - (void)forward; @@ -45,7 +45,7 @@ @synthesize field = _field; @synthesize toolbar = _toolbar; @synthesize webView = _webView; -@synthesize translateController = _translateController; +@synthesize translationDelegate = _translationDelegate; - (void)viewDidLoad { [super viewDidLoad]; @@ -155,8 +155,8 @@ _webView.restorationIdentifier = @"webView"; _webView.navigationDelegate = self; _webView.UIDelegate = self; - _translateController = [[TranslateController alloc] init]; - _webView.translationDelegate = _translateController; + _translationDelegate = [[ShellTranslationDelegate alloc] init]; + _webView.translationController.delegate = _translationDelegate; [_webView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
diff --git a/ios/web_view/shell/translate_controller.h b/ios/web_view/shell/translate_controller.h deleted file mode 100644 index c252251..0000000 --- a/ios/web_view/shell/translate_controller.h +++ /dev/null
@@ -1,14 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_WEB_VIEW_SHELL_TRANSLATE_CONTROLLER_H_ -#define IOS_WEB_VIEW_SHELL_TRANSLATE_CONTROLLER_H_ - -#import <ChromeWebView/ChromeWebView.h> -#import <Foundation/Foundation.h> - -@interface TranslateController : NSObject<CWVTranslateDelegate> -@end - -#endif // IOS_WEB_VIEW_SHELL_TRANSLATE_CONTROLLER_H_
diff --git a/ios/web_view/shell/translate_controller.m b/ios/web_view/shell/translate_controller.m deleted file mode 100644 index e28d0089..0000000 --- a/ios/web_view/shell/translate_controller.m +++ /dev/null
@@ -1,67 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "ios/web_view/shell/translate_controller.h" - -#import <ChromeWebView/ChromeWebView.h> -#import <UIKit/UIKit.h> - -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - -@interface TranslateController () -// Action Sheet to prompt user whether or not the page should be translated. -@property(nonatomic, strong) UIAlertController* beforeTranslateActionSheet; -// Manager which performs the translation of the content. -@property(nonatomic, strong) id<CWVTranslateManager> translateManager; -@end - -@implementation TranslateController - -@synthesize beforeTranslateActionSheet = _beforeTranslateActionSheet; -@synthesize translateManager = _translateManager; - -- (void)dealloc { - [_beforeTranslateActionSheet dismissViewControllerAnimated:YES - completion:nil]; -} - -#pragma mark CWVTranslateDelegate methods - -- (void)translateStepChanged:(CRIWVTransateStep)step - manager:(id<CWVTranslateManager>)manager { - if (step == CRIWVTransateStepBeforeTranslate) { - self.translateManager = manager; - self.beforeTranslateActionSheet = [UIAlertController - alertControllerWithTitle:nil - message:@"Translate?" - preferredStyle:UIAlertControllerStyleActionSheet]; - UIAlertAction* cancelAction = - [UIAlertAction actionWithTitle:@"Nope." - style:UIAlertActionStyleCancel - handler:^(UIAlertAction* action) { - self.beforeTranslateActionSheet = nil; - self.translateManager = nil; - }]; - [_beforeTranslateActionSheet addAction:cancelAction]; - - UIAlertAction* translateAction = - [UIAlertAction actionWithTitle:@"Yes!" - style:UIAlertActionStyleDefault - handler:^(UIAlertAction* action) { - self.beforeTranslateActionSheet = nil; - [_translateManager translate]; - self.translateManager = nil; - }]; - [_beforeTranslateActionSheet addAction:translateAction]; - - [[UIApplication sharedApplication].keyWindow.rootViewController - presentViewController:_beforeTranslateActionSheet - animated:YES - completion:nil]; - } -} - -@end
diff --git a/media/base/BUILD.gn b/media/base/BUILD.gn index f5ef5c4a..1fe71c3 100644 --- a/media/base/BUILD.gn +++ b/media/base/BUILD.gn
@@ -470,6 +470,7 @@ "time_delta_interpolator_unittest.cc", "vector_math_unittest.cc", "video_codecs_unittest.cc", + "video_color_space_unittest.cc", "video_decoder_config_unittest.cc", "video_frame_pool_unittest.cc", "video_frame_unittest.cc",
diff --git a/media/base/android/media_drm_bridge.cc b/media/base/android/media_drm_bridge.cc index 27a2bdf..3a4517e 100644 --- a/media/base/android/media_drm_bridge.cc +++ b/media/base/android/media_drm_bridge.cc
@@ -112,18 +112,18 @@ } } -ContentDecryptionModule::MessageType GetMessageType(RequestType request_type) { +CdmMessageType GetMessageType(RequestType request_type) { switch (request_type) { case RequestType::REQUEST_TYPE_INITIAL: - return ContentDecryptionModule::LICENSE_REQUEST; + return CdmMessageType::LICENSE_REQUEST; case RequestType::REQUEST_TYPE_RENEWAL: - return ContentDecryptionModule::LICENSE_RENEWAL; + return CdmMessageType::LICENSE_RENEWAL; case RequestType::REQUEST_TYPE_RELEASE: - return ContentDecryptionModule::LICENSE_RELEASE; + return CdmMessageType::LICENSE_RELEASE; } NOTREACHED(); - return ContentDecryptionModule::LICENSE_REQUEST; + return CdmMessageType::LICENSE_REQUEST; } CdmKeyInformation::KeyStatus ConvertKeyStatus(KeyStatus key_status, @@ -690,7 +690,7 @@ std::vector<uint8_t> message; JavaByteArrayToByteVector(env, j_message, &message); - ContentDecryptionModule::MessageType message_type = + CdmMessageType message_type = GetMessageType(static_cast<RequestType>(j_message_type)); task_runner_->PostTask(
diff --git a/media/base/content_decryption_module.h b/media/base/content_decryption_module.h index df06c712..fac2bcd 100644 --- a/media/base/content_decryption_module.h +++ b/media/base/content_decryption_module.h
@@ -46,6 +46,16 @@ SESSION_TYPE_MAX = PERSISTENT_RELEASE_MESSAGE_SESSION }; +// Type of message being sent to the application. +// Must be consistent with the values specified in the spec: +// https://w3c.github.io/encrypted-media/#idl-def-MediaKeyMessageType +enum class CdmMessageType { + LICENSE_REQUEST, + LICENSE_RENEWAL, + LICENSE_RELEASE, + MESSAGE_TYPE_MAX = LICENSE_RELEASE +}; + // An interface that represents the Content Decryption Module (CDM) in the // Encrypted Media Extensions (EME) spec in Chromium. // See http://w3c.github.io/encrypted-media/#cdm @@ -73,16 +83,6 @@ : public base::RefCountedThreadSafe<ContentDecryptionModule, ContentDecryptionModuleTraits> { public: - // Type of message being sent to the application. - // Must be consistent with the values specified in the spec: - // https://w3c.github.io/encrypted-media/#idl-def-MediaKeyMessageType - enum MessageType { - LICENSE_REQUEST, - LICENSE_RENEWAL, - LICENSE_RELEASE, - MESSAGE_TYPE_MAX = LICENSE_RELEASE - }; - // Provides a server certificate to be used to encrypt messages to the // license server. virtual void SetServerCertificate( @@ -170,7 +170,7 @@ // Called when the CDM needs to queue a message event to the session object. // See http://w3c.github.io/encrypted-media/#dom-evt-message typedef base::Callback<void(const std::string& session_id, - ContentDecryptionModule::MessageType message_type, + CdmMessageType message_type, const std::vector<uint8_t>& message)> SessionMessageCB;
diff --git a/media/base/ipc/media_param_traits_macros.h b/media/base/ipc/media_param_traits_macros.h index 52f5ed49..79083bc 100644 --- a/media/base/ipc/media_param_traits_macros.h +++ b/media/base/ipc/media_param_traits_macros.h
@@ -69,8 +69,8 @@ IPC_ENUM_TRAITS_MAX_VALUE(media::CdmPromise::Exception, media::CdmPromise::EXCEPTION_MAX) -IPC_ENUM_TRAITS_MAX_VALUE(media::ContentDecryptionModule::MessageType, - media::ContentDecryptionModule::MESSAGE_TYPE_MAX) +IPC_ENUM_TRAITS_MAX_VALUE(media::CdmMessageType, + media::CdmMessageType::MESSAGE_TYPE_MAX) IPC_ENUM_TRAITS_MAX_VALUE(media::CdmSessionType, media::CdmSessionType::SESSION_TYPE_MAX)
diff --git a/media/base/mock_filters.cc b/media/base/mock_filters.cc index 3625ebd..4c5d5f8 100644 --- a/media/base/mock_filters.cc +++ b/media/base/mock_filters.cc
@@ -230,10 +230,9 @@ OnRemoveSession(session_id, promise); } -void MockCdm::CallSessionMessageCB( - const std::string& session_id, - ContentDecryptionModule::MessageType message_type, - const std::vector<uint8_t>& message) { +void MockCdm::CallSessionMessageCB(const std::string& session_id, + CdmMessageType message_type, + const std::vector<uint8_t>& message) { session_message_cb_.Run(session_id, message_type, message); }
diff --git a/media/base/mock_filters.h b/media/base/mock_filters.h index 96a4ebb..cf02d45 100644 --- a/media/base/mock_filters.h +++ b/media/base/mock_filters.h
@@ -351,7 +351,7 @@ MOCK_METHOD3(OnSessionMessage, void(const std::string& session_id, - ContentDecryptionModule::MessageType message_type, + CdmMessageType message_type, const std::vector<uint8_t>& message)); MOCK_METHOD1(OnSessionClosed, void(const std::string& session_id)); @@ -511,7 +511,7 @@ MOCK_METHOD0(GetCdmContext, CdmContext*()); void CallSessionMessageCB(const std::string& session_id, - ContentDecryptionModule::MessageType message_type, + CdmMessageType message_type, const std::vector<uint8_t>& message); void CallSessionClosedCB(const std::string& session_id); void CallSessionKeysChangeCB(const std::string& session_id,
diff --git a/media/base/video_color_space.cc b/media/base/video_color_space.cc index 036cd57..03af659 100644 --- a/media/base/video_color_space.cc +++ b/media/base/video_color_space.cc
@@ -54,10 +54,138 @@ } gfx::ColorSpace VideoColorSpace::ToGfxColorSpace() const { - // TODO(hubbe): Make this type-safe. - return gfx::ColorSpace::CreateVideo(static_cast<int>(primaries), - static_cast<int>(transfer), - static_cast<int>(matrix), range); + gfx::ColorSpace::PrimaryID primary_id = gfx::ColorSpace::PrimaryID::INVALID; + gfx::ColorSpace::TransferID transfer_id = + gfx::ColorSpace::TransferID::INVALID; + gfx::ColorSpace::MatrixID matrix_id = gfx::ColorSpace::MatrixID::INVALID; + + switch (primaries) { + case PrimaryID::INVALID: + case PrimaryID::BT709: + case PrimaryID::UNSPECIFIED: + primary_id = gfx::ColorSpace::PrimaryID::BT709; + break; + case PrimaryID::BT470M: + primary_id = gfx::ColorSpace::PrimaryID::BT470M; + break; + case PrimaryID::BT470BG: + primary_id = gfx::ColorSpace::PrimaryID::BT470BG; + break; + case PrimaryID::SMPTE170M: + primary_id = gfx::ColorSpace::PrimaryID::SMPTE170M; + break; + case PrimaryID::SMPTE240M: + primary_id = gfx::ColorSpace::PrimaryID::SMPTE240M; + break; + case PrimaryID::FILM: + primary_id = gfx::ColorSpace::PrimaryID::FILM; + break; + case PrimaryID::BT2020: + primary_id = gfx::ColorSpace::PrimaryID::BT2020; + break; + case PrimaryID::SMPTEST428_1: + primary_id = gfx::ColorSpace::PrimaryID::SMPTEST428_1; + break; + case PrimaryID::SMPTEST431_2: + primary_id = gfx::ColorSpace::PrimaryID::SMPTEST431_2; + break; + case PrimaryID::SMPTEST432_1: + primary_id = gfx::ColorSpace::PrimaryID::SMPTEST432_1; + case PrimaryID::EBU_3213_E: + // TODO(uzair.jaleel) Need to check this once. + primary_id = gfx::ColorSpace::PrimaryID::INVALID; + break; + } + + switch (transfer) { + case TransferID::INVALID: + case TransferID::BT709: + case TransferID::UNSPECIFIED: + transfer_id = gfx::ColorSpace::TransferID::BT709; + break; + case TransferID::GAMMA22: + transfer_id = gfx::ColorSpace::TransferID::GAMMA22; + break; + case TransferID::GAMMA28: + transfer_id = gfx::ColorSpace::TransferID::GAMMA28; + break; + case TransferID::SMPTE170M: + transfer_id = gfx::ColorSpace::TransferID::SMPTE170M; + break; + case TransferID::SMPTE240M: + transfer_id = gfx::ColorSpace::TransferID::SMPTE240M; + break; + case TransferID::LINEAR: + transfer_id = gfx::ColorSpace::TransferID::LINEAR; + break; + case TransferID::LOG: + transfer_id = gfx::ColorSpace::TransferID::LOG; + break; + case TransferID::LOG_SQRT: + transfer_id = gfx::ColorSpace::TransferID::LOG_SQRT; + break; + case TransferID::IEC61966_2_4: + transfer_id = gfx::ColorSpace::TransferID::IEC61966_2_4; + break; + case TransferID::BT1361_ECG: + transfer_id = gfx::ColorSpace::TransferID::BT1361_ECG; + break; + case TransferID::IEC61966_2_1: + transfer_id = gfx::ColorSpace::TransferID::IEC61966_2_1; + break; + case TransferID::BT2020_10: + transfer_id = gfx::ColorSpace::TransferID::BT2020_10; + break; + case TransferID::BT2020_12: + transfer_id = gfx::ColorSpace::TransferID::BT2020_12; + break; + case TransferID::SMPTEST2084: + transfer_id = gfx::ColorSpace::TransferID::SMPTEST2084; + break; + case TransferID::SMPTEST428_1: + transfer_id = gfx::ColorSpace::TransferID::SMPTEST428_1; + break; + case TransferID::ARIB_STD_B67: + transfer_id = gfx::ColorSpace::TransferID::ARIB_STD_B67; + break; + } + + switch (matrix) { + case MatrixID::RGB: + matrix_id = gfx::ColorSpace::MatrixID::RGB; + break; + case MatrixID::INVALID: + case MatrixID::BT709: + case MatrixID::UNSPECIFIED: + matrix_id = gfx::ColorSpace::MatrixID::BT709; + break; + case MatrixID::FCC: + matrix_id = gfx::ColorSpace::MatrixID::FCC; + break; + case MatrixID::BT470BG: + matrix_id = gfx::ColorSpace::MatrixID::BT470BG; + break; + case MatrixID::SMPTE170M: + matrix_id = gfx::ColorSpace::MatrixID::SMPTE170M; + break; + case MatrixID::SMPTE240M: + matrix_id = gfx::ColorSpace::MatrixID::SMPTE240M; + break; + case MatrixID::YCOCG: + matrix_id = gfx::ColorSpace::MatrixID::YCOCG; + break; + case MatrixID::BT2020_NCL: + matrix_id = gfx::ColorSpace::MatrixID::BT2020_NCL; + break; + case MatrixID::BT2020_CL: + matrix_id = gfx::ColorSpace::MatrixID::BT2020_CL; + break; + case MatrixID::YDZDX: + matrix_id = gfx::ColorSpace::MatrixID::YDZDX; + break; + } + + return gfx::ColorSpace(primary_id, transfer_id, matrix_id, range); } VideoColorSpace VideoColorSpace::REC709() {
diff --git a/media/base/video_color_space_unittest.cc b/media/base/video_color_space_unittest.cc new file mode 100644 index 0000000..c49d08b --- /dev/null +++ b/media/base/video_color_space_unittest.cc
@@ -0,0 +1,45 @@ +// 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 "media/base/video_color_space.h" +#include "base/logging.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/gfx/color_space.h" +#include "ui/gfx/color_transform.h" +#include "ui/gfx/transform.h" + +namespace media { + +class VideoColorSpaceTest : public testing::Test {}; + +TEST(VideoColorSpaceTest, UnknownVideoToSRGB) { + // Invalid video spaces should be BT709. + VideoColorSpace invalid_video_color_space = VideoColorSpace( + VideoColorSpace::PrimaryID::INVALID, VideoColorSpace::TransferID::INVALID, + VideoColorSpace::MatrixID::INVALID, gfx::ColorSpace::RangeID::LIMITED); + gfx::ColorSpace unknown = invalid_video_color_space.ToGfxColorSpace(); + gfx::ColorSpace sRGB = gfx::ColorSpace::CreateSRGB(); + std::unique_ptr<gfx::ColorTransform> t(gfx::ColorTransform::NewColorTransform( + unknown, sRGB, gfx::ColorTransform::Intent::INTENT_PERCEPTUAL)); + + gfx::ColorTransform::TriStim tmp(16.0f / 255.0f, 0.5f, 0.5f); + t->Transform(&tmp, 1); + EXPECT_NEAR(tmp.x(), 0.0f, 0.001f); + EXPECT_NEAR(tmp.y(), 0.0f, 0.001f); + EXPECT_NEAR(tmp.z(), 0.0f, 0.001f); + + tmp = gfx::ColorTransform::TriStim(235.0f / 255.0f, 0.5f, 0.5f); + t->Transform(&tmp, 1); + EXPECT_NEAR(tmp.x(), 1.0f, 0.001f); + EXPECT_NEAR(tmp.y(), 1.0f, 0.001f); + EXPECT_NEAR(tmp.z(), 1.0f, 0.001f); + + // Test a blue color + tmp = gfx::ColorTransform::TriStim(128.0f / 255.0f, 240.0f / 255.0f, 0.5f); + t->Transform(&tmp, 1); + EXPECT_GT(tmp.z(), tmp.x()); + EXPECT_GT(tmp.z(), tmp.y()); +} + +} // namespace media
diff --git a/media/blink/cdm_session_adapter.cc b/media/blink/cdm_session_adapter.cc index 63a48d7..cd28eb1 100644 --- a/media/blink/cdm_session_adapter.cc +++ b/media/blink/cdm_session_adapter.cc
@@ -177,10 +177,9 @@ cdm_created_result_.reset(); } -void CdmSessionAdapter::OnSessionMessage( - const std::string& session_id, - ContentDecryptionModule::MessageType message_type, - const std::vector<uint8_t>& message) { +void CdmSessionAdapter::OnSessionMessage(const std::string& session_id, + CdmMessageType message_type, + const std::vector<uint8_t>& message) { WebContentDecryptionModuleSessionImpl* session = GetSession(session_id); DLOG_IF(WARNING, !session) << __func__ << " for unknown session " << session_id;
diff --git a/media/blink/cdm_session_adapter.h b/media/blink/cdm_session_adapter.h index 3a4a7a8..f870ce0 100644 --- a/media/blink/cdm_session_adapter.h +++ b/media/blink/cdm_session_adapter.h
@@ -117,7 +117,7 @@ // Callbacks for firing session events. void OnSessionMessage(const std::string& session_id, - ContentDecryptionModule::MessageType message_type, + CdmMessageType message_type, const std::vector<uint8_t>& message); void OnSessionKeysChange(const std::string& session_id, bool has_additional_usable_key,
diff --git a/media/blink/webcontentdecryptionmodulesession_impl.cc b/media/blink/webcontentdecryptionmodulesession_impl.cc index 7460c728..6db62b9 100644 --- a/media/blink/webcontentdecryptionmodulesession_impl.cc +++ b/media/blink/webcontentdecryptionmodulesession_impl.cc
@@ -43,15 +43,15 @@ const char kUpdateSessionUMAName[] = "UpdateSession"; blink::WebContentDecryptionModuleSession::Client::MessageType -convertMessageType(ContentDecryptionModule::MessageType message_type) { +convertMessageType(CdmMessageType message_type) { switch (message_type) { - case ContentDecryptionModule::LICENSE_REQUEST: + case CdmMessageType::LICENSE_REQUEST: return blink::WebContentDecryptionModuleSession::Client::MessageType:: kLicenseRequest; - case ContentDecryptionModule::LICENSE_RENEWAL: + case CdmMessageType::LICENSE_RENEWAL: return blink::WebContentDecryptionModuleSession::Client::MessageType:: kLicenseRenewal; - case ContentDecryptionModule::LICENSE_RELEASE: + case CdmMessageType::LICENSE_RELEASE: return blink::WebContentDecryptionModuleSession::Client::MessageType:: kLicenseRelease; } @@ -481,7 +481,7 @@ } void WebContentDecryptionModuleSessionImpl::OnSessionMessage( - ContentDecryptionModule::MessageType message_type, + CdmMessageType message_type, const std::vector<uint8_t>& message) { DCHECK(client_) << "Client not set before message event"; DCHECK(thread_checker_.CalledOnValidThread());
diff --git a/media/blink/webcontentdecryptionmodulesession_impl.h b/media/blink/webcontentdecryptionmodulesession_impl.h index d1ec07d..a79ea85 100644 --- a/media/blink/webcontentdecryptionmodulesession_impl.h +++ b/media/blink/webcontentdecryptionmodulesession_impl.h
@@ -51,7 +51,7 @@ void Remove(blink::WebContentDecryptionModuleResult result) override; // Callbacks. - void OnSessionMessage(ContentDecryptionModule::MessageType message_type, + void OnSessionMessage(CdmMessageType message_type, const std::vector<uint8_t>& message); void OnSessionKeysChange(bool has_additional_usable_key, CdmKeysInfo keys_info);
diff --git a/media/cdm/aes_decryptor.cc b/media/cdm/aes_decryptor.cc index 5c5f296..80cc1446 100644 --- a/media/cdm/aes_decryptor.cc +++ b/media/cdm/aes_decryptor.cc
@@ -315,7 +315,7 @@ promise->resolve(session_id); - session_message_cb_.Run(session_id, LICENSE_REQUEST, message); + session_message_cb_.Run(session_id, CdmMessageType::LICENSE_REQUEST, message); } void AesDecryptor::LoadSession(CdmSessionType session_type,
diff --git a/media/cdm/cdm_adapter.cc b/media/cdm/cdm_adapter.cc index 7b8f837..84c87b8 100644 --- a/media/cdm/cdm_adapter.cc +++ b/media/cdm/cdm_adapter.cc
@@ -87,19 +87,18 @@ return CdmPromise::UNKNOWN_ERROR; } -ContentDecryptionModule::MessageType ToMediaMessageType( - cdm::MessageType message_type) { +CdmMessageType ToMediaMessageType(cdm::MessageType message_type) { switch (message_type) { case cdm::kLicenseRequest: - return ContentDecryptionModule::LICENSE_REQUEST; + return CdmMessageType::LICENSE_REQUEST; case cdm::kLicenseRenewal: - return ContentDecryptionModule::LICENSE_RENEWAL; + return CdmMessageType::LICENSE_RENEWAL; case cdm::kLicenseRelease: - return ContentDecryptionModule::LICENSE_RELEASE; + return CdmMessageType::LICENSE_RELEASE; } NOTREACHED() << "Unexpected cdm::MessageType " << message_type; - return ContentDecryptionModule::LICENSE_REQUEST; + return CdmMessageType::LICENSE_REQUEST; } CdmKeyInformation::KeyStatus ToCdmKeyInformationKeyStatus(
diff --git a/media/cdm/ppapi/external_clear_key/clear_key_cdm.cc b/media/cdm/ppapi/external_clear_key/clear_key_cdm.cc index 80097750..b6c1934 100644 --- a/media/cdm/ppapi/external_clear_key/clear_key_cdm.cc +++ b/media/cdm/ppapi/external_clear_key/clear_key_cdm.cc
@@ -829,10 +829,9 @@ std::vector<uint8_t>(jwk_set.begin(), jwk_set.end()), std::move(promise)); } -void ClearKeyCdm::OnSessionMessage( - const std::string& session_id, - ContentDecryptionModule::MessageType message_type, - const std::vector<uint8_t>& message) { +void ClearKeyCdm::OnSessionMessage(const std::string& session_id, + CdmMessageType message_type, + const std::vector<uint8_t>& message) { DVLOG(1) << "OnSessionMessage: " << message.size(); // Ignore the message when we are waiting to update the loadable session.
diff --git a/media/cdm/ppapi/external_clear_key/clear_key_cdm.h b/media/cdm/ppapi/external_clear_key/clear_key_cdm.h index 66b77e9f..6d10d30 100644 --- a/media/cdm/ppapi/external_clear_key/clear_key_cdm.h +++ b/media/cdm/ppapi/external_clear_key/clear_key_cdm.h
@@ -94,7 +94,7 @@ // ContentDecryptionModule callbacks. void OnSessionMessage(const std::string& session_id, - ContentDecryptionModule::MessageType message_type, + CdmMessageType message_type, const std::vector<uint8_t>& message); void OnSessionKeysChange(const std::string& session_id, bool has_additional_usable_key,
diff --git a/media/filters/ffmpeg_video_decoder.cc b/media/filters/ffmpeg_video_decoder.cc index 1ed42bb9..09472056 100644 --- a/media/filters/ffmpeg_video_decoder.cc +++ b/media/filters/ffmpeg_video_decoder.cc
@@ -187,12 +187,13 @@ if (codec_context->color_primaries != AVCOL_PRI_UNSPECIFIED || codec_context->color_trc != AVCOL_TRC_UNSPECIFIED || codec_context->colorspace != AVCOL_SPC_UNSPECIFIED) { - video_frame->set_color_space(gfx::ColorSpace::CreateVideo( + media::VideoColorSpace video_color_space = media::VideoColorSpace( codec_context->color_primaries, codec_context->color_trc, codec_context->colorspace, codec_context->color_range != AVCOL_RANGE_MPEG ? gfx::ColorSpace::RangeID::FULL - : gfx::ColorSpace::RangeID::LIMITED)); + : gfx::ColorSpace::RangeID::LIMITED); + video_frame->set_color_space(video_color_space.ToGfxColorSpace()); } for (size_t i = 0; i < VideoFrame::NumPlanes(video_frame->format()); i++) {
diff --git a/media/mojo/clients/mojo_cdm.h b/media/mojo/clients/mojo_cdm.h index 425e901..9f29080 100644 --- a/media/mojo/clients/mojo_cdm.h +++ b/media/mojo/clients/mojo_cdm.h
@@ -38,7 +38,7 @@ public CdmContext, public mojom::ContentDecryptionModuleClient { public: - using MessageType = ContentDecryptionModule::MessageType; + using MessageType = CdmMessageType; static void Create( const std::string& key_system,
diff --git a/media/mojo/clients/mojo_cdm_unittest.cc b/media/mojo/clients/mojo_cdm_unittest.cc index 872e5c9..c5352df 100644 --- a/media/mojo/clients/mojo_cdm_unittest.cc +++ b/media/mojo/clients/mojo_cdm_unittest.cc
@@ -582,8 +582,7 @@ TEST_F(MojoCdmTest, SessionMessageCB_Success) { const std::string session_id = "message"; - const ContentDecryptionModule::MessageType message_type = - ContentDecryptionModule::LICENSE_REQUEST; + const CdmMessageType message_type = CdmMessageType::LICENSE_REQUEST; const std::vector<uint8_t> message = {0, 1, 2}; Initialize(SUCCESS); EXPECT_CALL(cdm_client_, OnSessionMessage(session_id, message_type, message));
diff --git a/media/mojo/interfaces/content_decryption_module.mojom b/media/mojo/interfaces/content_decryption_module.mojom index 5c02bd3..646c515 100644 --- a/media/mojo/interfaces/content_decryption_module.mojom +++ b/media/mojo/interfaces/content_decryption_module.mojom
@@ -11,6 +11,14 @@ [Native] enum EmeInitDataType; +// See media::CdmSessionType +[Native] +enum CdmSessionType; + +// See media::CdmMessageType +[Native] +enum CdmMessageType; + // Transport layer of media::CdmConfig (see media/base/cdm_config.h). struct CdmConfig { bool allow_distinctive_identifier; @@ -50,9 +58,6 @@ // spec (https://w3c.github.io/encrypted-media/). // See media/base/content_decryption_module.h interface ContentDecryptionModule { - // See media::CdmSessionType - [Native] - enum SessionType; // Sets ContentDecryptionModuleClient. Must be called before any other calls. SetClient(ContentDecryptionModuleClient client); @@ -73,7 +78,7 @@ // Creates a session with the |init_data_type|, |init_data| and |session_type| // provided. If |result.success| is false, the output |session_id| will be // empty. - CreateSessionAndGenerateRequest(SessionType session_type, + CreateSessionAndGenerateRequest(CdmSessionType session_type, EmeInitDataType init_data_type, array<uint8> init_data) => (CdmPromiseResult result, string session_id); @@ -84,7 +89,7 @@ // (true, empty) : Session not found. // (false, non-empty): N/A; this combination is not allowed. // (false, empty) : Unexpected error. See other fields in |result|. - LoadSession(SessionType session_type, string session_id) + LoadSession(CdmSessionType session_type, string session_id) => (CdmPromiseResult result, string session_id); // Updates a session specified by |session_id| with |response|. @@ -101,11 +106,7 @@ // Session callbacks. See media/base/content_decryption_module.h for details. interface ContentDecryptionModuleClient { - // See media::ContentDecryptionModule::MessageType - [Native] - enum MessageType; - - OnSessionMessage(string session_id, MessageType message_type, + OnSessionMessage(string session_id, CdmMessageType message_type, array<uint8> message); OnSessionClosed(string session_id);
diff --git a/media/mojo/interfaces/content_decryption_module.typemap b/media/mojo/interfaces/content_decryption_module.typemap index 7aadbc9c..372bde3 100644 --- a/media/mojo/interfaces/content_decryption_module.typemap +++ b/media/mojo/interfaces/content_decryption_module.typemap
@@ -21,7 +21,7 @@ type_mappings = [ "media.mojom.CdmKeyInformation.KeyStatus=media::CdmKeyInformation::KeyStatus", "media.mojom.CdmPromiseResult.Exception=media::CdmPromise::Exception", - "media.mojom.ContentDecryptionModule.SessionType=media::CdmSessionType", - "media.mojom.ContentDecryptionModuleClient.MessageType=media::ContentDecryptionModule::MessageType", + "media.mojom.CdmSessionType=media::CdmSessionType", + "media.mojom.CdmMessageType=media::CdmMessageType", "media.mojom.EmeInitDataType=media::EmeInitDataType", ]
diff --git a/media/mojo/services/mojo_cdm_service.cc b/media/mojo/services/mojo_cdm_service.cc index 45357ab5..4f5d3d4 100644 --- a/media/mojo/services/mojo_cdm_service.cc +++ b/media/mojo/services/mojo_cdm_service.cc
@@ -162,11 +162,10 @@ std::move(decryptor_service)); } -void MojoCdmService::OnSessionMessage( - const std::string& session_id, - ::media::ContentDecryptionModule::MessageType message_type, - const std::vector<uint8_t>& message) { - DVLOG(2) << __func__ << "(" << message_type << ")"; +void MojoCdmService::OnSessionMessage(const std::string& session_id, + ::media::CdmMessageType message_type, + const std::vector<uint8_t>& message) { + DVLOG(2) << __func__; client_->OnSessionMessage(session_id, message_type, message); }
diff --git a/media/mojo/services/mojo_cdm_service.h b/media/mojo/services/mojo_cdm_service.h index 737acc4..cd77fe24 100644 --- a/media/mojo/services/mojo_cdm_service.h +++ b/media/mojo/services/mojo_cdm_service.h
@@ -82,10 +82,9 @@ const std::string& error_message); // Callbacks for firing session events. - void OnSessionMessage( - const std::string& session_id, - ::media::ContentDecryptionModule::MessageType message_type, - const std::vector<uint8_t>& message); + void OnSessionMessage(const std::string& session_id, + ::media::CdmMessageType message_type, + const std::vector<uint8_t>& message); void OnSessionKeysChange(const std::string& session_id, bool has_additional_usable_key, CdmKeysInfo keys_info);
diff --git a/media/remoting/proto_enum_utils.cc b/media/remoting/proto_enum_utils.cc index cd52a04b..45e6ff7 100644 --- a/media/remoting/proto_enum_utils.cc +++ b/media/remoting/proto_enum_utils.cc
@@ -499,10 +499,9 @@ return base::nullopt; // Not a 'default' to ensure compile-time checks. } -base::Optional<ContentDecryptionModule::MessageType> ToMediaCdmMessageType( - pb::CdmMessageType value) { +base::Optional<CdmMessageType> ToMediaCdmMessageType(pb::CdmMessageType value) { using OriginType = pb::CdmMessageType; - using OtherType = ContentDecryptionModule; + using OtherType = CdmMessageType; switch (value) { CASE_RETURN_OTHER(LICENSE_REQUEST); CASE_RETURN_OTHER(LICENSE_RENEWAL); @@ -511,9 +510,8 @@ return base::nullopt; // Not a 'default' to ensure compile-time checks. } -base::Optional<pb::CdmMessageType> ToProtoCdmMessageType( - ContentDecryptionModule::MessageType value) { - using OriginType = ContentDecryptionModule; +base::Optional<pb::CdmMessageType> ToProtoCdmMessageType(CdmMessageType value) { + using OriginType = CdmMessageType; using OtherType = pb::CdmMessageType; switch (value) { CASE_RETURN_OTHER(LICENSE_REQUEST);
diff --git a/media/remoting/proto_enum_utils.h b/media/remoting/proto_enum_utils.h index 118b29b..1ffd188 100644 --- a/media/remoting/proto_enum_utils.h +++ b/media/remoting/proto_enum_utils.h
@@ -86,10 +86,8 @@ base::Optional<pb::CdmException> ToProtoCdmException( CdmPromise::Exception value); -base::Optional<ContentDecryptionModule::MessageType> ToMediaCdmMessageType( - pb::CdmMessageType value); -base::Optional<pb::CdmMessageType> ToProtoCdmMessageType( - ContentDecryptionModule::MessageType value); +base::Optional<CdmMessageType> ToMediaCdmMessageType(pb::CdmMessageType value); +base::Optional<pb::CdmMessageType> ToProtoCdmMessageType(CdmMessageType value); base::Optional<CdmSessionType> ToCdmSessionType(pb::CdmSessionType value); base::Optional<pb::CdmSessionType> ToProtoCdmSessionType(CdmSessionType value);
diff --git a/media/remoting/rpc.proto b/media/remoting/rpc.proto index 20a6883..f8f0cd6 100644 --- a/media/remoting/rpc.proto +++ b/media/remoting/rpc.proto
@@ -286,7 +286,7 @@ OUTPUT_ERROR = 6; } -// Proto version of media::ContentDecryptionModule::MessageType. +// Proto version of media::CdmMessageType. // NEVER change these numbers or re-use old ones; only add new ones. enum CdmMessageType { LICENSE_REQUEST = 0;
diff --git a/media/test/fake_encrypted_media.cc b/media/test/fake_encrypted_media.cc index 465f972..fabccc6 100644 --- a/media/test/fake_encrypted_media.cc +++ b/media/test/fake_encrypted_media.cc
@@ -42,10 +42,9 @@ } // Callbacks for firing session events. Delegate to |app_|. -void FakeEncryptedMedia::OnSessionMessage( - const std::string& session_id, - ContentDecryptionModule::MessageType message_type, - const std::vector<uint8_t>& message) { +void FakeEncryptedMedia::OnSessionMessage(const std::string& session_id, + CdmMessageType message_type, + const std::vector<uint8_t>& message) { app_->OnSessionMessage(session_id, message_type, message, decryptor_.get()); }
diff --git a/media/test/fake_encrypted_media.h b/media/test/fake_encrypted_media.h index 59f50b3..72c63ec 100644 --- a/media/test/fake_encrypted_media.h +++ b/media/test/fake_encrypted_media.h
@@ -21,11 +21,10 @@ public: virtual ~AppBase() {} - virtual void OnSessionMessage( - const std::string& session_id, - ContentDecryptionModule::MessageType message_type, - const std::vector<uint8_t>& message, - AesDecryptor* decryptor) = 0; + virtual void OnSessionMessage(const std::string& session_id, + CdmMessageType message_type, + const std::vector<uint8_t>& message, + AesDecryptor* decryptor) = 0; virtual void OnSessionClosed(const std::string& session_id) = 0; @@ -46,7 +45,7 @@ CdmContext* GetCdmContext(); // Callbacks for firing session events. Delegate to |app_|. void OnSessionMessage(const std::string& session_id, - ContentDecryptionModule::MessageType message_type, + CdmMessageType message_type, const std::vector<uint8_t>& message); void OnSessionClosed(const std::string& session_id); void OnSessionKeysChange(const std::string& session_id,
diff --git a/media/test/pipeline_integration_test.cc b/media/test/pipeline_integration_test.cc index 3b7a8ce..cd53510 100644 --- a/media/test/pipeline_integration_test.cc +++ b/media/test/pipeline_integration_test.cc
@@ -228,14 +228,13 @@ } void OnSessionMessage(const std::string& session_id, - ContentDecryptionModule::MessageType message_type, + CdmMessageType message_type, const std::vector<uint8_t>& message, AesDecryptor* decryptor) override { EXPECT_FALSE(session_id.empty()); EXPECT_FALSE(message.empty()); EXPECT_EQ(current_session_id_, session_id); - EXPECT_EQ(ContentDecryptionModule::MessageType::LICENSE_REQUEST, - message_type); + EXPECT_EQ(CdmMessageType::LICENSE_REQUEST, message_type); // Extract the key ID from |message|. For Clear Key this is a JSON object // containing a set of "kids". There should only be 1 key ID in |message|. @@ -338,7 +337,7 @@ class NoResponseApp : public FakeEncryptedMedia::AppBase { public: void OnSessionMessage(const std::string& session_id, - ContentDecryptionModule::MessageType message_type, + CdmMessageType message_type, const std::vector<uint8_t>& message, AesDecryptor* decryptor) override { EXPECT_FALSE(session_id.empty());
diff --git a/mojo/common/values_struct_traits.cc b/mojo/common/values_struct_traits.cc index 12e5173..886330bf 100644 --- a/mojo/common/values_struct_traits.cc +++ b/mojo/common/values_struct_traits.cc
@@ -2,9 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/memory/ptr_util.h" #include "mojo/common/values_struct_traits.h" +#include <memory> +#include <utility> +#include <vector> + +#include "base/containers/flat_map.h" +#include "base/memory/ptr_util.h" + namespace mojo { bool StructTraits<common::mojom::ListValueDataView, @@ -32,16 +38,19 @@ std::unique_ptr<base::DictionaryValue>* value_out) { mojo::MapDataView<mojo::StringDataView, common::mojom::ValueDataView> view; data.GetValuesDataView(&view); - auto dictionary_value = base::MakeUnique<base::DictionaryValue>(); + std::vector<base::Value::DictStorage::value_type> dict_storage; + dict_storage.reserve(view.size()); for (size_t i = 0; i < view.size(); ++i) { base::StringPiece key; std::unique_ptr<base::Value> value; if (!view.keys().Read(i, &key) || !view.values().Read(i, &value)) return false; - dictionary_value->SetWithoutPathExpansion(key, std::move(value)); + dict_storage.emplace_back(key.as_string(), std::move(value)); } - *value_out = std::move(dictionary_value); + *value_out = base::DictionaryValue::From( + base::MakeUnique<base::Value>(base::Value::DictStorage( + std::move(dict_storage), base::KEEP_LAST_OF_DUPES))); return true; }
diff --git a/net/http/http_util.cc b/net/http/http_util.cc index b1ff944..5f7c8531e 100644 --- a/net/http/http_util.cc +++ b/net/http/http_util.cc
@@ -345,6 +345,12 @@ } // namespace // static +bool HttpUtil::IsMethodSafe(const std::string& method) { + return method == "GET" || method == "HEAD" || method == "OPTIONS" || + method == "TRACE"; +} + +// static bool HttpUtil::IsSafeHeader(const std::string& name) { std::string lower_name(base::ToLowerASCII(name)); if (base::StartsWith(lower_name, "proxy-", base::CompareCase::SENSITIVE) ||
diff --git a/net/http/http_util.h b/net/http/http_util.h index cb3de35..5903238 100644 --- a/net/http/http_util.h +++ b/net/http/http_util.h
@@ -75,6 +75,9 @@ base::Time now, base::TimeDelta* retry_after); + // True if the request method is "safe" (per section 4.2.1 of RFC 7231). + static bool IsMethodSafe(const std::string& method); + // Returns true if it is safe to allow users and scripts to specify the header // named |name|. static bool IsSafeHeader(const std::string& name);
diff --git a/net/quic/chromium/quic_chromium_client_stream.cc b/net/quic/chromium/quic_chromium_client_stream.cc index 08cd6d8..8782b9a 100644 --- a/net/quic/chromium/quic_chromium_client_stream.cc +++ b/net/quic/chromium/quic_chromium_client_stream.cc
@@ -32,6 +32,7 @@ initial_headers_sent_(false), session_(session), can_migrate_(true), + initial_headers_frame_len_(0), weak_factory_(this) {} QuicChromiumClientStream::~QuicChromiumClientStream() { @@ -57,8 +58,15 @@ ConsumeHeaderList(); session_->OnInitialHeadersComplete(id(), header_block); - // The delegate will read the headers via a posted task. - NotifyDelegateOfHeadersCompleteLater(std::move(header_block), frame_len); + if (delegate_) { + // The delegate will receive the headers via a posted task. + NotifyDelegateOfHeadersCompleteLater(std::move(header_block), frame_len); + return; + } + + // Buffer the headers and deliver them when the delegate arrives. + initial_headers_ = std::move(header_block); + initial_headers_frame_len_ = frame_len; } void QuicChromiumClientStream::OnTrailingHeadersComplete( @@ -101,14 +109,14 @@ // The delegate will read the data via a posted task, and // will be able to, potentially, read all data which has queued up. - NotifyDelegateOfDataAvailableLater(); + if (delegate_) + NotifyDelegateOfDataAvailableLater(); } void QuicChromiumClientStream::OnClose() { if (delegate_) { delegate_->OnClose(); delegate_ = nullptr; - delegate_tasks_.clear(); } QuicStream::OnClose(); } @@ -186,14 +194,13 @@ QuicChromiumClientStream::Delegate* delegate) { DCHECK(!(delegate_ && delegate)); delegate_ = delegate; - if (delegate == nullptr) { - DCHECK(delegate_tasks_.empty()); + if (delegate == nullptr) return; - } - while (!delegate_tasks_.empty()) { - base::Closure closure = delegate_tasks_.front(); - delegate_tasks_.pop_front(); - closure.Run(); + + // Should this perhaps be via PostTask to make reasoning simpler? + if (!initial_headers_.empty()) { + delegate_->OnHeadersAvailable(std::move(initial_headers_), + initial_headers_frame_len_); } } @@ -201,7 +208,6 @@ if (delegate_) { QuicChromiumClientStream::Delegate* delegate = delegate_; delegate_ = nullptr; - delegate_tasks_.clear(); delegate->OnError(error); } } @@ -225,9 +231,12 @@ void QuicChromiumClientStream::NotifyDelegateOfHeadersCompleteLater( SpdyHeaderBlock headers, size_t frame_len) { - RunOrBuffer(base::Bind( - &QuicChromiumClientStream::NotifyDelegateOfHeadersComplete, - weak_factory_.GetWeakPtr(), base::Passed(std::move(headers)), frame_len)); + DCHECK(delegate_); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::Bind(&QuicChromiumClientStream::NotifyDelegateOfHeadersComplete, + weak_factory_.GetWeakPtr(), base::Passed(std::move(headers)), + frame_len)); } void QuicChromiumClientStream::NotifyDelegateOfHeadersComplete( @@ -254,7 +263,9 @@ } void QuicChromiumClientStream::NotifyDelegateOfDataAvailableLater() { - RunOrBuffer( + DCHECK(delegate_); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::Bind(&QuicChromiumClientStream::NotifyDelegateOfDataAvailable, weak_factory_.GetWeakPtr())); } @@ -264,14 +275,6 @@ delegate_->OnDataAvailable(); } -void QuicChromiumClientStream::RunOrBuffer(base::Closure closure) { - if (delegate_) { - base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, closure); - } else { - delegate_tasks_.push_back(closure); - } -} - void QuicChromiumClientStream::DisableConnectionMigration() { can_migrate_ = false; }
diff --git a/net/quic/chromium/quic_chromium_client_stream.h b/net/quic/chromium/quic_chromium_client_stream.h index cd867e2..ce47b64 100644 --- a/net/quic/chromium/quic_chromium_client_stream.h +++ b/net/quic/chromium/quic_chromium_client_stream.h
@@ -126,7 +126,6 @@ size_t frame_len); void NotifyDelegateOfDataAvailableLater(); void NotifyDelegateOfDataAvailable(); - void RunOrBuffer(base::Closure closure); NetLogWithSource net_log_; Delegate* delegate_; @@ -145,8 +144,10 @@ // Set to false if this stream to not be migrated during connection migration. bool can_migrate_; - // Holds notifications generated before delegate_ is set. - std::deque<base::Closure> delegate_tasks_; + // Stores the initial header if they arrive before the delegate. + SpdyHeaderBlock initial_headers_; + // Length of the HEADERS frame containing initial headers. + size_t initial_headers_frame_len_; base::WeakPtrFactory<QuicChromiumClientStream> weak_factory_;
diff --git a/net/url_request/url_request_http_job.cc b/net/url_request/url_request_http_job.cc index a54e0ef..203a6e2 100644 --- a/net/url_request/url_request_http_job.cc +++ b/net/url_request/url_request_http_job.cc
@@ -77,12 +77,6 @@ namespace { -// True if the request method is "safe" (per section 4.2.1 of RFC 7231). -bool IsMethodSafe(const std::string& method) { - return method == "GET" || method == "HEAD" || method == "OPTIONS" || - method == "TRACE"; -} - // Logs whether the CookieStore used for this request matches the // ChannelIDService used when establishing the connection that this request is // sent over. This logging is only done for requests to accounts.google.com, and @@ -704,7 +698,7 @@ registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) { options.set_same_site_cookie_mode( CookieOptions::SameSiteCookieMode::INCLUDE_STRICT_AND_LAX); - } else if (IsMethodSafe(request_->method())) { + } else if (HttpUtil::IsMethodSafe(request_->method())) { options.set_same_site_cookie_mode( CookieOptions::SameSiteCookieMode::INCLUDE_LAX); }
diff --git a/rlz/BUILD.gn b/rlz/BUILD.gn index f830d26a1..229991f 100644 --- a/rlz/BUILD.gn +++ b/rlz/BUILD.gn
@@ -11,72 +11,6 @@ defines = [ "RLZ_NETWORK_IMPLEMENTATION_CHROME_NET" ] } -source_set("rlz_lib") { - sources = [ - "chromeos/lib/machine_id_chromeos.cc", - "chromeos/lib/rlz_value_store_chromeos.cc", - "chromeos/lib/rlz_value_store_chromeos.h", - "ios/lib/machine_id_ios.cc", - "lib/crc8.cc", - "lib/crc8.h", - "lib/financial_ping.cc", - "lib/financial_ping.h", - "lib/machine_id.cc", - "lib/machine_id.h", - "lib/recursive_cross_process_lock_posix.cc", - "lib/recursive_cross_process_lock_posix.h", - "lib/rlz_lib.cc", - "lib/rlz_lib.h", - "lib/rlz_lib_clear.cc", - "lib/rlz_value_store.h", - "mac/lib/machine_id_mac.cc", - "mac/lib/rlz_value_store_mac.h", - "mac/lib/rlz_value_store_mac.mm", - "win/lib/lib_mutex.cc", - "win/lib/lib_mutex.h", - "win/lib/machine_deal.cc", - "win/lib/machine_deal.h", - "win/lib/machine_id_win.cc", - "win/lib/process_info.cc", - "win/lib/process_info.h", - "win/lib/registry_util.cc", - "win/lib/registry_util.h", - "win/lib/rlz_lib_win.cc", - "win/lib/rlz_value_store_registry.cc", - "win/lib/rlz_value_store_registry.h", - ] - - # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. - configs += [ "//build/config/compiler:no_size_t_to_int_warning" ] - - public_configs = [ ":rlz_config" ] - - deps = [ - ":rlz_utils", - "//base", - "//base/third_party/dynamic_annotations", - "//net", - "//url", - ] - - if (is_mac) { - libs = [ - "Foundation.framework", - "IOKit.framework", - ] - } - - if (is_ios) { - # These _mac files are also used on iOS. - set_sources_assignment_filter([]) - sources += [ - "mac/lib/rlz_value_store_mac.h", - "mac/lib/rlz_value_store_mac.mm", - ] - set_sources_assignment_filter(sources_assignment_filter) - } -} - source_set("rlz_utils") { sources = [ "lib/assert.cc", @@ -103,49 +37,117 @@ ] } -source_set("test_support") { - testonly = true - sources = [ - "test/rlz_test_helpers.cc", - "test/rlz_test_helpers.h", - ] - deps = [ - ":rlz_lib", - "//base", - "//base/test:test_support", - "//testing/gtest", - ] +if (!is_android) { + source_set("rlz_lib") { + sources = [ + "chromeos/lib/machine_id_chromeos.cc", + "chromeos/lib/rlz_value_store_chromeos.cc", + "chromeos/lib/rlz_value_store_chromeos.h", + "ios/lib/machine_id_ios.cc", + "lib/crc8.cc", + "lib/crc8.h", + "lib/financial_ping.cc", + "lib/financial_ping.h", + "lib/machine_id.cc", + "lib/machine_id.h", + "lib/recursive_cross_process_lock_posix.cc", + "lib/recursive_cross_process_lock_posix.h", + "lib/rlz_lib.cc", + "lib/rlz_lib.h", + "lib/rlz_lib_clear.cc", + "lib/rlz_value_store.h", + "mac/lib/machine_id_mac.cc", + "mac/lib/rlz_value_store_mac.h", + "mac/lib/rlz_value_store_mac.mm", + "win/lib/lib_mutex.cc", + "win/lib/lib_mutex.h", + "win/lib/machine_deal.cc", + "win/lib/machine_deal.h", + "win/lib/machine_id_win.cc", + "win/lib/process_info.cc", + "win/lib/process_info.h", + "win/lib/registry_util.cc", + "win/lib/registry_util.h", + "win/lib/rlz_lib_win.cc", + "win/lib/rlz_value_store_registry.cc", + "win/lib/rlz_value_store_registry.h", + ] + + # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. + configs += [ "//build/config/compiler:no_size_t_to_int_warning" ] + + public_configs = [ ":rlz_config" ] + + deps = [ + ":rlz_utils", + "//base", + "//base/third_party/dynamic_annotations", + "//net", + "//url", + ] + + if (is_mac) { + libs = [ + "Foundation.framework", + "IOKit.framework", + ] + } + + if (is_ios) { + # These _mac files are also used on iOS. + set_sources_assignment_filter([]) + sources += [ + "mac/lib/rlz_value_store_mac.h", + "mac/lib/rlz_value_store_mac.mm", + ] + set_sources_assignment_filter(sources_assignment_filter) + } + } + + source_set("test_support") { + testonly = true + sources = [ + "test/rlz_test_helpers.cc", + "test/rlz_test_helpers.h", + ] + deps = [ + ":rlz_lib", + "//base", + "//base/test:test_support", + "//testing/gtest", + ] + } + + test("rlz_unittests") { + sources = [ + "lib/crc32_unittest.cc", + "lib/crc8_unittest.cc", + "lib/financial_ping_test.cc", + "lib/lib_values_unittest.cc", + "lib/machine_id_unittest.cc", + "lib/rlz_lib_test.cc", + "lib/string_utils_unittest.cc", + "test/rlz_unittest_main.cc", + "win/lib/machine_deal_test.cc", + ] + + # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. + configs += [ "//build/config/compiler:no_size_t_to_int_warning" ] + + deps = [ + ":rlz_lib", + ":rlz_utils", + ":test_support", + "//base", + "//net:test_support", + "//testing/gmock", + "//testing/gtest", + "//third_party/zlib", + ] + } } -test("rlz_unittests") { - sources = [ - "lib/crc32_unittest.cc", - "lib/crc8_unittest.cc", - "lib/financial_ping_test.cc", - "lib/lib_values_unittest.cc", - "lib/machine_id_unittest.cc", - "lib/rlz_lib_test.cc", - "lib/string_utils_unittest.cc", - "test/rlz_unittest_main.cc", - "win/lib/machine_deal_test.cc", - ] - - # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. - configs += [ "//build/config/compiler:no_size_t_to_int_warning" ] - - deps = [ - ":rlz_lib", - ":rlz_utils", - ":test_support", - "//base", - "//net:test_support", - "//testing/gmock", - "//testing/gtest", - "//third_party/zlib", - ] -} - -if (!is_ios) { +if (!is_ios && !is_android) { executable("rlz_id") { sources = [ "examples/rlz_id.cc",
diff --git a/services/ui/gpu/gpu_main.cc b/services/ui/gpu/gpu_main.cc index fed0107d..0107591 100644 --- a/services/ui/gpu/gpu_main.cc +++ b/services/ui/gpu/gpu_main.cc
@@ -52,7 +52,7 @@ io_thread_("GpuIOThread"), compositor_thread_("DisplayCompositorThread"), power_monitor_(base::MakeUnique<base::PowerMonitorDeviceSource>()), - binding_(this, std::move(request)) { + binding_(this) { base::Thread::Options thread_options; #if defined(OS_WIN) @@ -92,6 +92,16 @@ // Start the compositor thread. compositor_thread_.Start(); compositor_thread_task_runner_ = compositor_thread_.task_runner(); + + // |this| will outlive the gpu thread and so it's safe to use + // base::Unretained here. + gpu_thread_task_runner_->PostTask( + FROM_HERE, + base::Bind(&GpuMain::InitOnGpuThread, base::Unretained(this), + io_thread_.task_runner(), compositor_thread_task_runner_)); + gpu_thread_task_runner_->PostTask( + FROM_HERE, base::Bind(&GpuMain::BindOnGpu, base::Unretained(this), + base::Passed(std::move(request)))); } GpuMain::~GpuMain() { @@ -112,34 +122,21 @@ io_thread_.Stop(); } -void GpuMain::OnStart() { - // |this| will outlive the gpu thread and so it's safe to use - // base::Unretained here. - gpu_thread_task_runner_->PostTask( - FROM_HERE, - base::Bind(&GpuMain::InitOnGpuThread, base::Unretained(this), - io_thread_.task_runner(), compositor_thread_task_runner_)); -} - void GpuMain::CreateGpuService(mojom::GpuServiceRequest request, mojom::GpuHostPtr gpu_host, const gpu::GpuPreferences& preferences, mojo::ScopedSharedBufferHandle activity_flags) { - // |this| will outlive the gpu thread and so it's safe to use - // base::Unretained here. - gpu_thread_task_runner_->PostTask( - FROM_HERE, - base::Bind(&GpuMain::CreateGpuServiceOnGpuThread, base::Unretained(this), - base::Passed(std::move(request)), - base::Passed(gpu_host.PassInterface()), preferences, - base::Passed( - gpu::GpuProcessActivityFlags(std::move(activity_flags))))); + DCHECK(gpu_thread_task_runner_->BelongsToCurrentThread()); + CreateGpuServiceOnGpuThread( + std::move(request), std::move(gpu_host), preferences, + gpu::GpuProcessActivityFlags(std::move(activity_flags))); } void GpuMain::CreateFrameSinkManager( cc::mojom::FrameSinkManagerRequest request, cc::mojom::FrameSinkManagerClientPtr client) { - if (!gpu_service_) { + DCHECK(gpu_thread_task_runner_->BelongsToCurrentThread()); + if (!gpu_service_ || !gpu_service_->is_initialized()) { pending_frame_sink_manager_request_ = std::move(request); pending_frame_sink_manager_client_info_ = client.PassInterface(); return; @@ -147,6 +144,10 @@ CreateFrameSinkManagerInternal(std::move(request), client.PassInterface()); } +void GpuMain::BindOnGpu(mojom::GpuMainRequest request) { + binding_.Bind(std::move(request)); +} + void GpuMain::InitOnGpuThread( scoped_refptr<base::SingleThreadTaskRunner> io_runner, scoped_refptr<base::SingleThreadTaskRunner> compositor_runner) { @@ -167,6 +168,7 @@ cc::mojom::FrameSinkManagerClientPtrInfo client_info) { DCHECK(!gpu_command_service_); DCHECK(gpu_service_); + DCHECK(gpu_thread_task_runner_->BelongsToCurrentThread()); gpu_command_service_ = new gpu::GpuInProcessThreadService( gpu_thread_task_runner_, gpu_service_->sync_point_manager(), gpu_service_->mailbox_manager(), gpu_service_->share_group()); @@ -175,18 +177,10 @@ mojom::GpuServicePtr gpu_service; mojom::GpuServiceRequest gpu_service_request(&gpu_service); - if (gpu_thread_task_runner_->BelongsToCurrentThread()) { - // If the FrameSinkManager creation was delayed because GpuService had not - // been created yet, then this is called, in gpu thread, right after - // GpuService is created. - BindGpuInternalOnGpuThread(std::move(gpu_service_request)); - } else { - gpu_thread_task_runner_->PostTask( - FROM_HERE, - base::Bind(&GpuMain::BindGpuInternalOnGpuThread, base::Unretained(this), - base::Passed(std::move(gpu_service_request)))); - } - + // If the FrameSinkManager creation was delayed because GpuService had not + // been created yet, then this is called, in gpu thread, right after + // GpuService is created. + BindGpuInternalOnGpuThread(std::move(gpu_service_request)); compositor_thread_task_runner_->PostTask( FROM_HERE, base::Bind(&GpuMain::CreateFrameSinkManagerOnCompositorThread, base::Unretained(this), image_factory, @@ -224,6 +218,7 @@ } void GpuMain::TearDownOnGpuThread() { + binding_.Close(); gpu_service_.reset(); gpu_memory_buffer_factory_.reset(); gpu_init_.reset(); @@ -231,11 +226,9 @@ void GpuMain::CreateGpuServiceOnGpuThread( mojom::GpuServiceRequest request, - mojom::GpuHostPtrInfo gpu_host_info, + mojom::GpuHostPtr gpu_host, const gpu::GpuPreferences& preferences, gpu::GpuProcessActivityFlags activity_flags) { - mojom::GpuHostPtr gpu_host; - gpu_host.Bind(std::move(gpu_host_info)); gpu_service_->UpdateGPUInfoFromPreferences(preferences); gpu_service_->InitializeWithHost(std::move(gpu_host), std::move(activity_flags));
diff --git a/services/ui/gpu/gpu_main.h b/services/ui/gpu/gpu_main.h index 005c6d5..4b87174 100644 --- a/services/ui/gpu/gpu_main.h +++ b/services/ui/gpu/gpu_main.h
@@ -46,6 +46,7 @@ GpuService* gpu_service() { return gpu_service_.get(); } private: + void BindOnGpu(mojom::GpuMainRequest request); void InitOnGpuThread( scoped_refptr<base::SingleThreadTaskRunner> io_runner, scoped_refptr<base::SingleThreadTaskRunner> compositor_runner); @@ -59,7 +60,7 @@ cc::mojom::FrameSinkManagerRequest request, cc::mojom::FrameSinkManagerClientPtrInfo client_info); void CreateGpuServiceOnGpuThread(mojom::GpuServiceRequest request, - mojom::GpuHostPtrInfo gpu_host_info, + mojom::GpuHostPtr gpu_host, const gpu::GpuPreferences& preferences, gpu::GpuProcessActivityFlags activity_flags); void BindGpuInternalOnGpuThread(mojom::GpuServiceRequest request);
diff --git a/services/ui/gpu/gpu_service.h b/services/ui/gpu/gpu_service.h index f07519b..d6e2d3f 100644 --- a/services/ui/gpu/gpu_service.h +++ b/services/ui/gpu/gpu_service.h
@@ -61,6 +61,8 @@ base::WaitableEvent* shutdown_event = nullptr); void Bind(mojom::GpuServiceRequest request); + bool is_initialized() const { return !!gpu_host_; } + media::MediaGpuChannelManager* media_gpu_channel_manager() { return media_gpu_channel_manager_.get(); }
diff --git a/services/ui/ws/gpu_host.cc b/services/ui/ws/gpu_host.cc index 85ac3aa..586bb1d 100644 --- a/services/ui/ws/gpu_host.cc +++ b/services/ui/ws/gpu_host.cc
@@ -41,7 +41,6 @@ // TODO(sad): Once GPU process is split, this would look like: // connector->BindInterface("gpu", &gpu_main_); gpu_main_impl_ = base::MakeUnique<GpuMain>(MakeRequest(&gpu_main_)); - gpu_main_impl_->OnStart(); // TODO(sad): Correctly initialize gpu::GpuPreferences (like it is initialized // in GpuProcessHost::Init()).
diff --git a/storage/browser/blob/blob_url_request_job_factory.cc b/storage/browser/blob/blob_url_request_job_factory.cc index 2b0c37533..ceb8761 100644 --- a/storage/browser/blob/blob_url_request_job_factory.cc +++ b/storage/browser/blob/blob_url_request_job_factory.cc
@@ -8,6 +8,7 @@ #include <utility> #include "base/strings/string_util.h" +#include "net/base/load_flags.h" #include "net/base/request_priority.h" #include "net/url_request/url_request_context.h" #include "storage/browser/blob/blob_data_handle.h" @@ -31,6 +32,8 @@ const GURL kBlobUrl("blob://see_user_data/"); std::unique_ptr<net::URLRequest> request = request_context->CreateRequest( kBlobUrl, net::DEFAULT_PRIORITY, request_delegate); + request->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES | + net::LOAD_DO_NOT_SEND_COOKIES); SetRequestedBlobDataHandle(request.get(), std::move(blob_data_handle)); return request; }
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index b72308d..71bc05c 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -1310,6 +1310,21 @@ ] } ], + "LsdPermissionPrompt": [ + { + "platforms": [ + "android" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "LsdPermissionPrompt" + ] + } + ] + } + ], "MacAllowBackgroundingProcesses": [ { "platforms": [ @@ -1991,6 +2006,52 @@ ] } ], + "PasswordProtectionLowReputationPing": [ + { + "platforms": [ + "chromeos", + "linux", + "mac", + "win" + ], + "experiments": [ + { + "name": "SBEROnlyNoIncognito", + "params": { + "extended_reporting": "true", + "history_sync": "false", + "incognito": "false" + }, + "enable_features": [ + "LowReputationPinging" + ] + } + ] + } + ], + "PasswordProtectionProtectedPasswordEntryPing": [ + { + "platforms": [ + "chromeos", + "linux", + "mac", + "win" + ], + "experiments": [ + { + "name": "SBEROnlyNoIncognito", + "params": { + "extended_reporting": "true", + "history_sync": "false", + "incognito": "false" + }, + "enable_features": [ + "ProtectedPasswordEntryPinging" + ] + } + ] + } + ], "PasswordSeparatedSigninFlow": [ { "platforms": [
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG b/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG index 531373c..620454d 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG
@@ -18002,7 +18002,6 @@ crbug.com/591099 http/tests/serviceworker/chromium/sandboxed-iframe-fetch-event.html [ Crash ] crbug.com/591099 http/tests/serviceworker/chromium/service-worker-gc.html [ Failure ] crbug.com/591099 http/tests/serviceworker/chromium/window-close-during-registration.html [ Failure ] -crbug.com/591099 http/tests/serviceworker/fetch-request-fallback.html [ Crash Pass ] crbug.com/591099 http/tests/serviceworker/fetch-request-xhr.html [ Failure Pass ] crbug.com/591099 http/tests/serviceworker/indexeddb.html [ Pass Timeout ] crbug.com/591099 http/tests/serviceworker/navigation-preload/chromium/navigation-preload-resource-timing.html [ Failure Pass ]
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index 6c09f888..dbaa7468 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -3389,3 +3389,5 @@ crbug.com/718717 [ Win ] fast/css-grid-layout/grid-align-justify-stretch-with-orthogonal-flows.html [ Failure Pass Timeout ] crbug.com/719298 [ Win ] fast/dnd/dropEffect-for-effectAllowed.html [ Failure Pass Timeout ] crbug.com/719299 [ Win ] external/wpt/css/css-ui-3/outline-004.html [ Failure Pass Timeout ] + +crbug.com/719837 [ Debug ] inspector/sources/debugger/rethrow-error-from-bindings-crash.html [ Timeout ]
diff --git a/third_party/WebKit/LayoutTests/animations/composition/box-shadow-composition.html b/third_party/WebKit/LayoutTests/animations/composition/box-shadow-composition.html index 1805c13..98955aa1 100644 --- a/third_party/WebKit/LayoutTests/animations/composition/box-shadow-composition.html +++ b/third_party/WebKit/LayoutTests/animations/composition/box-shadow-composition.html
@@ -45,11 +45,24 @@ addFrom: 'rgb(100, 100, 100) 10px 20px 30px 40px', addTo: 'rgb(200, 200, 200) 20px 40px 60px 80px', }, [ - {at: -0.3, is: 'rgb(80, 90, 100) 8px 16px 24px 32px, rgb(90, 110, 130) 9px 18px 27px 36px'}, - {at: 0, is: 'rgb(110, 120, 130) 11px 22px 33px 44px, rgb(120, 140, 160) 12px 24px 36px 48px'}, - {at: 0.5, is: 'rgb(160, 170, 180) 16px 32px 48px 64px, rgb(170, 190, 210) 17px 34px 51px 68px'}, - {at: 1, is: 'rgb(210, 220, 230) 21px 42px 63px 84px, rgb(220, 240, 255) 22px 44px 66px 88px'}, - {at: 1.5, is: 'rgb(255, 255, 255) 26px 52px 78px 104px, rgb(255, 255, 255) 27px 54px 81px 108px'}, + {at: -0.3, is: 'rgb(80, 90, 100) 8px 16px 24px 32px, rgb(20, 40, 60) 2px 4px 6px 8px'}, + {at: 0, is: 'rgb(110, 120, 130) 11px 22px 33px 44px, rgb(20, 40, 60) 2px 4px 6px 8px'}, + {at: 0.5, is: 'rgb(160, 170, 180) 16px 32px 48px 64px, rgb(20, 40, 60) 2px 4px 6px 8px'}, + {at: 1, is: 'rgb(210, 220, 230) 21px 42px 63px 84px, rgb(20, 40, 60) 2px 4px 6px 8px'}, + {at: 1.5, is: 'rgb(255, 255, 255) 26px 52px 78px 104px, rgb(20, 40, 60) 2px 4px 6px 8px'}, +]); + +assertComposition({ + property: 'box-shadow', + underlying: 'rgb(10, 20, 30) 1px 2px 3px 4px', + addFrom: 'rgb(100, 100, 100) 10px 20px 30px 40px, rgb(100, 100, 100) 10px 20px 30px 40px inset', + addTo: 'rgb(200, 200, 200) 20px 40px 60px 80px, rgb(200, 200, 200) 20px 40px 60px 80px inset', +}, [ + {at: -0.3, is: 'rgb(80, 90, 100) 8px 16px 24px 32px, rgb(70, 70, 70) 7px 14px 21px 28px inset'}, + {at: 0, is: 'rgb(110, 120, 130) 11px 22px 33px 44px, rgb(100, 100, 100) 10px 20px 30px 40px inset'}, + {at: 0.5, is: 'rgb(160, 170, 180) 16px 32px 48px 64px, rgb(150, 150, 150) 15px 30px 45px 60px inset'}, + {at: 1, is: 'rgb(210, 220, 230) 21px 42px 63px 84px, rgb(200, 200, 200) 20px 40px 60px 80px inset'}, + {at: 1.5, is: 'rgb(255, 255, 255) 26px 52px 78px 104px, rgb(250, 250, 250) 25px 50px 75px 100px inset'}, ]); assertComposition({ @@ -58,11 +71,11 @@ addFrom: 'rgb(100, 100, 100) 10px 20px 30px 40px', replaceTo: 'rgb(200, 200, 200) 20px 40px 60px 80px', }, [ - {at: -0.3, is: 'rgb(83, 96, 109) 8.3px 16.6px 24.9px 33.2px, rgb(96, 122, 148) 9.6px 19.2px 28.8px 38.4px'}, - {at: 0, is: 'rgb(110, 120, 130) 11px 22px 33px 44px, rgb(120, 140, 160) 12px 24px 36px 48px'}, - {at: 0.5, is: 'rgb(155, 160, 165) 15.5px 31px 46.5px 62px, rgb(160, 170, 180) 16px 32px 48px 64px'}, + {at: -0.3, is: 'rgb(83, 96, 109) 8.3px 16.6px 24.9px 33.2px, rgb(26, 52, 78) 2.6px 5.2px 7.8px 10.4px'}, + {at: 0, is: 'rgb(110, 120, 130) 11px 22px 33px 44px, rgb(20, 40, 60) 2px 4px 6px 8px'}, + {at: 0.5, is: 'rgb(155, 160, 165) 15.5px 31px 46.5px 62px, rgba(20, 40, 60, 0.5) 1px 2px 3px 4px'}, {at: 1, is: 'rgb(200, 200, 200) 20px 40px 60px 80px'}, - {at: 1.5, is: 'rgba(255, 255, 255, 0.5) 24.5px 49px 73.5px 98px, rgba(255, 255, 255, 0.5) 24px 48px 72px 96px'}, + {at: 1.5, is: 'rgba(255, 255, 255, 0.5) 24.5px 49px 73.5px 98px, rgba(0, 0, 0, 0) -1px -2px 0px -4px'}, ]); assertComposition({ @@ -71,11 +84,11 @@ replaceFrom: 'rgb(100, 100, 100) 10px 20px 30px 40px', addTo: 'rgb(200, 200, 200) 20px 40px 60px 80px', }, [ - {at: -0.3, is: 'rgba(96, 91, 87, 0.701961) 6.7px 13.4px 20.1px 26.8px, rgba(91, 83, 74, 0.701961) 6.4px 12.8px 19.2px 25.6px'}, + {at: -0.3, is: 'rgba(96, 91, 87, 0.7) 6.7px 13.4px 20.1px 26.8px, rgba(0, 0, 0, 0) -0.6px -1.2px 0px -2.4px'}, {at: 0, is: 'rgb(100, 100, 100) 10px 20px 30px 40px'}, - {at: 0.5, is: 'rgb(155, 160, 165) 15.5px 31px 46.5px 62px, rgb(160, 170, 180) 16px 32px 48px 64px'}, - {at: 1, is: 'rgb(210, 220, 230) 21px 42px 63px 84px, rgb(220, 240, 255) 22px 44px 66px 88px'}, - {at: 1.5, is: 'rgb(255, 255, 255) 26.5px 53px 79.5px 106px, rgb(255, 255, 255) 28px 56px 84px 112px'}, + {at: 0.5, is: 'rgb(155, 160, 165) 15.5px 31px 46.5px 62px, rgba(20, 40, 60, 0.5) 1px 2px 3px 4px'}, + {at: 1, is: 'rgb(210, 220, 230) 21px 42px 63px 84px, rgb(20, 40, 60) 2px 4px 6px 8px'}, + {at: 1.5, is: 'rgb(255, 255, 255) 26.5px 53px 79.5px 106px, rgb(30, 60, 90) 3px 6px 9px 12px'}, ]); assertComposition({ @@ -84,11 +97,11 @@ addFrom: 'rgb(100, 100, 100) 10px 20px 30px 40px, rgb(200, 200, 200) 20px 40px 60px 80px', replaceTo: 'rgb(200, 200, 200) 20px 40px 60px 80px', }, [ - {at: -0.3, is: 'rgb(83, 96, 109) 8.3px 16.6px 24.9px 33.2px, rgb(226, 252, 255) 22.6px 45.2px 67.8px 90.4px, rgb(122, 174, 226) 12.2px 24.4px 36.6px 48.8px, rgb(213, 226, 239) 21.3px 42.6px 63.9px 85.2px, rgb(96, 122, 148) 9.6px 19.2px 28.8px 38.4px, rgb(252, 255, 255) 25.2px 50.4px 75.6px 100.8px'}, - {at: 0, is: 'rgb(110, 120, 130) 11px 22px 33px 44px, rgb(220, 240, 255) 22px 44px 66px 88px, rgb(140, 180, 220) 14px 28px 42px 56px, rgb(210, 220, 230) 21px 42px 63px 84px, rgb(120, 140, 160) 12px 24px 36px 48px, rgb(240, 255, 255) 24px 48px 72px 96px'}, - {at: 0.5, is: 'rgb(155, 160, 165) 15.5px 31px 46.5px 62px, rgb(210, 220, 230) 21px 42px 63px 84px, rgb(170, 190, 210) 17px 34px 51px 68px, rgb(205, 210, 215) 20.5px 41px 61.5px 82px, rgb(160, 170, 180) 16px 32px 48px 64px, rgb(220, 240, 255) 22px 44px 66px 88px'}, + {at: -0.3, is: 'rgb(83, 96, 109) 8.3px 16.6px 24.9px 33.2px, rgb(255, 255, 255) 28.6px 57.2px 85.8px 114.4px, rgb(52, 104, 156) 5.2px 10.4px 15.6px 20.8px'}, + {at: 0, is: 'rgb(110, 120, 130) 11px 22px 33px 44px, rgb(220, 240, 255) 22px 44px 66px 88px, rgb(40, 80, 120) 4px 8px 12px 16px'}, + {at: 0.5, is: 'rgb(155, 160, 165) 15.5px 31px 46.5px 62px, rgb(110, 120, 130) 11px 22px 33px 44px, rgba(40, 80, 120, 0.5) 2px 4px 6px 8px'}, {at: 1, is: 'rgb(200, 200, 200) 20px 40px 60px 80px'}, - {at: 1.5, is: 'rgba(255, 255, 255, 0.5) 24.5px 49px 73.5px 98px, rgba(255, 255, 255, 0.5) 19px 38px 57px 76px, rgba(255, 255, 255, 0.5) 23px 46px 69px 92px, rgba(255, 255, 255, 0.5) 19.5px 39px 58.5px 78px, rgba(255, 255, 255, 0.5) 24px 48px 72px 96px, rgba(255, 255, 255, 0.5) 18px 36px 54px 72px'}, + {at: 1.5, is: 'rgba(255, 255, 255, 0.5) 24.5px 49px 73.5px 98px, rgba(0, 0, 0, 0) -11px -22px 0px -44px, rgba(0, 0, 0, 0) -2px -4px 0px -8px'}, ]); </script> </body>
diff --git a/third_party/WebKit/LayoutTests/animations/composition/text-shadow-composition.html b/third_party/WebKit/LayoutTests/animations/composition/text-shadow-composition.html index 843ee7f0..27ecda4a 100644 --- a/third_party/WebKit/LayoutTests/animations/composition/text-shadow-composition.html +++ b/third_party/WebKit/LayoutTests/animations/composition/text-shadow-composition.html
@@ -32,11 +32,11 @@ addFrom: 'rgb(100, 100, 100) 10px 20px 30px', addTo: 'rgb(200, 200, 200) 20px 40px 60px', }, [ - {at: -0.3, is: 'rgb(80, 90, 100) 8px 16px 24px, rgb(90, 110, 130) 9px 18px 27px'}, - {at: 0, is: 'rgb(110, 120, 130) 11px 22px 33px, rgb(120, 140, 160) 12px 24px 36px'}, - {at: 0.5, is: 'rgb(160, 170, 180) 16px 32px 48px, rgb(170, 190, 210) 17px 34px 51px'}, - {at: 1, is: 'rgb(210, 220, 230) 21px 42px 63px, rgb(220, 240, 255) 22px 44px 66px'}, - {at: 1.5, is: 'rgb(255, 255, 255) 26px 52px 78px, rgb(255, 255, 255) 27px 54px 81px'}, + {at: -0.3, is: 'rgb(80, 90, 100) 8px 16px 24px, rgb(20, 40, 60) 2px 4px 6px'}, + {at: 0, is: 'rgb(110, 120, 130) 11px 22px 33px, rgb(20, 40, 60) 2px 4px 6px'}, + {at: 0.5, is: 'rgb(160, 170, 180) 16px 32px 48px, rgb(20, 40, 60) 2px 4px 6px'}, + {at: 1, is: 'rgb(210, 220, 230) 21px 42px 63px, rgb(20, 40, 60) 2px 4px 6px'}, + {at: 1.5, is: 'rgb(255, 255, 255) 26px 52px 78px, rgb(20, 40, 60) 2px 4px 6px'}, ]); assertComposition({ @@ -45,11 +45,11 @@ addFrom: 'rgb(100, 100, 100) 10px 20px 30px', replaceTo: 'rgb(200, 200, 200) 20px 40px 60px', }, [ - {at: -0.3, is: 'rgb(83, 96, 109) 8.3px 16.6px 24.9px, rgb(96, 122, 148) 9.6px 19.2px 28.8px'}, - {at: 0, is: 'rgb(110, 120, 130) 11px 22px 33px, rgb(120, 140, 160) 12px 24px 36px'}, - {at: 0.5, is: 'rgb(155, 160, 165) 15.5px 31px 46.5px, rgb(160, 170, 180) 16px 32px 48px'}, + {at: -0.3, is: 'rgb(83, 96, 109) 8.3px 16.6px 24.9px, rgb(26, 52, 78) 2.6px 5.2px 7.8px'}, + {at: 0, is: 'rgb(110, 120, 130) 11px 22px 33px, rgb(20, 40, 60) 2px 4px 6px'}, + {at: 0.5, is: 'rgb(155, 160, 165) 15.5px 31px 46.5px, rgba(20, 40, 60, 0.5) 1px 2px 3px'}, {at: 1, is: 'rgb(200, 200, 200) 20px 40px 60px'}, - {at: 1.5, is: 'rgba(255, 255, 255, 0.5) 24.5px 49px 73.5px, rgba(255, 255, 255, 0.5) 24px 48px 72px'}, + {at: 1.5, is: 'rgba(255, 255, 255, 0.5) 24.5px 49px 73.5px, rgba(0, 0, 0, 0) -1px -2px 0px'}, ]); assertComposition({ @@ -58,11 +58,11 @@ replaceFrom: 'rgb(100, 100, 100) 10px 20px 30px', addTo: 'rgb(200, 200, 200) 20px 40px 60px', }, [ - {at: -0.3, is: 'rgba(96, 91, 87, 0.701961) 6.7px 13.4px 20.1px, rgba(91, 83, 74, 0.701961) 6.4px 12.8px 19.2px'}, + {at: -0.3, is: 'rgba(96, 91, 87, 0.7) 6.7px 13.4px 20.1px, rgba(0, 0, 0, 0) -0.6px -1.2px 0px'}, {at: 0, is: 'rgb(100, 100, 100) 10px 20px 30px'}, - {at: 0.5, is: 'rgb(155, 160, 165) 15.5px 31px 46.5px, rgb(160, 170, 180) 16px 32px 48px'}, - {at: 1, is: 'rgb(210, 220, 230) 21px 42px 63px, rgb(220, 240, 255) 22px 44px 66px'}, - {at: 1.5, is: 'rgb(255, 255, 255) 26.5px 53px 79.5px, rgb(255, 255, 255) 28px 56px 84px'}, + {at: 0.5, is: 'rgb(155, 160, 165) 15.5px 31px 46.5px, rgba(20, 40, 60, 0.5) 1px 2px 3px'}, + {at: 1, is: 'rgb(210, 220, 230) 21px 42px 63px, rgb(20, 40, 60) 2px 4px 6px'}, + {at: 1.5, is: 'rgb(255, 255, 255) 26.5px 53px 79.5px, rgb(30, 60, 90) 3px 6px 9px'}, ]); assertComposition({ @@ -71,11 +71,11 @@ addFrom: 'rgb(100, 100, 100) 10px 20px 30px, rgb(200, 200, 200) 20px 40px 60px', replaceTo: 'rgb(200, 200, 200) 20px 40px 60px', }, [ - {at: -0.3, is: 'rgb(83, 96, 109) 8.3px 16.6px 24.9px, rgb(226, 252, 255) 22.6px 45.2px 67.8px, rgb(122, 174, 226) 12.2px 24.4px 36.6px, rgb(213, 226, 239) 21.3px 42.6px 63.9px, rgb(96, 122, 148) 9.6px 19.2px 28.8px, rgb(252, 255, 255) 25.2px 50.4px 75.6px'}, - {at: 0, is: 'rgb(110, 120, 130) 11px 22px 33px, rgb(220, 240, 255) 22px 44px 66px, rgb(140, 180, 220) 14px 28px 42px, rgb(210, 220, 230) 21px 42px 63px, rgb(120, 140, 160) 12px 24px 36px, rgb(240, 255, 255) 24px 48px 72px'}, - {at: 0.5, is: 'rgb(155, 160, 165) 15.5px 31px 46.5px, rgb(210, 220, 230) 21px 42px 63px, rgb(170, 190, 210) 17px 34px 51px, rgb(205, 210, 215) 20.5px 41px 61.5px, rgb(160, 170, 180) 16px 32px 48px, rgb(220, 240, 255) 22px 44px 66px'}, + {at: -0.3, is: 'rgb(83, 96, 109) 8.3px 16.6px 24.9px, rgb(255, 255, 255) 28.6px 57.2px 85.8px, rgb(52, 104, 156) 5.2px 10.4px 15.6px'}, + {at: 0, is: 'rgb(110, 120, 130) 11px 22px 33px, rgb(220, 240, 255) 22px 44px 66px, rgb(40, 80, 120) 4px 8px 12px'}, + {at: 0.5, is: 'rgb(155, 160, 165) 15.5px 31px 46.5px, rgb(110, 120, 130) 11px 22px 33px, rgba(40, 80, 120, 0.5) 2px 4px 6px'}, {at: 1, is: 'rgb(200, 200, 200) 20px 40px 60px'}, - {at: 1.5, is: 'rgba(255, 255, 255, 0.5) 24.5px 49px 73.5px, rgba(255, 255, 255, 0.5) 19px 38px 57px, rgba(255, 255, 255, 0.5) 23px 46px 69px, rgba(255, 255, 255, 0.5) 19.5px 39px 58.5px, rgba(255, 255, 255, 0.5) 24px 48px 72px, rgba(255, 255, 255, 0.5) 18px 36px 54px'}, + {at: 1.5, is: 'rgba(255, 255, 255, 0.5) 24.5px 49px 73.5px, rgba(0, 0, 0, 0) -11px -22px 0px, rgba(0, 0, 0, 0) -2px -4px 0px'}, ]); </script> </body>
diff --git a/third_party/WebKit/LayoutTests/animations/interpolation/box-shadow-interpolation.html b/third_party/WebKit/LayoutTests/animations/interpolation/box-shadow-interpolation.html index 5e5f772c..8cc9034 100644 --- a/third_party/WebKit/LayoutTests/animations/interpolation/box-shadow-interpolation.html +++ b/third_party/WebKit/LayoutTests/animations/interpolation/box-shadow-interpolation.html
@@ -27,12 +27,12 @@ from: neutralKeyframe, to: '20px 20px 20px 20px black', }, [ - {at: -0.3, is: '7px 33px 7px 33px black'}, - {at: 0, is: '10px 30px 10px 30px black'}, - {at: 0.3, is: '13px 27px 13px 27px black'}, - {at: 0.6, is: '16px 24px 16px 24px black'}, - {at: 1, is: '20px 20px 20px 20px black'}, - {at: 1.5, is: '25px 15px 25px 15px black'}, + {at: -0.3, is: 'rgb(0, 0, 0) 7px 33px 7px 33px'}, + {at: 0, is: 'rgb(0, 0, 0) 10px 30px 10px 30px'}, + {at: 0.3, is: 'rgb(0, 0, 0) 13px 27px 13px 27px'}, + {at: 0.6, is: 'rgb(0, 0, 0) 16px 24px 16px 24px'}, + {at: 1, is: 'rgb(0, 0, 0) 20px 20px 20px 20px'}, + {at: 1.5, is: 'rgb(0, 0, 0) 25px 15px 25px 15px'}, ]); assertInterpolation({ @@ -40,12 +40,12 @@ from: 'initial', to: '20px 20px 20px 20px black', }, [ - {at: -0.3, is: '-6px -6px 0px -6px transparent'}, + {at: -0.3, is: 'rgba(0, 0, 0, 0) -6px -6px 0px -6px'}, {at: 0, is: 'none'}, - {at: 0.3, is: '6px 6px 6px 6px rgba(0, 0, 0, 0.3)'}, - {at: 0.6, is: '12px 12px 12px 12px rgba(0, 0, 0, 0.6)'}, - {at: 1, is: '20px 20px 20px 20px black'}, - {at: 1.5, is: '30px 30px 30px 30px black'}, + {at: 0.3, is: 'rgba(0, 0, 0, 0.3) 6px 6px 6px 6px'}, + {at: 0.6, is: 'rgba(0, 0, 0, 0.6) 12px 12px 12px 12px'}, + {at: 1, is: 'rgb(0, 0, 0) 20px 20px 20px 20px'}, + {at: 1.5, is: 'rgb(0, 0, 0) 30px 30px 30px 30px'}, ]); assertInterpolation({ @@ -53,12 +53,12 @@ from: 'inherit', to: '20px 20px 20px 20px black', }, [ - {at: -0.3, is: '33px 7px 33px 7px black'}, - {at: 0, is: '30px 10px 30px 10px black'}, - {at: 0.3, is: '27px 13px 27px 13px black'}, - {at: 0.6, is: '24px 16px 24px 16px black'}, - {at: 1, is: '20px 20px 20px 20px black'}, - {at: 1.5, is: '15px 25px 15px 25px black'}, + {at: -0.3, is: 'rgb(0, 0, 0) 33px 7px 33px 7px'}, + {at: 0, is: 'rgb(0, 0, 0) 30px 10px 30px 10px'}, + {at: 0.3, is: 'rgb(0, 0, 0) 27px 13px 27px 13px'}, + {at: 0.6, is: 'rgb(0, 0, 0) 24px 16px 24px 16px'}, + {at: 1, is: 'rgb(0, 0, 0) 20px 20px 20px 20px'}, + {at: 1.5, is: 'rgb(0, 0, 0) 15px 25px 15px 25px'}, ]); assertInterpolation({ @@ -66,52 +66,66 @@ from: 'unset', to: '20px 20px 20px 20px black', }, [ - {at: -0.3, is: '-6px -6px 0px -6px transparent'}, + {at: -0.3, is: 'rgba(0, 0, 0, 0) -6px -6px 0px -6px'}, {at: 0, is: 'none'}, - {at: 0.3, is: '6px 6px 6px 6px rgba(0, 0, 0, 0.3)'}, - {at: 0.6, is: '12px 12px 12px 12px rgba(0, 0, 0, 0.6)'}, - {at: 1, is: '20px 20px 20px 20px black'}, - {at: 1.5, is: '30px 30px 30px 30px black'}, + {at: 0.3, is: 'rgba(0, 0, 0, 0.3) 6px 6px 6px 6px'}, + {at: 0.6, is: 'rgba(0, 0, 0, 0.6) 12px 12px 12px 12px'}, + {at: 1, is: 'rgb(0, 0, 0) 20px 20px 20px 20px'}, + {at: 1.5, is: 'rgb(0, 0, 0) 30px 30px 30px 30px'}, ]); // Test basic functionality, and clipping blur at 0 assertInterpolation({ property: 'box-shadow', from: '15px 10px 5px 6px black', - to: '-15px -10px 25px -4px orange' + to: '-15px -10px 25px -4px orange', }, [ - {at: -0.3, is: '24px 16px 0px 9px black'}, - {at: 0, is: '15px 10px 5px 6px black'}, - {at: 0.3, is: '6px 4px 11px 3px rgb(77, 50, 0)'}, - {at: 0.6, is: '-3px -2px 17px 0px rgb(153, 99, 0)'}, - {at: 1, is: '-15px -10px 25px -4px orange'}, - {at: 1.5, is: '-30px -20px 35px -9px rgb(255, 248, 0)'}, + {at: -0.3, is: 'rgb(0, 0, 0) 24px 16px 0px 9px'}, + {at: 0, is: 'rgb(0, 0, 0) 15px 10px 5px 6px'}, + {at: 0.3, is: 'rgb(77, 50, 0) 6px 4px 11px 3px'}, + {at: 0.6, is: 'rgb(153, 99, 0) -3px -2px 17px 0px'}, + {at: 1, is: 'rgb(255, 165, 0) -15px -10px 25px -4px'}, + {at: 1.5, is: 'rgb(255, 248, 0) -30px -20px 35px -9px'}, +]); + +// Test with color as first value. +assertInterpolation({ + property: 'box-shadow', + from: 'black 15px 10px 5px 6px', + to: 'orange -15px -10px 25px -4px', +}, [ + {at: -0.3, is: 'rgb(0, 0, 0) 24px 16px 0px 9px'}, + {at: 0, is: 'rgb(0, 0, 0) 15px 10px 5px 6px'}, + {at: 0.3, is: 'rgb(77, 50, 0) 6px 4px 11px 3px'}, + {at: 0.6, is: 'rgb(153, 99, 0) -3px -2px 17px 0px'}, + {at: 1, is: 'rgb(255, 165, 0) -15px -10px 25px -4px'}, + {at: 1.5, is: 'rgb(255, 248, 0) -30px -20px 35px -9px'}, ]); assertInterpolation({ property: 'box-shadow', from: '15px 10px 5px 6px black inset', - to: '-15px -10px 25px -4px orange inset' + to: '-15px -10px 25px -4px orange inset', }, [ - {at: -0.3, is: '24px 16px 0px 9px black inset'}, - {at: 0, is: '15px 10px 5px 6px black inset'}, - {at: 0.3, is: '6px 4px 11px 3px rgb(77, 50, 0) inset'}, - {at: 0.6, is: '-3px -2px 17px 0px rgb(153, 99, 0) inset'}, - {at: 1, is: '-15px -10px 25px -4px orange inset'}, - {at: 1.5, is: '-30px -20px 35px -9px rgb(255, 248, 0) inset'}, + {at: -0.3, is: 'rgb(0, 0, 0) 24px 16px 0px 9px inset'}, + {at: 0, is: 'rgb(0, 0, 0) 15px 10px 5px 6px inset'}, + {at: 0.3, is: 'rgb(77, 50, 0) 6px 4px 11px 3px inset'}, + {at: 0.6, is: 'rgb(153, 99, 0) -3px -2px 17px 0px inset'}, + {at: 1, is: 'rgb(255, 165, 0) -15px -10px 25px -4px inset'}, + {at: 1.5, is: 'rgb(255, 248, 0) -30px -20px 35px -9px inset'}, ]); assertInterpolation({ property: 'box-shadow', from: '15px 10px 5px 6px black', - to: '-15px -10px 25px -4px' + to: '-15px -10px 25px -4px', }, [ - {at: -0.3, is: '24px 16px 0px 9px black'}, - {at: 0, is: '15px 10px 5px 6px black'}, - {at: 0.3, is: '6px 4px 11px 3px rgb(0, 38, 0)'}, - {at: 0.6, is: '-3px -2px 17px 0px rgb(0, 77, 0)'}, - {at: 1, is: '-15px -10px 25px -4px green'}, - {at: 1.5, is: '-30px -20px 35px -9px rgb(0, 192, 0)'}, + {at: -0.3, is: 'rgb(0, 0, 0) 24px 16px 0px 9px'}, + {at: 0, is: 'rgb(0, 0, 0) 15px 10px 5px 6px'}, + {at: 0.3, is: 'rgb(0, 38, 0) 6px 4px 11px 3px'}, + {at: 0.6, is: 'rgb(0, 77, 0) -3px -2px 17px 0px'}, + {at: 1, is: 'rgb(0, 128, 0) -15px -10px 25px -4px'}, + {at: 1.5, is: 'rgb(0, 192, 0) -30px -20px 35px -9px'}, ]); assertInterpolation({ @@ -119,26 +133,26 @@ from: '10px 10px 10px 10px black', to: '10px 10px 10px 10px currentColor', }, [ - {at: -0.3, is: '10px 10px 10px 10px black'}, - {at: 0, is: '10px 10px 10px 10px black'}, - {at: 0.3, is: '10px 10px 10px 10px rgb(0, 38, 0)'}, - {at: 0.6, is: '10px 10px 10px 10px rgb(0, 77, 0)'}, - {at: 1, is: '10px 10px 10px 10px green'}, - {at: 1.5, is: '10px 10px 10px 10px rgb(0, 192, 0)'}, + {at: -0.3, is: 'rgb(0, 0, 0) 10px 10px 10px 10px'}, + {at: 0, is: 'rgb(0, 0, 0) 10px 10px 10px 10px'}, + {at: 0.3, is: 'rgb(0, 38, 0) 10px 10px 10px 10px'}, + {at: 0.6, is: 'rgb(0, 77, 0) 10px 10px 10px 10px'}, + {at: 1, is: 'rgb(0, 128, 0) 10px 10px 10px 10px'}, + {at: 1.5, is: 'rgb(0, 192, 0) 10px 10px 10px 10px'}, ]); // Test padding shorter lists assertInterpolation({ property: 'box-shadow', from: '10px 20px rgba(255, 255, 0, 0.5), inset 5px 10em #008000', - to: 'none' + to: 'none', }, [ - {at: -0.3, is: '13px 26px rgba(255, 255, 0, 0.65), inset 6.5px 39px rgb(0, 166, 0)'}, - {at: 0, is: '10px 20px rgba(255, 255, 0, 0.5), inset 5px 30px #008000'}, - {at: 0.3, is: '7px 14px rgba(255, 255, 0, 0.35), inset 3.5px 21px rgba(0, 128, 0, 0.7)'}, - {at: 0.6, is: '4px 8px rgba(255, 255, 0, 0.2), inset 2px 12px rgba(0, 128, 0, 0.4)'}, + {at: -0.3, is: 'rgba(255, 255, 0, 0.65) 13px 26px 0px 0px, rgb(0, 166, 0) 6.5px 39px 0px 0px inset'}, + {at: 0, is: 'rgba(255, 255, 0, 0.5) 10px 20px 0px 0px, rgb(0, 128, 0) 5px 30px 0px 0px inset'}, + {at: 0.3, is: 'rgba(255, 255, 0, 0.353) 7px 14px 0px 0px, rgba(0, 128, 0, 0.7) 3.5px 21px 0px 0px inset'}, + {at: 0.6, is: 'rgba(255, 255, 0, 0.2) 4px 8px 0px 0px, rgba(0, 128, 0, 0.4) 2px 12px 0px 0px inset'}, {at: 1, is: 'none'}, - {at: 1.5, is: '-5px -10px transparent, inset -2.5px -15px transparent'}, + {at: 1.5, is: 'rgba(0, 0, 0, 0) -5px -10px 0px 0px, rgba(0, 0, 0, 0) -2.5px -15px 0px 0px inset'}, ]); // Test unmatched inset
diff --git a/third_party/WebKit/LayoutTests/animations/interpolation/text-shadow-interpolation.html b/third_party/WebKit/LayoutTests/animations/interpolation/text-shadow-interpolation.html index 13fdd3b..cfc3f52 100644 --- a/third_party/WebKit/LayoutTests/animations/interpolation/text-shadow-interpolation.html +++ b/third_party/WebKit/LayoutTests/animations/interpolation/text-shadow-interpolation.html
@@ -23,7 +23,7 @@ assertInterpolation({ property: 'text-shadow', from: neutralKeyframe, - to: '20px 20px 20px green', + to: 'green 20px 20px 20px', }, [ {at: -0.3, is: 'rgb(255, 176, 0) 7px 33px 7px'}, {at: 0, is: 'rgb(255, 165, 0) 10px 30px 10px'}, @@ -36,7 +36,7 @@ assertInterpolation({ property: 'text-shadow', from: 'initial', - to: '20px 20px 20px green', + to: 'green 20px 20px 20px', }, [ {at: -0.3, is: 'rgba(0, 0, 0, 0) -6px -6px 0px'}, {at: 0, is: 'none'}, @@ -49,7 +49,7 @@ assertInterpolation({ property: 'text-shadow', from: 'inherit', - to: '20px 20px 20px green', + to: 'green 20px 20px 20px', }, [ {at: -0.3, is: 'rgb(255, 176, 0) 33px 7px 33px'}, {at: 0, is: 'rgb(255, 165, 0) 30px 10px 30px'}, @@ -62,7 +62,7 @@ assertInterpolation({ property: 'text-shadow', from: 'unset', - to: '20px 20px 20px green', + to: 'green 20px 20px 20px', }, [ {at: -0.3, is: 'rgb(255, 176, 0) 33px 7px 33px'}, {at: 0, is: 'rgb(255, 165, 0) 30px 10px 30px'}, @@ -74,28 +74,28 @@ assertInterpolation({ property: 'text-shadow', - from: '15px 10px 5px black', - to: '-15px -10px 25px orange' + from: 'black 15px 10px 5px', + to: 'orange -15px -10px 25px', }, [ - {at: -0.3, is: '24px 16px 0px black'}, - {at: 0, is: '15px 10px 5px black'}, - {at: 0.3, is: '6px 4px 11px rgb(77, 50, 0)'}, - {at: 0.6, is: '-3px -2px 17px rgb(153, 99, 0)'}, - {at: 1, is: '-15px -10px 25px orange'}, - {at: 1.5, is: '-30px -20px 35px rgb(255, 248, 0)'}, + {at: -0.3, is: 'rgb(0, 0, 0) 24px 16px 0px'}, + {at: 0, is: 'rgb(0, 0, 0) 15px 10px 5px'}, + {at: 0.3, is: 'rgb(77, 50, 0) 6px 4px 11px'}, + {at: 0.6, is: 'rgb(153, 99, 0) -3px -2px 17px'}, + {at: 1, is: 'rgb(255, 165, 0) -15px -10px 25px'}, + {at: 1.5, is: 'rgb(255, 248, 0) -30px -20px 35px'}, ]); assertInterpolation({ property: 'text-shadow', - from: '10px 10px 10px black', - to: '10px 10px 10px currentColor' + from: 'black 10px 10px 10px', + to: 'currentColor 10px 10px 10px', }, [ - {at: -0.3, is: '10px 10px 10px black'}, - {at: 0, is: '10px 10px 10px black'}, - {at: 0.3, is: '10px 10px 10px rgb(0, 38, 0)'}, - {at: 0.6, is: '10px 10px 10px rgb(0, 77, 0)'}, - {at: 1, is: '10px 10px 10px green'}, - {at: 1.5, is: '10px 10px 10px rgb(0, 192, 0)'}, + {at: -0.3, is: 'rgb(0, 0, 0) 10px 10px 10px'}, + {at: 0, is: 'rgb(0, 0, 0) 10px 10px 10px'}, + {at: 0.3, is: 'rgb(0, 38, 0) 10px 10px 10px'}, + {at: 0.6, is: 'rgb(0, 77, 0) 10px 10px 10px'}, + {at: 1, is: 'rgb(0, 128, 0) 10px 10px 10px'}, + {at: 1.5, is: 'rgb(0, 192, 0) 10px 10px 10px'}, ]); </script> </body>
diff --git a/third_party/WebKit/LayoutTests/animations/responsive/box-shadow-responsive.html b/third_party/WebKit/LayoutTests/animations/responsive/box-shadow-responsive.html index 797d4891..ad5b4ae9 100644 --- a/third_party/WebKit/LayoutTests/animations/responsive/box-shadow-responsive.html +++ b/third_party/WebKit/LayoutTests/animations/responsive/box-shadow-responsive.html
@@ -27,8 +27,8 @@ configurations: [{ state: {inherited: 'blue 0px 0px 0px 0px, yellow 100px 100px 100px 100px'}, expect: [ - {at: 0.25, is: 'rgb(0, 32, 191) 5px 5px 5px 5px, rgb(191, 223, 0) 80px 80px 80px 80px'}, - {at: 0.75, is: 'rgb(0, 96, 64) 15px 15px 15px 15px, rgb(64, 160, 0) 40px 40px 40px 40px'}, + {at: 0.25, is: 'rgb(0, 32, 191) 5px 5px 5px 5px, rgba(255, 255, 0, 0.75) 75px 75px 75px 75px'}, + {at: 0.75, is: 'rgb(0, 96, 64) 15px 15px 15px 15px, rgba(255, 255, 0, 0.25) 25px 25px 25px 25px'}, ], }, { state: {inherited: 'yellow 100px 100px 100px 100px'},
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/fetch-request-css-cross-origin-mime-check.html b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/fetch-request-css-cross-origin-mime-check.https.html similarity index 88% rename from third_party/WebKit/LayoutTests/http/tests/serviceworker/fetch-request-css-cross-origin-mime-check.html rename to third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/fetch-request-css-cross-origin-mime-check.https.html index c53f470..7835f60a 100644 --- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/fetch-request-css-cross-origin-mime-check.html +++ b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/fetch-request-css-cross-origin-mime-check.https.html
@@ -1,9 +1,9 @@ <!DOCTYPE html> <title>Service Worker: Mime type checking of CSS files fetched via SW.</title> -<script src="../resources/testharness.js"></script> -<script src="../resources/testharnessreport.js"></script> -<script src="../resources/get-host-info.js?pipe=sub"></script> -<script src="resources/test-helpers.js"></script> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script src="resources/test-helpers.sub.js"></script> <script> function getElementColorInFrame(frame, id) {
diff --git a/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/fetch-request-fallback.https.html b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/fetch-request-fallback.https.html index 57934d5..400d83a 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/fetch-request-fallback.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/fetch-request-fallback.https.html
@@ -3,111 +3,280 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/common/get-host-info.sub.js"></script> -<script src="resources/test-helpers.sub.js?pipe=sub"></script> +<script src="resources/test-helpers.sub.js"></script> <script> -var expected_urls = []; - -function xhr_fail_test(frame, url) { - expected_urls.push(url); - return new Promise(function(resolve, reject) { - frame.contentWindow.xhr(url) - .then(function(){ - reject(url + ' should fail.'); - }) - .catch(function(){ - resolve(); - }); +function get_fetched_urls(worker) { + return new Promise(function(resolve) { + var channel = new MessageChannel(); + channel.port1.onmessage = function(msg) { resolve(msg); }; + worker.postMessage({port: channel.port2}, [channel.port2]); }); } -function xhr_succeed_test(frame, url) { - expected_urls.push(url); - return new Promise(function(resolve, reject) { - frame.contentWindow.xhr(url) - .then(function(){ - resolve(); - }) - .catch(function(){ - reject(url + ' should succeed.'); - }); +function check_urls(worker, expected_requests) { + return get_fetched_urls(worker) + .then(function(msg) { + var requests = msg.data.requests; + assert_object_equals(requests, expected_requests); }); } -async_test(function(t) { - var path = new URL(".", window.location).pathname; - var SCOPE = 'resources/fetch-request-fallback-iframe.html'; - var SCRIPT = 'resources/fetch-request-fallback-worker.js'; - var host_info = get_host_info(); - var BASE_URL = host_info['HTTPS_ORIGIN'] + - path + 'resources/fetch-access-control.py?'; - var OTHER_BASE_URL = host_info['HTTPS_REMOTE_ORIGIN'] + - path + 'resources/fetch-access-control.py?'; - var REDIRECT_URL = host_info['HTTPS_ORIGIN'] + - path + 'resources/redirect.py?Redirect='; - var frame; - var worker; - service_worker_unregister_and_register(t, SCRIPT, SCOPE) - .then(function(registration) { - worker = registration.installing; - return wait_for_state(t, worker, 'activated'); +var path = new URL(".", window.location).pathname; +var SCOPE = 'resources/fetch-request-fallback-iframe.html'; +var SCRIPT = 'resources/fetch-request-fallback-worker.js'; +var host_info = get_host_info(); +var BASE_URL = host_info['HTTPS_ORIGIN'] + + path + 'resources/fetch-access-control.py?'; +var BASE_PNG_URL = BASE_URL + 'PNGIMAGE&'; +var OTHER_BASE_URL = host_info['HTTPS_REMOTE_ORIGIN'] + + path + 'resources/fetch-access-control.py?'; +var OTHER_BASE_PNG_URL = OTHER_BASE_URL + 'PNGIMAGE&'; +var REDIRECT_URL = host_info['HTTPS_ORIGIN'] + + path + 'resources/redirect.py?Redirect='; +var register; + +promise_test(function(t) { + var registration; + var worker; + + register = service_worker_unregister_and_register(t, SCRIPT, SCOPE) + .then(function(r) { + registration = r; + worker = registration.installing; + return wait_for_state(t, worker, 'activated'); + }) + .then(function() { return with_iframe(SCOPE); }) + .then(function(frame) { + // This test should not be considered complete until after the service + // worker has been unregistered. Currently, `testharness.js` does not + // support asynchronous global "tear down" logic, so this must be + // expressed using a dedicated `promise_test`. Because the other + // sub-tests in this file are declared synchronously, this test will be + // the final test executed. + promise_test(function(t) { + t.add_cleanup(function() { + frame.remove(); + }); + return registration.unregister(); + }, 'restore global state'); + + return {frame: frame, worker: worker}; + }); + + return register; + }, 'initialize global state'); + +function promise_frame_test(body, desc) { + promise_test(function(test) { + return register.then(function(result) { + return body(test, result.frame, result.worker); + }); + }, desc); +} + +promise_frame_test(function(t, frame, worker) { + return check_urls( + worker, + [{ + url: host_info['HTTPS_ORIGIN'] + path + SCOPE, + mode: 'navigate' + }]); + }, 'The SW must intercept the request for a main resource.'); + +promise_frame_test(function(t, frame, worker) { + return frame.contentWindow.xhr(BASE_URL) + .then(function() { + return check_urls( + worker, + [{ url: BASE_URL, mode: 'cors' }]); + }); + }, 'The SW must intercept the request of same origin XHR.'); + +promise_frame_test(function(t, frame, worker) { + return promise_rejects( + t, + null, + frame.contentWindow.xhr(OTHER_BASE_URL), + 'SW fallbacked CORS-unsupported other origin XHR should fail.') + .then(function() { + return check_urls( + worker, + [{ url: OTHER_BASE_URL, mode: 'cors' }]); + }); + }, 'The SW must intercept the request of CORS-unsupported other origin XHR.'); + +promise_frame_test(function(t, frame, worker) { + return frame.contentWindow.xhr(OTHER_BASE_URL + 'ACAOrigin=*') + .then(function() { + return check_urls( + worker, + [{ url: OTHER_BASE_URL + 'ACAOrigin=*', mode: 'cors' }]); }) - .then(function() { return with_iframe(SCOPE); }) - .then(function(f) { - frame = f; - return xhr_succeed_test(frame, BASE_URL); + }, 'The SW must intercept the request of CORS-supported other origin XHR.'); + +promise_frame_test(function(t, frame, worker) { + return frame.contentWindow.xhr( + REDIRECT_URL + encodeURIComponent(BASE_URL)) + .then(function() { + return check_urls( + worker, + [{ + url: REDIRECT_URL + encodeURIComponent(BASE_URL), + mode: 'cors' + }]); + }); + }, 'The SW must intercept only the first request of redirected XHR.'); + +promise_frame_test(function(t, frame, worker) { + return promise_rejects( + t, + null, + frame.contentWindow.xhr( + REDIRECT_URL + encodeURIComponent(OTHER_BASE_URL)), + 'SW fallbacked XHR which is redirected to CORS-unsupported ' + + 'other origin should fail.') + .then(function() { + return check_urls( + worker, + [{ + url: REDIRECT_URL + encodeURIComponent(OTHER_BASE_URL), + mode: 'cors' + }]); + }); + }, 'The SW must intercept only the first request for XHR which is' + + ' redirected to CORS-unsupported other origin.'); + +promise_frame_test(function(t, frame, worker) { + return frame.contentWindow.xhr( + REDIRECT_URL + + encodeURIComponent(OTHER_BASE_URL + 'ACAOrigin=*')) + .then(function() { + return check_urls( + worker, + [{ + url: REDIRECT_URL + + encodeURIComponent(OTHER_BASE_URL + 'ACAOrigin=*'), + mode: 'cors' + }]); + }); + }, 'The SW must intercept only the first request for XHR which is ' + + 'redirected to CORS-supported other origin.'); + +promise_frame_test(function(t, frame, worker) { + return frame.contentWindow.load_image(BASE_PNG_URL, '') + .then(function() { + return check_urls( + worker, + [{ url: BASE_PNG_URL, mode: 'no-cors' }]); + }); + }, 'The SW must intercept the request for image.'); + +promise_frame_test(function(t, frame, worker) { + return frame.contentWindow.load_image(OTHER_BASE_PNG_URL, '') + .then(function() { + return check_urls( + worker, + [{ url: OTHER_BASE_PNG_URL, mode: 'no-cors' }]); + }); + }, 'The SW must intercept the request for other origin image.'); + +promise_frame_test(function(t, frame, worker) { + return promise_rejects( + t, + null, + frame.contentWindow.load_image(OTHER_BASE_PNG_URL, 'anonymous'), + 'SW fallbacked CORS-unsupported other origin image request ' + + 'should fail.') + .then(function() { + return check_urls( + worker, + [{ url: OTHER_BASE_PNG_URL, mode: 'cors' }]); }) - .then(function(f) { - return xhr_fail_test(frame, OTHER_BASE_URL); - }) - .then(function(f) { - return xhr_succeed_test(frame, OTHER_BASE_URL + 'ACAOrigin=*'); - }) - .then(function(f) { - return xhr_succeed_test(frame, - REDIRECT_URL + encodeURIComponent(BASE_URL)); + }, 'The SW must intercept the request for CORS-unsupported other ' + + 'origin image.'); + +promise_frame_test(function(t, frame, worker) { + return frame.contentWindow.load_image( + OTHER_BASE_PNG_URL + 'ACAOrigin=*', 'anonymous') + .then(function() { + return check_urls( + worker, + [{ url: OTHER_BASE_PNG_URL + 'ACAOrigin=*', mode: 'cors' }]); + }); + }, 'The SW must intercept the request for CORS-supported other ' + + 'origin image.'); + +promise_frame_test(function(t, frame, worker) { + return frame.contentWindow.load_image( + REDIRECT_URL + encodeURIComponent(BASE_PNG_URL), '') + .catch(function() { + assert_unreached( + 'SW fallbacked redirected image request should succeed.'); }) .then(function() { - return xhr_fail_test( - frame, - REDIRECT_URL + encodeURIComponent(OTHER_BASE_URL)); + return check_urls( + worker, + [{ + url: REDIRECT_URL + encodeURIComponent(BASE_PNG_URL), + mode: 'no-cors' + }]); + }); + }, 'The SW must intercept only the first request for redirected ' + + 'image resource.'); + +promise_frame_test(function(t, frame, worker) { + return frame.contentWindow.load_image( + REDIRECT_URL + encodeURIComponent(OTHER_BASE_PNG_URL), '') + .catch(function() { + assert_unreached( + 'SW fallbacked image request which is redirected to ' + + 'other origin should succeed.'); }) .then(function() { - return xhr_succeed_test( - frame, - REDIRECT_URL + - encodeURIComponent(OTHER_BASE_URL + 'ACAOrigin=*')); + return check_urls( + worker, + [{ + url: REDIRECT_URL + encodeURIComponent(OTHER_BASE_PNG_URL), + mode: 'no-cors' + }]); }) + }, 'The SW must intercept only the first request for image ' + + 'resource which is redirected to other origin.'); + +promise_frame_test(function(t, frame, worker) { + return promise_rejects( + t, + null, + frame.contentWindow.load_image( + REDIRECT_URL + encodeURIComponent(OTHER_BASE_PNG_URL), + 'anonymous'), + 'SW fallbacked image request which is redirected to ' + + 'CORS-unsupported other origin should fail.') .then(function() { - return new Promise(function(resolve) { - var channel = new MessageChannel(); - channel.port1.onmessage = t.step_func(function(msg) { - frame.remove(); - resolve(msg); - }); - worker.postMessage({port: channel.port2}, [channel.port2]); - }); - }) - .then(function(msg) { - var requests = msg.data.requests; - assert_equals(requests.length, expected_urls.length + 1, - 'The count of the requests which are passed to the ' + - 'ServiceWorker must be correct.'); - assert_equals(requests[0].url, new URL(SCOPE, location).toString(), - 'The first request to the SW must be the request for ' + - 'the page.'); - assert_equals(requests[0].mode, 'navigate', - 'The mode of the first request to the SW must be ' + - 'navigate'); - for (var i = 0; i < expected_urls.length; ++i) { - assert_equals(requests[i + 1].url, expected_urls[i], - 'The URL of the request which was passed from XHR ' + - 'to the ServiceWorker must be correct.'); - assert_equals(requests[i + 1].mode, 'cors', - 'The mode of the request which was passed from XHR ' + - 'to the ServiceWorker must be cors.'); - } - service_worker_unregister_and_done(t, SCOPE); - }) - .catch(unreached_rejection(t)); - }, 'Verify the fallback behavior of FetchEvent'); + return check_urls( + worker, + [{ + url: REDIRECT_URL + encodeURIComponent(OTHER_BASE_PNG_URL), + mode: 'cors' + }]); + }); + }, 'The SW must intercept only the first request for image ' + + 'resource which is redirected to CORS-unsupported other origin.'); + +promise_frame_test(function(t, frame, worker) { + return frame.contentWindow.load_image( + REDIRECT_URL + + encodeURIComponent(OTHER_BASE_PNG_URL + 'ACAOrigin=*'), + 'anonymous') + .then(function() { + return check_urls( + worker, + [{ + url: REDIRECT_URL + + encodeURIComponent(OTHER_BASE_PNG_URL + 'ACAOrigin=*'), + mode: 'cors' + }]); + }); + }, 'The SW must intercept only the first request for image ' + + 'resource which is redirected to CORS-supported other origin.'); </script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-css-cross-origin-mime-check-cross.css b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-cross.css similarity index 100% rename from third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-css-cross-origin-mime-check-cross.css rename to third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-cross.css
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-css-cross-origin-mime-check-cross.html b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-cross.html similarity index 100% rename from third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-css-cross-origin-mime-check-cross.html rename to third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-cross.html
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-css-cross-origin-mime-check-iframe.html b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-iframe.html similarity index 100% rename from third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-css-cross-origin-mime-check-iframe.html rename to third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-iframe.html
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-css-cross-origin-mime-check-same.css b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-same.css similarity index 100% rename from third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-css-cross-origin-mime-check-same.css rename to third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-same.css
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-css-cross-origin-mime-check-same.html b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-same.html similarity index 100% rename from third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-css-cross-origin-mime-check-same.html rename to third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-same.html
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-css-cross-origin-mime-check-worker.js b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-worker.js similarity index 75% rename from third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-css-cross-origin-mime-check-worker.js rename to third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-worker.js index 96c1447..274142f5 100644 --- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-css-cross-origin-mime-check-worker.js +++ b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-worker.js
@@ -1,15 +1,15 @@ -importScripts('../../resources/get-host-info.js'); -importScripts('test-helpers.js'); +importScripts('/common/get-host-info.sub.js'); +importScripts('test-helpers.sub.js'); self.addEventListener('fetch', function(event) { if (event.request.url.indexOf('cross-origin-css.css') != -1) { event.respondWith(fetch( - get_host_info()['HTTP_REMOTE_ORIGIN'] + base_path() + + get_host_info()['HTTPS_REMOTE_ORIGIN'] + base_path() + 'fetch-request-css-cross-origin-mime-check-cross.css', {mode: 'no-cors'})); } else if (event.request.url.indexOf('cross-origin-html.css') != -1) { event.respondWith(fetch( - get_host_info()['HTTP_REMOTE_ORIGIN'] + base_path() + + get_host_info()['HTTPS_REMOTE_ORIGIN'] + base_path() + 'fetch-request-css-cross-origin-mime-check-cross.html', {mode: 'no-cors'})); } else if (event.request.url.indexOf('synthetic.css') != -1) {
diff --git a/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-fallback-iframe.html b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-fallback-iframe.html index f00d24e..37c7c62f 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-fallback-iframe.html +++ b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/resources/fetch-request-fallback-iframe.html
@@ -12,4 +12,21 @@ request.send(); }); } + +function load_image(url, cross_origin) { + return new Promise(function(resolve, reject) { + var img = document.createElement('img'); + document.body.appendChild(img); + img.onload = function() { + resolve(); + }; + img.onerror = function() { + reject(); + }; + if (cross_origin != '') { + img.crossOrigin = cross_origin; + } + img.src = url; + }); +} </script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/fetch-request-fallback.html b/third_party/WebKit/LayoutTests/http/tests/serviceworker/fetch-request-fallback.html deleted file mode 100644 index 7453e950..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/fetch-request-fallback.html +++ /dev/null
@@ -1,286 +0,0 @@ -<!DOCTYPE html> -<title>Service Worker: the fallback behavior of FetchEvent</title> -<script src="../resources/testharness.js"></script> -<script src="../resources/testharnessreport.js"></script> -<script src="../resources/get-host-info.js?pipe=sub"></script> -<script src="resources/test-helpers.js"></script> -<script> - -function assert_resolves(promise, description) { - return new Promise(function(resolve, reject) { - promise - .then( - function() { resolve(); }, - function() { reject(description); }); - }); -} - -function assert_rejects(promise, description) { - return new Promise(function(resolve, reject) { - promise - .then( - function() { reject(description); }, - function() { resolve(); }); - }); -} - -function get_fetched_urls(worker) { - return new Promise(function(resolve) { - var channel = new MessageChannel(); - channel.port1.onmessage = function(msg) { resolve(msg); }; - worker.postMessage({port: channel.port2}, [channel.port2]); - }); -} - -function check_urls(worker, expected_requests, description) { - return get_fetched_urls(worker) - .then(function(msg) { - var requests = msg.data.requests; - assert_object_equals(requests, expected_requests, description); - }); -} - -async_test(function(t) { - var SCOPE = 'resources/fetch-request-fallback-iframe.html'; - var SCRIPT = 'resources/fetch-request-fallback-worker.js'; - var host_info = get_host_info(); - var BASE_URL = host_info['HTTP_ORIGIN'] + - '/serviceworker/resources/fetch-access-control.php?'; - var BASE_PNG_URL = BASE_URL + 'PNGIMAGE&'; - var OTHER_BASE_URL = host_info['HTTP_REMOTE_ORIGIN'] + - '/serviceworker/resources/fetch-access-control.php?'; - var OTHER_BASE_PNG_URL = OTHER_BASE_URL + 'PNGIMAGE&'; - var REDIRECT_URL = host_info['HTTP_ORIGIN'] + - '/serviceworker/resources/redirect.php?Redirect='; - var frame; - var worker; - service_worker_unregister_and_register(t, SCRIPT, SCOPE) - .then(function(registration) { - worker = registration.installing; - return wait_for_state(t, worker, 'activated'); - }) - .then(function() { return with_iframe(SCOPE); }) - .then(function(f) { - frame = f; - return check_urls( - worker, - [{ - url: host_info['HTTP_ORIGIN'] + '/serviceworker/' + SCOPE, - mode: 'navigate' - }], - 'The SW must intercept the request for a main resourc.'); - }) - .then(function() { - return assert_resolves( - frame.contentWindow.xhr(BASE_URL), - 'SW fallbacked same origin XHR should succeed.'); - }) - .then(function() { - return check_urls( - worker, - [{ url: BASE_URL, mode: 'cors' }], - 'The SW must intercept the request of same origin XHR.'); - }) - .then(function() { - return assert_rejects( - frame.contentWindow.xhr(OTHER_BASE_URL), - 'SW fallbacked CORS-unsupported other origin XHR should fail.'); - }) - .then(function() { - return check_urls( - worker, - [{ url: OTHER_BASE_URL, mode: 'cors' }], - 'The SW must intercept the request of CORS-unsupported other ' + - 'origin XHR.'); - }) - .then(function() { - return assert_resolves( - frame.contentWindow.xhr(OTHER_BASE_URL + 'ACAOrigin=*'), - 'SW fallbacked CORS-supported other origin XHR should succeed.'); - }) - .then(function() { - return check_urls( - worker, - [{ url: OTHER_BASE_URL + 'ACAOrigin=*', mode: 'cors' }], - 'The SW must intercept the request of CORS-supported other ' + - 'origin XHR.'); - }) - .then(function() { - return assert_resolves( - frame.contentWindow.xhr( - REDIRECT_URL + encodeURIComponent(BASE_URL)), - 'SW fallbacked redirected XHR should succeed.'); - }) - .then(function() { - return check_urls( - worker, - [{ - url: REDIRECT_URL + encodeURIComponent(BASE_URL), - mode: 'cors' - }], - 'The SW must intercept only the first request of redirected ' + - 'XHR.'); - }) - .then(function() { - return assert_rejects( - frame.contentWindow.xhr( - REDIRECT_URL + encodeURIComponent(OTHER_BASE_URL)), - 'SW fallbacked XHR which is redirected to CORS-unsupported ' + - 'other origin should fail.'); - }) - .then(function() { - return check_urls( - worker, - [{ - url: REDIRECT_URL + encodeURIComponent(OTHER_BASE_URL), - mode: 'cors' - }], - 'The SW must intercept only the first request for XHR which is' + - ' redirected to CORS-unsupported other origin.'); - }) - .then(function() { - return assert_resolves( - frame.contentWindow.xhr( - REDIRECT_URL + - encodeURIComponent(OTHER_BASE_URL + 'ACAOrigin=*')), - 'SW fallbacked XHR which is redirected to CORS-supported other ' + - 'origin should succeed.'); - }) - .then(function() { - return check_urls( - worker, - [{ - url: REDIRECT_URL + - encodeURIComponent(OTHER_BASE_URL + 'ACAOrigin=*'), - mode: 'cors' - }], - 'The SW must intercept only the first request for XHR which is ' + - 'redirected to CORS-supported other origin.'); - }) - .then(function() { - return assert_resolves( - frame.contentWindow.load_image(BASE_PNG_URL, ''), - 'SW fallbacked image request should succeed.'); - }) - .then(function() { - return check_urls( - worker, - [{ url: BASE_PNG_URL, mode: 'no-cors' }], - 'The SW must intercept the request for image.'); - }) - .then(function() { - return assert_resolves( - frame.contentWindow.load_image(OTHER_BASE_PNG_URL, ''), - 'SW fallbacked other origin image request should succeed.'); - }) - .then(function() { - return check_urls( - worker, - [{ url: OTHER_BASE_PNG_URL, mode: 'no-cors' }], - 'The SW must intercept the request for other origin image.') - }) - .then(function() { - return assert_rejects( - frame.contentWindow.load_image(OTHER_BASE_PNG_URL, 'anonymous'), - 'SW fallbacked CORS-unsupported other origin image request ' + - 'should fail.'); - }) - .then(function() { - return check_urls( - worker, - [{ url: OTHER_BASE_PNG_URL, mode: 'cors' }], - 'The SW must intercept the request for CORS-unsupported other ' + - 'origin image.') - }) - .then(function() { - return assert_resolves( - frame.contentWindow.load_image( - OTHER_BASE_PNG_URL + 'ACAOrigin=*', 'anonymous'), - 'SW fallbacked CORS-supported other origin image request should' + - ' succeed.'); - }) - .then(function() { - return check_urls( - worker, - [{ url: OTHER_BASE_PNG_URL + 'ACAOrigin=*', mode: 'cors' }], - 'The SW must intercept the request for CORS-supported other ' + - 'origin image.') - }) - .then(function() { - return assert_resolves( - frame.contentWindow.load_image( - REDIRECT_URL + encodeURIComponent(BASE_PNG_URL), ''), - 'SW fallbacked redirected image request should succeed.'); - }) - .then(function() { - return check_urls( - worker, - [{ - url: REDIRECT_URL + encodeURIComponent(BASE_PNG_URL), - mode: 'no-cors' - }], - 'The SW must intercept only the first request for redirected ' + - 'image resource.'); - }) - .then(function() { - return assert_resolves( - frame.contentWindow.load_image( - REDIRECT_URL + encodeURIComponent(OTHER_BASE_PNG_URL), ''), - 'SW fallbacked image request which is redirected to other ' + - 'origin should succeed.'); - }) - .then(function() { - return check_urls( - worker, - [{ - url: REDIRECT_URL + encodeURIComponent(OTHER_BASE_PNG_URL), - mode: 'no-cors' - }], - 'The SW must intercept only the first request for image ' + - 'resource which is redirected to other origin.'); - }) - .then(function() { - return assert_rejects( - frame.contentWindow.load_image( - REDIRECT_URL + encodeURIComponent(OTHER_BASE_PNG_URL), - 'anonymous'), - 'SW fallbacked image request which is redirected to ' + - 'CORS-unsupported other origin should fail.'); - }) - .then(function() { - return check_urls( - worker, - [{ - url: REDIRECT_URL + encodeURIComponent(OTHER_BASE_PNG_URL), - mode: 'cors' - }], - 'The SW must intercept only the first request for image ' + - 'resource which is redirected to CORS-unsupported other origin.'); - }) - .then(function() { - return assert_resolves( - frame.contentWindow.load_image( - REDIRECT_URL + - encodeURIComponent(OTHER_BASE_PNG_URL + 'ACAOrigin=*'), - 'anonymous'), - 'SW fallbacked image request which is redirected to ' + - 'CORS-supported other origin should succeed.'); - }) - .then(function() { - return check_urls( - worker, - [{ - url: REDIRECT_URL + - encodeURIComponent(OTHER_BASE_PNG_URL + 'ACAOrigin=*'), - mode: 'cors' - }], - 'The SW must intercept only the first request for image ' + - 'resource which is redirected to CORS-supported other origin.'); - }) - .then(function() { - frame.remove(); - service_worker_unregister_and_done(t, SCOPE); - }) - .catch(unreached_rejection(t)); - }, 'Verify the fallback behavior of FetchEvent'); -</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-fallback-iframe.html b/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-fallback-iframe.html deleted file mode 100644 index 37c7c62f..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-fallback-iframe.html +++ /dev/null
@@ -1,32 +0,0 @@ -<script> -function xhr(url) { - return new Promise(function(resolve, reject) { - var request = new XMLHttpRequest(); - request.addEventListener( - 'error', - function(event) { reject(event); }); - request.addEventListener( - 'load', - function(event) { resolve(request.response); }); - request.open('GET', url); - request.send(); - }); -} - -function load_image(url, cross_origin) { - return new Promise(function(resolve, reject) { - var img = document.createElement('img'); - document.body.appendChild(img); - img.onload = function() { - resolve(); - }; - img.onerror = function() { - reject(); - }; - if (cross_origin != '') { - img.crossOrigin = cross_origin; - } - img.src = url; - }); -} -</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-fallback-worker.js b/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-fallback-worker.js deleted file mode 100644 index aeb63ea..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-fallback-worker.js +++ /dev/null
@@ -1,15 +0,0 @@ -// TODO(horo): Service worker can be killed at some point during the test. So we -// should use storage API instead of this global variable. -var requests = []; - -self.addEventListener('message', function(event) { - event.data.port.postMessage({requests: requests}); - requests = []; - }); - -self.addEventListener('fetch', function(event) { - requests.push({ - url: event.request.url, - mode: event.request.mode - }); - });
diff --git a/third_party/WebKit/LayoutTests/transitions/multiple-shadow-transitions-expected.txt b/third_party/WebKit/LayoutTests/transitions/multiple-shadow-transitions-expected.txt index d3acad1..f2aee0f 100644 --- a/third_party/WebKit/LayoutTests/transitions/multiple-shadow-transitions-expected.txt +++ b/third_party/WebKit/LayoutTests/transitions/multiple-shadow-transitions-expected.txt
@@ -1,4 +1,4 @@ PASS - "box-shadow" property for "box" element at 0.5s saw something close to: rgb(255, 0, 0) 0px 0px 10px 0px, rgb(0, 0, 255) 0px 0px 10px 0px -PASS - "box-shadow" property for "box2" element at 0.5s saw something close to: rgb(255, 0, 0) 0px -20px 10px 0px, rgb(128, 0, 128) 0px 0px 10px 0px -PASS - "box-shadow" property for "box3" element at 0.5s saw something close to: rgb(128, 0, 128) 0px 0px 10px 0px, rgb(0, 0, 255) 0px 20px 10px 0px +PASS - "box-shadow" property for "box2" element at 0.5s saw something close to: rgb(255, 0, 0) 0px -20px 10px 0px, rgba(0, 0, 255, 0.5) 0px 10px 5px 0px +PASS - "box-shadow" property for "box3" element at 0.5s saw something close to: rgb(128, 0, 128) 0px 0px 10px 0px, rgba(0, 0, 255, 0.5) 0px 10px 5px 0px
diff --git a/third_party/WebKit/LayoutTests/transitions/multiple-shadow-transitions.html b/third_party/WebKit/LayoutTests/transitions/multiple-shadow-transitions.html index 0a8825d..1237cca 100644 --- a/third_party/WebKit/LayoutTests/transitions/multiple-shadow-transitions.html +++ b/third_party/WebKit/LayoutTests/transitions/multiple-shadow-transitions.html
@@ -54,8 +54,8 @@ const expectedValues = [ // [time, element-id, property, expected-value, tolerance] [0.5, 'box', 'box-shadow', 'rgb(255, 0, 0) 0px 0px 10px 0px, rgb(0, 0, 255) 0px 0px 10px 0px', 4], - [0.5, 'box2', 'box-shadow', 'rgb(255, 0, 0) 0px -20px 10px 0px, rgb(128, 0, 128) 0px 0px 10px 0px', 4], - [0.5, 'box3', 'box-shadow', 'rgb(128, 0, 128) 0px 0px 10px 0px, rgb(0, 0, 255) 0px 20px 10px 0px', 4], + [0.5, 'box2', 'box-shadow', 'rgb(255, 0, 0) 0px -20px 10px 0px, rgba(0, 0, 255, 0.5) 0px 10px 5px 0px', 4], + [0.5, 'box3', 'box-shadow', 'rgb(128, 0, 128) 0px 0px 10px 0px, rgba(0, 0, 255, 0.5) 0px 10px 5px 0px', 4], ]; function setupTest()
diff --git a/third_party/WebKit/LayoutTests/webaudio/event-constructor.html b/third_party/WebKit/LayoutTests/webaudio/event-constructor.html index 1aafcba..7ea4c99 100644 --- a/third_party/WebKit/LayoutTests/webaudio/event-constructor.html +++ b/third_party/WebKit/LayoutTests/webaudio/event-constructor.html
@@ -5,177 +5,147 @@ <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> <script src="resources/audit-util.js"></script> - <script src="resources/audio-testing.js"></script> + <script src="resources/audit.js"></script> </head> <body> <script> var audit = Audit.createTaskRunner(); - audit.defineTask("offline-constructor", function (taskDone) { - var success = true; - - success = Should("new OfflineAudioCompletionEvent()", function () { + audit.define('offline-constructor', (task, should) => { + should(function() { new OfflineAudioCompletionEvent(); - }).throw("TypeError") && success; + }, 'new OfflineAudioCompletionEvent()').throw('TypeError'); - success = Should('new OfflineAudioCompletionEvent("complete")', - function () { - new OfflineAudioCompletionEvent("complete"); - }).throw("TypeError") && success; + should(function() { + new OfflineAudioCompletionEvent('complete'); + }, 'new OfflineAudioCompletionEvent("complete")').throw('TypeError'); - success = Should('new OfflineAudioCompletionEvent("complete", {})', - function () { - new OfflineAudioCompletionEvent("complete", {}); - }).throw("TypeError") && success; + should( + function() { + new OfflineAudioCompletionEvent('complete', {}); + }, + 'new OfflineAudioCompletionEvent("complete", {})') + .throw('TypeError'); - success = Should( - 'new OfflineAudioCompletionEvent("complete", {foo: 42})', - function () { - new OfflineAudioCompletionEvent("complete", { - foo: 42 - }); - }).throw("TypeError") && success; + should( + function() { + new OfflineAudioCompletionEvent('complete', {foo: 42}); + }, + 'new OfflineAudioCompletionEvent("complete", {foo: 42})') + .throw('TypeError'); var context = new OfflineAudioContext(1, 100, 48000); - var buffer = new AudioBuffer(context, { - length: 42 - }); + var buffer = new AudioBuffer(context, {length: 42}); - success = Should( - 'new OfflineAudioCompletionEvent("complete", {renderedBuffer: buffer})', - function () { - new OfflineAudioCompletionEvent("complete", { - renderedBuffer: buffer - }); - }).notThrow() && success; + should( + function() { + new OfflineAudioCompletionEvent( + 'complete', {renderedBuffer: buffer}); + }, + 'new OfflineAudioCompletionEvent("complete", {renderedBuffer: buffer})') + .notThrow(); - Should("OfflineAudioCompletionEvent construction handled", success) - .summarize("correctly", "incorrectly"); - - taskDone(); + task.done(); }); - audit.defineTask("offline-event", function (taskDone) { + audit.define('offline-event', (task, should) => { // Only need the context for constructing the AudioBuffers for the // tests. var context = new OfflineAudioContext(1, 100, 48000); - var success = true; - // Just an arbitrary AudioBuffer. - var buffer = new AudioBuffer(context, { - length: 10 - }); + var buffer = new AudioBuffer(context, {length: 10}); var event; - success = Should("new OfflineAudioCompletionEvent()", function () { - event = new OfflineAudioCompletionEvent("foo", { - renderedBuffer: buffer - }); - }).notThrow() && success; + should(function() { + event = + new OfflineAudioCompletionEvent('foo', {renderedBuffer: buffer}); + }, 'new OfflineAudioCompletionEvent()').notThrow(); - success = Should("event.renderedBuffer == buffer", event.renderedBuffer == - buffer) - .beEqualTo(true) && success; + should(event.renderedBuffer == buffer, 'event.renderedBuffer == buffer') + .beEqualTo(true); - Should("OfflineAudioCompletionEvent constructed", success) - .summarize("correctly", - "incorrectly"); - - taskDone(); + task.done(); }); - audit.defineTask("audio-processing", function (taskDone) { + audit.define('audio-processing', (task, should) => { // Only need the context for constructing the AudioBuffers for the // tests. var context = new OfflineAudioContext(1, 100, 48000); // Fairly arbitrary buffers and time - var input = new AudioBuffer(context, { - length: 10 - }); - var output = new AudioBuffer(context, { - length: 20 - }); + var input = new AudioBuffer(context, {length: 10}); + var output = new AudioBuffer(context, {length: 20}); var time = Math.PI; - var success = true; - // Verify required arguments. - success = Should("new AudioProcessingEvent()", function () { + should(function() { new AudioProcessingEvent(); - }).throw("TypeError") && success; + }, 'new AudioProcessingEvent()').throw('TypeError'); - success = Should('new AudioProcessingEvent("proc")', function () { - new AudioProcessingEvent("proc"); - }).throw("TypeError") && success; + should(function() { + new AudioProcessingEvent('proc'); + }, 'new AudioProcessingEvent("proc")').throw('TypeError'); - success = Should('new AudioProcessingEvent("proc", {foo: 99})', - function () { - new AudioProcessingEvent("proc", { - foo: 99 - }); - }).throw("TypeError") && success; + should(function() { + new AudioProcessingEvent('proc', {foo: 99}); + }, 'new AudioProcessingEvent("proc", {foo: 99})').throw('TypeError'); - success = Should( - 'new AudioProcessingEvent("proc", {inputBuffer: input, outputBuffer: output})', - function () { - new AudioProcessingEvent("proc", { - inputBuffer: input, - outputBuffer: output - }); - }).throw("TypeError") && success; + should( + function() { + new AudioProcessingEvent( + 'proc', {inputBuffer: input, outputBuffer: output}); + }, + 'new AudioProcessingEvent("proc", ' + + '{inputBuffer: input, outputBuffer: output})') + .throw('TypeError'); - success = Should( - 'new AudioProcessingEvent("proc", {inputBuffer: input, playbackTime: time})', - function () { - new AudioProcessingEvent("proc", { - inputBuffer: input, - playbackTime: time - }); - }).throw("TypeError") && success; + should( + function() { + new AudioProcessingEvent( + 'proc', {inputBuffer: input, playbackTime: time}); + }, + 'new AudioProcessingEvent("proc", ' + + '{inputBuffer: input, playbackTime: time})') + .throw('TypeError'); - success = Should( - 'new AudioProcessingEvent("proc", {outputBuffer: output, playbackTime: time})', - function () { - new AudioProcessingEvent("proc", { - outputBuffer: output, - playbackTime: time - }); - }).throw("TypeError") && success; + should( + function() { + new AudioProcessingEvent( + 'proc', {outputBuffer: output, playbackTime: time}); + }, + 'new AudioProcessingEvent("proc", ' + + '{outputBuffer: output, playbackTime: time})') + .throw('TypeError'); // Finally test valid call var event; - success = Should( - 'new AudioProcessingEvent("proc", {inputBuffer: input, outputBuffer: output, playbackTime: time})', - function () { - event = new AudioProcessingEvent("proc", { - inputBuffer: input, - outputBuffer: output, - playbackTime: time - }); - }).notThrow() && success; + should( + function() { + event = new AudioProcessingEvent('proc', { + inputBuffer: input, + outputBuffer: output, + playbackTime: time + }); + }, + 'new AudioProcessingEvent("proc", ' + + '{inputBuffer: input, outputBuffer: output, playbackTime: time})') + .notThrow(); - success = Should("event.playbackTime", event.playbackTime) - .beEqualTo(time) && success; + should(event.playbackTime, 'event.playbackTime').beEqualTo(time); - success = Should("event.inputBuffer == input", event.inputBuffer == - input) - .beEqualTo(true) && success; + should(event.inputBuffer == input, 'event.inputBuffer == input') + .beEqualTo(true); - success = Should("event.outputBuffer == output", event.outputBuffer == - output) - .beEqualTo(true) && success; + should(event.outputBuffer == output, 'event.outputBuffer == output') + .beEqualTo(true); - Should("AudioProcessingEvent construction handled", success) - .summarize("correctly", "incorrectly"); - - taskDone(); + task.done(); }); - audit.runTasks(); + audit.run(); </script> </body> </html>
diff --git a/third_party/WebKit/Source/bindings/core/v8/LocalWindowProxy.cpp b/third_party/WebKit/Source/bindings/core/v8/LocalWindowProxy.cpp index 3b33bb8..930b5bb 100644 --- a/third_party/WebKit/Source/bindings/core/v8/LocalWindowProxy.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/LocalWindowProxy.cpp
@@ -276,40 +276,22 @@ } void LocalWindowProxy::SetSecurityToken(SecurityOrigin* origin) { - // The security token is a fast path optimization for cross-context v8 checks. - // If two contexts have the same token, then the SecurityOrigins can access - // each other. Otherwise, v8 will fall back to a full CanAccess() check. + // If two tokens are equal, then the SecurityOrigins canAccess each other. + // If two tokens are not equal, then we have to call canAccess. + // Note: we can't use the HTTPOrigin if it was set from the DOM. String token; - // The default v8 security token is to the global object itself. By - // definition, the global object is unique and using it as the security token - // will always trigger a full CanAccess() check from any other context. - // - // Using the default security token to force a callback to CanAccess() is - // required for three things: - // 1. When a new window is opened, the browser displays the pending URL rather - // than about:blank. However, if the Document is accessed, it is no longer - // safe to show the pending URL, as the initial empty Document may have - // been modified. Forcing a CanAccess() call allows Blink to notify the - // browser if the initial empty Document is accessed. - // 2. If document.domain is set, a full CanAccess() check is required as two - // Documents are only same-origin if document.domain is set to the same - // value. Checking this can currently only be done in Blink, so require a - // full CanAccess() check. - bool use_default_security_token = - world_->IsMainWorld() && (GetFrame() - ->Loader() - .StateMachine() - ->IsDisplayingInitialEmptyDocument() || - origin->DomainWasSetInDOM()); - if (origin && !use_default_security_token) + // If document.domain is modified, v8 needs to do a full canAccess check, + // so always use an empty security token in that case. + bool delay_set = world_->IsMainWorld() && origin->DomainWasSetInDOM(); + if (origin && !delay_set) token = origin->ToString(); - // 3. The ToString() method on SecurityOrigin returns the string "null" for - // empty security origins and for security origins that should only allow - // access to themselves (i.e. opaque origins). Using the default security - // token serves for two purposes: it allows fast-path security checks for - // accesses inside the same context, and forces a full CanAccess() check - // for contexts that don't inherit the same origin, which will always fail. + // An empty or "null" token means we always have to call + // canAccess. The toString method on securityOrigins returns the + // string "null" for empty security origins and for security + // origins that should only allow access to themselves. In this + // case, we use the global object as the security token to avoid + // calling canAccess when a script accesses its own objects. v8::HandleScope handle_scope(GetIsolate()); v8::Local<v8::Context> context = script_state_->GetContext(); if (token.IsEmpty() || token == "null") {
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScheduledAction.cpp b/third_party/WebKit/Source/bindings/core/v8/ScheduledAction.cpp index 55ed937..853c25f 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScheduledAction.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScheduledAction.cpp
@@ -37,6 +37,7 @@ #include "bindings/core/v8/V8BindingForCore.h" #include "bindings/core/v8/V8GCController.h" #include "bindings/core/v8/V8ScriptRunner.h" +#include "bindings/core/v8/WorkerOrWorkletScriptController.h" #include "core/dom/Document.h" #include "core/dom/ExecutionContext.h" #include "core/frame/LocalFrame.h"
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8AbstractEventListener.cpp b/third_party/WebKit/Source/bindings/core/v8/V8AbstractEventListener.cpp index ad844fa..e8a8543b 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8AbstractEventListener.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8AbstractEventListener.cpp
@@ -34,6 +34,7 @@ #include "bindings/core/v8/V8Event.h" #include "bindings/core/v8/V8EventListenerHelper.h" #include "bindings/core/v8/V8EventTarget.h" +#include "bindings/core/v8/WorkerOrWorkletScriptController.h" #include "core/dom/Document.h" #include "core/dom/DocumentParser.h" #include "core/dom/ExecutionContext.h"
diff --git a/third_party/WebKit/Source/core/CoreInitializer.cpp b/third_party/WebKit/Source/core/CoreInitializer.cpp index 0042a13..b141225 100644 --- a/third_party/WebKit/Source/core/CoreInitializer.cpp +++ b/third_party/WebKit/Source/core/CoreInitializer.cpp
@@ -75,7 +75,7 @@ } void CoreInitializer::Initialize() { - ASSERT(!IsInitialized()); + DCHECK(!IsInitialized()); is_initialized_ = true; // Note: in order to add core static strings for a new module (1) // the value of 'coreStaticStringsCount' must be updated with the
diff --git a/third_party/WebKit/Source/core/animation/CSSImageListInterpolationType.cpp b/third_party/WebKit/Source/core/animation/CSSImageListInterpolationType.cpp index 82d4d697..19ee26d 100644 --- a/third_party/WebKit/Source/core/animation/CSSImageListInterpolationType.cpp +++ b/third_party/WebKit/Source/core/animation/CSSImageListInterpolationType.cpp
@@ -147,6 +147,7 @@ InterpolationValue&& end) const { return ListInterpolationFunctions::MaybeMergeSingles( std::move(start), std::move(end), + ListInterpolationFunctions::LengthMatchingStrategy::kLowestCommonMultiple, CSSImageInterpolationType::StaticMergeSingleConversions); }
diff --git a/third_party/WebKit/Source/core/animation/CSSLengthListInterpolationType.cpp b/third_party/WebKit/Source/core/animation/CSSLengthListInterpolationType.cpp index 36d4ca3..d666851 100644 --- a/third_party/WebKit/Source/core/animation/CSSLengthListInterpolationType.cpp +++ b/third_party/WebKit/Source/core/animation/CSSLengthListInterpolationType.cpp
@@ -124,6 +124,7 @@ InterpolationValue&& end) const { return ListInterpolationFunctions::MaybeMergeSingles( std::move(start), std::move(end), + ListInterpolationFunctions::LengthMatchingStrategy::kLowestCommonMultiple, LengthInterpolationFunctions::MergeSingles); } @@ -144,6 +145,7 @@ double interpolation_fraction) const { ListInterpolationFunctions::Composite( underlying_value_owner, underlying_fraction, *this, value, + ListInterpolationFunctions::LengthMatchingStrategy::kLowestCommonMultiple, LengthInterpolationFunctions::NonInterpolableValuesAreCompatible, LengthInterpolationFunctions::Composite); }
diff --git a/third_party/WebKit/Source/core/animation/CSSShadowListInterpolationType.cpp b/third_party/WebKit/Source/core/animation/CSSShadowListInterpolationType.cpp index 4ae5e64..f3337ff 100644 --- a/third_party/WebKit/Source/core/animation/CSSShadowListInterpolationType.cpp +++ b/third_party/WebKit/Source/core/animation/CSSShadowListInterpolationType.cpp
@@ -116,6 +116,7 @@ InterpolationValue&& end) const { return ListInterpolationFunctions::MaybeMergeSingles( std::move(start), std::move(end), + ListInterpolationFunctions::LengthMatchingStrategy::kPadToLargest, ShadowInterpolationFunctions::MaybeMergeSingles); } @@ -134,6 +135,7 @@ double interpolation_fraction) const { ListInterpolationFunctions::Composite( underlying_value_owner, underlying_fraction, *this, value, + ListInterpolationFunctions::LengthMatchingStrategy::kPadToLargest, ShadowInterpolationFunctions::NonInterpolableValuesAreCompatible, ShadowInterpolationFunctions::Composite); }
diff --git a/third_party/WebKit/Source/core/animation/CSSSizeListInterpolationType.cpp b/third_party/WebKit/Source/core/animation/CSSSizeListInterpolationType.cpp index 25e95df..2426991 100644 --- a/third_party/WebKit/Source/core/animation/CSSSizeListInterpolationType.cpp +++ b/third_party/WebKit/Source/core/animation/CSSSizeListInterpolationType.cpp
@@ -150,6 +150,7 @@ InterpolationValue&& end) const { return ListInterpolationFunctions::MaybeMergeSingles( std::move(start), std::move(end), + ListInterpolationFunctions::LengthMatchingStrategy::kLowestCommonMultiple, SizeInterpolationFunctions::MaybeMergeSingles); } @@ -168,6 +169,8 @@ double interpolation_fraction) const { ListInterpolationFunctions::Composite( underlying_value_owner, underlying_fraction, *this, value, + ListInterpolationFunctions::LengthMatchingStrategy::kLowestCommonMultiple, + SizeInterpolationFunctions::NonInterpolableValuesAreCompatible, SizeInterpolationFunctions::Composite); }
diff --git a/third_party/WebKit/Source/core/animation/CompositorAnimationsTest.cpp b/third_party/WebKit/Source/core/animation/CompositorAnimationsTest.cpp index e681582..0b4fc40 100644 --- a/third_party/WebKit/Source/core/animation/CompositorAnimationsTest.cpp +++ b/third_party/WebKit/Source/core/animation/CompositorAnimationsTest.cpp
@@ -242,15 +242,10 @@ } AnimatableValueKeyframeEffectModel* CreateKeyframeEffectModel( - PassRefPtr<AnimatableValueKeyframe> prp_from, - PassRefPtr<AnimatableValueKeyframe> prp_to, - PassRefPtr<AnimatableValueKeyframe> prp_c = nullptr, - PassRefPtr<AnimatableValueKeyframe> prp_d = nullptr) { - RefPtr<AnimatableValueKeyframe> from = prp_from; - RefPtr<AnimatableValueKeyframe> to = prp_to; - RefPtr<AnimatableValueKeyframe> c = prp_c; - RefPtr<AnimatableValueKeyframe> d = prp_d; - + RefPtr<AnimatableValueKeyframe> from, + RefPtr<AnimatableValueKeyframe> to, + RefPtr<AnimatableValueKeyframe> c = nullptr, + RefPtr<AnimatableValueKeyframe> d = nullptr) { EXPECT_EQ(from->Offset(), 0); AnimatableValueKeyframeVector frames; frames.push_back(from);
diff --git a/third_party/WebKit/Source/core/animation/ListInterpolationFunctions.cpp b/third_party/WebKit/Source/core/animation/ListInterpolationFunctions.cpp index 82b26f7..6f39102 100644 --- a/third_party/WebKit/Source/core/animation/ListInterpolationFunctions.cpp +++ b/third_party/WebKit/Source/core/animation/ListInterpolationFunctions.cpp
@@ -48,12 +48,29 @@ return true; } +static size_t MatchLengths(size_t start_length, + size_t end_length, + ListInterpolationFunctions::LengthMatchingStrategy + length_matching_strategy) { + if (length_matching_strategy == + ListInterpolationFunctions::LengthMatchingStrategy:: + kLowestCommonMultiple) { + return lowestCommonMultiple(start_length, end_length); + } + DCHECK_EQ(length_matching_strategy, + ListInterpolationFunctions::LengthMatchingStrategy::kPadToLargest); + return std::max(start_length, end_length); +} + PairwiseInterpolationValue ListInterpolationFunctions::MaybeMergeSingles( InterpolationValue&& start, InterpolationValue&& end, + LengthMatchingStrategy length_matching_strategy, MergeSingleItemConversionsCallback merge_single_item_conversions) { - size_t start_length = ToInterpolableList(*start.interpolable_value).length(); - size_t end_length = ToInterpolableList(*end.interpolable_value).length(); + const size_t start_length = + ToInterpolableList(*start.interpolable_value).length(); + const size_t end_length = + ToInterpolableList(*end.interpolable_value).length(); if (start_length == 0 && end_length == 0) { return PairwiseInterpolationValue(std::move(start.interpolable_value), @@ -77,7 +94,8 @@ std::move(start.non_interpolable_value)); } - size_t final_length = lowestCommonMultiple(start_length, end_length); + const size_t final_length = + MatchLengths(start_length, end_length, length_matching_strategy); std::unique_ptr<InterpolableList> result_start_interpolable_list = InterpolableList::Create(final_length); std::unique_ptr<InterpolableList> result_end_interpolable_list = @@ -95,21 +113,43 @@ ToNonInterpolableList(*end.non_interpolable_value); for (size_t i = 0; i < final_length; i++) { - InterpolationValue start( - start_interpolable_list.Get(i % start_length)->Clone(), - start_non_interpolable_list.Get(i % start_length)); - InterpolationValue end(end_interpolable_list.Get(i % end_length)->Clone(), - end_non_interpolable_list.Get(i % end_length)); - PairwiseInterpolationValue result = - merge_single_item_conversions(std::move(start), std::move(end)); - if (!result) - return nullptr; - result_start_interpolable_list->Set( - i, std::move(result.start_interpolable_value)); - result_end_interpolable_list->Set(i, - std::move(result.end_interpolable_value)); - result_non_interpolable_values[i] = - std::move(result.non_interpolable_value); + PairwiseInterpolationValue result = nullptr; + if (length_matching_strategy == + LengthMatchingStrategy::kLowestCommonMultiple || + (i < start_length && i < end_length)) { + InterpolationValue start( + start_interpolable_list.Get(i % start_length)->Clone(), + start_non_interpolable_list.Get(i % start_length)); + InterpolationValue end(end_interpolable_list.Get(i % end_length)->Clone(), + end_non_interpolable_list.Get(i % end_length)); + PairwiseInterpolationValue result = + merge_single_item_conversions(std::move(start), std::move(end)); + if (!result) + return nullptr; + result_start_interpolable_list->Set( + i, std::move(result.start_interpolable_value)); + result_end_interpolable_list->Set( + i, std::move(result.end_interpolable_value)); + result_non_interpolable_values[i] = + std::move(result.non_interpolable_value); + } else { + DCHECK_EQ(length_matching_strategy, + LengthMatchingStrategy::kPadToLargest); + if (i < start_length) { + result_start_interpolable_list->Set( + i, start_interpolable_list.Get(i)->Clone()); + result_end_interpolable_list->Set( + i, start_interpolable_list.Get(i)->CloneAndZero()); + result_non_interpolable_values[i] = start_non_interpolable_list.Get(i); + } else { + DCHECK_LT(i, end_length); + result_start_interpolable_list->Set( + i, end_interpolable_list.Get(i)->CloneAndZero()); + result_end_interpolable_list->Set( + i, end_interpolable_list.Get(i)->Clone()); + result_non_interpolable_values[i] = end_non_interpolable_list.Get(i); + } + } } return PairwiseInterpolationValue( @@ -144,16 +184,59 @@ NonInterpolableList::Create(std::move(new_non_interpolable_values)); } +// This helper function makes value the same length as length_value by +// CloneAndZero-ing the additional items from length_value into value. +static void PadToSameLength(InterpolationValue& value, + const InterpolationValue& length_value) { + InterpolableList& interpolable_list = + ToInterpolableList(*value.interpolable_value); + NonInterpolableList& non_interpolable_list = + ToNonInterpolableList(*value.non_interpolable_value); + const size_t current_length = interpolable_list.length(); + InterpolableList& target_interpolable_list = + ToInterpolableList(*length_value.interpolable_value); + NonInterpolableList& target_non_interpolable_list = + ToNonInterpolableList(*length_value.non_interpolable_value); + const size_t target_length = target_interpolable_list.length(); + DCHECK_LT(current_length, target_length); + std::unique_ptr<InterpolableList> new_interpolable_list = + InterpolableList::Create(target_length); + Vector<RefPtr<NonInterpolableValue>> new_non_interpolable_values( + target_length); + size_t index = 0; + for (; index < current_length; index++) { + new_interpolable_list->Set(index, + std::move(interpolable_list.GetMutable(index))); + new_non_interpolable_values[index] = non_interpolable_list.Get(index); + } + for (; index < target_length; index++) { + new_interpolable_list->Set( + index, target_interpolable_list.Get(index)->CloneAndZero()); + new_non_interpolable_values[index] = + target_non_interpolable_list.Get(index); + } + value.interpolable_value = std::move(new_interpolable_list); + value.non_interpolable_value = + NonInterpolableList::Create(std::move(new_non_interpolable_values)); +} + static bool NonInterpolableListsAreCompatible( const NonInterpolableList& a, const NonInterpolableList& b, size_t length, + ListInterpolationFunctions::LengthMatchingStrategy length_matching_strategy, ListInterpolationFunctions::NonInterpolableValuesAreCompatibleCallback non_interpolable_values_are_compatible) { for (size_t i = 0; i < length; i++) { - if (!non_interpolable_values_are_compatible(a.Get(i % a.length()), - b.Get(i % b.length()))) - return false; + if (length_matching_strategy == + ListInterpolationFunctions::LengthMatchingStrategy:: + kLowestCommonMultiple || + (i < a.length() && i < b.length())) { + if (!non_interpolable_values_are_compatible(a.Get(i % a.length()), + b.Get(i % b.length()))) { + return false; + } + } } return true; } @@ -163,10 +246,11 @@ double underlying_fraction, const InterpolationType& type, const InterpolationValue& value, + LengthMatchingStrategy length_matching_strategy, NonInterpolableValuesAreCompatibleCallback non_interpolable_values_are_compatible, CompositeItemCallback composite_item) { - size_t underlying_length = + const size_t underlying_length = ToInterpolableList(*underlying_value_owner.Value().interpolable_value) .length(); if (underlying_length == 0) { @@ -177,7 +261,7 @@ const InterpolableList& interpolable_list = ToInterpolableList(*value.interpolable_value); - size_t value_length = interpolable_list.length(); + const size_t value_length = interpolable_list.length(); if (value_length == 0) { DCHECK(!value.non_interpolable_value); underlying_value_owner.MutableValue().interpolable_value->Scale( @@ -187,30 +271,55 @@ const NonInterpolableList& non_interpolable_list = ToNonInterpolableList(*value.non_interpolable_value); - size_t new_length = lowestCommonMultiple(underlying_length, value_length); + const size_t final_length = + MatchLengths(underlying_length, value_length, length_matching_strategy); if (!NonInterpolableListsAreCompatible( ToNonInterpolableList( *underlying_value_owner.Value().non_interpolable_value), - non_interpolable_list, new_length, + non_interpolable_list, final_length, length_matching_strategy, non_interpolable_values_are_compatible)) { underlying_value_owner.Set(type, value); return; } InterpolationValue& underlying_value = underlying_value_owner.MutableValue(); - if (underlying_length < new_length) - RepeatToLength(underlying_value, new_length); + if (length_matching_strategy == + LengthMatchingStrategy::kLowestCommonMultiple) { + if (underlying_length < final_length) { + RepeatToLength(underlying_value, final_length); + } + InterpolableList& underlying_interpolable_list = + ToInterpolableList(*underlying_value.interpolable_value); + NonInterpolableList& underlying_non_interpolable_list = + ToNonInterpolableList(*underlying_value.non_interpolable_value); - InterpolableList& underlying_interpolable_list = - ToInterpolableList(*underlying_value.interpolable_value); - NonInterpolableList& underlying_non_interpolable_list = - ToNonInterpolableList(*underlying_value.non_interpolable_value); - for (size_t i = 0; i < new_length; i++) { - composite_item(underlying_interpolable_list.GetMutable(i), - underlying_non_interpolable_list.GetMutable(i), - underlying_fraction, - *interpolable_list.Get(i % value_length), - non_interpolable_list.Get(i % value_length)); + for (size_t i = 0; i < final_length; i++) { + composite_item(underlying_interpolable_list.GetMutable(i), + underlying_non_interpolable_list.GetMutable(i), + underlying_fraction, + *interpolable_list.Get(i % value_length), + non_interpolable_list.Get(i % value_length)); + } + } else { + DCHECK_EQ(length_matching_strategy, LengthMatchingStrategy::kPadToLargest); + if (underlying_length < final_length) { + DCHECK_EQ(value_length, final_length); + PadToSameLength(underlying_value, value); + } + InterpolableList& underlying_interpolable_list = + ToInterpolableList(*underlying_value.interpolable_value); + NonInterpolableList& underlying_non_interpolable_list = + ToNonInterpolableList(*underlying_value.non_interpolable_value); + + for (size_t i = 0; i < value_length; i++) { + composite_item(underlying_interpolable_list.GetMutable(i), + underlying_non_interpolable_list.GetMutable(i), + underlying_fraction, *interpolable_list.Get(i), + non_interpolable_list.Get(i)); + } + for (size_t i = value_length; i < final_length; i++) { + underlying_interpolable_list.GetMutable(i)->Scale(underlying_fraction); + } } }
diff --git a/third_party/WebKit/Source/core/animation/ListInterpolationFunctions.h b/third_party/WebKit/Source/core/animation/ListInterpolationFunctions.h index 8e1fe60..9e868cb 100644 --- a/third_party/WebKit/Source/core/animation/ListInterpolationFunctions.h +++ b/third_party/WebKit/Source/core/animation/ListInterpolationFunctions.h
@@ -23,12 +23,15 @@ return InterpolationValue(InterpolableList::Create(0)); } + enum class LengthMatchingStrategy { kLowestCommonMultiple, kPadToLargest }; + using MergeSingleItemConversionsCallback = PairwiseInterpolationValue (*)(InterpolationValue&& start, InterpolationValue&& end); static PairwiseInterpolationValue MaybeMergeSingles( InterpolationValue&& start, InterpolationValue&& end, + LengthMatchingStrategy, MergeSingleItemConversionsCallback); using EqualNonInterpolableValuesCallback = @@ -48,6 +51,7 @@ double underlying_fraction, const InterpolationType&, const InterpolationValue&, + LengthMatchingStrategy, NonInterpolableValuesAreCompatibleCallback, CompositeItemCallback); };
diff --git a/third_party/WebKit/Source/core/clipboard/DataObject.cpp b/third_party/WebKit/Source/core/clipboard/DataObject.cpp index 68e324a..e21fadf 100644 --- a/third_party/WebKit/Source/core/clipboard/DataObject.cpp +++ b/third_party/WebKit/Source/core/clipboard/DataObject.cpp
@@ -57,7 +57,9 @@ continue; data_object->item_list_.push_back( DataObjectItem::CreateFromPasteboard(type, sequence_number)); - ASSERT(types_seen.insert(type).is_new_entry); +#if DCHECK_IS_ON() + DCHECK(types_seen.insert(type).is_new_entry); +#endif } return data_object; } @@ -142,7 +144,9 @@ case DataObjectItem::kStringKind: // Per the spec, type must be unique among all items of kind 'string'. results.push_back(item->GetType()); - ASSERT(types_seen.insert(item->GetType()).is_new_entry); +#if DCHECK_IS_ON() + DCHECK(types_seen.insert(item->GetType()).is_new_entry); +#endif break; case DataObjectItem::kFileKind: contains_files = true; @@ -151,7 +155,9 @@ } if (contains_files) { results.push_back(kMimeTypeFiles); - ASSERT(types_seen.insert(kMimeTypeFiles).is_new_entry); +#if DCHECK_IS_ON() + DCHECK(types_seen.insert(kMimeTypeFiles).is_new_entry); +#endif } return results; }
diff --git a/third_party/WebKit/Source/core/clipboard/DataObject.h b/third_party/WebKit/Source/core/clipboard/DataObject.h index 24d994a..2d699c5a 100644 --- a/third_party/WebKit/Source/core/clipboard/DataObject.h +++ b/third_party/WebKit/Source/core/clipboard/DataObject.h
@@ -98,7 +98,7 @@ filesystem_id_ = file_system_id; } const String& FilesystemId() const { - ASSERT(!filesystem_id_.IsEmpty()); + DCHECK(!filesystem_id_.IsEmpty()); return filesystem_id_; }
diff --git a/third_party/WebKit/Source/core/clipboard/DataObjectItem.cpp b/third_party/WebKit/Source/core/clipboard/DataObjectItem.cpp index 020b1060..785d4a52 100644 --- a/third_party/WebKit/Source/core/clipboard/DataObjectItem.cpp +++ b/third_party/WebKit/Source/core/clipboard/DataObjectItem.cpp
@@ -118,7 +118,7 @@ if (source_ == kInternalSource) { if (file_) return file_.Get(); - ASSERT(shared_buffer_); + DCHECK(shared_buffer_); // FIXME: This code is currently impossible--we never populate // m_sharedBuffer when dragging in. At some point though, we may need to // support correctly converting a shared buffer into a file.
diff --git a/third_party/WebKit/Source/core/clipboard/DataTransfer.cpp b/third_party/WebKit/Source/core/clipboard/DataTransfer.cpp index 558c0b7e..2738516 100644 --- a/third_party/WebKit/Source/core/clipboard/DataTransfer.cpp +++ b/third_party/WebKit/Source/core/clipboard/DataTransfer.cpp
@@ -218,7 +218,7 @@ } void DataTransfer::setDragImage(Element* image, int x, int y) { - ASSERT(image); + DCHECK(image); if (!IsForDragAndDrop()) return; @@ -265,7 +265,7 @@ static ImageResourceContent* GetImageResourceContent(Element* element) { // Attempt to pull ImageResourceContent from element - ASSERT(element); + DCHECK(element); LayoutObject* layout_object = element->GetLayoutObject(); if (!layout_object || !layout_object->IsImage()) return 0; @@ -316,7 +316,7 @@ void DataTransfer::WriteURL(Node* node, const KURL& url, const String& title) { if (!data_object_) return; - ASSERT(!url.IsEmpty()); + DCHECK(!url.IsEmpty()); data_object_->SetURLAndTitle(url, title);
diff --git a/third_party/WebKit/Source/core/clipboard/DraggedIsolatedFileSystem.cpp b/third_party/WebKit/Source/core/clipboard/DraggedIsolatedFileSystem.cpp index 31b6de4..b52f75e 100644 --- a/third_party/WebKit/Source/core/clipboard/DraggedIsolatedFileSystem.cpp +++ b/third_party/WebKit/Source/core/clipboard/DraggedIsolatedFileSystem.cpp
@@ -11,12 +11,12 @@ void DraggedIsolatedFileSystem::Init( DraggedIsolatedFileSystem::FileSystemIdPreparationCallback callback) { - ASSERT(!prepare_callback_); + DCHECK(!prepare_callback_); prepare_callback_ = callback; } void DraggedIsolatedFileSystem::PrepareForDataObject(DataObject* data_object) { - ASSERT(prepare_callback_); + DCHECK(prepare_callback_); (*prepare_callback_)(data_object); }
diff --git a/third_party/WebKit/Source/core/clipboard/Pasteboard.cpp b/third_party/WebKit/Source/core/clipboard/Pasteboard.cpp index 426f7f5..a706221 100644 --- a/third_party/WebKit/Source/core/clipboard/Pasteboard.cpp +++ b/third_party/WebKit/Source/core/clipboard/Pasteboard.cpp
@@ -73,7 +73,7 @@ void Pasteboard::WriteImage(Image* image, const KURL& url, const String& title) { - ASSERT(image); + DCHECK(image); const WebImage web_image(image); if (web_image.IsNull())
diff --git a/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp b/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp index a2f7877..42cf16d 100644 --- a/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp +++ b/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp
@@ -361,7 +361,7 @@ const CSSValue* CSSComputedStyleDeclaration::GetPropertyCSSValue( AtomicString custom_property_name) const { - Node* styled_node = this->StyledNode(); + Node* styled_node = StyledNode(); if (!styled_node) return nullptr; @@ -370,9 +370,11 @@ const ComputedStyle* style = ComputeComputedStyle(); if (!style) return nullptr; + // Don't use styled_node in case it was discarded or replaced in + // UpdateStyleAndLayoutTreeForNode. return ComputedStyleCSSValueMapping::Get( custom_property_name, *style, - styled_node->GetDocument().GetPropertyRegistry()); + StyledNode()->GetDocument().GetPropertyRegistry()); } std::unique_ptr<HashMap<AtomicString, RefPtr<CSSVariableData>>> @@ -385,7 +387,7 @@ const CSSValue* CSSComputedStyleDeclaration::GetPropertyCSSValue( CSSPropertyID property_id) const { - Node* styled_node = this->StyledNode(); + Node* styled_node = StyledNode(); if (!styled_node) return nullptr; @@ -394,7 +396,7 @@ // The style recalc could have caused the styled node to be discarded or // replaced if it was a PseudoElement so we need to update it. - styled_node = this->StyledNode(); + styled_node = StyledNode(); LayoutObject* layout_object = styled_node->GetLayoutObject(); const ComputedStyle* style = ComputeComputedStyle(); @@ -407,7 +409,7 @@ if (force_full_layout) { document.UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(styled_node); - styled_node = this->StyledNode(); + styled_node = StyledNode(); style = ComputeComputedStyle(); layout_object = styled_node->GetLayoutObject(); }
diff --git a/third_party/WebKit/Source/core/css/RuleSet.cpp b/third_party/WebKit/Source/core/css/RuleSet.cpp index c8a5742..ad60c3d 100644 --- a/third_party/WebKit/Source/core/css/RuleSet.cpp +++ b/third_party/WebKit/Source/core/css/RuleSet.cpp
@@ -370,7 +370,7 @@ } void RuleSet::CompactRules() { - ASSERT(pending_rules_); + DCHECK(pending_rules_); PendingRuleMaps* pending_rules = pending_rules_.Release(); CompactPendingRules(pending_rules->id_rules, id_rules_); CompactPendingRules(pending_rules->class_rules, class_rules_);
diff --git a/third_party/WebKit/Source/core/css/SelectorFilter.cpp b/third_party/WebKit/Source/core/css/SelectorFilter.cpp index cd78a45..4b50414 100644 --- a/third_party/WebKit/Source/core/css/SelectorFilter.cpp +++ b/third_party/WebKit/Source/core/css/SelectorFilter.cpp
@@ -87,7 +87,9 @@ ancestor_identifier_filter_->Remove(parent_frame.identifier_hashes[i]); parent_stack_.pop_back(); if (parent_stack_.IsEmpty()) { - ASSERT(ancestor_identifier_filter_->LikelyEmpty()); +#if DCHECK_IS_ON() + DCHECK(ancestor_identifier_filter_->LikelyEmpty()); +#endif ancestor_identifier_filter_.reset(); } }
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp index 370f3736..c8d1504 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp
@@ -815,8 +815,8 @@ CSSValuePair::kDropIdenticalValues); } -static CSSValue* ConsumeBorderImageSlice(CSSPropertyID property, - CSSParserTokenRange& range) { +static CSSValue* ConsumeBorderImageSlice(CSSParserTokenRange& range, + bool default_fill) { bool fill = ConsumeIdent<CSSValueFill>(range); CSSValue* slices[4] = {0}; @@ -836,14 +836,7 @@ fill = true; } Complete4Sides(slices); - // FIXME: For backwards compatibility, -webkit-border-image, - // -webkit-mask-box-image and -webkit-box-reflect have to do a fill by - // default. - // FIXME: What do we do with -webkit-box-reflect and -webkit-mask-box-image? - // Probably just have to leave them filling... - if (property == CSSPropertyWebkitBorderImage || - property == CSSPropertyWebkitMaskBoxImage || - property == CSSPropertyWebkitBoxReflect) + if (default_fill) fill = true; return CSSBorderImageSliceValue::Create( CSSQuadValue::Create(slices[0], slices[1], slices[2], slices[3], @@ -893,14 +886,14 @@ CSSQuadValue::kSerializeAsQuad); } -static bool ConsumeBorderImageComponents(CSSPropertyID property, - CSSParserTokenRange& range, +static bool ConsumeBorderImageComponents(CSSParserTokenRange& range, const CSSParserContext* context, CSSValue*& source, CSSValue*& slice, CSSValue*& width, CSSValue*& outset, - CSSValue*& repeat) { + CSSValue*& repeat, + bool default_fill) { do { if (!source) { source = ConsumeImageOrNone(range, context); @@ -913,7 +906,7 @@ continue; } if (!slice) { - slice = ConsumeBorderImageSlice(property, range); + slice = ConsumeBorderImageSlice(range, default_fill); if (slice) { DCHECK(!width); DCHECK(!outset); @@ -937,16 +930,15 @@ return true; } -static CSSValue* ConsumeWebkitBorderImage(CSSPropertyID property, - CSSParserTokenRange& range, +static CSSValue* ConsumeWebkitBorderImage(CSSParserTokenRange& range, const CSSParserContext* context) { CSSValue* source = nullptr; CSSValue* slice = nullptr; CSSValue* width = nullptr; CSSValue* outset = nullptr; CSSValue* repeat = nullptr; - if (ConsumeBorderImageComponents(property, range, context, source, slice, - width, outset, repeat)) + if (ConsumeBorderImageComponents(range, context, source, slice, width, outset, + repeat, true /* default_fill */)) return CreateBorderImageValue(source, slice, width, outset, repeat); return nullptr; } @@ -971,8 +963,7 @@ CSSValue* mask = nullptr; if (!range.AtEnd()) { - mask = - ConsumeWebkitBorderImage(CSSPropertyWebkitBoxReflect, range, context); + mask = ConsumeWebkitBorderImage(range, context); if (!mask) return nullptr; } @@ -1786,7 +1777,7 @@ return ConsumeBorderImageRepeat(range_); case CSSPropertyBorderImageSlice: case CSSPropertyWebkitMaskBoxImageSlice: - return ConsumeBorderImageSlice(property, range_); + return ConsumeBorderImageSlice(range_, false /* default_fill */); case CSSPropertyBorderImageOutset: case CSSPropertyWebkitMaskBoxImageOutset: return ConsumeBorderImageOutset(range_); @@ -1794,7 +1785,7 @@ case CSSPropertyWebkitMaskBoxImageWidth: return ConsumeBorderImageWidth(range_); case CSSPropertyWebkitBorderImage: - return ConsumeWebkitBorderImage(property, range_, context_); + return ConsumeWebkitBorderImage(range_, context_); case CSSPropertyWebkitBoxReflect: return ConsumeReflect(range_, context_); case CSSPropertyBackgroundAttachment: @@ -2491,15 +2482,18 @@ return range_.AtEnd(); } +// TODO(crbug.com/668012): refactor out property specific logic from this method +// and remove CSSPropetyID argument bool CSSPropertyParser::ConsumeBorderImage(CSSPropertyID property, + bool default_fill, bool important) { CSSValue* source = nullptr; CSSValue* slice = nullptr; CSSValue* width = nullptr; CSSValue* outset = nullptr; CSSValue* repeat = nullptr; - if (ConsumeBorderImageComponents(property, range_, context_, source, slice, - width, outset, repeat)) { + if (ConsumeBorderImageComponents(range_, context_, source, slice, width, + outset, repeat, default_fill)) { switch (property) { case CSSPropertyWebkitMaskBoxImage: AddProperty(CSSPropertyWebkitMaskBoxImageSource, @@ -3338,8 +3332,9 @@ case CSSPropertyBorder: return ConsumeBorder(important); case CSSPropertyBorderImage: + return ConsumeBorderImage(property, false /* default_fill */, important); case CSSPropertyWebkitMaskBoxImage: - return ConsumeBorderImage(property, important); + return ConsumeBorderImage(property, true /* default_fill */, important); case CSSPropertyPageBreakAfter: case CSSPropertyPageBreakBefore: case CSSPropertyPageBreakInside:
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.h b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.h index 23bfd9b..57a3ee8 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.h +++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.h
@@ -114,7 +114,7 @@ bool ConsumeBorderSpacing(bool important); // CSS3 Parsing Routines (for properties specific to CSS3) - bool ConsumeBorderImage(CSSPropertyID, bool important); + bool ConsumeBorderImage(CSSPropertyID, bool default_fill, bool important); bool ConsumeFlex(bool important);
diff --git a/third_party/WebKit/Source/core/dom/DOMTypedArray.h b/third_party/WebKit/Source/core/dom/DOMTypedArray.h index abdd363..d269e16 100644 --- a/third_party/WebKit/Source/core/dom/DOMTypedArray.h +++ b/third_party/WebKit/Source/core/dom/DOMTypedArray.h
@@ -79,10 +79,10 @@ private: explicit DOMTypedArray(PassRefPtr<WTFTypedArray> buffer_view) - : DOMArrayBufferView(buffer_view) {} + : DOMArrayBufferView(std::move(buffer_view)) {} DOMTypedArray(PassRefPtr<WTFTypedArray> buffer_view, DOMArrayBufferBase* dom_array_buffer) - : DOMArrayBufferView(buffer_view, dom_array_buffer) {} + : DOMArrayBufferView(std::move(buffer_view), dom_array_buffer) {} }; extern template class CORE_EXTERN_TEMPLATE_EXPORT
diff --git a/third_party/WebKit/Source/core/dom/ExecutionContext.cpp b/third_party/WebKit/Source/core/dom/ExecutionContext.cpp index 73785b2..1441ab9 100644 --- a/third_party/WebKit/Source/core/dom/ExecutionContext.cpp +++ b/third_party/WebKit/Source/core/dom/ExecutionContext.cpp
@@ -29,6 +29,7 @@ #include <memory> #include "bindings/core/v8/SourceLocation.h" +#include "bindings/core/v8/V8BindingForCore.h" #include "core/dom/ExecutionContextTask.h" #include "core/dom/SuspendableObject.h" #include "core/dom/TaskRunnerHelper.h"
diff --git a/third_party/WebKit/Source/core/frame/DOMTimer.cpp b/third_party/WebKit/Source/core/frame/DOMTimer.cpp index e527576..40d6a6c 100644 --- a/third_party/WebKit/Source/core/frame/DOMTimer.cpp +++ b/third_party/WebKit/Source/core/frame/DOMTimer.cpp
@@ -133,7 +133,7 @@ void DOMTimer::Fired() { ExecutionContext* context = GetExecutionContext(); - ASSERT(context); + DCHECK(context); context->Timers()->SetTimerNestingLevel(nesting_level_); DCHECK(!context->IsContextSuspended()); // Only the first execution of a multi-shot timer should get an affirmative
diff --git a/third_party/WebKit/Source/core/frame/DOMWindow.cpp b/third_party/WebKit/Source/core/frame/DOMWindow.cpp index 84ccd65..0eef068 100644 --- a/third_party/WebKit/Source/core/frame/DOMWindow.cpp +++ b/third_party/WebKit/Source/core/frame/DOMWindow.cpp
@@ -368,7 +368,7 @@ Document* active_document = nullptr; if (context) { - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); active_document = ToDocument(context); if (!active_document) return; @@ -415,13 +415,13 @@ if (!page) return; - ASSERT(context); + DCHECK(context); bool allow_focus = context->IsWindowInteractionAllowed(); if (allow_focus) { context->ConsumeWindowInteraction(); } else { - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); allow_focus = opener() && (opener() != this) && (ToDocument(context)->domWindow() == opener()); }
diff --git a/third_party/WebKit/Source/core/frame/Deprecation.cpp b/third_party/WebKit/Source/core/frame/Deprecation.cpp index 9f73ac9..eceee5ec 100644 --- a/third_party/WebKit/Source/core/frame/Deprecation.cpp +++ b/third_party/WebKit/Source/core/frame/Deprecation.cpp
@@ -130,7 +130,7 @@ if (!page->GetUseCounter().HasRecordedMeasurement(feature)) { page->GetUseCounter().RecordMeasurement(feature); - ASSERT(!DeprecationMessage(feature).IsEmpty()); + DCHECK(!DeprecationMessage(feature).IsEmpty()); ConsoleMessage* console_message = ConsoleMessage::Create(kDeprecationMessageSource, kWarningMessageLevel, DeprecationMessage(feature));
diff --git a/third_party/WebKit/Source/core/frame/Frame.cpp b/third_party/WebKit/Source/core/frame/Frame.cpp index a3aaa924..28a96d4 100644 --- a/third_party/WebKit/Source/core/frame/Frame.cpp +++ b/third_party/WebKit/Source/core/frame/Frame.cpp
@@ -313,7 +313,7 @@ } } - ASSERT(GetSecurityContext()->GetSecurityOrigin()); + DCHECK(GetSecurityContext()->GetSecurityOrigin()); SecurityOrigin& origin = *GetSecurityContext()->GetSecurityOrigin(); // This is the normal case. A document can navigate its decendant frames,
diff --git a/third_party/WebKit/Source/core/frame/FrameSerializer.cpp b/third_party/WebKit/Source/core/frame/FrameSerializer.cpp index f11ea6d..a225865 100644 --- a/third_party/WebKit/Source/core/frame/FrameSerializer.cpp +++ b/third_party/WebKit/Source/core/frame/FrameSerializer.cpp
@@ -206,7 +206,7 @@ AppendRewrittenAttribute(out, element, attribute.GetName().ToString(), new_link_for_the_element); } else { - ASSERT(is_src_doc_attribute); + DCHECK(is_src_doc_attribute); // Emit src instead of srcdoc attribute for frame elements - we want the // serialized subframe to use html contents from the link provided by // Delegate::rewriteLink rather than html contents from srcdoc @@ -271,7 +271,7 @@ void FrameSerializer::SerializeFrame(const LocalFrame& frame) { TRACE_EVENT0("page-serialization", "FrameSerializer::serializeFrame"); - ASSERT(frame.GetDocument()); + DCHECK(frame.GetDocument()); Document& document = *frame.GetDocument(); KURL url = document.Url(); @@ -300,7 +300,7 @@ } for (Node* node : serialized_nodes) { - ASSERT(node); + DCHECK(node); if (!node->IsElementNode()) continue; @@ -383,7 +383,7 @@ } WTF::TextEncoding text_encoding(style_sheet.Contents()->Charset()); - ASSERT(text_encoding.IsValid()); + DCHECK(text_encoding.IsValid()); String text_string = css_text.ToString(); CString text = text_encoding.Encode( text_string, WTF::kCSSEncodedEntitiesForUnencodables); @@ -410,7 +410,7 @@ } void FrameSerializer::SerializeCSSRule(CSSRule* rule) { - ASSERT(rule->parentStyleSheet()->OwnerDocument()); + DCHECK(rule->parentStyleSheet()->OwnerDocument()); Document& document = *rule->parentStyleSheet()->OwnerDocument(); switch (rule->type()) { @@ -422,7 +422,7 @@ case CSSRule::kImportRule: { CSSImportRule* import_rule = ToCSSImportRule(rule); KURL sheet_base_url = rule->parentStyleSheet()->BaseURL(); - ASSERT(sheet_base_url.IsValid()); + DCHECK(sheet_base_url.IsValid()); KURL import_url = KURL(sheet_base_url, import_rule->href()); if (import_rule->styleSheet()) SerializeCSSStyleSheet(*import_rule->styleSheet(), import_url);
diff --git a/third_party/WebKit/Source/core/frame/FrameView.cpp b/third_party/WebKit/Source/core/frame/FrameView.cpp index 883b2e6..ae3818d 100644 --- a/third_party/WebKit/Source/core/frame/FrameView.cpp +++ b/third_party/WebKit/Source/core/frame/FrameView.cpp
@@ -232,7 +232,9 @@ } FrameView::~FrameView() { - ASSERT(has_been_disposed_); +#if DCHECK_IS_ON() + DCHECK(has_been_disposed_); +#endif } DEFINE_TRACE(FrameView) { @@ -990,7 +992,7 @@ // Synchronously enter layout, to layout the view containing the host // object/embed/iframe. - ASSERT(frame_view); + DCHECK(frame_view); frame_view->UpdateLayout(); } @@ -1108,7 +1110,7 @@ ScheduleOrthogonalWritingModeRootsForLayout(); } - ASSERT(!IsInPerformLayout()); + DCHECK(!IsInPerformLayout()); Lifecycle().AdvanceTo(DocumentLifecycle::kInPerformLayout); // performLayout is the actual guts of layout(). @@ -1179,9 +1181,9 @@ void FrameView::UpdateLayout() { // We should never layout a Document which is not in a LocalFrame. - ASSERT(frame_); + DCHECK(frame_); ASSERT(frame_->View() == this); - ASSERT(frame_->GetPage()); + DCHECK(frame_->GetPage()); ScriptForbiddenScope forbid_script; @@ -1313,7 +1315,7 @@ if (!in_subtree_layout && !document->Printing()) AdjustViewSizeAndLayout(); - ASSERT(layout_subtree_root_list_.IsEmpty()); + DCHECK(layout_subtree_root_list_.IsEmpty()); } // Reset m_layoutSchedulingEnabled to its previous value. CheckDoesNotNeedLayout(); @@ -1373,7 +1375,7 @@ RELEASE_ASSERT(!GetLayoutViewItem().IsNull()); LayoutViewItem root_for_paint_invalidation = GetLayoutViewItem(); - ASSERT(!root_for_paint_invalidation.NeedsLayout()); + DCHECK(!root_for_paint_invalidation.NeedsLayout()); TRACE_EVENT1("blink", "FrameView::invalidateTree", "root", root_for_paint_invalidation.DebugName().Ascii()); @@ -1524,10 +1526,10 @@ } void FrameView::AddPartToUpdate(LayoutEmbeddedObject& object) { - ASSERT(IsInPerformLayout()); + DCHECK(IsInPerformLayout()); // Tell the DOM element that it needs a FrameViewBase update. Node* node = object.GetNode(); - ASSERT(node); + DCHECK(node); if (isHTMLObjectElement(*node) || isHTMLEmbedElement(*node)) ToHTMLPlugInElement(node)->SetNeedsPluginUpdate(true); @@ -1591,7 +1593,7 @@ } void FrameView::AddBackgroundAttachmentFixedObject(LayoutObject* object) { - ASSERT(!background_attachment_fixed_objects_.Contains(object)); + DCHECK(!background_attachment_fixed_objects_.Contains(object)); background_attachment_fixed_objects_.insert(object); if (ScrollingCoordinator* scrolling_coordinator = @@ -1608,7 +1610,7 @@ } void FrameView::RemoveBackgroundAttachmentFixedObject(LayoutObject* object) { - ASSERT(background_attachment_fixed_objects_.Contains(object)); + DCHECK(background_attachment_fixed_objects_.Contains(object)); background_attachment_fixed_objects_.erase(object); if (ScrollingCoordinator* scrolling_coordinator = @@ -1783,8 +1785,8 @@ *viewport_constrained_objects_) { LayoutObject* layout_object = viewport_constrained_object; LayoutItem layout_item = LayoutItem(layout_object); - ASSERT(layout_item.Style()->HasViewportConstrainedPosition()); - ASSERT(layout_item.HasLayer()); + DCHECK(layout_item.Style()->HasViewportConstrainedPosition()); + DCHECK(layout_item.HasLayer()); PaintLayer* layer = LayoutBoxModel(layout_item).Layer(); if (layer->IsPaintInvalidationContainer()) @@ -1837,7 +1839,7 @@ // all of the objects. // FIXME: Find out what are enough to invalidate in slow path scrolling. // crbug.com/451090#9. - ASSERT(!GetLayoutViewItem().IsNull()); + DCHECK(!GetLayoutViewItem().IsNull()); if (ContentsInCompositedLayer()) GetLayoutViewItem() .Layer() @@ -1849,7 +1851,7 @@ if (ContentsInCompositedLayer()) { IntRect update_rect = VisibleContentRect(); - ASSERT(!GetLayoutViewItem().IsNull()); + DCHECK(!GetLayoutViewItem().IsNull()); // FIXME: We should not allow paint invalidation out of paint invalidation // state. crbug.com/457415 DisablePaintInvalidationStateAsserts disabler; @@ -1901,7 +1903,7 @@ bool FrameView::ProcessUrlFragmentHelper(const String& name, UrlFragmentBehavior behavior) { - ASSERT(frame_->GetDocument()); + DCHECK(frame_->GetDocument()); if (behavior == kUrlFragmentScroll && !frame_->GetDocument()->IsRenderingReady()) { @@ -1954,7 +1956,7 @@ } void FrameView::SetFragmentAnchor(Node* anchor_node) { - ASSERT(anchor_node); + DCHECK(anchor_node); fragment_anchor_ = anchor_node; // We need to update the layout tree before scrolling. @@ -2008,7 +2010,7 @@ } void FrameView::SetLayoutSize(const IntSize& size) { - ASSERT(!LayoutSizeFixedToFrameSize()); + DCHECK(!LayoutSizeFixedToFrameSize()); SetLayoutSizeInternal(size); } @@ -2110,7 +2112,7 @@ TRACE_EVENT0("blink", "FrameView::updateCompositedSelectionIfNeeded"); Page* page = GetFrame().GetPage(); - ASSERT(page); + DCHECK(page); CompositedSelection selection; LocalFrame* focused_frame = page->GetFocusController().FocusedFrame(); @@ -2523,7 +2525,7 @@ } void FrameView::UpdatePluginsTimerFired(TimerBase*) { - ASSERT(!IsInPerformLayout()); + DCHECK(!IsInPerformLayout()); for (unsigned i = 0; i < kMaxUpdatePluginsIterations; ++i) { if (UpdatePlugins()) return; @@ -2531,7 +2533,7 @@ } void FrameView::FlushAnyPendingPostLayoutTasks() { - ASSERT(!IsInPerformLayout()); + DCHECK(!IsInPerformLayout()); if (post_layout_tasks_timer_.IsActive()) PerformPostLayoutTasks(); if (update_plugins_timer_.IsActive()) { @@ -2541,7 +2543,7 @@ } void FrameView::ScheduleUpdatePluginsIfNecessary() { - ASSERT(!IsInPerformLayout()); + DCHECK(!IsInPerformLayout()); if (update_plugins_timer_.IsActive() || part_update_set_.IsEmpty()) return; update_plugins_timer_.StartOneShot(0, BLINK_FROM_HERE); @@ -2551,18 +2553,18 @@ // FIXME: We can reach here, even when the page is not active! // http/tests/inspector/elements/html-link-import.html and many other // tests hit that case. - // We should ASSERT(isActive()); or at least return early if we can! + // We should DCHECK(isActive()); or at least return early if we can! // Always called before or after performLayout(), part of the highest-level // layout() call. - ASSERT(!IsInPerformLayout()); + DCHECK(!IsInPerformLayout()); TRACE_EVENT0("blink,benchmark", "FrameView::performPostLayoutTasks"); post_layout_tasks_timer_.Stop(); frame_->Selection().DidLayout(); - ASSERT(frame_->GetDocument()); + DCHECK(frame_->GetDocument()); FontFaceSet::DidLayout(*frame_->GetDocument()); // Cursor update scheduling is done by the local root, which is the main frame @@ -2588,17 +2590,17 @@ } bool FrameView::WasViewportResized() { - ASSERT(frame_); + DCHECK(frame_); LayoutViewItem layout_view_item = this->GetLayoutViewItem(); if (layout_view_item.IsNull()) return false; - ASSERT(layout_view_item.Style()); + DCHECK(layout_view_item.Style()); return (GetLayoutSize(kIncludeScrollbars) != last_viewport_size_ || layout_view_item.Style()->Zoom() != last_zoom_factor_); } void FrameView::SendResizeEventIfNeeded() { - ASSERT(frame_); + DCHECK(frame_); LayoutViewItem layout_view_item = this->GetLayoutViewItem(); if (layout_view_item.IsNull() || layout_view_item.GetDocument().Printing()) @@ -3258,7 +3260,7 @@ (!GetFrame().Tree().Parent()->IsLocalFrame())); LayoutViewItem view = GetLayoutViewItem(); - ASSERT(!view.IsNull()); + DCHECK(!view.IsNull()); ForAllNonThrottledFrameViews([](FrameView& frame_view) { frame_view.Lifecycle().AdvanceTo(DocumentLifecycle::kInPaint); }); @@ -3810,7 +3812,7 @@ } void FrameView::AddScrollableArea(ScrollableArea* scrollable_area) { - ASSERT(scrollable_area); + DCHECK(scrollable_area); if (!scrollable_areas_) scrollable_areas_ = new ScrollableAreaSet; scrollable_areas_->insert(scrollable_area); @@ -3831,7 +3833,7 @@ } void FrameView::AddAnimatingScrollableArea(ScrollableArea* scrollable_area) { - ASSERT(scrollable_area); + DCHECK(scrollable_area); if (!animating_scrollable_areas_) animating_scrollable_areas_ = new ScrollableAreaSet; animating_scrollable_areas_->insert(scrollable_area); @@ -4282,7 +4284,7 @@ bool FrameView::AdjustScrollbarExistence( ComputeScrollbarExistenceOption option) { - ASSERT(in_update_scrollbars_); + DCHECK(in_update_scrollbars_); // If we came in here with the view already needing a layout, then go ahead // and do that first. (This will be the common case, e.g., when the page
diff --git a/third_party/WebKit/Source/core/frame/FrameView.h b/third_party/WebKit/Source/core/frame/FrameView.h index 4d596f7c..a1d552cb 100644 --- a/third_party/WebKit/Source/core/frame/FrameView.h +++ b/third_party/WebKit/Source/core/frame/FrameView.h
@@ -134,7 +134,7 @@ void Resize(const IntSize& size) { SetFrameRect(IntRect(Location(), size)); } LocalFrame& GetFrame() const { - ASSERT(frame_); + DCHECK(frame_); return *frame_; }
diff --git a/third_party/WebKit/Source/core/frame/FrameViewAutoSizeInfo.cpp b/third_party/WebKit/Source/core/frame/FrameViewAutoSizeInfo.cpp index 61f512e..416bc53 100644 --- a/third_party/WebKit/Source/core/frame/FrameViewAutoSizeInfo.cpp +++ b/third_party/WebKit/Source/core/frame/FrameViewAutoSizeInfo.cpp
@@ -15,7 +15,7 @@ FrameViewAutoSizeInfo::FrameViewAutoSizeInfo(FrameView* view) : frame_view_(view), in_auto_size_(false), did_run_autosize_(false) { - ASSERT(frame_view_); + DCHECK(frame_view_); } DEFINE_TRACE(FrameViewAutoSizeInfo) { @@ -24,7 +24,7 @@ void FrameViewAutoSizeInfo::ConfigureAutoSizeMode(const IntSize& min_size, const IntSize& max_size) { - ASSERT(!min_size.IsEmpty()); + DCHECK(!min_size.IsEmpty()); ASSERT(min_size.Width() <= max_size.Width()); ASSERT(min_size.Height() <= max_size.Height());
diff --git a/third_party/WebKit/Source/core/frame/ImageBitmap.cpp b/third_party/WebKit/Source/core/frame/ImageBitmap.cpp index 236964c..4534c55e 100644 --- a/third_party/WebKit/Source/core/frame/ImageBitmap.cpp +++ b/third_party/WebKit/Source/core/frame/ImageBitmap.cpp
@@ -417,7 +417,7 @@ ParsedOptions& parsed_options, AlphaDisposition image_format, ColorBehavior color_behavior) { - ASSERT(image); + DCHECK(image); IntRect img_rect(IntPoint(), IntSize(image->width(), image->height())); const IntRect src_rect = Intersection(img_rect, parsed_options.crop_rect); @@ -629,7 +629,7 @@ ImageBitmap::ImageBitmap(HTMLCanvasElement* canvas, Optional<IntRect> crop_rect, const ImageBitmapOptions& options) { - ASSERT(canvas->IsPaintable()); + DCHECK(canvas->IsPaintable()); RefPtr<Image> input; if (canvas->PlaceholderFrame()) { input = canvas->PlaceholderFrame(); @@ -978,7 +978,7 @@ } PassRefPtr<StaticBitmapImage> ImageBitmap::Transfer() { - ASSERT(!IsNeutered()); + DCHECK(!IsNeutered()); is_neutered_ = true; image_->Transfer(); return std::move(image_);
diff --git a/third_party/WebKit/Source/core/frame/LayoutSubtreeRootList.cpp b/third_party/WebKit/Source/core/frame/LayoutSubtreeRootList.cpp index 357b1371..80c9303 100644 --- a/third_party/WebKit/Source/core/frame/LayoutSubtreeRootList.cpp +++ b/third_party/WebKit/Source/core/frame/LayoutSubtreeRootList.cpp
@@ -15,7 +15,7 @@ } LayoutObject* LayoutSubtreeRootList::RandomRoot() { - ASSERT(!IsEmpty()); + DCHECK(!IsEmpty()); return *Unordered().begin(); }
diff --git a/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp b/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp index 80de18a..9007394 100644 --- a/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp +++ b/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp
@@ -295,7 +295,7 @@ if (!document_) return; - ASSERT(!document_->IsActive()); + DCHECK(!document_->IsActive()); // FIXME: This should be part of SuspendableObject shutdown ClearEventQueue(); @@ -464,7 +464,7 @@ LocalDOMWindow::~LocalDOMWindow() { // Cleared when detaching document. - ASSERT(!event_queue_); + DCHECK(!event_queue_); } void LocalDOMWindow::Dispose() { @@ -529,7 +529,7 @@ } void LocalDOMWindow::SendOrientationChangeEvent() { - ASSERT(RuntimeEnabledFeatures::orientationEventEnabled()); + DCHECK(RuntimeEnabledFeatures::orientationEventEnabled()); DCHECK(GetFrame()->IsLocalRoot()); // Before dispatching the event, build a list of all frames in the page @@ -552,7 +552,7 @@ } int LocalDOMWindow::orientation() const { - ASSERT(RuntimeEnabledFeatures::orientationEventEnabled()); + DCHECK(RuntimeEnabledFeatures::orientationEventEnabled()); if (!GetFrame() || !GetFrame()->GetPage()) return 0; @@ -1120,7 +1120,7 @@ return; GetFrame()->Tree().SetName(name); - ASSERT(GetFrame()->Loader().Client()); + DCHECK(GetFrame()->Loader().Client()); GetFrame()->Loader().Client()->DidChangeName(name); } @@ -1167,7 +1167,7 @@ CSSStyleDeclaration* LocalDOMWindow::getComputedStyle( Element* elt, const String& pseudo_elt) const { - ASSERT(elt); + DCHECK(elt); return CSSComputedStyleDeclaration::Create(elt, false, pseudo_elt); }
diff --git a/third_party/WebKit/Source/core/frame/LocalFrame.cpp b/third_party/WebKit/Source/core/frame/LocalFrame.cpp index b2b8623..3a34057 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrame.cpp +++ b/third_party/WebKit/Source/core/frame/LocalFrame.cpp
@@ -305,8 +305,8 @@ bool horizontal_lock, ScrollbarMode vertical_scrollbar_mode, bool vertical_lock) { - ASSERT(this); - ASSERT(GetPage()); + DCHECK(this); + DCHECK(GetPage()); bool is_local_root = this->IsLocalRoot(); @@ -339,7 +339,7 @@ // FIXME: Not clear what the right thing for OOPI is here. if (!OwnerLayoutItem().IsNull()) { HTMLFrameOwnerElement* owner = DeprecatedLocalOwner(); - ASSERT(owner); + DCHECK(owner); // FIXME: OOPI might lead to us temporarily lying to a frame and telling it // that it's owned by a FrameOwner that knows nothing about it. If we're // lying to this frame, don't let it clobber the existing widget. @@ -355,7 +355,7 @@ LocalFrame::~LocalFrame() { // Verify that the FrameView has been cleared as part of detaching // the frame owner. - ASSERT(!view_); + DCHECK(!view_); } DEFINE_TRACE(LocalFrame) { @@ -751,7 +751,7 @@ return nullptr; view_->UpdateAllLifecyclePhasesExceptPaint(); - ASSERT(GetDocument()->IsActive()); + DCHECK(GetDocument()->IsActive()); FloatRect painting_rect = FloatRect(Selection().Bounds()); GlobalPaintFlags paint_flags =
diff --git a/third_party/WebKit/Source/core/frame/LocalFrame.h b/third_party/WebKit/Source/core/frame/LocalFrame.h index 243f9d97..45f9220 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrame.h +++ b/third_party/WebKit/Source/core/frame/LocalFrame.h
@@ -296,7 +296,7 @@ } inline NavigationScheduler& LocalFrame::GetNavigationScheduler() const { - ASSERT(navigation_scheduler_); + DCHECK(navigation_scheduler_); return *navigation_scheduler_.Get(); } @@ -337,7 +337,7 @@ } inline EventHandler& LocalFrame::GetEventHandler() const { - ASSERT(event_handler_); + DCHECK(event_handler_); return *event_handler_; }
diff --git a/third_party/WebKit/Source/core/frame/PlatformEventController.cpp b/third_party/WebKit/Source/core/frame/PlatformEventController.cpp index de4986b5b..492b3726 100644 --- a/third_party/WebKit/Source/core/frame/PlatformEventController.cpp +++ b/third_party/WebKit/Source/core/frame/PlatformEventController.cpp
@@ -20,8 +20,8 @@ void PlatformEventController::OneShotCallback(TimerBase* timer) { DCHECK_EQ(timer, &timer_); - ASSERT(HasLastData()); - ASSERT(!timer_.IsActive()); + DCHECK(HasLastData()); + DCHECK(!timer_.IsActive()); DidUpdateData(); }
diff --git a/third_party/WebKit/Source/core/frame/PlatformEventDispatcher.cpp b/third_party/WebKit/Source/core/frame/PlatformEventDispatcher.cpp index 464c28a..90ccfd1 100644 --- a/third_party/WebKit/Source/core/frame/PlatformEventDispatcher.cpp +++ b/third_party/WebKit/Source/core/frame/PlatformEventDispatcher.cpp
@@ -14,7 +14,7 @@ void PlatformEventDispatcher::AddController( PlatformEventController* controller) { - ASSERT(controller); + DCHECK(controller); // TODO: If we can avoid to register a same controller twice, we can change // this 'if' to ASSERT. if (controllers_.Contains(controller)) @@ -30,7 +30,7 @@ void PlatformEventDispatcher::RemoveController( PlatformEventController* controller) { - ASSERT(controllers_.Contains(controller)); + DCHECK(controllers_.Contains(controller)); controllers_.erase(controller); if (!is_dispatching_ && controllers_.IsEmpty()) {
diff --git a/third_party/WebKit/Source/core/frame/RemoteFrame.cpp b/third_party/WebKit/Source/core/frame/RemoteFrame.cpp index 553b3d1..b03a004 100644 --- a/third_party/WebKit/Source/core/frame/RemoteFrame.cpp +++ b/third_party/WebKit/Source/core/frame/RemoteFrame.cpp
@@ -40,7 +40,7 @@ } RemoteFrame::~RemoteFrame() { - ASSERT(!view_); + DCHECK(!view_); } DEFINE_TRACE(RemoteFrame) { @@ -133,7 +133,7 @@ if (!DeprecatedLocalOwner()) return; - ASSERT(!DeprecatedLocalOwner()->OwnedWidget()); + DCHECK(!DeprecatedLocalOwner()->OwnedWidget()); SetView(RemoteFrameView::Create(this)); @@ -152,7 +152,7 @@ if (web_layer_) GraphicsLayer::RegisterContentsLayer(web_layer_); - ASSERT(Owner()); + DCHECK(Owner()); ToHTMLFrameOwnerElement(Owner())->SetNeedsCompositingUpdate(); }
diff --git a/third_party/WebKit/Source/core/frame/RemoteFrameView.cpp b/third_party/WebKit/Source/core/frame/RemoteFrameView.cpp index 30f847e..5543771 100644 --- a/third_party/WebKit/Source/core/frame/RemoteFrameView.cpp +++ b/third_party/WebKit/Source/core/frame/RemoteFrameView.cpp
@@ -17,7 +17,7 @@ RemoteFrameView::RemoteFrameView(RemoteFrame* remote_frame) : remote_frame_(remote_frame) { - ASSERT(remote_frame); + DCHECK(remote_frame); } RemoteFrameView::~RemoteFrameView() {}
diff --git a/third_party/WebKit/Source/core/frame/RemoteFrameView.h b/third_party/WebKit/Source/core/frame/RemoteFrameView.h index bfb93c60..8fd5c98 100644 --- a/third_party/WebKit/Source/core/frame/RemoteFrameView.h +++ b/third_party/WebKit/Source/core/frame/RemoteFrameView.h
@@ -32,7 +32,7 @@ FrameViewBase* Parent() const override { return parent_; } RemoteFrame& GetFrame() const { - ASSERT(remote_frame_); + DCHECK(remote_frame_); return *remote_frame_; }
diff --git a/third_party/WebKit/Source/core/frame/RootFrameViewport.h b/third_party/WebKit/Source/core/frame/RootFrameViewport.h index ccd1761e..661cda8f 100644 --- a/third_party/WebKit/Source/core/frame/RootFrameViewport.h +++ b/third_party/WebKit/Source/core/frame/RootFrameViewport.h
@@ -124,7 +124,7 @@ void UpdateScrollAnimator(); ScrollableArea& VisualViewport() const { - ASSERT(visual_viewport_); + DCHECK(visual_viewport_); return *visual_viewport_; }
diff --git a/third_party/WebKit/Source/core/frame/SmartClip.cpp b/third_party/WebKit/Source/core/frame/SmartClip.cpp index caa41f5e..bd1070ac 100644 --- a/third_party/WebKit/Source/core/frame/SmartClip.cpp +++ b/third_party/WebKit/Source/core/frame/SmartClip.cpp
@@ -202,7 +202,7 @@ // image in the smart clip. It seems to want to include sprites created from // CSS background images but to skip actual backgrounds. bool SmartClip::ShouldSkipBackgroundImage(Node* node) { - ASSERT(node); + DCHECK(node); // Apparently we're only interested in background images on spans and divs. if (!isHTMLSpanElement(*node) && !isHTMLDivElement(*node)) return true;
diff --git a/third_party/WebKit/Source/core/frame/SuspendableTimer.cpp b/third_party/WebKit/Source/core/frame/SuspendableTimer.cpp index f1ceee2..02ec32cd 100644 --- a/third_party/WebKit/Source/core/frame/SuspendableTimer.cpp +++ b/third_party/WebKit/Source/core/frame/SuspendableTimer.cpp
@@ -57,7 +57,7 @@ void SuspendableTimer::Suspend() { #if DCHECK_IS_ON() - ASSERT(!suspended_); + DCHECK(!suspended_); suspended_ = true; #endif if (IsActive()) { @@ -70,7 +70,7 @@ void SuspendableTimer::Resume() { #if DCHECK_IS_ON() - ASSERT(suspended_); + DCHECK(suspended_); suspended_ = false; #endif if (next_fire_interval_ >= 0.0) {
diff --git a/third_party/WebKit/Source/core/frame/VisualViewport.cpp b/third_party/WebKit/Source/core/frame/VisualViewport.cpp index 32be070..615977da 100644 --- a/third_party/WebKit/Source/core/frame/VisualViewport.cpp +++ b/third_party/WebKit/Source/core/frame/VisualViewport.cpp
@@ -442,7 +442,7 @@ if (!web_scrollbar_layer) { ScrollingCoordinator* coordinator = GetPage().GetScrollingCoordinator(); - ASSERT(coordinator); + DCHECK(coordinator); ScrollbarOrientation webcore_orientation = is_horizontal ? kHorizontalScrollbar : kVerticalScrollbar; web_scrollbar_layer = coordinator->CreateSolidColorScrollbarLayer(
diff --git a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp index f18545d..50570f2 100644 --- a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp +++ b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp
@@ -931,7 +931,7 @@ } const String& CSPDirectiveList::PluginTypesText() const { - ASSERT(HasPluginTypes()); + DCHECK(HasPluginTypes()); return plugin_types_->GetText(); } @@ -958,7 +958,7 @@ String name, value; if (ParseDirective(directive_begin, position, name, value)) { - ASSERT(!name.IsEmpty()); + DCHECK(!name.IsEmpty()); AddDirective(name, value); } @@ -975,8 +975,8 @@ const UChar* end, String& name, String& value) { - ASSERT(name.IsEmpty()); - ASSERT(value.IsEmpty()); + DCHECK(name.IsEmpty()); + DCHECK(value.IsEmpty()); const UChar* position = begin; skipWhile<UChar, IsASCIISpace>(position, end); @@ -1209,7 +1209,7 @@ } void CSPDirectiveList::AddDirective(const String& name, const String& value) { - ASSERT(!name.IsEmpty()); + DCHECK(!name.IsEmpty()); ContentSecurityPolicy::DirectiveType type = ContentSecurityPolicy::GetDirectiveType(name);
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp index 399514c..8d9d4d8b 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp
@@ -243,7 +243,7 @@ } void ContentSecurityPolicy::CopyStateFrom(const ContentSecurityPolicy* other) { - ASSERT(policies_.IsEmpty()); + DCHECK(policies_.IsEmpty()); for (const auto& policy : other->policies_) AddAndReportPolicyFromHeaderValue(policy->Header(), policy->HeaderType(), policy->HeaderSource());
diff --git a/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp b/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp index 39b949f..1a9bfaa8 100644 --- a/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp
@@ -465,7 +465,7 @@ Page* page = GetDocument().GetPage(); if (!page || !page->IsPageVisible() || GetDocument().UnloadStarted()) return; - if (GetDocument().GetFrame()->ShouldUsePrintingLayout()) + if (page->Suspended()) return; String message; if (GetLayoutObject() && willValidate())
diff --git a/third_party/WebKit/Source/core/html/HTMLFormControlElementTest.cpp b/third_party/WebKit/Source/core/html/HTMLFormControlElementTest.cpp index 1db8e6a..a97e562 100644 --- a/third_party/WebKit/Source/core/html/HTMLFormControlElementTest.cpp +++ b/third_party/WebKit/Source/core/html/HTMLFormControlElementTest.cpp
@@ -10,6 +10,7 @@ #include "core/html/HTMLInputElement.h" #include "core/layout/LayoutObject.h" #include "core/loader/EmptyClients.h" +#include "core/page/ScopedPageSuspender.h" #include "core/page/ValidationMessageClient.h" #include "core/testing/DummyPageHolder.h" #include "testing/gtest/include/gtest/gtest.h" @@ -57,7 +58,7 @@ protected: void SetUp() override; - DummyPageHolder& Page() const { return *dummy_page_holder_; } + Page& GetPage() const { return dummy_page_holder_->GetPage(); } Document& GetDocument() const { return *document_; } private: @@ -128,13 +129,12 @@ GetDocument().View()->UpdateAllLifecyclePhases(); ValidationMessageClient* validation_message_client = new MockValidationMessageClient(); - GetDocument().GetPage()->SetValidationMessageClient( - validation_message_client); + GetPage().SetValidationMessageClient(validation_message_client); + Page::OrdinaryPages().insert(&GetPage()); HTMLInputElement* input = toHTMLInputElement(GetDocument().getElementById("input")); - GetDocument().GetFrame()->SetPrinting(true, FloatSize(800, 600), - FloatSize(800, 600), 1); + ScopedPageSuspender suspender; // print() suspends the page. input->reportValidity(); EXPECT_FALSE(validation_message_client->IsValidationMessageVisible(*input)); }
diff --git a/third_party/WebKit/Source/core/html/canvas/CanvasFontCache.cpp b/third_party/WebKit/Source/core/html/canvas/CanvasFontCache.cpp index b10ef08..f855d476 100644 --- a/third_party/WebKit/Source/core/html/canvas/CanvasFontCache.cpp +++ b/third_party/WebKit/Source/core/html/canvas/CanvasFontCache.cpp
@@ -58,7 +58,7 @@ HashMap<String, Font>::iterator i = fonts_resolved_using_default_style_.find(font_string); if (i != fonts_resolved_using_default_style_.end()) { - ASSERT(font_lru_list_.Contains(font_string)); + DCHECK(font_lru_list_.Contains(font_string)); font_lru_list_.erase(font_string); font_lru_list_.insert(font_string); resolved_font = i->value; @@ -83,7 +83,7 @@ MutableStylePropertySet* parsed_style; MutableStylePropertyMap::iterator i = fetched_fonts_.find(font_string); if (i != fetched_fonts_.end()) { - ASSERT(font_lru_list_.Contains(font_string)); + DCHECK(font_lru_list_.Contains(font_string)); parsed_style = i->value; font_lru_list_.erase(font_string); font_lru_list_.insert(font_string); @@ -118,8 +118,8 @@ } void CanvasFontCache::DidProcessTask() { - ASSERT(pruning_scheduled_); - ASSERT(main_cache_purge_preventer_); + DCHECK(pruning_scheduled_); + DCHECK(main_cache_purge_preventer_); while (fetched_fonts_.size() > MaxFonts()) { fetched_fonts_.erase(font_lru_list_.front()); fonts_resolved_using_default_style_.erase(font_lru_list_.front()); @@ -133,7 +133,7 @@ void CanvasFontCache::SchedulePruningIfNeeded() { if (pruning_scheduled_) return; - ASSERT(!main_cache_purge_preventer_); + DCHECK(!main_cache_purge_preventer_); main_cache_purge_preventer_ = WTF::WrapUnique(new FontCachePurgePreventer); Platform::Current()->CurrentThread()->AddTaskObserver(this); pruning_scheduled_ = true;
diff --git a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.cpp b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.cpp index 482ec20..8c6f540 100644 --- a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.cpp +++ b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.cpp
@@ -191,7 +191,7 @@ if (LocalDOMWindow* window = event_target.ToLocalDOMWindow()) return FromInternal(*window); - ASSERT(event_target.GetExecutionContext()->IsWorkerGlobalScope()); + DCHECK(event_target.GetExecutionContext()->IsWorkerGlobalScope()); return ImageBitmapFactories::FromInternal( *ToWorkerGlobalScope(event_target.GetExecutionContext())); } @@ -212,7 +212,7 @@ } void ImageBitmapFactories::DidFinishLoading(ImageBitmapLoader* loader) { - ASSERT(pending_loaders_.Contains(loader)); + DCHECK(pending_loaders_.Contains(loader)); pending_loaders_.erase(loader); } @@ -277,7 +277,7 @@ DOMArrayBuffer* array_buffer, const String& premultiply_alpha_option, const String& color_space_conversion_option) { - ASSERT(!IsMainThread()); + DCHECK(!IsMainThread()); ImageDecoder::AlphaOption alpha_op = ImageDecoder::kAlphaPremultiplied; if (premultiply_alpha_option == "none")
diff --git a/third_party/WebKit/Source/core/input/EventHandler.cpp b/third_party/WebKit/Source/core/input/EventHandler.cpp index 88231b20..cf17e1d 100644 --- a/third_party/WebKit/Source/core/input/EventHandler.cpp +++ b/third_party/WebKit/Source/core/input/EventHandler.cpp
@@ -168,7 +168,7 @@ bool IsCursorChange() const { return is_cursor_change_; } const Cursor& GetCursor() const { - ASSERT(is_cursor_change_); + DCHECK(is_cursor_change_); return cursor_; } @@ -368,8 +368,8 @@ } void EventHandler::CursorUpdateTimerFired(TimerBase*) { - ASSERT(frame_); - ASSERT(frame_->GetDocument()); + DCHECK(frame_); + DCHECK(frame_->GetDocument()); UpdateCursor(); } @@ -792,8 +792,8 @@ HitTestResult* hovered_node, bool only_update_scrollbars, bool force_leave) { - ASSERT(frame_); - ASSERT(frame_->View()); + DCHECK(frame_); + DCHECK(frame_->View()); mouse_event_manager_->SetLastKnownMousePosition(mouse_event); @@ -816,7 +816,7 @@ } // Mouse events simulated from touch should not hit-test again. - ASSERT(!mouse_event.FromTouch()); + DCHECK(!mouse_event.FromTouch()); HitTestRequest::HitTestRequestType hit_type = HitTestRequest::kMove; if (mouse_event_manager_->MousePressed()) { @@ -958,7 +958,7 @@ } // Mouse events simulated from touch should not hit-test again. - ASSERT(!mouse_event.FromTouch()); + DCHECK(!mouse_event.FromTouch()); HitTestRequest::HitTestRequestType hit_type = HitTestRequest::kRelease; HitTestRequest request(hit_type); @@ -1341,7 +1341,7 @@ // Non-scrolling related gesture events do a single cross-frame hit-test and // jump directly to the inner most frame. This matches handleMousePressEvent // etc. - ASSERT(!targeted_event.Event().IsScrollEvent()); + DCHECK(!targeted_event.Event().IsScrollEvent()); // Update mouseout/leave/over/enter events before jumping directly to the // inner most frame. @@ -1403,7 +1403,7 @@ // FIXME: Unify this with the other best* functions which are very similar. TRACE_EVENT0("input", "EventHandler::bestClickableNodeForHitTestResult"); - ASSERT(result.IsRectBasedTest()); + DCHECK(result.IsRectBasedTest()); // If the touch is over a scrollbar, don't adjust the touch point since touch // adjustment only takes into account DOM nodes so a touch over a scrollbar @@ -1433,7 +1433,7 @@ const HitTestResult& result, IntPoint& target_point, Node*& target_node) { - ASSERT(result.IsRectBasedTest()); + DCHECK(result.IsRectBasedTest()); IntPoint touch_center = frame_->View()->ContentsToRootFrame(result.RoundedPointInMainFrame()); IntRect touch_rect = frame_->View()->ContentsToRootFrame( @@ -1640,7 +1640,7 @@ DCHECK_EQ(frame_, &frame_->LocalFrameRoot()); // Scrolling events get hit tested per frame (like wheel events do). - ASSERT(!gesture_event.IsScrollEvent()); + DCHECK(!gesture_event.IsScrollEvent()); HitTestRequest::HitTestRequestType hit_type = gesture_manager_->GetHitTypeForGestureType(gesture_event.GetType()); @@ -1726,7 +1726,7 @@ // If we did a rect-based hit test it must be resolved to the best single node // by now to ensure consumers don't accidentally use one of the other // candidates. - ASSERT(!hit_test_result.IsRectBasedTest()); + DCHECK(!hit_test_result.IsRectBasedTest()); return GestureEventWithHitTestResults(adjusted_event, hit_test_result); } @@ -1936,8 +1936,8 @@ void EventHandler::HoverTimerFired(TimerBase*) { TRACE_EVENT0("input", "EventHandler::hoverTimerFired"); - ASSERT(frame_); - ASSERT(frame_->GetDocument()); + DCHECK(frame_); + DCHECK(frame_->GetDocument()); if (LayoutViewItem layout_item = frame_->ContentLayoutItem()) { if (FrameView* view = frame_->View()) {
diff --git a/third_party/WebKit/Source/core/input/TouchEventManager.cpp b/third_party/WebKit/Source/core/input/TouchEventManager.cpp index e1015508..fa285af 100644 --- a/third_party/WebKit/Source/core/input/TouchEventManager.cpp +++ b/third_party/WebKit/Source/core/input/TouchEventManager.cpp
@@ -354,7 +354,7 @@ // in the active sequence. This must be a single document to // ensure we don't leak Nodes between documents. touch_sequence_document_ = &(touch_info.touch_node->GetDocument()); - ASSERT(touch_sequence_document_->GetFrame()->View()); + DCHECK(touch_sequence_document_->GetFrame()->View()); } // Ideally we'd ASSERT(!m_targetForTouchID.contains(point.id()) @@ -431,7 +431,7 @@ touch_node = touch_sequence_document_; target_frame = touch_sequence_document_->GetFrame(); } - ASSERT(target_frame); + DCHECK(target_frame); // pagePoint should always be in the target element's document coordinates. FloatPoint page_point = @@ -472,7 +472,7 @@ touch_sequence_document_.Clear(); } - ASSERT(frame_->View()); + DCHECK(frame_->View()); if (touch_sequence_document_ && (!touch_sequence_document_->GetFrame() || !touch_sequence_document_->GetFrame()->View())) {
diff --git a/third_party/WebKit/Source/core/inspector/DOMEditor.cpp b/third_party/WebKit/Source/core/inspector/DOMEditor.cpp index cc0a1ae..899fe36 100644 --- a/third_party/WebKit/Source/core/inspector/DOMEditor.cpp +++ b/third_party/WebKit/Source/core/inspector/DOMEditor.cpp
@@ -234,7 +234,7 @@ bool Perform(ExceptionState& exception_state) override { old_html_ = CreateMarkup(node_.Get()); - ASSERT(node_->ownerDocument()); + DCHECK(node_->ownerDocument()); DOMPatchSupport dom_patch_support(dom_editor_.Get(), *node_->ownerDocument()); new_node_ =
diff --git a/third_party/WebKit/Source/core/inspector/DOMPatchSupport.cpp b/third_party/WebKit/Source/core/inspector/DOMPatchSupport.cpp index a5a76bf..2a4f851 100644 --- a/third_party/WebKit/Source/core/inspector/DOMPatchSupport.cpp +++ b/third_party/WebKit/Source/core/inspector/DOMPatchSupport.cpp
@@ -77,7 +77,7 @@ else if (GetDocument().IsXMLDocument()) new_document = XMLDocument::Create(); - ASSERT(new_document); + DCHECK(new_document); new_document->SetContextFeatures(GetDocument().GetContextFeatures()); if (!GetDocument().IsHTMLDocument()) { DocumentParser* parser = XMLDocumentParser::Create(*new_document, nullptr);
diff --git a/third_party/WebKit/Source/core/inspector/DevToolsHost.cpp b/third_party/WebKit/Source/core/inspector/DevToolsHost.cpp index 50cc4f7..56ab672 100644 --- a/third_party/WebKit/Source/core/inspector/DevToolsHost.cpp +++ b/third_party/WebKit/Source/core/inspector/DevToolsHost.cpp
@@ -69,7 +69,7 @@ ~FrontendMenuProvider() override { // Verify that this menu provider has been detached. - ASSERT(!devtools_host_); + DCHECK(!devtools_host_); } DEFINE_INLINE_VIRTUAL_TRACE() { @@ -117,7 +117,7 @@ menu_provider_(nullptr) {} DevToolsHost::~DevToolsHost() { - ASSERT(!client_); + DCHECK(!client_); } DEFINE_TRACE(DevToolsHost) { @@ -209,7 +209,7 @@ float x, float y, const Vector<ContextMenuItem>& items) { - ASSERT(frontend_frame_); + DCHECK(frontend_frame_); FrontendMenuProvider* menu_provider = FrontendMenuProvider::Create(this, items); menu_provider_ = menu_provider;
diff --git a/third_party/WebKit/Source/core/inspector/InspectorAnimationAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorAnimationAgent.cpp index afae337..de6c245 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorAnimationAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorAnimationAgent.cpp
@@ -102,7 +102,7 @@ if (is_transition) { // Obtain keyframes and convert keyframes back to delay - ASSERT(effect->Model()->IsKeyframeEffectModel()); + DCHECK(effect->Model()->IsKeyframeEffectModel()); const KeyframeEffectModelBase* model = ToKeyframeEffectModelBase(effect->Model()); Vector<RefPtr<Keyframe>> keyframes = @@ -281,7 +281,7 @@ if (!id_to_animation_clone_.at(id)) { KeyframeEffectReadOnly* old_effect = ToKeyframeEffectReadOnly(animation->effect()); - ASSERT(old_effect->Model()->IsKeyframeEffectModel()); + DCHECK(old_effect->Model()->IsKeyframeEffectModel()); KeyframeEffectModelBase* old_model = ToKeyframeEffectModelBase(old_effect->Model()); EffectModel* new_model = nullptr; @@ -535,7 +535,7 @@ if (!state_->booleanProperty(AnimationAgentState::animationAgentEnabled, false)) return; - ASSERT(frame->GetDocument()); + DCHECK(frame->GetDocument()); frame->GetDocument()->Timeline().SetPlaybackRate( ReferenceTimeline().PlaybackRate()); }
diff --git a/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp index 581e0a26..8602639 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp
@@ -817,7 +817,7 @@ for (CSSStyleSheet* css_style_sheet : removed_sheets) { InspectorStyleSheet* inspector_style_sheet = css_style_sheet_to_inspector_style_sheet_.at(css_style_sheet); - ASSERT(inspector_style_sheet); + DCHECK(inspector_style_sheet); document_css_style_sheets->erase(css_style_sheet); if (id_to_inspector_style_sheet_.Contains(inspector_style_sheet->Id())) { @@ -1423,7 +1423,7 @@ Member<StyleSheetAction> revert = actions.at(j); DummyExceptionStateForTesting undo_exception_state; revert->Undo(undo_exception_state); - ASSERT(!undo_exception_state.HadException()); + DCHECK(!undo_exception_state.HadException()); } return Response::Error( String::Format("Failed applying edit #%d: ", i) +
diff --git a/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp index 4a86b26..cf9f2c9 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp
@@ -369,7 +369,7 @@ Node* candidate = node; while (candidate && !candidate->IsShadowRoot()) candidate = candidate->ParentOrShadowHostNode(); - ASSERT(candidate); + DCHECK(candidate); ShadowRoot* shadow_root = ToShadowRoot(candidate); return shadow_root->GetType() == ShadowRootType::kUserAgent ? shadow_root @@ -512,7 +512,7 @@ for (node = InnerFirstChild(node); node; node = InnerNextSibling(node)) { int child_node_id = node_map->at(node); - ASSERT(child_node_id); + DCHECK(child_node_id); PushChildNodesToFrontend(child_node_id, depth, pierce); } @@ -641,7 +641,7 @@ int InspectorDOMAgent::PushNodePathToFrontend(Node* node_to_push, NodeToIdMap* node_map) { - ASSERT(node_to_push); // Invalid input + DCHECK(node_to_push); // Invalid input // InspectorDOMAgent might have been resetted already. See crbug.com/450491 if (!document_) return 0; @@ -668,7 +668,7 @@ for (int i = path.size() - 1; i >= 0; --i) { int node_id = node_map->at(path.at(i).Get()); - ASSERT(node_id); + DCHECK(node_id); PushChildNodesToFrontend(node_id); } return node_map->at(node_to_push); @@ -849,7 +849,7 @@ Response InspectorDOMAgent::setOuterHTML(int node_id, const String& outer_html) { if (!node_id) { - ASSERT(document_); + DCHECK(document_); DOMPatchSupport dom_patch_support(dom_editor_.Get(), *document_.Get()); dom_patch_support.PatchDocument(outer_html); return Response::OK(); @@ -1034,7 +1034,7 @@ // XPath evaluation for (Document* document : docs) { - ASSERT(document); + DCHECK(document); DummyExceptionStateForTesting exception_state; XPathResult* result = DocumentXPathEvaluator::evaluate( *document, whitespace_trimmed_query, document, nullptr, @@ -2004,9 +2004,9 @@ // If a PseudoElement is bound, its parent element must be bound, too. Element* parent = pseudo_element->ParentOrShadowHostElement(); - ASSERT(parent); + DCHECK(parent); int parent_id = document_node_to_id_map_->at(parent); - ASSERT(parent_id); + DCHECK(parent_id); Unbind(pseudo_element, document_node_to_id_map_.Get()); GetFrontend()->pseudoElementRemoved(parent_id, pseudo_element_id);
diff --git a/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp index 26709a03..8c08761 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
@@ -556,7 +556,7 @@ // Find breakpoint owner node. if (!insertion) breakpoint_owner = InspectorDOMAgent::InnerParentNode(target); - ASSERT(breakpoint_owner); + DCHECK(breakpoint_owner); while (!(dom_breakpoints_.at(breakpoint_owner) & (1 << breakpoint_type))) { Node* parent_node = InspectorDOMAgent::InnerParentNode(breakpoint_owner); if (!parent_node) @@ -569,7 +569,7 @@ } int breakpoint_owner_node_id = dom_agent_->BoundNodeId(breakpoint_owner); - ASSERT(breakpoint_owner_node_id); + DCHECK(breakpoint_owner_node_id); description->setInteger("nodeId", breakpoint_owner_node_id); description->setString("type", DomTypeName(breakpoint_type)); String json = description->serialize();
diff --git a/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp index a6b6606b..6b79c135 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp
@@ -355,7 +355,7 @@ reasons_bitmask &= ~kCompositingReasonStringMap[i].reason; #endif } - ASSERT(!reasons_bitmask); + DCHECK(!reasons_bitmask); return Response::OK(); }
diff --git a/third_party/WebKit/Source/core/inspector/InspectorResourceContentLoader.cpp b/third_party/WebKit/Source/core/inspector/InspectorResourceContentLoader.cpp index 4eed7c1b..ba11004 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorResourceContentLoader.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorResourceContentLoader.cpp
@@ -185,7 +185,7 @@ } InspectorResourceContentLoader::~InspectorResourceContentLoader() { - ASSERT(resources_.IsEmpty()); + DCHECK(resources_.IsEmpty()); } DEFINE_TRACE(InspectorResourceContentLoader) {
diff --git a/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp b/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp index 0d713d8..7731f8d 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp
@@ -152,7 +152,7 @@ Document* document, CSSRuleSourceDataList* result) : parsed_text_(parsed_text), document_(document), result_(result) { - ASSERT(result_); + DCHECK(result_); } DECLARE_TRACE(); @@ -247,7 +247,7 @@ } CSSRuleSourceData* StyleSheetHandler::PopRuleData() { - ASSERT(!current_rule_data_stack_.IsEmpty()); + DCHECK(!current_rule_data_stack_.IsEmpty()); current_rule_data_ = nullptr; CSSRuleSourceData* data = current_rule_data_stack_.back().Get(); current_rule_data_stack_.pop_back(); @@ -300,7 +300,7 @@ String comment_text = parsed_text_.Substring(start_offset, end_offset - start_offset); - ASSERT(comment_text.StartsWith("/*")); + DCHECK(comment_text.StartsWith("/*")); comment_text = comment_text.Substring(2); // Require well-formed comments. @@ -723,7 +723,7 @@ : style_(style), source_data_(source_data), parent_style_sheet_(parent_style_sheet) { - ASSERT(style_); + DCHECK(style_); } InspectorStyle::~InspectorStyle() {} @@ -1159,7 +1159,7 @@ CSSRuleSourceData* InspectorStyleSheet::RuleSourceDataAfterSourceRange( const SourceRange& source_range) { - ASSERT(source_data_); + DCHECK(source_data_); unsigned index = 0; for (; index < source_data_->size(); ++index) { CSSRuleSourceData* sd = source_data_->at(index).Get(); @@ -1222,7 +1222,7 @@ const SourceRange& source_range, const String& rule_text, ExceptionState& exception_state) { - ASSERT(source_data_); + DCHECK(source_data_); CSSRuleSourceData* containing_rule_source_data = nullptr; for (size_t i = 0; i < source_data_->size(); ++i) { @@ -1876,7 +1876,7 @@ Element* element, Listener* listener) : InspectorStyleSheetBase(listener), element_(element) { - ASSERT(element_); + DCHECK(element_); } void InspectorStyleSheetForInlineStyle::DidModifyElementAttribute() {
diff --git a/third_party/WebKit/Source/core/inspector/InspectorTraceEvents.cpp b/third_party/WebKit/Source/core/inspector/InspectorTraceEvents.cpp index bca637c9..5577eec 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorTraceEvents.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorTraceEvents.cpp
@@ -501,7 +501,7 @@ InspectorStyleRecalcInvalidationTrackingEvent::Data( Node* node, const StyleChangeReasonForTracing& reason) { - ASSERT(node); + DCHECK(node); std::unique_ptr<TracedValue> value = TracedValue::Create(); value->SetString("frame", ToHexString(node->GetDocument().GetFrame())); @@ -611,7 +611,7 @@ std::unique_ptr<TracedValue> InspectorLayoutInvalidationTrackingEvent::Data( const LayoutObject* layout_object, LayoutInvalidationReasonForTracing reason) { - ASSERT(layout_object); + DCHECK(layout_object); std::unique_ptr<TracedValue> value = TracedValue::Create(); value->SetString("frame", ToHexString(layout_object->GetFrame())); SetGeneratingNodeInfo(value.get(), layout_object, "nodeId", "nodeName"); @@ -623,7 +623,7 @@ std::unique_ptr<TracedValue> InspectorPaintInvalidationTrackingEvent::Data( const LayoutObject* layout_object, const LayoutObject& paint_container) { - ASSERT(layout_object); + DCHECK(layout_object); std::unique_ptr<TracedValue> value = TracedValue::Create(); value->SetString("frame", ToHexString(layout_object->GetFrame())); SetGeneratingNodeInfo(value.get(), &paint_container, "paintId");
diff --git a/third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp b/third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp index fc99ff6..8a7330e 100644 --- a/third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp +++ b/third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp
@@ -100,7 +100,7 @@ task_runner_(WTF::MakeUnique<InspectorTaskRunner>()), paused_(false) { MutexLocker locker(CreationMutex()); - ASSERT(!instance_); + DCHECK(!instance_); instance_ = this; } @@ -126,8 +126,8 @@ void MainThreadDebugger::SetClientMessageLoop( std::unique_ptr<ClientMessageLoop> client_message_loop) { - ASSERT(!client_message_loop_); - ASSERT(client_message_loop); + DCHECK(!client_message_loop_); + DCHECK(client_message_loop); client_message_loop_ = std::move(client_message_loop); } @@ -140,7 +140,7 @@ void MainThreadDebugger::ContextCreated(ScriptState* script_state, LocalFrame* frame, SecurityOrigin* origin) { - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); v8::HandleScope handles(script_state->GetIsolate()); DOMWrapperWorld& world = script_state->World(); StringBuilder aux_data_builder; @@ -337,7 +337,7 @@ v8::Local<v8::Context> context) { ExecutionContext* execution_context = ToExecutionContext(context); DCHECK(execution_context); - ASSERT(execution_context->IsDocument()); + DCHECK(execution_context->IsDocument()); return ToV8(MemoryInfo::Create(), context->Global(), isolate); }
diff --git a/third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp b/third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp index bddc64f..4a49c42 100644 --- a/third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp +++ b/third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp
@@ -100,8 +100,8 @@ void NetworkResourcesData::ResourceData::SetContent(const String& content, bool base64_encoded) { - ASSERT(!HasData()); - ASSERT(!HasContent()); + DCHECK(!HasData()); + DCHECK(!HasContent()); content_ = content; base64_encoded_ = base64_encoded; } @@ -109,13 +109,13 @@ size_t NetworkResourcesData::ResourceData::RemoveContent() { size_t result = 0; if (HasData()) { - ASSERT(!HasContent()); + DCHECK(!HasContent()); result = data_buffer_->size(); data_buffer_ = nullptr; } if (HasContent()) { - ASSERT(!HasData()); + DCHECK(!HasData()); result = content_.CharactersSizeInBytes(); content_ = String(); } @@ -163,7 +163,7 @@ void NetworkResourcesData::ResourceData::AppendData(const char* data, size_t data_length) { - ASSERT(!HasContent()); + DCHECK(!HasContent()); if (!data_buffer_) data_buffer_ = SharedBuffer::Create(data, data_length); else
diff --git a/third_party/WebKit/Source/core/layout/BUILD.gn b/third_party/WebKit/Source/core/layout/BUILD.gn index 47bbcdbd..fb26056 100644 --- a/third_party/WebKit/Source/core/layout/BUILD.gn +++ b/third_party/WebKit/Source/core/layout/BUILD.gn
@@ -422,6 +422,7 @@ "ng/ng_physical_box_fragment.h", "ng/ng_physical_fragment.cc", "ng/ng_physical_fragment.h", + "ng/ng_positioned_float.h", "ng/ng_relative_utils.cc", "ng/ng_relative_utils.h", "ng/ng_space_utils.cc",
diff --git a/third_party/WebKit/Source/core/layout/LayoutBox.cpp b/third_party/WebKit/Source/core/layout/LayoutBox.cpp index f62823d..7d03f24c 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBox.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBox.cpp
@@ -5040,10 +5040,10 @@ // Only propagate layout overflow from the child if the child isn't clipping // its overflow. If it is, then its overflow is internal to it, and we don't - // care about it. layoutOverflowRectForPropagation takes care of this and just + // care about it. LayoutOverflowRectForPropagation takes care of this and just // propagates the border box rect instead. LayoutRect child_layout_overflow_rect = - child.LayoutOverflowRectForPropagation(StyleRef()); + child.LayoutOverflowRectForPropagation(); child_layout_overflow_rect.Move(delta); AddLayoutOverflow(child_layout_overflow_rect); @@ -5054,7 +5054,7 @@ if (child.HasSelfPaintingLayer()) return; LayoutRect child_visual_overflow_rect = - child.VisualOverflowRectForPropagation(StyleRef()); + child.VisualOverflowRectForPropagation(); child_visual_overflow_rect.Move(delta); AddContentsVisualOverflow(child_visual_overflow_rect); } @@ -5252,45 +5252,38 @@ return nullptr; } -LayoutRect LayoutBox::LogicalVisualOverflowRectForPropagation( - const ComputedStyle& parent_style) const { - LayoutRect rect = VisualOverflowRectForPropagation(parent_style); - if (!parent_style.IsHorizontalWritingMode()) +LayoutRect LayoutBox::LogicalVisualOverflowRectForPropagation() const { + LayoutRect rect = VisualOverflowRectForPropagation(); + if (!Parent()->StyleRef().IsHorizontalWritingMode()) return rect.TransposedRect(); return rect; } DISABLE_CFI_PERF -LayoutRect LayoutBox::VisualOverflowRectForPropagation( - const ComputedStyle& parent_style) const { - // If the writing modes of the child and parent match, then we don't have to - // do anything fancy. Just return the result. - LayoutRect rect = VisualOverflowRect(); - if (parent_style.GetWritingMode() == Style()->GetWritingMode()) +LayoutRect LayoutBox::RectForOverflowPropagation(const LayoutRect& rect) const { + // If the child and parent are in the same blocks direction, then we don't + // have to do anything fancy. Just return the rect. + if (Parent()->StyleRef().IsFlippedBlocksWritingMode() == + StyleRef().IsFlippedBlocksWritingMode()) return rect; - // We are putting ourselves into our parent's coordinate space. If there is a - // flipped block mismatch in a particular axis, then we have to flip the rect - // along that axis. - if (IsFlippedBlocksWritingMode(Style()->GetWritingMode()) || - IsFlippedBlocksWritingMode(parent_style.GetWritingMode())) - rect.SetX(Size().Width() - rect.MaxX()); - - return rect; + // Convert the rect into parent's blocks direction by flipping along the y + // axis. + LayoutRect result = rect; + result.SetX(Size().Width() - rect.MaxX()); + return result; } DISABLE_CFI_PERF -LayoutRect LayoutBox::LogicalLayoutOverflowRectForPropagation( - const ComputedStyle& parent_style) const { - LayoutRect rect = LayoutOverflowRectForPropagation(parent_style); - if (!parent_style.IsHorizontalWritingMode()) +LayoutRect LayoutBox::LogicalLayoutOverflowRectForPropagation() const { + LayoutRect rect = LayoutOverflowRectForPropagation(); + if (!Parent()->StyleRef().IsHorizontalWritingMode()) return rect.TransposedRect(); return rect; } DISABLE_CFI_PERF -LayoutRect LayoutBox::LayoutOverflowRectForPropagation( - const ComputedStyle& parent_style) const { +LayoutRect LayoutBox::LayoutOverflowRectForPropagation() const { // Only propagate interior layout overflow if we don't clip it. LayoutRect rect = BorderBoxRect(); // We want to include the margin, but only when it adds height. Quirky margins @@ -5320,19 +5313,7 @@ FlipForWritingMode(rect); } - // If the writing modes of the child and parent match, then we don't have to - // do anything fancy. Just return the result. - if (parent_style.GetWritingMode() == Style()->GetWritingMode()) - return rect; - - // We are putting ourselves into our parent's coordinate space. If there is a - // flipped block mismatch in a particular axis, then we have to flip the rect - // along that axis. - if (IsFlippedBlocksWritingMode(Style()->GetWritingMode()) || - IsFlippedBlocksWritingMode(parent_style.GetWritingMode())) - rect.SetX(Size().Width() - rect.MaxX()); - - return rect; + return RectForOverflowPropagation(rect); } DISABLE_CFI_PERF
diff --git a/third_party/WebKit/Source/core/layout/LayoutBox.h b/third_party/WebKit/Source/core/layout/LayoutBox.h index c18283a3..2a39ef4 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBox.h +++ b/third_party/WebKit/Source/core/layout/LayoutBox.h
@@ -1217,12 +1217,16 @@ return ToLayoutSize(PhysicalLocation()); } - LayoutRect LogicalVisualOverflowRectForPropagation( - const ComputedStyle&) const; - LayoutRect VisualOverflowRectForPropagation(const ComputedStyle&) const; - LayoutRect LogicalLayoutOverflowRectForPropagation( - const ComputedStyle&) const; - LayoutRect LayoutOverflowRectForPropagation(const ComputedStyle&) const; + // Convert a local rect in this box's blocks direction into parent's blocks + // direction, for parent to accumulate layout or visual overflow. + LayoutRect RectForOverflowPropagation(const LayoutRect&) const; + + LayoutRect LogicalVisualOverflowRectForPropagation() const; + LayoutRect VisualOverflowRectForPropagation() const { + return RectForOverflowPropagation(VisualOverflowRect()); + } + LayoutRect LogicalLayoutOverflowRectForPropagation() const; + LayoutRect LayoutOverflowRectForPropagation() const; bool HasOverflowModel() const { return overflow_.get(); } bool HasSelfVisualOverflow() const {
diff --git a/third_party/WebKit/Source/core/layout/LayoutBoxTest.cpp b/third_party/WebKit/Source/core/layout/LayoutBoxTest.cpp index 0b6c93be..2ba6802 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBoxTest.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBoxTest.cpp
@@ -263,4 +263,54 @@ EXPECT_EQ(LayoutRect(0, 0, 100, 100), target->LocalVisualRect()); } +TEST_F(LayoutBoxTest, ContentsVisualOverflowPropagation) { + SetBodyInnerHTML( + "<style>" + " div { width: 100px; height: 100px }" + "</style>" + "<div id='a'>" + " <div style='height: 50px'></div>" + " <div id='b' style='writing-mode: vertical-rl; margin-left: 60px'>" + " <div style='width: 30px'></div>" + " <div id='c' style='margin-top: 40px'>" + " <div style='width: 10px'></div>" + " <div style='margin-top: 20px; margin-left: 10px'></div>" + " </div>" + " <div id='d' style='writing-mode: vertical-lr; margin-top: 40px'>" + " <div style='width: 10px'></div>" + " <div style='margin-top: 20px'></div>" + " </div>" + " </div>" + "</div>"); + + auto* c = ToLayoutBox(GetLayoutObjectByElementId("c")); + EXPECT_EQ(LayoutRect(0, 0, 100, 100), c->SelfVisualOverflowRect()); + EXPECT_EQ(LayoutRect(10, 20, 100, 100), c->ContentsVisualOverflowRect()); + EXPECT_EQ(LayoutRect(0, 0, 110, 120), c->VisualOverflowRect()); + // C and its parent b have the same blocks direction. + EXPECT_EQ(LayoutRect(0, 0, 110, 120), c->VisualOverflowRectForPropagation()); + + auto* d = ToLayoutBox(GetLayoutObjectByElementId("d")); + EXPECT_EQ(LayoutRect(0, 0, 100, 100), d->SelfVisualOverflowRect()); + EXPECT_EQ(LayoutRect(10, 20, 100, 100), d->ContentsVisualOverflowRect()); + EXPECT_EQ(LayoutRect(0, 0, 110, 120), d->VisualOverflowRect()); + // D and its parent b have different blocks direction. + EXPECT_EQ(LayoutRect(-10, 0, 110, 120), + d->VisualOverflowRectForPropagation()); + + auto* b = ToLayoutBox(GetLayoutObjectByElementId("b")); + EXPECT_EQ(LayoutRect(0, 0, 100, 100), b->SelfVisualOverflowRect()); + // Union of VisualOverflowRectForPropagations offset by locations of c and d. + EXPECT_EQ(LayoutRect(30, 40, 200, 120), b->ContentsVisualOverflowRect()); + EXPECT_EQ(LayoutRect(0, 0, 230, 160), b->VisualOverflowRect()); + // B and its parent A have different blocks direction. + EXPECT_EQ(LayoutRect(-130, 0, 230, 160), + b->VisualOverflowRectForPropagation()); + + auto* a = ToLayoutBox(GetLayoutObjectByElementId("a")); + EXPECT_EQ(LayoutRect(0, 0, 100, 100), a->SelfVisualOverflowRect()); + EXPECT_EQ(LayoutRect(-70, 50, 230, 160), a->ContentsVisualOverflowRect()); + EXPECT_EQ(LayoutRect(-70, 0, 230, 210), a->VisualOverflowRect()); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/layout/LayoutInline.cpp b/third_party/WebKit/Source/core/layout/LayoutInline.cpp index 0c19c50e2..5ef0366 100644 --- a/third_party/WebKit/Source/core/layout/LayoutInline.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutInline.cpp
@@ -1079,7 +1079,7 @@ LayoutBox* curr_box = ToLayoutBox(curr); if (!curr_box->HasSelfPaintingLayer() && curr_box->InlineBoxWrapper()) { LayoutRect logical_rect = - curr_box->LogicalVisualOverflowRectForPropagation(StyleRef()); + curr_box->LogicalVisualOverflowRectForPropagation(); if (is_horizontal) { logical_rect.MoveBy(curr_box->Location()); result.UniteIfNonZero(logical_rect);
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableRow.cpp b/third_party/WebKit/Source/core/layout/LayoutTableRow.cpp index 54b6566a..440f7a2 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTableRow.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTableRow.cpp
@@ -313,12 +313,12 @@ LayoutSize cell_row_offset = cell->Location() - Location(); LayoutRect cell_visual_overflow_rect = - cell->VisualOverflowRectForPropagation(StyleRef()); + cell->VisualOverflowRectForPropagation(); cell_visual_overflow_rect.Move(cell_row_offset); AddContentsVisualOverflow(cell_visual_overflow_rect); LayoutRect cell_layout_overflow_rect = - cell->LayoutOverflowRectForPropagation(StyleRef()); + cell->LayoutOverflowRectForPropagation(); cell_layout_overflow_rect.Move(cell_row_offset); AddLayoutOverflow(cell_layout_overflow_rect); }
diff --git a/third_party/WebKit/Source/core/layout/api/LineLayoutBox.h b/third_party/WebKit/Source/core/layout/api/LineLayoutBox.h index bf6b5ba0..2d49673 100644 --- a/third_party/WebKit/Source/core/layout/api/LineLayoutBox.h +++ b/third_party/WebKit/Source/core/layout/api/LineLayoutBox.h
@@ -75,13 +75,11 @@ } bool HasOverflowModel() const { return ToBox()->HasOverflowModel(); } - LayoutRect LogicalVisualOverflowRectForPropagation( - const ComputedStyle& style) const { - return ToBox()->LogicalVisualOverflowRectForPropagation(style); + LayoutRect LogicalVisualOverflowRectForPropagation() const { + return ToBox()->LogicalVisualOverflowRectForPropagation(); } - LayoutRect LogicalLayoutOverflowRectForPropagation( - const ComputedStyle& style) const { - return ToBox()->LogicalLayoutOverflowRectForPropagation(style); + LayoutRect LogicalLayoutOverflowRectForPropagation() const { + return ToBox()->LogicalLayoutOverflowRectForPropagation(); } void SetLocation(const LayoutPoint& location) {
diff --git a/third_party/WebKit/Source/core/layout/line/InlineFlowBox.cpp b/third_party/WebKit/Source/core/layout/line/InlineFlowBox.cpp index 8522e46..b296976 100644 --- a/third_party/WebKit/Source/core/layout/line/InlineFlowBox.cpp +++ b/third_party/WebKit/Source/core/layout/line/InlineFlowBox.cpp
@@ -1138,8 +1138,7 @@ // be adjusted for writing-mode differences. if (!box.HasSelfPaintingLayer()) { LayoutRect child_logical_visual_overflow = - box.LogicalVisualOverflowRectForPropagation( - GetLineLayoutItem().StyleRef()); + box.LogicalVisualOverflowRectForPropagation(); child_logical_visual_overflow.Move(inline_box->LogicalLeft(), inline_box->LogicalTop()); logical_visual_overflow.Unite(child_logical_visual_overflow); @@ -1150,8 +1149,7 @@ // as layout overflow. This rectangle must include transforms and relative // positioning and be adjusted for writing-mode differences. LayoutRect child_logical_layout_overflow = - box.LogicalLayoutOverflowRectForPropagation( - GetLineLayoutItem().StyleRef()); + box.LogicalLayoutOverflowRectForPropagation(); child_logical_layout_overflow.Move(inline_box->LogicalLeft(), inline_box->LogicalTop()); logical_layout_overflow.Unite(child_logical_layout_overflow);
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.cc index 9f18afb..2f108e1c 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.cc
@@ -394,9 +394,8 @@ float_does_not_fit) { container_builder_.AddUnpositionedFloat(floating_object); } else { - floating_object->logical_offset = - PositionFloat(floating_object.Get(), MutableConstraintSpace()); - container_builder_.MutablePositionedFloats().push_back(floating_object); + container_builder_.MutablePositionedFloats().push_back( + PositionFloat(floating_object.Get(), MutableConstraintSpace())); FindNextLayoutOpportunity(); } }
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_block_layout_algorithm.cc b/third_party/WebKit/Source/core/layout/ng/ng_block_layout_algorithm.cc index 01fe88e8..f9d504e 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_block_layout_algorithm.cc +++ b/third_party/WebKit/Source/core/layout/ng/ng_block_layout_algorithm.cc
@@ -93,10 +93,9 @@ DCHECK(container_builder->BfcOffset()) << "Parent BFC offset should be known here"; const auto& floating_objects = container_builder->UnpositionedFloats(); - PositionFloats(origin_block_offset, - container_builder->BfcOffset().value().block_offset, - floating_objects, space); - container_builder->MutablePositionedFloats().AppendVector(floating_objects); + container_builder->MutablePositionedFloats().AppendVector(PositionFloats( + origin_block_offset, container_builder->BfcOffset().value().block_offset, + floating_objects, space)); container_builder->MutableUnpositionedFloats().clear(); }
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_block_layout_algorithm_test.cc b/third_party/WebKit/Source/core/layout/ng/ng_block_layout_algorithm_test.cc index 9344257..35d627b 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_block_layout_algorithm_test.cc +++ b/third_party/WebKit/Source/core/layout/ng/ng_block_layout_algorithm_test.cc
@@ -352,7 +352,7 @@ ASSERT_EQ(1UL, body_fragment->PositionedFloats().size()); ASSERT_EQ(1UL, body_fragment->PositionedFloats().size()); auto float_nonempties_fragment = - body_fragment->PositionedFloats().at(0)->fragment; + body_fragment->PositionedFloats().at(0).fragment; // 70 = first_child's height(50) + first child's margin-bottom(20) EXPECT_THAT(float_nonempties_fragment->TopOffset(), LayoutUnit(70)); EXPECT_THAT(float_nonempties_fragment->LeftOffset(), LayoutUnit(0)); @@ -874,14 +874,14 @@ ASSERT_EQ(2UL, container_fragment->PositionedFloats().size()); RefPtr<NGPhysicalFragment> left_float_fragment = - container_fragment->PositionedFloats().at(0)->fragment; + container_fragment->PositionedFloats().at(0).fragment; // inline 25 = empty2's padding(15) + left float's margin(10) // block 10 = left float's margin EXPECT_THAT(left_float_fragment->Offset(), NGPhysicalOffset(LayoutUnit(25), LayoutUnit(10))); auto right_float_fragment = - container_fragment->PositionedFloats().at(1)->fragment; + container_fragment->PositionedFloats().at(1).fragment; LayoutUnit right_float_offset = LayoutUnit(125); // inline offset 150 = empty2's padding(15) + right float's margin(10) + right // float offset(125) @@ -997,7 +997,7 @@ int left_float_block_offset = 8; EXPECT_EQ(left_float_block_offset, left_float->OffsetTop()); auto left_float_fragment = - regular_fragment->PositionedFloats().at(0)->fragment; + regular_fragment->PositionedFloats().at(0).fragment; EXPECT_THAT(LayoutUnit(), left_float_fragment->TopOffset()); Element* left_wide_float = GetDocument().getElementById("left-wide-float"); @@ -1007,7 +1007,7 @@ int left_wide_float_block_offset = 38; EXPECT_EQ(left_wide_float_block_offset, left_wide_float->OffsetTop()); auto left_wide_float_fragment = - regular_fragment->PositionedFloats().at(1)->fragment; + regular_fragment->PositionedFloats().at(1).fragment; // 30 = left-float's height. EXPECT_THAT(LayoutUnit(30), left_wide_float_fragment->TopOffset()); @@ -1028,7 +1028,7 @@ EXPECT_EQ(right_float_inline_offset, right_float->OffsetLeft()); EXPECT_EQ(right_float_block_offset, right_float->OffsetTop()); auto right_float_fragment = - container_fragment->PositionedFloats().at(0)->fragment; + container_fragment->PositionedFloats().at(0).fragment; // 60 = right_float_block_offset(68) - body's margin(8) EXPECT_THAT(LayoutUnit(right_float_block_offset - 8), right_float_fragment->TopOffset()); @@ -1048,7 +1048,7 @@ EXPECT_EQ(left_float_with_margin_block_offset, left_float_with_margin->OffsetTop()); auto left_float_with_margin_fragment = - container_fragment->PositionedFloats().at(1)->fragment; + container_fragment->PositionedFloats().at(1).fragment; // 70 = left_float_with_margin_block_offset(78) - body's margin(8) EXPECT_THAT(LayoutUnit(left_float_with_margin_block_offset - 8), left_float_with_margin_fragment->TopOffset());
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_block_node.cc b/third_party/WebKit/Source/core/layout/ng/ng_block_node.cc index 292c002..0dc927d 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_block_node.cc +++ b/third_party/WebKit/Source/core/layout/ng/ng_block_node.cc
@@ -65,10 +65,10 @@ // Similar to FragmentPositionUpdated but for floats. // - Updates layout object's geometric information. // - Creates legacy FloatingObject and attached it to the provided parent. -void FloatingObjectPositionedUpdated(NGFloatingObject* ng_floating_object, +void FloatingObjectPositionedUpdated(const NGPositionedFloat& positioned_float, LayoutBox* parent) { NGPhysicalBoxFragment* box_fragment = - ToNGPhysicalBoxFragment(ng_floating_object->fragment.Get()); + ToNGPhysicalBoxFragment(positioned_float.fragment.Get()); FragmentPositionUpdated(*box_fragment); LayoutBox* layout_box = ToLayoutBox(box_fragment->GetLayoutObject()); @@ -78,7 +78,7 @@ FloatingObject* floating_object = ToLayoutBlockFlow(parent)->InsertFloatingObject(*layout_box); floating_object->SetIsInPlacedTree(false); - floating_object->SetX(ng_floating_object->left_offset); + floating_object->SetX(positioned_float.left_offset); floating_object->SetY(box_fragment->TopOffset()); floating_object->SetIsPlaced(true); floating_object->SetIsInPlacedTree(true); @@ -281,9 +281,9 @@ // We may still have unpositioned floats when we reach the root box. if (!layout_box_->Parent()) { - for (const RefPtr<NGFloatingObject>& floating_object : + for (const NGPositionedFloat& positioned_float : fragment->PositionedFloats()) { - FloatingObjectPositionedUpdated(floating_object.Get(), layout_box_); + FloatingObjectPositionedUpdated(positioned_float, layout_box_); } } @@ -291,11 +291,10 @@ if (child_fragment->IsPlaced()) FragmentPositionUpdated(ToNGPhysicalBoxFragment(*child_fragment)); - for (const RefPtr<NGFloatingObject>& floating_object : + for (const NGPositionedFloat& positioned_float : ToNGPhysicalBoxFragment(child_fragment.Get())->PositionedFloats()) { FloatingObjectPositionedUpdated( - floating_object.Get(), - ToLayoutBox(child_fragment->GetLayoutObject())); + positioned_float, ToLayoutBox(child_fragment->GetLayoutObject())); } }
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_floating_object.h b/third_party/WebKit/Source/core/layout/ng/ng_floating_object.h index bf8e009..c7b5a503 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_floating_object.h +++ b/third_party/WebKit/Source/core/layout/ng/ng_floating_object.h
@@ -50,31 +50,17 @@ NGLogicalOffset origin_offset; NGLogicalOffset from_offset; - // Calculated logical offset. It's never {@code nullopt} for a positioned - // float. - WTF::Optional<NGLogicalOffset> logical_offset; - // Writing mode of the float's constraint space. NGWritingMode writing_mode; RefPtr<NGPhysicalFragment> fragment; - // In the case where a legacy FloatingObject is attached to not its own - // parent, e.g. a float surrounded by a bunch of nested empty divs, - // NG float fragment's LeftOffset() cannot be used as legacy FloatingObject's - // left offset because that offset should be relative to the original float - // parent. - // {@code left_offset} is calculated when we know to which parent this float - // would be attached. - LayoutUnit left_offset; - bool IsLeft() const { return exclusion_type == NGExclusion::kFloatLeft; } bool IsRight() const { return exclusion_type == NGExclusion::kFloatRight; } String ToString() const { - return String::Format("Type: '%d' Fragment: '%s'", exclusion_type, - fragment->ToString().Ascii().data()); + return String::Format("Type: '%d'", exclusion_type); } private:
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_floats_utils.cc b/third_party/WebKit/Source/core/layout/ng/ng_floats_utils.cc index 762b170a..47ab32ec 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_floats_utils.cc +++ b/third_party/WebKit/Source/core/layout/ng/ng_floats_utils.cc
@@ -78,21 +78,20 @@ return exclusion; } -// Updates the Floating Object's left offset from the provided parent_space +// Calculates the Floating Object's left offset from the provided parent_space // and {@code floating_object}'s space and margins. -void UpdateFloatingObjectLeftOffset(const NGConstraintSpace& new_parent_space, - const NGLogicalOffset& float_logical_offset, - NGFloatingObject* floating_object) { - DCHECK(floating_object); +LayoutUnit CalculateLeftOffset(const NGConstraintSpace& new_parent_space, + const NGLogicalOffset& float_logical_offset, + const NGFloatingObject& floating_object) { // TODO(glebl): We should use physical offset here. - floating_object->left_offset = floating_object->from_offset.inline_offset - - new_parent_space.BfcOffset().inline_offset + - float_logical_offset.inline_offset; + return floating_object.from_offset.inline_offset - + new_parent_space.BfcOffset().inline_offset + + float_logical_offset.inline_offset; } } // namespace -NGLogicalOffset PositionFloat(NGFloatingObject* floating_object, - NGConstraintSpace* new_parent_space) { +NGPositionedFloat PositionFloat(NGFloatingObject* floating_object, + NGConstraintSpace* new_parent_space) { DCHECK(floating_object); DCHECK(floating_object->fragment) << "Fragment cannot be null here"; @@ -132,21 +131,29 @@ NGLogicalOffset logical_offset = CalculateLogicalOffsetForOpportunity( opportunity, float_offset, floating_object); - UpdateFloatingObjectLeftOffset(*new_parent_space, logical_offset, - floating_object); - return logical_offset; + + LayoutUnit left_offset = + CalculateLeftOffset(*new_parent_space, logical_offset, *floating_object); + + return NGPositionedFloat(floating_object->fragment, logical_offset, + left_offset); } -void PositionFloats(LayoutUnit origin_block_offset, - LayoutUnit from_block_offset, - const Vector<RefPtr<NGFloatingObject>>& floating_objects, - NGConstraintSpace* space) { +const Vector<NGPositionedFloat> PositionFloats( + LayoutUnit origin_block_offset, + LayoutUnit from_block_offset, + const Vector<RefPtr<NGFloatingObject>>& floating_objects, + NGConstraintSpace* space) { + Vector<NGPositionedFloat> positioned_floats; + positioned_floats.ReserveCapacity(floating_objects.size()); + for (auto& floating_object : floating_objects) { floating_object->origin_offset.block_offset = origin_block_offset; floating_object->from_offset.block_offset = from_block_offset; - floating_object->logical_offset = - PositionFloat(floating_object.Get(), space); + positioned_floats.push_back(PositionFloat(floating_object.Get(), space)); } + + return positioned_floats; } } // namespace blink
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_floats_utils.h b/third_party/WebKit/Source/core/layout/ng/ng_floats_utils.h index 449b6c5..81a2e3bf 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_floats_utils.h +++ b/third_party/WebKit/Source/core/layout/ng/ng_floats_utils.h
@@ -9,19 +9,23 @@ #include "core/layout/ng/ng_constraint_space.h" #include "core/layout/ng/ng_floating_object.h" #include "core/layout/ng/ng_fragment_builder.h" +#include "core/layout/ng/ng_positioned_float.h" namespace blink { // Positions {@code floating_object} into {@code new_parent_space}. -// @returns Logical offset of the positioned float. -CORE_EXPORT NGLogicalOffset PositionFloat(NGFloatingObject*, - NGConstraintSpace* new_parent_space); +// @returns A positioned float. +CORE_EXPORT NGPositionedFloat +PositionFloat(NGFloatingObject*, NGConstraintSpace* new_parent_space); -// Positions the list of floats by updating their {@code logical_offset}. -void PositionFloats(LayoutUnit origin_block_offset, - LayoutUnit from_block_offset, - const Vector<RefPtr<NGFloatingObject>>&, - NGConstraintSpace*); +// Positions the list of {@code floating_objects}. Adds them as exclusions to +// {@code space}. +CORE_EXPORT const Vector<NGPositionedFloat> PositionFloats( + LayoutUnit origin_block_offset, + LayoutUnit from_block_offset, + const Vector<RefPtr<NGFloatingObject>>& floating_objects, + NGConstraintSpace* space); + } // namespace blink #endif // NGFloatsUtils_h
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_fragment_builder.cc b/third_party/WebKit/Source/core/layout/ng/ng_fragment_builder.cc index d2c03777..e75e3ca1 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_fragment_builder.cc +++ b/third_party/WebKit/Source/core/layout/ng/ng_fragment_builder.cc
@@ -196,14 +196,10 @@ break_token = NGBlockBreakToken::Create(node_.Get()); } - for (auto& floating_object : positioned_floats_) { - DCHECK(floating_object->logical_offset) - << "logical_offset should be set for a positioned float."; - NGPhysicalFragment* floating_fragment = floating_object->fragment.Get(); - floating_fragment->SetOffset( - floating_object->logical_offset.value().ConvertToPhysical( - writing_mode_, direction_, physical_size, - floating_fragment->Size())); + for (auto& positioned_float : positioned_floats_) { + NGPhysicalFragment* floating_fragment = positioned_float.fragment.Get(); + floating_fragment->SetOffset(positioned_float.offset.ConvertToPhysical( + writing_mode_, direction_, physical_size, floating_fragment->Size())); } RefPtr<NGPhysicalBoxFragment> fragment = AdoptRef(new NGPhysicalBoxFragment(
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_fragment_builder.h b/third_party/WebKit/Source/core/layout/ng/ng_fragment_builder.h index 0924450..cb2dea73 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_fragment_builder.h +++ b/third_party/WebKit/Source/core/layout/ng/ng_fragment_builder.h
@@ -10,6 +10,7 @@ #include "core/layout/ng/ng_constraint_space.h" #include "core/layout/ng/ng_floating_object.h" #include "core/layout/ng/ng_physical_fragment.h" +#include "core/layout/ng/ng_positioned_float.h" #include "platform/wtf/Allocator.h" namespace blink { @@ -112,7 +113,7 @@ } // Mutable list of positioned floats, i.e. floats with logical_offset set. - Vector<RefPtr<NGFloatingObject>>& MutablePositionedFloats() { + Vector<NGPositionedFloat>& MutablePositionedFloats() { return positioned_floats_; } @@ -173,7 +174,7 @@ // determine its block position in space. Vector<RefPtr<NGFloatingObject>> unpositioned_floats_; - Vector<RefPtr<NGFloatingObject>> positioned_floats_; + Vector<NGPositionedFloat> positioned_floats_; WTF::Optional<NGLogicalOffset> bfc_offset_; NGMarginStrut end_margin_strut_;
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_physical_box_fragment.cc b/third_party/WebKit/Source/core/layout/ng/ng_physical_box_fragment.cc index 3d0b71b..dcc2d1a 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_physical_box_fragment.cc +++ b/third_party/WebKit/Source/core/layout/ng/ng_physical_box_fragment.cc
@@ -13,7 +13,7 @@ NGPhysicalSize size, NGPhysicalSize overflow, Vector<RefPtr<NGPhysicalFragment>>& children, - Vector<RefPtr<NGFloatingObject>>& positioned_floats, + Vector<NGPositionedFloat>& positioned_floats, const WTF::Optional<NGLogicalOffset>& bfc_offset, const NGMarginStrut& end_margin_strut, RefPtr<NGBreakToken> break_token)
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_physical_box_fragment.h b/third_party/WebKit/Source/core/layout/ng/ng_physical_box_fragment.h index e240321..d621f84 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_physical_box_fragment.h +++ b/third_party/WebKit/Source/core/layout/ng/ng_physical_box_fragment.h
@@ -10,12 +10,11 @@ #include "core/layout/ng/geometry/ng_margin_strut.h" #include "core/layout/ng/ng_floating_object.h" #include "core/layout/ng/ng_physical_fragment.h" +#include "core/layout/ng/ng_positioned_float.h" #include "platform/wtf/Optional.h" namespace blink { -struct NGFloatingObject; - class CORE_EXPORT NGPhysicalBoxFragment final : public NGPhysicalFragment { public: // This modifies the passed-in children vector. @@ -23,7 +22,7 @@ NGPhysicalSize size, NGPhysicalSize overflow, Vector<RefPtr<NGPhysicalFragment>>& children, - Vector<RefPtr<NGFloatingObject>>& positioned_floats, + Vector<NGPositionedFloat>& positioned_floats, const WTF::Optional<NGLogicalOffset>& bfc_offset, const NGMarginStrut& end_margin_strut, RefPtr<NGBreakToken> break_token = nullptr); @@ -38,7 +37,7 @@ // List of positioned floats that need to be copied to the old layout tree. // TODO(layout-ng): remove this once we change painting code to handle floats // differently. - const Vector<RefPtr<NGFloatingObject>>& PositionedFloats() const { + const Vector<NGPositionedFloat>& PositionedFloats() const { return positioned_floats_; } @@ -51,7 +50,7 @@ private: NGPhysicalSize overflow_; Vector<RefPtr<NGPhysicalFragment>> children_; - Vector<RefPtr<NGFloatingObject>> positioned_floats_; + Vector<NGPositionedFloat> positioned_floats_; const WTF::Optional<NGLogicalOffset> bfc_offset_; const NGMarginStrut end_margin_strut_; };
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_positioned_float.h b/third_party/WebKit/Source/core/layout/ng/ng_positioned_float.h new file mode 100644 index 0000000..8443fa0 --- /dev/null +++ b/third_party/WebKit/Source/core/layout/ng/ng_positioned_float.h
@@ -0,0 +1,35 @@ +// 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 NGPositionedFloat_h +#define NGPositionedFloat_h + +#include "core/CoreExport.h" +#include "core/layout/ng/ng_physical_fragment.h" + +namespace blink { + +// Contains the information necessary for copying back data to a FloatingObject. +struct CORE_EXPORT NGPositionedFloat { + NGPositionedFloat(RefPtr<NGPhysicalFragment> fragment, + NGLogicalOffset offset, + LayoutUnit left_offset) + : fragment(fragment), offset(offset), left_offset(left_offset) {} + + RefPtr<NGPhysicalFragment> fragment; + NGLogicalOffset offset; + + // In the case where a legacy FloatingObject is attached to not its own + // parent, e.g. a float surrounded by a bunch of nested empty divs, + // NG float fragment's LeftOffset() cannot be used as legacy FloatingObject's + // left offset because that offset should be relative to the original float + // parent. + // {@code left_offset} is calculated when we know to which parent this float + // would be attached. + LayoutUnit left_offset; +}; + +} // namespace blink + +#endif // NGPositionedFloat_h
diff --git a/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp b/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp index 96ab8d11..894c2b58 100644 --- a/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp +++ b/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp
@@ -100,6 +100,8 @@ void ReportDisallowedLoad() override { ++*filtered_load_counter_; } + bool ShouldLogToConsole() override { return false; } + private: const LoadPolicy policy_; int* filtered_load_counter_;
diff --git a/third_party/WebKit/Source/core/loader/SubresourceFilter.cpp b/third_party/WebKit/Source/core/loader/SubresourceFilter.cpp index 4b38f38e..bdfbdf1 100644 --- a/third_party/WebKit/Source/core/loader/SubresourceFilter.cpp +++ b/third_party/WebKit/Source/core/loader/SubresourceFilter.cpp
@@ -4,6 +4,8 @@ #include "core/loader/SubresourceFilter.h" +#include <utility> + #include "core/dom/TaskRunnerHelper.h" #include "platform/WebTaskRunner.h" #include "platform/weborigin/KURL.h" @@ -58,7 +60,6 @@ void SubresourceFilter::ReportLoad( WebDocumentSubresourceFilter::LoadPolicy load_policy) { - // TODO(csharrison): log console errors here. switch (load_policy) { case WebDocumentSubresourceFilter::kAllow: break; @@ -66,6 +67,8 @@ subresource_filter_->ReportDisallowedLoad(); // fall through case WebDocumentSubresourceFilter::kWouldDisallow: + // TODO(csharrison): log console errors here based on + // subresource_filter_->ShouldLogToConsole(). document_loader_->DidObserveLoadingBehavior( kWebLoadingBehaviorSubresourceFilterMatch); break;
diff --git a/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.cpp b/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.cpp index ebd8677..b59a07a 100644 --- a/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.cpp +++ b/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.cpp
@@ -78,7 +78,7 @@ } void OffscreenCanvas::SetNeutered() { - ASSERT(!context_); + DCHECK(!context_); is_neutered_ = true; size_.SetWidth(0); size_.SetHeight(0); @@ -209,7 +209,7 @@ CanvasRenderingContext::ContextType type = rendering_context_factory->GetContextType(); ASSERT(type < CanvasRenderingContext::kContextTypeCount); - ASSERT(!RenderingContextFactories()[type]); + DCHECK(!RenderingContextFactories()[type]); RenderingContextFactories()[type] = std::move(rendering_context_factory); }
diff --git a/third_party/WebKit/Source/core/page/ChromeClient.cpp b/third_party/WebKit/Source/core/page/ChromeClient.cpp index a7c4ea8..de6af36 100644 --- a/third_party/WebKit/Source/core/page/ChromeClient.cpp +++ b/third_party/WebKit/Source/core/page/ChromeClient.cpp
@@ -112,7 +112,7 @@ bool ChromeClient::OpenBeforeUnloadConfirmPanel(const String& message, LocalFrame* frame, bool is_reload) { - ASSERT(frame); + DCHECK(frame); return OpenJavaScriptDialog( frame, message, ChromeClient::kHTMLDialog, [this, frame, is_reload]() { return OpenBeforeUnloadConfirmPanelDelegate(frame, is_reload); @@ -121,7 +121,7 @@ bool ChromeClient::OpenJavaScriptAlert(LocalFrame* frame, const String& message) { - ASSERT(frame); + DCHECK(frame); if (!CanOpenModalIfDuringPageDismissal(frame->Tree().Top(), ChromeClient::kAlertDialog, message)) return false; @@ -133,7 +133,7 @@ bool ChromeClient::OpenJavaScriptConfirm(LocalFrame* frame, const String& message) { - ASSERT(frame); + DCHECK(frame); if (!CanOpenModalIfDuringPageDismissal(frame->Tree().Top(), ChromeClient::kConfirmDialog, message)) return false; @@ -147,7 +147,7 @@ const String& prompt, const String& default_value, String& result) { - ASSERT(frame); + DCHECK(frame); if (!CanOpenModalIfDuringPageDismissal(frame->Tree().Top(), ChromeClient::kPromptDialog, prompt)) return false;
diff --git a/third_party/WebKit/Source/core/page/ContextMenuController.cpp b/third_party/WebKit/Source/core/page/ContextMenuController.cpp index 31933724..e48f194 100644 --- a/third_party/WebKit/Source/core/page/ContextMenuController.cpp +++ b/third_party/WebKit/Source/core/page/ContextMenuController.cpp
@@ -133,7 +133,7 @@ std::unique_ptr<ContextMenu> ContextMenuController::CreateContextMenu( Event* event) { - ASSERT(event); + DCHECK(event); if (!event->IsMouseEvent()) return nullptr; @@ -181,7 +181,7 @@ item->Action() > kContextMenuItemLastCustomTag) return; - ASSERT(menu_provider_); + DCHECK(menu_provider_); menu_provider_->ContextMenuItemSelected(item); }
diff --git a/third_party/WebKit/Source/core/page/CreateWindow.cpp b/third_party/WebKit/Source/core/page/CreateWindow.cpp index 6e78204..ba80330 100644 --- a/third_party/WebKit/Source/core/page/CreateWindow.cpp +++ b/third_party/WebKit/Source/core/page/CreateWindow.cpp
@@ -83,7 +83,7 @@ if (!page) return nullptr; - ASSERT(page->MainFrame()); + DCHECK(page->MainFrame()); LocalFrame& frame = *ToLocalFrame(page->MainFrame()); if (!EqualIgnoringASCIICase(request.FrameName(), "_blank")) @@ -183,7 +183,7 @@ LocalFrame& opener_frame, ExceptionState& exception_state) { LocalFrame* active_frame = calling_window.GetFrame(); - ASSERT(active_frame); + DCHECK(active_frame); KURL completed_url = url_string.IsEmpty() ? KURL(kParsedURLString, g_empty_string)
diff --git a/third_party/WebKit/Source/core/page/Page.cpp b/third_party/WebKit/Source/core/page/Page.cpp index 941a30c..6dc4b21 100644 --- a/third_party/WebKit/Source/core/page/Page.cpp +++ b/third_party/WebKit/Source/core/page/Page.cpp
@@ -129,15 +129,15 @@ visibility_state_(kPageVisibilityStateVisible), is_cursor_visible_(true), subframe_count_(0) { - ASSERT(editor_client_); + DCHECK(editor_client_); - ASSERT(!AllPages().Contains(this)); + DCHECK(!AllPages().Contains(this)); AllPages().insert(this); } Page::~Page() { // willBeDestroyed() must be called before Page destruction. - ASSERT(!main_frame_); + DCHECK(!main_frame_); } void Page::CloseSoon() { @@ -654,7 +654,7 @@ if (main_frame->IsAttached()) main_frame->Detach(FrameDetachType::kRemove); - ASSERT(AllPages().Contains(this)); + DCHECK(AllPages().Contains(this)); AllPages().erase(this); OrdinaryPages().erase(this);
diff --git a/third_party/WebKit/Source/core/page/PagePopupController.cpp b/third_party/WebKit/Source/core/page/PagePopupController.cpp index 94ce51ea..23e830ba 100644 --- a/third_party/WebKit/Source/core/page/PagePopupController.cpp +++ b/third_party/WebKit/Source/core/page/PagePopupController.cpp
@@ -40,7 +40,7 @@ PagePopupController::PagePopupController(PagePopup& popup, PagePopupClient* client) : popup_(popup), popup_client_(client) { - ASSERT(client); + DCHECK(client); } PagePopupController* PagePopupController::Create(PagePopup& popup, @@ -66,7 +66,7 @@ void PagePopupController::selectFontsFromOwnerDocument( Document* target_document) { - ASSERT(target_document); + DCHECK(target_document); if (popup_client_) popup_client_->SelectFontsFromOwnerDocument(*target_document); }
diff --git a/third_party/WebKit/Source/core/page/PagePopupSupplement.cpp b/third_party/WebKit/Source/core/page/PagePopupSupplement.cpp index 59c712d..18c07433 100644 --- a/third_party/WebKit/Source/core/page/PagePopupSupplement.cpp +++ b/third_party/WebKit/Source/core/page/PagePopupSupplement.cpp
@@ -64,7 +64,7 @@ void PagePopupSupplement::Install(LocalFrame& frame, PagePopup& popup, PagePopupClient* popup_client) { - ASSERT(popup_client); + DCHECK(popup_client); ProvideTo(frame, SupplementName(), new PagePopupSupplement(frame, popup, popup_client)); }
diff --git a/third_party/WebKit/Source/core/page/PrintContext.cpp b/third_party/WebKit/Source/core/page/PrintContext.cpp index dc76a2a66..12bed3d 100644 --- a/third_party/WebKit/Source/core/page/PrintContext.cpp +++ b/third_party/WebKit/Source/core/page/PrintContext.cpp
@@ -171,7 +171,7 @@ } void PrintContext::EndPrintMode() { - ASSERT(is_printing_); + DCHECK(is_printing_); is_printing_ = false; if (IsFrameValid()) frame_->SetPrinting(false, FloatSize(), FloatSize(), 0);
diff --git a/third_party/WebKit/Source/core/page/SpatialNavigation.cpp b/third_party/WebKit/Source/core/page/SpatialNavigation.cpp index 4daebfc..bba9611 100644 --- a/third_party/WebKit/Source/core/page/SpatialNavigation.cpp +++ b/third_party/WebKit/Source/core/page/SpatialNavigation.cpp
@@ -57,8 +57,8 @@ distance(MaxDistance()), is_offscreen(true), is_offscreen_after_scrolling(true) { - ASSERT(node); - ASSERT(node->IsElementNode()); + DCHECK(node); + DCHECK(node->IsElementNode()); if (isHTMLAreaElement(*node)) { HTMLAreaElement& area = toHTMLAreaElement(*node); @@ -152,7 +152,7 @@ if (!frame_view) return true; - ASSERT(!frame_view->NeedsLayout()); + DCHECK(!frame_view->NeedsLayout()); LayoutRect container_viewport_rect(frame_view->VisibleContentRect()); // We want to select a node if it is currently off screen, but will be @@ -198,7 +198,7 @@ } bool ScrollInDirection(LocalFrame* frame, WebFocusType type) { - ASSERT(frame); + DCHECK(frame); if (frame && CanScrollInDirection(frame->GetDocument(), type)) { int dx = 0; @@ -230,7 +230,7 @@ } bool ScrollInDirection(Node* container, WebFocusType type) { - ASSERT(container); + DCHECK(container); if (container->IsDocumentNode()) return ScrollInDirection(ToDocument(container)->GetFrame(), type); @@ -292,7 +292,7 @@ } bool IsScrollableNode(const Node* node) { - ASSERT(!node->IsDocumentNode()); + DCHECK(!node->IsDocumentNode()); if (!node) return false; @@ -307,7 +307,7 @@ Node* ScrollableEnclosingBoxOrParentFrameForNodeInDirection(WebFocusType type, Node* node) { - ASSERT(node); + DCHECK(node); Node* parent = node; do { // FIXME: Spatial navigation is broken for OOPI. @@ -322,7 +322,7 @@ } bool CanScrollInDirection(const Node* container, WebFocusType type) { - ASSERT(container); + DCHECK(container); if (container->IsDocumentNode()) return CanScrollInDirection(ToDocument(container)->GetFrame(), type); @@ -676,7 +676,7 @@ LayoutRect VirtualRectForAreaElementAndDirection(HTMLAreaElement& area, WebFocusType type) { - ASSERT(area.ImageElement()); + DCHECK(area.ImageElement()); // Area elements tend to overlap more than other focusable elements. We // flatten the rect of the area elements to minimize the effect of overlapping // areas.
diff --git a/third_party/WebKit/Source/core/page/TouchAdjustment.cpp b/third_party/WebKit/Source/core/page/TouchAdjustment.cpp index 1a806da..a90771f 100644 --- a/third_party/WebKit/Source/core/page/TouchAdjustment.cpp +++ b/third_party/WebKit/Source/core/page/TouchAdjustment.cpp
@@ -109,7 +109,7 @@ if (node->IsTextNode() || node->IsShadowRoot()) return false; - ASSERT(node->GetLayoutObject()); + DCHECK(node->GetLayoutObject()); return node->GetLayoutObject()->IsBox(); } @@ -160,7 +160,7 @@ Node* node, SubtargetGeometryList& subtargets) { // Node guaranteed to have layoutObject due to check in node filter. - ASSERT(node->GetLayoutObject()); + DCHECK(node->GetLayoutObject()); Vector<FloatQuad> quads; node->GetLayoutObject()->AbsoluteQuads(quads); @@ -173,7 +173,7 @@ SubtargetGeometryList& subtargets) { // This is a variant of appendBasicSubtargetsForNode that adds special // subtargets for selected or auto-selectable parts of text nodes. - ASSERT(node->GetLayoutObject()); + DCHECK(node->GetLayoutObject()); if (!node->IsTextNode()) return AppendBasicSubtargetsForNode(node, subtargets); @@ -235,7 +235,7 @@ static inline void AppendZoomableSubtargets(Node* node, SubtargetGeometryList& subtargets) { LayoutBox* layout_object = ToLayoutBox(node->GetLayoutObject()); - ASSERT(layout_object); + DCHECK(layout_object); Vector<FloatQuad> quads; FloatRect border_box_rect(layout_object->BorderBoxRect()); @@ -320,7 +320,7 @@ // preferred even when contained in an element that monitors all // click-events. Node* responding_node = responder_map.at(candidate); - ASSERT(responding_node); + DCHECK(responding_node); if (ancestors_to_responders_set.Contains(responding_node)) continue; // Consolidate bounds for editable content.
diff --git a/third_party/WebKit/Source/core/page/scrolling/ScrollState.cpp b/third_party/WebKit/Source/core/page/scrolling/ScrollState.cpp index c28dc37..12053e2f 100644 --- a/third_party/WebKit/Source/core/page/scrolling/ScrollState.cpp +++ b/third_party/WebKit/Source/core/page/scrolling/ScrollState.cpp
@@ -16,10 +16,10 @@ namespace { Element* ElementForId(int element_id) { Node* node = DOMNodeIds::NodeForId(element_id); - ASSERT(node); + DCHECK(node); if (!node) return nullptr; - ASSERT(node->IsElementNode()); + DCHECK(node->IsElementNode()); if (!node->IsElementNode()) return nullptr; return static_cast<Element*>(node);
diff --git a/third_party/WebKit/Source/core/page/scrolling/SnapCoordinator.cpp b/third_party/WebKit/Source/core/page/scrolling/SnapCoordinator.cpp index 14191c4..5762342d 100644 --- a/third_party/WebKit/Source/core/page/scrolling/SnapCoordinator.cpp +++ b/third_party/WebKit/Source/core/page/scrolling/SnapCoordinator.cpp
@@ -105,8 +105,8 @@ ScrollbarOrientation orientation) { const ComputedStyle* style = element.GetComputedStyle(); const LayoutBox* snap_container = element.GetLayoutBox(); - ASSERT(style); - ASSERT(snap_container); + DCHECK(style); + DCHECK(snap_container); Vector<double> result;
diff --git a/third_party/WebKit/Source/core/probe/CoreProbes.cpp b/third_party/WebKit/Source/core/probe/CoreProbes.cpp index fb0477c..27d41ba 100644 --- a/third_party/WebKit/Source/core/probe/CoreProbes.cpp +++ b/third_party/WebKit/Source/core/probe/CoreProbes.cpp
@@ -30,6 +30,7 @@ #include "core/probe/CoreProbes.h" +#include "bindings/core/v8/V8BindingForCore.h" #include "core/CoreProbeSink.h" #include "core/events/Event.h" #include "core/events/EventTarget.h"
diff --git a/third_party/WebKit/Source/core/streams/ReadableStreamOperations.cpp b/third_party/WebKit/Source/core/streams/ReadableStreamOperations.cpp index 7e92a55..ec9645d4 100644 --- a/third_party/WebKit/Source/core/streams/ReadableStreamOperations.cpp +++ b/third_party/WebKit/Source/core/streams/ReadableStreamOperations.cpp
@@ -59,7 +59,7 @@ bool ReadableStreamOperations::IsReadableStream(ScriptState* script_state, ScriptValue value) { - ASSERT(!value.IsEmpty()); + DCHECK(!value.IsEmpty()); if (!value.IsObject()) return false; @@ -129,7 +129,7 @@ bool ReadableStreamOperations::IsReadableStreamDefaultReader( ScriptState* script_state, ScriptValue value) { - ASSERT(!value.IsEmpty()); + DCHECK(!value.IsEmpty()); if (!value.IsObject()) return false;
diff --git a/third_party/WebKit/Source/core/streams/ReadableStreamOperationsTest.cpp b/third_party/WebKit/Source/core/streams/ReadableStreamOperationsTest.cpp index d90424e..82d2c21 100644 --- a/third_party/WebKit/Source/core/streams/ReadableStreamOperationsTest.cpp +++ b/third_party/WebKit/Source/core/streams/ReadableStreamOperationsTest.cpp
@@ -48,7 +48,7 @@ Iteration() : is_set_(false), is_done_(false), is_valid_(true) {} void Set(ScriptValue v) { - ASSERT(!v.IsEmpty()); + DCHECK(!v.IsEmpty()); is_set_ = true; v8::TryCatch block(v.GetScriptState()->GetIsolate()); v8::Local<v8::Value> value;
diff --git a/third_party/WebKit/Source/core/streams/UnderlyingSourceBase.cpp b/third_party/WebKit/Source/core/streams/UnderlyingSourceBase.cpp index 38f8251..2d9b108 100644 --- a/third_party/WebKit/Source/core/streams/UnderlyingSourceBase.cpp +++ b/third_party/WebKit/Source/core/streams/UnderlyingSourceBase.cpp
@@ -16,7 +16,7 @@ ScriptValue js_controller) { // Cannot call start twice (e.g., cannot use the same UnderlyingSourceBase to // construct multiple streams). - ASSERT(!controller_); + DCHECK(!controller_); controller_ = new ReadableStreamController(js_controller);
diff --git a/third_party/WebKit/Source/core/timing/PerformanceBase.cpp b/third_party/WebKit/Source/core/timing/PerformanceBase.cpp index 1b09ef6..4cef3f69 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceBase.cpp +++ b/third_party/WebKit/Source/core/timing/PerformanceBase.cpp
@@ -367,14 +367,14 @@ if (!allow_redirect_details) { ResourceLoadTiming* final_timing = final_response.GetResourceLoadTiming(); - ASSERT(final_timing); + DCHECK(final_timing); if (final_timing) start_time = final_timing->RequestTime(); } ResourceLoadTiming* last_redirect_timing = redirect_chain.back().GetResourceLoadTiming(); - ASSERT(last_redirect_timing); + DCHECK(last_redirect_timing); double last_redirect_end_time = last_redirect_timing->ReceiveHeadersEnd(); PerformanceEntry* entry = PerformanceResourceTiming::Create( @@ -488,7 +488,7 @@ void PerformanceBase::UnregisterPerformanceObserver( PerformanceObserver& old_observer) { - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); // Deliver any pending observations on this observer before unregistering. if (active_observers_.Contains(&old_observer) && !old_observer.ShouldBeSuspended()) { @@ -535,7 +535,7 @@ } void PerformanceBase::ResumeSuspendedObservers() { - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); if (suspended_observers_.IsEmpty()) return; @@ -550,7 +550,7 @@ } void PerformanceBase::DeliverObservationsTimerFired(TimerBase*) { - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); PerformanceObservers observers; active_observers_.Swap(observers); for (const auto& observer : observers) {
diff --git a/third_party/WebKit/Source/core/timing/PerformanceObserver.cpp b/third_party/WebKit/Source/core/timing/PerformanceObserver.cpp index 57e44d0..35f4c461 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceObserver.cpp +++ b/third_party/WebKit/Source/core/timing/PerformanceObserver.cpp
@@ -20,7 +20,7 @@ ExecutionContext* execution_context, PerformanceBase* performance, PerformanceObserverCallback* callback) { - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); return new PerformanceObserver(execution_context, performance, callback); } @@ -70,7 +70,7 @@ } void PerformanceObserver::EnqueuePerformanceEntry(PerformanceEntry& entry) { - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); performance_entries_.push_back(&entry); if (performance_) performance_->ActivateObserver(*this); @@ -81,7 +81,7 @@ } void PerformanceObserver::Deliver() { - ASSERT(!ShouldBeSuspended()); + DCHECK(!ShouldBeSuspended()); if (performance_entries_.IsEmpty()) return;
diff --git a/third_party/WebKit/Source/core/timing/SharedWorkerPerformance.cpp b/third_party/WebKit/Source/core/timing/SharedWorkerPerformance.cpp index 9187132..24c0dff 100644 --- a/third_party/WebKit/Source/core/timing/SharedWorkerPerformance.cpp +++ b/third_party/WebKit/Source/core/timing/SharedWorkerPerformance.cpp
@@ -65,8 +65,8 @@ double SharedWorkerPerformance::GetWorkerStart(ExecutionContext* context, SharedWorker&) const { - ASSERT(context); - ASSERT(context->IsDocument()); + DCHECK(context); + DCHECK(context->IsDocument()); Document* document = ToDocument(context); if (!document->Loader()) return 0;
diff --git a/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp b/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp index a88ef27..0d36627 100644 --- a/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp
@@ -31,6 +31,7 @@ #include "bindings/core/v8/ScriptSourceCode.h" #include "bindings/core/v8/SourceLocation.h" #include "bindings/core/v8/V8AbstractEventListener.h" +#include "bindings/core/v8/WorkerOrWorkletScriptController.h" #include "core/dom/ContextLifecycleNotifier.h" #include "core/dom/ExceptionCode.h" #include "core/dom/SuspendableObject.h" @@ -74,7 +75,7 @@ } // namespace WorkerGlobalScope::~WorkerGlobalScope() { - DCHECK(!script_controller_); + DCHECK(!ScriptController()); InstanceCounters::DecrementCounter( InstanceCounters::kWorkerGlobalScopeCounter); } @@ -106,10 +107,8 @@ } RemoveAllEventListeners(); - script_controller_->Dispose(); - script_controller_.Clear(); event_queue_->Close(); - thread_ = nullptr; + WorkerOrWorkletGlobalScope::Dispose(); } void WorkerGlobalScope::ReportFeature(UseCounter::Feature feature) { @@ -224,11 +223,11 @@ script_loader->CachedMetadata() ? script_loader->CachedMetadata()->size() : 0); - script_controller_->Evaluate(ScriptSourceCode(script_loader->SourceText(), + ScriptController()->Evaluate(ScriptSourceCode(script_loader->SourceText(), script_loader->ResponseURL()), &error_event, handler, v8_cache_options_); if (error_event) { - script_controller_->RethrowExceptionFromImportedScript(error_event, + ScriptController()->RethrowExceptionFromImportedScript(error_event, exception_state); return; } @@ -258,18 +257,10 @@ return timers_.HasInstalledTimeout(); } -bool WorkerGlobalScope::IsJSExecutionForbidden() const { - return script_controller_->IsExecutionForbidden(); -} - bool WorkerGlobalScope::IsContextThread() const { return GetThread()->IsCurrentThread(); } -void WorkerGlobalScope::DisableEval(const String& error_message) { - script_controller_->DisableEval(error_message); -} - void WorkerGlobalScope::AddConsoleMessage(ConsoleMessage* console_message) { DCHECK(IsContextThread()); GetThread()->GetWorkerReportingProxy().ReportConsoleMessage( @@ -323,18 +314,15 @@ std::unique_ptr<SecurityOrigin::PrivilegeData> starter_origin_privilage_data, WorkerClients* worker_clients) - : url_(url), + : WorkerOrWorkletGlobalScope(thread->GetIsolate()), + url_(url), user_agent_(user_agent), v8_cache_options_(kV8CacheOptionsDefault), - script_controller_( - WorkerOrWorkletScriptController::Create(this, thread->GetIsolate())), thread_(thread), - closing_(false), event_queue_(WorkerEventQueue::Create(this)), worker_clients_(worker_clients), timers_(TaskRunnerHelper::Get(TaskType::kTimer, this)), - time_origin_(time_origin), - last_pending_error_event_id_(0) { + time_origin_(time_origin) { InstanceCounters::IncrementCounter( InstanceCounters::kWorkerGlobalScopeCounter); SetSecurityOrigin(SecurityOrigin::Create(url)); @@ -385,15 +373,14 @@ DEFINE_TRACE(WorkerGlobalScope) { visitor->Trace(location_); visitor->Trace(navigator_); - visitor->Trace(script_controller_); visitor->Trace(event_queue_); visitor->Trace(timers_); visitor->Trace(event_listeners_); visitor->Trace(pending_error_events_); visitor->Trace(fetch_context_); - ExecutionContext::Trace(visitor); EventTargetWithInlineData::Trace(visitor); SecurityContext::Trace(visitor); + WorkerOrWorkletGlobalScope::Trace(visitor); Supplementable<WorkerGlobalScope>::Trace(visitor); }
diff --git a/third_party/WebKit/Source/core/workers/WorkerGlobalScope.h b/third_party/WebKit/Source/core/workers/WorkerGlobalScope.h index 03e28e2d..62a1d199 100644 --- a/third_party/WebKit/Source/core/workers/WorkerGlobalScope.h +++ b/third_party/WebKit/Source/core/workers/WorkerGlobalScope.h
@@ -29,7 +29,6 @@ #include <memory> #include "bindings/core/v8/V8CacheOptions.h" -#include "bindings/core/v8/WorkerOrWorkletScriptController.h" #include "core/CoreExport.h" #include "core/dom/ExecutionContext.h" #include "core/events/EventListener.h" @@ -124,9 +123,7 @@ // ExecutionContext bool IsWorkerGlobalScope() const final { return true; } - bool IsJSExecutionForbidden() const final; bool IsContextThread() const final; - void DisableEval(const String& error_message) final; String UserAgent() const final { return user_agent_; } DOMTimerCoordinator* Timers() final { return &timers_; } @@ -147,11 +144,6 @@ double TimeOrigin() const { return time_origin_; } WorkerSettings* GetWorkerSettings() const { return worker_settings_.get(); } - - WorkerOrWorkletScriptController* ScriptController() final { - return script_controller_.Get(); - } - WorkerClients* Clients() const { return worker_clients_.Get(); } // Available only when off-main-thread-fetch is enabled. @@ -195,10 +187,9 @@ mutable Member<WorkerLocation> location_; mutable Member<WorkerNavigator> navigator_; - Member<WorkerOrWorkletScriptController> script_controller_; WorkerThread* thread_; - bool closing_; + bool closing_ = false; Member<WorkerEventQueue> event_queue_; @@ -211,7 +202,7 @@ HeapHashSet<Member<V8AbstractEventListener>> event_listeners_; HeapHashMap<int, Member<ErrorEvent>> pending_error_events_; - int last_pending_error_event_id_; + int last_pending_error_event_id_ = 0; Member<WorkerFetchContext> fetch_context_; };
diff --git a/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.cpp b/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.cpp index 8743d587..108d35c 100644 --- a/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.cpp
@@ -4,6 +4,7 @@ #include "core/workers/WorkerOrWorkletGlobalScope.h" +#include "bindings/core/v8/WorkerOrWorkletScriptController.h" #include "core/dom/ExecutionContextTask.h" #include "core/dom/TaskRunnerHelper.h" #include "core/frame/Deprecation.h" @@ -16,8 +17,10 @@ namespace blink { -WorkerOrWorkletGlobalScope::WorkerOrWorkletGlobalScope() - : used_features_(UseCounter::kNumberOfFeatures) {} +WorkerOrWorkletGlobalScope::WorkerOrWorkletGlobalScope(v8::Isolate* isolate) + : script_controller_( + WorkerOrWorkletScriptController::Create(this, isolate)), + used_features_(UseCounter::kNumberOfFeatures) {} WorkerOrWorkletGlobalScope::~WorkerOrWorkletGlobalScope() = default; @@ -46,6 +49,14 @@ ReportDeprecation(feature); } +bool WorkerOrWorkletGlobalScope::IsJSExecutionForbidden() const { + return script_controller_->IsExecutionForbidden(); +} + +void WorkerOrWorkletGlobalScope::DisableEval(const String& error_message) { + script_controller_->DisableEval(error_message); +} + void WorkerOrWorkletGlobalScope::PostTask( TaskType type, const WebTraceLocation& location, @@ -66,6 +77,17 @@ is_instrumented)); } +void WorkerOrWorkletGlobalScope::Dispose() { + DCHECK(script_controller_); + script_controller_->Dispose(); + script_controller_.Clear(); +} + +DEFINE_TRACE(WorkerOrWorkletGlobalScope) { + visitor->Trace(script_controller_); + ExecutionContext::Trace(visitor); +} + void WorkerOrWorkletGlobalScope::RunTask( std::unique_ptr<ExecutionContextTask> task, bool is_instrumented) {
diff --git a/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.h b/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.h index 2fd4a653..62698815 100644 --- a/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.h +++ b/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.h
@@ -16,11 +16,13 @@ class CORE_EXPORT WorkerOrWorkletGlobalScope : public ExecutionContext { public: - WorkerOrWorkletGlobalScope(); + explicit WorkerOrWorkletGlobalScope(v8::Isolate*); virtual ~WorkerOrWorkletGlobalScope(); // ExecutionContext bool IsWorkerOrWorkletGlobalScope() const final { return true; } + bool IsJSExecutionForbidden() const final; + void DisableEval(const String& error_message) final; void PostTask( TaskType, const WebTraceLocation&, @@ -28,7 +30,6 @@ const String& task_name_for_instrumentation = g_empty_string) final; virtual ScriptWrappable* GetScriptWrappable() const = 0; - virtual WorkerOrWorkletScriptController* ScriptController() = 0; // Returns true when the WorkerOrWorkletGlobalScope is closing (e.g. via // WorkerGlobalScope#close() method). If this returns true, the worker is @@ -38,7 +39,7 @@ // Should be called before destroying the global scope object. Allows // sub-classes to perform any cleanup needed. - virtual void Dispose() = 0; + virtual void Dispose(); // Called from UseCounter to record API use in this execution context. void CountFeature(UseCounter::Feature); @@ -51,6 +52,12 @@ // MainThreadWorkletGlobalScope) or after dispose() is called. virtual WorkerThread* GetThread() const = 0; + WorkerOrWorkletScriptController* ScriptController() { + return script_controller_.Get(); + } + + DECLARE_VIRTUAL_TRACE(); + protected: virtual void ReportFeature(UseCounter::Feature) = 0; virtual void ReportDeprecation(UseCounter::Feature) = 0; @@ -58,6 +65,8 @@ private: void RunTask(std::unique_ptr<ExecutionContextTask>, bool is_instrumented); + Member<WorkerOrWorkletScriptController> script_controller_; + // This is the set of features that this worker has used. BitVector used_features_; };
diff --git a/third_party/WebKit/Source/core/workers/WorkletGlobalScope.cpp b/third_party/WebKit/Source/core/workers/WorkletGlobalScope.cpp index 6ae660d..ebff7ee 100644 --- a/third_party/WebKit/Source/core/workers/WorkletGlobalScope.cpp +++ b/third_party/WebKit/Source/core/workers/WorkletGlobalScope.cpp
@@ -17,21 +17,12 @@ const String& user_agent, PassRefPtr<SecurityOrigin> security_origin, v8::Isolate* isolate) - : url_(url), - user_agent_(user_agent), - script_controller_( - WorkerOrWorkletScriptController::Create(this, isolate)) { + : WorkerOrWorkletGlobalScope(isolate), url_(url), user_agent_(user_agent) { SetSecurityOrigin(std::move(security_origin)); } WorkletGlobalScope::~WorkletGlobalScope() {} -void WorkletGlobalScope::Dispose() { - DCHECK(script_controller_); - script_controller_->Dispose(); - script_controller_.Clear(); -} - v8::Local<v8::Object> WorkletGlobalScope::Wrap( v8::Isolate*, v8::Local<v8::Object> creation_context) { @@ -51,14 +42,6 @@ return v8::Local<v8::Object>(); } -void WorkletGlobalScope::DisableEval(const String& error_message) { - script_controller_->DisableEval(error_message); -} - -bool WorkletGlobalScope::IsJSExecutionForbidden() const { - return script_controller_->IsExecutionForbidden(); -} - bool WorkletGlobalScope::IsSecureContext(String& error_message) const { // Until there are APIs that are available in worklets and that // require a privileged context test that checks ancestors, just do @@ -80,7 +63,6 @@ } DEFINE_TRACE(WorkletGlobalScope) { - visitor->Trace(script_controller_); ExecutionContext::Trace(visitor); SecurityContext::Trace(visitor); WorkerOrWorkletGlobalScope::Trace(visitor);
diff --git a/third_party/WebKit/Source/core/workers/WorkletGlobalScope.h b/third_party/WebKit/Source/core/workers/WorkletGlobalScope.h index 5fcde1b..c0947f6 100644 --- a/third_party/WebKit/Source/core/workers/WorkletGlobalScope.h +++ b/third_party/WebKit/Source/core/workers/WorkletGlobalScope.h
@@ -17,7 +17,6 @@ namespace blink { class EventQueue; -class WorkerOrWorkletScriptController; class CORE_EXPORT WorkletGlobalScope : public GarbageCollectedFinalized<WorkletGlobalScope>, @@ -29,7 +28,6 @@ public: ~WorkletGlobalScope() override; - void Dispose() override; bool IsWorkletGlobalScope() const final { return true; } @@ -37,9 +35,6 @@ ScriptWrappable* GetScriptWrappable() const final { return const_cast<WorkletGlobalScope*>(this); } - WorkerOrWorkletScriptController* ScriptController() final { - return script_controller_.Get(); - } // Always returns false here as worklets don't have a #close() method on // the global. @@ -54,8 +49,6 @@ v8::Local<v8::Object> wrapper) final; // ExecutionContext - void DisableEval(const String& error_message) final; - bool IsJSExecutionForbidden() const final; String UserAgent() const final { return user_agent_; } SecurityContext& GetSecurityContext() final { return *this; } EventQueue* GetEventQueue() const final { @@ -91,7 +84,6 @@ KURL url_; String user_agent_; - Member<WorkerOrWorkletScriptController> script_controller_; }; DEFINE_TYPE_CASTS(WorkletGlobalScope,
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/UIUtils.js b/third_party/WebKit/Source/devtools/front_end/ui/UIUtils.js index 26d1f97..66d61ac9 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/UIUtils.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/UIUtils.js
@@ -1110,6 +1110,7 @@ * @param {!Common.Setting} themeSetting */ UI.initializeUIUtils = function(document, themeSetting) { + document.body.classList.toggle('inactive', !document.hasFocus()); document.defaultView.addEventListener('focus', UI._windowFocused.bind(UI, document), false); document.defaultView.addEventListener('blur', UI._windowBlurred.bind(UI, document), false); document.addEventListener('focus', UI._focusChanged.bind(UI), true);
diff --git a/third_party/WebKit/Source/modules/ModulesInitializer.cpp b/third_party/WebKit/Source/modules/ModulesInitializer.cpp index 983e5ba2..2ada34d 100644 --- a/third_party/WebKit/Source/modules/ModulesInitializer.cpp +++ b/third_party/WebKit/Source/modules/ModulesInitializer.cpp
@@ -38,7 +38,7 @@ namespace blink { void ModulesInitializer::Initialize() { - ASSERT(!IsInitialized()); + DCHECK(!IsInitialized()); // Strings must be initialized before calling CoreInitializer::init(). const unsigned kModulesStaticStringsCount = @@ -100,7 +100,7 @@ HTMLMediaElement::RegisterMediaControlsFactory( WTF::MakeUnique<MediaControlsImpl::Factory>()); - ASSERT(IsInitialized()); + DCHECK(IsInitialized()); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/audio_output_devices/SetSinkIdCallbacks.cpp b/third_party/WebKit/Source/modules/audio_output_devices/SetSinkIdCallbacks.cpp index 96cdd96..72ecc34 100644 --- a/third_party/WebKit/Source/modules/audio_output_devices/SetSinkIdCallbacks.cpp +++ b/third_party/WebKit/Source/modules/audio_output_devices/SetSinkIdCallbacks.cpp
@@ -37,7 +37,7 @@ HTMLMediaElement& element, const String& sink_id) : resolver_(resolver), element_(element), sink_id_(sink_id) { - ASSERT(resolver_); + DCHECK(resolver_); } SetSinkIdCallbacks::~SetSinkIdCallbacks() {}
diff --git a/third_party/WebKit/Source/modules/cachestorage/Cache.cpp b/third_party/WebKit/Source/modules/cachestorage/Cache.cpp index 0825b5d..f02785c 100644 --- a/third_party/WebKit/Source/modules/cachestorage/Cache.cpp +++ b/third_party/WebKit/Source/modules/cachestorage/Cache.cpp
@@ -388,7 +388,7 @@ const RequestInfo& request, const CacheQueryOptions& options, ExceptionState& exception_state) { - ASSERT(!request.isNull()); + DCHECK(!request.isNull()); if (request.isRequest()) return MatchImpl(script_state, request.getAsRequest(), options); Request* new_request = @@ -407,7 +407,7 @@ const RequestInfo& request, const CacheQueryOptions& options, ExceptionState& exception_state) { - ASSERT(!request.isNull()); + DCHECK(!request.isNull()); if (request.isRequest()) return MatchAllImpl(script_state, request.getAsRequest(), options); Request* new_request = @@ -420,7 +420,7 @@ ScriptPromise Cache::add(ScriptState* script_state, const RequestInfo& request, ExceptionState& exception_state) { - ASSERT(!request.isNull()); + DCHECK(!request.isNull()); HeapVector<Member<Request>> requests; if (request.isRequest()) { requests.push_back(request.getAsRequest()); @@ -456,7 +456,7 @@ const RequestInfo& request, const CacheQueryOptions& options, ExceptionState& exception_state) { - ASSERT(!request.isNull()); + DCHECK(!request.isNull()); if (request.isRequest()) return DeleteImpl(script_state, request.getAsRequest(), options); Request* new_request = @@ -470,7 +470,7 @@ const RequestInfo& request, Response* response, ExceptionState& exception_state) { - ASSERT(!request.isNull()); + DCHECK(!request.isNull()); if (request.isRequest()) return PutImpl(script_state, HeapVector<Member<Request>>(1, request.getAsRequest()), @@ -491,7 +491,7 @@ const RequestInfo& request, const CacheQueryOptions& options, ExceptionState& exception_state) { - ASSERT(!request.isNull()); + DCHECK(!request.isNull()); if (request.isRequest()) return KeysImpl(script_state, request.getAsRequest(), options); Request* new_request = @@ -637,7 +637,7 @@ "' is unsupported"); return promise; } - ASSERT(!requests[i]->HasBody()); + DCHECK(!requests[i]->HasBody()); if (VaryHeaderContainsAsterisk(responses[i])) { barrier_callback->OnError("Vary header contains *");
diff --git a/third_party/WebKit/Source/modules/cachestorage/CacheStorage.cpp b/third_party/WebKit/Source/modules/cachestorage/CacheStorage.cpp index edc6154..d02266709 100644 --- a/third_party/WebKit/Source/modules/cachestorage/CacheStorage.cpp +++ b/third_party/WebKit/Source/modules/cachestorage/CacheStorage.cpp
@@ -309,7 +309,7 @@ const RequestInfo& request, const CacheQueryOptions& options, ExceptionState& exception_state) { - ASSERT(!request.isNull()); + DCHECK(!request.isNull()); if (!CommonChecks(script_state, exception_state)) return ScriptPromise();
diff --git a/third_party/WebKit/Source/modules/cachestorage/CacheTest.cpp b/third_party/WebKit/Source/modules/cachestorage/CacheTest.cpp index 49479df..8fc6923 100644 --- a/third_party/WebKit/Source/modules/cachestorage/CacheTest.cpp +++ b/third_party/WebKit/Source/modules/cachestorage/CacheTest.cpp
@@ -322,7 +322,7 @@ } ScriptValue Call(ScriptValue value) override { - ASSERT(!value.IsEmpty()); + DCHECK(!value.IsEmpty()); *value_ = value; return value; } @@ -357,7 +357,7 @@ ErrorWebCacheForTests* test_cache; Cache* cache = CreateCache(fetcher, test_cache = new NotImplementedErrorCache()); - ASSERT(cache); + DCHECK(cache); const String url = "http://www.cachetest.org/"; @@ -390,7 +390,7 @@ ErrorWebCacheForTests* test_cache; Cache* cache = CreateCache(fetcher, test_cache = new NotImplementedErrorCache()); - ASSERT(cache); + DCHECK(cache); const String url = "http://www.cache.arguments.test/"; test_cache->SetExpectedUrl(&url); @@ -405,7 +405,7 @@ options.setCacheName(expected_query_params.cache_name); Request* request = NewRequestFromUrl(url); - ASSERT(request); + DCHECK(request); ScriptPromise match_result = cache->match(GetScriptState(), RequestToRequestInfo(request), options, exception_state); @@ -420,7 +420,7 @@ EXPECT_EQ(kNotImplementedString, GetRejectString(string_match_result)); request = NewRequestFromUrl(url); - ASSERT(request); + DCHECK(request); ScriptPromise match_all_result = cache->matchAll(GetScriptState(), RequestToRequestInfo(request), options, exception_state); @@ -440,7 +440,7 @@ EXPECT_EQ(kNotImplementedString, GetRejectString(keys_result1)); request = NewRequestFromUrl(url); - ASSERT(request); + DCHECK(request); ScriptPromise keys_result2 = cache->keys(GetScriptState(), RequestToRequestInfo(request), options, exception_state); @@ -464,7 +464,7 @@ ErrorWebCacheForTests* test_cache; Cache* cache = CreateCache(fetcher, test_cache = new NotImplementedErrorCache()); - ASSERT(cache); + DCHECK(cache); WebServiceWorkerCache::QueryParams expected_query_params; expected_query_params.cache_name = "this is another cache name"; @@ -475,7 +475,7 @@ const String url = "http://batch.operations.test/"; Request* request = NewRequestFromUrl(url); - ASSERT(request); + DCHECK(request); WebServiceWorkerResponse web_response; std::vector<KURL> url_list; @@ -520,7 +520,7 @@ test_cache->SetExpectedBatchOperations(&expected_put_operations); request = NewRequestFromUrl(url); - ASSERT(request); + DCHECK(request); ScriptPromise put_result = cache->put( GetScriptState(), RequestToRequestInfo(request), response->clone(GetScriptState(), exception_state), exception_state);
diff --git a/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.h b/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.h index 7d9d7c5..6963be6 100644 --- a/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.h +++ b/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.h
@@ -476,7 +476,7 @@ c->setMatrix(ctm); draw_func(c, &foreground_flags); } else { - ASSERT(IsFullCanvasCompositeMode(GetState().GlobalComposite())); + DCHECK(IsFullCanvasCompositeMode(GetState().GlobalComposite())); c->saveLayer(nullptr, &composite_flags); shadow_flags.setBlendMode(SkBlendMode::kSrcOver); c->setMatrix(ctm);
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasStyle.cpp b/third_party/WebKit/Source/modules/canvas2d/CanvasStyle.cpp index c0293a7..43dfce4 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasStyle.cpp +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasStyle.cpp
@@ -99,12 +99,12 @@ : type_(kImagePattern), pattern_(pattern) {} CanvasStyle* CanvasStyle::CreateFromGradient(CanvasGradient* gradient) { - ASSERT(gradient); + DCHECK(gradient); return new CanvasStyle(gradient); } CanvasStyle* CanvasStyle::CreateFromPattern(CanvasPattern* pattern) { - ASSERT(pattern); + DCHECK(pattern); return new CanvasStyle(pattern); }
diff --git a/third_party/WebKit/Source/modules/compositorworker/CompositorWorker.cpp b/third_party/WebKit/Source/modules/compositorworker/CompositorWorker.cpp index 4ed98bfc..656c7d6 100644 --- a/third_party/WebKit/Source/modules/compositorworker/CompositorWorker.cpp +++ b/third_party/WebKit/Source/modules/compositorworker/CompositorWorker.cpp
@@ -23,7 +23,7 @@ CompositorWorker* CompositorWorker::Create(ExecutionContext* context, const String& url, ExceptionState& exception_state) { - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); Document* document = ToDocument(context); if (!document->GetPage()) { exception_state.ThrowDOMException(kInvalidAccessError, @@ -43,7 +43,7 @@ } CompositorWorker::~CompositorWorker() { - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); } const AtomicString& CompositorWorker::InterfaceName() const {
diff --git a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.cpp b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.cpp index 7df5f6c..eaae83a0 100644 --- a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.cpp +++ b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.cpp
@@ -5,6 +5,7 @@ #include "modules/compositorworker/CompositorWorkerGlobalScope.h" #include <memory> +#include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/serialization/SerializedScriptValue.h" #include "core/dom/CompositorWorkerProxyClient.h" #include "core/dom/ExecutionContext.h"
diff --git a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThread.cpp b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThread.cpp index bc363d68..3d0df5b 100644 --- a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThread.cpp +++ b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThread.cpp
@@ -19,7 +19,7 @@ double time_origin) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("compositor-worker"), "CompositorWorkerThread::create"); - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); return WTF::WrapUnique(new CompositorWorkerThread( std::move(worker_loader_proxy), worker_object_proxy, time_origin)); }
diff --git a/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.cpp b/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.cpp index 55dbf25..8336951 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.cpp +++ b/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.cpp
@@ -92,7 +92,7 @@ PasswordCredential::Create(data, exception_state); if (exception_state.HadException()) return nullptr; - ASSERT(credential); + DCHECK(credential); // After creating the Credential, populate its 'additionalData', 'idName', and // 'passwordName' attributes. If the form's 'enctype' is anything other than
diff --git a/third_party/WebKit/Source/modules/crypto/CryptoResultImpl.cpp b/third_party/WebKit/Source/modules/crypto/CryptoResultImpl.cpp index 0396abe..f1463f9b 100644 --- a/third_party/WebKit/Source/modules/crypto/CryptoResultImpl.cpp +++ b/third_party/WebKit/Source/modules/crypto/CryptoResultImpl.cpp
@@ -64,7 +64,7 @@ class CryptoResultImpl::Resolver final : public ScriptPromiseResolver { public: static Resolver* Create(ScriptState* script_state, CryptoResultImpl* result) { - ASSERT(script_state->ContextIsValid()); + DCHECK(script_state->ContextIsValid()); Resolver* resolver = new Resolver(script_state, result); resolver->SuspendIfNeeded(); resolver->KeepAliveWhilePending(); @@ -128,7 +128,7 @@ } CryptoResultImpl::~CryptoResultImpl() { - ASSERT(!resolver_); + DCHECK(!resolver_); } DEFINE_TRACE(CryptoResultImpl) { @@ -226,7 +226,7 @@ } void CryptoResultImpl::Cancel() { - ASSERT(cancel_); + DCHECK(cancel_); cancel_->Cancel(); cancel_.Clear(); ClearResolver();
diff --git a/third_party/WebKit/Source/modules/csspaint/CSSPaintImageGeneratorImpl.cpp b/third_party/WebKit/Source/modules/csspaint/CSSPaintImageGeneratorImpl.cpp index 57746d37..66fa48d 100644 --- a/third_party/WebKit/Source/modules/csspaint/CSSPaintImageGeneratorImpl.cpp +++ b/third_party/WebKit/Source/modules/csspaint/CSSPaintImageGeneratorImpl.cpp
@@ -42,10 +42,10 @@ CSSPaintImageGeneratorImpl::~CSSPaintImageGeneratorImpl() {} void CSSPaintImageGeneratorImpl::SetDefinition(CSSPaintDefinition* definition) { - ASSERT(!definition_); + DCHECK(!definition_); definition_ = definition; - ASSERT(observer_); + DCHECK(observer_); observer_->PaintImageGeneratorReady(); }
diff --git a/third_party/WebKit/Source/modules/csspaint/PaintRenderingContext2D.cpp b/third_party/WebKit/Source/modules/csspaint/PaintRenderingContext2D.cpp index 2dce7e8..8ff2c35 100644 --- a/third_party/WebKit/Source/modules/csspaint/PaintRenderingContext2D.cpp +++ b/third_party/WebKit/Source/modules/csspaint/PaintRenderingContext2D.cpp
@@ -29,12 +29,12 @@ } int PaintRenderingContext2D::Width() const { - ASSERT(image_buffer_); + DCHECK(image_buffer_); return image_buffer_->size().Width(); } int PaintRenderingContext2D::Height() const { - ASSERT(image_buffer_); + DCHECK(image_buffer_); return image_buffer_->size().Height(); } @@ -57,17 +57,17 @@ } PaintCanvas* PaintRenderingContext2D::ExistingDrawingCanvas() const { - ASSERT(image_buffer_); + DCHECK(image_buffer_); return image_buffer_->Canvas(); } AffineTransform PaintRenderingContext2D::BaseTransform() const { - ASSERT(image_buffer_); + DCHECK(image_buffer_); return image_buffer_->BaseTransform(); } void PaintRenderingContext2D::DidDraw(const SkIRect& dirty_rect) { - ASSERT(image_buffer_); + DCHECK(image_buffer_); return image_buffer_->DidDraw(SkRect::Make(dirty_rect)); }
diff --git a/third_party/WebKit/Source/modules/csspaint/PaintWorkletGlobalScope.cpp b/third_party/WebKit/Source/modules/csspaint/PaintWorkletGlobalScope.cpp index 988d9a6..20c8688 100644 --- a/third_party/WebKit/Source/modules/csspaint/PaintWorkletGlobalScope.cpp +++ b/third_party/WebKit/Source/modules/csspaint/PaintWorkletGlobalScope.cpp
@@ -77,7 +77,7 @@ v8::Isolate* isolate = ScriptController()->GetScriptState()->GetIsolate(); v8::Local<v8::Context> context = ScriptController()->GetContext(); - ASSERT(ctor_value.V8Value()->IsFunction()); + DCHECK(ctor_value.V8Value()->IsFunction()); v8::Local<v8::Function> constructor = v8::Local<v8::Function>::Cast(ctor_value.V8Value());
diff --git a/third_party/WebKit/Source/modules/csspaint/PaintWorkletTest.cpp b/third_party/WebKit/Source/modules/csspaint/PaintWorkletTest.cpp index fa235a8..7a9be6568 100644 --- a/third_party/WebKit/Source/modules/csspaint/PaintWorkletTest.cpp +++ b/third_party/WebKit/Source/modules/csspaint/PaintWorkletTest.cpp
@@ -38,11 +38,11 @@ ScriptSourceCode("registerPaint('foo', class { paint() { } });")); CSSPaintDefinition* definition = global_scope->FindDefinition("foo"); - ASSERT(definition); + DCHECK(definition); v8::Isolate* isolate = global_scope->ScriptController()->GetScriptState()->GetIsolate(); - ASSERT(isolate); + DCHECK(isolate); // Set our ScopedPersistent to the paint function, and make weak. ScopedPersistent<v8::Function> handle; @@ -51,13 +51,13 @@ handle.Set(isolate, definition->PaintFunctionForTesting(isolate)); handle.SetPhantom(); } - ASSERT(!handle.IsEmpty()); - ASSERT(handle.IsWeak()); + DCHECK(!handle.IsEmpty()); + DCHECK(handle.IsWeak()); // Run a GC, persistent shouldn't have been collected yet. ThreadState::Current()->CollectAllGarbage(); V8GCController::CollectAllGarbageForTesting(isolate); - ASSERT(!handle.IsEmpty()); + DCHECK(!handle.IsEmpty()); // Delete the page & associated objects. page_.reset(); @@ -65,7 +65,7 @@ // Run a GC, the persistent should have been collected. ThreadState::Current()->CollectAllGarbage(); V8GCController::CollectAllGarbageForTesting(isolate); - ASSERT(handle.IsEmpty()); + DCHECK(handle.IsEmpty()); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/encoding/TextDecoder.cpp b/third_party/WebKit/Source/modules/encoding/TextDecoder.cpp index b552a9bd..26745c83 100644 --- a/third_party/WebKit/Source/modules/encoding/TextDecoder.cpp +++ b/third_party/WebKit/Source/modules/encoding/TextDecoder.cpp
@@ -79,14 +79,14 @@ String TextDecoder::decode(const BufferSource& input, const TextDecodeOptions& options, ExceptionState& exception_state) { - ASSERT(!input.isNull()); + DCHECK(!input.isNull()); if (input.isArrayBufferView()) { const char* start = static_cast<const char*>( input.getAsArrayBufferView().View()->BaseAddress()); size_t length = input.getAsArrayBufferView().View()->byteLength(); return decode(start, length, options, exception_state); } - ASSERT(input.isArrayBuffer()); + DCHECK(input.isArrayBuffer()); const char* start = static_cast<const char*>(input.getAsArrayBuffer()->Data()); size_t length = input.getAsArrayBuffer()->ByteLength();
diff --git a/third_party/WebKit/Source/modules/fetch/BytesConsumerTest.cpp b/third_party/WebKit/Source/modules/fetch/BytesConsumerTest.cpp index 76e513d..4c7bb386 100644 --- a/third_party/WebKit/Source/modules/fetch/BytesConsumerTest.cpp +++ b/third_party/WebKit/Source/modules/fetch/BytesConsumerTest.cpp
@@ -48,7 +48,7 @@ class FakeBlobBytesConsumer : public BytesConsumer { public: explicit FakeBlobBytesConsumer(PassRefPtr<BlobDataHandle> handle) - : blob_handle_(handle) {} + : blob_handle_(std::move(handle)) {} ~FakeBlobBytesConsumer() override {} Result BeginRead(const char** buffer, size_t* available) override {
diff --git a/third_party/WebKit/Source/modules/fetch/BytesConsumerTestUtil.h b/third_party/WebKit/Source/modules/fetch/BytesConsumerTestUtil.h index c70a84bd..4c5d0cf 100644 --- a/third_party/WebKit/Source/modules/fetch/BytesConsumerTestUtil.h +++ b/third_party/WebKit/Source/modules/fetch/BytesConsumerTestUtil.h
@@ -69,7 +69,7 @@ // In mock methods we use RefPtr<> rather than PassRefPtr<>. void DidFetchDataLoadedBlobHandle( PassRefPtr<BlobDataHandle> blob_data_handle) override { - DidFetchDataLoadedBlobHandleMock(blob_data_handle); + DidFetchDataLoadedBlobHandleMock(std::move(blob_data_handle)); } };
diff --git a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp index c09677a..f2fa66b 100644 --- a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp +++ b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp
@@ -99,7 +99,8 @@ class DataConsumerHandleTestUtil::ReplayingHandle::ReaderImpl final : public Reader { public: - ReaderImpl(PassRefPtr<Context> context, Client* client) : context_(context) { + ReaderImpl(PassRefPtr<Context> context, Client* client) + : context_(std::move(context)) { context_->AttachReader(client); } ~ReaderImpl() { context_->DetachReader(); }
diff --git a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.h b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.h index 3fd5bb3..4fa3532 100644 --- a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.h +++ b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.h
@@ -187,7 +187,7 @@ public: ReaderImpl(const String& name, PassRefPtr<Context> context) - : name_(name.IsolatedCopy()), context_(context) { + : name_(name.IsolatedCopy()), context_(std::move(context)) { context_->RecordAttach(name_.IsolatedCopy()); } ~ReaderImpl() override { context_->RecordDetach(name_.IsolatedCopy()); } @@ -218,7 +218,7 @@ private: DataConsumerHandle(const String& name, PassRefPtr<Context> context) - : name_(name.IsolatedCopy()), context_(context) {} + : name_(name.IsolatedCopy()), context_(std::move(context)) {} std::unique_ptr<Reader> ObtainReader(Client*) { return WTF::MakeUnique<ReaderImpl>(name_, context_);
diff --git a/third_party/WebKit/Source/modules/navigatorcontentutils/NavigatorContentUtils.cpp b/third_party/WebKit/Source/modules/navigatorcontentutils/NavigatorContentUtils.cpp index f078654b..384e7fbe 100644 --- a/third_party/WebKit/Source/modules/navigatorcontentutils/NavigatorContentUtils.cpp +++ b/third_party/WebKit/Source/modules/navigatorcontentutils/NavigatorContentUtils.cpp
@@ -147,7 +147,7 @@ return; Document* document = navigator.GetFrame()->GetDocument(); - ASSERT(document); + DCHECK(document); if (!VerifyCustomHandlerURL(*document, url, exception_state)) return; @@ -195,7 +195,7 @@ return declined; Document* document = navigator.GetFrame()->GetDocument(); - ASSERT(document); + DCHECK(document); if (document->IsContextDestroyed()) return declined; @@ -220,7 +220,7 @@ return; Document* document = navigator.GetFrame()->GetDocument(); - ASSERT(document); + DCHECK(document); if (!VerifyCustomHandlerURL(*document, url, exception_state)) return;
diff --git a/third_party/WebKit/Source/modules/netinfo/NavigatorNetworkInformation.cpp b/third_party/WebKit/Source/modules/netinfo/NavigatorNetworkInformation.cpp index d2fe282..b87cf43 100644 --- a/third_party/WebKit/Source/modules/netinfo/NavigatorNetworkInformation.cpp +++ b/third_party/WebKit/Source/modules/netinfo/NavigatorNetworkInformation.cpp
@@ -43,7 +43,7 @@ NetworkInformation* NavigatorNetworkInformation::connection() { if (!connection_ && GetFrame()) { - ASSERT(GetFrame()->DomWindow()); + DCHECK(GetFrame()->DomWindow()); connection_ = NetworkInformation::Create( GetFrame()->DomWindow()->GetExecutionContext()); }
diff --git a/third_party/WebKit/Source/modules/netinfo/NetworkInformation.cpp b/third_party/WebKit/Source/modules/netinfo/NetworkInformation.cpp index d0f4b57..eb7ddec 100644 --- a/third_party/WebKit/Source/modules/netinfo/NetworkInformation.cpp +++ b/third_party/WebKit/Source/modules/netinfo/NetworkInformation.cpp
@@ -47,7 +47,7 @@ } NetworkInformation::~NetworkInformation() { - ASSERT(!observing_); + DCHECK(!observing_); } String NetworkInformation::type() const { @@ -69,7 +69,7 @@ void NetworkInformation::ConnectionChange(WebConnectionType type, double downlink_max_mbps) { - ASSERT(GetExecutionContext()->IsContextThread()); + DCHECK(GetExecutionContext()->IsContextThread()); // This can happen if the observer removes and then adds itself again // during notification. @@ -111,7 +111,7 @@ void NetworkInformation::RemoveAllEventListeners() { EventTargetWithInlineData::RemoveAllEventListeners(); - ASSERT(!HasEventListeners()); + DCHECK(!HasEventListeners()); StopObserving(); }
diff --git a/third_party/WebKit/Source/modules/netinfo/WorkerNavigatorNetworkInformation.cpp b/third_party/WebKit/Source/modules/netinfo/WorkerNavigatorNetworkInformation.cpp index fde821b..c18a94b 100644 --- a/third_party/WebKit/Source/modules/netinfo/WorkerNavigatorNetworkInformation.cpp +++ b/third_party/WebKit/Source/modules/netinfo/WorkerNavigatorNetworkInformation.cpp
@@ -55,7 +55,7 @@ NetworkInformation* WorkerNavigatorNetworkInformation::connection( ExecutionContext* context) { - ASSERT(context); + DCHECK(context); if (!connection_) connection_ = NetworkInformation::Create(context); return connection_.Get();
diff --git a/third_party/WebKit/Source/modules/plugins/PluginOcclusionSupport.cpp b/third_party/WebKit/Source/modules/plugins/PluginOcclusionSupport.cpp index 745a0ef..4a7503c 100644 --- a/third_party/WebKit/Source/modules/plugins/PluginOcclusionSupport.cpp +++ b/third_party/WebKit/Source/modules/plugins/PluginOcclusionSupport.cpp
@@ -110,7 +110,7 @@ if (ro == ro2) return true; } - ASSERT(false); // We should have seen ro1 and ro2 by now. + NOTREACHED(); // We should have seen ro1 and ro2 by now. return false; } } @@ -158,7 +158,7 @@ const IntRect& frame_rect, Vector<IntRect>& occlusions) { LayoutObject* plugin_node = element->GetLayoutObject(); - ASSERT(plugin_node); + DCHECK(plugin_node); if (!plugin_node->Style()) return; Vector<const LayoutObject*> plugin_zstack;
diff --git a/third_party/WebKit/Source/modules/presentation/Presentation.cpp b/third_party/WebKit/Source/modules/presentation/Presentation.cpp index d29a2ba..bc08402a9 100644 --- a/third_party/WebKit/Source/modules/presentation/Presentation.cpp +++ b/third_party/WebKit/Source/modules/presentation/Presentation.cpp
@@ -19,10 +19,10 @@ // static Presentation* Presentation::Create(LocalFrame* frame) { - ASSERT(frame); + DCHECK(frame); Presentation* presentation = new Presentation(frame); PresentationController* controller = PresentationController::From(*frame); - ASSERT(controller); + DCHECK(controller); controller->SetPresentation(presentation); return presentation; }
diff --git a/third_party/WebKit/Source/modules/presentation/PresentationAvailability.cpp b/third_party/WebKit/Source/modules/presentation/PresentationAvailability.cpp index 2f08e51f..a6be63d 100644 --- a/third_party/WebKit/Source/modules/presentation/PresentationAvailability.cpp +++ b/third_party/WebKit/Source/modules/presentation/PresentationAvailability.cpp
@@ -54,7 +54,7 @@ urls_(urls), value_(value), state_(State::kActive) { - ASSERT(execution_context->IsDocument()); + DCHECK(execution_context->IsDocument()); WebVector<WebURL> data(urls.size()); for (size_t i = 0; i < urls.size(); ++i) data[i] = WebURL(urls[i]);
diff --git a/third_party/WebKit/Source/modules/presentation/PresentationAvailabilityCallbacks.cpp b/third_party/WebKit/Source/modules/presentation/PresentationAvailabilityCallbacks.cpp index 621be7c..d32fbe0 100644 --- a/third_party/WebKit/Source/modules/presentation/PresentationAvailabilityCallbacks.cpp +++ b/third_party/WebKit/Source/modules/presentation/PresentationAvailabilityCallbacks.cpp
@@ -17,7 +17,7 @@ PresentationAvailabilityProperty* resolver, const Vector<KURL>& urls) : resolver_(resolver), urls_(urls) { - ASSERT(resolver_); + DCHECK(resolver_); } PresentationAvailabilityCallbacks::~PresentationAvailabilityCallbacks() {}
diff --git a/third_party/WebKit/Source/modules/presentation/PresentationConnection.cpp b/third_party/WebKit/Source/modules/presentation/PresentationConnection.cpp index eab4646..9afc9f60 100644 --- a/third_party/WebKit/Source/modules/presentation/PresentationConnection.cpp +++ b/third_party/WebKit/Source/modules/presentation/PresentationConnection.cpp
@@ -156,7 +156,7 @@ proxy_(nullptr) {} PresentationConnection::~PresentationConnection() { - ASSERT(!blob_loader_); + DCHECK(!blob_loader_); } void PresentationConnection::BindProxy( @@ -170,9 +170,9 @@ ScriptPromiseResolver* resolver, const WebPresentationInfo& presentation_info, PresentationRequest* request) { - ASSERT(resolver); - ASSERT(request); - ASSERT(resolver->GetExecutionContext()->IsDocument()); + DCHECK(resolver); + DCHECK(request); + DCHECK(resolver->GetExecutionContext()->IsDocument()); Document* document = ToDocument(resolver->GetExecutionContext()); if (!document->GetFrame()) @@ -191,8 +191,8 @@ PresentationController* controller, const WebPresentationInfo& presentation_info, PresentationRequest* request) { - ASSERT(controller); - ASSERT(request); + DCHECK(controller); + DCHECK(request); PresentationConnection* connection = new PresentationConnection( controller->GetFrame(), presentation_info.id, presentation_info.url); @@ -294,7 +294,7 @@ } void PresentationConnection::send(Blob* data, ExceptionState& exception_state) { - ASSERT(data); + DCHECK(data); if (!CanSendMessage(exception_state)) return; @@ -332,7 +332,7 @@ messages_.pop_front(); break; case kMessageTypeBlob: - ASSERT(!blob_loader_); + DCHECK(!blob_loader_); blob_loader_ = new BlobLoader(message->blob_data_handle, this); break; }
diff --git a/third_party/WebKit/Source/modules/presentation/PresentationConnectionCallbacks.cpp b/third_party/WebKit/Source/modules/presentation/PresentationConnectionCallbacks.cpp index cd9d0896..68d95e02 100644 --- a/third_party/WebKit/Source/modules/presentation/PresentationConnectionCallbacks.cpp +++ b/third_party/WebKit/Source/modules/presentation/PresentationConnectionCallbacks.cpp
@@ -19,8 +19,8 @@ ScriptPromiseResolver* resolver, PresentationRequest* request) : resolver_(resolver), request_(request), connection_(nullptr) { - ASSERT(resolver_); - ASSERT(request_); + DCHECK(resolver_); + DCHECK(request_); } void PresentationConnectionCallbacks::OnSuccess(
diff --git a/third_party/WebKit/Source/modules/screen_orientation/ScreenOrientation.cpp b/third_party/WebKit/Source/modules/screen_orientation/ScreenOrientation.cpp index 341149d..c32e72d 100644 --- a/third_party/WebKit/Source/modules/screen_orientation/ScreenOrientation.cpp +++ b/third_party/WebKit/Source/modules/screen_orientation/ScreenOrientation.cpp
@@ -93,7 +93,7 @@ // static ScreenOrientation* ScreenOrientation::Create(LocalFrame* frame) { - ASSERT(frame); + DCHECK(frame); // Check if the ScreenOrientationController is supported for the // frame. It will not be for all LocalFrames, or the frame may @@ -102,7 +102,7 @@ return nullptr; ScreenOrientation* orientation = new ScreenOrientation(frame); - ASSERT(orientation->Controller()); + DCHECK(orientation->Controller()); // FIXME: ideally, we would like to provide the ScreenOrientationController // the case where it is not defined but for the moment, it is eagerly // created when the LocalFrame is created so we shouldn't be in that
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchRespondWithObserver.cpp b/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchRespondWithObserver.cpp index feb359e..3c4a4deb 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchRespondWithObserver.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchRespondWithObserver.cpp
@@ -28,7 +28,7 @@ void ForeignFetchRespondWithObserver::OnResponseFulfilled( const ScriptValue& value) { - ASSERT(GetExecutionContext()); + DCHECK(GetExecutionContext()); ExceptionState exception_state(value.GetIsolate(), ExceptionState::kUnknownContext, "ForeignFetchEvent", "respondWith");
diff --git a/third_party/WebKit/Source/modules/serviceworkers/RespondWithObserver.cpp b/third_party/WebKit/Source/modules/serviceworkers/RespondWithObserver.cpp index 2ec1b57..19c6f1e 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/RespondWithObserver.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/RespondWithObserver.cpp
@@ -44,7 +44,7 @@ resolve_type_(type) {} ScriptValue Call(ScriptValue value) override { - ASSERT(observer_); + DCHECK(observer_); ASSERT(resolve_type_ == kFulfilled || resolve_type_ == kRejected); if (resolve_type_ == kRejected) { observer_->ResponseWasRejected( @@ -76,7 +76,7 @@ void RespondWithObserver::DidDispatchEvent( DispatchEventResult dispatch_result) { - ASSERT(GetExecutionContext()); + DCHECK(GetExecutionContext()); if (state_ != kInitial) return;
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorker.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorker.cpp index a8c4118..5456aea 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorker.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorker.cpp
@@ -155,7 +155,7 @@ : AbstractWorker(execution_context), handle_(std::move(handle)), was_stopped_(false) { - ASSERT(handle_); + DCHECK(handle_); handle_->ServiceWorker()->SetProxy(this); }
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainer.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainer.cpp index 210f2bc..938a10f 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainer.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainer.cpp
@@ -132,7 +132,7 @@ } ServiceWorkerContainer::~ServiceWorkerContainer() { - ASSERT(!provider_); + DCHECK(!provider_); } void ServiceWorkerContainer::ContextDestroyed(ExecutionContext*) {
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeClient.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeClient.cpp index 9292088..1b324091 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeClient.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeClient.cpp
@@ -42,7 +42,7 @@ ServiceWorkerGlobalScopeClient* ServiceWorkerGlobalScopeClient::From( ExecutionContext* context) { WorkerClients* clients = ToWorkerGlobalScope(context)->Clients(); - ASSERT(clients); + DCHECK(clients); return static_cast<ServiceWorkerGlobalScopeClient*>( Supplement<WorkerClients>::From(clients, SupplementName())); }
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerRegistration.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerRegistration.cpp index 96ba626..d25cec8e 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerRegistration.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerRegistration.cpp
@@ -66,7 +66,7 @@ ServiceWorkerRegistration* ServiceWorkerRegistration::GetOrCreate( ExecutionContext* execution_context, std::unique_ptr<WebServiceWorkerRegistration::Handle> handle) { - ASSERT(handle); + DCHECK(handle); ServiceWorkerRegistration* existing_registration = static_cast<ServiceWorkerRegistration*>(handle->Registration()->Proxy()); @@ -133,8 +133,8 @@ : ContextLifecycleObserver(execution_context), handle_(std::move(handle)), stopped_(false) { - ASSERT(handle_); - ASSERT(!handle_->Registration()->Proxy()); + DCHECK(handle_); + DCHECK(!handle_->Registration()->Proxy()); if (!execution_context) return;
diff --git a/third_party/WebKit/Source/modules/serviceworkers/WaitUntilObserver.cpp b/third_party/WebKit/Source/modules/serviceworkers/WaitUntilObserver.cpp index 839f336a..72cb101 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/WaitUntilObserver.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/WaitUntilObserver.cpp
@@ -62,7 +62,7 @@ resolve_type_(type) {} ScriptValue Call(ScriptValue value) override { - ASSERT(observer_); + DCHECK(observer_); ASSERT(resolve_type_ == kFulfilled || resolve_type_ == kRejected); if (resolve_type_ == kRejected) { observer_->ReportError(value);
diff --git a/third_party/WebKit/Source/modules/speech/SpeechRecognition.cpp b/third_party/WebKit/Source/modules/speech/SpeechRecognition.cpp index 7d8a9cbe..21c26a62 100644 --- a/third_party/WebKit/Source/modules/speech/SpeechRecognition.cpp +++ b/third_party/WebKit/Source/modules/speech/SpeechRecognition.cpp
@@ -39,7 +39,7 @@ SpeechRecognition* SpeechRecognition::Create(ExecutionContext* context) { ASSERT(context && context->IsDocument()); Document* document = ToDocument(context); - ASSERT(document); + DCHECK(document); return new SpeechRecognition(document->GetPage(), context); }
diff --git a/third_party/WebKit/Source/modules/speech/SpeechSynthesis.cpp b/third_party/WebKit/Source/modules/speech/SpeechSynthesis.cpp index b587a1e..2541781 100644 --- a/third_party/WebKit/Source/modules/speech/SpeechSynthesis.cpp +++ b/third_party/WebKit/Source/modules/speech/SpeechSynthesis.cpp
@@ -86,7 +86,7 @@ void SpeechSynthesis::StartSpeakingImmediately() { SpeechSynthesisUtterance* utterance = CurrentSpeechUtterance(); - ASSERT(utterance); + DCHECK(utterance); utterance->SetStartTime(MonotonicallyIncreasingTime()); is_paused_ = false; @@ -94,7 +94,7 @@ } void SpeechSynthesis::speak(SpeechSynthesisUtterance* utterance) { - ASSERT(utterance); + DCHECK(utterance); utterance_queue_.push_back(utterance); @@ -138,7 +138,7 @@ void SpeechSynthesis::HandleSpeakingCompleted( SpeechSynthesisUtterance* utterance, bool error_occurred) { - ASSERT(utterance); + DCHECK(utterance); bool should_start_speaking = false; // If the utterance that completed was the one we're currently speaking,
diff --git a/third_party/WebKit/Source/modules/speech/testing/PlatformSpeechSynthesizerMock.cpp b/third_party/WebKit/Source/modules/speech/testing/PlatformSpeechSynthesizerMock.cpp index e30b1a67..d5feafb 100644 --- a/third_party/WebKit/Source/modules/speech/testing/PlatformSpeechSynthesizerMock.cpp +++ b/third_party/WebKit/Source/modules/speech/testing/PlatformSpeechSynthesizerMock.cpp
@@ -51,14 +51,14 @@ PlatformSpeechSynthesizerMock::~PlatformSpeechSynthesizerMock() {} void PlatformSpeechSynthesizerMock::SpeakingErrorOccurred(TimerBase*) { - ASSERT(current_utterance_); + DCHECK(current_utterance_); Client()->SpeakingErrorOccurred(current_utterance_); SpeakNext(); } void PlatformSpeechSynthesizerMock::SpeakingFinished(TimerBase*) { - ASSERT(current_utterance_); + DCHECK(current_utterance_); Client()->DidFinishSpeaking(current_utterance_); SpeakNext(); } @@ -99,7 +99,7 @@ } void PlatformSpeechSynthesizerMock::SpeakNow() { - ASSERT(current_utterance_); + DCHECK(current_utterance_); Client()->DidStartSpeaking(current_utterance_); // Fire a fake word and then sentence boundary event.
diff --git a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp index 9a8fcfb..f91cec74 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp
@@ -198,8 +198,8 @@ } void WebGL2RenderingContextBase::InitializeNewContext() { - ASSERT(!isContextLost()); - ASSERT(GetDrawingBuffer()); + DCHECK(!isContextLost()); + DCHECK(GetDrawingBuffer()); read_framebuffer_binding_ = nullptr; @@ -695,7 +695,7 @@ WebGLFramebuffer* read_framebuffer_binding = GetFramebufferBinding(GL_READ_FRAMEBUFFER); if (!read_framebuffer_binding) { - ASSERT(GetDrawingBuffer()); + DCHECK(GetDrawingBuffer()); if (mode != GL_BACK && mode != GL_NONE) { SynthesizeGLError(GL_INVALID_OPERATION, "readBuffer", "invalid read buffer"); @@ -807,7 +807,7 @@ // Due to WebGL's same-origin restrictions, it is not possible to // taint the origin using the WebGL API. - ASSERT(canvas()->OriginClean()); + DCHECK(canvas()->OriginClean()); if (!ValidateValueFitNonNegInt32("readPixels", "offset", offset)) return; @@ -4557,7 +4557,7 @@ const char* function_name, WebGLProgram* program, GLuint block_index) { - ASSERT(program); + DCHECK(program); if (!program->LinkStatus(this)) { SynthesizeGLError(GL_INVALID_OPERATION, function_name, "program not linked"); @@ -4967,13 +4967,13 @@ bool WebGL2RenderingContextBase::IsBufferBoundToTransformFeedback( WebGLBuffer* buffer) { - ASSERT(buffer); + DCHECK(buffer); return transform_feedback_binding_->IsBufferBoundToTransformFeedback(buffer); } bool WebGL2RenderingContextBase::IsBufferBoundToNonTransformFeedback( WebGLBuffer* buffer) { - ASSERT(buffer); + DCHECK(buffer); if (bound_array_buffer_ == buffer || bound_vertex_array_object_->BoundElementArrayBuffer() == buffer || @@ -4995,7 +4995,7 @@ const char* function_name, GLenum target, WebGLBuffer* buffer) { - ASSERT(buffer); + DCHECK(buffer); switch (buffer->GetInitialTarget()) { case GL_ELEMENT_ARRAY_BUFFER:
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLActiveInfo.h b/third_party/WebKit/Source/modules/webgl/WebGLActiveInfo.h index c0e68f43..ca091066 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLActiveInfo.h +++ b/third_party/WebKit/Source/modules/webgl/WebGLActiveInfo.h
@@ -48,9 +48,9 @@ private: WebGLActiveInfo(const String& name, GLenum type, GLint size) : name_(name), type_(type), size_(size) { - ASSERT(name.length()); - ASSERT(type); - ASSERT(size); + DCHECK(name.length()); + DCHECK(type); + DCHECK(size); } String name_; GLenum type_;
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLBuffer.cpp b/third_party/WebKit/Source/modules/webgl/WebGLBuffer.cpp index 42d8869..0ec9adbc 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLBuffer.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGLBuffer.cpp
@@ -53,7 +53,7 @@ void WebGLBuffer::SetInitialTarget(GLenum target) { // WebGL restricts the ability to bind buffers to multiple targets based on // it's initial bind point. - ASSERT(!initial_target_); + DCHECK(!initial_target_); initial_target_ = target; }
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLFramebuffer.cpp b/third_party/WebKit/Source/modules/webgl/WebGLFramebuffer.cpp index a4d00d3e..a001e4e 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLFramebuffer.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGLFramebuffer.cpp
@@ -316,7 +316,7 @@ void WebGLFramebuffer::RemoveAttachmentFromBoundFramebuffer( GLenum target, WebGLSharedObject* attachment) { - ASSERT(IsBound(target)); + DCHECK(IsBound(target)); if (!object_) return; if (!attachment)
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLObject.cpp b/third_party/WebKit/Source/modules/webgl/WebGLObject.cpp index b6abc8a4..8c84b43 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLObject.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGLObject.cpp
@@ -60,7 +60,7 @@ if (gl) { DeleteObjectImpl(gl); // Ensure the inherited class no longer claims to have a valid object - ASSERT(!HasObject()); + DCHECK(!HasObject()); } } }
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLQuery.cpp b/third_party/WebKit/Source/modules/webgl/WebGLQuery.cpp index 9bdf904..98f62d8 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLQuery.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGLQuery.cpp
@@ -33,8 +33,8 @@ } void WebGLQuery::SetTarget(GLenum target) { - ASSERT(Object()); - ASSERT(!target_); + DCHECK(Object()); + DCHECK(!target_); target_ = target; }
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp index 4d8304c..aac68e9 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp
@@ -191,9 +191,9 @@ return nullptr; WebGLRenderingContextBase* candidate = *(ActiveContexts().begin()); - ASSERT(!candidate->isContextLost()); + DCHECK(!candidate->isContextLost()); for (WebGLRenderingContextBase* context : ActiveContexts()) { - ASSERT(!context->isContextLost()); + DCHECK(!context->isContextLost()); if (context->ContextGL()->GetLastFlushIdCHROMIUM() < candidate->ContextGL()->GetLastFlushIdCHROMIUM()) { candidate = context; @@ -231,7 +231,7 @@ removed_contexts++; } - ASSERT(!context->isContextLost()); + DCHECK(!context->isContextLost()); ActiveContexts().insert(context); } @@ -255,8 +255,8 @@ WebGLRenderingContextBase* context) { // These two sets keep weak references to their contexts; // verify that the GC already removed the |context| entries. - ASSERT(!ForciblyEvictedContexts().Contains(context)); - ASSERT(!ActiveContexts().Contains(context)); + DCHECK(!ForciblyEvictedContexts().Contains(context)); + DCHECK(!ActiveContexts().Contains(context)); unsigned max_gl_contexts = CurrentMaxGLContexts(); // Try to re-enable the oldest inactive contexts. @@ -591,7 +591,7 @@ static void CreateContextProviderOnMainThread( ContextProviderCreationInfo* creation_info, WaitableEvent* waitable_event) { - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); creation_info->created_context_provider = Platform::Current()->CreateOffscreenGraphicsContext3DProvider( creation_info->context_attributes, creation_info->url, 0, @@ -1038,7 +1038,7 @@ is_ext_srgb_formats_types_added_(false), is_ext_color_buffer_float_formats_added_(false), version_(version) { - ASSERT(context_provider); + DCHECK(context_provider); context_group_->AddContext(this); @@ -1115,8 +1115,8 @@ } void WebGLRenderingContextBase::InitializeNewContext() { - ASSERT(!isContextLost()); - ASSERT(GetDrawingBuffer()); + DCHECK(!isContextLost()); + DCHECK(GetDrawingBuffer()); marked_canvas_dirty_ = false; animation_frame_in_progress_ = false; @@ -1256,7 +1256,7 @@ } void WebGLRenderingContextBase::SetupFlags() { - ASSERT(GetDrawingBuffer()); + DCHECK(GetDrawingBuffer()); if (canvas()) { if (Page* p = canvas()->GetDocument().GetPage()) { synthesized_errors_to_console_ = @@ -1319,7 +1319,7 @@ ConvertToBaseCallback(std::move(null_function))); GetDrawingBuffer()->AddNewMailboxCallback(nullptr); - ASSERT(GetDrawingBuffer()); + DCHECK(GetDrawingBuffer()); drawing_buffer_->BeginDestruction(); drawing_buffer_.Clear(); } @@ -1483,7 +1483,7 @@ if (!hidden && isContextLost() && restore_allowed_ && auto_recovery_method_ == kAuto) { - ASSERT(!restore_timer_.IsActive()); + DCHECK(!restore_timer_.IsActive()); restore_timer_.StartOneShot(0, BLINK_FROM_HERE); } } @@ -3979,7 +3979,7 @@ } } else { if (read_buffer_of_default_framebuffer_ == GL_NONE) { - ASSERT(IsWebGL2OrHigher()); + DCHECK(IsWebGL2OrHigher()); SynthesizeGLError(GL_INVALID_OPERATION, function_name, "no image to read from"); return false; @@ -4165,9 +4165,9 @@ GLsizei width, GLsizei height, const char* function_name) { - ASSERT(!samples); // |samples| > 0 is only valid in WebGL2's + DCHECK(!samples); // |samples| > 0 is only valid in WebGL2's // renderbufferStorageMultisample(). - ASSERT(!IsWebGL2OrHigher()); // Make sure this is overridden in WebGL 2. + DCHECK(!IsWebGL2OrHigher()); // Make sure this is overridden in WebGL 2. switch (internalformat) { case GL_DEPTH_COMPONENT16: case GL_RGBA4: @@ -4188,7 +4188,7 @@ renderbuffer_binding_->SetSize(width, height); break; case GL_DEPTH_STENCIL_OES: - ASSERT(IsDepthStencilSupported()); + DCHECK(IsDepthStencilSupported()); ContextGL()->RenderbufferStorage(target, GL_DEPTH24_STENCIL8_OES, width, height); renderbuffer_binding_->SetSize(width, height); @@ -4559,7 +4559,7 @@ int height, const char* function_name) { RefPtr<Image> image(std::move(pass_image)); - ASSERT(image); + DCHECK(image); IntSize size(width, height); ImageBuffer* buf = generated_image_cache_.GetImageBuffer(size); @@ -5405,7 +5405,7 @@ level, internalformat, width, height, depth, 0, format, type, xoffset, yoffset, zoffset)) return; - ASSERT(bitmap->BitmapImage()); + DCHECK(bitmap->BitmapImage()); // TODO(kbr): make this work for sub-rectangles of ImageBitmaps. if (function_id != kTexSubImage3D && function_id != kTexImage3D && @@ -7462,7 +7462,7 @@ } void WebGLRenderingContextBase::MaybeRestoreContext(TimerBase*) { - ASSERT(isContextLost()); + DCHECK(isContextLost()); // The rendering context is not restored unless the default behavior of the // webglcontextlost event was prevented earlier.
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLUniformLocation.cpp b/third_party/WebKit/Source/modules/webgl/WebGLUniformLocation.cpp index 842b6984..2aeb45a 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLUniformLocation.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGLUniformLocation.cpp
@@ -36,7 +36,7 @@ WebGLUniformLocation::WebGLUniformLocation(WebGLProgram* program, GLint location) : program_(program), location_(location) { - ASSERT(program_); + DCHECK(program_); link_count_ = program_->LinkCount(); }
diff --git a/third_party/WebKit/Source/modules/webusb/USBAlternateInterface.cpp b/third_party/WebKit/Source/modules/webusb/USBAlternateInterface.cpp index 8b6d8f7..9eac61f 100644 --- a/third_party/WebKit/Source/modules/webusb/USBAlternateInterface.cpp +++ b/third_party/WebKit/Source/modules/webusb/USBAlternateInterface.cpp
@@ -32,7 +32,7 @@ USBAlternateInterface::USBAlternateInterface(const USBInterface* interface, size_t alternate_index) : interface_(interface), alternate_index_(alternate_index) { - ASSERT(interface_); + DCHECK(interface_); ASSERT(alternate_index_ < interface_->Info().alternates.size()); }
diff --git a/third_party/WebKit/Source/modules/webusb/USBConfiguration.cpp b/third_party/WebKit/Source/modules/webusb/USBConfiguration.cpp index 9623955..05ab6eb 100644 --- a/third_party/WebKit/Source/modules/webusb/USBConfiguration.cpp +++ b/third_party/WebKit/Source/modules/webusb/USBConfiguration.cpp
@@ -31,7 +31,7 @@ USBConfiguration::USBConfiguration(const USBDevice* device, size_t configuration_index) : device_(device), configuration_index_(configuration_index) { - ASSERT(device_); + DCHECK(device_); ASSERT(configuration_index_ < device_->Info().configurations.size()); }
diff --git a/third_party/WebKit/Source/modules/webusb/USBDevice.cpp b/third_party/WebKit/Source/modules/webusb/USBDevice.cpp index 63296201..03bd0ff3 100644 --- a/third_party/WebKit/Source/modules/webusb/USBDevice.cpp +++ b/third_party/WebKit/Source/modules/webusb/USBDevice.cpp
@@ -87,7 +87,7 @@ Vector<uint8_t> ConvertBufferSource( const ArrayBufferOrArrayBufferView& buffer) { - ASSERT(!buffer.isNull()); + DCHECK(!buffer.isNull()); Vector<uint8_t> vector; if (buffer.isArrayBuffer()) vector.Append(static_cast<uint8_t*>(buffer.getAsArrayBuffer()->Data()),
diff --git a/third_party/WebKit/Source/modules/webusb/USBEndpoint.cpp b/third_party/WebKit/Source/modules/webusb/USBEndpoint.cpp index 3f63ecd..4c25e8c 100644 --- a/third_party/WebKit/Source/modules/webusb/USBEndpoint.cpp +++ b/third_party/WebKit/Source/modules/webusb/USBEndpoint.cpp
@@ -71,7 +71,7 @@ USBEndpoint::USBEndpoint(const USBAlternateInterface* alternate, size_t endpoint_index) : alternate_(alternate), endpoint_index_(endpoint_index) { - ASSERT(alternate_); + DCHECK(alternate_); ASSERT(endpoint_index_ < alternate_->Info().endpoints.size()); }
diff --git a/third_party/WebKit/Source/platform/TimerTest.cpp b/third_party/WebKit/Source/platform/TimerTest.cpp index 9cbc0d2..ee46d223 100644 --- a/third_party/WebKit/Source/platform/TimerTest.cpp +++ b/third_party/WebKit/Source/platform/TimerTest.cpp
@@ -97,7 +97,7 @@ }; explicit OnHeapTimerOwner(PassRefPtr<Record> record) - : timer_(this, &OnHeapTimerOwner::Fired), record_(record) {} + : timer_(this, &OnHeapTimerOwner::Fired), record_(std::move(record)) {} ~OnHeapTimerOwner() { record_->SetOwnerIsDestructed(); } void StartOneShot(double interval, const WebTraceLocation& caller) {
diff --git a/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp b/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp index ecec9e6..f1509884 100644 --- a/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp
@@ -69,7 +69,7 @@ public: Canvas2DLayerBridgePtr() {} Canvas2DLayerBridgePtr(PassRefPtr<Canvas2DLayerBridge> layer_bridge) - : layer_bridge_(layer_bridge) {} + : layer_bridge_(std::move(layer_bridge)) {} ~Canvas2DLayerBridgePtr() { Clear(); } @@ -82,7 +82,7 @@ void operator=(PassRefPtr<Canvas2DLayerBridge> layer_bridge) { DCHECK(!layer_bridge_); - layer_bridge_ = layer_bridge; + layer_bridge_ = std::move(layer_bridge); } Canvas2DLayerBridge* operator->() { return layer_bridge_.Get(); }
diff --git a/third_party/WebKit/Source/platform/wtf/AssertionsTest.cpp b/third_party/WebKit/Source/platform/wtf/AssertionsTest.cpp index ee6a2e12..930c0283 100644 --- a/third_party/WebKit/Source/platform/wtf/AssertionsTest.cpp +++ b/third_party/WebKit/Source/platform/wtf/AssertionsTest.cpp
@@ -13,7 +13,7 @@ TEST(AssertionsTest, Assertions) { DCHECK(true); #if DCHECK_IS_ON() - EXPECT_DEATH_IF_SUPPORTED(ASSERT(false), ""); + EXPECT_DEATH_IF_SUPPORTED(DCHECK(false), ""); EXPECT_DEATH_IF_SUPPORTED(NOTREACHED(), ""); #endif
diff --git a/third_party/WebKit/Source/platform/wtf/PassRefPtr.h b/third_party/WebKit/Source/platform/wtf/PassRefPtr.h index 0547aea..f36ee84d 100644 --- a/third_party/WebKit/Source/platform/wtf/PassRefPtr.h +++ b/third_party/WebKit/Source/platform/wtf/PassRefPtr.h
@@ -74,7 +74,7 @@ PassRefPtr(T* ptr) : ptr_(ptr) { RefIfNotNull(ptr); } PassRefPtr(PassRefPtr&& o) : ptr_(o.LeakRef()) {} template <typename U> - PassRefPtr(const PassRefPtr<U>& o, EnsurePtrConvertibleArgDecl(U, T)) + PassRefPtr(PassRefPtr<U>&& o, EnsurePtrConvertibleArgDecl(U, T)) : ptr_(o.LeakRef()) {} ALWAYS_INLINE ~PassRefPtr() { DerefIfNotNull(ptr_); }
diff --git a/third_party/WebKit/Source/platform/wtf/dtoa/bignum-dtoa.cc b/third_party/WebKit/Source/platform/wtf/dtoa/bignum-dtoa.cc index bee7cf3..4c377d0 100644 --- a/third_party/WebKit/Source/platform/wtf/dtoa/bignum-dtoa.cc +++ b/third_party/WebKit/Source/platform/wtf/dtoa/bignum-dtoa.cc
@@ -36,7 +36,7 @@ namespace double_conversion { static int NormalizedExponent(uint64_t significand, int exponent) { - ASSERT(significand != 0); + DCHECK_NE(significand, 0u); while ((significand & Double::kHiddenBit) == 0) { significand = significand << 1; exponent = exponent - 1; @@ -87,7 +87,7 @@ void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits, Vector<char> buffer, int* length, int* decimal_point) { - ASSERT(v > 0); + DCHECK_GT(v, 0); DCHECK(!Double(v).IsSpecial()); uint64_t significand = Double(v).Significand(); bool is_even = (significand & 1) == 0; @@ -118,7 +118,7 @@ // 4e-324. In this case the denominator needs fewer than 324*4 binary digits. // The maximum double is 1.7976931348623157e308 which needs fewer than // 308*4 binary digits. - ASSERT(Bignum::kMaxSignificantBits >= 324*4); + DCHECK_GE(Bignum::kMaxSignificantBits, 324*4); bool need_boundary_deltas = (mode == BIGNUM_DTOA_SHORTEST); InitialScaledStartValues(v, estimated_power, need_boundary_deltas, &numerator, &denominator, @@ -178,7 +178,7 @@ while (true) { uint16_t digit; digit = numerator->DivideModuloIntBignum(*denominator); - ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive. + DCHECK_LE(digit, 9u); // digit is a uint16_t and therefore always positive. // digit = numerator / denominator (integer division). // numerator = numerator % denominator. buffer[(*length)++] = static_cast<char>(digit + '0'); @@ -224,7 +224,7 @@ // loop would have stopped earlier. // We still have an assert here in case the preconditions were not // satisfied. - ASSERT(buffer[(*length) - 1] != '9'); + DCHECK_NE(buffer[(*length) - 1], '9'); buffer[(*length) - 1]++; } else { // Halfway case. @@ -235,7 +235,7 @@ if ((buffer[(*length) - 1] - '0') % 2 == 0) { // Round down => Do nothing. } else { - ASSERT(buffer[(*length) - 1] != '9'); + DCHECK_NE(buffer[(*length) - 1], '9'); buffer[(*length) - 1]++; } } @@ -249,7 +249,7 @@ // stopped the loop earlier. // We still have an ASSERT here, in case the preconditions were not // satisfied. - ASSERT(buffer[(*length) -1] != '9'); + DCHECK_NE(buffer[(*length) -1], '9'); buffer[(*length) - 1]++; return; } @@ -266,11 +266,11 @@ static void GenerateCountedDigits(int count, int* decimal_point, Bignum* numerator, Bignum* denominator, Vector<char>(buffer), int* length) { - ASSERT(count >= 0); + DCHECK_GE(count, 0); for (int i = 0; i < count - 1; ++i) { uint16_t digit; digit = numerator->DivideModuloIntBignum(*denominator); - ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive. + DCHECK_LE(digit, 9u); // digit is a uint16_t and therefore always positive. // digit = numerator / denominator (integer division). // numerator = numerator % denominator. buffer[i] = static_cast<char>(digit + '0'); @@ -323,7 +323,7 @@ } else if (-(*decimal_point) == requested_digits) { // We only need to verify if the number rounds down or up. // Ex: 0.04 and 0.06 with requested_digits == 1. - ASSERT(*decimal_point == -requested_digits); + DCHECK_EQ(*decimal_point, -requested_digits); // Initially the fraction lies in range (1, 10]. Multiply the denominator // by 10 so that we can compare more easily. denominator->Times10(); @@ -402,7 +402,7 @@ Bignum* numerator, Bignum* denominator, Bignum* delta_minus, Bignum* delta_plus) { // A positive exponent implies a positive power. - ASSERT(estimated_power >= 0); + DCHECK_GE(estimated_power, 0); // Since the estimated_power is positive we simply multiply the denominator // by 10^estimated_power. @@ -521,7 +521,7 @@ // numerator = v * 10^-estimated_power * 2 * 2^-exponent. // Remember: numerator has been abused as power_ten. So no need to assign it // to itself. - ASSERT(numerator == power_ten); + DCHECK_EQ(numerator, power_ten); numerator->MultiplyByUInt64(significand); // denominator = 2 * 2^-exponent with exponent < 0.
diff --git a/third_party/WebKit/Source/platform/wtf/dtoa/bignum.cc b/third_party/WebKit/Source/platform/wtf/dtoa/bignum.cc index dce8d39e..b551709 100644 --- a/third_party/WebKit/Source/platform/wtf/dtoa/bignum.cc +++ b/third_party/WebKit/Source/platform/wtf/dtoa/bignum.cc
@@ -48,7 +48,7 @@ // Guaranteed to lie in one Bigit. void Bignum::AssignUInt16(uint16_t value) { - ASSERT(kBigitSize >= BitSize(value)); + DCHECK_GE(kBigitSize, BitSize(value)); Zero(); if (value == 0) return; @@ -94,7 +94,8 @@ uint64_t result = 0; for (int i = from; i < from + digits_to_read; ++i) { int digit = buffer[i] - '0'; - ASSERT(0 <= digit && digit <= 9); + DCHECK_LE(0, digit); + DCHECK_LE(digit, 9); result = result * 10 + digit; } return result; @@ -192,7 +193,7 @@ EnsureCapacity(1 + Max(BigitLength(), other.BigitLength()) - exponent_); Chunk carry = 0; int bigit_pos = other.exponent_ - exponent_; - ASSERT(bigit_pos >= 0); + DCHECK_GE(bigit_pos, 0); for (int i = 0; i < other.used_digits_; ++i) { Chunk sum = bigits_[bigit_pos] + other.bigits_[i] + carry; bigits_[bigit_pos] = sum & kBigitMask; @@ -215,7 +216,7 @@ DCHECK(IsClamped()); DCHECK(other.IsClamped()); // We require this to be bigger than other. - ASSERT(LessEqual(other, *this)); + DCHECK(LessEqual(other, *this)); Align(other); @@ -223,7 +224,7 @@ Chunk borrow = 0; int i; for (i = 0; i < other.used_digits_; ++i) { - ASSERT((borrow == 0) || (borrow == 1)); + DCHECK((borrow == 0) || (borrow == 1)); Chunk difference = bigits_[i + offset] - other.bigits_[i] - borrow; bigits_[i + offset] = difference & kBigitMask; borrow = difference >> (kChunkSize - 1); @@ -257,7 +258,7 @@ // The product of a bigit with the factor is of size kBigitSize + 32. // Assert that this number + 1 (for the carry) fits into double chunk. - ASSERT(kDoubleChunkSize >= kBigitSize + 32 + 1); + DCHECK_GE(kDoubleChunkSize, kBigitSize + 32 + 1); DoubleChunk carry = 0; for (int i = 0; i < used_digits_; ++i) { DoubleChunk product = static_cast<DoubleChunk>(factor) * bigits_[i] + carry; @@ -279,7 +280,7 @@ Zero(); return; } - ASSERT(kBigitSize < 32); + DCHECK_LT(kBigitSize, 32); uint64_t carry = 0; uint64_t low = factor & 0xFFFFFFFF; uint64_t high = factor >> 32; @@ -319,7 +320,7 @@ { kFive1, kFive2, kFive3, kFive4, kFive5, kFive6, kFive7, kFive8, kFive9, kFive10, kFive11, kFive12 }; - ASSERT(exponent >= 0); + DCHECK_GE(exponent, 0); if (exponent == 0) return; if (used_digits_ == 0) return; @@ -404,7 +405,7 @@ } // Since the result was guaranteed to lie inside the number the // accumulator must be 0 now. - ASSERT(accumulator == 0); + DCHECK_EQ(accumulator, 0u); // Don't forget to update the used_digits and the exponent. used_digits_ = product_length; @@ -414,8 +415,8 @@ void Bignum::AssignPowerUInt16(uint16_t base, int power_exponent) { - ASSERT(base != 0); - ASSERT(power_exponent >= 0); + DCHECK_NE(base, 0); + DCHECK_GE(power_exponent, 0); if (power_exponent == 0) { AssignUInt16(1); return; @@ -490,7 +491,7 @@ uint16_t Bignum::DivideModuloIntBignum(const Bignum& other) { DCHECK(IsClamped()); DCHECK(other.IsClamped()); - ASSERT(other.used_digits_ > 0); + DCHECK_GT(other.used_digits_, 0); // Easy case: if we have less digits than the divisor than the result is // 0. Note: this handles the case where this == 0, too. @@ -508,14 +509,14 @@ // This naive approach is extremely inefficient if the this divided other // might be big. This function is implemented for doubleToString where // the result should be small (less than 10). - ASSERT(other.bigits_[other.used_digits_ - 1] >= ((1 << kBigitSize) / 16)); + DCHECK_GE(other.bigits_[other.used_digits_ - 1], ((1u << kBigitSize) / 16)); // Remove the multiples of the first digit. // Example this = 23 and other equals 9. -> Remove 2 multiples. result += static_cast<uint16_t>(bigits_[used_digits_ - 1]); SubtractTimes(other, bigits_[used_digits_ - 1]); } - ASSERT(BigitLength() == other.BigitLength()); + DCHECK_EQ(BigitLength(), other.BigitLength()); // Both bignums are at the same length now. // Since other has more than 0 digits we know that the access to @@ -552,7 +553,7 @@ template<typename S> static int SizeInHexChars(S number) { - ASSERT(number > 0); + DCHECK_GT(number, 0u); int result = 0; while (number != 0) { number >>= 4; @@ -563,7 +564,8 @@ static char HexCharOfValue(uint8_t value) { - ASSERT(0 <= value && value <= 16); + DCHECK_LE(0, value); + DCHECK_LE(value, 16); if (value < 10) return value + '0'; return value - 10 + 'A'; } @@ -572,7 +574,7 @@ bool Bignum::ToHexString(char* buffer, int buffer_size) const { DCHECK(IsClamped()); // Each bigit must be printable as separate hex-character. - ASSERT(kBigitSize % 4 == 0); + DCHECK_EQ(kBigitSize % 4, 0); const int kHexCharsPerBigit = kBigitSize / 4; if (used_digits_ == 0) { @@ -720,15 +722,15 @@ } used_digits_ += zero_digits; exponent_ -= zero_digits; - ASSERT(used_digits_ >= 0); - ASSERT(exponent_ >= 0); + DCHECK_GE(used_digits_, 0); + DCHECK_GE(exponent_, 0); } } void Bignum::BigitsShiftLeft(int shift_amount) { - ASSERT(shift_amount < kBigitSize); - ASSERT(shift_amount >= 0); + DCHECK_LT(shift_amount, kBigitSize); + DCHECK_GE(shift_amount, 0); Chunk carry = 0; for (int i = 0; i < used_digits_; ++i) { Chunk new_carry = bigits_[i] >> (kBigitSize - shift_amount); @@ -743,7 +745,7 @@ void Bignum::SubtractTimes(const Bignum& other, int factor) { - ASSERT(exponent_ <= other.exponent_); + DCHECK_LE(exponent_, other.exponent_); if (factor < 3) { for (int i = 0; i < factor; ++i) { SubtractBignum(other);
diff --git a/third_party/WebKit/Source/platform/wtf/dtoa/cached-powers.cc b/third_party/WebKit/Source/platform/wtf/dtoa/cached-powers.cc index 1eeb8494..8ce1c869 100644 --- a/third_party/WebKit/Source/platform/wtf/dtoa/cached-powers.cc +++ b/third_party/WebKit/Source/platform/wtf/dtoa/cached-powers.cc
@@ -143,13 +143,13 @@ // Check that the static constants match the values in kCachedPowers. static void ValidateStaticConstants() { - ASSERT(kCachedPowersOffset == -kCachedPowers[0].decimal_exponent); - ASSERT(PowersOfTenCache::kDecimalExponentDistance == + DCHECK_EQ(kCachedPowersOffset, -kCachedPowers[0].decimal_exponent); + DCHECK_EQ(PowersOfTenCache::kDecimalExponentDistance, (kCachedPowers[1].decimal_exponent - kCachedPowers[0].decimal_exponent)); - ASSERT(PowersOfTenCache::kMinDecimalExponent == + DCHECK_EQ(PowersOfTenCache::kMinDecimalExponent, kCachedPowers[0].decimal_exponent); - ASSERT(PowersOfTenCache::kMaxDecimalExponent == + DCHECK_EQ(PowersOfTenCache::kMaxDecimalExponent, kCachedPowers[kCachedPowersLength - 1].decimal_exponent); } #endif @@ -167,10 +167,13 @@ int foo = kCachedPowersOffset; int index = (foo + static_cast<int>(k) - 1) / kDecimalExponentDistance + 1; - ASSERT(0 <= index && index < kCachedPowersLength); + DCHECK_LE(0, index); +#if DCHECK_IS_ON() + DCHECK_LT(index, kCachedPowersLength); +#endif CachedPower cached_power = kCachedPowers[index]; - ASSERT(min_exponent <= cached_power.binary_exponent); - ASSERT(cached_power.binary_exponent <= max_exponent); + DCHECK_LE(min_exponent, cached_power.binary_exponent); + DCHECK_LE(cached_power.binary_exponent, max_exponent); *decimal_exponent = cached_power.decimal_exponent; *power = DiyFp(cached_power.significand, cached_power.binary_exponent); } @@ -179,8 +182,8 @@ void PowersOfTenCache::GetCachedPowerForDecimalExponent(int requested_exponent, DiyFp* power, int* found_exponent) { - ASSERT(kMinDecimalExponent <= requested_exponent); - ASSERT(requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance); + DCHECK_LE(kMinDecimalExponent, requested_exponent); + DCHECK_LT(requested_exponent, kMaxDecimalExponent + kDecimalExponentDistance); #if DCHECK_IS_ON() ValidateStaticConstants(); #endif @@ -189,8 +192,8 @@ CachedPower cached_power = kCachedPowers[index]; *power = DiyFp(cached_power.significand, cached_power.binary_exponent); *found_exponent = cached_power.decimal_exponent; - ASSERT(*found_exponent <= requested_exponent); - ASSERT(requested_exponent < *found_exponent + kDecimalExponentDistance); + DCHECK_LE(*found_exponent, requested_exponent); + DCHECK_LT(requested_exponent, *found_exponent + kDecimalExponentDistance); } } // namespace double_conversion
diff --git a/third_party/WebKit/Source/platform/wtf/dtoa/double-conversion.cc b/third_party/WebKit/Source/platform/wtf/dtoa/double-conversion.cc index 15a6384..110acd0 100644 --- a/third_party/WebKit/Source/platform/wtf/dtoa/double-conversion.cc +++ b/third_party/WebKit/Source/platform/wtf/dtoa/double-conversion.cc
@@ -78,7 +78,7 @@ int length, int exponent, StringBuilder* result_builder) const { - ASSERT(length != 0); + DCHECK_NE(length, 0); result_builder->AddCharacter(decimal_digits[0]); if (length != 1) { result_builder->AddCharacter('.'); @@ -97,7 +97,7 @@ result_builder->AddCharacter('0'); return; } - ASSERT(exponent < 1e4); + DCHECK_LT(exponent, 1e4); const int kMaxExponentLength = 5; char buffer[kMaxExponentLength + 1]; int first_char_pos = kMaxExponentLength; @@ -124,7 +124,7 @@ if (digits_after_point > 0) { result_builder->AddCharacter('.'); result_builder->AddPadding('0', -decimal_point); - ASSERT(length <= digits_after_point - (-decimal_point)); + DCHECK_LE(length, digits_after_point - (-decimal_point)); result_builder->AddSubstring(decimal_digits, length); int remaining_digits = digits_after_point - (-decimal_point) - length; result_builder->AddPadding('0', remaining_digits); @@ -139,10 +139,10 @@ } } else { // "decima.l_rep000" - ASSERT(digits_after_point > 0); + DCHECK_GT(digits_after_point, 0); result_builder->AddSubstring(decimal_digits, decimal_point); result_builder->AddCharacter('.'); - ASSERT(length - decimal_point <= digits_after_point); + DCHECK_LE(length - decimal_point, digits_after_point); result_builder->AddSubstring(&decimal_digits[decimal_point], length - decimal_point); int remaining_digits = digits_after_point - (length - decimal_point); @@ -197,7 +197,7 @@ bool DoubleToStringConverter::ToFixed(double value, int requested_digits, StringBuilder* result_builder) const { - ASSERT(kMaxFixedDigitsBeforePoint == 60); + DCHECK_EQ(kMaxFixedDigitsBeforePoint, 60); const double kFirstNonFixed = 1e60; if (Double(value).IsSpecial()) { @@ -245,7 +245,7 @@ bool sign; // Add space for digit before the decimal point and the '\0' character. const int kDecimalRepCapacity = kMaxExponentialDigits + 2; - ASSERT(kDecimalRepCapacity > kBase10MaximalLength); + DCHECK_GT(kDecimalRepCapacity, kBase10MaximalLength); char decimal_rep[kDecimalRepCapacity]; int decimal_rep_length; @@ -257,7 +257,7 @@ DoubleToAscii(value, PRECISION, requested_digits + 1, decimal_rep, kDecimalRepCapacity, &sign, &decimal_rep_length, &decimal_point); - ASSERT(decimal_rep_length <= requested_digits + 1); + DCHECK_LE(decimal_rep_length, requested_digits + 1); for (int i = decimal_rep_length; i < requested_digits + 1; ++i) { decimal_rep[i] = '0'; @@ -301,7 +301,7 @@ DoubleToAscii(value, PRECISION, precision, decimal_rep, kDecimalRepCapacity, &sign, &decimal_rep_length, &decimal_point); - ASSERT(decimal_rep_length <= precision); + DCHECK_LE(decimal_rep_length, precision); bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0); if (sign && (value != 0.0 || !unique_zero)) { @@ -359,7 +359,7 @@ int* point) { Vector<char> vector(buffer, buffer_length); DCHECK(!Double(v).IsSpecial()); - ASSERT(mode == SHORTEST || requested_digits >= 0); + DCHECK(mode == SHORTEST || requested_digits >= 0); if (Double(v).Sign() < 0) { *sign = true; @@ -482,7 +482,7 @@ // Copy significant digits of the integer part (if any) to the buffer. while (*current >= '0' && *current <= '9') { if (significant_digits < kMaxSignificantDigits) { - ASSERT(buffer_pos < kBufferSize); + DCHECK_LT(buffer_pos, kBufferSize); buffer[buffer_pos++] = static_cast<char>(*current); significant_digits++; } else { @@ -519,7 +519,7 @@ // There is a fractional part. while (*current >= '0' && *current <= '9') { if (significant_digits < kMaxSignificantDigits) { - ASSERT(buffer_pos < kBufferSize); + DCHECK_LT(buffer_pos, kBufferSize); buffer[buffer_pos++] = static_cast<char>(*current); significant_digits++; exponent--; @@ -565,7 +565,8 @@ } const int max_exponent = INT_MAX / 2; - ASSERT(-max_exponent / 2 <= exponent && exponent <= max_exponent / 2); + DCHECK_LE(-max_exponent / 2, exponent); + DCHECK_LE(exponent, max_exponent / 2); int num = 0; do { // Check overflow. @@ -590,7 +591,7 @@ exponent--; } - ASSERT(buffer_pos < kBufferSize); + DCHECK_LT(buffer_pos, kBufferSize); buffer[buffer_pos] = '\0'; double converted = Strtod(Vector<const char>(buffer, buffer_pos), exponent);
diff --git a/third_party/WebKit/Source/platform/wtf/dtoa/fast-dtoa.cc b/third_party/WebKit/Source/platform/wtf/dtoa/fast-dtoa.cc index a2613ca..f58d186 100644 --- a/third_party/WebKit/Source/platform/wtf/dtoa/fast-dtoa.cc +++ b/third_party/WebKit/Source/platform/wtf/dtoa/fast-dtoa.cc
@@ -140,7 +140,7 @@ // Conceptually rest ~= too_high - buffer // We need to do the following tests in this order to avoid over- and // underflows. - ASSERT(rest <= unsafe_interval); + DCHECK_LE(rest, unsafe_interval); while (rest < small_distance && // Negated condition 1 unsafe_interval - rest >= ten_kappa && // Negated condition 2 (rest + ten_kappa < small_distance || // buffer{-1} > w_high @@ -186,7 +186,7 @@ uint64_t ten_kappa, uint64_t unit, int* kappa) { - ASSERT(rest < ten_kappa); + DCHECK_LT(rest, ten_kappa); // The following tests are done in a specific order to avoid overflows. They // will work correctly with any uint64 values of rest < ten_kappa and unit. // @@ -241,7 +241,7 @@ int number_bits, uint32_t* power, int* exponent) { - ASSERT(number < (uint32_t)(1 << (number_bits + 1))); + DCHECK_LT(number, (uint32_t)(1 << (number_bits + 1))); switch (number_bits) { case 32: @@ -387,10 +387,11 @@ Vector<char> buffer, int* length, int* kappa) { - ASSERT(low.E() == w.E() && w.E() == high.E()); - ASSERT(low.F() + 1 <= high.F() - 1); - ASSERT(kMinimalTargetExponent <= w.E() && - w.E() <= kMaximalTargetExponent); + DCHECK_EQ(low.E(), w.E()); + DCHECK_EQ(w.E(), high.E()); + DCHECK_LE(low.F() + 1, high.F() - 1); + DCHECK_LE(kMinimalTargetExponent, w.E()); + DCHECK_LE(w.E(), kMaximalTargetExponent); // low, w and high are imprecise, but by less than one ulp (unit in the // last place). If we remove (resp. add) 1 ulp from low (resp. high) we // are certain that the new numbers are outside of the interval we want @@ -456,9 +457,9 @@ // data (like the interval or 'unit'), too. // Note that the multiplication by 10 does not overflow, because w.e >= -60 // and thus one.e >= -60. - ASSERT(one.E() >= -60); - ASSERT(fractionals < one.F()); - ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.F()); + DCHECK_GE(one.E(), -60); + DCHECK_LT(fractionals, one.F()); + DCHECK_GE(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10, one.F()); while (true) { fractionals *= 10; unit *= 10; @@ -512,10 +513,10 @@ Vector<char> buffer, int* length, int* kappa) { - ASSERT(kMinimalTargetExponent <= w.E() && - w.E() <= kMaximalTargetExponent); - ASSERT(kMinimalTargetExponent >= -60); - ASSERT(kMaximalTargetExponent <= -32); + DCHECK_LE(kMinimalTargetExponent, w.E()); + DCHECK_LE(w.E(), kMaximalTargetExponent); + DCHECK_GE(kMinimalTargetExponent, -60); + DCHECK_LE(kMaximalTargetExponent, -32); // w is assumed to have an error less than 1 unit. Whenever w is scaled we // also scale its error. uint64_t w_error = 1; @@ -567,9 +568,9 @@ // data (the 'unit'), too. // Note that the multiplication by 10 does not overflow, because w.e >= -60 // and thus one.e >= -60. - ASSERT(one.E() >= -60); - ASSERT(fractionals < one.F()); - ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.F()); + DCHECK_GE(one.E(), -60); + DCHECK_LT(fractionals, one.F()); + DCHECK_GE(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10, one.F()); while (requested_digits > 0 && fractionals > w_error) { fractionals *= 10; w_error *= 10; @@ -609,7 +610,7 @@ // Grisu3 will never output representations that lie exactly on a boundary. DiyFp boundary_minus, boundary_plus; Double(v).NormalizedBoundaries(&boundary_minus, &boundary_plus); - ASSERT(boundary_plus.E() == w.E()); + DCHECK_EQ(boundary_plus.E(), w.E()); DiyFp ten_mk; // Cached power of ten: 10^-k int mk; // -k int ten_mk_minimal_binary_exponent = @@ -620,10 +621,10 @@ ten_mk_minimal_binary_exponent, ten_mk_maximal_binary_exponent, &ten_mk, &mk); - ASSERT((kMinimalTargetExponent <= - w.E() + ten_mk.E() + DiyFp::kSignificandSize) && - (kMaximalTargetExponent >= - w.E() + ten_mk.E() + DiyFp::kSignificandSize)); + DCHECK_LE(kMinimalTargetExponent, + w.E() + ten_mk.E() + DiyFp::kSignificandSize); + DCHECK_GE(kMaximalTargetExponent, + w.E() + ten_mk.E() + DiyFp::kSignificandSize); // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a // 64 bit significand and ten_mk is thus only precise up to 64 bits. @@ -634,8 +635,8 @@ // In other words: let f = scaled_w.f() and e = scaled_w.e(), then // (f-1) * 2^e < w*10^k < (f+1) * 2^e DiyFp scaled_w = DiyFp::Times(w, ten_mk); - ASSERT(scaled_w.E() == - boundary_plus.E() + ten_mk.E() + DiyFp::kSignificandSize); + DCHECK_EQ(scaled_w.E(), + boundary_plus.E() + ten_mk.E() + DiyFp::kSignificandSize); // In theory it would be possible to avoid some recomputations by computing // the difference between w and boundary_minus/plus (a power of 2) and to // compute scaled_boundary_minus/plus by subtracting/adding from @@ -679,10 +680,10 @@ ten_mk_minimal_binary_exponent, ten_mk_maximal_binary_exponent, &ten_mk, &mk); - ASSERT((kMinimalTargetExponent <= - w.E() + ten_mk.E() + DiyFp::kSignificandSize) && - (kMaximalTargetExponent >= - w.E() + ten_mk.E() + DiyFp::kSignificandSize)); + DCHECK_LE(kMinimalTargetExponent, + w.E() + ten_mk.E() + DiyFp::kSignificandSize); + DCHECK_GE(kMaximalTargetExponent, + w.E() + ten_mk.E() + DiyFp::kSignificandSize); // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a // 64 bit significand and ten_mk is thus only precise up to 64 bits. @@ -713,7 +714,7 @@ Vector<char> buffer, int* length, int* decimal_point) { - ASSERT(v > 0); + DCHECK_GT(v, 0); DCHECK(!Double(v).IsSpecial()); bool result = false;
diff --git a/third_party/WebKit/Source/platform/wtf/dtoa/fixed-dtoa.cc b/third_party/WebKit/Source/platform/wtf/dtoa/fixed-dtoa.cc index f01d3d9a..231af21 100644 --- a/third_party/WebKit/Source/platform/wtf/dtoa/fixed-dtoa.cc +++ b/third_party/WebKit/Source/platform/wtf/dtoa/fixed-dtoa.cc
@@ -55,11 +55,12 @@ accumulator >>= 32; accumulator = accumulator + (high_bits_ >> 32) * multiplicand; high_bits_ = (accumulator << 32) + part; - ASSERT((accumulator >> 32) == 0); + DCHECK_EQ((accumulator >> 32), 0u); } void Shift(int shift_amount) { - ASSERT(-64 <= shift_amount && shift_amount <= 64); + DCHECK_LE(-64, shift_amount); + DCHECK_LE(shift_amount, 64); if (shift_amount == 0) { return; } else if (shift_amount == -64) { @@ -232,7 +233,8 @@ static void FillFractionals(uint64_t fractionals, int exponent, int fractional_count, Vector<char> buffer, int* length, int* decimal_point) { - ASSERT(-128 <= exponent && exponent <= 0); + DCHECK_LE(-128, exponent); + DCHECK_LE(exponent, 0); // 'fractionals' is a fixed-point number, with binary point at bit // (-exponent). Inside the function the non-converted remainder of fractionals // is a fixed-point number, with binary point at bit 'point'. @@ -264,7 +266,8 @@ RoundUp(buffer, length, decimal_point); } } else { // We need 128 bits. - ASSERT(64 < -exponent && -exponent <= 128); + DCHECK_LT(64, -exponent); + DCHECK_LE(-exponent, 128); UInt128 fractionals128 = UInt128(fractionals, 0); fractionals128.Shift(-exponent - 64); int point = 128; @@ -382,7 +385,7 @@ } else if (exponent < -128) { // This configuration (with at most 20 digits) means that all digits must be // 0. - ASSERT(fractional_count <= 20); + DCHECK_LE(fractional_count, 20); buffer[0] = '\0'; *length = 0; *decimal_point = -fractional_count;
diff --git a/third_party/WebKit/Source/platform/wtf/dtoa/strtod.cc b/third_party/WebKit/Source/platform/wtf/dtoa/strtod.cc index 6a841c4..3746aa7 100644 --- a/third_party/WebKit/Source/platform/wtf/dtoa/strtod.cc +++ b/third_party/WebKit/Source/platform/wtf/dtoa/strtod.cc
@@ -119,7 +119,7 @@ } // The input buffer has been trimmed. Therefore the last digit must be // different from '0'. - ASSERT(buffer[buffer.length() - 1] != '0'); + DCHECK_NE(buffer[buffer.length() - 1], '0'); // Set the last digit to be non-zero. This is sufficient to guarantee // correct rounding. significant_buffer[kMaxSignificantDecimalDigits - 1] = '1'; @@ -138,7 +138,8 @@ int i = 0; while (i < buffer.length() && result <= (kMaxUint64 / 10 - 1)) { int digit = buffer[i++] - '0'; - ASSERT(0 <= digit && digit <= 9); + DCHECK_LE(0, digit); + DCHECK_LE(digit, 9); result = 10 * result + digit; } *number_of_read_digits = i; @@ -194,14 +195,14 @@ if (exponent < 0 && -exponent < kExactPowersOfTenSize) { // 10^-exponent fits into a double. *result = static_cast<double>(ReadUint64(trimmed, &read_digits)); - ASSERT(read_digits == trimmed.length()); + DCHECK_EQ(read_digits, trimmed.length()); *result /= exact_powers_of_ten[-exponent]; return true; } if (0 <= exponent && exponent < kExactPowersOfTenSize) { // 10^exponent fits into a double. *result = static_cast<double>(ReadUint64(trimmed, &read_digits)); - ASSERT(read_digits == trimmed.length()); + DCHECK_EQ(read_digits, trimmed.length()); *result *= exact_powers_of_ten[exponent]; return true; } @@ -213,7 +214,7 @@ // 10^remaining_digits. As a result the remaining exponent now fits // into a double too. *result = static_cast<double>(ReadUint64(trimmed, &read_digits)); - ASSERT(read_digits == trimmed.length()); + DCHECK_EQ(read_digits, trimmed.length()); *result *= exact_powers_of_ten[remaining_digits]; *result *= exact_powers_of_ten[exponent - remaining_digits]; return true; @@ -226,11 +227,11 @@ // Returns 10^exponent as an exact DiyFp. // The given exponent must be in the range [1; kDecimalExponentDistance[. static DiyFp AdjustmentPowerOfTen(int exponent) { - ASSERT(0 < exponent); - ASSERT(exponent < PowersOfTenCache::kDecimalExponentDistance); + DCHECK_LT(0, exponent); + DCHECK_LT(exponent, PowersOfTenCache::kDecimalExponentDistance); // Simply hardcode the remaining powers for the given decimal exponent // distance. - ASSERT(PowersOfTenCache::kDecimalExponentDistance == 8); + DCHECK_EQ(PowersOfTenCache::kDecimalExponentDistance, 8); switch (exponent) { case 1: return DiyFp(UINT64_2PART_C(0xa0000000, 00000000), -60); case 2: return DiyFp(UINT64_2PART_C(0xc8000000, 00000000), -57); @@ -270,7 +271,7 @@ input.Normalize(); error <<= old_e - input.E(); - ASSERT(exponent <= PowersOfTenCache::kMaxDecimalExponent); + DCHECK_LE(exponent, PowersOfTenCache::kMaxDecimalExponent); if (exponent < PowersOfTenCache::kMinDecimalExponent) { *result = 0.0; return true; @@ -288,7 +289,7 @@ if (kMaxUint64DecimalDigits - buffer.length() >= adjustment_exponent) { // The product of input with the adjustment power fits into a 64 bit // integer. - ASSERT(DiyFp::kSignificandSize == 64); + DCHECK_EQ(DiyFp::kSignificandSize, 64); } else { // The adjustment power is exact. There is hence only an error of 0.5. error += kDenominator / 2; @@ -330,8 +331,8 @@ precision_digits_count -= shift_amount; } // We use uint64_ts now. This only works if the DiyFp uses uint64_ts too. - ASSERT(DiyFp::kSignificandSize == 64); - ASSERT(precision_digits_count < 64); + DCHECK_EQ(DiyFp::kSignificandSize, 64); + DCHECK_LT(precision_digits_count, 64); uint64_t one64 = 1; uint64_t precision_bits_mask = (one64 << precision_digits_count) - 1; uint64_t precision_bits = input.F() & precision_bits_mask; @@ -375,14 +376,14 @@ DiyFp upper_boundary = Double(guess).UpperBoundary(); - ASSERT(buffer.length() + exponent <= kMaxDecimalPower + 1); - ASSERT(buffer.length() + exponent > kMinDecimalPower); - ASSERT(buffer.length() <= kMaxSignificantDecimalDigits); + DCHECK_LE(buffer.length() + exponent, kMaxDecimalPower + 1); + DCHECK_GT(buffer.length() + exponent, kMinDecimalPower); + DCHECK_LE(buffer.length(), kMaxSignificantDecimalDigits); // Make sure that the Bignum will be able to hold all our numbers. // Our Bignum implementation has a separate field for exponents. Shifts will // consume at most one bigit (< 64 bits). // ln(10) == 3.3219... - ASSERT(((kMaxDecimalPower + 1) * 333 / 100) < Bignum::kMaxSignificantBits); + DCHECK_LT(((kMaxDecimalPower + 1) * 333 / 100), Bignum::kMaxSignificantBits); Bignum input; Bignum boundary; input.AssignDecimalString(buffer);
diff --git a/third_party/WebKit/Source/web/EditorClientImpl.cpp b/third_party/WebKit/Source/web/EditorClientImpl.cpp index 79ab7993..e6f71c6 100644 --- a/third_party/WebKit/Source/web/EditorClientImpl.cpp +++ b/third_party/WebKit/Source/web/EditorClientImpl.cpp
@@ -29,9 +29,9 @@ #include "core/editing/SelectionType.h" #include "core/exported/WebViewBase.h" #include "core/frame/ContentSettingsClient.h" +#include "core/frame/WebLocalFrameBase.h" #include "public/web/WebFrameClient.h" #include "public/web/WebViewClient.h" -#include "web/WebLocalFrameImpl.h" namespace blink { @@ -41,7 +41,7 @@ void EditorClientImpl::RespondToChangedSelection(LocalFrame* frame, SelectionType selection_type) { - WebLocalFrameImpl* web_frame = WebLocalFrameImpl::FromFrame(frame); + WebLocalFrameBase* web_frame = WebLocalFrameBase::FromFrame(frame); if (web_frame->Client()) web_frame->Client()->DidChangeSelection(selection_type != kRangeSelection); } @@ -66,7 +66,7 @@ } bool EditorClientImpl::HandleKeyboardEvent(LocalFrame* frame) { - WebLocalFrameImpl* web_frame = WebLocalFrameImpl::FromFrame(frame); + WebLocalFrameBase* web_frame = WebLocalFrameBase::FromFrame(frame); return web_frame->Client()->HandleCurrentKeyboardEvent(); }
diff --git a/third_party/WebKit/Source/web/WebDOMMessageEvent.cpp b/third_party/WebKit/Source/web/WebDOMMessageEvent.cpp index a64ffa5..de5de44d 100644 --- a/third_party/WebKit/Source/web/WebDOMMessageEvent.cpp +++ b/third_party/WebKit/Source/web/WebDOMMessageEvent.cpp
@@ -39,7 +39,6 @@ #include "public/web/WebDocument.h" #include "public/web/WebFrame.h" #include "public/web/WebSerializedScriptValue.h" -#include "web/WebLocalFrameImpl.h" namespace blink {
diff --git a/third_party/WebKit/Source/web/tests/FrameTestHelpers.cpp b/third_party/WebKit/Source/web/tests/FrameTestHelpers.cpp index 4a0fd3c..7d6cbf11 100644 --- a/third_party/WebKit/Source/web/tests/FrameTestHelpers.cpp +++ b/third_party/WebKit/Source/web/tests/FrameTestHelpers.cpp
@@ -95,6 +95,11 @@ return &client; } +TestWebViewClient* DefaultWebViewClient() { + DEFINE_STATIC_LOCAL(TestWebViewClient, client, ()); + return &client; +} + } // namespace void LoadFrame(WebFrame* frame, const std::string& url) { @@ -196,10 +201,8 @@ if (!web_frame_client) web_frame_client = DefaultWebFrameClient(); - if (!web_view_client) { - owned_test_web_view_client_ = WTF::MakeUnique<TestWebViewClient>(); - web_view_client = owned_test_web_view_client_.get(); - } + if (!web_view_client) + web_view_client = DefaultWebViewClient(); if (!web_widget_client) web_widget_client = web_view_client->WidgetClient(); web_view_ = static_cast<WebViewBase*>(
diff --git a/third_party/WebKit/Source/web/tests/FrameTestHelpers.h b/third_party/WebKit/Source/web/tests/FrameTestHelpers.h index 1899419..0cf8943 100644 --- a/third_party/WebKit/Source/web/tests/FrameTestHelpers.h +++ b/third_party/WebKit/Source/web/tests/FrameTestHelpers.h
@@ -242,8 +242,6 @@ WebViewBase* web_view_; SettingOverrider* setting_overrider_; UseMockScrollbarSettings mock_scrollbar_settings_; - // Non-null if the WebViewHelper owns the TestWebViewClient. - std::unique_ptr<TestWebViewClient> owned_test_web_view_client_; TestWebViewClient* test_web_view_client_; };
diff --git a/third_party/WebKit/Source/web/tests/MHTMLTest.cpp b/third_party/WebKit/Source/web/tests/MHTMLTest.cpp index b1fc822..3b3cfe6e 100644 --- a/third_party/WebKit/Source/web/tests/MHTMLTest.cpp +++ b/third_party/WebKit/Source/web/tests/MHTMLTest.cpp
@@ -112,7 +112,7 @@ void AddResource(const char* url, const char* mime, PassRefPtr<SharedBuffer> data) { - SerializedResource resource(ToKURL(url), mime, data); + SerializedResource resource(ToKURL(url), mime, std::move(data)); resources_.push_back(resource); }
diff --git a/third_party/WebKit/Source/web/tests/ScreenWakeLockTest.cpp b/third_party/WebKit/Source/web/tests/ScreenWakeLockTest.cpp index 816cfc2..2ad6aa65 100644 --- a/third_party/WebKit/Source/web/tests/ScreenWakeLockTest.cpp +++ b/third_party/WebKit/Source/web/tests/ScreenWakeLockTest.cpp
@@ -51,6 +51,10 @@ // mojom::WakeLockService void RequestWakeLock() override { registry_->SetWakeLockStatus(true); } void CancelWakeLock() override { registry_->SetWakeLockStatus(false); } + void AddClient( + device::mojom::blink::WakeLockServiceRequest wake_lock) override {} + void HasWakeLockForTests( + const HasWakeLockForTestsCallback& callback) override {} mojo::Binding<WakeLockService> binding_; MockInterfaceProvider* const registry_;
diff --git a/third_party/WebKit/Source/web/tests/WebDocumentSubresourceFilterTest.cpp b/third_party/WebKit/Source/web/tests/WebDocumentSubresourceFilterTest.cpp index fafaf552..08119de 100644 --- a/third_party/WebKit/Source/web/tests/WebDocumentSubresourceFilterTest.cpp +++ b/third_party/WebKit/Source/web/tests/WebDocumentSubresourceFilterTest.cpp
@@ -4,6 +4,9 @@ #include "public/platform/WebDocumentSubresourceFilter.h" +#include <string> +#include <vector> + #include "core/dom/Element.h" #include "core/html/HTMLImageElement.h" #include "platform/testing/URLTestHelpers.h" @@ -43,6 +46,8 @@ void ReportDisallowedLoad() override {} + bool ShouldLogToConsole() override { return false; } + const std::vector<std::string>& QueriedSubresourcePaths() const { return queried_subresource_paths_; }
diff --git a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp index 11314f5..7d90d5e 100644 --- a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp +++ b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp
@@ -6845,85 +6845,70 @@ class TestAccessInitialDocumentWebFrameClient : public FrameTestHelpers::TestWebFrameClient { public: - virtual void DidAccessInitialDocument() { ++did_access_initial_document_; } + TestAccessInitialDocumentWebFrameClient() + : did_access_initial_document_(false) {} - // !!!!!!!!!!!!!!!!!! IMPORTANT !!!!!!!!!!!!!!!!!! - // If the actual counts in the tests below increase, this could be an - // indicator of a bug that causes DidAccessInitialDocument() to always be - // invoked, regardless of whether or not the initial document is accessed. - // Please do not simply increment the expected counts in the below tests - // without understanding what's causing the increased count. - int did_access_initial_document_ = 0; + virtual void DidAccessInitialDocument() { + did_access_initial_document_ = true; + } + + bool did_access_initial_document_; }; TEST_P(ParameterizedWebFrameTest, DidAccessInitialDocumentBody) { + // FIXME: Why is this local webViewClient needed instead of the default + // WebViewHelper one? With out it there's some mysterious crash in the + // WebViewHelper destructor. + FrameTestHelpers::TestWebViewClient web_view_client; TestAccessInitialDocumentWebFrameClient web_frame_client; FrameTestHelpers::WebViewHelper web_view_helper; - web_view_helper.Initialize(true, &web_frame_client); + web_view_helper.Initialize(true, &web_frame_client, &web_view_client); RunPendingTasks(); - EXPECT_EQ(0, web_frame_client.did_access_initial_document_); + EXPECT_FALSE(web_frame_client.did_access_initial_document_); // Create another window that will try to access it. FrameTestHelpers::WebViewHelper new_web_view_helper; WebView* new_view = new_web_view_helper.InitializeWithOpener( web_view_helper.WebView()->MainFrame(), true); RunPendingTasks(); - EXPECT_EQ(0, web_frame_client.did_access_initial_document_); + EXPECT_FALSE(web_frame_client.did_access_initial_document_); // Access the initial document by modifying the body. new_view->MainFrame()->ExecuteScript( WebScriptSource("window.opener.document.body.innerHTML += 'Modified';")); RunPendingTasks(); - EXPECT_EQ(2, web_frame_client.did_access_initial_document_); + EXPECT_TRUE(web_frame_client.did_access_initial_document_); - web_view_helper.Reset(); -} - -TEST_P(ParameterizedWebFrameTest, DidAccessInitialDocumentOpen) { - TestAccessInitialDocumentWebFrameClient web_frame_client; - FrameTestHelpers::WebViewHelper web_view_helper; - web_view_helper.Initialize(true, &web_frame_client); - RunPendingTasks(); - EXPECT_EQ(0, web_frame_client.did_access_initial_document_); - - // Create another window that will try to access it. - FrameTestHelpers::WebViewHelper new_web_view_helper; - WebView* new_view = new_web_view_helper.InitializeWithOpener( - web_view_helper.WebView()->MainFrame(), true); - RunPendingTasks(); - EXPECT_EQ(0, web_frame_client.did_access_initial_document_); - - // Access the initial document by calling document.open(), which allows - // arbitrary modification of the initial document. + // Access the initial document again, to ensure we don't notify twice. new_view->MainFrame()->ExecuteScript( - WebScriptSource("window.opener.document.open();")); + WebScriptSource("window.opener.document.body.innerHTML += 'Modified';")); RunPendingTasks(); - EXPECT_EQ(1, web_frame_client.did_access_initial_document_); - - web_view_helper.Reset(); + EXPECT_TRUE(web_frame_client.did_access_initial_document_); } TEST_P(ParameterizedWebFrameTest, DidAccessInitialDocumentNavigator) { + // FIXME: Why is this local webViewClient needed instead of the default + // WebViewHelper one? With out it there's some mysterious crash in the + // WebViewHelper destructor. + FrameTestHelpers::TestWebViewClient web_view_client; TestAccessInitialDocumentWebFrameClient web_frame_client; FrameTestHelpers::WebViewHelper web_view_helper; - web_view_helper.Initialize(true, &web_frame_client); + web_view_helper.Initialize(true, &web_frame_client, &web_view_client); RunPendingTasks(); - EXPECT_EQ(0, web_frame_client.did_access_initial_document_); + EXPECT_FALSE(web_frame_client.did_access_initial_document_); // Create another window that will try to access it. FrameTestHelpers::WebViewHelper new_web_view_helper; WebView* new_view = new_web_view_helper.InitializeWithOpener( web_view_helper.WebView()->MainFrame(), true); RunPendingTasks(); - EXPECT_EQ(0, web_frame_client.did_access_initial_document_); + EXPECT_FALSE(web_frame_client.did_access_initial_document_); // Access the initial document to get to the navigator object. new_view->MainFrame()->ExecuteScript( WebScriptSource("console.log(window.opener.navigator);")); RunPendingTasks(); - EXPECT_EQ(3, web_frame_client.did_access_initial_document_); - - web_view_helper.Reset(); + EXPECT_TRUE(web_frame_client.did_access_initial_document_); } TEST_P(ParameterizedWebFrameTest, DidAccessInitialDocumentViaJavascriptUrl) { @@ -6931,83 +6916,85 @@ FrameTestHelpers::WebViewHelper web_view_helper; web_view_helper.Initialize(true, &web_frame_client); RunPendingTasks(); - EXPECT_EQ(0, web_frame_client.did_access_initial_document_); + EXPECT_FALSE(web_frame_client.did_access_initial_document_); // Access the initial document from a javascript: URL. FrameTestHelpers::LoadFrame(web_view_helper.WebView()->MainFrame(), "javascript:document.body.appendChild(document." "createTextNode('Modified'))"); - EXPECT_EQ(1, web_frame_client.did_access_initial_document_); - - web_view_helper.Reset(); + EXPECT_TRUE(web_frame_client.did_access_initial_document_); } TEST_P(ParameterizedWebFrameTest, DidAccessInitialDocumentBodyBeforeModalDialog) { + // FIXME: Why is this local webViewClient needed instead of the default + // WebViewHelper one? With out it there's some mysterious crash in the + // WebViewHelper destructor. + FrameTestHelpers::TestWebViewClient web_view_client; TestAccessInitialDocumentWebFrameClient web_frame_client; FrameTestHelpers::WebViewHelper web_view_helper; - web_view_helper.Initialize(true, &web_frame_client); + web_view_helper.Initialize(true, &web_frame_client, &web_view_client); RunPendingTasks(); - EXPECT_EQ(0, web_frame_client.did_access_initial_document_); + EXPECT_FALSE(web_frame_client.did_access_initial_document_); // Create another window that will try to access it. FrameTestHelpers::WebViewHelper new_web_view_helper; WebView* new_view = new_web_view_helper.InitializeWithOpener( web_view_helper.WebView()->MainFrame(), true); RunPendingTasks(); - EXPECT_EQ(0, web_frame_client.did_access_initial_document_); + EXPECT_FALSE(web_frame_client.did_access_initial_document_); // Access the initial document by modifying the body. new_view->MainFrame()->ExecuteScript( WebScriptSource("window.opener.document.body.innerHTML += 'Modified';")); - EXPECT_EQ(2, web_frame_client.did_access_initial_document_); + EXPECT_TRUE(web_frame_client.did_access_initial_document_); // Run a modal dialog, which used to run a nested run loop and require // a special case for notifying about the access. new_view->MainFrame()->ExecuteScript( WebScriptSource("window.opener.confirm('Modal');")); - EXPECT_EQ(3, web_frame_client.did_access_initial_document_); + EXPECT_TRUE(web_frame_client.did_access_initial_document_); // Ensure that we don't notify again later. RunPendingTasks(); - EXPECT_EQ(3, web_frame_client.did_access_initial_document_); - - web_view_helper.Reset(); + EXPECT_TRUE(web_frame_client.did_access_initial_document_); } TEST_P(ParameterizedWebFrameTest, DidWriteToInitialDocumentBeforeModalDialog) { + // FIXME: Why is this local webViewClient needed instead of the default + // WebViewHelper one? With out it there's some mysterious crash in the + // WebViewHelper destructor. + FrameTestHelpers::TestWebViewClient web_view_client; TestAccessInitialDocumentWebFrameClient web_frame_client; FrameTestHelpers::WebViewHelper web_view_helper; - web_view_helper.Initialize(true, &web_frame_client); + web_view_helper.Initialize(true, &web_frame_client, &web_view_client); RunPendingTasks(); - EXPECT_EQ(0, web_frame_client.did_access_initial_document_); + EXPECT_FALSE(web_frame_client.did_access_initial_document_); // Create another window that will try to access it. FrameTestHelpers::WebViewHelper new_web_view_helper; WebView* new_view = new_web_view_helper.InitializeWithOpener( web_view_helper.WebView()->MainFrame(), true); RunPendingTasks(); - EXPECT_EQ(0, web_frame_client.did_access_initial_document_); + EXPECT_FALSE(web_frame_client.did_access_initial_document_); // Access the initial document with document.write, which moves us past the // initial empty document state of the state machine. new_view->MainFrame()->ExecuteScript( WebScriptSource("window.opener.document.write('Modified'); " "window.opener.document.close();")); - EXPECT_EQ(1, web_frame_client.did_access_initial_document_); + EXPECT_TRUE(web_frame_client.did_access_initial_document_); // Run a modal dialog, which used to run a nested run loop and require // a special case for notifying about the access. new_view->MainFrame()->ExecuteScript( WebScriptSource("window.opener.confirm('Modal');")); - EXPECT_EQ(1, web_frame_client.did_access_initial_document_); + EXPECT_TRUE(web_frame_client.did_access_initial_document_); // Ensure that we don't notify again later. RunPendingTasks(); - EXPECT_EQ(1, web_frame_client.did_access_initial_document_); - - web_view_helper.Reset(); + EXPECT_TRUE(web_frame_client.did_access_initial_document_); } class TestScrolledFrameClient : public FrameTestHelpers::TestWebFrameClient {
diff --git a/third_party/WebKit/public/platform/WebDocumentSubresourceFilter.h b/third_party/WebKit/public/platform/WebDocumentSubresourceFilter.h index a97ac12..25f6e8c 100644 --- a/third_party/WebKit/public/platform/WebDocumentSubresourceFilter.h +++ b/third_party/WebKit/public/platform/WebDocumentSubresourceFilter.h
@@ -23,6 +23,10 @@ // Report that a resource loaded by the document (not a preload) was // disallowed. virtual void ReportDisallowedLoad() = 0; + + // Returns true if disallowed resource loads should be logged to the devtools + // console. + virtual bool ShouldLogToConsole() = 0; }; } // namespace blink
diff --git a/third_party/libaddressinput/chromium/chrome_address_validator.cc b/third_party/libaddressinput/chromium/chrome_address_validator.cc index b0bd189..f76bcbd1 100644 --- a/third_party/libaddressinput/chromium/chrome_address_validator.cc +++ b/third_party/libaddressinput/chromium/chrome_address_validator.cc
@@ -17,6 +17,7 @@ #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_normalizer.h" #include "third_party/libaddressinput/src/cpp/include/libaddressinput/source.h" #include "third_party/libaddressinput/src/cpp/include/libaddressinput/storage.h" +#include "third_party/libaddressinput/src/cpp/src/rule.h" namespace autofill { namespace { @@ -27,6 +28,7 @@ using ::i18n::addressinput::BuildCallback; using ::i18n::addressinput::FieldProblemMap; using ::i18n::addressinput::PreloadSupplier; +using ::i18n::addressinput::Rule; using ::i18n::addressinput::Source; using ::i18n::addressinput::Storage; @@ -58,6 +60,20 @@ supplier_->LoadRules(region_code, *rules_loaded_); } +std::vector<std::string> AddressValidator::GetRegionSubKeys( + const std::string& region_code) { + if (!AreRulesLoadedForRegion(region_code)) + return std::vector<std::string>(); + + auto rules = supplier_->GetRulesForRegion(region_code); + auto rule_iterator = rules.find("data/" + region_code); + + if (rule_iterator == rules.end() || !rule_iterator->second) + return std::vector<std::string>(); + + return rule_iterator->second->GetSubKeys(); +} + AddressValidator::Status AddressValidator::ValidateAddress( const AddressData& address, const FieldProblemMap* filter,
diff --git a/third_party/libaddressinput/chromium/chrome_address_validator.h b/third_party/libaddressinput/chromium/chrome_address_validator.h index 43a4a40..7a2c7c6 100644 --- a/third_party/libaddressinput/chromium/chrome_address_validator.h +++ b/third_party/libaddressinput/chromium/chrome_address_validator.h
@@ -94,6 +94,13 @@ // Invokes |load_rules_listener| when the loading has finished. virtual void LoadRules(const std::string& region_code); + // Returns the list of sub-regions (recorded as sub-keys) of the region + // (recorded as rule) indicated by |region_code|. So, if the |region_code| is + // a country code, sub-region means the country's admin area. + // This function should be called when the rules are loaded. + virtual std::vector<std::string> GetRegionSubKeys( + const std::string& region_code); + // Validates the |address| and populates |problems| with the validation // problems, filtered according to the |filter| parameter. //
diff --git a/third_party/libaddressinput/chromium/chrome_address_validator_unittest.cc b/third_party/libaddressinput/chromium/chrome_address_validator_unittest.cc index 13b5a8b..bc4c9d8 100644 --- a/third_party/libaddressinput/chromium/chrome_address_validator_unittest.cc +++ b/third_party/libaddressinput/chromium/chrome_address_validator_unittest.cc
@@ -5,6 +5,7 @@ #include "third_party/libaddressinput/chromium/chrome_address_validator.h" #include <stddef.h> +#include <set> #include <string> #include <utility> #include <vector> @@ -67,8 +68,8 @@ private: // LoadRulesListener implementation. - virtual void OnAddressValidationRulesLoaded(const std::string& country_code, - bool success) override { + void OnAddressValidationRulesLoaded(const std::string& country_code, + bool success) override { AddressData address_data; address_data.region_code = country_code; FieldProblemMap dummy; @@ -110,6 +111,26 @@ AddressValidator* LargeAddressValidatorTest::validator_ = NULL; +TEST_F(AddressValidatorTest, SubKeysLoaded) { + const std::string country_code = "US"; + const std::string first_state = "AL"; + + validator_->LoadRules(country_code); + std::vector<std::string> sub_keys = + validator_->GetRegionSubKeys(country_code); + ASSERT_FALSE(sub_keys.empty()); + ASSERT_EQ(sub_keys[0], first_state); +} + +TEST_F(AddressValidatorTest, SubKeysNotLoaded) { + const std::string country_code = "ZZ"; + + validator_->LoadRules(country_code); + std::vector<std::string> sub_keys = + validator_->GetRegionSubKeys(country_code); + ASSERT_TRUE(sub_keys.empty()); +} + TEST_F(AddressValidatorTest, RegionHasRules) { const std::vector<std::string>& region_codes = GetRegionCodes(); AddressData address; @@ -758,7 +779,7 @@ virtual ~TestAddressValidator() {} protected: - virtual base::TimeDelta GetBaseRetryPeriod() const override { + base::TimeDelta GetBaseRetryPeriod() const override { return base::TimeDelta::FromSeconds(0); } @@ -770,7 +791,7 @@ // data. class FailingSource : public Source { public: - explicit FailingSource() + FailingSource() : failures_number_(0), attempts_number_(0), actual_source_(true) {} virtual ~FailingSource() {} @@ -781,8 +802,7 @@ // Source implementation. // Always fails for the first |failures_number| times. - virtual void Get(const std::string& url, - const Callback& callback) const override { + void Get(const std::string& url, const Callback& callback) const override { ++attempts_number_; // |callback| takes ownership of the |new std::string|. if (failures_number_-- > 0) @@ -823,8 +843,7 @@ private: // LoadRulesListener implementation. - virtual void OnAddressValidationRulesLoaded(const std::string&, - bool success) override { + void OnAddressValidationRulesLoaded(const std::string&, bool success) override { load_rules_success_ = success; }
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 9a920f2..f76bc4b4 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -5283,6 +5283,7 @@ <int value="30" label="Important site info setting"/> <int value="31" label="Permission autoblocker data setting"/> <int value="32" label="Subresource filter setting"/> + <int value="33" label="Subresource filter metadata"/> </enum> <enum name="ContentTypeParseableResult" type="int"> @@ -20802,6 +20803,7 @@ <int value="1" label="native notifications not supported"/> <int value="2" label="missing required capabilities"/> <int value="3" label="could not connect to signals"/> + <int value="4" label="incompatible spec version"/> </enum> <enum name="LinuxSandboxStatus" type="int"> @@ -27066,8 +27068,8 @@ <int value="3" label="Timed out"/> <int value="4" label="Matched whitelist"/> <int value="5" label="Response already cached"/> - <int value="6" label="Not extended reporting user"/> - <int value="7" label="Incognito"/> + <int value="6" label="DEPRECATED: Not extended reporting user"/> + <int value="7" label="DEPRECATED: Incognito"/> <int value="8" label="Request malformed"/> <int value="9" label="Fetch failed"/> <int value="10" label="Response malformed"/> @@ -33406,6 +33408,8 @@ <int value="7" label="Content setting allowed (global)"/> <int value="8" label="Content setting blocked (global)"/> <int value="9" label="Content setting wildcard update"/> + <int value="10" label="UI Suppressed (Smart Logic)"/> + <int value="11" label="Content setting blocked while UI suppressed"/> </enum> <enum name="SubresourceFilterActivationDecision" type="int">
diff --git a/ui/accessibility/ax_node_data.cc b/ui/accessibility/ax_node_data.cc index 0debb01..ffaa3eb7 100644 --- a/ui/accessibility/ax_node_data.cc +++ b/ui/accessibility/ax_node_data.cc
@@ -23,6 +23,19 @@ namespace { +bool IsFlagSet(uint32_t bitfield, uint32_t flag) { + return 0 != (bitfield & (1 << flag)); +} + +std::string StateBitfieldToString(uint32_t state) { + std::string str; + for (uint32_t i = AX_STATE_NONE + 1; i <= AX_STATE_LAST; ++i) { + if (IsFlagSet(state, i)) + str += " " + base::ToUpperASCII(ToString(static_cast<AXState>(i))); + } + return str; +} + std::string IntVectorToString(const std::vector<int>& items) { std::string str; for (size_t i = 0; i < items.size(); ++i) { @@ -157,13 +170,7 @@ } AXNodeData::AXNodeData() - : id(-1), - role(AX_ROLE_UNKNOWN), - // Turn on all flags to more easily catch bugs where no flags are set. - // This will be cleared back to a 0-state before use. - state(0xFFFFFFFF), - offset_container_id(-1) { -} + : id(-1), role(AX_ROLE_UNKNOWN), state(0), offset_container_id(-1) {} AXNodeData::~AXNodeData() { } @@ -417,65 +424,22 @@ SetValue(base::UTF16ToUTF8(value)); } -// static -bool AXNodeData::IsFlagSet(uint32_t state, ui::AXState state_flag) { - return 0 != (state & (1 << state_flag)); -} - -void AXNodeData::AddStateFlag(ui::AXState state_flag) { - state |= (1 << state_flag); -} - -bool AXNodeData::HasStateFlag(ui::AXState state_flag) const { +bool AXNodeData::HasState(AXState state_flag) const { return IsFlagSet(state, state_flag); } +void AXNodeData::AddState(AXState state_flag) { + DCHECK_NE(state_flag, AX_STATE_NONE); + state |= (1 << state_flag); +} + std::string AXNodeData::ToString() const { std::string result; result += "id=" + IntToString(id); result += " " + ui::ToString(role); - if (state & (1 << AX_STATE_BUSY)) - result += " BUSY"; - if (state & (1 << AX_STATE_COLLAPSED)) - result += " COLLAPSED"; - if (state & (1 << AX_STATE_EDITABLE)) - result += " EDITABLE"; - if (state & (1 << AX_STATE_EXPANDED)) - result += " EXPANDED"; - if (state & (1 << AX_STATE_FOCUSABLE)) - result += " FOCUSABLE"; - if (state & (1 << AX_STATE_HASPOPUP)) - result += " HASPOPUP"; - if (state & (1 << AX_STATE_HOVERED)) - result += " HOVERED"; - if (state & (1 << AX_STATE_INVISIBLE)) - result += " INVISIBLE"; - if (state & (1 << AX_STATE_LINKED)) - result += " LINKED"; - if (state & (1 << AX_STATE_MULTISELECTABLE)) - result += " MULTISELECTABLE"; - if (state & (1 << AX_STATE_OFFSCREEN)) - result += " OFFSCREEN"; - if (state & (1 << AX_STATE_PRESSED)) - result += " PRESSED"; - if (state & (1 << AX_STATE_PROTECTED)) - result += " PROTECTED"; - if (state & (1 << AX_STATE_READ_ONLY)) - result += " READONLY"; - if (state & (1 << AX_STATE_REQUIRED)) - result += " REQUIRED"; - if (state & (1 << AX_STATE_RICHLY_EDITABLE)) - result += " RICHLY_EDITABLE"; - if (state & (1 << AX_STATE_SELECTABLE)) - result += " SELECTABLE"; - if (state & (1 << AX_STATE_SELECTED)) - result += " SELECTED"; - if (state & (1 << AX_STATE_VERTICAL)) - result += " VERTICAL"; - if (state & (1 << AX_STATE_VISITED)) - result += " VISITED"; + result += StateBitfieldToString(state); result += " (" + IntToString(location.x()) + ", " + IntToString(location.y()) + ")-(" +
diff --git a/ui/accessibility/ax_node_data.h b/ui/accessibility/ax_node_data.h index f44024f7..037e074 100644 --- a/ui/accessibility/ax_node_data.h +++ b/ui/accessibility/ax_node_data.h
@@ -106,12 +106,9 @@ void SetValue(const std::string& value); void SetValue(const base::string16& value); - // Helper to check whether |state_flag| is set in the given |state|. - static bool IsFlagSet(uint32_t state, ui::AXState state_flag); - - // Set or check bits in |state_|. - void AddStateFlag(ui::AXState state_flag); - bool HasStateFlag(ui::AXState state_flag) const; + // Set or check bits in |state|. + bool HasState(ui::AXState state_flag) const; + void AddState(ui::AXState state_flag); // Return a string representation of this data, for debugging. virtual std::string ToString() const;
diff --git a/ui/accessibility/ax_node_position_unittest.cc b/ui/accessibility/ax_node_position_unittest.cc index 7b720ac..277c9997 100644 --- a/ui/accessibility/ax_node_position_unittest.cc +++ b/ui/accessibility/ax_node_position_unittest.cc
@@ -116,12 +116,12 @@ inline_box2_.id = INLINE_BOX2_ID; root_.role = AX_ROLE_DIALOG; - root_.state = 1 << AX_STATE_FOCUSABLE; + root_.AddState(AX_STATE_FOCUSABLE); root_.SetName(std::string("ButtonCheck box") + TEXT_VALUE); root_.location = gfx::RectF(0, 0, 800, 600); button_.role = AX_ROLE_BUTTON; - button_.state = 1 << AX_STATE_HASPOPUP; + button_.AddState(AX_STATE_HASPOPUP); button_.SetName("Button"); button_.location = gfx::RectF(20, 20, 200, 30); button_.AddIntListAttribute(AX_ATTR_WORD_STARTS, std::vector<int32_t>{0}); @@ -141,7 +141,7 @@ root_.child_ids.push_back(check_box_.id); text_field_.role = AX_ROLE_TEXT_FIELD; - text_field_.state = 1 << AX_STATE_EDITABLE; + text_field_.AddState(AX_STATE_EDITABLE); text_field_.SetValue(TEXT_VALUE); text_field_.AddIntListAttribute(AX_ATTR_CACHED_LINE_STARTS, std::vector<int32_t>{0, 7}); @@ -151,13 +151,13 @@ root_.child_ids.push_back(text_field_.id); static_text1_.role = AX_ROLE_STATIC_TEXT; - static_text1_.state = 1 << AX_STATE_EDITABLE; + static_text1_.AddState(AX_STATE_EDITABLE); static_text1_.SetName("Line 1"); static_text1_.AddIntAttribute(AX_ATTR_NEXT_ON_LINE_ID, line_break_.id); static_text1_.child_ids.push_back(inline_box1_.id); inline_box1_.role = AX_ROLE_INLINE_TEXT_BOX; - inline_box1_.state = 1 << AX_STATE_EDITABLE; + inline_box1_.AddState(AX_STATE_EDITABLE); inline_box1_.SetName("Line 1"); inline_box1_.AddIntListAttribute(AX_ATTR_WORD_STARTS, std::vector<int32_t>{0, 5}); @@ -166,17 +166,17 @@ inline_box1_.AddIntAttribute(AX_ATTR_NEXT_ON_LINE_ID, line_break_.id); line_break_.role = AX_ROLE_LINE_BREAK; - line_break_.state = 1 << AX_STATE_EDITABLE; + line_break_.AddState(AX_STATE_EDITABLE); line_break_.SetName("\n"); line_break_.AddIntAttribute(AX_ATTR_PREVIOUS_ON_LINE_ID, inline_box1_.id); static_text2_.role = AX_ROLE_STATIC_TEXT; - static_text2_.state = 1 << AX_STATE_EDITABLE; + static_text2_.AddState(AX_STATE_EDITABLE); static_text2_.SetName("Line 2"); static_text2_.child_ids.push_back(inline_box2_.id); inline_box2_.role = AX_ROLE_INLINE_TEXT_BOX; - inline_box2_.state = 1 << AX_STATE_EDITABLE; + inline_box2_.AddState(AX_STATE_EDITABLE); inline_box2_.SetName("Line 2"); inline_box2_.AddIntListAttribute(AX_ATTR_WORD_STARTS, std::vector<int32_t>{0, 5});
diff --git a/ui/accessibility/ax_tree.cc b/ui/accessibility/ax_tree.cc index c726a4d0..b2c0833 100644 --- a/ui/accessibility/ax_tree.cc +++ b/ui/accessibility/ax_tree.cc
@@ -360,10 +360,8 @@ if (old_data.state != new_data.state) { for (int i = AX_STATE_NONE + 1; i <= AX_STATE_LAST; ++i) { AXState state = static_cast<AXState>(i); - if (old_data.HasStateFlag(state) != new_data.HasStateFlag(state)) { - delegate_->OnStateChanged(this, node, state, - new_data.HasStateFlag(state)); - } + if (old_data.HasState(state) != new_data.HasState(state)) + delegate_->OnStateChanged(this, node, state, new_data.HasState(state)); } }
diff --git a/ui/accessibility/ax_tree_fuzzer.cc b/ui/accessibility/ax_tree_fuzzer.cc index de4b22d..84afea8b 100644 --- a/ui/accessibility/ax_tree_fuzzer.cc +++ b/ui/accessibility/ax_tree_fuzzer.cc
@@ -31,7 +31,6 @@ while (i < size) { ui::AXNodeData node; node.id = data[i++]; - node.state = 0; if (i < size) { size_t child_count = data[i++]; for (size_t j = 0; j < child_count && i < size; j++)
diff --git a/ui/accessibility/ax_tree_unittest.cc b/ui/accessibility/ax_tree_unittest.cc index 7c13c19..b685134 100644 --- a/ui/accessibility/ax_tree_unittest.cc +++ b/ui/accessibility/ax_tree_unittest.cc
@@ -212,7 +212,7 @@ AXNodeData root; root.id = 1; root.role = AX_ROLE_DIALOG; - root.state = 1 << AX_STATE_FOCUSABLE; + root.AddState(AX_STATE_FOCUSABLE); root.location = gfx::RectF(0, 0, 800, 600); root.child_ids.push_back(2); root.child_ids.push_back(3); @@ -220,13 +220,11 @@ AXNodeData button; button.id = 2; button.role = AX_ROLE_BUTTON; - button.state = 0; button.location = gfx::RectF(20, 20, 200, 30); AXNodeData checkbox; checkbox.id = 3; checkbox.role = AX_ROLE_CHECK_BOX; - checkbox.state = 0; checkbox.location = gfx::RectF(20, 50, 200, 30); AXTreeUpdate initial_state; @@ -275,7 +273,6 @@ AXNodeData list; list.id = 3; list.role = AX_ROLE_LIST; - list.state = 0; list.child_ids.push_back(4); list.child_ids.push_back(5); list.child_ids.push_back(6); @@ -283,17 +280,14 @@ AXNodeData list_item_2; list_item_2.id = 5; list_item_2.role = AX_ROLE_LIST_ITEM; - list_item_2.state = 0; AXNodeData list_item_3; list_item_3.id = 6; list_item_3.role = AX_ROLE_LIST_ITEM; - list_item_3.state = 0; AXNodeData button; button.id = 7; button.role = AX_ROLE_BUTTON; - button.state = 0; AXTreeUpdate update; update.root_id = 3; @@ -576,7 +570,6 @@ AXTreeUpdate initial_state; AXNodeData node; node.id = 0; - node.state = 0; initial_state.nodes.push_back(node); initial_state.nodes.push_back(node); ui::AXTree tree; @@ -588,11 +581,9 @@ AXTreeUpdate initial_state; AXNodeData node; node.id = 0; - node.state = 0; initial_state.nodes.push_back(node); AXNodeData node2; node2.id = 0; - node2.state = 0; node2.child_ids.push_back(0); node2.child_ids.push_back(0); initial_state.nodes.push_back(node2); @@ -605,13 +596,11 @@ AXTreeUpdate initial_state; AXNodeData node; node.id = 0; - node.state = 0; node.child_ids.push_back(1); initial_state.nodes.push_back(node); AXNodeData node2; node2.id = 1; - node2.state = 0; node2.child_ids.push_back(1); node2.child_ids.push_back(1); initial_state.nodes.push_back(node2); @@ -626,10 +615,9 @@ initial_state.nodes.resize(1); initial_state.nodes[0].id = 1; initial_state.nodes[0].role = AX_ROLE_BUTTON; - initial_state.nodes[0].state = 0; initial_state.nodes[0].AddIntAttribute(ui::AX_ATTR_CHECKED_STATE, ui::AX_CHECKED_STATE_TRUE); - initial_state.nodes[0].AddStateFlag(AX_STATE_FOCUSABLE); + initial_state.nodes[0].AddState(AX_STATE_FOCUSABLE); AXTree tree(initial_state); FakeAXTreeDelegate fake_delegate; @@ -641,11 +629,10 @@ update.nodes.resize(1); update.nodes[0].id = 1; update.nodes[0].role = AX_ROLE_CHECK_BOX; - update.nodes[0].state = 0; update.nodes[0].AddIntAttribute(ui::AX_ATTR_CHECKED_STATE, ui::AX_CHECKED_STATE_FALSE); - update.nodes[0].AddStateFlag(AX_STATE_FOCUSABLE); - update.nodes[0].AddStateFlag(AX_STATE_VISITED); + update.nodes[0].AddState(AX_STATE_FOCUSABLE); + update.nodes[0].AddState(AX_STATE_VISITED); EXPECT_TRUE(tree.Unserialize(update)); const std::vector<std::string>& change_log =
diff --git a/ui/accessibility/platform/ax_platform_node_auralinux.cc b/ui/accessibility/platform/ax_platform_node_auralinux.cc index 4a85863..46dd7dd 100644 --- a/ui/accessibility/platform/ax_platform_node_auralinux.cc +++ b/ui/accessibility/platform/ax_platform_node_auralinux.cc
@@ -461,23 +461,22 @@ } void AXPlatformNodeAuraLinux::GetAtkState(AtkStateSet* atk_state_set) { - const uint32_t state = GetData().state; - - if (state & (1 << ui::AX_STATE_DEFAULT)) + AXNodeData data = GetData(); + if (data.HasState(ui::AX_STATE_DEFAULT)) atk_state_set_add_state(atk_state_set, ATK_STATE_DEFAULT); - if (state & (1 << ui::AX_STATE_EDITABLE)) + if (data.HasState(ui::AX_STATE_EDITABLE)) atk_state_set_add_state(atk_state_set, ATK_STATE_EDITABLE); - if (!(state & (1 << ui::AX_STATE_DISABLED))) + if (!data.HasState(ui::AX_STATE_DISABLED)) atk_state_set_add_state(atk_state_set, ATK_STATE_ENABLED); - if (state & (1 << ui::AX_STATE_EXPANDED)) + if (data.HasState(ui::AX_STATE_EXPANDED)) atk_state_set_add_state(atk_state_set, ATK_STATE_EXPANDED); - if (state & (1 << ui::AX_STATE_FOCUSABLE)) + if (data.HasState(ui::AX_STATE_FOCUSABLE)) atk_state_set_add_state(atk_state_set, ATK_STATE_FOCUSABLE); - if (state & (1 << ui::AX_STATE_PRESSED)) + if (data.HasState(ui::AX_STATE_PRESSED)) atk_state_set_add_state(atk_state_set, ATK_STATE_PRESSED); - if (state & (1 << ui::AX_STATE_SELECTABLE)) + if (data.HasState(ui::AX_STATE_SELECTABLE)) atk_state_set_add_state(atk_state_set, ATK_STATE_SELECTABLE); - if (state & (1 << ui::AX_STATE_SELECTED)) + if (data.HasState(ui::AX_STATE_SELECTED)) atk_state_set_add_state(atk_state_set, ATK_STATE_SELECTED); // Checked state
diff --git a/ui/accessibility/platform/ax_platform_node_mac.mm b/ui/accessibility/platform/ax_platform_node_mac.mm index 989b5b9..d9744b5 100644 --- a/ui/accessibility/platform/ax_platform_node_mac.mm +++ b/ui/accessibility/platform/ax_platform_node_mac.mm
@@ -291,7 +291,7 @@ - (BOOL)accessibilityIsIgnored { return [[self AXRole] isEqualToString:NSAccessibilityUnknownRole] || - node_->GetData().HasStateFlag(ui::AX_STATE_INVISIBLE); + node_->GetData().HasState(ui::AX_STATE_INVISIBLE); } - (id)accessibilityHitTest:(NSPoint)point { @@ -381,10 +381,8 @@ switch (node_->GetData().role) { case ui::AX_ROLE_TEXT_FIELD: [axAttributes addObject:kTextfieldAttributes]; - if (!ui::AXNodeData::IsFlagSet(node_->GetData().state, - ui::AX_STATE_PROTECTED)) { + if (!node_->GetData().HasState(ui::AX_STATE_PROTECTED)) [axAttributes addObjectsFromArray:kUnprotectedTextfieldAttributes]; - } // Fallthrough. case ui::AX_ROLE_CHECK_BOX: case ui::AX_ROLE_COMBO_BOX: @@ -405,7 +403,7 @@ } - (BOOL)accessibilityIsAttributeSettable:(NSString*)attributeName { - if (node_->GetData().HasStateFlag(ui::AX_STATE_DISABLED)) + if (node_->GetData().HasState(ui::AX_STATE_DISABLED)) return NO; // Allow certain attributes to be written via an accessibility client. A @@ -421,25 +419,23 @@ if ([attributeName isEqualToString:NSAccessibilityValueAttribute]) { // NSSecureTextField doesn't allow values to be edited (despite showing up // as editable), match its behavior. - if (node_->GetData().HasStateFlag(ui::AX_STATE_PROTECTED)) + if (node_->GetData().HasState(ui::AX_STATE_PROTECTED)) return NO; // Since tabs use the Radio Button role on Mac, the standard way to set // them is via the value attribute rather than the selected attribute. if (node_->GetData().role == ui::AX_ROLE_TAB) - return !node_->GetData().HasStateFlag(ui::AX_STATE_SELECTED); + return !node_->GetData().HasState(ui::AX_STATE_SELECTED); } if ([attributeName isEqualToString:NSAccessibilityValueAttribute] || [attributeName isEqualToString:NSAccessibilitySelectedTextAttribute] || [attributeName isEqualToString:NSAccessibilitySelectedTextRangeAttribute]) { - return !ui::AXNodeData::IsFlagSet(node_->GetData().state, - ui::AX_STATE_READ_ONLY); + return !node_->GetData().HasState(ui::AX_STATE_READ_ONLY); } if ([attributeName isEqualToString:NSAccessibilityFocusedAttribute]) { - return ui::AXNodeData::IsFlagSet(node_->GetData().state, - ui::AX_STATE_FOCUSABLE); + return node_->GetData().HasState(ui::AX_STATE_FOCUSABLE); } // TODO(patricialor): Add callbacks for updating the above attributes except @@ -453,7 +449,7 @@ // Check for attributes first. Only the |data.action| should be set here - any // type-specific information, if needed, should be set below. if ([attribute isEqualToString:NSAccessibilityValueAttribute] && - !node_->GetData().HasStateFlag(ui::AX_STATE_PROTECTED)) { + !node_->GetData().HasState(ui::AX_STATE_PROTECTED)) { data.action = node_->GetData().role == ui::AX_ROLE_TAB ? ui::AX_ACTION_SET_SELECTION : ui::AX_ACTION_SET_VALUE; @@ -519,8 +515,7 @@ ui::AXRole role = node_->GetData().role; switch (role) { case ui::AX_ROLE_TEXT_FIELD: - if (ui::AXNodeData::IsFlagSet(node_->GetData().state, - ui::AX_STATE_PROTECTED)) + if (node_->GetData().HasState(ui::AX_STATE_PROTECTED)) return NSAccessibilitySecureTextFieldSubrole; break; default: @@ -540,13 +535,11 @@ } - (NSNumber*)AXEnabled { - return @(!ui::AXNodeData::IsFlagSet(node_->GetData().state, - ui::AX_STATE_DISABLED)); + return @(!node_->GetData().HasState(ui::AX_STATE_DISABLED)); } - (NSNumber*)AXFocused { - if (ui::AXNodeData::IsFlagSet(node_->GetData().state, - ui::AX_STATE_FOCUSABLE)) + if (node_->GetData().HasState(ui::AX_STATE_FOCUSABLE)) return @(node_->GetDelegate()->GetFocus() == node_->GetNativeViewAccessible()); return @NO; @@ -591,7 +584,7 @@ // Misc attributes. - (NSNumber*)AXSelected { - return @(node_->GetData().HasStateFlag(ui::AX_STATE_SELECTED)); + return @(node_->GetData().HasState(ui::AX_STATE_SELECTED)); } - (NSString*)AXPlaceholderValue { @@ -601,7 +594,7 @@ // Text-specific attributes. - (NSString*)AXSelectedText { - if (ui::AXNodeData::IsFlagSet(node_->GetData().state, ui::AX_STATE_PROTECTED)) + if (node_->GetData().HasState(ui::AX_STATE_PROTECTED)) return nil; NSRange selectedTextRange; @@ -610,7 +603,7 @@ } - (NSValue*)AXSelectedTextRange { - if (ui::AXNodeData::IsFlagSet(node_->GetData().state, ui::AX_STATE_PROTECTED)) + if (node_->GetData().HasState(ui::AX_STATE_PROTECTED)) return nil; int textDir, start, end; @@ -627,19 +620,19 @@ } - (NSNumber*)AXNumberOfCharacters { - if (ui::AXNodeData::IsFlagSet(node_->GetData().state, ui::AX_STATE_PROTECTED)) + if (node_->GetData().HasState(ui::AX_STATE_PROTECTED)) return nil; return @([[self AXValue] length]); } - (NSValue*)AXVisibleCharacterRange { - if (ui::AXNodeData::IsFlagSet(node_->GetData().state, ui::AX_STATE_PROTECTED)) + if (node_->GetData().HasState(ui::AX_STATE_PROTECTED)) return nil; return [NSValue valueWithRange:{0, [[self AXNumberOfCharacters] intValue]}]; } - (NSNumber*)AXInsertionPointLineNumber { - if (ui::AXNodeData::IsFlagSet(node_->GetData().state, ui::AX_STATE_PROTECTED)) + if (node_->GetData().HasState(ui::AX_STATE_PROTECTED)) return nil; // Multiline is not supported on views. return @0;
diff --git a/ui/accessibility/tree_generator.cc b/ui/accessibility/tree_generator.cc index 480a040..faebbfb 100644 --- a/ui/accessibility/tree_generator.cc +++ b/ui/accessibility/tree_generator.cc
@@ -88,18 +88,15 @@ update.root_id = permuted[0]; update.nodes.resize(node_count); update.nodes[0].id = permuted[0]; - update.nodes[0].state = AX_STATE_NONE; if (node_count > 1) { update.nodes[0].child_ids.push_back(permuted[1]); update.nodes[1].id = permuted[1]; - update.nodes[1].state = AX_STATE_NONE; } // The remaining nodes are assigned based on their parent // selected from the next bits from |tree_index|. for (int i = 2; i < node_count; ++i) { update.nodes[i].id = permuted[i]; - update.nodes[i].state = AX_STATE_NONE; int parent_index = (tree_index % i); tree_index /= i; update.nodes[parent_index].child_ids.push_back(permuted[i]);
diff --git a/ui/file_manager/file_manager/common/js/volume_manager_common.js b/ui/file_manager/file_manager/common/js/volume_manager_common.js index 355344f1..32e517ef 100644 --- a/ui/file_manager/file_manager/common/js/volume_manager_common.js +++ b/ui/file_manager/file_manager/common/js/volume_manager_common.js
@@ -185,6 +185,7 @@ case VolumeManagerCommon.RootType.REMOVABLE: return VolumeManagerCommon.VolumeType.REMOVABLE; case VolumeManagerCommon.RootType.DRIVE: + case VolumeManagerCommon.RootType.TEAM_DRIVES_GRAND_ROOT: case VolumeManagerCommon.RootType.TEAM_DRIVE: case VolumeManagerCommon.RootType.DRIVE_OTHER: case VolumeManagerCommon.RootType.DRIVE_OFFLINE:
diff --git a/ui/gfx/color_space.cc b/ui/gfx/color_space.cc index ef58e58..2bb9982 100644 --- a/ui/gfx/color_space.cc +++ b/ui/gfx/color_space.cc
@@ -17,142 +17,6 @@ namespace gfx { -// static -ColorSpace ColorSpace::CreateVideo(int video_primary, - int video_transfer, - int video_matrix, - RangeID range_id) { - // TODO(hubbe): Use more context to decide how to handle UNSPECIFIED values. - ColorSpace result; - switch (video_primary) { - default: - case 0: // RESERVED0 - case 1: // BT709 - case 2: // UNSPECIFIED - case 3: // RESERVED - result.primaries_ = PrimaryID::BT709; - break; - case 4: // BT470M - result.primaries_ = PrimaryID::BT470M; - break; - case 5: // BT470BG - result.primaries_ = PrimaryID::BT470BG; - break; - case 6: // SMPTE170M - result.primaries_ = PrimaryID::SMPTE170M; - break; - case 7: // SMPTE240M - result.primaries_ = PrimaryID::SMPTE240M; - break; - case 8: // FILM - result.primaries_ = PrimaryID::FILM; - break; - case 9: // BT2020 - result.primaries_ = PrimaryID::BT2020; - break; - case 10: // SMPTEST428_1 - result.primaries_ = PrimaryID::SMPTEST428_1; - break; - case 11: // SMPTEST431_2 - result.primaries_ = PrimaryID::SMPTEST431_2; - break; - case 12: // SMPTEST432_1 - result.primaries_ = PrimaryID::SMPTEST432_1; - break; - } - switch (video_transfer) { - default: - case 0: // RESERVED0 - case 1: // BT709 - case 2: // UNSPECIFIED - case 3: // RESERVED - result.transfer_ = TransferID::BT709; - break; - case 4: // GAMMA22 - result.transfer_ = TransferID::GAMMA22; - break; - case 5: // GAMMA28 - result.transfer_ = TransferID::GAMMA28; - break; - case 6: // SMPTE170M - result.transfer_ = TransferID::SMPTE170M; - break; - case 7: // SMPTE240M - result.transfer_ = TransferID::SMPTE240M; - break; - case 8: // LINEAR - result.transfer_ = TransferID::LINEAR; - break; - case 9: // LOG - result.transfer_ = TransferID::LOG; - break; - case 10: // LOG_SQRT - result.transfer_ = TransferID::LOG_SQRT; - break; - case 11: // IEC61966_2_4 - result.transfer_ = TransferID::IEC61966_2_4; - break; - case 12: // BT1361_ECG - result.transfer_ = TransferID::BT1361_ECG; - break; - case 13: // IEC61966_2_1 - result.transfer_ = TransferID::IEC61966_2_1; - break; - case 14: // BT2020_10 - result.transfer_ = TransferID::BT2020_10; - break; - case 15: // BT2020_12 - result.transfer_ = TransferID::BT2020_12; - break; - case 16: // SMPTEST2084 - result.transfer_ = TransferID::SMPTEST2084; - break; - case 17: // SMPTEST428_1 - result.transfer_ = TransferID::SMPTEST428_1; - break; - case 18: // ARIB_STD_B67 - result.transfer_ = TransferID::ARIB_STD_B67; - break; - } - switch (video_matrix) { - case 0: // RGB - result.matrix_ = MatrixID::RGB; - break; - default: - case 1: // BT709 - case 2: // UNSPECIFIED - case 3: // RESERVED - result.matrix_ = MatrixID::BT709; - break; - case 4: // FCC - result.matrix_ = MatrixID::FCC; - break; - case 5: // BT470BG - result.matrix_ = MatrixID::BT470BG; - break; - case 6: // SMPTE170M - result.matrix_ = MatrixID::SMPTE170M; - break; - case 7: // SMPTE240M - result.matrix_ = MatrixID::SMPTE240M; - break; - case 8: // YCOCG - result.matrix_ = MatrixID::YCOCG; - break; - case 9: // BT2020_NCL - result.matrix_ = MatrixID::BT2020_NCL; - break; - case 10: // BT2020_CL - result.matrix_ = MatrixID::BT2020_CL; - break; - case 11: // YDZDX - result.matrix_ = MatrixID::YDZDX; - break; - } - result.range_ = range_id; - return result; -} - ColorSpace::ColorSpace() {} ColorSpace::ColorSpace(PrimaryID primaries,
diff --git a/ui/gfx/color_space.h b/ui/gfx/color_space.h index 643a69c..8626758 100644 --- a/ui/gfx/color_space.h +++ b/ui/gfx/color_space.h
@@ -123,15 +123,6 @@ ColorSpace& operator=(const ColorSpace& other); ~ColorSpace(); - // Create a color space with primary, transfer and matrix values from the - // H264 specification (Table E-3 Colour Primaries, E-4 Transfer - // Characteristics, and E-5 Matrix Coefficients in - // https://www.itu.int/rec/T-REC-H.264/en). - static ColorSpace CreateVideo(int h264_primary, - int h264_transfer, - int h264_matrix, - RangeID range_id); - // Returns true if this is not the default-constructor object. bool IsValid() const;
diff --git a/ui/gfx/color_transform_unittest.cc b/ui/gfx/color_transform_unittest.cc index 289e0012..d5217a7 100644 --- a/ui/gfx/color_transform_unittest.cc +++ b/ui/gfx/color_transform_unittest.cc
@@ -311,33 +311,6 @@ EXPECT_NEAR(tmp.z(), 1.0f, kEpsilon); } -TEST(SimpleColorSpace, UnknownVideoToSRGB) { - // Invalid video spaces should be BT709. - ColorSpace unknown = gfx::ColorSpace::CreateVideo( - -1, -1, -1, gfx::ColorSpace::RangeID::LIMITED); - ColorSpace sRGB = ColorSpace::CreateSRGB(); - std::unique_ptr<ColorTransform> t(ColorTransform::NewColorTransform( - unknown, sRGB, ColorTransform::Intent::INTENT_PERCEPTUAL)); - - ColorTransform::TriStim tmp(16.0f / 255.0f, 0.5f, 0.5f); - t->Transform(&tmp, 1); - EXPECT_NEAR(tmp.x(), 0.0f, 0.001f); - EXPECT_NEAR(tmp.y(), 0.0f, 0.001f); - EXPECT_NEAR(tmp.z(), 0.0f, 0.001f); - - tmp = ColorTransform::TriStim(235.0f / 255.0f, 0.5f, 0.5f); - t->Transform(&tmp, 1); - EXPECT_NEAR(tmp.x(), 1.0f, 0.001f); - EXPECT_NEAR(tmp.y(), 1.0f, 0.001f); - EXPECT_NEAR(tmp.z(), 1.0f, 0.001f); - - // Test a blue color - tmp = ColorTransform::TriStim(128.0f / 255.0f, 240.0f / 255.0f, 0.5f); - t->Transform(&tmp, 1); - EXPECT_GT(tmp.z(), tmp.x()); - EXPECT_GT(tmp.z(), tmp.y()); -} - TEST(SimpleColorSpace, ToUndefined) { ColorSpace null; ColorSpace nonnull = gfx::ColorSpace::CreateSRGB();
diff --git a/ui/views/accessibility/ax_view_obj_wrapper.cc b/ui/views/accessibility/ax_view_obj_wrapper.cc index 2a22590..e636e34 100644 --- a/ui/views/accessibility/ax_view_obj_wrapper.cc +++ b/ui/views/accessibility/ax_view_obj_wrapper.cc
@@ -46,15 +46,14 @@ } void AXViewObjWrapper::Serialize(ui::AXNodeData* out_node_data) { - out_node_data->state = 0; view_->GetAccessibleNodeData(out_node_data); out_node_data->id = GetID(); if (view_->IsAccessibilityFocusable()) - out_node_data->state |= 1 << ui::AX_STATE_FOCUSABLE; + out_node_data->AddState(ui::AX_STATE_FOCUSABLE); if (!view_->visible()) - out_node_data->state |= 1 << ui::AX_STATE_INVISIBLE; + out_node_data->AddState(ui::AX_STATE_INVISIBLE); out_node_data->location = gfx::RectF(view_->GetBoundsInScreen()); }
diff --git a/ui/views/accessibility/ax_window_obj_wrapper.cc b/ui/views/accessibility/ax_window_obj_wrapper.cc index 0f08a3c..6c5bf35 100644 --- a/ui/views/accessibility/ax_window_obj_wrapper.cc +++ b/ui/views/accessibility/ax_window_obj_wrapper.cc
@@ -53,7 +53,6 @@ out_node_data->role = is_alert_ ? ui::AX_ROLE_ALERT : ui::AX_ROLE_WINDOW; out_node_data->AddStringAttribute(ui::AX_ATTR_NAME, base::UTF16ToUTF8(window_->GetTitle())); - out_node_data->state = 0; out_node_data->location = gfx::RectF(window_->GetBoundsInScreen()); ui::AXTreeIDRegistry::AXTreeID child_ax_tree_id = @@ -104,8 +103,10 @@ Widget* widget = Widget::GetWidgetForNativeView(window); if (widget) { - widget->GetRootView()->NotifyAccessibilityEvent( - ui::AX_EVENT_LOCATION_CHANGED, true); + views::View* view = widget->GetRootView(); + if (view) { + view->NotifyAccessibilityEvent(ui::AX_EVENT_LOCATION_CHANGED, true); + } } }
diff --git a/ui/views/accessibility/native_view_accessibility_base.cc b/ui/views/accessibility/native_view_accessibility_base.cc index 2ed7e26f..b1feda1 100644 --- a/ui/views/accessibility/native_view_accessibility_base.cc +++ b/ui/views/accessibility/native_view_accessibility_base.cc
@@ -40,13 +40,12 @@ const ui::AXNodeData& NativeViewAccessibilityBase::GetData() const { data_ = ui::AXNodeData(); - data_.state = 0; // Views may misbehave if their widget is closed; return an unknown role // rather than possibly crashing. if (!view_->GetWidget() || view_->GetWidget()->IsClosed()) { data_.role = ui::AX_ROLE_UNKNOWN; - data_.state = 1 << ui::AX_STATE_DISABLED; + data_.AddState(ui::AX_STATE_DISABLED); return data_; } @@ -58,13 +57,13 @@ base::UTF16ToUTF8(description)); if (view_->IsAccessibilityFocusable()) - data_.state |= (1 << ui::AX_STATE_FOCUSABLE); + data_.AddState(ui::AX_STATE_FOCUSABLE); if (!view_->enabled()) - data_.state |= (1 << ui::AX_STATE_DISABLED); + data_.AddState(ui::AX_STATE_DISABLED); if (!view_->IsDrawn()) - data_.state |= (1 << ui::AX_STATE_INVISIBLE); + data_.AddState(ui::AX_STATE_INVISIBLE); return data_; }
diff --git a/ui/views/accessibility/native_view_accessibility_unittest.cc b/ui/views/accessibility/native_view_accessibility_unittest.cc index 0deb578..ba8fa7e 100644 --- a/ui/views/accessibility/native_view_accessibility_unittest.cc +++ b/ui/views/accessibility/native_view_accessibility_unittest.cc
@@ -111,14 +111,14 @@ TEST_F(NativeViewAccessibilityTest, InvisibleViews) { EXPECT_TRUE(widget_->IsVisible()); EXPECT_FALSE( - button_accessibility()->GetData().HasStateFlag(ui::AX_STATE_INVISIBLE)); + button_accessibility()->GetData().HasState(ui::AX_STATE_INVISIBLE)); EXPECT_FALSE( - label_accessibility()->GetData().HasStateFlag(ui::AX_STATE_INVISIBLE)); + label_accessibility()->GetData().HasState(ui::AX_STATE_INVISIBLE)); button_->SetVisible(false); EXPECT_TRUE( - button_accessibility()->GetData().HasStateFlag(ui::AX_STATE_INVISIBLE)); + button_accessibility()->GetData().HasState(ui::AX_STATE_INVISIBLE)); EXPECT_TRUE( - label_accessibility()->GetData().HasStateFlag(ui::AX_STATE_INVISIBLE)); + label_accessibility()->GetData().HasState(ui::AX_STATE_INVISIBLE)); } TEST_F(NativeViewAccessibilityTest, WritableFocus) {
diff --git a/ui/views/controls/button/button.cc b/ui/views/controls/button/button.cc index 8adf74d..18a992c 100644 --- a/ui/views/controls/button/button.cc +++ b/ui/views/controls/button/button.cc
@@ -66,7 +66,7 @@ node_data->role = ui::AX_ROLE_BUTTON; node_data->SetName(accessible_name_); if (!enabled()) - node_data->AddStateFlag(ui::AX_STATE_DISABLED); + node_data->AddState(ui::AX_STATE_DISABLED); } ////////////////////////////////////////////////////////////////////////////////
diff --git a/ui/views/controls/button/custom_button.cc b/ui/views/controls/button/custom_button.cc index cdf6a6d6..c5f602d 100644 --- a/ui/views/controls/button/custom_button.cc +++ b/ui/views/controls/button/custom_button.cc
@@ -356,13 +356,13 @@ Button::GetAccessibleNodeData(node_data); switch (state_) { case STATE_HOVERED: - node_data->AddStateFlag(ui::AX_STATE_HOVERED); + node_data->AddState(ui::AX_STATE_HOVERED); break; case STATE_PRESSED: - node_data->AddStateFlag(ui::AX_STATE_PRESSED); + node_data->AddState(ui::AX_STATE_PRESSED); break; case STATE_DISABLED: - node_data->AddStateFlag(ui::AX_STATE_DISABLED); + node_data->AddState(ui::AX_STATE_DISABLED); break; case STATE_NORMAL: case STATE_COUNT:
diff --git a/ui/views/controls/button/image_button.cc b/ui/views/controls/button/image_button.cc index fd2151e2a..c8cc3f4 100644 --- a/ui/views/controls/button/image_button.cc +++ b/ui/views/controls/button/image_button.cc
@@ -289,7 +289,7 @@ (!toggled_ && !alternate_images_[ButtonState::STATE_NORMAL].isNull())) { node_data->role = ui::AX_ROLE_TOGGLE_BUTTON; if (toggled_) - node_data->AddStateFlag(ui::AX_STATE_PRESSED); + node_data->AddState(ui::AX_STATE_PRESSED); } }
diff --git a/ui/views/controls/button/menu_button.cc b/ui/views/controls/button/menu_button.cc index 08bdacd..af3cd2c 100644 --- a/ui/views/controls/button/menu_button.cc +++ b/ui/views/controls/button/menu_button.cc
@@ -299,7 +299,7 @@ void MenuButton::GetAccessibleNodeData(ui::AXNodeData* node_data) { CustomButton::GetAccessibleNodeData(node_data); node_data->role = ui::AX_ROLE_POP_UP_BUTTON; - node_data->AddStateFlag(ui::AX_STATE_HASPOPUP); + node_data->AddState(ui::AX_STATE_HASPOPUP); if (enabled()) { node_data->AddIntAttribute(ui::AX_ATTR_ACTION, ui::AX_SUPPORTED_ACTION_OPEN);
diff --git a/ui/views/controls/label.cc b/ui/views/controls/label.cc index 182d335e..2523f9a 100644 --- a/ui/views/controls/label.cc +++ b/ui/views/controls/label.cc
@@ -403,7 +403,7 @@ void Label::GetAccessibleNodeData(ui::AXNodeData* node_data) { node_data->role = ui::AX_ROLE_STATIC_TEXT; - node_data->AddStateFlag(ui::AX_STATE_READ_ONLY); + node_data->AddState(ui::AX_STATE_READ_ONLY); // Note that |render_text_| is never elided (see the comment in Init() too). node_data->SetName(render_text_->GetDisplayText()); }
diff --git a/ui/views/controls/label_unittest.cc b/ui/views/controls/label_unittest.cc index d53b502..8fb2773 100644 --- a/ui/views/controls/label_unittest.cc +++ b/ui/views/controls/label_unittest.cc
@@ -498,7 +498,7 @@ label()->GetAccessibleNodeData(&node_data); EXPECT_EQ(ui::AX_ROLE_STATIC_TEXT, node_data.role); EXPECT_EQ(label()->text(), node_data.GetString16Attribute(ui::AX_ATTR_NAME)); - EXPECT_TRUE(node_data.HasStateFlag(ui::AX_STATE_READ_ONLY)); + EXPECT_TRUE(node_data.HasState(ui::AX_STATE_READ_ONLY)); } TEST_F(LabelTest, TextChangeWithoutLayout) {
diff --git a/ui/views/controls/menu/menu_item_view.cc b/ui/views/controls/menu/menu_item_view.cc index 46ff17be..c2d98e2 100644 --- a/ui/views/controls/menu/menu_item_view.cc +++ b/ui/views/controls/menu/menu_item_view.cc
@@ -171,7 +171,7 @@ switch (GetType()) { case SUBMENU: - node_data->AddStateFlag(ui::AX_STATE_HASPOPUP); + node_data->AddState(ui::AX_STATE_HASPOPUP); break; case CHECKBOX: case RADIO: {
diff --git a/ui/views/controls/menu/submenu_view.cc b/ui/views/controls/menu/submenu_view.cc index 1f9abd4..5f3b54c7 100644 --- a/ui/views/controls/menu/submenu_view.cc +++ b/ui/views/controls/menu/submenu_view.cc
@@ -188,7 +188,7 @@ GetMenuItem()->GetAccessibleNodeData(node_data); node_data->role = ui::AX_ROLE_MENU_LIST_POPUP; // Menus in Chrome are always traversed in a vertical direction. - node_data->AddStateFlag(ui::AX_STATE_VERTICAL); + node_data->AddState(ui::AX_STATE_VERTICAL); } void SubmenuView::PaintChildren(const ui::PaintContext& context) {
diff --git a/ui/views/controls/progress_bar.cc b/ui/views/controls/progress_bar.cc index c624fed..70824b2 100644 --- a/ui/views/controls/progress_bar.cc +++ b/ui/views/controls/progress_bar.cc
@@ -52,7 +52,7 @@ void ProgressBar::GetAccessibleNodeData(ui::AXNodeData* node_data) { node_data->role = ui::AX_ROLE_PROGRESS_INDICATOR; - node_data->AddStateFlag(ui::AX_STATE_READ_ONLY); + node_data->AddState(ui::AX_STATE_READ_ONLY); } gfx::Size ProgressBar::GetPreferredSize() const {
diff --git a/ui/views/controls/progress_bar_unittest.cc b/ui/views/controls/progress_bar_unittest.cc index 8f1c84b..6653eeb 100644 --- a/ui/views/controls/progress_bar_unittest.cc +++ b/ui/views/controls/progress_bar_unittest.cc
@@ -18,7 +18,7 @@ bar.GetAccessibleNodeData(&node_data); EXPECT_EQ(ui::AX_ROLE_PROGRESS_INDICATOR, node_data.role); EXPECT_EQ(base::string16(), node_data.GetString16Attribute(ui::AX_ATTR_NAME)); - EXPECT_TRUE(node_data.HasStateFlag(ui::AX_STATE_READ_ONLY)); + EXPECT_TRUE(node_data.HasState(ui::AX_STATE_READ_ONLY)); } } // namespace views
diff --git a/ui/views/controls/tabbed_pane/tabbed_pane.cc b/ui/views/controls/tabbed_pane/tabbed_pane.cc index 98aa69d..ba9abe4d 100644 --- a/ui/views/controls/tabbed_pane/tabbed_pane.cc +++ b/ui/views/controls/tabbed_pane/tabbed_pane.cc
@@ -228,9 +228,9 @@ void Tab::GetAccessibleNodeData(ui::AXNodeData* data) { data->role = ui::AX_ROLE_TAB; data->SetName(title()->text()); - data->AddStateFlag(ui::AX_STATE_SELECTABLE); + data->AddState(ui::AX_STATE_SELECTABLE); if (selected()) - data->AddStateFlag(ui::AX_STATE_SELECTED); + data->AddState(ui::AX_STATE_SELECTED); } bool Tab::HandleAccessibleAction(const ui::AXActionData& action_data) {
diff --git a/ui/views/controls/tabbed_pane/tabbed_pane_unittest.cc b/ui/views/controls/tabbed_pane/tabbed_pane_unittest.cc index 37a00605..5e470b57 100644 --- a/ui/views/controls/tabbed_pane/tabbed_pane_unittest.cc +++ b/ui/views/controls/tabbed_pane/tabbed_pane_unittest.cc
@@ -159,18 +159,12 @@ // Check the a11y information for each tab. for (int i = 0; i < kNumTabs; ++i) { ui::AXNodeData data; - - // AXViewObjWrapper::Serialize() and NativeViewAccessibilityBase::GetData() - // are normally responsible for clearing the state from the default - // AXNodeData constructor. Do the same here. - data.state = 0; - GetTabAt(i)->GetAccessibleNodeData(&data); SCOPED_TRACE(testing::Message() << "Tab at index: " << i); EXPECT_EQ(ui::AX_ROLE_TAB, data.role); EXPECT_EQ(DefaultTabTitle(), data.GetString16Attribute(ui::AX_ATTR_NAME)); - EXPECT_TRUE(data.HasStateFlag(ui::AX_STATE_SELECTABLE)); - EXPECT_EQ(i == 0, data.HasStateFlag(ui::AX_STATE_SELECTED)); + EXPECT_TRUE(data.HasState(ui::AX_STATE_SELECTABLE)); + EXPECT_EQ(i == 0, data.HasState(ui::AX_STATE_SELECTED)); } ui::AXActionData action;
diff --git a/ui/views/controls/table/table_view.cc b/ui/views/controls/table/table_view.cc index 1241261..984efa12 100644 --- a/ui/views/controls/table/table_view.cc +++ b/ui/views/controls/table/table_view.cc
@@ -445,7 +445,7 @@ void TableView::GetAccessibleNodeData(ui::AXNodeData* node_data) { node_data->role = ui::AX_ROLE_TABLE; - node_data->AddStateFlag(ui::AX_STATE_READ_ONLY); + node_data->AddState(ui::AX_STATE_READ_ONLY); node_data->AddIntAttribute(ui::AX_ATTR_SET_SIZE, RowCount()); if (selection_model_.active() != ui::ListSelectionModel::kUnselectedIndex) { @@ -455,7 +455,7 @@ node_data->AddIntAttribute(ui::AX_ATTR_POS_IN_SET, selection_model_.active()); if (selection_model_.IsSelected(selection_model_.active())) { - node_data->AddStateFlag(ui::AX_STATE_SELECTED); + node_data->AddState(ui::AX_STATE_SELECTED); } std::vector<base::string16> name_parts;
diff --git a/ui/views/controls/textfield/textfield.cc b/ui/views/controls/textfield/textfield.cc index f5ef652..2c7c520d 100644 --- a/ui/views/controls/textfield/textfield.cc +++ b/ui/views/controls/textfield/textfield.cc
@@ -912,11 +912,11 @@ ui::AX_SUPPORTED_ACTION_ACTIVATE); } if (read_only()) - node_data->AddStateFlag(ui::AX_STATE_READ_ONLY); + node_data->AddState(ui::AX_STATE_READ_ONLY); else - node_data->AddStateFlag(ui::AX_STATE_EDITABLE); + node_data->AddState(ui::AX_STATE_EDITABLE); if (text_input_type_ == ui::TEXT_INPUT_TYPE_PASSWORD) { - node_data->AddStateFlag(ui::AX_STATE_PROTECTED); + node_data->AddState(ui::AX_STATE_PROTECTED); node_data->SetValue(base::string16(text().size(), '*')); } else { node_data->SetValue(text());
diff --git a/ui/views/controls/textfield/textfield_unittest.cc b/ui/views/controls/textfield/textfield_unittest.cc index 474b476..d712c65 100644 --- a/ui/views/controls/textfield/textfield_unittest.cc +++ b/ui/views/controls/textfield/textfield_unittest.cc
@@ -3101,21 +3101,19 @@ textfield_->SetText(ASCIIToUTF16("password")); ui::AXNodeData node_data_regular; - node_data_regular.state = 0; textfield_->GetAccessibleNodeData(&node_data_regular); EXPECT_EQ(ui::AX_ROLE_TEXT_FIELD, node_data_regular.role); EXPECT_EQ(ASCIIToUTF16("password"), node_data_regular.GetString16Attribute(ui::AX_ATTR_VALUE)); - EXPECT_FALSE(node_data_regular.HasStateFlag(ui::AX_STATE_PROTECTED)); + EXPECT_FALSE(node_data_regular.HasState(ui::AX_STATE_PROTECTED)); textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); ui::AXNodeData node_data_protected; - node_data_protected.state = 0; textfield_->GetAccessibleNodeData(&node_data_protected); EXPECT_EQ(ui::AX_ROLE_TEXT_FIELD, node_data_protected.role); EXPECT_EQ(ASCIIToUTF16("********"), node_data_protected.GetString16Attribute(ui::AX_ATTR_VALUE)); - EXPECT_TRUE(node_data_protected.HasStateFlag(ui::AX_STATE_PROTECTED)); + EXPECT_TRUE(node_data_protected.HasState(ui::AX_STATE_PROTECTED)); } // Verify that cursor visibility is controlled by SetCursorEnabled.
diff --git a/ui/views/controls/tree/tree_view.cc b/ui/views/controls/tree/tree_view.cc index 31b8fde8..8e28b82 100644 --- a/ui/views/controls/tree/tree_view.cc +++ b/ui/views/controls/tree/tree_view.cc
@@ -414,7 +414,7 @@ void TreeView::GetAccessibleNodeData(ui::AXNodeData* node_data) { node_data->role = ui::AX_ROLE_TREE; - node_data->AddStateFlag(ui::AX_STATE_READ_ONLY); + node_data->AddState(ui::AX_STATE_READ_ONLY); if (!selected_node_) return;
diff --git a/ui/views/widget/native_widget_aura.cc b/ui/views/widget/native_widget_aura.cc index 4904f00c..65d5903 100644 --- a/ui/views/widget/native_widget_aura.cc +++ b/ui/views/widget/native_widget_aura.cc
@@ -48,6 +48,7 @@ #include "ui/views/widget/widget_delegate.h" #include "ui/views/widget/window_reorderer.h" #include "ui/wm/core/shadow_types.h" +#include "ui/wm/core/transient_window_manager.h" #include "ui/wm/core/window_animations.h" #include "ui/wm/core/window_util.h" #include "ui/wm/public/activation_client.h" @@ -181,6 +182,14 @@ if (!context) context = parent; parent = NULL; + + // Generally transient bubbles are showing state associated to the parent + // window. Make sure the transient bubble is only visible if the parent is + // visible, otherwise the bubble may not make sense by itself. + if (params.type == Widget::InitParams::TYPE_BUBBLE) { + wm::TransientWindowManager::Get(window_) + ->set_parent_controls_visibility(true); + } } // SetAlwaysOnTop before SetParent so that always-on-top container is used. SetAlwaysOnTop(params.keep_on_top);
diff --git a/ui/views/widget/native_widget_aura_unittest.cc b/ui/views/widget/native_widget_aura_unittest.cc index 8583f05..d338942 100644 --- a/ui/views/widget/native_widget_aura_unittest.cc +++ b/ui/views/widget/native_widget_aura_unittest.cc
@@ -27,6 +27,7 @@ #include "ui/wm/core/base_focus_rules.h" #include "ui/wm/core/default_activation_client.h" #include "ui/wm/core/focus_controller.h" +#include "ui/wm/core/transient_window_manager.h" namespace views { namespace { @@ -651,5 +652,39 @@ EXPECT_TRUE(delegate2.view()->HasFocus()); } +// Tests that the transient child bubble window is only visible if the parent is +// visible. +TEST_F(NativeWidgetAuraTest, VisibilityOfChildBubbleWindow) { + // Create a parent window. + Widget parent; + Widget::InitParams parent_params(Widget::InitParams::TYPE_WINDOW); + parent_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; + parent_params.context = root_window(); + parent.Init(parent_params); + parent.SetBounds(gfx::Rect(0, 0, 480, 320)); + + // Add a child bubble window to the above parent window and show it. + Widget child; + Widget::InitParams child_params(Widget::InitParams::TYPE_BUBBLE); + child_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; + child_params.parent = parent.GetNativeWindow(); + child.Init(child_params); + child.SetBounds(gfx::Rect(0, 0, 200, 200)); + child.Show(); + + // Check that the bubble window is added as the transient child and it is + // hidden because parent window is hidden. + wm::TransientWindowManager* manager = + wm::TransientWindowManager::Get(child.GetNativeWindow()); + EXPECT_EQ(parent.GetNativeWindow(), manager->transient_parent()); + EXPECT_FALSE(parent.IsVisible()); + EXPECT_FALSE(child.IsVisible()); + + // Show the parent window should make the transient child bubble visible. + parent.Show(); + EXPECT_TRUE(parent.IsVisible()); + EXPECT_TRUE(child.IsVisible()); +} + } // namespace } // namespace views